{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE TemplateHaskell     #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\nmodule Test.Grenade.Layers.PadCrop where\n\nimport           Grenade\n\nimport           Hedgehog\n\nimport           Numeric.LinearAlgebra.Static ( norm_Inf )\n\nimport           Test.Hedgehog.Hmatrix\n\nimport           Data.Serialize\nimport           Data.Either\nimport           System.Random.MWC             (create)\n\ntype PadCropNet3D = Network '[Pad 2 3 4 6, Crop 2 3 4 6] '[ 'D3 7 9 5, 'D3 16 15 5, 'D3 7 9 5 ]\ntype PadCropNet2D = Network '[Pad 2 3 4 6, Crop 2 3 4 6] '[ 'D2 7 9, 'D2 16 15, 'D2 7 9 ]\n\nprop_pad_crop :: Property\nprop_pad_crop =\n  let net :: PadCropNet3D\n      net = Pad :~> Crop :~> NNil\n  in  property $\n    forAll genOfShape >>= \\(d :: S ('D3 7 9 5)) ->\n      let (tapes, res)  = runForwards  net d\n          (_    , grad) = runBackwards net tapes d\n      in  do assert $ d ~~~ res\n             assert $ grad ~~~ d\n\nprop_pad_crop_2d :: Property\nprop_pad_crop_2d =\n  let net :: Network '[Pad 2 3 4 6, Crop 2 3 4 6] '[ 'D2 7 9, 'D2 16 15, 'D2 7 9 ]\n      net = Pad :~> Crop :~> NNil\n  in  property $\n    forAll genOfShape >>= \\(d :: S ('D2 7 9)) ->\n      let (tapes, res)  = runForwards  net d\n          (_    , grad) = runBackwards net tapes d\n      in  do assert $ d ~~~ res\n             assert $ grad ~~~ d\n\nprop_pad_crop_is_serializable :: Property\nprop_pad_crop_is_serializable = withTests 1 $ property $ do\n  gen <- evalIO create\n  pad  :: Pad 2 3 4 6  <- evalIO $ createRandomWith UniformInit gen\n  crop :: Crop 2 3 4 6 <- evalIO $ createRandomWith UniformInit gen\n  let net :: PadCropNet3D\n      net = pad :~> crop :~> NNil\n      bs = encode net\n      dec = decode bs :: Either String PadCropNet3D\n  assert $ isRight dec\n\nprop_can_show_pad_crop :: Property\nprop_can_show_pad_crop = \n  let net :: PadCropNet3D\n      net = Pad :~> Crop :~> NNil\n  in (withTests 1 . property) $ show net `seq` success\n\nprop_can_update_pad_crop_and_use_in_batches :: Property\nprop_can_update_pad_crop_and_use_in_batches =\n  let net :: PadCropNet3D\n      net = Pad :~> Crop :~> NNil\n  in  property $\n    forAll genOfShape >>= \\(d :: S ('D3 7 9 5)) ->\n      let (tapes, _) = runForwards  net d\n          (v    , _)   = runBackwards net tapes d\n      in do\n        runUpdate defSGD net v `seq` success\n        runUpdate defAdam net v `seq` success\n        reduceGradient @PadCropNet3D [v] `seq` success\n        \n\n(~~~) :: S x -> S x -> Bool\n(S1D x) ~~~ (S1D y) = norm_Inf (x - y) < 0.00001\n(S2D x) ~~~ (S2D y) = norm_Inf (x - y) < 0.00001\n(S3D x) ~~~ (S3D y) = norm_Inf (x - y) < 0.00001\n\n\ntests :: IO Bool\ntests = checkParallel $$(discover)\n", "meta": {"hexsha": "dac026255932acec41da7e864c5c422dce8c7cc5", "size": 2886, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/PadCrop.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/PadCrop.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Layers/PadCrop.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": 32.4269662921, "max_line_length": 95, "alphanum_fraction": 0.5897435897, "num_tokens": 961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4499293303560008}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE NamedFieldPuns #-}\n{-# LANGUAGE NamedFieldPuns #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE ConstraintKinds #-}\n\nmodule Matrix where\n\nimport Prelude\nimport qualified Prelude\nimport qualified Data.Matrix\nimport qualified Data.Eigen.Matrix\nimport Foreign.C.Types\nimport qualified Numeric.LinearAlgebra.HMatrix\nimport qualified Numeric.LinearAlgebra.Data\nimport Control.Parallel.Strategies\nimport qualified Data.Array as Array\nimport Data.Array(Array, (!), range, Ix)\nimport GHC.Generics\nimport Control.Arrow\nimport Control.Monad.Writer\nimport Control.Monad.Identity\n\nimport qualified Data.Set as Set\nimport Data.Set(Set)\nimport qualified Data.Map as Map\nimport Data.Map(Map)\n\n\n\n\ndata Matrix a b v = Matrix (Array (a, b) v) deriving (Show, Eq, Ord, Functor, Generic)\ninstance (NFData a, NFData b, NFData v) => NFData (Matrix a b v)\ntype Vector a v = Matrix a () v\n\ntype Ix' a = (Ix a, Bounded a, Enum a)\n\ninstance (Ix' a, Ix' b) => Enum (a, b) where\n  fromEnum (x, (y :: b)) = fromEnum x * Array.rangeSize (fullRange :: (b, b)) + fromEnum y\n  toEnum i =\n    let (d, m) = i `divMod` (Array.rangeSize (fullRange :: (b, b))) in\n      (toEnum d, (toEnum m :: b))\n\ninstance (Linear v, Ix' a, Ix' b) => Linear (Matrix a b v) where\n  zero = Matrix (f_array (\\(_a, _b) -> zero))\n  add = matrixZipWith add\n  minus = fmap minus\n\nfullRange :: Bounded a => (a, a)\nfullRange = (minBound, maxBound)\n\n\nvector_of_function f = Matrix (f_array (\\(x, ()) -> f x))\n\n{-# INLINE matrix_mult #-}\nmatrix_mult :: (Ix' a, Ix' b, Ix' c, Num v) => Matrix a b v -> Matrix b c v -> Matrix a c v\nmatrix_mult (Matrix x) (Matrix y) = Matrix (Array.array fullRange [ ((a, c), sum [ x ! (a, b) * y ! (b, c) | b <- range fullRange]) | a <- range fullRange, c <- range fullRange])\n\n{-# INLINE matrixZipWith #-}\nmatrixZipWith f (Matrix a) (Matrix b) =\n  Matrix (f_array (\\k -> f (a ! k) (b ! k)))\n\n{-# INLINE f_array #-}\nf_array :: Ix' k => (k -> v) -> Array k v\nf_array f = Array.array fullRange [(k, f k) | k <- range fullRange]\n\ntype Solution b v = Map b (Map b v)\n\ntype Solution_with_trace a b v =\n  -- decomposes as much products as it can, providing for each product:\n  -- 1. how much of non-decomposable products are necessary\n  -- 2. how much of input recipes ([a]) you need to craft\n  Map b (Map b v, Map a v)\n\nclass Linear a where\n  zero :: a\n  add :: a -> a -> a\n  minus :: a -> a\n\ninstance (Linear a, Linear b) => Linear (a, b) where\n  zero = (zero, zero)\n  add (a1, b1) (a2, b2) = (add a1 a2, add b1 b2)\n  minus (a, b) = (minus a, minus b)\n\ninstance Linear Double where\n  zero = 0\n  add = (+)\n  minus x = -x\n\ninstance Linear Rational where\n  zero = 0\n  add = (+)\n  minus x = -x\n\ninstance VectorSpace Rational where\n  type Scalar Rational = Rational\n  scale = (*)\n\ninstance (Eq v, Ord k, VectorSpace v) => VectorSpace (Map k v) where\n  type Scalar (Map k v) = Scalar v\n  scale s = fmap (scale s)\n\ninstance (VectorSpace a, VectorSpace b, Scalar a ~ Scalar b) => VectorSpace (a, b) where\n  type Scalar (a, b) = Scalar a\n  scale s = (scale s *** scale s)\n\ninstance (Ord k, Linear v, Eq v) => Linear (Map k v) where\n  zero = Map.empty\n  add a b = Map.filter (/= zero) (Map.unionWith add a b)\n  minus = fmap minus\n\nfind_kernel ::\n  forall v1 b s.\n  ( Linear v1\n  , Eq b\n  , Eq v1\n  , Ord b)\n  =>\n  (v1 -> v1 -> s)\n  -> (s -> v1 -> v1)\n  -> [Map b v1] -> Solution b s\nfind_kernel divide mult_v1 rows = go rows where\n\n  lookupLhs :: (Map b v1) -> b -> v1\n  lookupLhs lhs b = case Map.lookup b lhs of\n    Nothing -> zero\n    Just x -> x\n\n  addRow a1 a2 = (Map.unionWith add a1 a2)\n\n  scaleRow (s :: s) a1 = fmap (mult_v1 s) a1\n\n  minusRow m = fmap minus m\n  \n  remove_b :: (b, (Map b v1)) -> (Map b v1) -> (Map b v1)\n  remove_b (b, row0) row1 =\n    (\\m -> if m Map.! b == zero then Map.delete b m else error \"should be zero\") $ addRow row1 (minusRow $ scaleRow (lookupLhs row1 b `divide` lookupLhs row0 b) row0)\n  \n  go :: [(Map b v1)] -> Solution b s\n  go [] = Map.empty\n  go (row0 : rest) = case [(b, v) | (b, v) <- Map.toList row0, v /= zero] of\n    [] -> -- all coefficients are 0, equation is useless\n      go rest\n    (chosen_b, chosen_v) : _ ->\n      case go (map (remove_b (chosen_b, row0)) rest) of\n        solutionDecompose ->\n          case map (\\(b, v) ->\n                           if b == chosen_b\n                           then Map.empty\n                           else\n                             case (Map.lookup b solutionDecompose) of\n                               Nothing ->\n                                 Map.singleton b v\n                               Just vs ->\n                                 fmap (`mult_v1` v) vs\n                        ) (Map.toList row0) of\n            lhs ->\n              let sum_of_lhs = Map.unionsWith add lhs in\n              (Map.insert chosen_b (fmap ((`divide` chosen_v) . minus) sum_of_lhs) solutionDecompose)\n\nclass Linear a => VectorSpace a where\n  type Scalar a :: *\n  scale :: Scalar a -> a -> a\n\nfind_kernel_with_trace ::\n  forall v a b s.\n  ( VectorSpace v\n  , Scalar v ~ v\n  , Ord a\n  , Fractional v\n  , Eq b\n  , Eq v\n  , Num v\n  , Ord b)\n  =>\n  (v -> v -> v)\n  -> (v -> v -> v)\n  -> Map a (Map b v) -> Solution_with_trace a b v\nfind_kernel_with_trace divide mult_v1 rows = go (map (\\(a, row) -> (row, Map.singleton a 1)) $ Map.toList rows) where\n\n  lookupLhs :: (Map b v, Map a v) -> b -> v\n  lookupLhs (lhs, _) b = case Map.lookup b lhs of\n    Nothing -> zero\n    Just x -> x\n\n  addRow = add\n\n  scaleRow = scale\n\n  minusRow = minus\n  \n  remove_b :: (b, (Map b v, Map a v)) -> (Map b v, Map a v) -> (Map b v, Map a v)\n  remove_b (b, row0) row1 =\n    (\\(m, r) -> if Map.member b m then error \"should be absent\" else (m, r)) $ addRow row1 (minusRow $ scaleRow (lookupLhs row1 b `divide` lookupLhs row0 b) row0)\n  \n  go :: [(Map b v, Map a v)] -> Solution_with_trace a b v\n  go [] = Map.empty\n  go (row0 : rest) = case [(b, v) | (b, v) <- Map.toList (fst row0), v /= zero] of\n    [] -> -- all coefficients are 0, equation is useless\n      go rest\n    (chosen_b, chosen_v) : _ -> runIdentity $ do\n      row0 <- return $ scaleRow (recip chosen_v) row0\n      chosen_v <- return $ ()\n      rest <- return $ map (remove_b (chosen_b, row0)) rest\n      (lhs, rhs) <- return $ row0\n      row0 <- return $ ()\n      return $\n        case go rest of\n          solutionDecompose ->\n            case map (\\(b, v) ->\n                             if b == chosen_b\n                             then zero\n                             else\n                               case Map.lookup b solutionDecompose of\n                                 Nothing -> do\n                                   (Map.singleton b v, zero) -- don't need any recipes to make the raw material\n                                 Just results ->\n                                   scale v results\n                          ) (Map.toList lhs) of\n              lhs ->\n                let sum_of_lhs = foldr add zero lhs in\n                (Map.insert chosen_b (add (minus sum_of_lhs) (zero, rhs)) solutionDecompose)\n\n", "meta": {"hexsha": "d6478954c6ba2a58448bc84559d1cb1607164f0d", "size": 7246, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Matrix.hs", "max_stars_repo_name": "Rotsor/factorio-module-selector", "max_stars_repo_head_hexsha": "22a595ba36bbf9ca337bba0dfbe3c387308f43b3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Matrix.hs", "max_issues_repo_name": "Rotsor/factorio-module-selector", "max_issues_repo_head_hexsha": "22a595ba36bbf9ca337bba0dfbe3c387308f43b3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix.hs", "max_forks_repo_name": "Rotsor/factorio-module-selector", "max_forks_repo_head_hexsha": "22a595ba36bbf9ca337bba0dfbe3c387308f43b3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5043478261, "max_line_length": 178, "alphanum_fraction": 0.5727297819, "num_tokens": 2131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.44979967981277214}}
{"text": "module STCR2Z1T0PointSet where\n\nimport           Data.Array.Repa         as R\nimport           Data.Binary             (decodeFile)\nimport           Data.Complex\nimport           Data.List               as L\nimport           DFT.Plan\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.IO\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Types\nimport           Utils.Array\n\n\nmain = do\n  args@(numPointStr:numOrientationStr:sigmaStr:taoStr:lenStr:initialScaleStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:histFilePath:pinwheelFlagStr:numIterationStr:writeSourceFlagStr:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      sigma = read sigmaStr :: Double\n      tao = read taoStr :: Double\n      len = read lenStr :: Int\n      initialScale = read initialScaleStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      theta0Freq = read theta0FreqsStr :: Double\n      theta0Freqs = [-theta0Freq .. theta0Freq]\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      pinwheelFlag = read pinwheelFlagStr :: Bool\n      numIteration = read numIterationStr :: Int\n      writeSourceFlag = read writeSourceFlagStr :: Bool\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/STCR2Z1T0PointSet\"\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  radialArr <-\n    if flag\n      then R.map magnitude . getNormalizedHistogramArr <$>\n           decodeFile histFilePath\n      else do\n        putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n        solveMonteCarloR2Z1T0Radial\n          numThread\n          numTrail\n          maxTrail\n          numPoint\n          numPoint\n          sigma\n          tao\n          initialScale\n          theta0Freqs\n          thetaFreqs\n          histFilePath\n          (emptyHistogram\n             [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n             , L.length theta0Freqs\n             , L.length thetaFreqs\n             ]\n             0)\n  arrR2Z1T0 <-\n    computeUnboxedP $\n    computeR2Z1T0ArrayRadial\n      radialArr\n      numPoint\n      numPoint\n      1\n      thetaFreqs\n      theta0Freqs\n  plan <- makeR2Z1T0Plan emptyPlan arrR2Z1T0\n  let n = 30\n      m = round $ (fromIntegral n) * (sqrt 2) / 2\n      a = 10\n      b = -10\n      c = 10\n      a' = round $ (fromIntegral a) * (sqrt 2) / 2\n      b' = round $ (fromIntegral b) * (sqrt 2) / 2\n      c' = round $ (fromIntegral c) * (sqrt 2) / 2\n      r = 30\n      numTheta = 7\n      deltaTheta = (1 * pi) / numTheta\n      xs =\n        ((L.map\n            (\\(i, j) -> R2S1RPPoint (round i, round j, 0, 1))\n            [ (r * cos (k * deltaTheta) + 0, r * sin (k * deltaTheta) + 0)\n            | k <- [0 .. numTheta]\n            ]) -- L.++\n                -- (L.map\n                --    (\\(i, j) -> R2S1RPPoint (round i, round j, 0, 1))\n                --    [ ((r + 30) * cos (k * deltaTheta), (r + 30) * sin (k * deltaTheta))\n                --    | k <- [0 .. numTheta - 1]\n                --    ])\n               -- L.++\n                -- (L.map\n                --    (\\(i, j) -> R2S1RPPoint (round i, round j, 0, 1))\n                --    [ ( (r + 15 * 2) * cos (k * deltaTheta)\n                --      , (r + 15 * 2) * sin (k * deltaTheta))\n                --    | k <- [0 .. numTheta - 1]\n                --    ])\n               -- L.++ [R2S1RPPoint (3, 5, 0, 1)]\n         )\n               -- ([R2S1RPPoint (i, i, 0, 1) | i <- [a',a' + b' .. c']] L.++\n               --  [R2S1RPPoint (i, -i, 0, 1) | i <- [-a',-(a' + b') .. -c']] L.++\n               --  [R2S1RPPoint (i, i, 0, 1) | i <- [-a',-(a' + b') .. -c']] L.++\n               --  [R2S1RPPoint (i, -i, 0, 1) | i <- [a',a' + b' .. c']] L.++\n               --  [R2S1RPPoint (i, 0, 0, 1) | i <- [a,a + b .. c]] L.++\n               --  [R2S1RPPoint (0, i, 0, 1) | i <- [-a,-(a + b) .. -c]] L.++\n               --  [R2S1RPPoint (i, 0, 0, 1) | i <- [-a,-(a + b) .. -c]] L.++\n               --  [R2S1RPPoint (0, i, 0, 1) | i <- [a,a + b .. c]] L.++\n               --  [R2S1RPPoint (3, 5, 0, 1)])\n                -- [ R2S1RPPoint (n, 0, 0, 1)\n                -- , R2S1RPPoint (0, n, 0, 1)\n                -- , R2S1RPPoint (-n, 0, 0, 1)\n                -- , R2S1RPPoint (0, -n, 0, 1)\n                -- , R2S1RPPoint (m, m, 0, 1)\n                -- , R2S1RPPoint (-m, m, 0, 1)\n                -- , R2S1RPPoint (m, -m, 0, 1)\n                -- , R2S1RPPoint (-m, -m, 0, 1)\n                -- ]\n  let bias = computeBiasR2T0 numPoint numPoint theta0Freqs xs\n      eigenVec =\n        computeInitialEigenVectorR2T0\n          numPoint\n          numPoint\n          theta0Freqs\n          thetaFreqs\n          xs\n  powerMethod1\n    plan\n    folderPath\n    numPoint\n    numPoint\n    numOrientation\n    thetaFreqs\n    theta0Freqs\n    arrR2Z1T0\n    numIteration\n    writeSourceFlag\n    \"\"\n    0.5\n    bias\n    eigenVec\n", "meta": {"hexsha": "60bdccc3fc9b9d13ebd2c4782c094207f8fe9ece", "size": 5150, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z1T0PointSet/STCR2Z1T0PointSet.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/STCR2Z1T0PointSet/STCR2Z1T0PointSet.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/STCR2Z1T0PointSet/STCR2Z1T0PointSet.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 34.7972972973, "max_line_length": 212, "alphanum_fraction": 0.487184466, "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.44952216580340765}}
{"text": "module STCLocalEigenVector where\n\nimport           Control.Monad             as M\nimport           Control.Monad.Parallel             as MP\nimport           Data.Array.Repa           as R\nimport           Data.Binary               (decodeFile)\nimport           Data.Complex\nimport           Data.List                 as L\nimport           DFT.Plan\nimport           FokkerPlanck.DomainChange\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.IO\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Types\nimport           Utils.Array\nimport           Utils.Parallel\n\n{-# INLINE timeReversal #-}\ntimeReversal :: (R.Source r e) => Array r DIM4 e -> Array D DIM4 e\ntimeReversal arr =\n  let (Z :. nf :. _ :. _ :. _) = extent arr\n      n = div nf 2\n   in R.backpermute\n        (extent arr)\n        (\\(Z :. k :. l :. i :. j) ->\n           let x = nf - n\n            in if k >= x\n                 then (Z :. k - x :. l  :. i :. j)\n                 else (Z :. k + n :. l :. i :. j))\n        arr\n\nmain = do\n  args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:thetaFreqsStr:scaleFreqsStr:histFileName:cutoffRadiusStr:initDistStr:useFFTWWisdomFlagStr:fftwWisdomFileName:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scaleFreq = read scaleFreqsStr :: Double\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      cutoffRadius = read cutoffRadiusStr :: Int\n      initDist = read initDistStr :: [R2S1RPPoint]\n      useFFTWWisdomFlag = read useFFTWWisdomFlagStr :: Bool\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/STCLocalEigenVector\"\n      histFilePath = folderPath </> histFileName\n      fftwWisdomFilePath = folderPath </> fftwWisdomFileName\n      sourceDist = L.take 1 initDist\n      sinkDist = L.drop 1 initDist\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  radialArr <-\n    if flag\n      then R.map magnitude . getNormalizedHistogramArr <$>\n           decodeFile histFilePath\n      else do\n        putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n        solveMonteCarloR2Z2T0S0Radial\n          numThread\n          numTrail\n          maxTrail\n          numPoint\n          numPoint\n          thetaSigma\n          scaleSigma\n          maxScale\n          tao\n          thetaFreqs\n          thetaFreqs\n          scaleFreqs\n          scaleFreqs\n          histFilePath\n          (emptyHistogram\n             [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n             , L.length scaleFreqs\n             , L.length thetaFreqs\n             , L.length scaleFreqs\n             , L.length thetaFreqs\n             ]\n             0)\n  let localEigenVector =\n        computeLocalEigenVector\n          (ParallelParams numThread 0)\n          (pinwheelHollow 2)\n          (cutoff cutoffRadius radialArr)\n          numPoint\n          numPoint\n          maxScale\n          thetaFreqs\n          scaleFreqs\n      localEigenVectorSink =\n        computeLocalEigenVectorSink\n          (ParallelParams numThread 0)\n          (pinwheelHollow 2)\n          (cutoff cutoffRadius radialArr)\n          numPoint\n          numPoint\n          maxScale\n          thetaFreqs\n          scaleFreqs\n  plan <-\n    make4DPlan emptyPlan useFFTWWisdomFlag fftwWisdomFilePath localEigenVector\n  sourceDistArr <-\n    computeInitialDistributionR2T0S0\n      plan\n      numPoint\n      numPoint\n      thetaFreqs\n      scaleFreqs\n      maxScale\n      sourceDist\n  sinkDistArr <-\n    computeInitialDistributionR2T0S0\n      plan\n      numPoint\n      numPoint\n      thetaFreqs\n      scaleFreqs\n      maxScale\n      sinkDist\n  filterF <- dft4D plan . computeS . makeFilter4D $ localEigenVector\n  filterSinkF <- dft4D plan . computeS . makeFilter4D $ localEigenVector\n  -- Source\n  sourceArr <- convolve4D plan filterF sourceDistArr\n  sourceR2 <-\n    R.sumP .\n    R.sumS .\n    rotate4D .\n    rotate4D . r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs $\n    sourceArr\n  plotImageRepaComplex (folderPath </> \"Source.png\") .\n    ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n    sourceR2\n  -- Sink\n  sinkArr <- convolve4D plan filterSinkF sinkDistArr\n  -- let sinkArr =\n  --       R.traverse2\n  --         sinkArr'\n  --         (fromListUnboxed (Z :. (L.length thetaFreqs)) thetaFreqs)\n  --         const $ \\f fFreq idx@(Z :. k :. l :. i :. j) ->\n  --         f idx * ((exp (0 :+ (-1) * (fFreq (Z :. k)) * pi)))\n  sinkR2 <-\n    R.sumP .\n    R.sumS .\n    rotate4D .\n    rotate4D . r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs $\n    sinkArr\n  plotImageRepaComplex (folderPath </> \"Sink.png\") .\n    ImageRepa 8 . computeS . extend (Z :. (1 :: Int) :. All :. All) $\n    sinkR2\n  -- Completion\n  -- plotImageRepa (folderPath </> \"Completion.png\") .\n  --   ImageRepa 8 .\n  --   computeS .\n  --   extend (Z :. (1 :: Int) :. All :. All) .\n  --   R.sumS . R.sumS . rotate4D . rotate4D . R.map magnitude $\n  --   (timeReversal $  r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs sinkArr) *^\n  --   (r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs sourceArr)\n  -- completionFieldR2 plan folderPath \"\" sourceR2 sinkR2\n  completionFieldR2Z2\n    plan\n    folderPath\n    \"\"\n    numOrientation\n    thetaFreqs\n    numScale\n    scaleFreqs\n    sourceArr\n    sinkArr\n    -- (computeS $\n    --  R.traverse2\n    --    sinkArr\n    --    (fromListUnboxed (Z :. (L.length thetaFreqs)) thetaFreqs)\n    --    const $ \\f fFreq idx@(Z :. k :. l :. i :. j) ->\n    --    f idx * ((exp (0 :+ (-1) * (fFreq (Z :. k)) * pi))))\n    -- (computeS . R.map (\\x -> let (m,p) = polar x\n    --                          in mkPolar m (p + pi)) $ sinkArr)\n    -- (computeS $ flip4D sinkArr)\n    -- (computeS $ timeReverse4D thetaFreqs sinkArr)\n  -- MP.mapM_\n  --   (\\(tf, sf) ->\n  --      plotImageRepaComplex (folderPath </> printf \"Source_%d_%d.png\" tf sf) .\n  --      ImageRepa 8 .\n  --      computeS .\n  --      extend (Z :. (1 :: Int) :. All :. All) .\n  --      R.slice\n  --        (r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs sourceArr) $\n  --      (Z :. tf :. sf :. All :. All))\n  --   [ (tf, sf)\n  --   | tf <- [0 .. numOrientation - 1]\n  --   , sf <- [0 .. numScale - 1]\n  --   ]\n    -- [ (tf, sf)\n    -- | tf <- [0 .. L.length thetaFreqs - 1]\n    -- , sf <- [0 .. L.length scaleFreqs - 1]\n    -- ]\n", "meta": {"hexsha": "9e40b21ed10702ed371b301897dccb824139e954", "size": 6997, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCLocalEigenVector/STCLocalEigenVector.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/STCLocalEigenVector/STCLocalEigenVector.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/STCLocalEigenVector/STCLocalEigenVector.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 33.319047619, "max_line_length": 248, "alphanum_fraction": 0.5836787195, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.44938661733105334}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes                      #-}\n{-# LANGUAGE ApplicativeDo                            #-}\n{-# LANGUAGE DeriveDataTypeable                       #-}\n{-# LANGUAGE DeriveGeneric                            #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE KindSignatures                           #-}\n{-# LANGUAGE MultiParamTypeClasses                    #-}\n{-# LANGUAGE PatternSynonyms                          #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE RecordWildCards                          #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeFamilies                             #-}\n{-# LANGUAGE TypeInType                               #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE UndecidableInstances                     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nmodule Backprop.Learn.Model.Regression (\n    LinReg(..)\n  , LogReg, pattern LogReg\n  , LRp(..), lrBeta, lrAlpha, runLRp\n  , expandInput, expandOutput, reshapeInput, reshapeOutput\n  , ARIMA(..), ARIMAp(..), ARIMAs(..)\n  , ARIMAUnroll, arimaUnroll\n  , ARIMAUnrollFinal, arimaUnrollFinal\n  , AR, MA, ARMA\n  ) where\n\nimport           Backprop.Learn.Initialize\nimport           Backprop.Learn.Model.Class\nimport           Backprop.Learn.Model.Combinator\nimport           Backprop.Learn.Model.Function\nimport           Backprop.Learn.Model.Parameter\nimport           Backprop.Learn.Model.State\nimport           Control.DeepSeq\nimport           Control.Monad.Primitive\nimport           Data.Finite\nimport           Data.Kind\nimport           Data.List\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Type.Equality\nimport           Data.Typeable\nimport           GHC.Generics                          (Generic)\nimport           GHC.TypeLits.Compare\nimport           GHC.TypeLits.Extra\nimport           GHC.TypeNats\nimport           Lens.Micro\nimport           Numeric.Backprop\nimport           Numeric.LinearAlgebra.Static.Backprop\nimport           Numeric.LinearAlgebra.Static.Vector\nimport           Numeric.OneLiner\nimport           Numeric.Opto.Ref\nimport           Numeric.Opto.Update hiding            ((<.>))\nimport           Statistics.Distribution\nimport           Unsafe.Coerce\nimport qualified Data.Binary                           as Bi\nimport qualified Data.Type.Tuple                       as T\nimport qualified Data.Vector.Generic.Sized             as SVG\nimport qualified Data.Vector.Sized                     as SV\nimport qualified Data.Vector.Storable.Sized            as SVS\nimport qualified Numeric.LinearAlgebra                 as HU\nimport qualified Numeric.LinearAlgebra.Static          as H\nimport qualified System.Random.MWC                     as MWC\n\n-- | Multivariate linear regression, from an i-vector to an o-vector.\ndata LinReg (i :: Nat) (o :: Nat) = LinReg\n  deriving Typeable\n\n-- | Mutivariate Logistic regression, from an i-vector to an o-vector.\n--\n-- Essentially a linear regression postcomposed with the logistic\n-- function.\ntype LogReg i o = RMap (R o) (R o) (LinReg i o)\n\n-- | Constructor for a 'LogReg'\npattern LogReg :: LogReg i o\npattern LogReg <- RM _ LinReg\n  where\n    LogReg = RM logistic LinReg\n{-# COMPLETE LogReg #-}\n\n-- | Linear Regression parameter\ndata LRp i o = LRp\n    { _lrAlpha :: !(R o)\n    , _lrBeta  :: !(L o i)\n    }\n  deriving (Generic, Typeable, Show)\n\ninstance NFData (LRp i o)\ninstance (KnownNat i, KnownNat o) => Initialize (LRp i o)\ninstance (KnownNat i, KnownNat o) => Additive (LRp i o)\ninstance (KnownNat i, KnownNat o) => Scaling Double (LRp i o)\ninstance (KnownNat i, KnownNat o) => Metric Double (LRp i o)\ninstance (KnownNat i, KnownNat o, Ref m (LRp i o) v) => AdditiveInPlace m v (LRp i o)\ninstance (KnownNat i, KnownNat o, Ref m (LRp i o) v) => ScalingInPlace m v Double (LRp i o)\ninstance (KnownNat i, KnownNat o) => Bi.Binary (LRp i o)\ninstance (KnownNat i, KnownNat o) => Backprop (LRp i o)\n\nlrBeta :: Lens (LRp i o) (LRp i' o) (L o i) (L o i')\nlrBeta f lrp = (\\w -> lrp { _lrBeta = w }) <$> f (_lrBeta lrp)\n\nlrAlpha :: Lens' (LRp i o) (R o)\nlrAlpha f lrp = (\\b -> lrp { _lrAlpha = b }) <$> f (_lrAlpha lrp)\n\nrunLRp\n    :: (KnownNat i, KnownNat o, Reifies s W)\n    => BVar s (LRp i o)\n    -> BVar s (R i)\n    -> BVar s (R o)\nrunLRp lrp x = (lrp ^^. lrBeta) #> x + (lrp ^^. lrAlpha)\n\ninstance (KnownNat i, KnownNat o) => Num (LRp i o) where\n    (+)         = gPlus\n    (-)         = gMinus\n    (*)         = gTimes\n    negate      = gNegate\n    abs         = gAbs\n    signum      = gSignum\n    fromInteger = gFromInteger\n\ninstance (KnownNat i, KnownNat o) => Fractional (LRp i o) where\n    (/)          = gDivide\n    recip        = gRecip\n    fromRational = gFromRational\n\ninstance (KnownNat i, KnownNat o) => Floating (LRp i o) where\n    pi    = gPi\n    sqrt  = gSqrt\n    exp   = gExp\n    log   = gLog\n    sin   = gSin\n    cos   = gCos\n    tan   = gTan\n    asin  = gAsin\n    acos  = gAcos\n    atan  = gAtan\n    sinh  = gSinh\n    cosh  = gCosh\n    asinh = gAsinh\n    acosh = gAcosh\n    atanh = gAtanh\n\ninstance (KnownNat i, KnownNat o) => Learn (R i) (R o) (LinReg i o) where\n    type LParamMaybe (LinReg i o) = 'Just (LRp i o)\n\n    runLearn _ (J_ p) = stateless (runLRp p)\n\n-- | Adjust an 'LRp' to take extra inputs, initialized randomly.\n--\n-- Initial contributions to each output is randomized.\nexpandInput\n    :: (PrimMonad m, ContGen d, KnownNat i, KnownNat j, KnownNat o)\n    => LRp i o\n    -> d\n    -> MWC.Gen (PrimState m)\n    -> m (LRp (i + j) o)\nexpandInput LRp{..} d g = LRp _lrAlpha . (_lrBeta H.|||) <$> initialize d g\n\n-- | Adjust an 'LRp' to return extra ouputs, initialized randomly\nexpandOutput\n    :: (PrimMonad m, ContGen d, KnownNat i, KnownNat o, KnownNat p)\n    => LRp i o\n    -> d\n    -> MWC.Gen (PrimState m)\n    -> m (LRp i (o + p))\nexpandOutput LRp{..} d g = do\n    newAlpha <- initialize d g\n    newBeta  <- initialize d g\n    pure (LRp (_lrAlpha H.# newAlpha) (_lrBeta H.=== newBeta))\n\n-- | Premute (or remove) inputs\n--\n-- Removed inputs will simply have their contributions removed from each\n-- output.\nreshapeInput\n    :: KnownNat i\n    => SV.Vector i' (Finite i)\n    -> LRp i o\n    -> LRp i' o\nreshapeInput is p = p { _lrBeta = colsL . fmap (\u03b2 `SV.index`) $ is }\n  where\n    \u03b2 = lCols (_lrBeta p)\n\n-- | Premute (or remove) outputs\nreshapeOutput\n    :: KnownNat o\n    => SV.Vector o' (Finite o)\n    -> LRp i o\n    -> LRp i o'\nreshapeOutput is LRp{..} =\n    LRp { _lrAlpha = vecR . SVG.convert . fmap (\u03b1 `SVS.index`) $ is\n        , _lrBeta  = rowsL . fmap (\u03b2 `SV.index`) $ is\n        }\n  where\n    \u03b1 = rVec _lrAlpha\n    \u03b2 = lRows _lrBeta\n\n\n-- | Auto-regressive integrated moving average model.\n--\n-- ARIMA(p,d,q) is an ARIMA model with p autoregressive history terms on\n-- the d-th order differenced history and q error (innovation) history\n-- terms.\n--\n-- It is a @'Learn' Double Double@ instance, and is meant to predict the\n-- \"next step\" of a time sequence.\n--\n-- In this state, it is a runnable stateful model.  To train, use with\n-- 'ARIMAUnroll' to unroll and fix the initial state.\ndata ARIMA :: Nat -> Nat -> Nat -> Type where\n    ARIMA :: { _arimaGenYHist :: forall m. PrimMonad m => MWC.Gen (PrimState m) -> m Double\n             , _arimaGenEHist :: forall m. PrimMonad m => MWC.Gen (PrimState m) -> m Double\n             }\n          -> ARIMA p d q\n\n-- | The \"unrolled\" and \"destated\" 'ARIMA' model, which takes a vector of\n-- sequential inputs and outputs a vector of the model's expected next\n-- steps.\n--\n-- Useful for actually training 'ARIMA' using gradient descent.\n--\n-- This /fixes/ the initial error history to be zero (or a fixed stochastic\n-- sample), and treats the initial output history to be a /learned\n-- parameter/.\n--\n-- @\n-- instance 'Learn' ('SV.Vector' n 'Double') (SV.Vector n Double) ('ARIMAUnroll' p q) where\n--     -- | Initial state is a parameter, but initial error history is fixed\n--     type 'LParamMaybe' (ARIMAUnroll p q) = 'Just (T2 (ARIMAp p q) (ARIMAs p q))\n--     type 'LStateMaybe' (ARIMAUnroll p q) = 'Nothing\n-- @\ntype ARIMAUnroll p d q = DeParamAt (T.T2 (ARIMAp p q) (ARIMAs p d q))\n                                   (T.T2 (ARIMAp p q) (T.T2 Double (R (p + d))))\n                                   (R q)\n                                   (UnrollTrainState (Max (p + d) q) (ARIMA p d q))\n\n-- | 'ARIMAUnroll', but only looking at the final output after running the\n-- model on all inputs.\n--\n-- @\n-- instance 'Learn' ('SV.Vector' n 'Double') Double ('ARIMAUnrollFinal' p q) where\n--     -- | Initial state is a parameter, but initial error history is fixed\n--     type 'LParamMaybe' (ARIMAUnrollFinal p q) = 'Just (T2 (ARIMAp p q) (ARIMAs p q))\n--     type 'LStateMaybe' (ARIMAUnrollFinal p q) = 'Nothing\n-- @\ntype ARIMAUnrollFinal p d q = DeParamAt (T.T2 (ARIMAp p q) (ARIMAs p d q))\n                                        (T.T2 (ARIMAp p q) (T.T2 Double (R (p + d))))\n                                        (R q)\n                                        (UnrollFinalTrainState (Max (p + d) q) (ARIMA p d q))\n\nsplitHist\n    :: T.T2 (ARIMAp p q) (ARIMAs p d q)\n    -> (T.T2 (ARIMAp p q) (T.T2 Double (R (p + d))), R q)\nsplitHist (T.T2 p ARIMAs{..}) = (T.T2 p (T.T2 _arimaYPred _arimaYHist), _arimaEHist)\n\njoinHist\n    :: T.T2 (ARIMAp p q) (T.T2 Double (R (p + d)))\n    -> R q\n    -> T.T2 (ARIMAp p q) (ARIMAs p d q)\njoinHist (T.T2 p (T.T2 _arimaYPred _arimaYHist)) _arimaEHist = T.T2 p ARIMAs{..}\n\n-- | Constructor for 'ARIMAUnroll'\narimaUnroll\n    :: KnownNat q\n    => ARIMA p d q\n    -> ARIMAUnroll p d q\narimaUnroll a@ARIMA{..} = DPA\n    { _dpaSplit      = splitHist\n    , _dpaJoin       = joinHist\n    , _dpaParam      = 0\n    , _dpaParamStoch = fmap vecR . SVS.replicateM . _arimaGenEHist\n    , _dpaLearn      = UnrollTrainState a\n    }\n\n-- | Constructor for 'ARIMAUnrollFinal'\narimaUnrollFinal\n    :: KnownNat q\n    => ARIMA p d q\n    -> ARIMAUnrollFinal p d q\narimaUnrollFinal a@ARIMA{..} = DPA\n    { _dpaSplit      = splitHist\n    , _dpaJoin       = joinHist\n    , _dpaParam      = 0\n    , _dpaParamStoch = fmap vecR . SVS.replicateM . _arimaGenEHist\n    , _dpaLearn      = UnrollFinalTrainState a\n    }\n\n\n-- | 'ARIMA' parmaeters\ndata ARIMAp :: Nat -> Nat -> Type where\n    ARIMAp :: { _arimaPhi      :: !(R p)\n              , _arimaTheta    :: !(R q)\n              , _arimaConstant :: !Double\n              }\n           -> ARIMAp p q\n  deriving (Generic, Show)\n\n-- | 'ARIMA' state\ndata ARIMAs :: Nat -> Nat -> Nat -> Type where\n    ARIMAs :: { _arimaYPred :: !Double\n              , _arimaYHist :: !(R (p + d))\n              , _arimaEHist :: !(R q)\n              }\n          -> ARIMAs p d q\n  deriving (Generic, Show)\n\ninstance (KnownNat p, KnownNat d, KnownNat q) => Learn Double Double (ARIMA p d q) where\n    type LParamMaybe (ARIMA p d q) = 'Just (ARIMAp p q)\n    type LStateMaybe (ARIMA p d q) = 'Just (ARIMAs p d q)\n\n    runLearn ARIMA{..} (J_ p) x (J_ s) = (y, J_ s')\n      where\n        d :: L p (p + d)\n        d  = difference\n        e  = x - (s ^^. arimaYPred)\n        y  = (p ^^. arimaConstant)\n           + (p ^^. arimaPhi  ) <.> (constVar d #> (s ^^. arimaYHist))\n           + (p ^^. arimaTheta) <.> (s ^^. arimaEHist)\n        yHist' = case Proxy @1 %<=? Proxy @(p + d) of\n          LE Refl -> single y # constVar dropLast #> (s ^^. arimaYHist)\n          NLE _ _ -> 0\n        eHist' = case Proxy @1 %<=? Proxy @q of\n          LE Refl -> single e # constVar dropLast #> (s ^^. arimaEHist)\n          NLE _ _ -> 0\n        s' = isoVar3 ARIMAs (\\(ARIMAs pr yh eh) -> (pr,yh,eh))\n                y\n                yHist'\n                eHist'\n\nmonosquare :: forall n. (n <=? (n ^ 2)) :~: 'True\nmonosquare = unsafeCoerce Refl\n\ndropLast :: forall n. (KnownNat n, 1 <= n) => L (n - 1) n\ndropLast = case monosquare @n of\n    Refl -> vecL . SVS.generate $ \\ij ->\n      let i :: Finite n\n          j :: Finite (n - 1)\n          (i, j) = separateProduct ij\n      in  if fromIntegral @_ @Int i == fromIntegral j\n            then 1\n            else 0\n\nsingle :: Reifies s W => BVar s Double -> BVar s (R 1)\nsingle = konst\n\ndifference'\n    :: Int                  -- ^ initial\n    -> Int                  -- ^ target\n    -> HU.Matrix Double     -- ^ target x initial\ndifference' n m = foldl' go (HU.ident m) [m + 1 .. n]\n  where\n    go x k = x HU.<> d k\n    d k = HU.build (k-1, k) $ \\i j ->\n        case round @_ @Int (j - i) of\n          0 -> 1\n          1 -> -1\n          _ -> 0\n\ndifference :: forall n m. (KnownNat n, KnownNat m) => L n (n + m)\ndifference = fromJust . H.create $ difference' (n + m) n\n  where\n    n = fromIntegral $ natVal (Proxy @n)\n    m = fromIntegral $ natVal (Proxy @m)\n\ninstance NFData (ARIMAp p q)\ninstance NFData (ARIMAs p d q)\n\ninstance Num (ARIMAp p q) where\n    (+)         = gPlus\n    (-)         = gMinus\n    (*)         = gTimes\n    negate      = gNegate\n    abs         = gAbs\n    signum      = gSignum\n    fromInteger = gFromInteger\n\ninstance Num (ARIMAs p d q) where\n    (+)         = gPlus\n    (-)         = gMinus\n    (*)         = gTimes\n    negate      = gNegate\n    abs         = gAbs\n    signum      = gSignum\n    fromInteger = gFromInteger\n\ninstance Fractional (ARIMAp p q) where\n    (/)          = gDivide\n    recip        = gRecip\n    fromRational = gFromRational\n\ninstance Fractional (ARIMAs p d q) where\n    (/)          = gDivide\n    recip        = gRecip\n    fromRational = gFromRational\n\ninstance Floating (ARIMAp p q) where\n    pi    = gPi\n    sqrt  = gSqrt\n    exp   = gExp\n    log   = gLog\n    sin   = gSin\n    cos   = gCos\n    asin  = gAsin\n    acos  = gAcos\n    atan  = gAtan\n    sinh  = gSinh\n    cosh  = gCosh\n    asinh = gAsinh\n    acosh = gAcosh\n    atanh = gAtanh\n\ninstance Floating (ARIMAs p d q) where\n    pi    = gPi\n    sqrt  = gSqrt\n    exp   = gExp\n    log   = gLog\n    sin   = gSin\n    cos   = gCos\n    asin  = gAsin\n    acos  = gAcos\n    atan  = gAtan\n    sinh  = gSinh\n    cosh  = gCosh\n    asinh = gAsinh\n    acosh = gAcosh\n    atanh = gAtanh\n\ninstance Additive (ARIMAp p q) where\n    (.+.)   = gAdd\n    addZero = gAddZero\ninstance Additive (ARIMAs p d q) where\n    (.+.)   = gAdd\n    addZero = gAddZero\n\ninstance (KnownNat p, KnownNat q) => Scaling Double (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q) => Scaling Double (ARIMAs p d q)\n\ninstance (KnownNat p, KnownNat q) => Metric  Double (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q) => Metric  Double (ARIMAs p d q)\n\ninstance (KnownNat p, KnownNat q, Ref m (ARIMAp p q) v) => AdditiveInPlace m v (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q, Ref m (ARIMAs p d q) v) => AdditiveInPlace m v (ARIMAs p d q)\n\ninstance (KnownNat p, KnownNat q, Ref m (ARIMAp p q) v) => ScalingInPlace m v Double (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q, Ref m (ARIMAs p d q) v) => ScalingInPlace m v Double (ARIMAs p d q)\n\ninstance (KnownNat p, KnownNat q) => Initialize (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q) => Initialize (ARIMAs p d q)\n\ninstance (KnownNat p, KnownNat q) => Bi.Binary (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q) => Bi.Binary (ARIMAs p d q)\n\ninstance (KnownNat p, KnownNat q) => Backprop (ARIMAp p q)\ninstance (KnownNat p, KnownNat d, KnownNat q) => Backprop (ARIMAs p d q)\n\narimaPhi :: Lens (ARIMAp p q) (ARIMAp p' q) (R p) (R p')\narimaPhi f a = (\\x' -> a { _arimaPhi = x' } ) <$> f (_arimaPhi a)\n\narimaTheta :: Lens (ARIMAp p q) (ARIMAp p q') (R q) (R q')\narimaTheta f a = (\\x' -> a { _arimaTheta = x' } ) <$> f (_arimaTheta a)\n\narimaConstant :: Lens' (ARIMAp p q) Double\narimaConstant f a = (\\x' -> a { _arimaConstant = x' } ) <$> f (_arimaConstant a)\n\narimaYPred :: Lens' (ARIMAs p d q) Double\narimaYPred f a = (\\x' -> a { _arimaYPred = x' } ) <$> f (_arimaYPred a)\n\narimaYHist :: Lens' (ARIMAs p d q) (R (p + d))\narimaYHist f a = (\\x' -> a { _arimaYHist = x' } ) <$> f (_arimaYHist a)\n\narimaEHist :: Lens (ARIMAs p d q) (ARIMAs p d q') (R q) (R q')\narimaEHist f a = (\\x' -> a { _arimaEHist = x' } ) <$> f (_arimaEHist a)\n\n-- | Autoregressive model\ntype AR p = ARIMA p 0 0\n\n-- | Moving average model\ntype MA = ARIMA 0 0\n\n-- | Autoregressive Moving average model\ntype ARMA p = ARIMA p 0\n\n", "meta": {"hexsha": "3d9a36370e92edfe732c28c71b3eae5a1b90c981", "size": 16455, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old2/src/Backprop/Learn/Model/Regression.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old2/src/Backprop/Learn/Model/Regression.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old2/src/Backprop/Learn/Model/Regression.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 33.7192622951, "max_line_length": 113, "alphanum_fraction": 0.5707687633, "num_tokens": 5172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.44937255203292403}}
{"text": "{-# LANGUAGE BangPatterns, \n             ScopedTypeVariables,\n             RecordWildCards,\n             FlexibleContexts,\n             TypeFamilies,\n             DeriveGeneric #-}\nmodule Main where\n\nimport Data.IDX ( decodeIDXFile, idxIntContent, IDXData ) \n{------------------------}\nimport Numeric.LinearAlgebra as NL ( Vector, fromList )\n{------------------------}\nimport Data.Vector.Unboxed as DTU ( toList )\n\nimport Prelude hiding (readFile)\nimport Neuro\n    ( Samples, Sample, createNetwork, tanh', saveNetwork, trainNTimes )\n\n\nmain :: IO ()\nmain = do\n  n <- createNetwork 784 [64] 10\n  samples <- importTrain\n  {-----------------------------}\n  let n' = trainNTimes 50 5.0 tanh tanh' n samples\n  saveNetwork \"smartNet5.nn\" n'\n\n\nimportTrain :: IO (Samples Double)\nimportTrain = do\n    Just idxTrain  <- decodeIDXFile \"train-images.idx3-ubyte\" -- image\n    Just idxResult <- decodeIDXFile \"train-labels.idx1-ubyte\" -- result\n    return $ samples idxTrain idxResult\n\nsamples :: IDXData -> IDXData -> [Sample Double]\nsamples idxTrain idxResult = Prelude.zip (image idxTrain) (result idxResult) :: [Sample Double]\n\nimage  = matrix2x2 . _0_1to0_255 . DTU.toList . idxIntContent\nresult = unitar . DTU.toList . idxIntContent\n\nunitar :: [Int] -> [NL.Vector Double]\nunitar []     = [] \nunitar (0:xs) = NL.fromList [1,-1,-1,-1,-1,-1,-1,-1,-1,-1] : unitar xs\nunitar (1:xs) = NL.fromList [-1,1,-1,-1,-1,-1,-1,-1,-1,-1] : unitar xs\nunitar (2:xs) = NL.fromList [-1,-1,1,-1,-1,-1,-1,-1,-1,-1] : unitar xs\nunitar (3:xs) = NL.fromList [-1,-1,-1,1,-1,-1,-1,-1,-1,-1] : unitar xs\nunitar (4:xs) = NL.fromList [-1,-1,-1,-1,1,-1,-1,-1,-1,-1] : unitar xs\nunitar (5:xs) = NL.fromList [-1,-1,-1,-1,-1,1,-1,-1,-1,-1] : unitar xs\nunitar (6:xs) = NL.fromList [-1,-1,-1,-1,-1,-1,1,-1,-1,-1] : unitar xs\nunitar (7:xs) = NL.fromList [-1,-1,-1,-1,-1,-1,-1,1,-1,-1] : unitar xs\nunitar (8:xs) = NL.fromList [-1,-1,-1,-1,-1,-1,-1,-1,1,-1] : unitar xs\nunitar (9:xs) = NL.fromList [-1,-1,-1,-1,-1,-1,-1,-1,-1,1] : unitar xs\n\n_0_1to0_255 :: [Int] -> [Double]\n_0_1to0_255 [] = []\n_0_1to0_255 (x:xs) = (fromIntegral x / 255) : _0_1to0_255 xs\n\nmatrix2x2 :: [Double] -> [NL.Vector Double]\nmatrix2x2 [] = []\nmatrix2x2 xs = NL.fromList (Prelude.take 784 xs) : matrix2x2 (Prelude.drop 784 xs)\n\n", "meta": {"hexsha": "ac81d20ed645739a774652cbd05d8ca1e7599615", "size": 2256, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "Alexander671/neuroLiquid", "max_stars_repo_head_hexsha": "48e816930b6b62b3fd4418190efaf2e71739cc4d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "Alexander671/neuroLiquid", "max_issues_repo_head_hexsha": "48e816930b6b62b3fd4418190efaf2e71739cc4d", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "Alexander671/neuroLiquid", "max_forks_repo_head_hexsha": "48e816930b6b62b3fd4418190efaf2e71739cc4d", "max_forks_repo_licenses": ["BSD-3-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.3870967742, "max_line_length": 95, "alphanum_fraction": 0.6050531915, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4492487816887972}}
{"text": "import System.Exit\n\nimport Quipper\nimport Quipper.Internal\n\nimport Quantum.Synthesis.Matrix\nimport Quantum.Synthesis.Ring\nimport Quipper.Libraries.Synthesis\n\nimport Quipper.Libraries.Decompose.GateBase\nimport Quipper.Libraries.Decompose\n\nimport Data.Complex\nimport Data.Ratio\nimport Data.Tuple\n\nimport Quipper.Utils.RandomSource\nimport System.Random\n\n-- declare sample_oracle's data type\ndata Oracle = Oracle {\n   qubit_num :: Int,\n   function :: ([Qubit], Qubit) -> Circ ([Qubit], Qubit)\n}\n\n-- declare circuit function\ncircuit_function :: Oracle -> Circ ([Bit], Bit)\ncircuit_function oracle = do\n     -- initialize string of qubits\n     top_qubits <- qinit (replicate (qubit_num oracle) False)\n     bottom_qubit <- qinit False\n     label (top_qubits, bottom_qubit) (\"|0>\",\"|0>\")\n\n     --prepare the initial states\n     --mapUnary hadamard top_qubits\n     --mapUnary hadamard bottom_qubit\n     \n     comment \"before oracle\"\n     -- call oracle\n     function oracle (top_qubits, bottom_qubit)\n     comment \"after oracle\"\n     \n     -- measure qubits\n     (top_qubits, bottom_qubit) <- measure (top_qubits, bottom_qubit)\n     -- discard unnecessary output and return result\n     return (top_qubits, bottom_qubit)\n\n\n-- * From a matrix\ntype Sixteen = Ten_and Six\n\nmymatrix :: Matrix Sixteen Sixteen (Integer)\nmymatrix = matrix [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], -- ([],0)\n                   [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], -- ([],1)\n                   [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], -- ([0],0)\n                   [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], -- ([0],1)\n                   [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], -- ([0,0],0)\n                   [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], -- ([0,0],1)\n                   [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], -- ([1,0],0)\n                   [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], -- ([1,0],1)\n                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], -- ([1],0)\n                   [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], -- ([1],1)\n                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], -- ([0,1],0)\n                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], -- ([0,1],1)\n                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], -- ([1,1],0)\n                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], -- ([1,1],1)\n                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], -- ([0,0,0],0)\n                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]] -- ([0,0,0],1)\n\nsynthesized = exact_synthesis mymatrix\n\ncircuit ::([Qubit], Qubit)-> Circ ([Qubit], Qubit)\ncircuit ([a, b, c], d) = do\n  synthesized [a,b,c,d]\n  return ([a,b,c],d)\n\n-- Standard decompose in X, Y , Z, H , S, S*, T, T* and CNOT\n-- needs : precision and randomSource\nrand = RandomSource(fst(split(mkStdGen 10)))\nprec = 20 * bits\ncircuit_decompose = decompose_generic (Standard prec rand) circuit\n\n\n--\noriginal_pdf :: IO ()\noriginal_pdf = do\n  print_generic Preview (circuit_function my_oracle)\n    where\n    -- declare empty_oracle's data type\n    my_oracle :: Oracle\n    my_oracle = Oracle {\n    -- set the length of qubit string\n        qubit_num = 3,\n        function = circuit\n    }\n\n-- \noriginal_ASCII :: IO ()\noriginal_ASCII = do\n  print_generic ASCII (circuit_function my_oracle)\n    where\n     -- declare empty_oracle's data type\n     my_oracle :: Oracle\n     my_oracle = Oracle {\n      -- set the length of qubit string\n       qubit_num = 3,\n       function = circuit\n     }\n\n\ndecompose_pdf :: IO ()\ndecompose_pdf = do\n  print_generic Preview (circuit_function my_oracle)\n    where\n   -- declare empty_oracle's data type\n   my_oracle :: Oracle\n   my_oracle = Oracle {\n     -- set the length of qubit string\n      qubit_num = 3,\n      function = circuit_decompose\n   }\n -- print mymatrix \n\ndecompose_ASCII :: IO ()\ndecompose_ASCII = do\n  print_generic ASCII (circuit_function my_oracle)\n    where\n   -- declare empty_oracle's data type\n   my_oracle :: Oracle\n   my_oracle = Oracle {\n     -- set the length of qubit string\n      qubit_num = 3,\n      function = circuit_decompose\n   }\n\n\nmain_menu = do \n  putStrLn \"\\n \\n \\n \\n \\n \\n \\n \\n choose an option:\"\n  putStrLn \" 1 - PDF original circuit\\n\"\n  putStrLn \" 2 - text description of original circuit\\n\"\n  putStrLn \" 3 - PDF decomposed circuit\\n\"\n  putStrLn \" 4 - text description of decomposed circuit\\n\"\n  putStrLn \" 5 - exit\\n\"\n  line <- getLine\n  case line of\n    \"1\" -> do original_pdf\n              main\n    \"2\" -> do original_ASCII\n              main\n    \"3\" -> do decompose_pdf\n              main\n    \"4\" -> do decompose_ASCII\n              main\n    \"5\" -> do exitSuccess\n    _ -> do main\n\nmain_qfold_cnot_7x2 = do\n  decompose_ASCII\n\nmain = do\n  --main_menu\n\n  -- or\n  -- if you want the circuit description a .txt file \n  -- comment the main_menu above \n  -- replacing it by:\n\n  main_qfold_cnot_7x2\n\n  -- and run:\n  -- $ ./qfold_cnot_7x2_quipper > circuit_cnot_7x2_quipper.txt  ", "meta": {"hexsha": "08d97320b0524981dbc85c384b86f317735e1418", "size": 5050, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "qfold_cnot_7x2_quipper.hs", "max_stars_repo_name": "AnaNeri/quantamorphismsGuide", "max_stars_repo_head_hexsha": "647fa79d68a132d72a5319df9822eeb410b70c79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-20T20:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-20T20:35:47.000Z", "max_issues_repo_path": "qfold_cnot_7x2_quipper.hs", "max_issues_repo_name": "AnaNeri/quantamorphismsGuide", "max_issues_repo_head_hexsha": "647fa79d68a132d72a5319df9822eeb410b70c79", "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": "qfold_cnot_7x2_quipper.hs", "max_forks_repo_name": "AnaNeri/quantamorphismsGuide", "max_forks_repo_head_hexsha": "647fa79d68a132d72a5319df9822eeb410b70c79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5321637427, "max_line_length": 83, "alphanum_fraction": 0.560990099, "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4491194134876732}}
{"text": "-----------------------------------------------------------------------------\n-- |\n-- Module      :  RL.Util\n-- Description :  Misc. Utilities\n-- Copyright   :  (c) David Banas, 2018\n-- License     :  BSD-style (see the file LICENSE)\n--\n-- Maintainer  :  David.Banas@target.com\n-- Stability   :  experimental\n-- Portability :  ?\n--\n-- Common utilities used throughout the RL package.\n-----------------------------------------------------------------------------\n\n{-# OPTIONS_GHC -Wall #-}\n\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE TypeApplications #-}\n\nmodule RL.Util where\n\nimport qualified Prelude as P\nimport Prelude (Show(..))\nimport Protolude  hiding (show, for)\n\nimport GHC.TypeLits\n\nimport qualified Data.Vector.Sized   as VS\nimport Data.Vector.Sized             (Vector)\n\nimport Control.Monad.Writer\nimport Data.Finite\nimport Data.Finite.Internal\nimport Data.List                     ((!!))\nimport Statistics.Distribution       (density)\nimport Statistics.Distribution.Gamma (gammaDistr)\nimport Text.Printf\n\nimport ConCat.TArr\n\n-- | Convenient abbreviation of: `natVal (Proxy @n)`.\nnat :: forall n. KnownNat n => Integer\nnat = natVal (Proxy @n)\n\n-- | Convenient abbreviation of: `fromIntegral (nat @n)`.\nint :: forall n. KnownNat n => Int\nint = fromIntegral (nat @n)\n\n-- | Apply the matrix representation of a two argument function.\n--\n-- The first argument is assumed to index the rows of the matrix.\nappFm\n  :: ( HasFin' a,   HasFin' b )\n  => Vector (Card a) (Vector (Card b) c)  -- ^ matrix representation of @f(r,c)@\n  -> a                                    -- ^ row\n  -> b                                    -- ^ column\n  -> c\nappFm f x y = f `VS.index` toFin x `VS.index` toFin y\n\n-- | Apply the vector representation of a function.\nappFv\n  :: ( HasFin' x )\n  => Vector (Card x) a  -- ^ vector representation of @f(x)@\n  -> x                  -- ^ function argument\n  -> a\nappFv f x = f `VS.index` toFin x\n\n-- | Convert an action-value matrix to a value vector.\n--\n-- (i.e. - \\(Q(s,a) -> V(s)\\))\nqToV\n  :: ( Ord a\n     , KnownNat m, KnownNat n, KnownNat k\n     , n ~ (k + 1)\n     )\n  => Vector m (Vector n a)  -- ^ matrix representation of @Q(s,a)@\n  -> Vector m a             -- ^ vector representation of @V(s)@\nqToV = VS.map VS.maximum\n\n-- | Convert an action-value matrix to a policy vector.\n--\n-- (i.e. - \\(Q(s,a) -> A(s)\\))\nqToP\n  :: ( Ord a, HasFin' act\n     , KnownNat m, KnownNat n, KnownNat k\n     , n ~ (k + 1), Card act ~ n\n     )\n  => Vector m (Vector n a)  -- ^ matrix representation of Q(s,a)\n  -> Vector m act           -- ^ vector representation of P(s)\nqToP = VS.map (unFin . VS.maxIndex)\n\n{----------------------------------------------------------------------\n  Misc.\n----------------------------------------------------------------------}\n\n-- | To control the formatting of printed floats in output matrices.\nnewtype Pfloat = Pfloat { unPfloat :: Float}\n  deriving (Eq)\n\ninstance Show Pfloat where\n  show x = printf \"%4.1f\" (unPfloat x)\n\n-- | To control the formatting of printed doubles in output matrices.\nnewtype Pdouble = Pdouble { unPdouble :: Double }\n  deriving (Eq, Ord)\n\ninstance Show Pdouble where\n  show x = printf \"%4.1f\" (unPdouble x)\n\npoisson :: Finite 5 -> Finite 12 -> Float\npoisson (Finite lambda) (Finite n') =\n  lambda' ^ n * exp (-lambda') / fromIntegral (fact n)\n where lambda' = fromIntegral lambda\n       n       = fromIntegral n'\n\nfact :: Int -> Int\nfact 0 = 1\nfact n = product [1..n]\n\npoissonVals :: VS.Vector 5 (VS.Vector 12 Float)\npoissonVals = VS.generate (VS.generate . poisson)\n\npoisson' :: Finite 5 -> Finite 21 -> Float\npoisson' n x@(Finite x') =\n  if x > 11  -- The Python code enforces this limit. And we're trying\n    then 0   -- for an \"apples-to-apples\" performance comparison.\n    else poissonVals `VS.index` n `VS.index` finite x'\n\n-- | Gamma pdf\n--\n-- Assuming `scale = 1`, `shape` should be: 1 + mean.\ngammaPdf :: Double -> Double -> Double -> Double\ngammaPdf shape scale = density (gammaDistr shape scale)\n\n-- | Gamma pmf\n--\n-- Scale assumed to be `1`, so as to match the calling signature of\n-- `poisson`.\ngamma :: Finite 5 -> Finite 12 -> Double\ngamma (Finite expect') (Finite n') =\n  0.1 * sum [gammaPdf' (n + x) | x <- [0.1 * m | m <- [-4..5]]]\n    where gammaPdf' = gammaPdf (1 + expect) 1\n          expect    = fromIntegral expect'\n          n         = fromIntegral n'\n\ngammaVals :: VS.Vector 5 (VS.Vector 12 Double)\ngammaVals = VS.generate (VS.generate . gamma)\n\ngamma' :: Finite 5 -> Finite 21 -> Double\ngamma' n (Finite x') =\n  if x' > 11\n    then 0\n    else gammaVals `VS.index` n `VS.index` finite x'\n\n-- | Monadically search list for first element less than\n-- given threshold under the given function, and return the last element\n-- if the threshold was never met.\n-- Return 'Nothing' if the input list was empty.\nwithinOnM :: Monad m\n          => Double\n          -> (a -> m Double)\n          -> [a]\n          -> m (Maybe a)\nwithinOnM _   _ [] = return Nothing\nwithinOnM eps f xs = do\n  n <- withinIxM eps $ map f xs\n  case n of\n    Nothing -> return Nothing\n    Just n' -> return $ Just (xs !! n')\n\n-- | Monadically find index of first list element less than or equal to\n-- given threshold, or the index of the last element if the threshold\n-- was never met.\n--\n-- A return value of 'Nothing' indicates an empty list was given.\nwithinIxM :: Monad m\n          => Double\n          -> [m Double]\n          -> m (Maybe Int)\nwithinIxM _   [] = return Nothing\nwithinIxM eps xs = withinIxM' 0 xs\n where withinIxM' n []     = return $ Just (n - 1)\n       withinIxM' n (y:ys) = do\n         y' <- y\n         if y' < eps then return (Just n)\n                     else withinIxM' (n+1) ys\n\n-- | Return the maximum value of a set, as well as a count of the number\n-- of non-zero elements in the set.\n--\n-- (See documentation for `chooseAndCount` function.)\nmaxAndNonZero :: (Foldable t, Num a, Ord a) => t a -> Writer [Int] a\nmaxAndNonZero = chooseAndCount max (/= 0)\n\n-- | Choose a value from the set using the given comparison function,\n-- and provide a count of the number of elements in the set meeting the\n-- given criteria.\nchooseAndCount :: (Foldable t, Num a)\n               => (a -> a -> a)  -- ^ choice function\n               -> (a -> Bool)    -- ^ counting predicate\n               -> t a            -- ^ foldable set of elements to count/compare\n               -> Writer [Int] a\nchooseAndCount f p xs = do\n  let (val, cnt::Int) =\n        foldl' ( \\ (v, c) x ->\n                   ( f v x\n                   , if p x\n                       then c + 1\n                       else c\n                   )\n               ) (0,0) xs\n  tell [cnt]\n  return val\n\nfor :: [a] -> (a -> b) -> [b]\nfor = flip map\n\nvsFor :: Vector n a -> (a -> b) -> Vector n b\nvsFor = flip VS.map\n\n-- | Mean value of a collection\nmean :: (Foldable f, Fractional a) => f a -> a\nmean = uncurry (/) . second fromIntegral . foldl' (\\ (!s, !n) x -> (s+x, n+1)) (0,0::Integer)\n\n-- | Find the mean square of a list of lists.\narrMeanSqr :: (Functor f, Foldable f, Functor g, Foldable g, Fractional a) => f (g a) -> a\narrMeanSqr = mean . fmap mean . fmap (fmap sqr)\n\n-- | Take the square of a numerical type.\nsqr :: Num a => a -> a\nsqr x = x * x\n\n-- | Convert any showable type to a string, avoiding the introduction\n-- of extra quotation marks when that type is a string to begin with.\ntoString :: (Show a, Typeable a) => a -> P.String\ntoString x = fromMaybe (show x) (cast x)\n\n-- | Convert a Bool to a Double.\nboolToDouble :: Bool -> Double\nboolToDouble True = 1\nboolToDouble _    = 0\n\n-- | Take every nth element from a list.\ntakeEvery :: Int -> [a] -> [a]\ntakeEvery _ [] = []\ntakeEvery n xs = P.head xs : (takeEvery n $ drop n xs)\n\n", "meta": {"hexsha": "000f505ee8b2c241db02ba4386e62e0e88cc0afe", "size": 7699, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/RL/Util.hs", "max_stars_repo_name": "capn-freako/haskell-rl", "max_stars_repo_head_hexsha": "fec87fa21daf46ccb993e8d661251fcc8ae7f838", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-04-16T21:41:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T14:54:06.000Z", "max_issues_repo_path": "src/RL/Util.hs", "max_issues_repo_name": "capn-freako/haskell-rl", "max_issues_repo_head_hexsha": "fec87fa21daf46ccb993e8d661251fcc8ae7f838", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-04-05T14:46:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-06T15:16:53.000Z", "max_forks_repo_path": "src/RL/Util.hs", "max_forks_repo_name": "capn-freako/haskell-rl", "max_forks_repo_head_hexsha": "fec87fa21daf46ccb993e8d661251fcc8ae7f838", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-04T00:00:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T00:00:42.000Z", "avg_line_length": 31.0443548387, "max_line_length": 93, "alphanum_fraction": 0.5781270295, "num_tokens": 2134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.44909999648344967}}
{"text": "-- Copyright \u00a9 2016 Bart Massey\n-- [This work is made available under the \"MIT License\".\n-- Please see the file LICENSE in this distribution for\n-- license details.]\n\n-- Analysis tool for a Hardware Random Number Generator\n\nimport Control.Lens\nimport Data.Char (toLower)\nimport Data.Colour\nimport Data.Colour.Names\nimport Data.Colour.SRGB\nimport Data.Default.Class\nimport Data.List.Split (splitOn)\nimport Data.Maybe\nimport Graphics.Rendering.Chart\nimport Graphics.Rendering.Chart.Backend.Cairo\n\nimport Data.Complex\nimport qualified Data.Vector.Unboxed as V\nimport Numeric.FFT.Vector.Unnormalized\n\nimport Control.Monad\nimport Data.Bits\nimport qualified Data.ByteString as B\nimport Data.List\nimport System.Console.ParseArgs\nimport System.Directory\nimport System.Exit (exitSuccess)\nimport System.FilePath\nimport System.Random\nimport Text.Printf\n\ndefaultAnalysisDir :: FilePath\ndefaultAnalysisDir = \"analysis\"\n\nwWindowSize :: Int\nwWindowSize = 4096\n\nanalysisFile :: FilePath -> FilePath -> String -> String-> FilePath\nanalysisFile dir what suff ext =\n    joinPath [dir, addExtension (what ++ \"-\" ++ suff) ext]\n\nplotSuffix :: Maybe FileFormat -> String\nplotSuffix (Just PDF) = \"pdf\"\nplotSuffix (Just SVG) = \"svg\"\nplotSuffix _ = error \"no suffix for (non)plot format\"\n\nplotRender :: FileFormat -> String -> Renderable a -> IO ()\nplotRender ff name r = do\n    _ <- renderableToFile (fo_format .~ ff $ def) name r\n    return ()\n\nreadSamples :: Int -> B.ByteString -> [Int]\nreadSamples sampleCount stuff =\n    take sampleCount $ makeInts $ B.unpack stuff\n    where\n      makeInts [] = []\n      makeInts [_] = error \"odd byte array\"\n      makeInts (b2 : b1 : bs) =\n          let i1 = fromIntegral b1\n              i2 = fromIntegral b2\n          in\n          ((i1 `shiftL` 8) .|. i2) : makeInts bs\n            \ntakeSpan :: Int -> Int -> [a] -> [a]\ntakeSpan start len xs =\n    take len $ drop start xs\n\nrawHist :: [Int] -> [(Int, Int)]\nrawHist samples =\n    map histify $ group $ sort $ samples ++ [smallest..largest]\n    where\n      smallest = minimum samples\n      largest = maximum samples\n      histify [] = error \"bad hist group\"\n      histify (x : xs) = (x, length xs)\n\nshowHist :: [(Int, Int)] -> String\nshowHist bins =\n    unlines $ map showBin bins\n    where\n      showBin (x, y) = unwords [show x, show y]\n\ntype ColourPair = (Colour Double, Colour Double)\n\nplotTimeSeries :: ColourPair -> [Int]\n               -> Renderable (LayoutPick Int Int Int)\nplotTimeSeries (color, color2) samples = do\n  let nSamples = length samples\n  let samplePoints = zip [(1::Int)..] samples\n  let zoomedPoints =\n          zip [0, nSamples `div` 100 ..] $\n              takeSpan (nSamples `div` 3) 100 samples\n  let allPlot =\n          toPlot $\n          plot_points_style .~ filledCircles 0.5 (opaque color2) $\n          plot_points_values .~ samplePoints $\n          plot_points_title .~ \"all\" $\n          def\n  let zoomedPlot =\n          toPlot $\n          plot_lines_style . line_color .~ opaque color $\n          plot_lines_values .~ [zoomedPoints] $\n          plot_lines_title .~ \"zoomed\" $\n          def\n  let tsLayout =\n          layout_x_axis .~ (laxis_title .~ \"sample\" $ def) $\n          layout_y_axis .~ (laxis_title .~ \"value\" $ def) $\n          layout_plots .~ [allPlot, zoomedPlot] $\n          def\n  layoutToRenderable tsLayout\n\nplotSampleHist :: ColourPair -> Int -> [Int]\n               -> Renderable (LayoutPick Int Int Int)\nplotSampleHist (color, _) nBins samples = do\n  let histPlot =\n          plotBars $\n          plot_bars_values .~  sampleBars ++ [(nBins, [0])] $\n          plot_bars_item_styles .~ [barStyle] $\n          plot_bars_spacing .~ BarsFixGap 0 0 $\n          plot_bars_alignment .~ BarsLeft $\n          def\n  let histLayout =\n          layout_x_axis .~ (laxis_title .~ \"value\" $ def) $\n          layout_y_axis .~ (laxis_title .~ \"frequency\" $ def) $\n          layout_plots .~ [histPlot] $\n          def\n  layoutToRenderable histLayout\n  where\n    sampleBars =\n        map (\\(x, y) -> (x, [y])) $ rawHist samples\n    barStyle = (FillStyleSolid (opaque gray),\n                Just (line_width .~ 0.05 $ line_color .~ opaque color $ def))\n\nplotSampleDFT :: ColourPair -> [Double]\n              -> Renderable (LayoutPick Double Double Double)\nplotSampleDFT (color, _) dftBins = do\n  let dftPlot =\n          plotBars $\n          plot_bars_spacing .~ BarsFixWidth 0.3 $\n          plot_bars_values .~ dftBars $\n          plot_bars_item_styles .~ [barStyle] $\n          def\n  let dftLayout =\n          layout_x_axis .~ (laxis_title .~ \"frequency\" $ def) $\n          layout_y_axis .~ (laxis_title .~ \"amplitude\" $ def) $\n          layout_plots .~ [dftPlot] $\n          def\n  layoutToRenderable dftLayout\n  where\n    dftBars = map (\\(x, y) -> (x, [y])) $ zip [0..] dftBins\n    barStyle = (FillStyleSolid (opaque color), Nothing)\n\ndata EntropyMode = EntropyModeRaw | EntropyModeNormalized\n\nentropy :: Real a => EntropyMode -> [a] -> Double\nentropy mode samples =\n    negate $ sum $ map binEntropy samples\n    where\n      weight =\n          case mode of\n            EntropyModeRaw -> 1.0\n            EntropyModeNormalized -> realToFrac $ sum samples\n      binEntropy 0 = 0\n      binEntropy count =\n          p * logBase 2 p\n          where\n            p = realToFrac count / weight\n\nhannWindow :: Int -> [Double]\nhannWindow nSamples =\n    map hannFunction [0 .. nSamples - 1]\n    where\n      hannFunction n =\n          0.5 * (1.0 - cos(2 * pi * fromIntegral n / nn))\n          where\n            nn = fromIntegral (nSamples - 1)\n\nsampleDFT :: [Double] -> [Double]\nsampleDFT samples =\n    map magnitude $ V.toList $ run dftR2C $ V.fromList samples\n\ndata Bias = BiasDebiased | BiasNominal Int\ndata DFTMode = DFTModeRaw |\n               DFTModeProper Int (Int -> [Double])\n\nsplitSamples :: Int -> [a] -> [[a]]\nsplitSamples n xs\n    | length first < n = []\n    | otherwise =\n        first : splitSamples n rest\n    where\n      (first, rest) = splitAt n xs\n\nprocessDFT :: Bias -> DFTMode -> [Int] -> [Double]\nprocessDFT bias dftMode samples =\n    case dftMode of\n      DFTModeRaw ->\n          sampleDFT dftSamples\n          where\n            dftStart = (nSamples - dftLength) `div` 3\n            dftLength = min 10000 nSamples\n            dftSamples = takeSpan dftStart dftLength normedSamples\n      DFTModeProper windowSize window ->\n        avgBins $ map (sampleDFT . applyWindow) $\n          splitSamples windowSize normedSamples\n        where\n          applyWindow xs =\n              zipWith (*) xs $ window windowSize\n          avgBins bins =\n              map average $ transpose bins\n    where\n      nSamples = length samples\n      normedSamples =\n          map norm samples\n          where\n            norm sample =\n                (fromIntegral sample - dftDC) / fromIntegral nSamples\n                where\n                  dftDC = \n                      case bias of\n                        BiasNominal nBits ->\n                            fromIntegral (2 ^ (nBits - 1) - 1 :: Integer)\n                        BiasDebiased ->\n                            average samples\n\naverage :: Real a => [a] -> Double\naverage samples =\n    realToFrac (sum samples) / fromIntegral (length samples)\n\nstdDeviation :: Real a => [a] -> Double\nstdDeviation samples =\n    sqrt (sum devs / fromIntegral (length devs))\n    where\n      devs = map (square . (`subtract` mean) . realToFrac) samples\n      square x = x * x\n      mean = average samples\n\nspectralFlatness :: [Double] -> Double\nspectralFlatness rDFT =\n    10.0 * (gMeanDB - aMeanDB)\n    where\n      xDFT = tail rDFT\n      nxDFT = fromIntegral (length xDFT)\n      gMeanDB = sum (map (logBase 10) xDFT) / nxDFT\n      aMeanDB = logBase 10 (sum xDFT) - logBase 10 nxDFT\n\nsecondMoment64 :: [Int] -> (Double, Double)\nsecondMoment64 samples =\n    (minimum devs, maximum devs)\n    where\n      devs = map stdDeviation $ splitSamples 64 samples\n\nshowStats :: Int -> [Int] -> [Double] -> [Double] -> String\nshowStats nBits samples rDFT wDFT = unlines [\n  printf \"min: %d\" (minimum samples),\n  printf \"max: %d\" (maximum samples),\n  printf \"mean: %0.3g\" (average samples),\n  printf \"byte-entropy: %0.3g\"\n      (entropyAdj * entropy EntropyModeNormalized hist),\n  printf \"second-moment-64s-min: %0.3g\" smMin,\n  printf \"second-moment-64s-max: %0.3g\" smMax,\n  printf \"spectral-entropy: %0.3g\"\n      (spectralEntropyAdj * entropy EntropyModeNormalized rDFT2),\n  printf \"spectral-flatness-db: %0.3g\" (spectralFlatness rDFT),\n  printf \"avg-spectral-flatness-db: %0.3g\" (spectralFlatness wDFT) ]\n  where\n    (smMin, smMax) = secondMoment64 samples\n    hist = map snd $ rawHist samples\n    rDFT2 = map (**2.0) $ tail rDFT\n    entropyAdj =\n        max 1.0 $ 8.0 / fromIntegral nBits\n    spectralEntropyAdj =\n        fromIntegral (max 8 nBits)  / logBase 2.0 (fromIntegral (length rDFT2))\n\nanalyze :: Maybe FileFormat -> ColourPair\n        -> String -> String -> Int -> [Int]\n        -> IO ()\nanalyze plotMode colors dir what nBits samples = do\n  let rDFT = processDFT BiasDebiased DFTModeRaw samples\n  let wDFT = processDFT BiasDebiased (DFTModeProper wWindowSize hannWindow) samples\n  writeFile (af \"stats\" \"txt\") $\n    showStats nBits samples rDFT wDFT\n  case plotMode of\n    Just ff -> do\n      writeFile (af \"hist\" \"txt\") $ showHist $ rawHist samples\n      let pr = plotRender ff\n      pr (af' \"ts\") $ plotTimeSeries colors samples\n      pr (af' \"hist\") $ plotSampleHist colors (2 ^ nBits) samples\n      pr (af' \"dft\") $ plotSampleDFT colors rDFT\n      pr (af' \"wdft\") $ plotSampleDFT colors wDFT\n    Nothing -> return ()\n  where\n    af = analysisFile dir what\n    af' name = af name (plotSuffix plotMode)\n\ndata ArgIndex = ArgIndexBitsFile\n              | ArgIndexPlotFormat\n              | ArgIndexAnalysisDir\n              | ArgIndexSampleCount\n              | ArgIndexColor\n              | ArgIndexColor2\n              | ArgIndexTests\n                deriving (Eq, Ord, Show)\n\nmaybeReadS :: ReadS a -> String -> Maybe a\nmaybeReadS f s =\n    case f s of\n      [(v, \"\")] -> Just v\n      _ -> Nothing\n\nreadColor :: String -> Colour Double\nreadColor name =\n    head $ mapMaybe id [\n               maybeReadS sRGB24reads name,\n               readColourName name,\n               error \"illegal color\" ]\n\nargd :: [Arg ArgIndex]\nargd = [\n  Arg {\n    argIndex = ArgIndexPlotFormat,\n    argName = Just \"plot-format\",\n    argAbbr = Just 'p',\n    argData = argDataDefaulted \"type\" ArgtypeString \"pdf\",\n    argDesc = \"Plot format (\\\"pdf\\\", \\\"svg\\\", or \\\"none\\\" for just stats)\" },\n  Arg {\n    argIndex = ArgIndexAnalysisDir,\n    argName = Just \"analysis-dir\",\n    argAbbr = Just 'a',\n    argData = argDataDefaulted \"dir\" ArgtypeString defaultAnalysisDir,\n    argDesc = \"Directory for analysis results\" },\n  Arg {\n    argIndex = ArgIndexSampleCount,\n    argName = Just \"sample-count\",\n    argAbbr = Just 's',\n    argData = argDataOptional \"count\" ArgtypeInt,\n    argDesc = \"Number of samples to analyze\" },\n  Arg {\n    argIndex = ArgIndexColor,\n    argName = Just \"color\",\n    argAbbr = Nothing,\n    argData = argDataDefaulted \"name/rgb\" ArgtypeString \"black\",\n    argDesc = \"Plot color\" },\n  Arg {\n    argIndex = ArgIndexColor2,\n    argName = Just \"secondary-color\",\n    argAbbr = Nothing,\n    argData = argDataDefaulted \"name/rgb\" ArgtypeString \"gray\",\n    argDesc = \"Plot secondary color\" },\n  Arg {\n    argIndex = ArgIndexTests,\n    argName = Just \"tests\",\n    argAbbr = Just 't',\n    argData = argDataOptional \"test-list\" ArgtypeString,\n    argDesc = \"Comma-separated list of tests (\\\"help\\\" for help)\" },\n  Arg {\n    argIndex = ArgIndexBitsFile,\n    argName = Nothing,\n    argAbbr = Nothing,\n    argData = argDataOptional \"bits-file\" ArgtypeString,\n    argDesc = \"Random bits.\" } ]\n\n\ntestSet :: [String]\ntestSet = [\"raw\",\"prng\",\"twobit\",\"mid\",\"mid7\",\"low\"]\n\ntestHelp :: IO ()\ntestHelp = do\n  printf \"Available Tests:\\n\"\n  mapM_ (\\t -> printf \"  %s\\n\" t) testSet\n  exitSuccess\n\nmain :: IO ()\nmain = do\n  args <- parseArgsIO ArgsComplete argd\n\n  let tests =\n          case getArg args ArgIndexTests of\n            Nothing -> testSet\n            Just(ts) -> splitOn \",\" ts\n  when (tests == [\"help\"]) testHelp\n\n  let plotFormat =\n          case map toLower $ getRequiredArg args ArgIndexPlotFormat of\n            \"none\" -> Nothing\n            \"pdf\" -> Just PDF\n            \"svg\" -> Just SVG\n            _ -> error \"unrecognized plot format\"\n\n  bitsFile <- getArgStdio args ArgIndexBitsFile ReadMode\n  rawSamples <- B.hGetContents bitsFile\n  let nSamples = B.length rawSamples `div` 2\n  let sampleCount = case getArg args ArgIndexSampleCount of\n                      Nothing -> nSamples\n                      Just n -> nSamples `min` n\n  let samples = readSamples sampleCount rawSamples\n\n  let analysisDir = getRequiredArg args ArgIndexAnalysisDir\n  createDirectoryIfMissing True analysisDir\n\n  let plotColor = readColor $ getRequiredArg args ArgIndexColor\n  let plotColor2 = readColor $ getRequiredArg args ArgIndexColor2\n\n  let aa name bits source =\n          when (name `elem` tests) $\n               analyze plotFormat (plotColor, plotColor2) analysisDir\n                       name bits source\n\n  aa \"raw\" 12 samples\n\n  prng12Samples <- replicateM (length samples) (randomRIO (0, 4095) :: IO Int)\n  aa \"prng12\" 12 prng12Samples\n\n  prngSamples <- replicateM (length samples) (randomRIO (0, 255) :: IO Int)\n  aa \"prng\" 8 prngSamples\n\n  let twoBitSamples = map (.&. 0x03) samples\n  aa \"twobit\" 2 twoBitSamples\n\n  let midSamples = map ((.&. 0xff) . (`shiftR` 1)) samples\n  aa \"mid\" 8 midSamples\n\n  let mid7Samples = map ((.&. 0x7f) . (`shiftR` 2)) samples\n  aa \"mid7\" 7 mid7Samples\n\n  let lowSamples = map (.&. 0xff) samples\n  aa \"low\" 8 lowSamples\n\n  let hmSamples = map hmBits samples\n                  where\n                    hmBits sample =\n                        let mid = (sample `shiftR` 1) .&. 0xff in\n                        mid `xor` (sample .&. 0x01) `xor`\n                          ((sample `shiftR` 9) .&. 0x01) `xor`\n                          ((sample `shiftR` 10) .&. 0x01) `xor`\n                          ((sample `shiftR` 11) .&. 0x01)\n  aa \"hm\" 8 hmSamples\n", "meta": {"hexsha": "850a128907c1ffbbfae1e326f928ac411e71357c", "size": 14095, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "anrand.hs", "max_stars_repo_name": "BartMassey/anrand", "max_stars_repo_head_hexsha": "405f55d4215f685ec94de5dd41197a6bd9080896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-13T08:06:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T08:06:50.000Z", "max_issues_repo_path": "anrand.hs", "max_issues_repo_name": "BartMassey/anrand", "max_issues_repo_head_hexsha": "405f55d4215f685ec94de5dd41197a6bd9080896", "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": "anrand.hs", "max_forks_repo_name": "BartMassey/anrand", "max_forks_repo_head_hexsha": "405f55d4215f685ec94de5dd41197a6bd9080896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-02T11:00:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T11:00:15.000Z", "avg_line_length": 32.0340909091, "max_line_length": 83, "alphanum_fraction": 0.6161759489, "num_tokens": 3921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4489965703150022}}
{"text": "{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# LANGUAGE TypeOperators       #-}\n\n#if MIN_VERSION_base(4,12,0)\n{-# LANGUAGE NoStarIsType         #-}\n#endif\n\n-- |\n-- Module      : Numeric.LinearAlgebra.Static.Vector\n-- Copyright   : (c) Justin Le 2018\n-- License     : BSD3\n--\n-- Maintainer  : justin@jle.im\n-- Stability   : experimental\n-- Portability : non-portable\n--\n-- Conversions between statically sized types in\n-- \"Numeric.LinearAlgebra.Static\" from /hmatrix/ and /vector-sized/.\n--\n-- This module is intentionally minimal, exporting only functions that\n-- cannot be written without \"unsafe\" operations.  With these, however, you\n-- can easily write other useful combinators by using type-safe operations\n-- like 'fmap', 'VS.map', 'liftA2', 'Data.Vector.Generic.Sized.convert',\n-- etc.\n--\n\nmodule Numeric.LinearAlgebra.Static.Vector (\n  -- * Vector\n  -- ** Real\n    rVec\n  , grVec\n  , vecR\n  , gvecR\n  -- ** Complex\n  , cVec\n  , gcVec\n  , vecC\n  , gvecC\n  -- * Matrix\n  -- ** Real\n  , lRows\n  , rowsL\n  , lCols\n  , colsL\n  , lVec\n  , glVec\n  , vecL\n  , gvecL\n  -- ** Complex\n  , mRows\n  , rowsM\n  , mCols\n  , colsM\n  , mVec\n  , gmVec\n  , vecM\n  , gvecM\n  ) where\n\nimport           Data.Foldable\nimport           Data.Proxy\nimport           GHC.TypeLits\nimport           Unsafe.Coerce\nimport qualified Data.Vector                  as UV\nimport qualified Data.Vector.Generic          as UVG\nimport qualified Data.Vector.Generic.Sized    as VG\nimport qualified Data.Vector.Sized            as V\nimport qualified Data.Vector.Storable.Sized   as VS\nimport qualified Numeric.LinearAlgebra        as HU\nimport qualified Numeric.LinearAlgebra.Static as H\n\n-- | Convert an /hmatrix/ vector (parameterized by its lenth) to\n-- a /vector-sized/ storable vector of 'Double's.\n--\n-- This is normally /O(1)/, but will be /O(n)/ if the 'H.R' was contructed\n-- with 'H.konst' or any other replicated-value constructor (like literals\n-- and 'fromInteger'/'fromRational').\nrVec :: KnownNat n => H.R n -> VS.Vector n H.\u211d\nrVec = unsafeCoerce . H.extract\n\n-- | 'rVec', but generalized to work for all types of sized vectors.\n--\n-- Usually /O(n)/, but if using this with storable vectors, should have the\n-- same characteristics as 'rVec' due to rewrite rules.\n--\n-- @since 0.1.3.0\ngrVec :: (KnownNat n, UVG.Vector v H.\u211d) => H.R n -> VG.Vector v n H.\u211d\ngrVec = VG.convert . rVec\n{-# NOINLINE[1] grVec #-}\n{-# RULES \"grVec\" grVec = rVec #-}\n\n-- | Convert a /vector-sized/ storable vector to an /hmatrix/ vector\n-- (parameterized by its lenth).\n--\n-- /O(1)/\nvecR :: VS.Vector n H.\u211d -> H.R n\nvecR = unsafeCoerce\n\n-- | 'vecR', but generalized to work for all types of sized vectors.\n--\n-- Usually /O(n)/, but if using this with storable vectors, should be /O(1)/\n-- due to rewrite rules (but don't rely on this).\n--\n-- @since 0.1.3.0\ngvecR :: UVG.Vector v H.\u211d => VG.Vector v n H.\u211d -> H.R n\ngvecR = vecR . VG.convert\n{-# NOINLINE[1] gvecR #-}\n{-# RULES \"gvecR\" gvecR = vecR #-}\n\n-- | Convert an /hmatrix/ complex vector (parameterized by its lenth) to\n-- a /vector-sized/ storable vector of 'Complex Double's, preserving the\n-- length in the type.\n--\n-- This is normally /O(1)/, but will be /O(n)/ if the 'H.C' was contructed\n-- with 'H.konst' or any other replicated-value constructor (like literals\n-- and 'fromInteger'/'fromRational').\ncVec :: KnownNat n => H.C n -> VS.Vector n H.\u2102\ncVec = unsafeCoerce . H.extract\n\n-- | 'cVec', but generalized to work for all types of sized vectors.\n--\n-- Usually /O(n)/, but if using this with storable vectors, should have the\n-- same characteristics as 'cVec' due to rewrite rules.\n--\n-- @since 0.1.3.0\ngcVec :: (KnownNat n, UVG.Vector v H.\u2102) => H.C n -> VG.Vector v n H.\u2102\ngcVec = VG.convert . cVec\n{-# NOINLINE[1] gcVec #-}\n{-# RULES \"gcVec\" gcVec = cVec #-}\n\n-- | Convert a /vector-sized/ storable vector to an /hmatrix/ complex\n-- vector (parameterized by its lenth), preserving the length in the type.\n--\n-- /O(1)/\nvecC :: VS.Vector n H.\u2102 -> H.C n\nvecC = unsafeCoerce\n\n-- | 'vecC', but generalized to work for all types of sized vectors.\n--\n-- Usually /O(n)/, but if using this with storable vectors, should be /O(1)/\n-- due to rewrite rules (but don't rely on this).\n--\n-- @since 0.1.3.0\ngvecC :: UVG.Vector v H.\u2102 => VG.Vector v n H.\u2102 -> H.C n\ngvecC = vecC . VG.convert\n{-# NOINLINE[1] gvecC #-}\n{-# RULES \"gvecC\" gvecC = vecC #-}\n\n-- | Split an /hmatrix/ matrix (parameterized by its dimensions) to\n-- a /vector-sized/ boxed vector of its rows (as /hmatrix/ vectors).\n--\n-- This is normally /O(m*n)/, but can sometimes be /O(m)/ depending on the\n-- representation of the 'H.L' being used.\nlRows\n    :: (KnownNat m, KnownNat n)\n    => H.L m n\n    -> V.Vector m (H.R n)\nlRows = unsafeCoerce\n      . UV.fromList\n      . HU.toRows\n      . H.extract\n\n-- | Join together a /vector-sized/ boxed vector of /hmatrix/ vectors to an\n-- /hmatrix/ matrix as its rows.\n--\n-- /O(m*n)/\nrowsL\n    :: forall m n. KnownNat n\n    => V.Vector m (H.R n)\n    -> H.L m n\nrowsL = (unsafeCoerce :: HU.Matrix Double -> H.L m n)\n      . HU.fromRows\n      . map H.extract\n      . toList\n\n-- | Split an /hmatrix/ matrix (parameterized by its dimensions) to\n-- a /vector-sized/ boxed vector of its columns (as /hmatrix/ vectors).\n--\n-- This is normally /O(m*n)/, but can sometimes be /O(n)/ depending on the\n-- representation of the 'H.L' being used.\nlCols\n    :: forall m n. (KnownNat m, KnownNat n)\n    => H.L m n\n    -> V.Vector n (H.R m)\nlCols = unsafeCoerce\n      . UV.fromList\n      . HU.toColumns\n      . H.extract\n\n-- | Join together a /vector-sized/ boxed vector of /hmatrix/ vectors to an\n-- /hmatrix/ matrix as its columns.\n--\n-- /O(m*n)/\ncolsL\n    :: forall m n. KnownNat m\n    => V.Vector n (H.R m)\n    -> H.L m n\ncolsL = (unsafeCoerce :: HU.Matrix Double -> H.L m n)\n      . HU.fromColumns\n      . map H.extract\n      . toList\n\n-- | Split an /hmatrix/ complex matrix (parameterized by its dimensions) to\n-- a /vector-sized/ boxed vector of its rows (as /hmatrix/ complex\n-- vectors).\n--\n-- This is normally /O(m*n)/, but can sometimes be /O(m)/ depending on the\n-- representation of the 'H.C' being used.\nmRows\n    :: forall m n. (KnownNat m, KnownNat n)\n    => H.M m n\n    -> V.Vector m (H.C n)\nmRows = unsafeCoerce\n      . UV.fromList\n      . HU.toRows\n      . H.extract\n\n-- | Join together a /vector-sized/ boxed vector of /hmatrix/ complex\n-- vectors to an /hmatrix/ complex matrix as its rows.\n--\n-- /O(m*n)/\nrowsM\n    :: forall m n. KnownNat n\n    => V.Vector m (H.C n)\n    -> H.M m n\nrowsM = (unsafeCoerce :: HU.Matrix H.\u2102 -> H.M m n)\n      . HU.fromRows\n      . map H.extract\n      . toList\n\n-- | Split an /hmatrix/ complex matrix (parameterized by its dimensions) to\n-- a /vector-sized/ boxed vector of its columns (as /hmatrix/ complex\n-- vectors).\n--\n-- This is normally /O(m*n)/, but can sometimes be /O(n)/ depending on the\n-- representation of the 'H.C' being used.\nmCols\n    :: forall m n. (KnownNat m, KnownNat n)\n    => H.M m n\n    -> V.Vector n (H.C m)\nmCols = unsafeCoerce\n      . UV.fromList\n      . HU.toColumns\n      . H.extract\n\n-- | Join together a /vector-sized/ boxed vector of /hmatrix/ complex\n-- vectors to an /hmatrix/ complex matrix as its columns.\n--\n-- /O(m*n)/\ncolsM\n    :: forall m n. KnownNat m\n    => V.Vector n (H.C m)\n    -> H.M m n\ncolsM = (unsafeCoerce :: HU.Matrix H.\u2102 -> H.M m n)\n      . HU.fromColumns\n      . map H.extract\n      . toList\n\n-- | Shape a /vector-sized/ storable vector of elements into an /hmatrix/\n-- matrix.\n--\n-- /O(1)/\n--\n-- @since 0.1.1.0\nvecL\n    :: forall m n. KnownNat n\n    => VS.Vector (m * n) H.\u211d\n    -> H.L m n\nvecL = (unsafeCoerce :: HU.Matrix H.\u211d -> H.L m n)\n     . HU.reshape (fromIntegral (natVal (Proxy @n)))\n     . unsafeCoerce\n\n-- | 'vecL', but generalized to work for all types of sized vectors.\n--\n-- Usually /O(n)/, but if using this with storable vectors, should be /O(1)/\n-- due to rewrite rules (but don't rely on this).\n--\n-- @since 0.1.3.0\ngvecL\n    :: (KnownNat n, UVG.Vector v H.\u211d)\n    => VG.Vector v (m * n) H.\u211d\n    -> H.L m n\ngvecL = vecL . VG.convert\n{-# NOINLINE[1] gvecL #-}\n{-# RULES \"gvecL\" gvecL = vecL #-}\n\n-- | Flatten an /hmatrix/ matrix into a /vector-sized/ storable vector of\n-- its items.\n--\n-- This is normally /O(m*n)/, but can sometimes be /O(1)/ depending on the\n-- representation of the 'H.L' being used.\n--\n-- @since 0.1.1.0\nlVec\n    :: forall m n. (KnownNat m, KnownNat n)\n    => H.L m n\n    -> VS.Vector (m * n) H.\u211d\nlVec = unsafeCoerce\n     . HU.flatten\n     . H.extract\n\n-- | 'lVec', but generalized to work for all types of sized vectors.\n--\n-- Usually /O(m*n)/, but if using this with storable vectors, should have the\n-- same characteristics as 'lVec' due to rewrite rules.\n--\n-- @since 0.1.3.0\nglVec\n    :: (KnownNat m, KnownNat n, UVG.Vector v H.\u211d)\n    => H.L m n\n    -> VG.Vector v (m * n) H.\u211d\nglVec = VG.convert . lVec\n{-# NOINLINE[1] glVec #-}\n{-# RULES \"glVec\" glVec = lVec #-}\n\n-- | Shape a /vector-sized/ storable vector of elements into an /hmatrix/\n-- complex matrix.\n--\n-- /O(1)/\n--\n-- @since 0.1.1.0\nvecM\n    :: forall m n. KnownNat n\n    => VS.Vector (m * n) H.\u2102\n    -> H.M m n\nvecM = (unsafeCoerce :: HU.Matrix H.\u2102 -> H.M m n)\n     . HU.reshape (fromIntegral (natVal (Proxy @n)))\n     . unsafeCoerce\n\n-- | 'vecM', but generalized to work for all types of sized vectors.\n--\n-- Usually /O(m*n)/, but if using this with storable vectors, should be /O(1)/\n-- due to rewrite rules (but don't rely on this).\n--\n-- @since 0.1.3.0\ngvecM\n    :: (KnownNat n, UVG.Vector v H.\u2102)\n    => VG.Vector v (m * n) H.\u2102\n    -> H.M m n\ngvecM = vecM . VG.convert\n{-# NOINLINE[1] gvecM #-}\n{-# RULES \"gvecM\" gvecM = vecM #-}\n\n-- | Flatten an /hmatrix/ complex matrix into a /vector-sized/ storable\n-- vector of its items.\n--\n-- This is normally /O(m*n)/, but can sometimes be /O(1)/ depending on the\n-- representation of the 'H.M' being used.\n--\n-- @since 0.1.1.0\nmVec\n    :: forall m n. (KnownNat m, KnownNat n)\n    => H.M m n\n    -> VS.Vector (m * n) H.\u2102\nmVec = unsafeCoerce\n     . HU.flatten\n     . H.extract\n\n-- | 'mVec', but generalized to work for all types of sized vectors.\n--\n-- Usually /O(m*n)/, but if using this with storable vectors, should have the\n-- same characteristics as 'mVec' due to rewrite rules.\n--\n-- @since 0.1.3.0\ngmVec\n    :: (KnownNat m, KnownNat n, UVG.Vector v H.\u2102)\n    => H.M m n\n    -> VG.Vector v (m * n) H.\u2102\ngmVec = VG.convert . mVec\n{-# NOINLINE[1] gmVec #-}\n{-# RULES \"gmVec\" gmVec = mVec #-}\n", "meta": {"hexsha": "71a1c751442bd14f66f83742c4fc3de743f72e00", "size": 10546, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Static/Vector.hs", "max_stars_repo_name": "mstksg/hmatrix-vector-sized", "max_stars_repo_head_hexsha": "9be24f91c72f5b3eb1b5a98d086a5f7fdea30980", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T07:50:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:50:31.000Z", "max_issues_repo_path": "src/Numeric/LinearAlgebra/Static/Vector.hs", "max_issues_repo_name": "mstksg/hmatrix-vector-sized", "max_issues_repo_head_hexsha": "9be24f91c72f5b3eb1b5a98d086a5f7fdea30980", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/Static/Vector.hs", "max_forks_repo_name": "mstksg/hmatrix-vector-sized", "max_forks_repo_head_hexsha": "9be24f91c72f5b3eb1b5a98d086a5f7fdea30980", "max_forks_repo_licenses": ["BSD-3-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.1226666667, "max_line_length": 78, "alphanum_fraction": 0.6242177129, "num_tokens": 3385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.44899656449855463}}
{"text": "module Noether.Algebra.Actions.Compatible where\n\nimport           Data.Complex\n\nimport           Noether.Lemmata.Prelude\nimport           Noether.Lemmata.TypeFu\n\nimport           Noether.Algebra.Single\nimport           Noether.Algebra.Tags\n\nimport           Noether.Algebra.Actions.Acts\n\n\n{-| A strategy-parameterized typeclass for a compatible action, where compatibility\n    is defined in the group action sense.\n\n    A compatible action satisfies\n    a `act` (a' `act` b) = (a `op` a') `act` b\n-}\n\nclass CompatibleK (lr :: Side) (op :: k1) (act :: k2) a b (s :: CompatibleE)\n\ndata CompatibleE = Compatible_Acts_Semigroup\n  { compatible_actor           :: Type\n  , compatible_action          :: ActsE\n  , compatible_actor_semigroup :: SemigroupE\n  }\n\ntype family CompatibleS (lr :: Side) (op :: k1) (act :: k2) (a :: Type) (b :: Type) = (r :: CompatibleE)\n\ninstance (ActsK lr act a b za, SemigroupK op a zs) =>\n         CompatibleK lr op act a b (Compatible_Acts_Semigroup a za zs)\n", "meta": {"hexsha": "2790b6649a738a7446a77d0ed85354f2f4b3542c", "size": 984, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "library/Noether/Algebra/Actions/Compatible.hs", "max_stars_repo_name": "evertedsphere/noether", "max_stars_repo_head_hexsha": "c4223f64b9df5b0dbbeec1fea726bfff7f5810f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "library/Noether/Algebra/Actions/Compatible.hs", "max_issues_repo_name": "evertedsphere/noether", "max_issues_repo_head_hexsha": "c4223f64b9df5b0dbbeec1fea726bfff7f5810f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "library/Noether/Algebra/Actions/Compatible.hs", "max_forks_repo_name": "evertedsphere/noether", "max_forks_repo_head_hexsha": "c4223f64b9df5b0dbbeec1fea726bfff7f5810f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8181818182, "max_line_length": 104, "alphanum_fraction": 0.6534552846, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4489126742804637}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n-- |\n-- Module      : PSO.NeuralSpec\n-- Description : Tests for PSO.Neural\n-- Copyright   : (c) Tom Westerhout, 2017\n-- License     : BSD3\n-- Maintainer  : t.westerhout@student.ru.nl\n-- Stability   : experimental\n\nmodule PSO.NeuralSpec where\n\nimport           Control.Monad\nimport           Control.Monad.ST\nimport           Control.Monad.Reader\nimport           Data.Complex\nimport qualified Data.Vector.Storable as V\nimport           Foreign.Storable\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Numeric.LinearAlgebra.Devel as LA.Devel\n\nimport           Test.Hspec\n\nimport           PSO.Random\nimport           PSO.Neural\n\n\n\nmain :: IO ()\nmain = hspec spec\n\nroundTo :: (RealFrac a) => Int -> a -> a\nroundTo n x = (fromInteger . round $ x * (10^n)) / (10.0^^n)\n\nroundToC :: (RealFrac a) => Int -> Complex a -> Complex a\nroundToC n (x :+ y) = (roundTo n x) :+ (roundTo n y)\n\n\nclass AlmostEq a where\n  eq' :: a -> a -> Bool\n\ninstance AlmostEq Float where\n  eq' x y = let epsilon = 1.0E-5\n             in abs (x - y) <= epsilon * max (abs x) (abs y)\n\ninstance AlmostEq a => AlmostEq (Complex a) where\n  eq' (xr :+ xi) (yr :+ yi) = xr `eq'` yr && xi `eq'` yi\n\ninstance (Storable a, AlmostEq a) => AlmostEq (V.Vector a) where\n  eq' x y = V.and $ V.zipWith eq' x y\n\n\ntoW n m w = LA.Devel.matrixFromVector LA.Devel.ColumnMajor m n w\n\nmkTheta a b w' \u03c3 = b + (toW (V.length a) (V.length b) w') LA.#> \u03c3\n\nlogWF' :: (Storable a, RealFloat a, Num (V.Vector (Complex a)), LA.Numeric (Complex a))\n       => V.Vector (Complex a)\n       -> V.Vector (Complex a)\n       -> V.Vector (Complex a)\n       -> V.Vector (Complex a)\n       -> Complex a\nlogWF' a b w' \u03c3 =\n  let n = V.length a\n      m = V.length b\n      \u03b8 = mkTheta a b w' \u03c3\n   in V.sum (V.zipWith (*) a \u03c3) + V.sum (V.map (log . cosh) \u03b8)\n\nlogQuotient1' ::\n     (Storable a, RealFloat a, Num (V.Vector (Complex a)), LA.Numeric (Complex a))\n  => V.Vector (Complex a)\n  -> V.Vector (Complex a)\n  -> V.Vector (Complex a)\n  -> V.Vector (Complex a)\n  -> Int -> Complex a\nlogQuotient1' a b w' \u03c3 flip =\n  let \u03c3' = \u03c3 V.// [(flip, (-1) * (\u03c3 V.! flip))]\n   in logWF' a b w' \u03c3' - logWF' a b w' \u03c3\n\nlogQuotient2' ::\n     (Storable a, RealFloat a, Num (V.Vector (Complex a)), LA.Numeric (Complex a))\n  => V.Vector (Complex a)\n  -> V.Vector (Complex a)\n  -> V.Vector (Complex a)\n  -> V.Vector (Complex a)\n  -> Int -> Int -> Complex a\nlogQuotient2' a b w' \u03c3 flip1 flip2 =\n  let \u03c3' = \u03c3 V.// [ (flip1, (-1) * (\u03c3 V.! flip1))\n                  , (flip2, (-1) * (\u03c3 V.! flip2)) ]\n   in logWF' a b w' \u03c3' - logWF' a b w' \u03c3\n\nlocEnergyHH1DOpen' ::\n     (Storable \u03b1, RealFloat \u03b1, Eq \u03b1, Num (V.Vector (Complex \u03b1)), LA.Numeric (Complex \u03b1))\n  => V.Vector (Complex \u03b1)\n  -> V.Vector (Complex \u03b1)\n  -> V.Vector (Complex \u03b1)\n  -> V.Vector (Complex \u03b1)\n  -> Complex \u03b1\nlocEnergyHH1DOpen' a b w' \u03c3 =\n  let zipper i x y\n        | x == y    = 1\n        | otherwise = -1 + 2 * exp (logQuotient2' a b w' \u03c3 i (i + 1))\n   in V.sum $ V.izipWith zipper \u03c3 (V.tail \u03c3)\n\na1 = V.fromList [   3.7e-01  :+   1.5e-01\n                ,   6.5e-01  :+   3.0e-01\n                , (-2.8e-01) :+ (-3.0e-01)\n                ] :: V.Vector (Complex Float)\n\nra1 :: UniformDist m (Complex Float) => m (V.Vector (Complex Float))\nra1 = uniformVector 10 ((-1.0) :+ (-1.0), 1.0 :+ 1.0)\n\nb1 = V.fromList [   6.0e-01  :+   8.4e-02\n                , (-2.6e-01) :+   9.2e-01\n                ,   5.5e-01  :+ (-8.2e-02)\n                ,   4.3e-01  :+   3.7e-01\n                ,   9.3e-01  :+   5.1e-01\n                ,   6.0e-02  :+   8.9e-01\n                ] :: V.Vector (Complex Float)\n\nrb1 :: UniformDist m (Complex Float) => m (V.Vector (Complex Float))\nrb1 = uniformVector 20 ((-1.0) :+ (-1.0), 1.0 :+ 1.0)\n\nw1 = V.fromList $\n      [   0.22 :+ (-0.93),   (-0.16) :+ (-0.47), (-0.57) :+ (-0.83),   (-0.16) :+ 0.86,    (-0.44) :+ 0.16,       0.43 :+ 0.96\n      , (-3.6e-2) :+ 0.36, (-1.5e-2) :+ (-0.14),    (-0.15) :+ 0.57,   0.79 :+ (-0.26),     0.95 :+ (-0.6),       0.56 :+ 0.98\n      ,      0.82 :+ 0.34,      0.85 :+ (-0.35),    0.64 :+ (-0.24), (-0.73) :+ (-0.8), (-0.34) :+ (-0.24), (-0.94) :+ (-0.46)\n      ] :: V.Vector (Complex Float)\n\nrw1 :: UniformDist m (Complex Float) => m (V.Vector (Complex Float))\nrw1 = uniformVector (10 * 20) ((-1.0) :+ (-1.0), 1.0 :+ 1.0)\n\n\u03c31  = V.fromList [ -1, -1, -1 ] :: V.Vector (Complex Float)\n\u03c32  = V.fromList [ 1,   1,  1 ] :: V.Vector (Complex Float)\n\u03c33  = V.fromList [ 1,  -1,  1 ] :: V.Vector (Complex Float)\n\nr\u03c31 :: Randomisable m Bool => m (V.Vector (Complex Float))\nr\u03c31 = randomSpin 10\n\nrbm1  = runST $ mkRbm a1 b1 w1\n\nmcmc1 = runST $ newMcmc rbm1 \u03c31 >>= unsafeFreezeMcmc\nmcmc2 = runST $ newMcmc rbm1 \u03c32 >>= unsafeFreezeMcmc\nmcmc3 = runST $ newMcmc rbm1 \u03c33 >>= unsafeFreezeMcmc\n\n\nspec :: Spec\nspec = do\n  describe \"mkRbm\" $ do\n    it \"Constructs a new RBM given a, b, and w\" $\n      debugPrintRbm rbm1\n  describe \"newMcmc\" $ do\n    it \"Constructs a new MCMC given RBM and \u03c3\" $\n      do debugPrintMcmc mcmc1\n         print $ (b1 + (toW 3 6 w1) LA.#> \u03c31)\n  describe \"logWF\" $ do\n    it \"1) Calculates ln(\u03c8(S)) \" $\n      do putStrLn $ \"logWF:  \" ++ show (logWF mcmc1)\n         putStrLn $ \"logWF': \" ++ show (logWF' a1 b1 w1 \u03c31)\n    it \"2) Calculates ln(\u03c8(S)) \" $\n      do putStrLn $ \"logWF:  \" ++ show (logWF mcmc2)\n         putStrLn $ \"logWF': \" ++ show (logWF' a1 b1 w1 \u03c32)\n    it \"3) Calculates ln(\u03c8(S)) \" $\n      do putStrLn $ \"logWF:  \" ++ show (logWF mcmc3)\n         putStrLn $ \"logWF': \" ++ show (logWF' a1 b1 w1 \u03c33)\n  describe \"logQuotient1\" $ do\n    it \"1) Calculates ln(\u03c8(S')/\u03c8(S))\" $\n      do putStrLn $ \"logQuotient1:  \" ++ show (logQuotient1 mcmc1 0)\n         putStrLn $ \"logQuotient1': \" ++ show (logQuotient1' a1 b1 w1 \u03c31 0)\n    it \"2) Calculates ln(\u03c8(S')/\u03c8(S))\" $\n      do putStrLn $ \"logQuotient1:  \" ++ show (logQuotient1 mcmc1 1)\n         putStrLn $ \"logQuotient1': \" ++ show (logQuotient1' a1 b1 w1 \u03c31 1)\n    it \"3) Calculates ln(\u03c8(S')/\u03c8(S))\" $\n      do putStrLn $ \"logQuotient1:  \" ++ show (logQuotient1 mcmc1 2)\n         putStrLn $ \"logQuotient1': \" ++ show (logQuotient1' a1 b1 w1 \u03c31 2)\n    it \"4) Calculates ln(\u03c8(S')/\u03c8(S))\" $\n      do putStrLn $ \"logQuotient1:  \" ++ show (logQuotient1 mcmc2 0)\n         putStrLn $ \"logQuotient1': \" ++ show (logQuotient1' a1 b1 w1 \u03c32 0)\n    it \"5) Calculates ln(\u03c8(S')/\u03c8(S))\" $\n      do putStrLn $ \"logQuotient1:  \" ++ show (logQuotient1 mcmc2 2)\n         putStrLn $ \"logQuotient1': \" ++ show (logQuotient1' a1 b1 w1 \u03c32 2)\n  describe \"logQuotient2\" $ do\n    it \"1) Calculates ln(\u03c8(S')/\u03c8(S))\" $\n      do putStrLn $ \"logQuotient2:  \" ++ show (logQuotient2 mcmc1 0 1)\n         putStrLn $ \"logQuotient2': \" ++ show (logQuotient2' a1 b1 w1 \u03c31 0 1)\n    it \"2) Calculates ln(\u03c8(S')/\u03c8(S))\" $\n      do putStrLn $ \"logQuotient2:  \" ++ show (logQuotient2 mcmc1 0 2)\n         putStrLn $ \"logQuotient2': \" ++ show (logQuotient2' a1 b1 w1 \u03c31 0 2)\n  describe \"locEnergyHH1DOpen'\" $ do\n    it \"1) Calculates Eloc(\u03c8)\" $\n      do putStrLn $ \"locEnergyHH1DOpen:  \" ++ show (locEnergyHH1DOpen mcmc3)\n         putStrLn $ \"locEnergyHH1DOpen': \" ++ show (locEnergyHH1DOpen' a1 b1 w1 \u03c33)\n  describe \"Random!\" $ do\n    it \"1) Calculates Eloc(\u03c8)\" $\n      do let job = do\n               a <- ra1\n               b <- rb1\n               w <- rw1\n               \u03c3 <- r\u03c31\n               rbm <- mkRbm a b w\n               mcmc <- newMcmc rbm \u03c3 >>= unsafeFreezeMcmc\n               lift $ putStrLn\n                    $ \"locEnergyHH1DOpen:  \" ++ show (locEnergyHH1DOpen mcmc)\n               lift $ putStrLn\n                    $ \"locEnergyHH1DOpen': \" ++ show (locEnergyHH1DOpen' a b w \u03c3)\n         runReaderT job =<< mkMWCGen (Just 135)\n         runReaderT job =<< mkMWCGen (Just 136)\n         runReaderT job =<< mkMWCGen (Just 137)\n", "meta": {"hexsha": "a10c677406223bdea063257ea4071b9c6ec34ae0", "size": 7723, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/PSO/NeuralSpec.hs", "max_stars_repo_name": "twesterhout/tcm-swarm", "max_stars_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/PSO/NeuralSpec.hs", "max_issues_repo_name": "twesterhout/tcm-swarm", "max_issues_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/PSO/NeuralSpec.hs", "max_forks_repo_name": "twesterhout/tcm-swarm", "max_forks_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1298076923, "max_line_length": 126, "alphanum_fraction": 0.5451249514, "num_tokens": 2942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4489126742804637}}
{"text": "module Budget.Budgeter(\n  budgeter\n  )where\n\nimport Numeric.LinearAlgebra\nimport Budget.Types\nimport Budget.Parse\nimport Budget.Printer\nimport Text.Parsec\nimport Finance.FutureValue\n\ngetNeededExpense :: BudgetItem -> Expense\ngetNeededExpense bs = case needed bs of\n  True -> Expense (name bs) (minPrice bs)\n  False -> Expense (name bs) 0.0\n\nreduceBs :: [BudgetItem] -> [Expense] -> [BudgetItem]\nreduceBs bs xs = map removeMin $ zip bs xs\n\nremoveMin :: (BudgetItem, Expense) -> BudgetItem\nremoveMin ((BudgetItem s i l h n), Expense _ m) = BudgetItem s i (l-m) (h-m) n\n\naDiag :: BudgetItem -> Double\naDiag (BudgetItem _ i low high _)\n  | low == high = 100000\n  | otherwise = (-2.0) * i * k**2\n  where k = 1.0 / (high-low)\n\naDiags :: [BudgetItem] -> [Double]\naDiags = map aDiag\n\ntype CurrentIndex = Integer\ntype Rank = Integer\naList :: CurrentIndex -> Rank -> [Double] -> [Double]\naList c r (x:xs)\n  |c `mod` (r+1) == 0 = x : aList (c+1) r xs\naList c r xs\n  | c == r^2-1 = [0]\n  | ((c+1) `mod` r == 0) && (c /= r^2-1) = -1 : aList (c+1) r xs\n  | (c `mod` (r+1) /= 0 && c >= r^2-r) = 1 : aList (c+1) r xs\n  | otherwise = 0 : aList (c+1) r xs\n\navailableCosts :: Double -> Double -> Double -> Double -> Double -> Double\navailableCosts cpm y v ipm apr\n  | cpm <= 0 = 0\n  | retirement > sustainableRetirement = cpm\n  | otherwise = availableCosts (cpm-10) y v ipm apr\n  where retirement = futureValue numberMonths v (ipm-cpm) ratePerMonth\n        sustainableRetirement = costsPerYear / apr\n        numberMonths = floor (12 * y)\n        ratePerMonth = apr/12\n        costsPerYear = cpm * 12\n\naMatrix :: [BudgetItem] -> Matrix Double\naMatrix bs = let as = aDiags bs\n                 r = (length as) + 1\n             in (r><r) $ aList 0 (toInteger r) as\n\nbElem :: BudgetItem -> Double\nbElem (BudgetItem _ i low high _)\n  | low == high = 100000\n  | otherwise = (-2.0) * i * k**2 * high\n  where k = 1.0 / (high-low)\n\nbElems :: [BudgetItem] -> [Double]\nbElems = map bElem\n\ntype TotalCost = Double\nbVector :: [BudgetItem] -> TotalCost -> Vector Double\nbVector bs tc = let vecElems = bElems bs ++ [tc]\n                in vector vecElems\n\nremoveNeeded :: BudgetInfo -> (BudgetInfo, [Expense])\nremoveNeeded (BudgetInfo i s y a bs) = (BudgetInfo (i - totalNeeded) s y a newBs, needs)\n  where needs = map getNeededExpense bs\n        newBs = reduceBs bs needs\n        totalNeeded = sum [x | (Expense _ x) <- needs]\n\ntype ItemNames = [String]\ncalculateBudget :: BudgetInfo -> [Expense]\ncalculateBudget (BudgetInfo i s y a bs)\n  | i > totalMaxCosts = expenses\n  | otherwise = calculateBudget' [] (BudgetInfo i s y a bs)\n  where maxCosts = map maxPrice bs\n        names = map name bs\n        expenses = [Expense n m | (n, m) <- zip names maxCosts]\n        totalMaxCosts = sum maxCosts\n\ninefficientNames :: [BudgetItem] -> Costs -> ItemNames\ninefficientNames bs costs  = [(name b)| (b,c) <- (zip bs costs), c < 0]\n\noptimizedCosts :: Double -> [BudgetItem] -> [Double]\noptimizedCosts i bs = init $ toList $ (aMatrix bs) <\\> (bVector bs (realToFrac i))\n\ncalculateBudget' :: ItemNames -> BudgetInfo -> [Expense]\ncalculateBudget' unusedItems (BudgetInfo i s y a bs)\n  | validCosts = expenses\n  | otherwise = calculateBudget' newUnusedNames cleanedBI\n  where costs = optimizedCosts i bs\n        validCosts = length [c | c <- costs, c < 0] == 0\n        allNames = (map name bs) ++ unusedItems\n        newUnusedNames = unusedItems ++ inefficientNames bs costs\n        cleanedBI = BudgetInfo i s y a [b | (b,c) <- (zip bs costs), c > 0]\n        appendedCosts = costs ++ (replicate ((length allNames) - (length costs)) 0)\n        expenses = [Expense n m | (n, m) <- zip allNames appendedCosts]\n\nstoreSavings (BudgetInfo ipm v ytr apr bs) = BudgetInfo cpm v ytr apr bs\n  where cpm = availableCosts ipm ytr v ipm apr\n\nunsafe :: Either ParseError BudgetInfo -> BudgetInfo\nunsafe (Right x) = x\n\nyearlySavings (BudgetInfo ipm _ _ _ _) cs = ipm - (sum cs)\n\ncombineExpenses :: [Expense] -> [Expense] -> [Expense]\ncombineExpenses e1s e2s = [Expense n1 (cost1 + cost2) | (Expense n1 cost1) <- e1s, (Expense n2 cost2) <- e2s,\n                           n1 == n2]\n\ngetBudget :: BudgetInfo -> String\ngetBudget bi = let saved_bi = storeSavings bi\n                   (available_bi, mandatory_costs) = removeNeeded saved_bi\n                   distro = calculateBudget available_bi\n                   finalExpenses = combineExpenses mandatory_costs distro\n               in fullPrint bi finalExpenses\n\nbudgeter :: String -> String\nbudgeter s = let bi = parse getBudgetInfo \"Fetching budget info\" s\n             in case fmap getBudget bi of\n                Left parsecError -> \"Encountered Input Parsing errror:\\n\" ++ show parsecError\n                Right finalString -> finalString\n", "meta": {"hexsha": "23311f249c0e69f167db007c318503a7548f5124", "size": 4732, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Budget/Budgeter.hs", "max_stars_repo_name": "PotentialParadox/budgeter", "max_stars_repo_head_hexsha": "40bea44f5e5ca4b58a661ff1f61e418c5b0e59b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Budget/Budgeter.hs", "max_issues_repo_name": "PotentialParadox/budgeter", "max_issues_repo_head_hexsha": "40bea44f5e5ca4b58a661ff1f61e418c5b0e59b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Budget/Budgeter.hs", "max_forks_repo_name": "PotentialParadox/budgeter", "max_forks_repo_head_hexsha": "40bea44f5e5ca4b58a661ff1f61e418c5b0e59b3", "max_forks_repo_licenses": ["BSD-3-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.1221374046, "max_line_length": 109, "alphanum_fraction": 0.6418005072, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.44889729016540675}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections       #-}\n{-# LANGUAGE TypeFamilies        #-}\n{-# LANGUAGE TypeOperators       #-}\n\nimport           Control.Applicative\nimport           Control.DeepSeq\nimport           Control.Monad\nimport           Control.Monad.Random\nimport           Control.Monad.Trans.Except\n\nimport qualified Data.Attoparsec.Text         as A\nimport           Data.List                    (foldl')\nimport qualified Data.Text                    as T\nimport qualified Data.Text.IO                 as T\nimport qualified Data.Vector.Storable         as V\n\nimport           Numeric.LinearAlgebra        (maxIndex)\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport           Options.Applicative\n\nimport           Grenade\nimport           Grenade.Utils.OneHot\n\n--\n-- Note: Input files can be downloaded at https://www.kaggle.com/scolianni/mnistasjpg\n--\n\n\n-- It's logistic regression!\n--\n-- This network is used to show how we can embed a Network as a layer in the larger MNIST\n-- type.\ntype FL i o =\n  Network\n    '[ FullyConnected i o, Logit ]\n    '[ 'D1 i, 'D1 o, 'D1 o ]\n\n-- The definition of our convolutional neural network.\n-- In the type signature, we have a type level list of shapes which are passed between the layers.\n-- One can see that the images we are inputing are two dimensional with 28 * 28 pixels.\n\n-- It's important to keep the type signatures, as there's many layers which can \"squeeze\" into the gaps\n-- between the shapes, so inference can't do it all for us.\n\n-- With the mnist data from Kaggle normalised to doubles between 0 and 1, learning rate of 0.01 and 15 iterations,\n-- this network should get down to about a 1.3% error rate.\n--\n-- /NOTE:/ This model is actually too complex for MNIST, and one should use the type given in the readme instead.\n--         This one is just here to demonstrate Inception layers in use.\n--\ntype MNIST =\n  Network\n    '[ Reshape,\n       Concat ('D3 28 28 1) Trivial ('D3 28 28 14) (InceptionMini 28 28 1 5 9),\n       Pooling 2 2 2 2, Relu,\n       Concat ('D3 14 14 3) (Convolution 15 3 1 1 1 1) ('D3 14 14 15) (InceptionMini 14 14 15 5 10), Crop 1 1 1 1, Pooling 3 3 3 3, Relu,\n       Reshape, FL 288 80, FL 80 10 ]\n    '[ 'D2 28 28, 'D3 28 28 1,\n       'D3 28 28 15, 'D3 14 14 15, 'D3 14 14 15, 'D3 14 14 18,\n       'D3 12 12 18, 'D3 4 4 18, 'D3 4 4 18,\n       'D1 288, 'D1 80, 'D1 10 ]\n\nrandomMnist :: IO MNIST\nrandomMnist = randomNetwork\n\nconvTest :: Int -> FilePath -> FilePath -> Optimizer opt -> ExceptT String IO ()\nconvTest iterations trainFile validateFile opt = do\n  net0         <- lift randomMnist\n  trainData    <- readMNIST trainFile\n  validateData <- readMNIST validateFile\n  lift $ foldM_ (runIteration trainData validateData) net0 [1..iterations]\n\n    where\n  trainEach !opt' !network (!i, !o) = force (train opt' network i o)\n\n  runIteration !trainRows !validateRows !net !i = do\n    putStrLn $ \"Number of training rows: \" ++ show (length trainRows)\n    let !trained' = foldl' (trainEach (sgdUpdateLearningParamters opt)) net trainRows\n    let !res      = fmap (\\(rowP,rowL) -> (rowL,) $ runNet trained' rowP) validateRows\n    let !res'     = fmap (\\(S1D label, S1D prediction) -> (maxIndex (SA.extract label), maxIndex (SA.extract prediction))) res\n    print trained'\n    putStrLn $ \"Iteration \" ++ show i ++ \": \" ++ show (length (filter ((==) <$> fst <*> snd) res')) ++ \" of \" ++ show (length res')\n    return trained'\n  sgdUpdateLearningParamters :: Optimizer opt -> Optimizer opt\n  sgdUpdateLearningParamters (OptSGD rate mom reg) = OptSGD rate mom (reg * 10)\n  sgdUpdateLearningParamters o                     = o\n\n\ndata MnistOpts = MnistOpts FilePath FilePath Int Bool (Optimizer 'SGD) (Optimizer 'Adam)\n\nmnist' :: Parser MnistOpts\nmnist' = MnistOpts <$> argument str (metavar \"TRAIN\")\n                   <*> argument str (metavar \"VALIDATE\")\n                   <*> option auto (long \"iterations\" <> short 'i' <> value 15)\n                 <*> flag False True (long \"use-adam\" <> short 'a')\n                 <*> (OptSGD\n                       <$> option auto (long \"train_rate\" <> short 'r' <> value 0.01)\n                       <*> option auto (long \"momentum\" <> value 0.9)\n                       <*> option auto (long \"l2\" <> value 0.0005)\n                       )\n                 <*> (OptAdam\n                       <$> option auto (long \"alpha\" <> short 'r' <> value 0.001)\n                       <*> option auto (long \"beta1\" <> value 0.9)\n                       <*> option auto (long \"beta2\" <> value 0.999)\n                       <*> option auto (long \"epsilon\" <> value 1e-4)\n                       <*> option auto (long \"lambda\" <> value 1e-3)\n                      )\n\nmain :: IO ()\nmain = do\n    MnistOpts mnist vali iter useAdam sgd adam <- execParser (info (mnist' <**> helper) idm)\n    putStrLn \"Training convolutional neural network...\"\n    res <- if useAdam\n      then runExceptT $ convTest iter mnist vali adam\n      else runExceptT $ convTest iter mnist vali sgd\n\n    case res of\n      Right () -> pure ()\n      Left err -> putStrLn err\n\nreadMNIST :: FilePath -> ExceptT String IO [(S ('D2 28 28), S ('D1 10))]\nreadMNIST mnist = ExceptT $ do\n  mnistdata <- T.readFile mnist\n  return $ traverse (A.parseOnly parseMNIST) (tail $ T.lines mnistdata)\n\nparseMNIST :: A.Parser (S ('D2 28 28), S ('D1 10))\nparseMNIST = do\n  Just lab <- oneHot <$> A.decimal\n  pixels   <- many (A.char ',' >> A.double)\n  image    <- maybe (fail \"Parsed row was of an incorrect size\") pure (fromStorable . V.fromList $ map realToFrac pixels)\n  return (image, lab)\n", "meta": {"hexsha": "fb2af71c51d12e70fdeb0ba9397ba04cd13407d2", "size": 5732, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/mnist.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": "examples/main/mnist.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": "examples/main/mnist.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": 41.5362318841, "max_line_length": 137, "alphanum_fraction": 0.6083391486, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4488870671879591}}
{"text": "module Main\n    ( main\n    ) where\n\n\n-------------------------------------------------------------------------------\nimport           Criterion\nimport           Criterion.Main\nimport           Data.Foldable\n-------------------------------------------------------------------------------\nimport           Statistics.RollingAverage\n-------------------------------------------------------------------------------\n\n\nmain :: IO ()\nmain = defaultMain [\n  bgroup \"ravgAdd\" $ flip map [1, 100, 1000] $ \\n ->\n    bgroup (show n) [\n        bench \"Int\" $ whnf (avgList n) ([1..fromIntegral n] :: [Int])\n      , bench \"Integer\" $ whnf (avgList n) ([1..fromIntegral n] :: [Integer])\n      ]\n  , bgroup \"ravg\" $ flip map [1, 100, 1000] $ \\n ->\n      bgroup (show n) [\n          bench \"Int\" $ whnf ravg' (avgList n ([1..fromIntegral n] :: [Int]))\n        , bench \"Integer\" $ whnf ravg' (avgList n ([1..fromIntegral n] :: [Integer]))\n      ]\n  ]\n\n\n-------------------------------------------------------------------------------\navgList :: Num a => Int -> [a] -> RollingAvg a\navgList lim = foldl' ravgAdd (mkRavg lim)\n\n\n-------------------------------------------------------------------------------\nravg' :: (Integral a) => RollingAvg a -> Double\nravg' = ravg\n", "meta": {"hexsha": "d2dc6ee95a0acf3b2d19bad2d6c8039d06ae0675", "size": 1244, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/Main.hs", "max_stars_repo_name": "Soostone/rolling-average", "max_stars_repo_head_hexsha": "939dfdfde84c4cdb4e292458ade43be80240ec18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-07T00:56:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-07T00:56:32.000Z", "max_issues_repo_path": "bench/Main.hs", "max_issues_repo_name": "Soostone/rolling-average", "max_issues_repo_head_hexsha": "939dfdfde84c4cdb4e292458ade43be80240ec18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/Main.hs", "max_forks_repo_name": "Soostone/rolling-average", "max_forks_repo_head_hexsha": "939dfdfde84c4cdb4e292458ade43be80240ec18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7368421053, "max_line_length": 85, "alphanum_fraction": 0.3745980707, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.44869224235349775}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n\nimport Control.Applicative ((<$>))\nimport Statistics.Sample.KernelDensity (kde)\nimport Text.Hastache (MuType(..), defaultConfig, hastacheFile)\nimport Text.Hastache.Context (mkStrContext)\nimport qualified Data.Attoparsec as B\nimport qualified Data.Attoparsec.Char8 as A\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport qualified Data.Vector.Unboxed as U\n\ncsv = do\n  B.takeTill A.isEndOfLine\n  (A.double `A.sepBy` A.char ',') `A.sepBy` A.endOfLine\n\nmain = do\n  waits <- (either error (U.fromList . map last . filter (not.null)) .\n            A.parseOnly csv) <$> B.readFile \"data/faithful.csv\"\n  let xs = map (\\(a,b) -> [a,b]) . U.toList . uncurry U.zip . kde 64 $ waits\n      context \"data\" = MuVariable . show $ xs\n  s <- hastacheFile defaultConfig \"kde.tpl\" (mkStrContext context)\n  L.writeFile \"kde.html\" s\n", "meta": {"hexsha": "a9640b954770d92a0faa1f0cd3a17cac850b8695", "size": 884, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/kde/KDE.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": "examples/kde/KDE.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": "examples/kde/KDE.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.8333333333, "max_line_length": 76, "alphanum_fraction": 0.7115384615, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.44853555125625855}}
{"text": "{-# LANGUAGE ConstraintKinds, PolyKinds, TypeFamilies #-}\n{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}\n\nmodule CFunctor where\n\nimport Generics.SOP.Constraint\nimport Numeric.LinearAlgebra hiding (C)\n\nclass CFunctor f where\n  type C f :: * -> Constraint\n  cfmap :: (C f a, C f b) => (a -> b) -> f a -> f b\n\n{-\ninstance {-# OVERLAPPABLE #-} Functor f => CFunctor f where\n  type C f = Top\n  cfmap = fmap\n-}\n\ninstance CFunctor Vector where\n  type C Vector = And Element (Container Vector)\n  cfmap = cmap\n\n", "meta": {"hexsha": "f9176887a1fe7f2f336d361045d66fc6cec8c0ee", "size": 512, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CFunctor.hs", "max_stars_repo_name": "vladfi1/hs-misc", "max_stars_repo_head_hexsha": "ff658f38bc2027d03d689b3f46dbeb4140312163", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-03-09T05:39:54.000Z", "max_stars_repo_stars_event_max_datetime": "2016-03-09T05:39:54.000Z", "max_issues_repo_path": "CFunctor.hs", "max_issues_repo_name": "vladfi1/hs-misc", "max_issues_repo_head_hexsha": "ff658f38bc2027d03d689b3f46dbeb4140312163", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CFunctor.hs", "max_forks_repo_name": "vladfi1/hs-misc", "max_forks_repo_head_hexsha": "ff658f38bc2027d03d689b3f46dbeb4140312163", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2608695652, "max_line_length": 59, "alphanum_fraction": 0.6875, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4483538246722341}}
{"text": "{-# language BangPatterns #-}\n{-# language DataKinds #-}\n{-# language FlexibleContexts #-}\n{-# language KindSignatures #-}\n{-# language LambdaCase #-}\n{-# language PolyKinds #-}\n{-# language StandaloneDeriving #-}\n{-# language TypeFamilies #-}\n{-# language TypeFamilyDependencies #-}\n{-# language UndecidableInstances #-}\n\nmodule Qprob where\n\nimport Control.Monad (join)\nimport Data.Coerce (coerce)\nimport Data.Kind (Type)\nimport Linear.Epsilon (nearZero)\nimport qualified Data.List as List\nimport qualified Data.Map as Map\nimport qualified Data.Complex as Complex\n\ndata Setting = Classical | Quantum\n\n--type family Setting' s = (s' :: Type) | s' -> s\n\nclass V (s :: Setting) where\n  type Setting' s = (s' :: Type) | s' -> s\n  oneS :: Setting' s\n  plusS :: Setting' s -> Setting' s -> Setting' s\n  zeroS :: Setting' s\n  timesS :: Setting' s -> Setting' s -> Setting' s\n  negateS :: Setting' s -> Setting' s\n  nearZeroS :: Setting' s -> Bool\n\ninstance V 'Classical where\n  type Setting' 'Classical = Double\n  oneS = one; plusS = plus; zeroS = zero; timesS = times; negateS = negate; nearZeroS = nearZero;\n  {-# inline oneS #-}\n  {-# inline plusS #-}\n  {-# inline zeroS #-}\n  {-# inline timesS #-}\n  {-# inline negateS #-}\n  {-# inline nearZeroS #-}\n\ninstance V 'Quantum where\n  type Setting' 'Quantum = Complex Double\n  oneS = one; plusS = plus; zeroS = zero; timesS = times; negateS = negate; nearZeroS = nearZero;\n  {-# inline oneS #-}\n  {-# inline plusS #-}\n  {-# inline zeroS #-}\n  {-# inline timesS #-}\n  {-# inline negateS #-}\n  {-# inline nearZeroS #-}\n\ndata Space (s :: Setting) a = Space !a !(Setting' s)\n\nderiving instance (Show a, Show (Setting' s)) => Show (Space s a)\nderiving instance (Eq a, Eq (Setting' s)) => Eq (Space s a)\n\nmapSpace :: (Setting' s -> Setting' s) -> Space s a -> Space s a\nmapSpace f (Space a s) = Space a (f s)\n\n-- | @W s a@ is a vector space whose basis elements are labelled\n--   by objects of type @a@ and where the coefficients are of type @Settings'' s@.\n--\n--   This is very similar to standard probability monads except that we\n--   allow probabilities to be types other than 'Double'.\nnewtype W (s :: Setting) a = W { runW :: [Space s a] }\n\nderiving instance (Show a, Show (Setting' s)) => Show (W s a)\nderiving instance (Eq a, Eq (Setting' s)) => Eq (W s a)\n\n-- | Transform the probabilities inside of 'W'.\nmapW :: (Setting' s -> Setting' s) -> W s a -> W s a\nmapW f (W l) = W (List.map (mapSpace f) l)\n\ninstance Semigroup (W s a) where\n  W x <> W y = W (x <> y)\n  {-# inline (<>) #-}\n\ninstance Monoid (W s a) where\n  mempty = W mempty\n  {-# inline mempty #-}\n\ninstance Functor (W s) where\n  fmap f w = fmapW f w\n  {-# inline fmap #-}\n\nfmapW :: (a -> b) -> W s a -> W s b\nfmapW f (W l) = W (List.map (\\(Space a p) -> Space (f a) p) l)\n{-# NOINLINE [1] fmapW #-}\n\n{-# RULES \"fmapW/coerce\" fmapW coerce = coerce #-}\n\ninstance V s => Applicative (W s) where\n  pure x = W [Space x oneS]\n  {-# inline pure #-}\n  W fs <*> W xs = W\n    ( do Space f a <- fs\n         Space x b <- xs\n         pure (Space (f x) (timesS a b))\n    )\n\ninfixl 7 .*\n(.*) :: V s => Setting' s -> W s a -> W s a\na .* b = mapW (a `timesS`) b\n\ntype P a = W 'Classical a\ntype Q a = W 'Quantum   a\n\nstar :: Q a -> Q a\nstar = mapW Complex.conjugate\n\nkron :: V s => W s a -> W s c -> W s (a,c)\nkron (W x) (W y) = W\n  ( do Space a r1 <- x\n       Space c r2 <- y\n       pure (Space (a,c) (r1 `timesS` r2))\n  )\n\ncollect :: (V s, Ord a) => W s a -> W s a\ncollect (W l) = W $ toList . fromListWith plusS $ l\n  where\n    toList = Map.foldrWithKey (\\k x xs -> (Space k x):xs) []\n    fromListWith f xs = fromListWithKey (\\_ x y -> f x y) xs\n    fromListWithKey f xs =\n      let ins t (Space a s) = Map.insertWithKey f a s t\n      in List.foldl' ins mempty xs\n\ninstance V s => Monad (W s) where\n  l >>= f = W $ List.concatMap (\\(Space (W d) p) -> List.map (\\(Space x q) -> (Space x (p `timesS` q))) d) (runW $ fmap f l)\n\n-- | When we come to observe the state of a quantum system, the quantum state becomes an ordinary probablistic one.\nobserve :: Ord a => Q a -> P a\nobserve = W . List.map (\\(Space a w) -> Space a (Complex.magnitude (w `times` w))) . runW . collect\n\nrotate :: Double -> Bool -> Q Bool\nrotate theta = \\case\n  True ->\n    let theta' = theta :+ 0\n    in subtract (cos (theta' / 2) .* pure True) (sin (theta' / 2) .* pure False)\n  False ->\n    let theta' = theta :+ 0\n    in (cos (theta' / 2) .* pure False) <> (sin (theta' / 2) .* pure True)\n\nrepeat :: Int -> (a -> a) -> (a -> a)\nrepeat 0 _ = id\nrepeat n f = repeat (n - 1) f . f\n\nrepeatM :: Monad m => Int -> (a -> m a) -> m a -> m a\nrepeatM n f = repeat n (>>= f)\n\nsnot :: Bool -> Q Bool\nsnot = rotate (pi / 2)\n\nsnot1 :: Int -> P Bool\nsnot1 n = pure True & repeatM n snot & observe\n \nsubtract :: V s => W s a -> W s a -> W s a\nsubtract a b = a <> ((negateS oneS) .* b)\n\n-- | Quantum Zeno effect.\n--\n-- A watched pot never boils.\nzeno1 :: Int -> P Bool\nzeno1 n = pure True & repeatM n (rotate (pi / fromIntegral n)) & collect & observe\n\nffor :: Functor f => f a -> (a -> b) -> f b\nffor = flip fmap\n\nliftBind :: (Functor f, Monad g) => f (g a) -> (a -> g b) -> f (g b)\nliftBind fga f = fmap (>>= f) fga\n\nzeno2 :: Int -> P Bool\nzeno2 n = pure True & repeat n\n  (\\x -> x `ffor` pure `liftBind` rotate (pi / fromIntegral n) `ffor` observe & join\n  ) & collect\n\ntype MixedState a = P (Q a)\n\ndata Experimenter = Experimenter\n  { experimenterMemory :: [Bool]\n  , experimenterState :: !Bool\n  }\n  deriving (Eq, Ord)\n\nzeno3 :: Int -> P Bool\nzeno3 n = pure (Experimenter [] True) & repeatM n\n  (\\(Experimenter m s) -> do\n    s' <- rotate (pi / fromIntegral n) s\n    pure $ Experimenter (s:m) s' \n  ) & observe & fmap experimenterState & collect\n\ntrimZero :: V s => W s a -> W s a\ntrimZero = W . List.filter (\\(Space _ v) -> not $ nearZeroS v) . runW\n\nsimplify :: Ord a => Q a -> Q a\nsimplify = trimZero . collect\n\n", "meta": {"hexsha": "a9ce6cfd5c493c4363fa0987e61039e884f02d61", "size": 5867, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Qprob.hs", "max_stars_repo_name": "chessai/qprob", "max_stars_repo_head_hexsha": "74eaf53be45a7c7e7c5741f364f930df1f0dd32c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T05:33:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:33:21.000Z", "max_issues_repo_path": "src/Qprob.hs", "max_issues_repo_name": "chessai/qprob", "max_issues_repo_head_hexsha": "74eaf53be45a7c7e7c5741f364f930df1f0dd32c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Qprob.hs", "max_forks_repo_name": "chessai/qprob", "max_forks_repo_head_hexsha": "74eaf53be45a7c7e7c5741f364f930df1f0dd32c", "max_forks_repo_licenses": ["BSD-3-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.335, "max_line_length": 124, "alphanum_fraction": 0.5960456792, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4480494138693242}}
{"text": "{-# LANGUAGE BangPatterns, DeriveFunctor, DeriveFoldable, DeriveTraversable, DeriveDataTypeable #-}\n-- | A scene graph is used to represent any N-dimensional scene. Since it is\n--   polymorphic over its contents, we can use it to represent a variety of\n--   things, from a physics world to a render tree.\nmodule Game.SceneGraph ( -- * Basic Data Types\n                         SceneGraph(..)\n                       , TransformView(..)\n                       -- * Views\n                       , viewTrans\n                       , matRep\n                       , Quaternion\n                       -- * Transformations\n                       , translate\n                       , scaleGraph\n                       , rotate2D\n                       , rotate3D\n                       , rotateQuat\n                       , rotate3DX\n                       , rotate3DY\n                       , rotate3DZ\n                       , rotateEuler\n                       , applyPoint\n                       , applyVector\n                       -- * Graph Visitors\n                       , optimize\n                       , sceneMap\n                       ) where\n\nimport Prelewd hiding (toList, join, (<>))\n\nimport Impure\n\nimport Control.DeepSeq\nimport Control.Monad.Par\nimport Data.Function.Pointless\nimport Data.Typeable\nimport Storage.List (init)\nimport Numeric.LinearAlgebra\nimport Text.Show\n\n-- | Represents an N-dimensional scene graph, with objects at the leaves, and\n--   transformations applied in a hierarchical fashion.\n--\n--   This is an instance of Functor, Foldable, and Traversable, so feel free to\n--   walk it like you would any recursive data structure.\ndata SceneGraph a = Object a\n                  | Transform !Transformation !(SceneGraph a)\n                  | Branch [SceneGraph a]\n    deriving (Show, Functor, Foldable, Typeable)\n\ninstance NFData a => NFData (SceneGraph a) where\n    rnf (Transform t g) = rnf t `seq` rnf g\n    rnf (Object x)      = rnf x\n    rnf (Branch xs)     = rnf xs\n\n-- | We represent the basic transformations (translate, scale, rotate) as their\n--   \"easy\" representation, as well as the more complicated matrix. This allows\n--   us to optimize the scene graph with the semantic information of chained\n--   transformations instead of just blindly multiplying matricies.\n--\n--   For example, instead of multiplying two (rather complicated) quaternion\n--   matricies to chain rotation, we just perform quaternion multiplication.\n--\n--   By keeping the matricies around too, we can always fall back on matrix\n--   multiplication, and we can also avoid recomputing them.\n--\n--   Oh yeah, and all the matricies use homogenous coordinates, so they're\n--   (N+1)x(N+1) in an n-dimensional scene. The more you know.\ndata Transformation = Translate !(Vector Double)\n                                 (Matrix Double)\n                    | Scale     !(Vector Double)\n                                 (Matrix Double)\n                    | Rotate2D  !Double -- \u03b8 - radians, clockwise.\n                                 (Matrix Double) -- affine representation\n                    | AffineTransform !(Matrix Double) -- fall back generic transformations\n                                                       -- also used for rotations.\n    deriving (Show, Typeable)\n\n-- | A data type used for deconstructing transformations and seeing what they\n--   \"really are\".\ndata TransformView = TranslateView !(Vector Double)\n                   | ScaleView !(Vector Double)\n                   | Rotate2DView !Double -- ^ \u03b8 - radians, clockwise.\n                   | AffineTransformView !(Matrix Double) --  ^ Uses homogenous coordinates.\n\n-- | Use this function to deconstruct a transformation into what it represents.\n--\n--   We use a more complicated internal data type for representing\n--   transformations, and this view can be used to simplify it. The GHC extension\n--   \"ViewPatterns\" will probably be of help here.\n--\n--   > -- f returns a scaled (by a factor of 2) translation vector.\n--   > f :: Transformation -> Vector Double\n--   > f (viewTrans -> Translate v) = v*2\nviewTrans :: Transformation -> TransformView\nviewTrans (Translate v _)     = TranslateView v\nviewTrans (Scale v _)         = ScaleView v\nviewTrans (Rotate2D \u03b8 _)      = Rotate2DView \u03b8\nviewTrans (AffineTransform m) = AffineTransformView m\n\n-- | Retrieves the matrix view of a transformation. This will be an (N+1)x(N+1)\n--   matrix, where N is the dimensions in the scene.\nmatRep :: Transformation -> Matrix Double\nmatRep (Translate _ m)     = m\nmatRep (Scale _ m)         = m\nmatRep (Rotate2D _ m)      = m\nmatRep (AffineTransform m) = m\n\nseq_ :: a -> ()\nseq_ = (`seq` ())\n\ninstance NFData Transformation where\n    rnf (Translate _ m)     = seq_ m\n    rnf (Scale     _ m)     = seq_ m\n    rnf (Rotate2D  _ m)     = seq_ m\n    rnf (AffineTransform _) = ()\n\n-- | Just a 4-element vector, specifying a 3-dimensional rotation. See the\n--   wikipedia page for more information on Quaternions.\ntype Quaternion = Vector Double\n\n-- | Represents a 2-dimensional, clockwise rotation by \u03b8 radians. This is\n--   probably easier to use than building a rotation matrix manually.\nrotate2D :: Double -- ^ \u03b8.\n         -> Transformation\nrotate2D !\u03b8 = Rotate2D \u03b8 $ rotate2DMat \u03b8\n\nrotate2DMat :: Double\n            -> Matrix Double\nrotate2DMat !\u03b8 = (3><3) [  c, s, 0\n                        , -s, c, 0\n                        , 0,  0, 1 ]\n    where\n        c = cos \u03b8\n        s = sin \u03b8\n\n-- | Rotates by a given quaternion.\n--\n--   Note: This algorithm is untested, and disagrees with wikipedia right now.\n--         I'll look into it one day.\nrotateQuat :: Quaternion -> Transformation\nrotateQuat q = AffineTransform $ (4><4) [ 1-2.0*(yy-zz), 2.0*(xy-zw)    , 2.0*(xz+yw), 0\n                                        , 2.0*(xy+zw)  , 1.0-2.0*(xx-zz), 2.0*(yz-xw), 0\n                                        , 2.0*(xz-yw)  , 2*(xw+yz)      , 1-2*(xx-yy), 0\n                                        , 0            , 0              , 0          , 1 ]\n    where\n        [ w, x, y, z ] = toList q\n        xx = x*x\n        yy = y*y\n        zz = z*z\n        zw = z*w\n        xy = x*y\n        xz = x*z\n        xw = x*w\n        yw = y*w\n        yz = y*z\n\n-- | Rotates by a given angle around an arbitrary 3-dimensional axis.\nrotate3D :: Double -- ^ The amount (in radians) to rotate by.\n         -> Vector Double -- ^ The 3-dimensional axis around which we are rotating.\n         -> Transformation\n-- https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle\nrotate3D !\u03b8 !axis = AffineTransform $ (4><4) [ c+x*xoc , x*yoc-zs, x*zoc+ys, 0\n                                             , y*xoc+zs, c+y*yoc , y*zoc-xs, 0\n                                             , z*xoc-ys, z*yoc+xs, c+z*zoc , 0\n                                             ,     0   ,    0    ,    0    , 1 ]\n    where\n        c = cos \u03b8\n        oc = 1-c\n        s = sin \u03b8\n        [x, y, z] = toList axis\n        xs = x*s\n        ys = y*s\n        zs = z*s\n        xoc = x*oc\n        yoc = y*oc\n        zoc = z*oc\n\n-- | Rotates \u03b8 radians clockwise around the X-axis.\nrotate3DX :: Double -- \u03b8\n          -> Transformation\nrotate3DX !\u03b8 = AffineTransform $ (4><4) [ 1,  0, 0, 0\n                                        , 0,  c, s, 0\n                                        , 0, -s, c, 0\n                                        , 0,  0, 0, 1 ]\n    where\n        c = cos \u03b8\n        s = sin \u03b8\n\n-- | Rotates \u03b8 radians clockwise around the Y axis.\nrotate3DY :: Double -- \u03b8\n          -> Transformation\nrotate3DY !\u03b8 = AffineTransform $ (4><4) [  c, 0, -s, 0\n                                        ,  0, 1,  0, 0\n                                        , -s, 0,  c, 0\n                                        ,  0, 0,  0, 1 ]\n    where\n        c = cos \u03b8\n        s = sin \u03b8\n\n-- | Rotates \u03b8 radians clockwise around the Y axis.\nrotate3DZ :: Double -- \u03b8\n          -> Transformation\nrotate3DZ !\u03b8 = AffineTransform $ (4><4) [  c,  s, 0, 0\n                                        , -s,  c, 0, 0\n                                        ,  0,  0, 1, 0\n                                        ,  0,  0, 0, 1 ]\n    where\n        c = cos \u03b8\n        s = sin \u03b8\n\n-- | Rotates around a yaw, pitch, and roll - all in one transformation.\nrotateEuler :: Double -- X-axis rotation.\n            -> Double -- Y-axis rotation.\n            -> Double -- Z-axis rotation.\n            -> Transformation\nrotateEuler x y z = let (AffineTransform x') = rotate3DX x\n                        (AffineTransform y') = rotate3DY y\n                        (AffineTransform z') = rotate3DZ z\n                     in AffineTransform $ z' * y' * x'\n\n-- | Adds a number to the end of a vector. Tends to be useful when constructing\n--   homogenous coordinates.\nvappend :: Element a => a -> Vector a -> Vector a\nvappend x = join . flip (:) [ constant x 1 ]\n\n-- | Applies the given modelview matrix to the given vector.\napplyVector :: Matrix Double -> Vector Double -> Vector Double\napplyVector m v = subVector 0 (dim v) $ m <> vappend 1.0 v\n\n-- | Applied the given modelview matrix to the given point.\napplyPoint :: Matrix Double -> Vector Double -> Vector Double\napplyPoint m p = subVector 0 (dim p) $ m <> vappend 0.0 p\n\nscaleMat :: Vector Double -> Matrix Double\nscaleMat = diag . vappend 1.0\n\n-- | Performs an n-dimensional scaling of the scene graph. Bigger numbers mean\n--   bigger objects. 1.0 means no scaling.\nscaleGraph :: Vector Double -- ^ The N-dimensional vector of values to scale by.\n           -> Transformation\nscaleGraph v = Scale v $ scaleMat v\n\ntranslateMat :: Vector Double -> Matrix Double\ntranslateMat v = fromColumns $ ((<?> error \"Empty vector\") . init . toColumns . ident $ dim v + 1) `mappend` [vappend 1.0 v]\n\n-- | Translates an n-dimensional scene graph by the given amount. Bigger values\n--   mean bigger objects. 1.0 means no scaling.\ntranslate :: Vector Double -- ^ The N-dimensional vector of values to translate by.\n          -> Transformation\ntranslate v = Translate v $ translateMat v\n\n-- | Cleans up a scene graph, and does its best to avoid as many\n--   multiplications and indirections as possible.\n--\n--   This will walk the whole graph, but if you're doing so anyhow, it'd be a\n--   great way to avoid a lot of extra processing due to inefficient structure.\noptimize :: SceneGraph a -> SceneGraph a\noptimize x@(Object _) = x\noptimize (Branch xs)  = optBranch xs\n    where\n        optBranch :: [SceneGraph a] -> SceneGraph a\n        optBranch []  = Branch [] -- lolwut\n        optBranch [x] = optimize x\n        optBranch xs' = Branch $ foldr f [] xs'\n            where\n                -- merges sub-branches up into their parent.\n                f y ys = case optimize y of\n                            Branch zs -> zs `mappend` ys\n                            g         -> g:ys\noptimize (Transform t g) = go\n    where\n        go = let subGraph = optimize g\n              in case subGraph of\n                Transform t' subsubGraph -> case (t, t') of\n                    (Translate v _, Translate v' _) -> Transform (combineTrans v v') subsubGraph\n                    (Scale v _, Scale v' _)         -> Transform (combineScale v v') subsubGraph\n                    (Rotate2D \u03b8 _, Rotate2D \u03c4 _)    -> Transform (combineRot \u03b8 \u03c4) subsubGraph\n                    (_, _)                          -> Transform t subGraph\n                _ -> Transform t subGraph\n        combineTrans = translate .: (+)\n        combineScale = scaleGraph .: (+)\n        combineRot   = rotate2D .: (+)\n                \n-- | Maps a function taking an object and its modelview matrix, returning a new\n--   scene graph of a possibly different type.\n--\n--   Please optimize the scene graph before calling this function for optimal\n--   efficiency.\n--\n--   To transform a point by the given matrix, use 'homPoint'. To\n--   transform a vector, use 'homVector'.\n--\n--   Don't do the multiplication yourself. You'll probably get it wrong.\nsceneMap :: NFData b\n         => Int -- ^ The number of dimensions in the scene.\n         -> (a -> Matrix Double -> b) -> SceneGraph a -> Par (SceneGraph b)\nsceneMap n f = sMap (ident n)\n    where\n        -- Give a stack of matricies to multiply and a scene graph, returns the\n        -- transformed (by f) scene graph.\n        sMap m (Object x)  = return . Object $ f x m\n        sMap m (Transform t child) = Transform t <$> sMap (matRep t * m) child\n        sMap m (Branch xs) = Branch <$> parMapM (sMap m) xs\n{-# INLINE sceneMap #-}\n", "meta": {"hexsha": "afd638e4ec602107d9b3d6c38abe5436591ee5a6", "size": 12467, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Game/SceneGraph.hs", "max_stars_repo_name": "bfops/Chess", "max_stars_repo_head_hexsha": "ea9e0e53d0c6c703b9e7d51b1e916a7bff66f099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-11T14:16:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T14:16:10.000Z", "max_issues_repo_path": "src/Game/SceneGraph.hs", "max_issues_repo_name": "bfops/Chess", "max_issues_repo_head_hexsha": "ea9e0e53d0c6c703b9e7d51b1e916a7bff66f099", "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/Game/SceneGraph.hs", "max_forks_repo_name": "bfops/Chess", "max_forks_repo_head_hexsha": "ea9e0e53d0c6c703b9e7d51b1e916a7bff66f099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7418300654, "max_line_length": 124, "alphanum_fraction": 0.5540226197, "num_tokens": 3151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4479843908931225}}
{"text": "--\n-- Benchmarks for LUSolve.\n--\n\nmodule LUSolveBenchmark (\n    benchmarks\n    ) where\n\nimport           Criterion                     (Benchmark, bench, bgroup, env,\n                                                nf)\n\nimport           Numeric.LinearAlgebra.LUSolve (luFactor)\n\nimport qualified Data.Matrix.Generic           as M\nimport qualified Data.Vector.Unboxed           as V\nimport           System.Random\n\nbundle :: Int -> [ a ] -> [[ a ]]\nbundle _ [] = []\nbundle n xs = take n xs : bundle n (drop n xs)\n\ntype Mat = M.Matrix V.Vector Double\n\nrunLUFactor :: Mat -> Mat\nrunLUFactor = (\\(x, _, _) -> x) . luFactor\n\nsetupEnv :: IO (Mat, Mat, Mat)\nsetupEnv = do\n  let mVals = randoms (mkStdGen 1) -- not a top level CAF, so will be GC'd promptly\n      randomSquareMatrices :: Int -> [ Mat ]\n      randomSquareMatrices n = Prelude.map (\\vs -> M.fromLists (bundle n vs)) (bundle (n * n) mVals)\n      m100:_ = randomSquareMatrices 100\n      m500:_ = randomSquareMatrices 500\n      m1000:_= randomSquareMatrices 1000\n  return (m100, m500, m1000)\n\nbenchmarks :: Benchmark\nbenchmarks = env setupEnv $ \\ ~(m100, m500, m1000) ->\n  bgroup \"luFactor\"\n    [ bench \"100 x 100\"   $ nf runLUFactor m100\n    , bench \"500 x 500\"   $ nf runLUFactor m500\n    , bench \"1000 x 1000\" $ nf runLUFactor m1000\n    ]\n", "meta": {"hexsha": "cb7c25415c9ad74c9917db99521823c6d318ff86", "size": 1296, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmark/LUSolveBenchmark.hs", "max_stars_repo_name": "gwright83/luSolve", "max_stars_repo_head_hexsha": "cc0059ebafa327e26067d06e9adedc9f04bdd462", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-12T01:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-12T01:05:37.000Z", "max_issues_repo_path": "benchmark/LUSolveBenchmark.hs", "max_issues_repo_name": "gwright83/luSolve", "max_issues_repo_head_hexsha": "cc0059ebafa327e26067d06e9adedc9f04bdd462", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-04T09:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-08T00:45:11.000Z", "max_forks_repo_path": "benchmark/LUSolveBenchmark.hs", "max_forks_repo_name": "gwright83/luSolve", "max_forks_repo_head_hexsha": "cc0059ebafa327e26067d06e9adedc9f04bdd462", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-04T10:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-04T10:00:35.000Z", "avg_line_length": 29.4545454545, "max_line_length": 100, "alphanum_fraction": 0.6026234568, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4477688504758319}}
{"text": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Roc (testRoc) where\n\nimport Data.Csv ((.:), FromNamedRecord(..), decodeByName)\nimport Codec.Compression.Lzma (decompress)\nimport Test.Tasty\nimport Test.Tasty.HUnit\nimport Test.Tasty.QuickCheck\nimport Statistics.Classification (ClassificationScore(..))\nimport Statistics.Classification.ROC (ROC(..), roc)\nimport System.Directory (doesFileExist)\nimport System.FilePath ((</>), (<.>))\nimport qualified Data.ByteString.Lazy as LB\nimport qualified Data.Vector as V\n\ncheckAUC :: V.Vector (ClassificationScore Bool) -> Bool\ncheckAUC v = 0 <= auc && auc <= 1\n  where auc = rocAUC $ roc v\n\nnewtype CScore = CScore { unCS :: ClassificationScore Bool }\n\ninstance FromNamedRecord CScore where\n  parseNamedRecord o = fmap CScore $ ClassificationScore <$> fmap (== (\"up\" :: String)) (o .: \"label\") <*> o .: \"prob_up\"\n\ntestExamples :: TestTree\ntestExamples = testGroup \"examples\" $ map (\\p -> testCase p (ex p)) validp\n  where\n    validp = filter (/= \"ri_czc-2\") $ pth <$> inst <*> [1..5 :: Int]\n    inst = [\"b_dce\", \"j_dce\", \"ri_czc\"]\n    pth prod n = prod ++ \"-\" ++ show n\n    ex b =\n      let p = \"data\" </> b <.> \"csv\" <.> \"xz\"\n      in doesFileExist p >>= \\case\n      True -> decodeByName . decompress <$> LB.readFile p >>= \\case\n        Left err -> assertFailure err\n        Right (_, cs) -> assertBool \"auc in range\" $ checkAUC (V.map unCS cs)\n      False -> assertBool \"no file\" True\n\npropAucRange :: [ClassificationScore Bool] -> Property\npropAucRange l = length l >= 1 ==> checkAUC (V.fromList l)\n\ntestRoc :: TestTree\ntestRoc = testGroup \"roc\" [\n    testProperty \"auc range\" propAucRange\n  , testExamples\n  ]\n", "meta": {"hexsha": "ba8030832102b4096caa707a3f1534ffa2c62783", "size": 1675, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Roc.hs", "max_stars_repo_name": "tsbattman/rochs", "max_stars_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Roc.hs", "max_issues_repo_name": "tsbattman/rochs", "max_issues_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Roc.hs", "max_forks_repo_name": "tsbattman/rochs", "max_forks_repo_head_hexsha": "b8a229ca906ae36a6b93e59db8de88d077644a55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1836734694, "max_line_length": 121, "alphanum_fraction": 0.663880597, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.4475332757677038}}
{"text": "{-# LANGUAGE Arrows #-}\r\n\r\nmodule Control.SF.AuxFunctions (\r\n    Event, edge, quantize,\r\n    presentFFT, fftA, \r\n    toMSF, toRealTimeMSF, \r\n    Control, buffer\r\n) where\r\n\r\nimport Prelude hiding (init)\r\nimport Control.Arrow\r\nimport Control.CCA.Types\r\n\r\nimport Numeric.FFT (fft)\r\nimport Data.Complex\r\nimport Data.Map (Map)\r\nimport qualified Data.Map as Map\r\n\r\n-- | Alternative for working with Math.FFT instead of Numeric.FFT\r\n--import qualified Math.FFT as FFT\r\n--import Data.Array.IArray\r\n--import Data.Array.CArray\r\n--myFFT n lst = elems $ (FFT.dft) (listArray (0, n-1) lst)\r\n\r\n-- For use with SF Conversions\r\nimport Control.Monad.Fix\r\nimport Control.SF.SF\r\nimport Control.SF.MSF\r\n\r\nimport Control.Concurrent.MonadIO\r\nimport Data.IORef.MonadIO\r\nimport qualified Data.Sequence as S\r\nimport Data.Foldable (toList)\r\nimport Control.DeepSeq\r\n\r\n\r\n--------------------------------------\r\n-- Generic Types and Functions\r\n--------------------------------------\r\n\r\ntype Event a = Maybe a\r\n\r\nedge :: ArrowInit a => a Bool Bool\r\nedge = proc b -> do\r\n    prev <- init False -< b\r\n    returnA -< prev && not b\r\n\r\n-- | Scrutinizes n samples at a time, updating after k new values from a signal function\r\nquantize :: ArrowInit a => Int -> Int -> a b (Event [b])\r\nquantize n k = proc d -> do\r\n    rec (ds,c) <- init ([],0) -< (take n (d:ds), c+1)\r\n    returnA -< if c >= n && c `mod` k == 0 then Just ds else Nothing\r\n\r\n\r\n\r\n--------------------------------------\r\n-- Fast Fourier Transform\r\n--------------------------------------\r\n\r\n-- | Converts the vector result of a dft into a map from frequency to magnitude.\r\n--   One common use is:\r\n--      fftA >>> arr (fmap $ presentFFT clockRate)\r\npresentFFT :: Double -> [Double] -> Map Double Double\r\npresentFFT clockRate a = Map.fromList $ map mkAssoc (zip [0..(length a)] a) where \r\n    mkAssoc (i,c) = (freq, c) where\r\n        samplesPerPeriod = fromIntegral (length a)\r\n        freq = fromIntegral i * (clockRate / samplesPerPeriod)\r\n\r\n-- | Given a quantization frequency (the number of samples between each \r\n--   successive FFT calculation) and a fundamental period, this will decompose\r\n--   the input signal into its constituent frequencies.\r\n--   NOTE: The fundamental period must be a power of two!\r\nfftA :: ArrowInit a => Int -> Int -> a Double (Event [Double])\r\nfftA qf fp = proc d -> do\r\n    carray <- quantize fp qf -< d :+ 0\r\n    returnA -< fmap (map magnitude . take (fp `div` 2) . fft) carray\r\n\r\n\r\n\r\n--------------------------------------\r\n-- Signal Function Conversions\r\n--------------------------------------\r\n\r\n-- | The following two functions are for lifting SFs to MSFs.  The first \r\n--   one is a quick and dirty solution, and the second one appropriately \r\n--   converts a simulated time SF into a real time one.\r\ntoMSF :: Monad m => SF a b -> MSF m a b\r\ntoMSF (SF sf) = MSF h\r\n    where \r\n      h a = return (b, toMSF sf')\r\n        where (b, sf') = sf a\r\n\r\n-- | The clockrate is the simulated rate of the input signal function.\r\n--   The buffer is the number of time steps the given signal function is \r\n--   allowed to get ahead of real time.  Thus, the real amount of time \r\n--   that it can get ahead is the buffer divided by the clockrate seconds.\r\n--   The threadHandler is a where the ThreadId of the forked thread is sent.\r\n--\r\n--   The output signal function takes and returns values in real time.  \r\n--   The input must be paired with time, and the return values are the \r\n--   list of bs generated in the given time step and a boolean that is \r\n--   true when time is synced and false when the simulation is running \r\n--   slower than real time.  Note that the returned list will be long \r\n--   if the clockrate is much faster than real time and potentially \r\n--   empty if it's slower.\r\ntoRealTimeMSF :: (Monad m, MonadIO m, MonadFix m, NFData b) => \r\n                 Double -> Int -> (ThreadId -> m ()) -> SF a b \r\n              -> MSF m (a, Double) ([b], Bool)\r\ntoRealTimeMSF clockrate buffer threadHandler sf = proc (a, t) -> do\r\n    t' <- init 0 -< t\r\n    rec f <- init 0 -< f'\r\n        let tseg = f + t-t'\r\n            (n,f') = properFraction $ tseg * clockrate\r\n    MSF initFun -< (a, n)\r\n  where\r\n      initFun (a, n) = do\r\n        inp <- newIORef a\r\n        out <- newIORef S.empty\r\n        nvar <- newEmptyMVar\r\n        tid <- liftIO $ forkIO $ worker inp out nvar 1 sf\r\n        threadHandler tid\r\n        h inp out nvar (a, n)\r\n      h inp out nvar (a, n) = do\r\n        writeIORef inp a\r\n        if (n > 0)\r\n          then do\r\n            tryPutMVar nvar n\r\n            b <- atomicModifyIORef out (swap . S.splitAt n)\r\n            return ((toList b, S.length b == n), MSF (h inp out nvar))\r\n          else return (([], True),MSF (h inp out nvar))\r\n      worker inp out nvar n (SF sf) = do\r\n        a <- readIORef inp\r\n        let (b, sf') = sf a\r\n        s <- deepseq b $ atomicModifyIORef out (\\s -> (s S.|> b, s))\r\n        n' <- if S.length s >= n+buffer then takeMVar nvar else return n\r\n        worker inp out nvar n' sf'\r\n      swap (a,b) = (b,a)\r\n\r\n\r\n\r\n\r\n--------------------------------------\r\n-- A Buffering Arrow (beta)\r\n--------------------------------------\r\n\r\ndata Control = Play | Pause | Record | Dump | Jump Integer\r\n             | ClearEarlier | ClearLater | ClearAll\r\n-- buffer takes a control signal as well as an input stream of data and \r\n-- returns values appropriate to the control signal:\r\n-- \r\nbuffer :: ArrowInit a => a (Control, b) [b]\r\nbuffer = proc (c,x) -> do\r\n    rec s <- init ([],[]) -< s'\r\n        let (ret, s') = case c of\r\n                Play -> next s\r\n                Pause -> ([], s)\r\n                Record -> ([], cons x s)\r\n                Dump -> (llToList s, s)\r\n                Jump n -> ([], nav n s)\r\n                ClearEarlier -> (fst s, ([], snd s))\r\n                ClearLater -> (snd s, (fst s, []))\r\n                ClearAll -> (llToList s, ([],[]))\r\n    returnA -< ret\r\n\r\n\r\n-- Helper stuff for buffer\r\n-- =======================\r\ntype LensList a = ([a],[a])\r\ncons :: a -> LensList a -> LensList a\r\ncons a (e,l) = (a:e, l)\r\n\r\nprev :: LensList a -> ([a], LensList a)\r\nprev l@([],_) = ([], l)\r\nprev (a:e, l) = ([a], (e, a:l))\r\n\r\nnext :: LensList a -> ([a], LensList a)\r\nnext l@(_,[]) = ([], l)\r\nnext (e, a:l) = ([a], (a:e, l))\r\n\r\nnav :: Integer -> LensList a -> LensList a\r\nnav 0 l = l\r\nnav n l | n > 0 = nav (n-1) (snd $ next l)\r\nnav n l | n < 0 = nav (n+1) (snd $ prev l)\r\n\r\nllToList :: LensList a -> [a]\r\nllToList (e, l) = e ++ l\r\n", "meta": {"hexsha": "4344f349691d96e7a4699273c5ad4c48f66d4cb1", "size": 6464, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Control/SF/AuxFunctions.hs", "max_stars_repo_name": "kianwilcox/haskell-music", "max_stars_repo_head_hexsha": "d6d628c0f63acf161903f23ad338dd59e4b67826", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-02-12T13:32:14.000Z", "max_stars_repo_stars_event_max_datetime": "2016-02-12T13:32:14.000Z", "max_issues_repo_path": "Control/SF/AuxFunctions.hs", "max_issues_repo_name": "kianwilcox/haskell-music", "max_issues_repo_head_hexsha": "d6d628c0f63acf161903f23ad338dd59e4b67826", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Control/SF/AuxFunctions.hs", "max_forks_repo_name": "kianwilcox/haskell-music", "max_forks_repo_head_hexsha": "d6d628c0f63acf161903f23ad338dd59e4b67826", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5668449198, "max_line_length": 89, "alphanum_fraction": 0.5587871287, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4474650848420402}}
{"text": "{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-# OPTIONS_HADDOCK show-extensions #-}\n\n-- |\n-- Module      : VectorSpace\n-- Description : Particle Swarm Optimisation\n-- Copyright   : (c) Tom Westerhout, 2017\n-- License     : BSD3\n-- Maintainer  : t.westerhout@student.ru.nl\n-- Stability   : experimental\n\nmodule PSO.VectorSpace\n  ( Scalable(..)\n  , VectorSpace(..)\n  ) where\n\nimport           Data.Complex        (Complex (..))\nimport           Foreign.Storable\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Generic as GV\n\nclass Scalable a v where\n  scale :: a -> v -> v\n\ninstance (Num a) => Scalable a a where\n  scale = (*)\n\ninstance (Num a) => Scalable a (Complex a) where\n  scale c (x :+ y) = (c * x) :+ (c * y)\n\ninstance (Num a, Storable a) => Scalable a (V.Vector a) where\n  scale c = V.map (c*)\n\ninstance (RealFloat a, Storable a) => Scalable a (V.Vector (Complex a)) where\n  scale c = scale (c :+ 0)\n\nclass (Num a, Num v, Scalable a v) => VectorSpace v a\n\ninstance (Num a, Num v, Scalable a v) => VectorSpace v a\n", "meta": {"hexsha": "855efafc3445fad62ec17d5ee6cb417af5aa38c5", "size": 1117, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PSO/VectorSpace.hs", "max_stars_repo_name": "twesterhout/tcm-swarm", "max_stars_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PSO/VectorSpace.hs", "max_issues_repo_name": "twesterhout/tcm-swarm", "max_issues_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PSO/VectorSpace.hs", "max_forks_repo_name": "twesterhout/tcm-swarm", "max_forks_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5952380952, "max_line_length": 77, "alphanum_fraction": 0.6445837064, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4474548185881536}}
{"text": "{-# LANGUAGE ScopedTypeVariables, BangPatterns, RecordWildCards #-}\n\n{-| Functions used internally by the SDR.Filter module. Most of these are\n    not actually used but exist for benchmarking purposes to determine the \n    fastest filter implementation.\n-}\nmodule SDR.FilterInternal where\n\nimport           Control.Monad.Primitive \nimport           Control.Monad\nimport           Foreign.C.Types\nimport           Foreign.Ptr\nimport           Data.Coerce\nimport           Data.Complex\nimport           Foreign.Marshal.Array\nimport           Foreign.Marshal.Alloc\nimport           Foreign.Storable\n\nimport qualified Data.Vector.Generic               as VG\nimport qualified Data.Vector.Generic.Mutable       as VGM\nimport qualified Data.Vector.Storable              as VS\nimport qualified Data.Vector.Storable.Mutable      as VSM\nimport qualified Data.Vector.Fusion.Bundle         as VFB\n\nimport           SDR.VectorUtils\nimport           SDR.Util\n\n{-# INLINE filterHighLevel #-}\nfilterHighLevel :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => v b -> Int -> v a -> vm (PrimState m) a -> m ()\nfilterHighLevel coeffs num inBuf outBuf = fill (VFB.generate num dotProd) outBuf\n    where\n    dotProd offset = VG.sum $ VG.zipWith mult (VG.unsafeDrop offset inBuf) coeffs\n\n{-# INLINE filterImperative1 #-}\nfilterImperative1 :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => v b -> Int -> v a -> vm (PrimState m) a -> m ()\nfilterImperative1 coeffs num inBuf outBuf = go 0\n    where\n    go offset \n        | offset < num = do\n            let res = dotProd offset\n            VGM.unsafeWrite outBuf offset res\n            go $ offset + 1\n        | otherwise    = return ()\n    dotProd offset = VG.sum $ VG.zipWith mult (VG.unsafeDrop offset inBuf) coeffs\n\n{-# INLINE filterImperative2 #-}\nfilterImperative2 :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => v b -> Int -> v a -> vm (PrimState m) a -> m ()\nfilterImperative2 coeffs num inBuf outBuf = go 0\n    where\n    go offset \n        | offset < num = do\n            let res = dotProd (VG.unsafeDrop offset inBuf)\n            VGM.unsafeWrite outBuf offset res\n            go $ offset + 1\n        | otherwise    = return ()\n    dotProd buf = go 0 0\n        where\n        go !accum j \n            | j < VG.length coeffs = go (VG.unsafeIndex buf j `mult` VG.unsafeIndex coeffs j  + accum) (j + 1)\n            | otherwise            = accum\n\ntype FilterCRR = CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\ntype FilterRR  = VS.Vector Float -> Int -> VS.Vector Float -> VS.MVector RealWorld Float -> IO ()\ntype FilterRC  = VS.Vector Float -> Int -> VS.Vector (Complex Float) -> VS.MVector RealWorld (Complex Float) -> IO ()\n\nfilterFFIR :: FilterCRR -> FilterRR \nfilterFFIR func coeffs num inBuf outBuf = \n    VS.unsafeWith (coerce coeffs) $ \\cPtr -> \n        VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n            VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n                func (fromIntegral num) (fromIntegral $ VG.length coeffs) cPtr iPtr oPtr\n\nfilterFFIC :: FilterCRR -> FilterRC \nfilterFFIC func coeffs num inBuf outBuf = \n    VS.unsafeWith (coerce coeffs) $ \\cPtr -> \n        VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n            VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n                func (fromIntegral num) (fromIntegral $ VG.length coeffs) cPtr iPtr oPtr\n\nforeign import ccall unsafe \"filterRR\"\n    filterRR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCRR :: FilterRR\nfilterCRR = filterFFIR filterRR_c \n\nforeign import ccall unsafe \"filterRC\"\n    filterRC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCRC :: FilterRC\nfilterCRC = filterFFIC filterRC_c\n\nforeign import ccall unsafe \"filterSSERR\"\n    filterSSERR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCSSERR :: FilterRR\nfilterCSSERR = filterFFIR filterSSERR_c\n\nforeign import ccall unsafe \"filterSSESymmetricRR\"\n    filterSSESymmetricRR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCSSESymmetricRR :: FilterRR\nfilterCSSESymmetricRR = filterFFIR filterSSESymmetricRR_c\n\nforeign import ccall unsafe \"filterSSERC\"\n    filterSSERC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCSSERC :: FilterRC\nfilterCSSERC = filterFFIC filterSSERC_c\n\nforeign import ccall unsafe \"filterSSERC2\"\n    filterSSERC2_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCSSERC2 :: FilterRC\nfilterCSSERC2 = filterFFIC filterSSERC2_c\n\nforeign import ccall unsafe \"filterAVXRR\"\n    filterAVXRR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCAVXRR :: FilterRR\nfilterCAVXRR = filterFFIR filterAVXRR_c\n\nforeign import ccall unsafe \"filterAVXSymmetricRR\"\n    filterAVXSymmetricRR_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCAVXSymmetricRR :: FilterRR\nfilterCAVXSymmetricRR = filterFFIR filterAVXSymmetricRR_c\n\nforeign import ccall unsafe \"filterAVXRC\"\n    filterAVXRC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCAVXRC :: FilterRC\nfilterCAVXRC = filterFFIC filterAVXRC_c\n\nforeign import ccall unsafe \"filterAVXRC2\"\n    filterAVXRC2_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCAVXRC2 :: FilterRC\nfilterCAVXRC2 = filterFFIC filterAVXRC2_c\n\nforeign import ccall unsafe \"filterSSESymmetricRC\"\n    filterSSESymmetricRC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCSSESymmetricRC :: FilterRC\nfilterCSSESymmetricRC = filterFFIC filterSSESymmetricRC_c\n\nforeign import ccall unsafe \"filterAVXSymmetricRC\"\n    filterAVXSymmetricRC_c :: CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nfilterCAVXSymmetricRC :: FilterRC\nfilterCAVXSymmetricRC = filterFFIC filterAVXSymmetricRC_c\n\n-- Decimation\n\n{-# INLINE decimateHighLevel #-}\ndecimateHighLevel :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => Int -> v b -> Int -> v a -> vm (PrimState m) a -> m ()\ndecimateHighLevel factor coeffs num inBuf outBuf = fill x outBuf\n    where \n    x = VFB.map dotProd (VFB.iterateN num (+ factor) 0)\n    dotProd offset = VG.sum $ VG.zipWith mult (VG.unsafeDrop offset inBuf) coeffs\n\ntype DecimateCRR = CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\ntype DecimateRR  = Int -> VS.Vector Float -> Int -> VS.Vector Float -> VS.MVector RealWorld Float -> IO ()\ntype DecimateRC  = Int -> VS.Vector Float -> Int -> VS.Vector (Complex Float) -> VS.MVector RealWorld (Complex Float) -> IO ()\n\ndecimateFFIR :: DecimateCRR -> DecimateRR \ndecimateFFIR func factor coeffs num inBuf outBuf = \n    VS.unsafeWith (coerce coeffs) $ \\cPtr -> \n        VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n            VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n                func (fromIntegral num) (fromIntegral factor) (fromIntegral $ VG.length coeffs) cPtr iPtr oPtr\n\ndecimateFFIC :: DecimateCRR -> DecimateRC \ndecimateFFIC func factor coeffs num inBuf outBuf = \n    VS.unsafeWith (coerce coeffs) $ \\cPtr -> \n        VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n            VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n                func (fromIntegral num) (fromIntegral factor) (fromIntegral $ VG.length coeffs) cPtr iPtr oPtr\n\nforeign import ccall unsafe \"decimateRR\"\n    decimateCRR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCRR :: DecimateRR\ndecimateCRR = decimateFFIR decimateCRR_c\n\nforeign import ccall unsafe \"decimateRC\"\n    decimateCRC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCRC :: DecimateRC\ndecimateCRC = decimateFFIC decimateCRC_c\n\nforeign import ccall unsafe \"decimateSSERR\"\n    decimateSSERR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCSSERR :: DecimateRR\ndecimateCSSERR = decimateFFIR decimateSSERR_c\n\nforeign import ccall unsafe \"decimateSSERC\"\n    decimateSSERC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCSSERC :: DecimateRC\ndecimateCSSERC = decimateFFIC decimateSSERC_c\n\nforeign import ccall unsafe \"decimateSSERC2\"\n    decimateSSERC2_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCSSERC2 :: DecimateRC\ndecimateCSSERC2 = decimateFFIC decimateSSERC2_c\n\nforeign import ccall unsafe \"decimateAVXRR\"\n    decimateAVXRR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCAVXRR :: DecimateRR\ndecimateCAVXRR = decimateFFIR decimateAVXRR_c\n\nforeign import ccall unsafe \"decimateAVXRC\"\n    decimateAVXRC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCAVXRC :: DecimateRC\ndecimateCAVXRC = decimateFFIC decimateAVXRC_c\n\nforeign import ccall unsafe \"decimateAVXRC2\"\n    decimateAVXRC2_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCAVXRC2 :: DecimateRC\ndecimateCAVXRC2 = decimateFFIC decimateAVXRC2_c\n\nforeign import ccall unsafe \"decimateSSESymmetricRR\"\n    decimateSSESymmetricRR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCSSESymmetricRR :: DecimateRR\ndecimateCSSESymmetricRR = decimateFFIR decimateSSESymmetricRR_c\n\nforeign import ccall unsafe \"decimateAVXSymmetricRR\"\n    decimateAVXSymmetricRR_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCAVXSymmetricRR :: DecimateRR\ndecimateCAVXSymmetricRR = decimateFFIR decimateAVXSymmetricRR_c\n\nforeign import ccall unsafe \"decimateSSESymmetricRC\"\n    decimateSSESymmetricRC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCSSESymmetricRC :: DecimateRC\ndecimateCSSESymmetricRC = decimateFFIC decimateSSESymmetricRC_c\n\nforeign import ccall unsafe \"decimateAVXSymmetricRC\"\n    decimateAVXSymmetricRC_c :: CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndecimateCAVXSymmetricRC :: DecimateRC\ndecimateCAVXSymmetricRC = decimateFFIC decimateAVXSymmetricRC_c\n\n-- Resampling\n{-# INLINE resampleHighLevel #-}\nresampleHighLevel :: (PrimMonad m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => Int -> Int -> v b -> Int -> Int -> v a -> vm (PrimState m) a -> m Int\nresampleHighLevel interpolation decimation coeffs filterOffset count inBuf outBuf = fill 0 filterOffset 0\n    where\n    fill i filterOffset inputOffset\n        | i < count = do\n            let dp = dotProd filterOffset inputOffset\n            VGM.unsafeWrite outBuf i dp\n            let (q, r)        = divMod (decimation - filterOffset - 1) interpolation\n                inputOffset'  = inputOffset + q + 1\n                filterOffset' = interpolation - 1 - r\n            filterOffset' `seq` inputOffset' `seq` fill (i + 1) filterOffset' inputOffset'\n        | otherwise = return filterOffset\n    dotProd filterOffset offset = VG.sum $ VG.zipWith mult (VG.unsafeDrop offset inBuf) (stride interpolation (VG.unsafeDrop filterOffset coeffs))\n\nforeign import ccall unsafe \"resampleRR\"\n    resample_c :: CInt -> CInt -> CInt -> CInt -> CInt -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\nresampleCRR :: Int -> Int -> Int -> Int -> VS.Vector Float -> VS.Vector Float -> VS.MVector RealWorld Float -> IO ()\nresampleCRR num interpolation decimation offset coeffs inBuf outBuf = \n    VS.unsafeWith (coerce coeffs) $ \\cPtr -> \n        VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n            VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n                resample_c (fromIntegral num) (fromIntegral $ VG.length coeffs) (fromIntegral interpolation) (fromIntegral decimation) (fromIntegral offset) cPtr iPtr oPtr\n\npad :: a -> Int -> [a] -> [a]\npad with num list = list ++ replicate (num - length list) with \n\nstrideList :: Int -> [a] -> [a]\nstrideList s xs = go 0 xs\n    where\n    go _ []     = []\n    go 0 (x:xs) = x : go (s-1) xs\n    go n (x:xs) = go (n - 1) xs\n\nroundUp :: Int -> Int -> Int\nroundUp num div = ((num + div - 1) `quot` div) * div\n\ndata Coeffs = Coeffs {\n    numCoeffs  :: Int,\n    numGroups  :: Int,\n    increments :: [Int],\n    groups     :: [[Float]]\n}\n\nprepareCoeffs :: Int -> Int -> Int -> [Float] -> Coeffs\nprepareCoeffs n interpolation decimation coeffs = Coeffs {..}\n    where\n    numCoeffs   = maximum $ map (length . snd) dats\n    numGroups   = length groups\n    increments  = map fst dats\n\n    groups      :: [[Float]]\n    groups      = map (pad 0 (roundUp numCoeffs n)) $ map snd dats\n\n    dats :: [(Int, [Float])]\n    dats = func 0\n        where\n\n        func' 0      = []\n        func' x      = func x\n\n        func :: Int -> [(Int, [Float])]\n        func offset = (increment, strideList interpolation $ drop offset coeffs) : func' offset'\n            where\n            (q, r)    = divMod (decimation - offset - 1) interpolation\n            increment = q + 1\n            offset'   = interpolation - 1 - r\n\nresampleFFIR :: (Ptr CFloat -> Ptr CFloat -> IO CInt) -> VS.Vector Float -> VSM.MVector RealWorld Float -> IO Int\nresampleFFIR func inBuf outBuf = liftM fromIntegral $\n    VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            func iPtr oPtr\n\nresampleFFIC :: (Ptr CFloat -> Ptr CFloat -> IO CInt) -> VS.Vector (Complex Float) -> VSM.MVector RealWorld (Complex Float) -> IO Int\nresampleFFIC func inBuf outBuf = liftM fromIntegral $\n    VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n        VSM.unsafeWith (coerce outBuf) $ \\oPtr -> \n            func iPtr oPtr\n\ntype ResampleR = CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt\n\nmkResampler :: ResampleR -> Int -> Int -> Int -> [Float] -> IO (Int -> Int -> VS.Vector Float -> VS.MVector RealWorld Float -> IO Int)\nmkResampler func n interpolation decimation coeffs = do\n    groupsP     <- mapM newArray $ map (map realToFrac) groups\n    groupsPP    <- newArray groupsP\n    incrementsP <- newArray $ map fromIntegral increments\n    return $ \\offset num -> resampleFFIR $ func (fromIntegral num) (fromIntegral numCoeffs) (fromIntegral offset) (fromIntegral numGroups) incrementsP groupsPP\n    where\n    Coeffs {..} = prepareCoeffs n interpolation decimation coeffs\n\ntype ResampleRR = Int -> Int -> [Float] -> IO (Int -> Int -> VS.Vector Float -> VS.MVector RealWorld Float -> IO Int)\n\nforeign import ccall unsafe \"resample2RR\"\n    resample2_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt\n\nresampleCRR2 :: ResampleRR\nresampleCRR2 = mkResampler resample2_c 1\n\nforeign import ccall unsafe \"resampleSSERR\"\n    resampleCSSERR_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt\n\nresampleCSSERR :: ResampleRR\nresampleCSSERR = mkResampler resampleCSSERR_c 4\n\nforeign import ccall unsafe \"resampleAVXRR\"\n    resampleAVXRR_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt\n\nresampleCAVXRR :: ResampleRR\nresampleCAVXRR = mkResampler resampleAVXRR_c 8\n\ntype ResampleRC = Int -> Int -> [Float] -> IO (Int -> Int -> VS.Vector (Complex Float) -> VS.MVector RealWorld (Complex Float) -> IO Int)\n\nmkResamplerC :: ResampleR -> Int -> Int -> Int -> [Float] -> IO (Int -> Int -> VS.Vector (Complex Float) -> VS.MVector RealWorld (Complex Float) -> IO Int)\nmkResamplerC func n interpolation decimation coeffs = do\n    groupsP     <- mapM newArray $ map (map realToFrac) groups\n    groupsPP    <- newArray groupsP\n    incrementsP <- newArray $ map fromIntegral increments\n    return $ \\offset num -> resampleFFIC $ func (fromIntegral num) (fromIntegral numCoeffs) (fromIntegral offset) (fromIntegral numGroups) incrementsP groupsPP\n    where\n    Coeffs {..} = prepareCoeffs n interpolation decimation coeffs\n\nforeign import ccall unsafe \"resample2RC\"\n    resample2RC_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt\n\nresampleCRC :: ResampleRC\nresampleCRC = mkResamplerC resample2RC_c 1\n\nforeign import ccall unsafe \"resampleSSERC\"\n    resampleCSSERC_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt\n\nresampleCSSERC :: ResampleRC\nresampleCSSERC = mkResamplerC resampleCSSERC_c 4\n\nforeign import ccall unsafe \"resampleAVXRC\"\n    resampleAVXRC_c :: CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr (Ptr CFloat) -> Ptr CFloat -> Ptr CFloat -> IO CInt\n\nresampleCAVXRC :: ResampleRC\nresampleCAVXRC = mkResamplerC resampleAVXRC_c 8\n\n{-\n - Cross buffer\n-}\n\n{-# INLINE decimateCrossHighLevel #-}\ndecimateCrossHighLevel :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => Int -> v b -> Int -> v a -> v a -> vm (PrimState m) a -> m ()\ndecimateCrossHighLevel factor coeffs num lastBuf nextBuf outBuf = fill x outBuf\n    where\n    x = VFB.map dotProd (VFB.iterateN num (+ factor) 0)\n    dotProd i = VG.sum $ VG.zipWith mult (VG.unsafeDrop i lastBuf VG.++ nextBuf) coeffs\n\n{-# INLINE filterCrossHighLevel #-}\nfilterCrossHighLevel :: (PrimMonad m, Functor m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => v b -> Int -> v a -> v a -> vm (PrimState m) a -> m ()\nfilterCrossHighLevel coeffs num lastBuf nextBuf outBuf = fill (VFB.generate num dotProd) outBuf\n    where\n    dotProd i = VG.sum $ VG.zipWith mult (VG.unsafeDrop i lastBuf VG.++ nextBuf) coeffs\n\n{-# INLINE resampleCrossHighLevel #-}\nresampleCrossHighLevel :: (PrimMonad m, Num a, Mult a b, VG.Vector v a, VG.Vector v b, VGM.MVector vm a) => Int -> Int -> v b -> Int -> Int -> v a -> v a -> vm (PrimState m) a -> m Int\nresampleCrossHighLevel interpolation decimation coeffs filterOffset count lastBuf nextBuf outBuf = fill 0 filterOffset 0\n    where\n    fill i filterOffset inputOffset\n        | i < count = do\n            let dp = dotProd filterOffset inputOffset\n            VGM.unsafeWrite outBuf i dp\n            let (q, r)        = divMod (decimation - filterOffset - 1) interpolation\n                inputOffset'  = inputOffset + q + 1\n                filterOffset' = interpolation - 1 - r\n            filterOffset' `seq` inputOffset' `seq` fill (i + 1) filterOffset' inputOffset'\n        | otherwise = return filterOffset\n    dotProd filterOffset i = VG.sum $ VG.zipWith mult (VG.unsafeDrop i lastBuf VG.++ nextBuf) (stride interpolation (VG.unsafeDrop filterOffset coeffs))\n\nforeign import ccall unsafe \"dcBlocker\"\n    c_dcBlocker :: CInt -> CFloat -> CFloat -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> Ptr CFloat -> IO ()\n\ndcBlocker :: Int -> Float -> Float -> VS.Vector Float -> VS.MVector RealWorld Float -> IO (Float, Float)\ndcBlocker num lastSample lastOutput inBuf outBuf = \n    alloca $ \\fsp -> \n        alloca $ \\fop -> \n            VS.unsafeWith (coerce inBuf) $ \\iPtr -> \n                VSM.unsafeWith (coerce outBuf) $ \\oPtr -> do\n                    c_dcBlocker (fromIntegral num) (realToFrac lastSample) (realToFrac lastOutput) fsp fop iPtr oPtr\n                    r1 <- peek fsp\n                    r2 <- peek fop\n                    return (realToFrac r1, realToFrac r2)\n", "meta": {"hexsha": "2abef9d023ea44ae4ec3be8a01aad00882debd8d", "size": 19220, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "hs_sources/SDR/FilterInternal.hs", "max_stars_repo_name": "adamwalker/sdr", "max_stars_repo_head_hexsha": "c7d4d7dacb41039976e11df93adb10d3570cb8ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 94, "max_stars_repo_stars_event_min_datetime": "2015-05-10T02:13:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T16:32:22.000Z", "max_issues_repo_path": "hs_sources/SDR/FilterInternal.hs", "max_issues_repo_name": "peixian/sdr", "max_issues_repo_head_hexsha": "55bc865ea6c6df2d7e6e9fe6c4c3d02f76a5b2ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-05-05T19:20:46.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-02T04:19:15.000Z", "max_forks_repo_path": "hs_sources/SDR/FilterInternal.hs", "max_forks_repo_name": "adamwalker/sdr", "max_forks_repo_head_hexsha": "c7d4d7dacb41039976e11df93adb10d3570cb8ce", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-07-12T11:23:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T07:41:21.000Z", "avg_line_length": 43.8812785388, "max_line_length": 184, "alphanum_fraction": 0.6728407908, "num_tokens": 5601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4474548074148794}}
{"text": "module LispParser where\n\nimport Control.Monad (liftM)\nimport Control.Monad.Error.Class (throwError)\nimport Data.Complex (Complex (..))\nimport Data.Ratio ((%))\nimport LispVal\nimport Numeric (readFloat, readHex, readOct)\nimport Text.ParserCombinators.Parsec hiding (spaces)\n\nreadOrThrow :: Parser a -> String -> ThrowsError a\nreadOrThrow parser input = case parse parser \"lisp\" input of\n    Left err  -> throwError $ Parser err\n    Right val -> return val\n\n\nreadExpr :: String -> ThrowsError LispVal\nreadExpr = readOrThrow parseExpr\n\nreadExprList :: String -> ThrowsError [LispVal]\nreadExprList = readOrThrow (endBy parseExpr spaces)\n\nparseLisp :: SourceName -> String -> Either ParseError LispVal\nparseLisp = parse parseExpr\n\nparseExpr :: Parser LispVal\nparseExpr =\n  parseAtom\n    <|> parseString\n    <|> parseCharacter\n    <|> try parseFloat\n    <|> try parseRational\n    <|> try parseComplex\n    <|> parseNumber\n    <|> parseQuote\n    <|> parseQuasiquote\n    <|> do\n      _ <- char '('\n      x <- try parseList <|> parseDottedList\n      _ <- char ')'\n      return x\n\nparseList :: Parser LispVal\nparseList = liftM List $ sepBy parseExpr spaces\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n  x <- endBy parseExpr spaces\n  xs <- char '.' >> spaces >> parseExpr\n  return $ DottedList x xs\n\nparseQuote :: Parser LispVal\nparseQuote = do\n  _ <- char '\\''\n  x <- parseExpr\n  return $ List [Atom \"quote\", x]\n\nparseQuasiquote :: Parser LispVal\nparseQuasiquote = do\n  _ <- char ','\n  x <- parseExpr\n  return $ List [Atom \"quasiquote\", x]\n\nparseAtom :: Parser LispVal\nparseAtom = do\n  first <- letter <|> symbol\n  rest <- many (letter <|> digit <|> symbol)\n  let atom = first : rest\n  return $ case atom of\n    \"True\" -> Bool True\n    \"False\" -> Bool False\n    _ -> Atom atom\n\nparseNumber :: Parser LispVal\nparseNumber = parseDecimal <|> parseHex <|> parseOct <|> parseDecimalNotation\n\nparseDecimal :: Parser LispVal\nparseDecimal = many1 digit >>= (return . Number . read)\n\nparseDecimalNotation :: Parser LispVal\nparseDecimalNotation = do\n  _ <- try $ string \"#d\"\n  x <- many1 digit\n  (return . Number . read) x\n\nparseHex :: Parser LispVal\nparseHex = do\n  _ <- try $ string \"#x\"\n  x <- many1 hexDigit\n  return $ Number (hexToDigit x)\n\nhexToDigit :: (Eq a, Num a) => String -> a\nhexToDigit x = fst $ head (readHex x)\n\nparseOct :: Parser LispVal\nparseOct = do\n  _ <- try $ string \"#o\"\n  x <- many1 octDigit\n  return $ Number (octToDigit x)\n\noctToDigit :: (Eq a, Num a) => String -> a\noctToDigit x = fst $ head (readOct x)\n\nparseString :: Parser LispVal\nparseString = do\n  _ <- char '\"'\n  x <- many $ noneOf \"\\\"\\\\\" <|> escapedChars\n  _ <- char '\"'\n  return $ String x\n\nparseFloat :: Parser LispVal\nparseFloat = do\n  whole <- many1 digit\n  _ <- char '.'\n  frac <- many1 digit\n  return . Float . fst . head . readFloat $ whole ++ \".\" ++ frac\n\nparseRational :: Parser LispVal\nparseRational = do\n  numerator <- many1 digit\n  _ <- char '/'\n  denominator <- many1 digit\n  return $ Rational (read numerator % read denominator)\n\nparseComplex :: Parser LispVal\nparseComplex = do\n  real <- many1 digit\n  _ <- char '+'\n  imaginary <- many1 digit\n  _ <- char 'i'\n  return $ Complex (read real :+ read imaginary)\n\nparseCharacter :: Parser LispVal\nparseCharacter = try (string \"\\\\#\") >>= (return . String)\n\nescapedChars :: Parser Char\nescapedChars = do\n  _ <- char '\\\\'\n  x <- oneOf \"\\\\\\\"\\'nrt\"\n  return $ case x of\n    '\\\\' -> x\n    '\"' -> x\n    '\\'' -> x\n    'n' -> '\\n'\n    't' -> '\\t'\n    'r' -> '\\r'\n    _ -> x\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n", "meta": {"hexsha": "7b9826c592c115005e51e2083982e2f7ebfc3733", "size": 3605, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "out/production/klaps/LispParser.hs", "max_stars_repo_name": "khang00/klaps", "max_stars_repo_head_hexsha": "a07f8e36bbc92d99d4d774eeeedd1ae42a502b23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "out/production/klaps/LispParser.hs", "max_issues_repo_name": "khang00/klaps", "max_issues_repo_head_hexsha": "a07f8e36bbc92d99d4d774eeeedd1ae42a502b23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "out/production/klaps/LispParser.hs", "max_forks_repo_name": "khang00/klaps", "max_forks_repo_head_hexsha": "a07f8e36bbc92d99d4d774eeeedd1ae42a502b23", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4090909091, "max_line_length": 77, "alphanum_fraction": 0.6474341193, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.44741290505710785}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Numeric.Signal\n-- Copyright   :  (c) Alexander Vivian Hugh McPhail 2010, 2014, 2015, 2016\n-- License     :  BSD3\n--\n-- Maintainer  :  haskell.vivian.mcphail <at> gmail <dot> com\n-- Stability   :  provisional\n-- Portability :  uses FFI\n--\n-- Signal processing functions\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.Signal (\n                       S.Convolvable(..),\n                       S.Filterable(),\n                       -- * Filtering\n                       hamming,\n                       pwelch,\n                       fir,standard_fir,broadband_fir,\n                       freqzF,freqzN,\n                       filter,broadband_filter,\n                       -- * Analytic Signal\n                       analytic_signal,analytic_power,analytic_phase,\n                       unwrap,\n                       -- * Statistics\n                       cross_covariance,cross_correlation,cross_spectrum,\n                       auto_covariance,auto_correlation,\n                       -- * Preprocessing\n                       detrend,\n                       resize,\n                       downsample,\n                       deriv,\n                       cumulative_sum\n                ) where\n\n-----------------------------------------------------------------------------\n\nimport qualified Numeric.Signal.Internal as S\n\nimport Numeric.GSL.Fitting.Linear\n \nimport Data.Complex\nimport Foreign.Storable()\n\n--import Data.Function.Unicode\n\nimport qualified Data.List as L\n\n--import Data.Packed.Vector\n--import Data.Packed(Container(..))\nimport Numeric.LinearAlgebra\n\nimport qualified Data.Vector.Generic as GV \n\nimport qualified Numeric.GSL.Fourier as F\n\nimport Prelude hiding(filter)\n\n-----------------------------------------------------------------------------\n\n-- | filters the signal\nfilter :: (S.Filterable a) \n         => Vector a   -- ^ zero coefficients\n       -> Vector a     -- ^ pole coefficients\n       -> Int   -- ^ sampling rate\n       -> Vector a     -- ^ input signal\n       -> Vector a     -- ^ output signal\nfilter b a s v = let len = size v\n                     w = min s len\n                     start = (negate . fromList . reverse . toList . subVector 0 w) v\n                     finish = (negate . fromList . reverse . toList . subVector (len-w) w) v\n                     v' = vjoin [start,v,finish]\n                 in subVector s len $ S.filter_ b a v'\n\n-----------------------------------------------------------------------------\n                     \n-- | Welch (1967) power spectrum density using periodogram/FFT method\npwelch :: Int            -- ^ sampling rate\n       -> Int            -- ^ window size\n       -> Vector Double  -- ^ input signal\n       -> (Vector Double,Vector Double)  -- ^ (frequency index,power density)  \npwelch s w v = let w' = max s w -- make window at least sampling rate\n                   r  = S.pwelch w' v\n                   sd = (fromIntegral s)/2\n                   -- scale for sampling rate\n                   r' = scale (recip sd) r\n                   f  = linspace ((w `div` 2) + 1) (0,sd)\n               in (f,r')\n\n-----------------------------------------------------------------------------\n\n-- | a broadband FIR\nbroadband_fir :: (S.Filterable a, Double ~ DoubleOf a, Convert (Complex a)) =>\n                Int           -- ^ sampling rate\n              -> (Int,Int)     -- ^ (lower,upper) frequency cutoff\n              -> Vector a -- ^ filter coefficients   \nbroadband_fir s (l,h) = let o = 501\n                            ny = (fromIntegral s) / 2.0\n                            fl = (fromIntegral l) / ny\n                            fh = (fromIntegral h) / ny\n                            f = [0, fl*0.95, fl, fh, fh*1.05, 1]\n                            m = [0,0,1,1,0,0]\n                            be = zip f m\n                        in standard_fir o be\n\n-- | a broadband filter\nbroadband_filter :: (S.Filterable a, Double ~ DoubleOf a) \n                   => Int        -- ^ sampling rate\n                 -> (Int,Int)    -- ^ (lower,upper) frequency cutoff\n                 -> Vector a            -- ^ input signal\n                 -> Vector a            -- ^ output signal\nbroadband_filter s f v = let b = S.fromDouble $ broadband_fir s f\n                         in filter b (scalar 1.0) s v\n                                \n-----------------------------------------------------------------------------\n\n-- | standard FIR filter\n-- |   FIR filter with grid a power of 2 greater than the order, ramp = grid/16, hamming window\nstandard_fir :: (S.Filterable a, Double ~ DoubleOf a, Convert (Complex a)) => \n               Int -> [(a,a)] -> Vector a\nstandard_fir o be = let grid  = calc_grid o\n                        trans_ = grid `div` 16\n                    in fir o be grid trans_ $ S.hamming_ (o+1)\n\ncalc_grid :: Int -> Int\ncalc_grid o = let next_power = ceiling (((log $ fromIntegral o) :: Double) / (log 2.0)) :: Int\n              in floor $ 2.0 ** ((fromIntegral next_power) :: Double)\n\n\n-- | produce an FIR filter\nfir :: (S.Filterable a\n      , Convert (Complex a), Double ~ DoubleOf a) =>\n      Int               -- ^ order (one less than the length of the filter)\n    -> [(a,a)] -- ^ band edge frequency, nondecreasing, [0, f1, ..., f(n-1), 1]\n                        -- ^ band edge magnitude\n    -> Int               -- ^ grid spacing\n    -> Int               -- ^ transition width\n    -> Vector a     -- ^ smoothing window (size is order + 1)\n    -> Vector a     -- ^ the filter coefficients\nfir o be gn tn w = let mid = o `div` 2\n                       (f,m) = unzip be\n                       f' = diff (((fromIntegral gn))/((fromIntegral tn))/2.0) f\n                       m' = interpolate f m f'\n                       grid = interpolate f' m' $ map (\\x -> (fromIntegral x)/(fromIntegral gn)) [0..(gn-1)]\n                       grid' = map (\\x -> x :+ 0) grid\n                       b = S.fromDouble $ fst $ fromComplex $ F.ifft $ double $ fromList $ grid' ++ (reverse (drop 1 grid'))\n                       b' = vjoin [subVector ((size b)-mid-1) (mid+1) b, subVector 1 (mid+1) b] \n                   in b' * w\n\nfloor_zero x\n    | x < 0.0   = 0.0\n    | otherwise = x\n\nceil_one x\n    | x > 1.0   = 1.0\n    | otherwise = x\n\ndiff :: S.Filterable a => a -> [a] -> [a]\ndiff _ []  = []\ndiff _ [x] = [x]\ndiff inc (x1:x2:xs)\n     | x1 == x2     = (floor_zero $ x1-inc):x1:(ceil_one $ x1+inc):(diff inc (L.filter (/= x2) xs))\n     | otherwise    = x1:(diff inc (x2:xs))\n\ninterpolate :: S.Filterable a => [a] -> [a] -> [a] -> [a]\ninterpolate _ _ []      = []\ninterpolate x y (xp:xs) = if xp == 1.0 \n                             then ((interpolate'' ((length x)-1) x y xp):(interpolate x y xs))\n                             else ((interpolate' x y xp):(interpolate x y xs))\n\ninterpolate' :: S.Filterable a => [a] -> [a] -> a -> a\ninterpolate' x y xp = let Just j = L.findIndex (> xp) x\n                      in (interpolate'' j x y xp)\n\ninterpolate'' :: S.Filterable a => Int -> [a] -> [a] -> a -> a\ninterpolate'' j x y xp = let x0 = x !! (j-1)\n                             y0 = y !! (j-1)\n                             x1 = x !! j\n                             y1 = y !! j\n                         in y0 + (xp - x0) * ((y1 - y0)/(x1-x0))\n\n-----------------------------------------------------------------------------\n\n-- | determine the frequency response of a filter, given a vector of frequencies\nfreqzF :: (S.Filterable a, Double ~ DoubleOf a, S.Filterable (DoubleOf a)) => \n         Vector a     -- ^ zero coefficients\n       -> Vector a       -- ^ pole coefficients\n       -> Int     -- ^ sampling rate   \n       -> Vector a       -- ^ frequencies\n       -> Vector a       -- ^ frequency response\nfreqzF b a s f = S.freqz b a ((2*pi/(fromIntegral s)) * f)\n\n-- | determine the frequency response of a filter, given a number of points and sampling rate\nfreqzN :: (S.Filterable a, Double ~ DoubleOf a) =>\n         Vector a     -- ^ zero coefficients\n       -> Vector a       -- ^ pole coefficients\n       -> Int     -- ^ sampling rate\n       -> Int     -- ^ number of points\n       -> (Vector a,Vector a)   -- ^ (frequencies,response)\nfreqzN b a s n = let w' = linspace n (0,((fromIntegral n)-1)/(fromIntegral (2*n)))\n                     r = S.freqz b a ((2*pi)*w')\n                     in ((fromIntegral s)*w',r)\n                     \n-----------------------------------------------------------------------------\n\n-- | an analytic signal is the original signal with Hilbert-transformed signal as imaginary component\nanalytic_signal :: Vector Double -> Vector (Complex Double)\nanalytic_signal = S.hilbert\n\n-- | the power (amplitude^2 = v * (conj c)) of an analytic signal\nanalytic_power :: S.Filterable a => Vector (Complex Double) -> Vector a\nanalytic_power = S.complex_power_\n\n-- | the phase of an analytic signal\nanalytic_phase :: (S.Filterable a) => \n                 Vector (Complex a) -> Vector a\nanalytic_phase = (uncurry arctan2) . fromComplex\n\n-----------------------------------------------------------------------------\n\n-- | remove a linear trend from data\ndetrend :: Int             -- ^ window size\n        -> Vector Double   -- ^ data to be detrended\n        -> Vector Double   -- ^ detrended data\ndetrend w v = let windows = size v `div` w\n                  re = size v - (windows * w)\n                  re' = if re == 0 then [] else [re]\n                  ws = takesV ((replicate windows w) ++ re') v\n                  ds = map detrend' ws\n                  windows' = (size v - (w `div` 2)) `div` w\n                  ws' = takesV (((w `div` 2):(replicate windows' w)) ++ [size v - (w `div` 2) - (windows' * w)]) v\n                  ds' = map detrend' ws'\n              in (vjoin ds + vjoin ds') / 2 \n    where detrend' x = let ln = size x\n                           t = linspace ln (1.0,fromIntegral ln)\n                           (c0,c1,_,_,_,_) = linear t x\n                       in x - (scale c1 t + scalar c0)\n\n-----------------------------------------------------------------------------\n\n-- | resize the vector to length n by resampling\nresize :: S.Filterable a => Int -> Vector a -> Vector a\nresize n v = S.downsample_ (size v `div` n) v\n\n-----------------------------------------------------------------------------\n\n-- | cross covariance of two signals\n--     the cross correlation is computed by dividing the result\n--     by the product of the two standard deviations\ncross_covariance :: S.Filterable a => \n                   Int           -- ^ maximum delay\n                 -> Vector a -- ^ time series\n                 -> Vector a -- ^ time series\n                 -> (a,a,Vector a) -- ^ (sd_x,sd_y,cov_xy)\ncross_covariance = S.cross_covariance_\n\n-- | cross correlation of two signals\ncross_correlation :: S.Filterable a => \n                   Int           -- ^ maximum delay\n                 -> Vector a -- ^ time series\n                 -> Vector a -- ^ time series\n                 -> Vector a -- ^ result\ncross_correlation l x y = let (sx,sy,r) = S.cross_covariance_ l x y\n                          in GV.map(/ (sx*sy)) r\n\n-- | compute the cross spectrum\ncross_spectrum :: (S.Filterable a, Double ~ DoubleOf a) =>\n                 Int                      -- ^ maximum delay\n               -> Vector a                 -- ^ time series\n               -> Vector a                 -- ^ time series\n               -> Vector (Complex Double)  -- ^ result\ncross_spectrum l x y = (\\(_,_,c) -> F.fft (complex $ double c)) (cross_covariance l x y)\n\n\n-- | auto covariance of two signals\n--     the auto correlation is computed by dividing the result\n--     by the variance\nauto_covariance :: S.Filterable a => \n                   Int           -- ^ maximum delay\n                 -> Vector a -- ^ time series\n                 -> (a,Vector a) -- ^ (var,cov_xx)\nauto_covariance l v = let (sd,_,r) = cross_covariance l v v\n                      in (sd*sd,r)\n\n-- | auto correlation of two signals\nauto_correlation :: S.Filterable a => \n                   Int           -- ^ maximum delay\n                 -> Vector a -- ^ time series\n                 -> Vector a -- ^ result\nauto_correlation l v = let (var,r) = auto_covariance l v\n                          in GV.map(/ var) r\n\n-----------------------------------------------------------------------------\n\n-- | coefficients of a Hamming window\nhamming :: S.Filterable a =>\n          Int           -- ^ length\n        -> Vector a -- ^ the Hamming coeffficents\nhamming = S.hamming_\n\n-- | resample, take one sample every n samples in the original\ndownsample :: S.Filterable a => Int -> Vector a -> Vector a\ndownsample = S.downsample_\n\n-- | the difference between consecutive elements of a vector\nderiv :: S.Filterable a => Vector a -> Vector a\nderiv = S.deriv_\n\n-- | cumulative sum of a series\ncumulative_sum :: S.Filterable a =>\n                 Vector a \n               -> Vector a\ncumulative_sum = S.cumulative_sum_\n\n-- | unwrap the phase of signal (input expected to be within (-pi,pi))\nunwrap :: S.Filterable a => Vector a -> Vector a\nunwrap = S.unwrap_\n\n-----------------------------------------------------------------------------\n", "meta": {"hexsha": "4e04b6edb54852ed44b43db907da22da3c3aa8d9", "size": 13306, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/Signal.hs", "max_stars_repo_name": "amcphail/hsignal", "max_stars_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-05-27T06:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T23:12:53.000Z", "max_issues_repo_path": "lib/Numeric/Signal.hs", "max_issues_repo_name": "amcphail/hsignal", "max_issues_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-10-30T11:41:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T23:38:57.000Z", "max_forks_repo_path": "lib/Numeric/Signal.hs", "max_forks_repo_name": "amcphail/hsignal", "max_forks_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0679012346, "max_line_length": 124, "alphanum_fraction": 0.4643769728, "num_tokens": 3123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4473002865949462}}
{"text": "{-# LANGUAGE CPP              #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-incomplete-patterns -fno-warn-missing-signatures #-}\n{-# LANGUAGE DataKinds        #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes       #-}\n{-# LANGUAGE TypeFamilies     #-}\n{-# LANGUAGE TypeOperators    #-}\n{-# LANGUAGE ViewPatterns     #-}\n\n-----------------------------------------------------------------------------\n{- |\nModule      :  Numeric.LinearAlgebra.Tests\nCopyright   :  (c) Alberto Ruiz 2007-14\nLicense     :  BSD3\nMaintainer  :  Alberto Ruiz\nStability   :  provisional\n\nSome tests.\n\n-}\n\nmodule Test.Numeric.LinearAlgebra.Tests(\n--  module Numeric.LinearAlgebra.Tests.Instances,\n--  module Numeric.LinearAlgebra.Tests.Properties,\n   qCheck,\n   utest,\n   runTests,\n   runBenchmarks\n , binaryTests\n-- , findNaN\n--, runBigTests\n) where\n\nimport           Data.List                                   (foldl1')\nimport           Numeric.LinearAlgebra\nimport           Numeric.LinearAlgebra.Devel\nimport           Numeric.LinearAlgebra.Static                (L)\nimport           System.Info\nimport           Test.HUnit                                  hiding (State, Testable, test,\n                                                              (~:))\nimport           Test.Numeric.LinearAlgebra.Tests.Instances\nimport           Test.Numeric.LinearAlgebra.Tests.Properties\n#if MIN_VERSION_base(4,11,0)\nimport           Prelude                                     hiding ((<>), (^))\n#else\nimport           Prelude                                     hiding ((^))\n#endif\nimport           Control.Applicative\nimport           Control.Arrow                               ((***))\nimport           Control.DeepSeq                             (NFData (..))\nimport           Control.Monad                               (when)\nimport           Control.Monad                               (ap)\nimport           Debug.Trace\nimport           Numeric.LinearAlgebra.Devel                 (unsafeFromForeignPtr,\n                                                              unsafeToForeignPtr)\nimport qualified Prelude\nimport           System.CPUTime\nimport           System.Exit\nimport           Text.Printf\n\nimport           Test.QuickCheck                             (Arbitrary, Property,\n                                                              Testable, arbitrary, choose,\n                                                              classify, coarbitrary,\n                                                              maxSize,\n                                                              quickCheckWithResult, shrink,\n                                                              sized, stdArgs, vector)\nimport qualified Test.QuickCheck                             as T\n\nimport           Test.QuickCheck.Test                        (isSuccess)\n\n--eps = peps :: Float\n--i = 0:+1 :: Complex Float\n\nqCheck n x = do\n    r <- quickCheckWithResult stdArgs {maxSize = n} x\n    when (not $ isSuccess r) (exitFailure)\n\na ^ b = a Prelude.^ (b :: Int)\n\nutest str b = TestCase $ assertBool str b\n\nfeye n = flipud (ident n) :: Matrix Float\n\n\n-----------------------------------------------------------\n\ndetTest1 = det m == 26\n        && det mc == 38 :+ (-3)\n        && det (feye 2) == -1\n    where\n        m = (3><3)\n            [ 1, 2, 3\n            , 4, 5, 7\n            , 2, 8, 4 :: Float\n            ]\n        mc = (3><3)\n            [ 1, 2, 3\n            , 4, 5, 7\n            , 2, 8, iC\n            ]\n\ndetTest2 = inv1 |~| inv2 && [det1] ~~ [det2]\n  where\n    m = complex (feye 6)\n    inv1 = inv m\n    det1 = det m\n    (inv2,(lda,sa)) = invlndet m\n    det2 = sa * exp lda\n\n---------------------------------------------------------------------\n\nnd1 = (3><3) [ 1/2, 1/4, 1/4\n             , 0/1, 1/2, 1/4\n             , 1/2, 1/4, 1/2 :: Float]\n\nnd2 = (2><2) [1, 0, 1, 1:: Complex Float]\n\nexpmTest1 = expm nd1 :~14~: (3><3)\n [ 1.762110887278176\n , 0.478085470590435\n , 0.478085470590435\n , 0.104719410945666\n , 1.709751181805343\n , 0.425725765117601\n , 0.851451530235203\n , 0.530445176063267\n , 1.814470592751009 ]\n\nexpmTest2 = expm nd2 :~15~: (2><2)\n [ 2.718281828459045\n , 0.000000000000000\n , 2.718281828459045\n , 2.718281828459045 ]\n\n-----------------------------------------------------\n\nmbCholTest = utest \"mbCholTest\" (ok1 && ok2) where\n    m1 = (2><2) [2,5,5,8 :: Float]\n    m2 = (2><2) [3,5,5,9 :: Complex Float]\n    ok1 = mbChol (trustSym m1) == Nothing\n    ok2 = mbChol (trustSym m2) == Just (chol $ trustSym m2)\n\n-----------------------------------------------------\n\ntriTest = utest \"triTest\" ok1 where\n\n  a :: Matrix R\n  a = (4><4)\n    [\n       4.30,  0.00,  0.00, 0.00,\n      -3.96, -4.87,  0.00, 0.00,\n       0.40,  0.31, -8.02, 0.00,\n      -0.27,  0.07, -5.95, 0.12\n    ]\n\n  w :: Matrix R\n  w = (4><2)\n    [\n      -12.90, -21.50,\n       16.75,  14.93,\n      -17.55,   6.33,\n      -11.04,   8.09\n    ]\n\n  v :: Matrix R\n  v = triSolve Lower a w\n\n  e :: Matrix R\n  e = (4><2)\n    [\n      -3.0000, -5.0000,\n      -1.0000,  1.0000,\n       2.0000, -1.0000,\n       1.0000,  6.0000\n    ]\n\n  ok1 = (norm_Inf . flatten $ e - v) <= 1e-13\n\n-----------------------------------------------------\n\ntriDiagTest = utest \"triDiagTest\" (ok1 && ok2) where\n\n  dL, d, dU :: Vector Float\n  dL =  fromList [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]\n  d  =  fromList [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\n  dU =  fromList [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0]\n\n  b :: Matrix R\n  b = (9><3)\n    [\n      1.0,   1.0,   1.0,\n      1.0,  -1.0,   2.0,\n      1.0,   1.0,   3.0,\n      1.0,  -1.0,   4.0,\n      1.0,   1.0,   5.0,\n      1.0,  -1.0,   6.0,\n      1.0,   1.0,   7.0,\n      1.0,  -1.0,   8.0,\n      1.0,   1.0,   9.0\n    ]\n\n  y :: Matrix R\n  y = (9><9)\n    [\n      1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n      3.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n      0.0, 3.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n      0.0, 0.0, 3.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0,\n      0.0, 0.0, 0.0, 3.0, 1.0, 4.0, 0.0, 0.0, 0.0,\n      0.0, 0.0, 0.0, 0.0, 3.0, 1.0, 4.0, 0.0, 0.0,\n      0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 1.0, 4.0, 0.0,\n      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 1.0, 4.0,\n      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 1.0\n    ]\n\n  x :: Matrix R\n  x = triDiagSolve dL d dU b\n\n  z :: Matrix C\n  z = (4><4)\n    [\n      1.0 :+ 1.0, 4.0 :+ 4.0, 0.0 :+ 0.0, 0.0 :+ 0.0,\n      3.0 :+ 3.0, 1.0 :+ 1.0, 4.0 :+ 4.0, 0.0 :+ 0.0,\n      0.0 :+ 0.0, 3.0 :+ 3.0, 1.0 :+ 1.0, 4.0 :+ 4.0,\n      0.0 :+ 0.0, 0.0 :+ 0.0, 3.0 :+ 3.0, 1.0 :+ 1.0\n    ]\n\n  zDL, zD, zDu :: Vector C\n  zDL = fromList [3.0 :+ 3.0, 3.0 :+ 3.0, 3.0 :+ 3.0]\n  zD  = fromList [1.0 :+ 1.0, 1.0 :+ 1.0, 1.0 :+ 1.0, 1.0 :+ 1.0]\n  zDu = fromList [4.0 :+ 4.0, 4.0 :+ 4.0, 4.0 :+ 4.0]\n\n  zB :: Matrix C\n  zB = (4><3)\n    [\n      1.0 :+ 1.0,   1.0  :+   1.0,  1.0 :+ (-1.0),\n      1.0 :+ 1.0, (-1.0) :+ (-1.0), 1.0 :+ (-1.0),\n      1.0 :+ 1.0,   1.0  :+   1.0,  1.0 :+ (-1.0),\n      1.0 :+ 1.0, (-1.0) :+ (-1.0), 1.0 :+ (-1.0)\n    ]\n\n  u :: Matrix C\n  u = triDiagSolve zDL zD zDu zB\n\n  ok1 = (maximum $ map abs $ concat $ toLists $ b - (y <> x)) <= 1e-15\n  ok2 = (maximum $ map magnitude $ concat $ toLists $ zB - (z <> u)) <= 1e-15\n\n---------------------------------------------------------------------\n\ntriDiagRegression = utest \"triDiagRegression\" ok where\n  minusOnes, twos :: Vector R\n  minusOnes = fromList [-1, -1]\n  twos      = fromList [2, 2, 2]\n  k :: Matrix R\n  k = (3><3)\n    [  2, -1,  0\n    , -1,  2, -1\n    ,  0, -1,  2\n    ]\n\n  b :: Matrix R\n  b = (3><1) [10, 10, 10]\n\n  tridiag = triDiagSolve minusOnes twos minusOnes b\n  simple = linearSolve k b\n\n  ok = case simple of\n    Just m  -> tridiag |~| m\n    Nothing -> False\n\n---------------------------------------------------------------------\n\nrandomTestGaussian = (unSym c) :~3~: unSym (snd (meanCov dat))\n  where\n    a = (3><3) [1,2,3,\n                2,4,0,\n               -2,2,1]\n    m = 3 |> [1,2,3]\n    c = mTm a\n    dat = gaussianSample 7 (10^6) m c\n\nrandomTestUniform = c :~2~: unSym (snd (meanCov dat))\n  where\n    c = diag $ 3 |> map ((/12).(^2)) [1,2,3]\n    dat = uniformSample 7 (10^6) [(0,1),(1,3),(3,6)]\n\n---------------------------------------------------------------------\n\nrot :: Float -> Matrix Float\nrot a = (3><3) [ c,0,s\n               , 0,1,0\n               ,-s,0,c ]\n    where c = cos a\n          s = sin a\n\nrotTest = fun (10^5) :~11~: rot 5E4\n    where fun n = foldl1' (<>) (map rot angles)\n              where angles = toList $ linspace n (0,1)\n\n---------------------------------------------------------------------\n-- vector <= 0.6.0.2 bug discovered by Patrick Perry\n-- http://trac.haskell.org/vector/ticket/31\n\noffsetTest = y == y' where\n    x = fromList [0..3 :: Float]\n    y = subVector 1 3 x\n    (f,o,n) = unsafeToForeignPtr y\n    y' = unsafeFromForeignPtr f o n\n\n---------------------------------------------------------------------\n\nnormsVTest = TestList [\n    utest \"normv2CD\" $ norm2PropC v\n--  , utest \"normv2CF\" $ norm2PropC (single v)\n#ifndef NONORMVTEST\n  , utest \"normv2D\"  $ norm2PropR x\n--  , utest \"normv2F\"  $ norm2PropR (single x)\n#endif\n  , utest \"normv1CD\" $ norm_1 v          == 8\n--  , utest \"normv1CF\" $ norm_1 (single v) == 8\n  , utest \"normv1D\"  $ norm_1 x          == 6\n--  , utest \"normv1F\"  $ norm_1 (single x) == 6\n\n  , utest \"normvInfCD\" $ norm_Inf v          == 5\n--  , utest \"normvInfCF\" $ norm_Inf (single v) == 5\n  , utest \"normvInfD\"  $ norm_Inf x          == 3\n--  , utest \"normvInfF\"  $ norm_Inf (single x) == 3\n\n ] where v = fromList [1,-2,3:+4] :: Vector (Complex Float)\n         x = fromList [1,2,-3] :: Vector Float\n#ifndef NONORMVTEST\n         norm2PropR a = norm_2 a =~= sqrt (udot a a)\n#endif\n         norm2PropC a = norm_2 a =~= realPart (sqrt (a `dot` a))\n         a =~= b = fromList [a] |~| fromList [b]\n\nnormsMTest = TestList [\n    utest \"norm2mCD\" $ norm_2 v          =~= 8.86164970498005\n--  , utest \"norm2mCF\" $ norm_2 (single v) =~= 8.86164970498005\n  , utest \"norm2mD\"  $ norm_2 x          =~= 5.96667765076216\n--  , utest \"norm2mF\"  $ norm_2 (single x) =~= 5.96667765076216\n\n  , utest \"norm1mCD\" $ norm_1 v          == 9\n--  , utest \"norm1mCF\" $ norm_1 (single v) == 9\n  , utest \"norm1mD\"  $ norm_1 x          == 7\n--  , utest \"norm1mF\"  $ norm_1 (single x) == 7\n\n  , utest \"normmInfCD\" $ norm_Inf v          == 12\n--  , utest \"normmInfCF\" $ norm_Inf (single v) == 12\n  , utest \"normmInfD\"  $ norm_Inf x          == 8\n--  , utest \"normmInfF\"  $ norm_Inf (single x) == 8\n\n  , utest \"normmFroCD\" $ norm_Frob v          =~= 8.88819441731559\n--  , utest \"normmFroCF\" $ norm_Frob (single v) =~~= 8.88819441731559\n  , utest \"normmFroD\"  $ norm_Frob x          =~= 6.24499799839840\n--  , utest \"normmFroF\"  $ norm_Frob (single x) =~~= 6.24499799839840\n\n ] where v = (2><2) [1,-2*iC,3:+4,7] :: Matrix (Complex Float)\n         x = (2><2) [1,2,-3,5] :: Matrix Float\n         a =~= b = fromList [a] :~10~: fromList [b]\n--       a =~~= b = fromList [a] :~5~: fromList [b]\n\n---------------------------------------------------------------------\n\nsumprodTest = TestList [\n    utest \"sumCD\" $ sumElements z            == 6\n  , utest \"sumCF\" $ sumElements (single z)   == 6\n  , utest \"sumD\"  $ sumElements v            == 6\n  , utest \"sumF\"  $ sumElements (single v)   == 6\n\n  , utest \"prodCD\" $ prodProp z\n  , utest \"prodCF\" $ prodProp (single z)\n  , utest \"prodD\"  $ prodProp v\n  , utest \"prodF\"  $ prodProp (single v)\n ] where v = fromList [1,2,3] :: Vector Float\n         z = fromList [1,2-iC,3+iC]\n         prodProp x = prodElements x == product (toList x)\n\n---------------------------------------------------------------------\n\nchainTest = utest \"chain\" $ foldl1' (<>) ms |~| optimiseMult ms where\n    ms = [ diag (fromList [1,2,3 :: Float])\n         , konst 3 (3,5)\n         , (5><10) [1 .. ]\n         , konst 5 (10,2)\n         ]\n\n---------------------------------------------------------------------\n\nconjuTest m = cmap conjugate (flatten (conj (tr m))) == flatten (tr m)\n\n---------------------------------------------------------------------\n\nnewtype State s a = State { runState :: s -> (a,s) }\n\ninstance Functor (State s)\n  where\n    fmap f x = pure f <*> x\n\ninstance Applicative (State s)\n  where\n    pure = return\n    (<*>) = ap\n\ninstance Monad (State s) where\n    return a = State $ \\s -> (a,s)\n    m >>= f = State $ \\s -> let (a,s') = runState m s\n                            in runState (f a) s'\n\nstate_get :: State s s\nstate_get = State $ \\s -> (s,s)\n\nstate_put :: s -> State s ()\nstate_put s = State $ \\_ -> ((),s)\n\nevalState :: State s a -> s -> a\nevalState m s = let (a,s') = runState m s\n                in seq s' a\n\nnewtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }\n\ninstance Monad m => Functor (MaybeT m)\n  where\n    fmap f x = pure f <*> x\n\ninstance Monad m => Applicative (MaybeT m)\n  where\n    pure = return\n    (<*>) = ap\n\ninstance Monad m => Monad (MaybeT m) where\n    return a = MaybeT $ return $ Just a\n    m >>= f  = MaybeT $ do\n                        res <- runMaybeT m\n                        case res of\n                                 Nothing -> return Nothing\n                                 Just r  -> runMaybeT (f r)\n    fail _   = MaybeT $ return Nothing\n\nlift_maybe m = MaybeT $ do\n                        res <- m\n                        return $ Just res\n\n-- apply a test to successive elements of a vector, evaluates to true iff test passes for all pairs\n--successive_ :: Storable a => (a -> a -> Bool) -> Vector a -> Bool\nsuccessive_ t v = maybe False (\\_ -> True) $ evalState (runMaybeT (mapVectorM_ stp (subVector 1 (size v - 1) v))) (v ! 0)\n   where stp e  = do\n                  ep <- lift_maybe $ state_get\n                  if t e ep\n                     then lift_maybe $ state_put e\n                     else (fail \"successive_ test failed\")\n\n-- operate on successive elements of a vector and return the resulting vector, whose length 1 less than that of the input\n--successive :: (Storable a, Storable b) => (a -> a -> b) -> Vector a -> Vector b\nsuccessive f v = evalState (mapVectorM stp (subVector 1 (size v - 1) v)) (v ! 0)\n   where stp  e = do\n                  ep <- state_get\n                  state_put e\n                  return $ f ep e\n\n\nsuccTest = utest \"successive\" $\n       successive_ (>) (fromList [1 :: Float,2,3,4]) == True\n    && successive_ (>) (fromList [1 :: Float,3,2,4]) == False\n    && successive (+) (fromList [1..10 :: Float]) == 9 |> [3,5,7,9,11,13,15,17,19]\n\n---------------------------------------------------------------------\n\nfindAssocTest = utest \"findAssoc\" ok\n  where\n    ok = m1 == m2\n    m1 = assoc (6,6) 7 $ zip (find (>0) (ident 5 :: Matrix Float)) [10 ..] :: Matrix Float\n    m2 = diagRect 7 (fromList[10..14]) 6 6\n\n---------------------------------------------------------------------\n\ncondTest = utest \"cond\" ok\n  where\n    ok = step v * v == cond v 0 0 0 v\n    v = fromList [-7 .. 7 ] :: Vector Float\n\n---------------------------------------------------------------------\n\nconformTest = utest \"conform\" ok\n  where\n    ok = 1 + row [1,2,3] + col [10,20,30,40] + (4><3) [1..]\n         == (4><3) [13,15,17\n                   ,26,28,30\n                   ,39,41,43\n                   ,52,54,56]\n\n---------------------------------------------------------------------\n\naccumTest = utest \"accum\" ok\n  where\n    x = ident 3 :: Matrix Float\n    ok = accum x (+) [((1,2),7), ((2,2),3)]\n         == (3><3) [1,0,0\n                   ,0,1,7\n                   ,0,0,4]\n         &&\n         toList (flatten x) == [1,0,0,0,1,0,0,0,1]\n\n--------------------------------------------------------------------------------\n\nconvolutionTest = utest \"convolution\" ok\n  where\n--    a = fromList [1..10]               :: Vector Float\n    b = fromList [1..3]                :: Vector Float\n    c = (5><7) [1..]                   :: Matrix Float\n--    d = (3><3) [0,-1,0,-1,4,-1,0,-1,0] :: Matrix Float\n    ok =  separable (corr b) c == corr2 (outer b b) c\n       && separable (conv b) c == conv2 (outer b b) c\n\n--------------------------------------------------------------------------------\n\nsparseTest = utest \"sparse\" (fst $ checkT (undefined :: GMatrix))\n\n--------------------------------------------------------------------------------\n\nstaticTest = utest \"static\" (fst $ checkT (undefined :: L 3 5))\n\n--------------------------------------------------------------------------------\n\nintTest = utest \"int ops\" (fst $ checkT (undefined :: Matrix I))\n\n--------------------------------------------------------------------------------\n\nmodularTest = utest \"modular ops\" (fst $ checkT (undefined :: Matrix (Mod 13 I)))\n\n--------------------------------------------------------------------------------\n\nindexProp g f x = a1 == g a2 && a2 == a3 && b1 == g b2 && b2 == b3\n  where\n    l = map g (toList (f x))\n    a1 = maximum l\n    b1 = minimum l\n    a2 = x `atIndex` maxIndex x\n    b2 = x `atIndex` minIndex x\n    a3 = maxElement x\n    b3 = minElement x\n\n--------------------------------------------------------------------------------\n\n_sliceTest = TestList\n    [ testSlice (chol . trustSym)  (gen 5 :: Matrix R)\n    , testSlice (chol . trustSym)  (gen 5 :: Matrix C)\n    , testSlice qr    (rec :: Matrix R)\n    , testSlice qr    (rec :: Matrix C)\n    , testSlice hess  (agen 5 :: Matrix R)\n    , testSlice hess  (agen 5 :: Matrix C)\n    , testSlice schur (agen 5 :: Matrix R)\n    , testSlice schur (agen 5 :: Matrix C)\n    , testSlice lu    (agen 5 :: Matrix R)\n    , testSlice lu    (agen 5 :: Matrix C)\n    , testSlice (luSolve (luPacked (agen 5 :: Matrix R))) (agen 5)\n    , testSlice (luSolve (luPacked (agen 5 :: Matrix C))) (agen 5)\n    , test_lus (agen 5 :: Matrix R)\n    , test_lus (agen 5 :: Matrix C)\n\n    , testSlice eig   (agen 5 :: Matrix R)\n    , testSlice eig   (agen 5 :: Matrix C)\n    , testSlice (eigSH . trustSym) (gen 5 :: Matrix R)\n    , testSlice (eigSH . trustSym) (gen 5 :: Matrix C)\n    , testSlice eigenvalues   (agen 5 :: Matrix R)\n    , testSlice eigenvalues   (agen 5 :: Matrix C)\n    , testSlice (eigenvaluesSH . trustSym) (gen 5 :: Matrix R)\n    , testSlice (eigenvaluesSH . trustSym) (gen 5 :: Matrix C)\n\n    , testSlice svd           (rec :: Matrix R)\n    , testSlice thinSVD       (rec :: Matrix R)\n    , testSlice compactSVD     (rec :: Matrix R)\n    , testSlice leftSV        (rec :: Matrix R)\n    , testSlice rightSV       (rec :: Matrix R)\n    , testSlice singularValues (rec :: Matrix R)\n\n    , testSlice svd           (rec :: Matrix C)\n    , testSlice thinSVD       (rec :: Matrix C)\n    , testSlice compactSVD     (rec :: Matrix C)\n    , testSlice leftSV        (rec :: Matrix C)\n    , testSlice rightSV       (rec :: Matrix C)\n    , testSlice singularValues (rec :: Matrix C)\n\n    , testSlice (linearSolve (agen 5:: Matrix R)) (agen 5)\n    , testSlice (flip linearSolve (agen 5:: Matrix R)) (agen 5)\n\n    , testSlice (linearSolve (agen 5:: Matrix C)) (agen 5)\n    , testSlice (flip linearSolve (agen 5:: Matrix C)) (agen 5)\n\n    , testSlice (linearSolveLS (ogen 5:: Matrix R)) (ogen 5)\n    , testSlice (flip linearSolveLS (ogen 5:: Matrix R)) (ogen 5)\n\n    , testSlice (linearSolveLS (ogen 5:: Matrix C)) (ogen 5)\n    , testSlice (flip linearSolveLS (ogen 5:: Matrix C)) (ogen 5)\n\n    , testSlice (linearSolveSVD (ogen 5:: Matrix R)) (ogen 5)\n    , testSlice (flip linearSolveSVD (ogen 5:: Matrix R)) (ogen 5)\n\n    , testSlice (linearSolveSVD (ogen 5:: Matrix C)) (ogen 5)\n    , testSlice (flip linearSolveSVD (ogen 5:: Matrix C)) (ogen 5)\n\n    , testSlice (linearSolveLS (ugen 5:: Matrix R)) (ugen 5)\n    , testSlice (flip linearSolveLS (ugen 5:: Matrix R)) (ugen 5)\n\n    , testSlice (linearSolveLS (ugen 5:: Matrix C)) (ugen 5)\n    , testSlice (flip linearSolveLS (ugen 5:: Matrix C)) (ugen 5)\n\n    , testSlice (linearSolveSVD (ugen 5:: Matrix R)) (ugen 5)\n    , testSlice (flip linearSolveSVD (ugen 5:: Matrix R)) (ugen 5)\n\n    , testSlice (linearSolveSVD (ugen 5:: Matrix C)) (ugen 5)\n    , testSlice (flip linearSolveSVD (ugen 5:: Matrix C)) (ugen 5)\n\n    , testSlice ((<>) (ogen 5:: Matrix R)) (gen 5)\n    , testSlice (flip (<>) (gen 5:: Matrix R)) (ogen 5)\n    , testSlice ((<>) (ogen 5:: Matrix C)) (gen 5)\n    , testSlice (flip (<>) (gen 5:: Matrix C)) (ogen 5)\n    , testSlice ((<>) (ogen 5:: Matrix Float)) (gen 5)\n    , testSlice (flip (<>) (gen 5:: Matrix Float)) (ogen 5)\n    , testSlice ((<>) (ogen 5:: Matrix (Complex Float))) (gen 5)\n    , testSlice (flip (<>) (gen 5:: Matrix (Complex Float))) (ogen 5)\n    , testSlice ((<>) (ogen 5:: Matrix I)) (gen 5)\n    , testSlice (flip (<>) (gen 5:: Matrix I)) (ogen 5)\n    , testSlice ((<>) (ogen 5:: Matrix Z)) (gen 5)\n    , testSlice (flip (<>) (gen 5:: Matrix Z)) (ogen 5)\n\n    , testSlice ((<>) (ogen 5:: Matrix (I ./. 7))) (gen 5)\n    , testSlice (flip (<>) (gen 5:: Matrix (I ./. 7))) (ogen 5)\n    , testSlice ((<>) (ogen 5:: Matrix (Z ./. 7))) (gen 5)\n    , testSlice (flip (<>) (gen 5:: Matrix (Z ./. 7))) (ogen 5)\n\n    , testSlice (flip cholSolve (agen 5:: Matrix R)) (chol $ trustSym $ gen 5)\n    , testSlice (flip cholSolve (agen 5:: Matrix C)) (chol $ trustSym $ gen 5)\n    , testSlice (cholSolve (chol $ trustSym $ gen 5:: Matrix R)) (agen 5)\n    , testSlice (cholSolve (chol $ trustSym $ gen 5:: Matrix C)) (agen 5)\n\n    , ok_qrgr        (rec :: Matrix R)\n    , ok_qrgr        (rec :: Matrix C)\n    , testSlice (test_qrgr 4 tau1) qrr1\n    , testSlice (test_qrgr 4 tau2) qrr2\n    ]\n  where\n    QR qrr1 tau1 = qrRaw (rec :: Matrix R)\n    QR qrr2 tau2 = qrRaw (rec :: Matrix C)\n\n    test_qrgr n t x = qrgr n (QR x t)\n\n    ok_qrgr x = TestCase . assertBool \"ok_qrgr\" $ simeq 1E-15 q q'\n      where\n        (q,_) = qr x\n        atau = qrRaw x\n        q' = qrgr (rows q) atau\n\n    simeq eps a b =  not $ magnit eps (norm_1 $ flatten (a-b))\n\n    test_lus m = testSlice f lup\n      where\n        f x = luSolve (LU x p) m\n        (LU lup p) = luPacked m\n\n    gen :: Numeric t => Int -> Matrix t\n    gen n = diagRect 1 (konst 5 n) n n\n\n    agen :: (Numeric t, Num (Vector t))=> Int -> Matrix t\n    agen n = gen n + fromInt ((n><n)[0..])\n\n    ogen :: (Numeric t, Num (Vector t))=> Int -> Matrix t\n    ogen n = gen n === gen n\n\n    ugen :: (Numeric t, Num (Vector t))=> Int -> Matrix t\n    ugen n = takeRows 3 (gen n)\n\n\n    rec :: Numeric t => Matrix t\n    rec = subMatrix (0,0) (4,5) (gen 5)\n\n    testSlice f x@(size->sz@(r,c)) =\n      TestList . map (TestCase . assertEqual \"\" (f x)) $ (map f (g y1 ++ g y2))\n      where\n        subm = subMatrix\n        g y = [ subm (a*r,b*c) sz y | a <-[0..2], b <- [0..2]]\n        h z = fromBlocks (replicate 3 (replicate 3 z))\n        y1  = h x\n        y2  = (tr . h . tr) x\n\n\n--------------------------------------------------------------------------------\n\n-- | All tests must pass with a maximum dimension of about 20\n--  (some tests may fail with bigger sizes due to precision loss).\nrunTests :: Int  -- ^ maximum dimension\n         -> IO ()\nrunTests n = do\n    let test :: forall t . T.Testable t => t -> IO ()\n        test p = qCheck n p\n    putStrLn \"------ index\"\n    test( \\m -> indexProp id flatten (single (m :: RM)) )\n    test( \\v -> indexProp id id (single (v :: Vector Float)) )\n    test( \\m -> indexProp id flatten (m :: RM) )\n    test( \\v -> indexProp id id (v :: Vector Float) )\n    test( \\m -> indexProp magnitude flatten (single (m :: CM)) )\n    test( \\v -> indexProp magnitude id (single (v :: Vector (Complex Float))) )\n    test( \\m -> indexProp magnitude flatten (m :: CM) )\n    test( \\v -> indexProp magnitude id (v :: Vector (Complex Float)) )\n    putStrLn \"------ mult Float\"\n    test (multProp1 10 . rConsist)\n    test (multProp1 10 . cConsist)\n    test (multProp2 10 . rConsist)\n    test (multProp2 10 . cConsist)\n--    putStrLn \"------ mult Float\"\n--    test (multProp1  6 . (single *** single) . rConsist)\n--    test (multProp1  6 . (single *** single) . cConsist)\n--    test (multProp2  6 . (single *** single) . rConsist)\n--    test (multProp2  6 . (single *** single) . cConsist)\n    putStrLn \"------ sub-trans\"\n    test (subProp . rM)\n    test (subProp . cM)\n    putStrLn \"------ ctrans\"\n    test (conjuTest . cM)\n    test (conjuTest . zM)\n    putStrLn \"------ lu\"\n    test (luProp    . rM)\n    test (luProp    . cM)\n    putStrLn \"------ inv (linearSolve)\"\n    test (invProp   . rSqWC)\n    test (invProp   . cSqWC)\n    putStrLn \"------ luSolve\"\n    test (linearSolveProp (luSolve.luPacked) . rSqWC)\n    test (linearSolveProp (luSolve.luPacked) . cSqWC)\n    putStrLn \"------ ldlSolve\"\n    test (linearSolvePropH (ldlSolve.ldlPacked) . rSymWC)\n    test (linearSolvePropH (ldlSolve.ldlPacked) . cSymWC)\n    putStrLn \"------ cholSolve\"\n    test (linearSolveProp (cholSolve.chol.trustSym) . rPosDef)\n    test (linearSolveProp (cholSolve.chol.trustSym) . cPosDef)\n    putStrLn \"------ luSolveLS\"\n    test (linearSolveProp linearSolveLS . rSqWC)\n    test (linearSolveProp linearSolveLS . cSqWC)\n    test (linearSolveProp2 linearSolveLS . rConsist)\n    test (linearSolveProp2 linearSolveLS . cConsist)\n    putStrLn \"------ pinv (linearSolveSVD)\"\n    test (pinvProp  . rM)\n    test (pinvProp  . cM)\n    putStrLn \"------ det\"\n    test (detProp   . rSqWC)\n    -- test (detProp   . cSqWC)\n    putStrLn \"------ svd\"\n    test (svdProp1  . rM)\n    test (svdProp1  . cM)\n    test (svdProp1a svd . rM)\n    test (svdProp1a svd . cM)\n--    test (svdProp1a svdRd)\n    test (svdProp1b svd . rM)\n    test (svdProp1b svd . cM)\n--    test (svdProp1b svdRd)\n    test (svdProp2 thinSVD . rM)\n    test (svdProp2 thinSVD . cM)\n--    test (svdProp2 thinSVDRd)\n--    test (svdProp2 thinSVDCd)\n    test (svdProp3  . rM)\n    test (svdProp3  . cM)\n    test (svdProp4  . rM)\n    test (svdProp4  . cM)\n    test (svdProp5a)\n    test (svdProp5b)\n    test (svdProp6a)\n    test (svdProp6b)\n    test (svdProp7  . rM)\n    test (svdProp7  . cM)\n--    putStrLn \"------ svdCd\"\n#ifdef NOZGESDD\n--    putStrLn \"Omitted\"\n#else\n--    test (svdProp1a svdCd)\n--    test (svdProp1b svdCd)\n#endif\n    putStrLn \"------ eig\"\n    test (eigSHProp . rHer)\n    test (eigSHProp . cHer)\n    test (eigProp   . rSq)\n    test (eigProp   . cSq)\n    test (eigSHProp2 . rHer)\n    test (eigSHProp2 . cHer)\n    test (eigProp2   . rSq)\n    test (eigProp2   . cSq)\n    putStrLn \"------ geig\"\n    test (uncurry geigProp . rSq2WC)\n    test (uncurry geigProp . cSq2WC)\n    putStrLn \"------ nullSpace\"\n    test (nullspaceProp . rM)\n    test (nullspaceProp . cM)\n    putStrLn \"------ qr\"\n    test (qrProp     . rM)\n    test (qrProp     . cM)\n    test (rqProp     . rM)\n--    test (rqProp     . cM)\n    test (rqProp1     . cM)\n    test (rqProp2     . cM)\n--    test (rqProp3     . cM)\n    putStrLn \"------ hess\"\n    test (hessProp   . rSq)\n    test (hessProp   . cSq)\n    putStrLn \"------ schur\"\n    test (schurProp2 . rSq)\n    test (schurProp1 . cSq)\n    putStrLn \"------ chol\"\n    test (cholProp   . rPosDef)\n    test (cholProp   . cPosDef)\n--    test (exactProp  . rPosDef)\n--    test (exactProp  . cPosDef)\n    putStrLn \"------ expm\"\n    test (expmDiagProp . complex. rSqWC)\n    test (expmDiagProp . cSqWC)\n    putStrLn \"------ vector operations - Float\"\n    test (\\u -> sin u ^ 2 + cos u ^ 2 |~| (1::RM))\n    test $ (\\u -> sin u ^ 2 + cos u ^ 2 |~| (1::CM)) . liftMatrix makeUnitary\n    test (\\u -> sin u ** 2 + cos u ** 2 |~| (1::RM))\n    test (\\u -> cos u * tan u |~| sin (u::RM))\n    test $ (\\u -> cos u * tan u |~| sin (u::CM)) . liftMatrix makeUnitary\n--    putStrLn \"------ vector operations - Float\"\n--    test (\\u -> sin u ^ 2 + cos u ^ 2 |~~| (1::FM))\n--    test $ (\\u -> sin u ^ 2 + cos u ^ 2 |~~| (1::ZM)) . liftMatrix makeUnitary\n--    test (\\u -> sin u ** 2 + cos u ** 2 |~~| (1::FM))\n--    test (\\u -> cos u * tan u |~~| sin (u::FM))\n--    test $ (\\u -> cos u * tan u |~~| sin (u::ZM)) . liftMatrix makeUnitary\n    putStrLn \"------ read . show\"\n    test (\\m -> (m::RM) == read (show m))\n    test (\\m -> (m::CM) == read (show m))\n    test (\\m -> toRows (m::RM) == read (show (toRows m)))\n    test (\\m -> toRows (m::CM) == read (show (toRows m)))\n    test (\\m -> (m::FM) == read (show m))\n    test (\\m -> (m::ZM) == read (show m))\n    test (\\m -> toRows (m::FM) == read (show (toRows m)))\n    test (\\m -> toRows (m::ZM) == read (show (toRows m)))\n    putStrLn \"------ some unit tests\"\n    c <- runTestTT $ TestList\n        [ utest \"1E5 rots\" rotTest\n        , utest \"det1\" detTest1\n        , utest \"invlndet\" detTest2\n        , utest \"expm1\" (expmTest1)\n        , utest \"expm2\" (expmTest2)\n        , utest \"arith1\" $ ((ones (100,100) * 5 + 2)/0.5 - 7)**2 |~| (49 :: RM)\n        , utest \"arith2\" $ ((scalar (1+iC) * ones (100,100) * 5 + 2)/0.5 - 7)**2 |~| ( scalar (140*iC-51) :: CM)\n        , utest \"arith3\" $ exp (scalar iC * ones(10,10)*pi) + 1 |~| 0\n        , utest \"<\\\\>\"   $ (3><2) [2,0,0,3,1,1::Float] <\\> 3|>[4,9,5] |~| 2|>[2,3]\n--        , utest \"gamma\" (gamma 5 == 24.0)\n--        , besselTest\n--        , exponentialTest\n        , utest \"randomGaussian\" randomTestGaussian\n        , utest \"randomUniform\" randomTestUniform\n        , utest \"buildVector/Matrix\" $\n                        complex (10 |> [0::Float ..]) == build 10 id\n                     && ident 5 == build (5,5) (\\r c -> if r==c then 1::Float else 0)\n        , utest \"rank\" $  rank ((2><3)[1,0,0,1,5*peps,0::Float]) == 1\n                       && rank ((2><3)[1,0,0,1,7*peps,0::Float]) == 2\n        , utest \"block\" $ fromBlocks [[ident 3,0],[0,ident 4]] == (ident 7 :: CM)\n        , mbCholTest\n        , triTest\n        , triDiagTest\n        , triDiagRegression\n        , utest \"offset\" offsetTest\n        , normsVTest\n        , normsMTest\n        , sumprodTest\n        , chainTest\n        , succTest\n        , findAssocTest\n        , condTest\n        , conformTest\n        , accumTest\n        , convolutionTest\n        , sparseTest\n        , staticTest\n        , intTest\n        , modularTest\n        -- , sliceTest\n        ]\n    when (errors c + failures c > 0) exitFailure\n    return ()\n\n\n-- single precision approximate equality\n-- infixl 4 |~~|\n-- a |~~| b = a :~6~: b\n\nmakeUnitary v | realPart n > 1    = v / scalar n\n              | otherwise = v\n    where n = sqrt (v `dot` v)\n\nbinaryTests :: IO ()\nbinaryTests = do\n  let test :: forall t . T.Testable t => t -> IO ()\n      test = qCheck 100\n  test vectorBinaryRoundtripProp\n  test staticVectorBinaryRoundtripProp\n  qCheck 30 matrixBinaryRoundtripProp\n  qCheck 30 staticMatrixBinaryRoundtripProp\n\n-- -- | Some additional tests on big matrices. They take a few minutes.\n-- runBigTests :: IO ()\n-- runBigTests = undefined\n\n{-\n-- | testcase for nonempty fpu stack\nfindNaN :: Int -> Bool\nfindNaN n = all (bugProp . eye) (take n $ cycle [1..20])\n  where eye m = ident m :: Matrix ( Float)\n-}\n\n--------------------------------------------------------------------------------\n\n-- | Performance measurements.\nrunBenchmarks :: IO ()\nrunBenchmarks = do\n    solveBench\n    subBench\n    mkVecBench\n    multBench\n    cholBench\n    luBench\n    luBench_2\n    svdBench\n    eigBench\n    putStrLn \"\"\n\n--------------------------------\n\ntime msg act = do\n    putStr (msg++\" \")\n    t0 <- getCPUTime\n    act `seq` putStr \" \"\n    t1 <- getCPUTime\n    printf \"%6.2f s CPU\\n\" $ (fromIntegral (t1 - t0) / (10^12 :: Float)) :: IO ()\n    return ()\n\ntimeR msg act = do\n    putStr (msg++\" \")\n    t0 <- getCPUTime\n    putStr (show act)\n    t1 <- getCPUTime\n    printf \"%6.2f s CPU\\n\" $ (fromIntegral (t1 - t0) / (10^12 :: Float)) :: IO ()\n    return ()\n\n--------------------------------\n\nmanymult n = foldl1' (<>) (map rot2 angles) where\n    angles = toList $ linspace n (0,1)\n    rot2 :: Float -> Matrix Float\n    rot2 a = (3><3) [ c,0,s\n                    , 0,1,0\n                    ,-s,0,c ]\n        where c = cos a\n              s = sin a\n\nmultb n = foldl1' (<>) (replicate (10^6) (ident n :: Matrix Float))\n\n--------------------------------\n\nmanyvec0 xs = sum $ map (\\x -> x + x**2 + x**3) xs\nmanyvec1 xs = sumElements $ fromRows $ map (\\x -> fromList [x,x**2,x**3]) xs\nmanyvec5 xs = sumElements $ fromRows $ map (\\x -> vec3 x (x**2) (x**3)) xs\n\n\nmanyvec2 xs = sum $ map (\\x -> sqrt(x^2 + (x**2)^2 +(x**3)^2)) xs\nmanyvec3 xs = sum $ map (norm_2 . (\\x -> fromList [x,x**2,x**3])) xs\n\nmanyvec4 xs = sum $ map (norm_2 . (\\x -> vec3 x (x**2) (x**3))) xs\n\nvec3 :: Float -> Float -> Float -> Vector Float\nvec3 a b c = runSTVector $ do\n    v <- newUndefinedVector 3\n    writeVector v 0 a\n    writeVector v 1 b\n    writeVector v 2 c\n    return v\n\nmkVecBench = do\n    let n = 1000000\n        xs = toList $ linspace n (0,1::Float)\n    putStr \"\\neval data... \"; print (sum xs)\n    timeR \"listproc        \" $ manyvec0 xs\n    timeR \"fromList matrix \" $ manyvec1 xs\n    timeR \"vec3 matrix     \" $ manyvec5 xs\n    timeR \"listproc norm   \" $ manyvec2 xs\n    timeR \"norm fromList   \" $ manyvec3 xs\n    timeR \"norm vec3       \" $ manyvec4 xs\n\n--------------------------------\n\nsubBench = do\n    putStrLn \"\"\n    let g = foldl1' (.) (replicate (10^5) (\\v -> subVector 1 (size v -1) v))\n    time \"0.1M subVector   \" (g (konst 1 (1+10^5) :: Vector Float) ! 0)\n    let f = foldl1' (.) (replicate (10^5) (fromRows.toRows))\n    time \"subVector-join  3\" (f (ident  3 :: Matrix Float) `atIndex` (0,0))\n    time \"subVector-join 10\" (f (ident 10 :: Matrix Float) `atIndex` (0,0))\n\n--------------------------------\n\nmultBench = do\n    let a = ident 1000 :: Matrix Float\n    let b = ident 2000 :: Matrix Float\n    a `seq` b `seq` putStrLn \"\"\n    time \"product of 1M different 3x3 matrices\" (manymult (10^6))\n    putStrLn \"\"\n    time \"product of 1M constant  1x1 matrices\" (multb 1)\n    time \"product of 1M constant  3x3 matrices\" (multb 3)\n    --time \"product of 1M constant  5x5 matrices\" (multb 5)\n    time \"product of 1M const.  10x10 matrices\" (multb 10)\n    --time \"product of 1M const.  15x15 matrices\" (multb 15)\n    time \"product of 1M const.  20x20 matrices\" (multb 20)\n    --time \"product of 1M const.  25x25 matrices\" (multb 25)\n    putStrLn \"\"\n    time \"product (1000 x 1000)<>(1000 x 1000)\" (a<>a)\n    time \"product (2000 x 2000)<>(2000 x 2000)\" (b<>b)\n\n--------------------------------\n\neigBench = do\n    let m = reshape 1000 (randomVector 777 Uniform (1000*1000))\n        s = m + tr m\n    m `seq` s `seq` putStrLn \"\"\n    time \"eigenvalues  symmetric 1000x1000\" (eigenvaluesSH (trustSym m))\n    time \"eigenvectors symmetric 1000x1000\" (snd $ eigSH (trustSym m))\n    time \"eigenvalues  general   1000x1000\" (eigenvalues m)\n    time \"eigenvectors general   1000x1000\" (snd $ eig m)\n\n--------------------------------\n\nsvdBench = do\n    let a = reshape 500  (randomVector 777 Uniform (3000*500))\n        b = reshape 1000 (randomVector 777 Uniform (1000*1000))\n        fv (_,_,v) = v `atIndex` (0,0)\n    a `seq` b `seq` putStrLn \"\"\n    time \"singular values  3000x500\" (singularValues a)\n    time \"thin svd         3000x500\" (fv $ thinSVD a)\n    time \"full svd         3000x500\" (fv $ svd a)\n    time \"singular values 1000x1000\" (singularValues b)\n    time \"full svd        1000x1000\" (fv $ svd b)\n\n--------------------------------\n\nsolveBenchN n = do\n    let x = uniformSample 777 (2*n) (replicate n (-1,1))\n        a = tr x <> x\n        b = asColumn $ randomVector 666 Uniform n\n    a `seq` b `seq` putStrLn \"\"\n    time (\"svd solve \" ++ show n) (linearSolveSVD a b)\n    time (\" ls solve \" ++ show n) (linearSolveLS a b)\n    time (\"    solve \" ++ show n) (linearSolve a b)\n--    time (\" LU solve \" ++ show n) (luSolve (luPacked a) b)\n    time (\"LDL solve \" ++ show n) (ldlSolve (ldlPacked (trustSym a)) b)\n    time (\"cholSolve \" ++ show n) (cholSolve (chol $ trustSym a) b)\n\nsolveBench = do\n    solveBenchN 500\n    solveBenchN 1000\n    solveBenchN 1500\n\n--------------------------------\n\ncholBenchN n = do\n    let x = uniformSample 777 (2*n) (replicate n (-1,1))\n        a = tr x <> x\n    a `seq` putStr \"\"\n    time (\"chol \" ++ show n) (chol $ trustSym a)\n\ncholBench = do\n    putStrLn \"\"\n    cholBenchN 1200\n    cholBenchN 600\n    cholBenchN 300\n--    cholBenchN 150\n--    cholBenchN 50\n\n--------------------------------------------------------------------------------\n\nluBenchN f n x msg = do\n    let m = diagRect 1 (fromList (replicate n x)) n n\n    m `seq` putStr \"\"\n    time (msg ++ \" \"++ show n) (rnf $ f m)\n\nluBench = do\n    putStrLn \"\"\n    luBenchN luPacked  1000 (5::R)          \"luPacked  Float    \"\n    luBenchN luPacked' 1000 (5::R)          \"luPacked' Float    \"\n    luBenchN luPacked' 1000 (5::Mod 9973 I) \"luPacked' I mod 9973\"\n    luBenchN luPacked' 1000 (5::Mod 9973 Z) \"luPacked' Z mod 9973\"\n\nluBenchN_2 f g n x msg = do\n    let m = diagRect 1 (fromList (replicate n x)) n n\n        b = flipud m\n    m `seq` b `seq` putStr \"\"\n    time (msg ++ \" \"++ show n) (f (g m) b)\n\nluBench_2 = do\n    putStrLn \"\"\n    luBenchN_2 luSolve  luPacked  500 (5::R)          \"luSolve .luPacked  Float    \"\n    luBenchN_2 luSolve' luPacked' 500 (5::R)          \"luSolve'.luPacked' Float    \"\n    luBenchN_2 luSolve' luPacked' 500 (5::Mod 9973 I) \"luSolve'.luPacked' I mod 9973\"\n    luBenchN_2 luSolve' luPacked' 500 (5::Mod 9973 Z) \"luSolve'.luPacked' Z mod 9973\"\n", "meta": {"hexsha": "3b9265d50d5abf2dbaec6ed65ab9c0d89c485cd1", "size": 36910, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Test/Numeric/LinearAlgebra/Tests.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Test/Numeric/LinearAlgebra/Tests.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Test/Numeric/LinearAlgebra/Tests.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 33.4936479129, "max_line_length": 121, "alphanum_fraction": 0.4977783798, "num_tokens": 12885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4471831375468674}}
{"text": "{-# LANGUAGE Strict #-}\nmodule STC.Multiplication where\n\nimport           Control.Concurrent.Async\nimport           Control.Monad            as M\nimport           Data.Array.Repa          as R\nimport           Data.Complex\nimport           Data.List                as L\nimport           Data.Vector.Storable     as VS\nimport           DFT.Plan\nimport           Filter.Utils\nimport           STC.DFTArray\nimport           Utils.List\nimport           Utils.Parallel\n\n{-# INLINE multiplyPinwheelBasis #-}\nmultiplyPinwheelBasis :: DFTPlan -> DFTArray -> DFTArray -> IO DFTArray\nmultiplyPinwheelBasis plan (DFTArray rows cols thetaFreqs rFreqs vecs1) (DFTArray _ _ _ _ vecs2) = do\n  dftVecs1 <-\n    dftExecuteBatchP plan (DFTPlanID DFT1DG [cols, rows] [0, 1]) .\n    L.map\n      (VS.convert .\n       toUnboxed .\n       computeS . makeFilter2D . fromUnboxed (Z :. cols :. rows) . VS.convert) $\n    vecs1\n  dftVecs2 <- dftExecuteBatchP plan (DFTPlanID DFT1DG [cols, rows] [0, 1]) vecs2\n  let dftVecs3 = L.zipWith (VS.zipWith (*)) dftVecs1 dftVecs2\n  DFTArray rows cols thetaFreqs rFreqs <$>\n    dftExecuteBatchP plan (DFTPlanID IDFT1DG [cols, rows] [0, 1]) dftVecs3\n\n{-# INLINE multiplyPinwheelBasisBatch #-}\nmultiplyPinwheelBasisBatch ::\n     DFTPlan -> Int -> DFTArray -> DFTArray -> IO DFTArray\nmultiplyPinwheelBasisBatch plan numBatch (DFTArray rows cols thetaFreqs rFreqs vecs1) (DFTArray _ _ _ _ vecs2) = do\n  let forwardPlanID = DFTPlanID DFT1DG [cols, rows] [0, 1]\n      backwardPlanID = DFTPlanID IDFT1DG [cols, rows] [0, 1]\n      forwardPlan = getDFTPlan plan forwardPlanID\n      backwardPlan = getDFTPlan plan backwardPlanID\n  fmap (DFTArray rows cols thetaFreqs rFreqs . L.concat) .\n    mapConcurrently\n      (M.mapM\n         (\\(vec1, vec2) -> do\n            dftVec1 <-\n              dftExecuteWithPlan forwardPlanID forwardPlan .\n              VS.convert .\n              toUnboxed .\n              computeS .\n              makeFilter2D . fromUnboxed (Z :. cols :. rows) . VS.convert $\n              vec1\n            dftVec2 <- dftExecuteWithPlan forwardPlanID forwardPlan vec2\n            dftExecuteWithPlan backwardPlanID backwardPlan $\n              VS.zipWith (*) dftVec1 dftVec2)) .\n    divideListN numBatch $\n    L.zip vecs1 vecs2\n\n\n{-# INLINE multiplyPinwheelBasisBatch1 #-}\nmultiplyPinwheelBasisBatch1 ::\n     DFTPlan -> Int -> VS.Vector (Complex Double) -> DFTArray -> IO DFTArray\nmultiplyPinwheelBasisBatch1 plan numBatch dftVec1 (DFTArray rows cols thetaFreqs rFreqs vecs2) = do\n  let forwardPlanID = DFTPlanID DFT1DG [cols, rows] [0, 1]\n      backwardPlanID = DFTPlanID IDFT1DG [cols, rows] [0, 1]\n      forwardPlan = getDFTPlan plan forwardPlanID\n      backwardPlan = getDFTPlan plan backwardPlanID\n  fmap (DFTArray rows cols thetaFreqs rFreqs . L.concat) .\n    mapConcurrently\n      (M.mapM\n         (\\vec2 -> do\n            dftVec2 <- dftExecuteWithPlan forwardPlanID forwardPlan vec2\n            dftExecuteWithPlan backwardPlanID backwardPlan $\n              VS.zipWith (*) dftVec1 dftVec2)) .\n    divideListN numBatch $\n    vecs2\n", "meta": {"hexsha": "eb0de5ff1ae5c5838d1e6571cee80fbaa2698b90", "size": 3050, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/Multiplication.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/Multiplication.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/Multiplication.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": 41.2162162162, "max_line_length": 115, "alphanum_fraction": 0.6537704918, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.44706872491608024}}
{"text": "module Markov where\n\nimport           MusicData\nimport           Utility\n\n-- import           Numeric.LinearAlgebra (Matrix, R, (><))\n\nimport           Data.Map              (Map)\nimport qualified Data.Map              as Map (empty, insertWith, lookup)\nimport qualified Data.Map.Merge.Strict as Map' (merge, preserveMissing,\n                                                zipWithMatched)\nimport qualified Data.Map.Strict       as Strict (Map)\nimport qualified Data.Map.Strict       as Map' (difference, elems, empty,\n                                                fromList, insert, insertWith,\n                                                keys, lookup, member, toList)\nimport qualified Data.Maybe            as Maybe (fromMaybe)\nimport qualified Data.Set              as Set (fromList, size, toList)\n\n-- |representation of bigrams and containing deterministic cadence sequences\ntype Bigram  = (Cadence, Cadence)\n\n-- |representation of counts for each trigram\ntype TransitionCounts = Strict.Map Bigram Double\n\n-- -- |representations of the Markov transition matrix\n-- type TransitionMatrix = Matrix R\n\n-- |representation of markov transition matrix as key-value pairs\ntype MarkovMap = Map Cadence [(Cadence, Double)]\n\n-- |mapping from list of events into list of existing preceding bigrams\nbigrams :: [a] -> [(a, a)]\nbigrams (x:xs)\n  | length (x:xs) < 2 = []\n  | otherwise = bigram (x:xs) : bigrams xs\n  where bigram (x:y:ys) = (\\a b -> (a, b)) x y\n\n-- |lifted 'shortcut' `toCadence` which operates on a list of integer lists\ntoCadences    :: (Integral a, Num a) => [[a]] -> [Cadence]\ntoCadences xs = toCadence <$> bigrams (flatTriad <$> xs)\n\n-- |mapping from input data into all theoretically possible bigrams\npairs   :: [Cadence] -> [Bigram]\npairs xs =\n  let cs  = unique xs\n   in [ (x, y) | x <- cs, y <- cs ]\n\n-- |mapping from input data into all possible trigrams with counts of zero\nzeroCounts             :: [Cadence] -> TransitionCounts\nzeroCounts xs           =\n  let mInsert acc key = Map'.insert key 0 acc\n   in foldl mInsert Map'.empty $ pairs xs\n\n-- |mapping from input data to counts of all occurring transitions\ncadenceCounts        :: [Cadence] -> TransitionCounts\ncadenceCounts xs      =\n  let mInsert acc key = Map'.insertWith (+) key 1 acc\n   in foldl mInsert Map'.empty $ bigrams xs\n\n-- |mapping from input to counts of cadences, including 'stationary' movements\ntransitionCounts       :: [Cadence] -> TransitionCounts\ntransitionCounts xs     = mergeMaps (foldl mInsert cadences (Map'.keys diff)) zeros\n  where diff            = Map'.difference zeros cadences\n        zeros           = zeroCounts xs\n        cadences        = cadenceCounts xs\n        mergeMaps m1 m2 = Map'.merge Map'.preserveMissing Map'.preserveMissing\n                          (Map'.zipWithMatched (\\k x y -> x)) m1 m2\n        keys k          = [ (fst k, nxt) | nxt <- unique xs ]\n        newKey k        = (fst k, fst k)\n        member k        = sequenceA [ f ks | f <- [Map'.member], ks <- keys k ] (cadences)\n        mInsert acc key\n          | all (\\x -> x == False) (member key) == True =\n              Map'.insert (newKey key) 1 acc\n          | otherwise   =\n              Map'.insert key (Maybe.fromMaybe 0 $ Map'.lookup key $ cadences) acc\n\n-- |helper function for probabilityList which generates probability sublists\ntransitionProbs      :: [Cadence] -> [Double] -> [[Double]]\ntransitionProbs _ []  = []\ntransitionProbs xs ys =\n  let j               = Set.size $ Set.fromList xs\n      i               = j^2\n      xx              = take j ys\n      recurse         = drop j ys\n   in fmap (/ sum xx) xx : transitionProbs xs recurse\n\n-- |mapping from list of Cadences into list of transitions with probabilities\nprobabilityMap   :: [Cadence] -> Map Bigram Double\nprobabilityMap xs = Map'.fromList $ zip (Map'.keys $ zeroCounts xs) $ concat\n                     . transitionProbs xs $ Map'.elems $ transitionCounts xs\n\n-- -- |mapping from list of cadences into transition matrix\n-- transitionMatrix   :: [Cadence] -> TransitionMatrix\n-- transitionMatrix xs =\n--   let n             = Set.size $ Set.fromList xs\n--    in (n><n) $ Map'.elems $ probabilityMap xs :: Matrix R\n\n-- |mapping from list of cadences into map with possible next probabilities\nmarkovMap              :: [Cadence] -> MarkovMap\nmarkovMap xs            = foldl mInsert Map.empty $ pairs xs\n  where mInsert acc key = Map.insertWith (++) (fst key) (pList key) acc\n        pList key       = [(snd key, Maybe.fromMaybe 0 $ Map.lookup key pMap)]\n        pMap            = probabilityMap xs", "meta": {"hexsha": "fdd5fc22cc18de016baa7e8e7d1cb23afae18ada", "size": 4554, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Markov.hs", "max_stars_repo_name": "OscarSouth/TheHarmonicAlgorithm", "max_stars_repo_head_hexsha": "645199e958669becc1d70d9b8e75dc0729ef0e27", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 96, "max_stars_repo_stars_event_min_datetime": "2018-07-27T15:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T12:55:28.000Z", "max_issues_repo_path": "src/Markov.hs", "max_issues_repo_name": "OscarSouth/TheHarmonicAlgorithm", "max_issues_repo_head_hexsha": "645199e958669becc1d70d9b8e75dc0729ef0e27", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-08-13T08:58:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-03T18:08:01.000Z", "max_forks_repo_path": "src/Markov.hs", "max_forks_repo_name": "OscarSouth/TheHarmonicAlgorithm", "max_forks_repo_head_hexsha": "645199e958669becc1d70d9b8e75dc0729ef0e27", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-08-13T13:26:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T03:30:28.000Z", "avg_line_length": 44.213592233, "max_line_length": 90, "alphanum_fraction": 0.6144049188, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4470687187626755}}
{"text": "{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE RankNTypes #-}\n{-# OPTIONS_GHC -Wincomplete-patterns #-}\n{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\n\nmodule Num where\n\nimport AST\nimport Control.Monad.Except\nimport qualified Data.Complex as C\n\n-- --------------------------------------------------------------------------\n-- Pogger number\n-- This module implements some conversion between pogger numbers.\n-- ophan instance. Why not? Nobody will define another Num for PoggerNum\n-- Somewhere else.\n-- --------------------------------------------------------------------------\n\n-- | convert a PoggerNum to Complex\npoggerNumToComplex :: PoggerNum -> C.Complex Double\npoggerNumToComplex (Integer n) = (realToFrac n) C.:+ 0.0\npoggerNumToComplex (Real r) = r C.:+ 0.0\npoggerNumToComplex (Rational a b) = (realToFrac a / realToFrac b) C.:+ 0.0\npoggerNumToComplex (Complex a b) = a C.:+ b\n\npoggerNumToDouble :: PoggerNum -> Double\npoggerNumToDouble (Integer n) = fromIntegral n\npoggerNumToDouble (Real r) = r\npoggerNumToDouble (Rational a b) = fromIntegral a / fromIntegral b\npoggerNumToDouble (Complex _ _) = error \"Can't downgrade complex to real\"\n\n-- | Convert complex to pogger complex.\ntoPoggerComplex :: C.Complex Double -> PoggerNum\ntoPoggerComplex c = Complex (C.realPart c) (C.imagPart c)\n\n-- | Generic binary operator that handles coersion rules.\npoggerBinop :: (forall a. Num a => a -> a -> a) -> PoggerNum -> PoggerNum -> PoggerNum\npoggerBinop op = mkop\n  where\n   mkop (Integer m) (Integer n) = Integer (m `op` n)\n   mkop (Rational m n) (Rational m' n') = Rational (m `op` m') (n `op` n')\n   mkop (Real r) (Real r') = Real (r `op` r')\n   mkop (Complex m n) (Complex m' n') = Complex (m `op` m') (n `op` n')\n   mkop (Rational a b) (Integer n) = simplify $ Rational (a `op` (n * b)) b\n   mkop i@(Integer _) r@(Rational _ _) = r `op` i\n   mkop m@(Complex _ _) n = toPoggerComplex (poggerNumToComplex m `op` poggerNumToComplex n)\n   mkop m n@(Complex _ _) = m `op` n\n   mkop m@(Real _) n = (Real . C.realPart) (poggerNumToComplex m `op` poggerNumToComplex n)\n   mkop m n@(Real _) = m `op` n\n\n{-# INLINE poggerBinop #-}\n\n-- | absolute value of pogger num\n-- >>> abs (Integer 2)\n-- Integer 2\npoggerUnary :: (forall a. Num a => a -> a) -> PoggerNum -> PoggerNum\npoggerUnary op = \\case\n  Integer m -> Integer (op m)\n  Rational m n -> Rational (op m) (op n)\n  Real m -> Real (op m)\n  c@(Complex _ _) ->\n    let a = op (poggerNumToComplex c)\n     in Complex (C.realPart a) (C.imagPart a)\n\ninstance Num PoggerNum where\n  (+) = poggerBinop (+)\n  {-# INLINE (+) #-}\n\n  (*) = poggerBinop (*)\n  {-# INLINE (*) #-}\n\n  abs = poggerUnary abs\n  {-# INLINE abs #-}\n\n  negate = poggerUnary negate\n  {-# INLINE negate #-}\n\n  fromInteger = Integer\n  {-# INLINE fromInteger #-}\n\n  signum = poggerUnary signum\n  {-# INLINE signum #-}\n\n-- | division on pogger number\npoggerNumDivide :: PoggerNum -> PoggerNum -> PoggerNum\npoggerNumDivide (Real r) (Real r') = Real (r / r')\npoggerNumDivide c@(Complex _ _) c'@(Complex _ _) =\n  toPoggerComplex (poggerNumToComplex c / poggerNumToComplex c')\npoggerNumDivide (Integer m) (Integer n) = (Integer . floor) ((fromIntegral m) / (fromIntegral n))\npoggerNumDivide (Rational m n) (Rational m' n') = simplify (Rational (m * n') (n * m'))\n\n-- >>> (abs . negate) (Rational 2 3 / Rational 5 3)\n-- Rational 2 5\n-- >>> Rational 2 3 / Rational 2 6\n-- Integer 2\ninstance Fractional PoggerNum where\n  (/) = poggerNumDivide\n  {-# INLINE (/) #-}\n\n  fromRational = Real . fromRational\n  {-# INLINE fromRational #-}\n\n-- | simply rational terms.\nsimplify :: PoggerNum -> PoggerNum\nsimplify (Rational a b) =\n  let v = gcd a b\n      r@(Rational m n) = Rational (a `div` v) (b `div` v)\n   in if n == 1\n        then Integer m\n        else Rational m n\nsimplify _ = error \"trying to simply non-rational\"\n{-# INLINE simplify #-}\n\n-- | ord for pogger number\ninstance Ord PoggerNum where\n  m <= n = poggerNumToDouble m <= poggerNumToDouble n\n  {-# INLINE (<=) #-}\n\ninstance Real PoggerNum where\n  toRational (Integer n) = fromIntegral n\n  toRational (Real r) = toRational r\n  toRational (Rational a b) = fromIntegral a / fromIntegral b\n  toRational (Complex a _) = toRational a\n  {-# INLINE toRational #-}\n\ninstance Enum PoggerNum where\n  toEnum n = Integer (fromIntegral n)\n  {-# INLINE toEnum #-}\n\n  fromEnum (Integer n) = fromIntegral n\n  fromEnum _ = (-1)\n  {-# INLINE fromEnum #-}\n\n-- | pogger\ninstance Integral PoggerNum where\n  toInteger (Integer n) = n\n  toInteger (Real r) = floor r\n  toInteger (Rational a b) = floor (fromIntegral a / fromIntegral b)\n  toInteger (Complex a _) = floor a\n  {-# INLINE toInteger #-}\n\n  quotRem (Integer a) (Integer b) =\n    let (a', b') = (quotRem a b)\n     in (Integer a', Integer b')\n  quotRem a b = error (\"no division algorithm defined for\" ++ show a ++ show b)\n\n-- | Safe wrappers\nsafeQuotRem :: PoggerNum -> PoggerNum -> ThrowsError (PoggerNum, PoggerNum)\nsafeQuotRem a@(Integer _) b@(Integer _) = return (quotRem a b)\nsafeQuotRem a _ = throwError (TypeMisMatch \"can't mod on non integer values\" (Number a))\n\nsafeMod :: PoggerNum -> PoggerNum -> ThrowsError PoggerNum\nsafeMod a b = safeQuotRem a b >>= return . snd\n\nsafeDiv :: PoggerNum -> PoggerNum -> ThrowsError PoggerNum\nsafeDiv a b = safeQuotRem a b >>= return . fst\n", "meta": {"hexsha": "cc409e923dcbbf8827f209e2d8329ba08bc58646", "size": 5257, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Num.hs", "max_stars_repo_name": "ailrk/poggerscheme", "max_stars_repo_head_hexsha": "c811dc471016a587645204a5436c3c9d3e8f474f", "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/Num.hs", "max_issues_repo_name": "ailrk/poggerscheme", "max_issues_repo_head_hexsha": "c811dc471016a587645204a5436c3c9d3e8f474f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-10-22T18:15:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T08:52:46.000Z", "max_forks_repo_path": "src/Num.hs", "max_forks_repo_name": "ailrk/poggerscheme", "max_forks_repo_head_hexsha": "c811dc471016a587645204a5436c3c9d3e8f474f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4840764331, "max_line_length": 97, "alphanum_fraction": 0.6465664828, "num_tokens": 1684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4462568686006788}}
{"text": "{-# LANGUAGE OverloadedStrings, ExistentialQuantification, FlexibleContexts, TypeApplications, RecordWildCards #-}\n\nmodule Main where\n--monad-bayes\nimport Control.Monad\nimport Control.Monad.Bayes.Sampler\nimport Control.Monad.Bayes.Traced\nimport Control.Monad.Bayes.Weighted\nimport Control.Monad.Bayes.Class\n--hvega\nimport qualified Graphics.Vega.VegaLite as VL\nimport qualified Graphics.Vega.Tutorials.VegaLite as VT\n--data\nimport qualified Data.Histogram as DH\nimport Data.Text (Text, pack)\nimport Data.List (sort, partition)\nimport Data.Vector.Unboxed.Base (Unbox)\nimport qualified Data.Vector.Unboxed as Vec\n--numeric\nimport Numeric.Log\nimport Numeric.LinearAlgebra (Matrix, Vector, toList, toInt, vector, matrix, dot, (#>), (!), cmap, scalar, size)\n--src\nimport BNN\nimport PlotVL\n--csv\nimport Control.Exception (IOException)\nimport qualified Control.Exception as Exception\nimport qualified Data.Foldable as Foldable\nimport Control.Applicative\nimport qualified Data.ByteString.Lazy as BL\nimport Data.Csv\nimport qualified Data.Vector as V\n\n--Data Type\ndata Item =\n  Item\n    { idNumber :: Double,\n      date :: String,\n      new_cases :: Double\n    }\n  deriving (Eq, Show)\n\n--Decoding\ninstance FromNamedRecord Item where\n  parseNamedRecord m =\n    Item\n      <$> m .: \"idNumber\"\n      <*> m .: \"date\"\n      <*> m .: \"new_cases\"\n\ndecodeItems :: BL.ByteString -> Either String (Vector Item)\ndecodeItems = fmap snd . Data.Csv.decodeByName\n\ndecodeItemsFromFile :: FilePath -> IO (Either String (Vector Item))\ndecodeItemsFromFile filePath = catchShowIO (BL.readFile filePath) >>= return . either Left decodeItems\n\ncatchShowIO :: IO a -> IO (Either String a)\ncatchShowIO action = fmap Right action `Exception.catch` handleIOException\n  where\n    handleIOException :: IOException -> IO (Either String a)\n    handleIOException = return . Left . show\n\nfillingData :: BL.ByteString ->  [Double] -> [Data]\nfillingData csvData noise = case decodeByName csvData of\n  Left err -> putStrLn err\n  Right (_,v) -> [Data (idNumber v) ((new_cases v) + n) | n <- noise]\n\nmain :: IO ()\nmain = do\n    -- putStrLn \"Enter the number of samples to train: \"\n    -- input1 <- getLine\n    -- let nsamples = (read input1 :: Int)\n\n    putStrLn \"Enter the number of nodes: \"\n    input3 <- getLine\n    let nnodes = (read input3 :: Int)\n\n    putStrLn \"Enter the number of predicted samples: \"\n    input4 <- getLine\n    let npredictive = (read input4 :: Int)\n\n    let nsamples = 365\n    noise <- sampleIOfixed $ replicateM nsamples $ normal 0.0 0.5 \n\n    -- case decodeByName csvData of\n    --   Left err -> putStrLn err\n    --   Right (_, v) -> decodeItems\n\n    csvData <- BL.readFile \"/home/leduin/Desktop/10th Semester/Bayesian Statistics/Project/owid-covid-data-ecuador.csv\"\n    \n    let observations = fillingData csvData noise\n\n    -- let observations = case decodeByName csvData of\n    --   Left err -> putStrLn err\n    --   Right (_,v) -> [Data (idNumber v) ((new_cases v) + n) | n <- noise]\n\n-- A SIMPLE NEURAL NETWORK\n    \n    --[ Data x (0.5 * x - 2 + n)\n    --let observations = take nsamples\n    --         [ Data x (2 * sin (x) + 1 + n)\n    --         | (x, n) <- zip (map ((/(fromIntegral nsamples)) . fromIntegral ) [0, 10 ..]) noise\n    --         ]\n\n        --nnodes = 3\n        --mkSampler = prior . mh 60000\n        mkSampler = prior . mh npredictive\n    predicted <-\n        sampleIOfixed $ mkSampler $ predDist $\n        postNN (priorNN nnodes) observations\n\n    let hist = histo2D (0, 10, 10) (-10, 20, 10)\n                ((\\(nn, d) -> (xValue d, yValue d)) <$> predicted)\n        cents = Vec.toList $ DH.binsCenters $ DH.bins hist\n        val = Vec.toList $ DH.histData hist\n\n    VL.toHtmlFile \"final.html\" $\n        plot\n            (600, 300)\n            (L [imagePlot \"xModel\" \"yModel\" \"zModel\", scatterBlue \"xObs\" \"yObs\" (0, 10) (-10, 10)])\n            ( Cols\n                [ (\"xModel\", VL.Numbers (fst <$> cents)),\n                (\"yModel\", VL.Numbers (snd <$> cents)),\n                (\"zModel\", VL.Numbers val),\n                (\"xObs\", VL.Numbers (xValue <$> observations)),\n                (\"yObs\", VL.Numbers (yValue <$> observations))\n                ]\n            )\n\n    putStrLn \"Success! Check html images in directory\"", "meta": {"hexsha": "6c936187c4924967746f351a0074fb99d31755de", "size": 4228, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "leduin/Bayesian-Neural-Network", "max_stars_repo_head_hexsha": "841d684fc50d71719695fb76a11096f786867728", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "leduin/Bayesian-Neural-Network", "max_issues_repo_head_hexsha": "841d684fc50d71719695fb76a11096f786867728", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "leduin/Bayesian-Neural-Network", "max_forks_repo_head_hexsha": "841d684fc50d71719695fb76a11096f786867728", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5230769231, "max_line_length": 119, "alphanum_fraction": 0.6428571429, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.44600228301604933}}
{"text": "module ImageProcess where\n\nimport Codec.Picture\nimport Data.Vector.Storable (Vector, length, toList)\nimport Numeric.LinearAlgebra\n--import Data.ByteString\n\n\n\nimagePath :: FilePath\nimagePath = \"./test.jpg\"\n\n\ngetDynamicImage :: FilePath -> IO(Maybe DynamicImage)\ngetDynamicImage filepath = do\n  res <- readImage filepath\n  case res of\n    Left err -> print err >> return Nothing\n    Right image -> return (Just image)\n\nreadImageInfo :: DynamicImage -> Image PixelRGB8\nreadImageInfo image =\n  let imagePixel8@(Image w h rgbs) = convertRGB8 image in\n  imagePixel8\n\n\ngetImageInfo :: FilePath -> IO(Maybe (Image PixelRGB8))\ngetImageInfo filepath = do\n  res <- readImage filepath\n  case res of\n    Left err -> print err >> return Nothing\n    Right image -> return $ Just (readImageInfo image)\n  \ngetImageWidth :: Image PixelRGB8 -> Int\ngetImageWidth image =\n  let (Image w _ _) = image in\n  w\n\ngetImageHeight :: Image PixelRGB8 -> Int\ngetImageHeight image =\n  let (Image _ h _) = image in\n  h\n\ngetImageRGBs :: Image PixelRGB8 -> Data.Vector.Storable.Vector(PixelBaseComponent Pixel8)\ngetImageRGBs image =\n  let (Image _ _ rgbs) = image in\n  rgbs\n\n\nprintPixels :: Show a => [a] -> IO()\nprintPixels [] = return()\nprintPixels (xr:xg:xb:xs) =\n  print [xr, xg, xb] >>\n  printPixels xs\n\n\ngenRGBList :: (Show a, Integral a, Fractional b) => [a] -> ([b], [b], [b])\ngenRGBList [] = ([], [], [])\ngenRGBList l =\n  let func [] rlist glist blist = ((reverse rlist), (reverse glist), (reverse blist))\n      func (xr:xg:xb:xs) rlist glist blist = func xs (((fromIntegral xr)/256.0):rlist) (((fromIntegral xg)/256.0):glist) (((fromIntegral xb)/256.0):blist) in\n  func l [] [] []\n\ngenMatrixFromList :: [R] -> Int -> Int -> Maybe (Matrix R)\ngenMatrixFromList [] _ _ = Nothing\ngenMatrixFromList l w h = Just ((w >< h) l)\n\n\ntestImageProcess :: FilePath -> IO()\ntestImageProcess filepath = do\n    imageM <- getImageInfo filepath\n    case imageM of\n      Nothing -> putStrLn \"nothing..\"\n      Just imagePixel8 ->\n        putStrLn \"the width of image: \" >>\n        print (getImageWidth imagePixel8) >>\n        putStrLn \"the height ofimage: \" >>\n        print (getImageHeight imagePixel8) >>\n        print (Data.Vector.Storable.length (getImageRGBs imagePixel8)) >>\n        let rgbs = getImageRGBs imagePixel8 in\n        let w = getImageWidth imagePixel8 in\n        let h = getImageHeight imagePixel8 in\n        let rgbsList = Data.Vector.Storable.toList rgbs in\n        let (rlist, glist, blist) = genRGBList rgbsList in\n        print (Prelude.length rlist) >>\n        print (Prelude.length glist) >>\n        print (Prelude.length blist) >>\n        let Just rMat = genMatrixFromList rlist w h in\n        let Just gMat = genMatrixFromList glist w h in\n        let Just bMat = genMatrixFromList blist w h in\n        print rMat\n\n\n\n\n\n\n\n{-\n\n\ndecodeImageWidth :: IO(Maybe (Image PixelRGB8)) -> IO(Maybe Int))\ndecodeImageWidth imageM = do\n  maybeImage <- imageM\n  case maybeImage of\n    Nothing -> return Nothing\n    Just (Image w h rgbs) -> return (Just w)\n  \n\ndecodeImageHeight :: IO(Maybe(Image PixelRGB8)) -> IO(Maybe Int)\ndecodeImageHeight imageM = do\n  maybeImage <- imageM\n  case maybeImage of\n    Nothing -> return Nothing\n    Just (Image w h rgbs) -> return (Just h)\n\ndecodeImageRGBs :: IO(Maybe (Image PixelRGB8)) -> IO(Maybe (Vector(PixelBaseComponent Pixel8)))\ndecodeImageRGBs imageM = do\n  maybeImage <- imageM\n  case maybeImage of\n    Nothing -> return Nothing\n    Just (Image w h rgbs) -> return (Just rgbs)\n\n\nreadRGBsPixel8 :: Maybe DynamicImage -> IO(Maybe (Vector(PixelBaseComponent Pixel8)))\nreadRGBsPixel8 Nothing = return Nothing\nreadRGBsPixel8 (Just image) =\n  let imagePixel8@(Image _ _ rgbs) = convertRGB8 image in return (Just rgbs)\n\ngetRGBs :: FilePath -> IO(Maybe (Vector(PixelBaseComponent Pixel8)))\ngetRGBs filepath = do\n  dynamicImage <- getDynamicImage filepath\n  rgbs <- readRGBsPixel8 dynamicImage\n  return rgbs\n\n-}\n{-}\nreadRGBsPixel8 :: DynamicImage -> Maybe (Vector (PixelBaseComponent Pixel8))\nreadRGBsPixel8 (ImageY8 image@(Image _ _ rgbs)) = Just rgbs\nreadRGBsPixel8 _ = Nothing\n\nreadRGBsPixel16 :: DynamicImage -> Maybe (Vector (PixelBaseComponent Pixel16))\nreadRGBsPixel16 :: (ImageY16 image@(Image _ _ rgbs)) = Just rgbs\nreadRGBsPixel16 _ = Nothing\n\nreadRGBsPixelYF :: DynamicImage -> Maybe (Vector (PixelBaseComponent PixelF))\nreadRGBsPixelYF :: (ImageF image@(Image _ _ rgbs)) = Just rgbs\nreadRGBsPixelYF _ = Nothing\n\nreadRGBsPixelYA8 :: DynamicImage -> Maybe (Vector (PixelBaseComponent PixelYA8))\nreadRGBsPixelYA8 :: (ImageYA8 image@(Image _ _ rgbs)) = Just rgbs\nreadRGBsPixelYA8 _ = Nothing\n\nreadRGBsPixelYA16 :: DynamicImage -> Maybe (Vector (PixelBaseComponent PixelYA16))\nreadRGBsPixelYA16 :: (ImageYA16 image@(Image _ _ rgbs)) = Just rgbs\nreadRGBsPixelYA16 _ = Nothing\n\n\n\ngetRGBsImage :: forall a. Pixel a => DynamicImage -> Vector (PixelBaseComponent a)\ngetRGBsImage (ImageY8 image@(Image _ _ rgbs@(MVector (Word8 _)))) = rgbs\ngetRGBsImage (ImageY16 image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageYF image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageYA8 image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageRGB8 image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageRGB16 image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageRGBF image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageRGBA8 image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageRGBA16 image@(Image _ _ rgbs)) = rgbs \ngetRGBsImage (ImageYCbCr8 image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageCMYK8 image@(Image _ _ rgbs)) = rgbs\ngetRGBsImage (ImageCMYK16 image@(Image _ _ rgbs)) = rgbs\n\nreadRGBs :: forall a. Pixel a => FilePath  -> IO(Maybe (Vector (PixelBaseComponent a)))\nreadRGBs filepath = do\n  res <- getDynamicImage filepath\n  case res of\n    Nothing -> print \"we got nothing!\" >> return Nothing\n    Just image -> return (Just (getRGBsImage image))\n\n-}\n{-\ngetRGBs :: Image -> Vector(PixelBaseComponent Word8)\ngetRGBs (Image _ _ rgbs) = rgbs \n-}\n\njustH :: Maybe Char\njustH = do\n  (x:xs) <- Just \"Hello\"\n  return x\n", "meta": {"hexsha": "59bfb867246782a80d0968e402c3d717d053a821", "size": 5986, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "vortex/ImageProcess.hs", "max_stars_repo_name": "neutronest/vortex", "max_stars_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2016-03-16T06:51:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T05:07:06.000Z", "max_issues_repo_path": "vortex/ImageProcess.hs", "max_issues_repo_name": "neutronest/vortex", "max_issues_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vortex/ImageProcess.hs", "max_forks_repo_name": "neutronest/vortex", "max_forks_repo_head_hexsha": "1b6fa46e9e33d83513251358521f83df301675f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3403141361, "max_line_length": 157, "alphanum_fraction": 0.7026394921, "num_tokens": 1764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4458558564907495}}
{"text": "{-# LANGUAGE DataKinds                  #-}\n{-# LANGUAGE DefaultSignatures          #-}\n{-# LANGUAGE DeriveFunctor              #-}\n{-# LANGUAGE DeriveGeneric              #-}\n{-# LANGUAGE DerivingVia                #-}\n{-# LANGUAGE FlexibleContexts           #-}\n{-# LANGUAGE FlexibleInstances          #-}\n{-# LANGUAGE GADTs                      #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE RankNTypes                 #-}\n{-# LANGUAGE ScopedTypeVariables        #-}\n{-# LANGUAGE StandaloneDeriving         #-}\n{-# LANGUAGE TypeApplications           #-}\n{-# LANGUAGE TypeOperators              #-}\n{-# LANGUAGE UndecidableInstances       #-}\n\nmodule Backprop.Learn.Regularize (\n    Regularizer\n  , Regularize(..)\n  , l1Reg\n  , l2Reg\n  , noReg\n  , l2RegMetric\n  , l1RegMetric\n  -- * Build instances\n  -- ** DerivingVia\n  , RegularizeMetric(..), NoRegularize(..)\n  -- ** Linear\n  , lassoLinear, ridgeLinear\n  -- ** Generics\n  , grnorm_1, grnorm_2\n  , glasso, gridge\n  -- * Manipulate regularizers\n  , addReg\n  , scaleReg\n  ) where\n\nimport           Control.Applicative\nimport           Control.Monad.Trans.State\nimport           Data.Ratio\nimport           Data.Semigroup hiding                 (Any(..))\nimport           Data.Type.Functor.Product\nimport           Data.Type.Tuple\nimport           Data.Vinyl\nimport           GHC.Exts\nimport           GHC.Generics\nimport           GHC.TypeNats\nimport           Generics.OneLiner\nimport           Numeric.Backprop                      as B\nimport           Numeric.LinearAlgebra.Static.Backprop ()\nimport           Numeric.Opto.Update hiding            ((<.>))\nimport qualified Data.Functor.Contravariant            as Co\nimport qualified Data.Vector.Generic                   as VG\nimport qualified Data.Vector.Generic.Sized             as SVG\nimport qualified Numeric.LinearAlgebra.Static          as H\n\n-- | A regularizer on parameters\ntype Regularizer p = forall s. Reifies s W => BVar s p -> BVar s Double\n\n-- | A class for data types that support regularization during training.\n--\n-- This class is somewhat similar to @'Metric' 'Double'@, in that it\n-- supports summing the components and summing squared components.\n-- However, the main difference is that when summing components, we only\n-- consider components that we want to regularize.\n--\n-- Often, this doesn't include bias terms (terms that \"add\" to inputs), and\n-- only includes terms that \"scale\" inputs, like components in a weight\n-- matrix of a feed-forward neural network layer.\n--\n-- However, if all of your components are to be regularized, you can use\n-- 'norm_1', 'norm_2', 'lassoLinear', and 'ridgeLinear' as sensible\n-- implementations, or use DerivingVia with 'RegularizeMetric':\n--\n-- @\n-- data MyType = ...\n--   deriving Regularize via (RegularizeMetric MyType)\n-- @\n--\n-- You can also derive an instance where /no/  are regularized, using\n-- 'NoRegularize':\n--\n-- @\n-- data MyType = ...\n--   deriving Regularize via (NoRegularize MyType)\n-- @\n--\n-- The default implementations are based on 'Generics', and work for types\n-- that are records of items that are all instances of 'Regularize'.\nclass Backprop p => Regularize p where\n\n    -- | Like 'norm_1': sums all of the weights in @p@, but only the\n    -- ones you want to regularize:\n    --\n    -- \\[\n    -- \\sum_w \\lvert w \\rvert\n    -- \\]\n    --\n    -- Note that typically bias terms (terms that add to inputs) are not\n    -- regularized.  Only \"weight\" terms that scale inputs are typically\n    -- regularized.\n    --\n    -- If @p@ is an instance of 'Metric', then you can set @'rnorm_1'\n    -- = 'norm_1'@.  However, this would count /all/ terms in @p@, even\n    -- potential bias terms.\n    rnorm_1 :: p -> Double\n\n    default rnorm_1 :: (ADT p, Constraints p Regularize) => p -> Double\n    rnorm_1 = grnorm_1\n\n    -- | Like 'norm_2': sums all of the /squares/ of the weights\n    -- n @p@, but only the ones you want to regularize:\n    --\n    -- \\[\n    -- \\sum_w w^2\n    -- \\]\n    --\n    -- Note that typically bias terms (terms that add to inputs) are not\n    -- regularized.  Only \"weight\" terms that scale inputs are typically\n    -- regularized.\n    --\n    -- If @p@ is an instance of 'Metric', then you can set @'rnorm_2'\n    -- = 'norm_2'@.  However, this would count /all/ terms in @p@, even\n    -- potential bias terms.\n    rnorm_2 :: p -> Double\n\n    default rnorm_2 :: (ADT p, Constraints p Regularize) => p -> Double\n    rnorm_2 = grnorm_2\n\n    -- | @'lasso' r p@ sets all regularized components (that is, components\n    -- summed by 'rnorm_1') in @p@ to be either @r@ if that component was\n    -- positive, or @-r@ if that component was negative.  Behavior is not\n    -- defined if the component is exactly zero, but either @r@ or @-r@ are\n    -- sensible possibilities.\n    --\n    -- It must set all /non-regularized/ components (like bias terms, or\n    -- whatever items that 'rnorm_1' ignores) to zero.\n    --\n    -- If @p@ is an instance of @'Linear' 'Double'@ and 'Num', then you can set\n    -- @'lasso' = 'lassoLinear'@.  However, this is only valid if 'rnorm_1'\n    -- counts /all/ terms in @p@, including potential bias terms.\n    lasso   :: Double -> p -> p\n\n    default lasso :: (ADT p, Constraints p Regularize) => Double -> p -> p\n    lasso = glasso\n\n    -- | @'ridge' r p@ scales all regularized components (that is,\n    -- components summed by 'rnorm_2') in @p@ by @r@.\n    --\n    -- It must set all /non-regularized/ components (like bias terms, or\n    -- whatever items that 'rnorm_2' ignores) to zero.\n    --\n    -- If @p@ is an instance of @'Linear' 'Double'@ and 'Num', then you can set\n    -- @'ridge' = 'ridgeLinear'@.  However, this is only valid if 'rnorm_2'\n    -- counts /all/ terms in @p@, including potential bias terms.\n    ridge   :: Double -> p -> p\n\n    default ridge :: (ADT p, Constraints p Regularize) => Double -> p -> p\n    ridge = gridge\n\ngrnorm_1 :: (ADT p, Constraints p Regularize) => p -> Double\ngrnorm_1 = getSum . gfoldMap @Regularize (Sum . rnorm_1)\n\ngrnorm_2 :: (ADT p, Constraints p Regularize) => p -> Double\ngrnorm_2 = getSum . gfoldMap @Regularize (Sum . rnorm_2)\n\nglasso :: (ADT p, Constraints p Regularize) => Double -> p -> p\nglasso r = gmap @Regularize (lasso r)\n\ngridge :: (ADT p, Constraints p Regularize) => Double -> p -> p\ngridge r = gmap @Regularize (ridge r)\n\n-- | Backpropagatable L1 regularization; also known as lasso\n-- regularization.\n--\n-- \\[\n-- \\sum_w \\lvert w \\rvert\n-- \\]\n--\n-- Note that typically bias terms (terms that add to inputs) are not\n-- regularized.  Only \"weight\" terms that scale inputs are typically\n-- regularized.\nl1Reg :: Regularize p => Double -> Regularizer p\nl1Reg \u03bb = liftOp1 . op1 $ \\x ->\n    ( \u03bb * rnorm_1 x\n    , (`lasso` x) . (* \u03bb)\n    )\n\n-- | Backpropagatable L2 regularization; also known as ridge\n-- regularization.\n--\n-- \\[\n-- \\sum_w w^2\n-- \\]\n--\n-- Note that typically bias terms (terms that add to inputs) are not\n-- regularized.  Only \"weight\" terms that scale inputs are typically\n-- regularized.\nl2Reg :: Regularize p => Double -> Regularizer p\nl2Reg \u03bb = liftOp1 . op1 $ \\x ->\n    ( \u03bb * rnorm_2 x\n    , (`ridge` x) . (* \u03bb)\n    )\n\n-- | No regularization\nnoReg :: Regularizer p\nnoReg _ = auto 0\n\n-- | A default implementation of 'lasso' for instances of @'Linear'\n-- 'Double'@ and 'Num'.  However, this is only valid if the corresponding\n-- 'rnorm_1' counts /all/ terms in @p@, including potential bias terms.\nlassoLinear :: (Linear Double p, Num p) => Double -> p -> p\nlassoLinear r = (r .*) . signum\n\n-- | A default implementation of 'ridge' for instances of @'Linear'\n-- 'Double'@.  However, this is only valid if the corresponding\n-- 'rnorm_2' counts /all/ terms in @p@, including potential bias terms.\nridgeLinear :: Linear Double p => Double -> p -> p\nridgeLinear = (.*)\n\n-- | L2 regularization for instances of 'Metric'.  This will count\n-- all terms, including any potential bias terms.\n--\n-- You can always use this as a regularizer instead of 'l2Reg', if you want\n-- to ignore the default behavior for a type, or if your type has no\n-- instance.\n--\n-- This is what 'l2Reg' would be for a type @p@ if you declare an instance\n-- of 'Regularize' with @'rnorm_2' = 'norm_2'@, and @'ridge'\n-- = 'ridgeLinear'@.\nl2RegMetric\n    :: (Metric Double p, Backprop p)\n    => Double                   -- ^ scaling factor (often 0.5)\n    -> Regularizer p\nl2RegMetric \u03bb = liftOp1 . op1 $ \\x ->\n            ( \u03bb * quadrance x, (.* x) . (* \u03bb))\n\n-- | L1 regularization for instances of 'Metric'.  This will count\n-- all terms, including any potential bias terms.\n--\n-- You can always use this as a regularizer instead of 'l2Reg', if you want\n-- to ignore the default behavior for a type, or if your type has no\n-- instance.\n--\n-- This is what 'l1Reg' would be for a type @p@ if you declare an instance\n-- of 'Regularize' with @'rnorm_1' = 'norm_1'@, and @'lasso'\n-- = 'lassoLinear'@.\nl1RegMetric\n    :: (Num p, Metric Double p, Backprop p)\n    => Double                   -- ^ scaling factor (often 0.5)\n    -> Regularizer p\nl1RegMetric \u03bb = liftOp1 . op1 $ \\x ->\n            ( \u03bb * norm_1 x, (.* signum x) . (* \u03bb)\n            )\n\n-- | Add together two regularizers\naddReg :: Regularizer p -> Regularizer p -> Regularizer p\naddReg f g x = f x + g x\n\n-- | Scale a regularizer's influence\nscaleReg :: Double -> Regularizer p -> Regularizer p\nscaleReg \u03bb reg = (* auto \u03bb) . reg\n\n-- | Newtype wrapper (meant to be used with DerivingVia) to derive an\n-- instance of 'Regularize' that uses its 'Metric' instance, and\n-- regularizes every component of a data type, including any potential bias\n-- terms.\nnewtype RegularizeMetric a = RegularizeMetric a\n  deriving (Show, Eq, Ord, Read, Generic, Functor, Backprop)\n\ninstance (Metric Double p, Num p, Backprop p) => Regularize (RegularizeMetric p) where\n    rnorm_1 = coerce $ norm_1 @_ @p\n    rnorm_2 = coerce $ norm_2 @_ @p\n    lasso   = coerce $ lassoLinear @p\n    ridge   = coerce $ ridgeLinear @p\n\n-- | Newtype wrapper (meant to be used with DerivingVia) to derive an\n-- instance of 'Regularize' that does not regularize any part of the type.\nnewtype NoRegularize a = NoRegularize a\n  deriving (Show, Eq, Ord, Read, Generic, Functor, Backprop)\n\ninstance Backprop a => Regularize (NoRegularize a) where\n    rnorm_1 _ = 0\n    rnorm_2 _ = 0\n    lasso _   = B.zero\n    ridge _   = B.zero\n\ninstance Regularize Double where\n    rnorm_1 = id\n    rnorm_2 = (** 2)\n    lasso r = (r *) . signum\n    ridge   = (*)\n\ninstance Regularize Float where\n    rnorm_1 = realToFrac\n    rnorm_2 = (** 2) . realToFrac\n    lasso r = (realToFrac r *) . signum\n    ridge   = (*) . realToFrac\n\ninstance Integral a => Regularize (Ratio a) where\n    rnorm_1 = realToFrac\n    rnorm_2 = (** 2) . realToFrac\n    lasso r = (realToFrac r *) . signum\n    ridge   = (*) . realToFrac\n\ninstance Regularize () where\n    rnorm_1 _ = 0\n    rnorm_2 _ = 0\n    lasso _ _ = ()\n    ridge _ _ = ()\ninstance (Regularize a, Regularize b) => Regularize (a, b)\ninstance (Regularize a, Regularize b, Regularize c) => Regularize (a, b, c)\ninstance (Regularize a, Regularize b, Regularize c, Regularize d) => Regularize (a, b, c, d)\ninstance (Regularize a, Regularize b, Regularize c, Regularize d, Regularize e) => Regularize (a, b, c, d, e)\n\ninstance (Regularize a, Regularize b) => Regularize (a :# b)\ninstance Regularize a => Regularize (TF a)\n\ninstance (RPureConstrained Regularize as, ReifyConstraint Backprop TF as, RMap as, RApply as, RFoldMap as) => Regularize (Rec TF as) where\n    rnorm_1 = getSum\n            . rfoldMap getConst\n            . rzipWith coerce (rpureConstrained @Regularize (Co.Op rnorm_1))\n    rnorm_2 = getSum\n            . rfoldMap getConst\n            . rzipWith coerce (rpureConstrained @Regularize (Co.Op rnorm_2))\n    lasso r = rzipWith coerce (rpureConstrained @Regularize (Endo (lasso r)))\n    ridge r = rzipWith coerce (rpureConstrained @Regularize (Endo (ridge r)))\n\ninstance (PureProdC Maybe Backprop as, PureProdC Maybe Regularize as) => Regularize (PMaybe TF as) where\n    rnorm_1 = getSum\n            . foldMapProd getConst\n            . zipWithProd coerce (pureProdC @_ @Regularize (Co.Op rnorm_1))\n    rnorm_2 = getSum\n            . foldMapProd getConst\n            . zipWithProd coerce (pureProdC @_ @Regularize (Co.Op rnorm_2))\n    lasso r = zipWithProd coerce (pureProdC @_ @Regularize (Endo (lasso r)))\n    ridge r = zipWithProd coerce (pureProdC @_ @Regularize (Endo (ridge r)))\n\ninstance (VG.Vector v a, Regularize a, Backprop (SVG.Vector v n a)) => Regularize (SVG.Vector v n a) where\n    rnorm_1 = (`execState` 0) . SVG.mapM_ (modify . (+) . rnorm_1)\n    rnorm_2 = (`execState` 0) . SVG.mapM_ (modify . (+) . rnorm_2)\n    lasso r = SVG.map (lasso r)\n    ridge r = SVG.map (ridge r)\n\nderiving via (RegularizeMetric (H.R n)) instance KnownNat n => Regularize (H.R n)\nderiving via (RegularizeMetric (H.L n m)) instance (KnownNat n, KnownNat m) => Regularize (H.L n m)\n", "meta": {"hexsha": "1f13c0281bd07554ec4737da7f78ad51d04bf6f8", "size": 12908, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Backprop/Learn/Regularize.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "src/Backprop/Learn/Regularize.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "src/Backprop/Learn/Regularize.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 37.1988472622, "max_line_length": 138, "alphanum_fraction": 0.6401456461, "num_tokens": 3727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4457360426508707}}
{"text": "module Lights where\n\nimport Types\nimport Numeric.Vector\nimport Numeric.Scalar (fromScalar, scalar)\nimport SceneRandom\nimport Control.Monad.State\nimport Raycast\n\nsampleLight :: Vec3d -> Vec3d -> Light -> State SceneContext (Vec3d, Vec3d)\n\nsampleLight start normal (Directional angle strength direction color)  = do\n  dir <- randVecCone (angle * pi / 180) direction\n  let incidence = normal \u00b7 negate dir\n  ss <- get\n  let scene = ss_getScene ss\n  case raycast scene (Ray start (negate dir)) of\n    Just _ -> return $ (vec3 0 0 0, negate dir)\n    Nothing -> return $ (color * (fromScalar $ incidence * scalar strength), negate dir)\n  \n-- TODO: Point light sampling\nsampleLight _ _ _ = return $ (vec3 0 0 0, vec3 0 0 0)\n", "meta": {"hexsha": "a1b5aaebe8ac5b8d2c48af7b8e1b4e5cba544aad", "size": 716, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lights.hs", "max_stars_repo_name": "craigmc08/haskell-raytracer", "max_stars_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lights.hs", "max_issues_repo_name": "craigmc08/haskell-raytracer", "max_issues_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lights.hs", "max_forks_repo_name": "craigmc08/haskell-raytracer", "max_forks_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1304347826, "max_line_length": 88, "alphanum_fraction": 0.717877095, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4456288198328004}}
{"text": "{-# LANGUAGE TypeFamilies #-}\nmodule Augmentation.Braid\n    (AugBraid (AugBraid)\n    ,relations\n    ,sChar\n    ,s\n    ,relations'\n    ) where\n\nimport Algebra\nimport Augmentation.DGA\nimport Braid.Class\nimport Libs.List\n\nimport Data.List\nimport Data.Either\nimport Data.Maybe\nimport Control.Monad\nimport Data.Functor.Identity\n\nimport Numeric.LinearAlgebra\n\nimport Debug.Trace\n\nsChar :: Int -> Char\nsChar 0 = error \"s 0\"\nsChar k = toEnum $ (2*k)+459\n\ninvsChar :: Char -> Int\ninvsChar c = if fromEnum c > 459 then (fromEnum c - 459) `div` 2 else error \"invsChar: c out of bounds\"\n\ns :: Int -> Algebra\ns = G . E . sChar\n{-\nsVec :: Int -> Vector R\nsVec i = i |> [if j == (i-1) then 1 else 0 | j <- [1..]]\n-}\nbph :: StdBraid -> Int -> [Int]\nbph b@(StdBraid k w) i = nub $ sort $ take k $ iterate (bphh w) i\n\nbphh :: [Int] -> Int -> Int\nbphh [] i = i\nbphh (w:ws) i\n    | w == i = bphh ws (i+1)\n    | w == (i-1) = bphh ws (i-1)\n    | otherwise = bphh ws i\n\nextractChar :: Algebra -> Maybe Char\nextractChar (G (E c)) = Just c\nextractChar e = Nothing\n\nsVec :: Int -> Int -> Vector Z\nsVec dim i = dim |> [toEnum $ if j == i then 1 else 0 | j <- [1..]]\n\neqVec :: StdBraid -> Int -> Maybe (Vector Z)\neqVec (StdBraid w ws) i = do\n                            { let dim = length ws\n                            ; let v = sum $ zipWith (\\w x -> if w == i then sVec dim x else if w == (i-1) then negate $ sVec dim x else 0) ws [1..]\n                            ; if i > w then Nothing else Just v\n                            }\n\nrelations' :: StdBraid -> Matrix Z\nrelations' b@(StdBraid w ws) = maybe (ident $ length ws) id $ do\n                                { let basePoints = map head $ nub $ map sort $ map (bph b) [1..w]\n                                ; let dim = length ws\n                                ; vs <- mapM (eqVec b) $ filter (\\i -> not $ i `elem` basePoints) [1..w]\n                                ; mat <- if vs == [] then Nothing else Just $ fromColumns vs\n                                ; let (q,_) = thinQR $ (fromZ mat :: Matrix R)\n                                ; let qqt = q Numeric.LinearAlgebra.<> (tr q)\n                                ; n <- (\\(a,b) -> if a == b then Just a else Nothing) $ size qqt\n                                ; return $ fromColumns $ map (toZ . roundVector) $ toColumns $ 2 * ((ident n) - qqt)\n                                }\n\n{-\naddVec :: Vector R -> Vector R -> Vector R\naddVec v1 v2\n    | diff <  0 = addVec v2 v1\n    | diff == 0 = v1 + v2\n    | otherwise = v1 + (fromList $ toList v2 ++ zers)\n    where diff = (size v1) - (size v2)\n          zers = take diff repeat 0\n\neqVec :: StdBraid -> Int -> Maybe (Vector R)\neqVec (StdBraid w ws) i = do\n                            { let v = sum $ zipWith (\\w x -> if w == i then sVec x else if w == (i-1) then negate $ sVec x else fromInteger 0) ws [1..]\n                            ; if i > w then Nothing else Just v\n                            }\n\nrelations' :: StdBraid -> Maybe (Matrix R)\nrelations' b@(StdBraid w ws) = do\n                                { let vecs = map (eqVec b) [1..w]\n                                ; dim <- if [V.length $ head vecs] == (nub $ map V.length vecs) then Just $ V.length $ head vecs else Nothing\n                                ; let mat = fmap fromIntegral $ M.transpose $ foldr (\\x m -> (colVector x) <|> m) dim vecs\n                                ; let zer = zeros (nrows mat) (ncols mat)\n                                ; (_,l,p,_) <- luDecomp mat\n                                ; \n                                    \n-}\neqh :: StdBraid -> Int -> Maybe (DGA_Map,DGA_Map,DGA_Map,DGA_Map)\neqh (StdBraid _ ws) i = do\n                            { let word = zipWith (\\w x ->\n                                        if w == i\n                                            then s x\n                                            else if w == (i-1) then recip $ s x\n                                                               else 1) ws [1..]\n                            ; chars <- mapM (\\(x,t) ->\n                                    (extractChar x) >>= (\\x' -> return (x',t))) $ catMaybes $ map (\\(x,t) ->\n                                        if x == i then Just (s t,True) else if x == i-1 then Just (s t,False) else Nothing) $ zip ws [1..]\n                            ; let (s1,r1) = head chars\n                            ; let (s2,r2) = last chars\n                            ; let tword = tail word\n                            ; let iword = init word\n                            ; let prod l = if l == [] then 1 else (head l) * (prod $ tail l)\n                            ; let g1 = if r1 then recip else id\n                            ; let g2 = if r2 then recip else id\n                            ; let m11 = DGA_Map [(s1,g1 $ prod tword)]\n                            ; let m12 = DGA_Map [(s1,g1 $ prod $ reverse $ tword)]\n                            ; let m21 = DGA_Map [(s2,g2 $ prod iword)]\n                            ; let m22 = DGA_Map [(s2,g2 $ prod $ reverse $ iword)]\n                            ; return (m11,m12,m21,m22)\n                            }\n\nnst :: Int -> (a,a,a,a) -> Maybe a\nnst 0 (a,_,_,_) = return a\nnst 1 (_,a,_,_) = return a\nnst 2 (_,_,a,_) = return a\nnst 3 (_,_,_,a) = return a\nnst _ _ = Nothing\n\nrelations :: StdBraid -> Maybe [DGA_Map]\nrelations b@(StdBraid w _) = do\n                                { let basePoints = map head $ nub $ map sort $ map (bph b) [1..w]\n                                ; let solutions = catMaybes $ map (eqh b) $ filter (\\x -> not $ x `elem` basePoints) [1..w]\n                                --; let toPerm l = foldr (\\x xs -> (x `mod` 4) * (4^(length xs)) + xs) l\n                                ; let fromPerm m n = if m == 0 then [] else (fromPerm (m-1) ((n - (n `mod` 4)) `div` 4)) ++ [n `mod` 4]\n                                ; let perms = map (fromPerm (length solutions)) [0..(4^(length solutions))-1]\n                                ; let maps = nub $ catMaybes $ map (\\l -> do\n                                                    { ms <- zipWithM nst l solutions\n                                                    ; let none = DGA_Map []\n                                                    ; let left = foldl compose_maps none ms\n                                                    ; let right = foldr compose_maps none ms\n                                                    ; if left == right && (and $ map (\\x -> x == compose_maps x x) ms) then return right else Nothing\n                                                    }) perms\n                                ; return maps\n                                }\n{-\neqh :: StdBraid -> Int -> Maybe ((Char,(Algebra,Algebra)),(Char,(Algebra,Algebra)))\neqh b@(StdBraid _ ws) i = do\n                            { let word = zipWith (\\w x -> if w == i\n                                    then s x\n                                    else if w == (i-1) then recip $ s x\n                                                       else 1) ws [1..]\n                            ; c0 <- mapM (\\(x,t) -> if x == i then Just (s t,False) else if x == i-1 then Just (s t,True) else Nothing) $ filter (\\(x,_) -> (x == i) || (x == i-1)) $ zip ws [1..]\n                            ; chars <- mapM (\\(x,b) -> (extractChar x) >>= (\\x' -> return $ (x',b))) c0\n                            ; let (s1,r1) = head chars\n                            ; let (s2,r2) = last chars\n                            ; let tword = tail word\n                            ; let iword = init word\n                            ; let pre = ((s1,(product $ tword, product $ reverse $ tword)),(s2,(product $ iword,product $ reverse $ iword)))\n                            ; let g1 = if r1 then recip else id\n                            ; let g2 = if r2 then recip else id\n                            ; let f ((c1,(e11,e12)),(c2,(e21,e22))) = ((c1,(g1 e11,g1 e12)),(c2,(g2 e21, g2 e22)))\n                            ; return $ f pre\n                            }\n\nrelations :: StdBraid -> Maybe [DGA_Map]\nrelations b@(StdBraid w _) = do\n                                { let basePoints = map head $ nub $ map sort $ map (bph b) [1..w]\n                                ; solutions <- mapM (eqh b) $ filter (\\x -> not $ x `elem` basePoints) [1..w]\n                                ; let solution = catMaybes $ map (\\((c1,(a11,a12)),(c2,(a21,a22))) -> if c2 == c1 then Nothing else Just [(c1,a11),(c1,a12),(c2,a21),(c2,a22)]) solutions\n                                ; let splited = map (\\x -> compose_maps x x) $ map (\\x -> DGA_Map $ zipWith (\\l x' -> l !! x') solution x) $ permutations [0..3]\n                                ; let fixed = nub $ filter (\\x -> x == (compose_maps x x)) splited\n                                ; return fixed\n                                }\n-}\nbuildMaph :: Maybe [(Char,Algebra)] -> Maybe [(Char,Algebra)] -> Maybe [(Char,Algebra)]\nbuildMaph m m'\n    | m == m' = m\n    | otherwise = buildMaph (m >>= (\\l -> Just $ map (\\(c,x) -> (c,applyDGAMap (DGA_Map l) x)) l)) m\n\nfootprinth :: Int -> [Either (Int,Char) Int] -> [(FreeGroup,Int)]\nfootprinth _k [] = []\nfootprinth k ((Right i):xs) = (E $ toEnum k,i):(footprinth (k+1) xs)\nfootprinth k ((Left (i,c)):xs) = [(E c,i-1),(invert $ E c,i+1)] ++ (footprinth (k+1) xs)\n\niscrossh :: [Either (Int,Char) Int] -> Int -> Bool\niscrossh [] _ = False\niscrossh ((Left _):_) 0 = False\niscrossh ((Left _):_) 1 = False\niscrossh ((Right _):_) 0 = True\niscrossh ((Right _):cs) x = iscrossh cs (x-1)\niscrossh ((Left _):cs) x = iscrossh cs (x-2)\n \ndata AugBraid = AugBraid Int [Either (Int,Char) Int] -- Either element of H1(L), and its position or an integer representing the corresponding braid group element\ninstance Braid AugBraid where\n    type M AugBraid = Either (Int,Char)\n    get_word (AugBraid _ w) = w\n    algebra_footprint (AugBraid _ w) = map (\\(g,i) -> (G g,i)) $ footprinth 65 w\n    toStdBraid (AugBraid w ws) = StdBraid w (rights ws)\n    fromStdBraid (StdBraid w ws) = AugBraid w (map Right ws)\n    isCross (AugBraid _ ws) x = iscrossh ws x\n    cross_art b row (Right s) = cross_art (toStdBraid b) row (Identity s)\n    cross_art _b row (Left (s,s')) = let s1 = head $ show $ E s'\n                                         s2 = show $ invert $ E s'\n                                      in if (row - (abs $ s-1)*3) `elem` [0..3]\n                        then Just $ (case ((row-(s-1)*3) `mod` 4) of 0 -> \"---\" ++ [s1] ++ \"----\"\n                                                                     1 -> \"   \" ++  \" \" ++ \"    \"\n                                                                     2 -> \"   \" ++  \" \" ++ \"    \"\n                                                                     3 -> \"--\" ++ s2 ++ \"---\")\n                        else Nothing\ninstance Eq AugBraid where\n    (==) = equal\ninstance Show AugBraid where\n    show = showBraid\n", "meta": {"hexsha": "13766b1f0b829452a5cb899231f9cb84ec2ec15b", "size": 10819, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Augmentation/Braid.hs", "max_stars_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_stars_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "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/Augmentation/Braid.hs", "max_issues_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_issues_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-08T23:05:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T19:21:55.000Z", "max_forks_repo_path": "src/Augmentation/Braid.hs", "max_forks_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_forks_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "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": 50.3209302326, "max_line_length": 194, "alphanum_fraction": 0.4275811073, "num_tokens": 2979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4455837807463672}}
{"text": "{-# OPTIONS_GHC  -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}\n{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}\n\n\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n-- | \n-- | Module : Approximate median\n-- | Creator: Xiao Ling\n-- | Created: 12/08/2015\n-- | TODO   : test standard deviation of alpha, beta, and final version\n-- |\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n\nmodule ApproxMedian (\n\n      MaxSize\n    , Store\n\n    , aMedian\n    , aMedian'\n\n  ) where\n\n\nimport Control.Monad.Trans \nimport Control.Monad.State\nimport Control.Monad.Reader\nimport Control.Monad.Identity\n\nimport Data.Random\nimport Data.Conduit\nimport Data.Sequence \nimport Data.Foldable (toList)\nimport qualified Data.Conduit.List as Cl\n\n\nimport Core\nimport Statistics\n\n\n{-----------------------------------------------------------------------------\n  Types \n------------------------------------------------------------------------------}\n\ntype MaxSize = Int\ntype Store a = (Seq a, MaxSize)\n\n-- * Construct an empty store given max size `s`\nstore :: MaxSize -> Store a\nstore = (,) empty\n\n{-----------------------------------------------------------------------------\n  Median II\n------------------------------------------------------------------------------}\n\n-- * determine the `e`ps -approx median of a list `xs` with confidence `d`elta.\naMedian :: (Ord a, Floating a) => Eps -> Delta -> [a] -> IO a\naMedian e d xs = eval $ Cl.sourceList xs $$ toMedian $ store s\n  where eval p = fmap (median . toList) . fmap fst . flip runRVar StdRandom $ evalStateT p 0\n        s      = round $ 7/(e^2) * log (2/d)\n\n-- * `tick` up a counter for each item `a` seen\n-- * and with probability min(1, s/i) put item `a` into store `t`\ntoMedian :: Store a -> Sink a (StateT Counter RVar) (Store a)\ntoMedian t = Cl.foldM (\\t a -> tick >> t $|> a) t\n\n-- * count items seen so far\ntick :: Enum s => MonadState s m => m ()\ntick = modify succ\n\n\n-- * with probability `s/i` uniformly select an item from the store `t` and replace it with `a`\n-- * mnemonic: `|>` is insertion for Sequences, and `$f` means do f probabilistically\n($|>) :: Store a -> a -> StateT Counter RVar (Store a)\n($|>) t@(as,s) a = do\n\n  i <- get\n\n  let p = s ./ i\n  if p >= 1 then return (as |> a, s) else do\n\n      h <- lift . toss $ coin p\n\n      if isHead h then do\n          x <- lift (uniform 0 s :: RVar Int)\n          let as' = update x a as \n          return (as',s)\n      else return t\n\n\n-- * Sledghammer division \n(./) :: (Fractional a, Read a, Show s, Show i) => s -> i -> a\n(./) s i = (read . show $ s)/(read . show $ i)\n\n\n\n{-----------------------------------------------------------------------------\n  Median II\n------------------------------------------------------------------------------}\n\n-- * determine the `e`ps - approx median of a list `xs` with confidence `d`elta.\naMedian' :: (Ord a, Floating a) => Eps -> Delta -> [a] -> IO a\naMedian' e d xs = eval $ Cl.sourceList xs $$ toMedian'\n  where eval p = fmap (median . toList) . fmap fst $ runRVar (evalStateT (runStateT p 0) (store s)) StdRandom\n        s      = round $ 7/(e^2) * log (2/d)\n\n\n-- * `tick` up a counter `i` of items seen so far\n-- * and with uniform probability put the item `a` into a store `as` of max size `s`\ntoMedian' :: Sink a (StateT Counter (StateT (Store a) RVar)) (Seq a)\ntoMedian' = tick' >> do\n  ma <- await\n  case ma of\n    Nothing -> (lift . lift $ get) >>= return . fst\n    Just a  -> (lift . place $ a ) >>  toMedian'\n\n\ntick' :: (Enum s, MonadTrans t, MonadState s m) => t m ()\ntick' = lift . modify $ succ        \n\n-- * with uniform probability `s/i` select an item from the\n-- * store and re`place` it with `a`\nplace :: a -> StateT Counter (StateT (Store a) RVar) ()\nplace a = do\n\n  i        <- get\n  t@(as,s) <- lift get\n\n  let p = s ./ i\n\n  if p >= 1 then lift $ put (as |> a, s) else do\n\n      h <- lift . lift . toss $ coin p\n      case isHead h of\n        False -> lift $ put (as,s)\n        _     -> do\n          x <- lift $ lift (uniform 0 s :: RVar Int)\n          let as' = update x a as\n          lift $ put (as',s)\n\n\n{-----------------------------------------------------------------------------\n  Awaiting SO response for this stuff\n------------------------------------------------------------------------------}\n\ninstance MonadState s m => MonadState s (RVarT m) where\n  get   = lift get\n  put   = lift . put\n  state = lift . state\n\n\nfoo :: (MonadState s m, MonadRandom m) => s -> RVarT m ()\nfoo s = do \n  x <- (uniformT 0 1 :: RVarT m Double)\n  if x < 0.5 then put s else return ()\n\n\nfoo' :: (MonadState String m, MonadRandom m) => RVarT m ()\nfoo' = foo \"hello\"\n\n--foo'' :: (MonadState String m, MonadRandom m) => m ()\n--foo''= runRVarT foo' StdRandom \n\n\nbar :: (MonadTrans t1, MonadState t m, MonadState s (t1 m)) => s -> RVarT (t1 m) ()\nbar s = do \n  x <- (uniformT 0 1 :: RVarT m Double)\n  a <- lift . lift $ get\n  if x < 0.5 then put s else return ()\n\n\n-- * desired behavior with state and ranndomness\n\nbaz :: (MonadState s m, MonadReader t m) => m ()\nbaz = get >> ask >> return ()\n\nbaz1 :: MonadReader t m => m ((),Int)\nbaz1 = runStateT baz 0 \n\nbaz1' :: Identity ((),Int)\nbaz1' = runReaderT baz1 (1,\"hello\")\n\nbaz2 :: MonadState s m => m ()\nbaz2 = runReaderT baz \"hello\"\n\nbaz2' :: Identity ((),[Int])\nbaz2' = runStateT baz2 [1..10]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0fecd7894c4ff25c3aa743260b58d35edc0c667d", "size": 5730, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "depricated/ApproxMedianDep.hs", "max_stars_repo_name": "lingxiao/CIS700", "max_stars_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "depricated/ApproxMedianDep.hs", "max_issues_repo_name": "lingxiao/CIS700", "max_issues_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "depricated/ApproxMedianDep.hs", "max_forks_repo_name": "lingxiao/CIS700", "max_forks_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4162679426, "max_line_length": 122, "alphanum_fraction": 0.4937172775, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4451932878770614}}
{"text": "{-|\nModule      : ODMatrix.ElementaryDecomposition.ShortestPath\nDescription : This module is responsible for computing the shortest path between two ODMs.\n\nContains the necesary functions to measure and compare ODMs.\n\n-}\nmodule ODMatrix.ElementaryDecomposition.ShortestPath (\n      Measure\n    , sePath\n    , ev\n    , ev3\n  ) where\n\n  import Control.Monad.State.Lazy \n  --import Control.Monad.Loops (iterateUntilM)\n  \n  import Numeric.LinearAlgebra\n\n  import qualified Data.HashMap.Lazy as M\n  import qualified Data.Hashable as H\n  import Data.Maybe\n\n  \n\n  import ODMatrix.ElementaryDecomposition (ElementaryMatrix(..), ODM, \n                                       getChildren, applyElementary, \n                                       applyPath,\n                                       applicables, elementaryValue, \n                                       opposite, isNullElementary)\n\n\n  -- import Debug.Trace (trace)\n  \n\n  -- | Measure or Metric prototype\n  type Measure = Int -> Int -> Double\n\n\n  -- | Elementary Value.\n  -- Given a metric m, a in route metric mr and a scale factor alpha returns a elementary value metric.\n  ev :: Double    -- ^ Scale factor alpha\n     -> Measure   -- ^ Metric m\n     -> Measure   -- ^ In route metric mr\n     -> Measure   -- ^ Elementary value metric\n  ev a m mr i j\n    | a < 0 = error \"The ajustment parameter must be greater than 0.\"\n    | otherwise = m i j + a * mr i j\n\n\n\n  -- | Shortest Path\n  -- Computes the sequence of elementary matrices between ODMs\n  sePath :: Measure             -- ^ Elementary value metric\n         -> ODM                 -- ^ Source ODM\n         -> ODM                 -- ^ Target ODM\n         -> [ElementaryMatrix]  -- ^ Sequence of elementary matrices in the shortest path\n  sePath m a b = evalState _process (_initialSEPState m a b)\n\n\n\n  -- | Map a Elementary Matrix to it related cells indexes\n  emc :: ElementaryMatrix -> (Int, Int)\n  emc (Elementary _ (cell1, _) (cell2, _)) = (cell1,cell2)\n\n\n\n  -- | Compares two ODMs\n  odmc :: (Matrix Double -> Double) -- ^ Function g to compute the remainder\n       -> Measure                   -- ^ Elementary value metric\n       -> Double                    -- ^ Scale factor\n       -> ODM                       -- ^ ODM A\n       -> ODM                       -- ^ ODM B\n       -> Double                    -- ^ Difference between A and B\n  odmc g ev beta a b = beta * g s + sum [ev i j | (i,j) <- sp]\n    where p = sePath ev a b\n          sp = map emc . filter (not . isNullElementary) $ p\n          s = b - applyPath a p -- Remainder\n\n\n\n\n  newtype HashMatrix = HashMatrix { hm :: ODM }\n\n  instance Show HashMatrix where\n    show (HashMatrix m) = show m\n\n  instance Eq HashMatrix where\n    (==) (HashMatrix a) (HashMatrix b) = a == b\n  \n  instance H.Hashable HashMatrix where\n    hashWithSalt salt (HashMatrix m) = floor $ m `atIndex` (salt `mod` rows m, salt `mod` cols m)\n\n\n  \n  \n\n\n\n\n\n\n\n  data SEP = SEP {\n      dist      :: M.HashMap HashMatrix Double\n    , prev      :: M.HashMap HashMatrix ElementaryMatrix\n    , visited   :: [ODM]\n    , target    :: ODM\n    , measure   :: Measure\n    } \n\n  instance Show SEP where\n    show = show . visited \n\n  \n  \n\n\n  \n  \n\n\n  -- | Elementary Value 3 (See the paper).\n  -- This is a special case of elementary value computed with only one metric.\n  -- Only works for regular grids.\n  ev3 :: Double -> Measure -> Measure\n  ev3 a m i j\n    | a <= 0 || a >= 1 = error \"The ajustment parameter a must be 0 < a < 1.\"\n    | otherwise = a * m i j + (1-a) * sum [ m k (k+1) | k <- [min i j .. max i j] ]\n\n\n\n  -- TODO: Implement metrics.\n\n  _initialSEPState :: Measure -> ODM -> ODM -> SEP\n  _initialSEPState m src trg = SEP (M.singleton (HashMatrix src) 0) M.empty [] trg m\n \n\n  -- | TODO: take out the harcoded 60.\n  -- | MAYBE IF IN THE FINAL STEP ASK FOR NEIGHBORS EMPTY.\n  _process :: State SEP [ElementaryMatrix]  \n  _process = do\n    s <- get\n    let (curr,d) = _getNext (dist s)\n        neighbors = applicables (0,60) curr . getChildren $ (target s) - curr\n        -- Filter out the visited neighbors\n        unvisited = filter (\\e -> applyElementary curr e `notElem` visited s) neighbors\n    -- Calculate min distance to all neighbors (unvisited)\n    modify $ minAndPrev curr d unvisited \n    -- \\t -> t {dist = foldr (mindist (measure t) curr d) (dist t) unvisited}\n    -- Add current to the previous of unvisited \n    \n    -- Mark the current as visited.\n    modify $ \\t -> t {dist = M.delete (HashMatrix curr) (dist t), \n                      visited = curr:visited t}\n    sn <- get\n    if curr == (target sn) || null neighbors  then return . fst $ _wrapUp curr sn else _process\n    -- if curr == (target sn) then return . fst $ _wrapUp curr sn else _process\n  \n\n  -- Calculate the min distance and the corresponding previous.\n  minAndPrev :: ODM -> Double -> [ElementaryMatrix] -> SEP -> SEP\n  minAndPrev curr d unvisited t = foldr f t nds\n    where nds = map (neighborsDists t curr d) unvisited\n          f (md,k,e) s = s { dist = M.insert k md (dist s),\n                             prev = M.insert k e (prev s) }\n                  \n\n  \n  neighborsDists :: SEP                           -- ^ Final state\n                 -> ODM                           -- ^ Current\n                 -> Double                        -- ^ Dist from origin\n                 -> ElementaryMatrix              -- ^ Neighbor\n                 -> (Double,HashMatrix,ElementaryMatrix)     -- ^ Min distance and Neighbor\n  neighborsDists s m d e = (min newd oldd, k, e)\n    where newd = d + elementaryValue (measure s) e\n          oldd = M.lookupDefault newd k (dist s)\n          k = HashMatrix $ applyElementary m e\n  \n\n  \n   \n\n  -- | Get next matrix to process and the shortest distance from src\n  _getNext :: M.HashMap HashMatrix Double -- ^ List of distances by ODM\n           -> (ODM,Double)                -- ^ ODM with min distance and the distance\n  _getNext ds \n    | null ds = error \"Not destination found\"\n    | otherwise = (\\(m,d) -> (hm m, d)) $ M.foldrWithKey f initial ds\n    where initial = head . M.toList $ ds            -- (k,v)\n          f k v mn@(_, minv) | v < minv = (k,v)\n                             | otherwise = mn\n\n  \n  _wrapUp :: ODM -> SEP -> ([ElementaryMatrix],SEP)\n  _wrapUp m s = (es, s)\n    where p = M.lookup (HashMatrix m) (prev s)\n          --op e = e {sign = - sign e}\n          odm = (\\x -> applyElementary m (opposite x)) <$> p\n          es = maybe [] (\\x -> fromJust p : fst (_wrapUp x s)) odm\n  \n\n\n  -- _testMatrix :: ODM\n  -- _testMatrix = matrix 10 [0,0,0,1,0,0,0,0,0,0,0,2,1,0,1,3,0,0,0,0,0,0,2,0,0,4,1,0,1,0,0,0,0,1,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\n  -- _testSimMatrix :: ODM\n  -- _testSimMatrix = matrix 10 [0,0,1,0,0,0,0,0,0,0,0,2,0,1,1,3,0,0,0,0,0,0,2,0,0,4,1,0,1,0,0,0,0,1,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\n  -- _testDifMatrix :: ODM\n  -- _testDifMatrix = matrix 10 [0,0,0,1,0,0,0,0,0,0,0,2,1,0,1,3,0,0,0,0,0,0,2,0,0,4,2,0,0,0,0,0,0,1,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]", "meta": {"hexsha": "2af9fcd3f3ca5316f549020b7ce4b88eec7fc1e8", "size": 7254, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ODMatrix/ElementaryDecomposition/ShortestPath.hs", "max_stars_repo_name": "renecura/odmatrix", "max_stars_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ODMatrix/ElementaryDecomposition/ShortestPath.hs", "max_issues_repo_name": "renecura/odmatrix", "max_issues_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ODMatrix/ElementaryDecomposition/ShortestPath.hs", "max_forks_repo_name": "renecura/odmatrix", "max_forks_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3791469194, "max_line_length": 233, "alphanum_fraction": 0.5624483044, "num_tokens": 2362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.445193280902399}}
{"text": "{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Matrix.Traversable\n  (\n    matrixTraverse\n  ) where\n\nimport Numeric.LinearAlgebra.HMatrix hiding (corr)\n\nimport Data.Traversable\n\nimport Util.Tuples\n\n-- Matrix cannot be an instance of Functor, so it cannot be an instance of traversable\n-- instead, convert to list and use the list traverse\nmatrixTraverse :: (Element b, Element c) => (a -> b -> (a,c)) -> a -> Matrix b -> (a, Matrix c)\nmatrixTraverse f a m = applySnd (fromLists) $ mapAccumL (mapAccumL f) a (toLists m)\n", "meta": {"hexsha": "8aa4c873117c99e380cd0d5644340777480b9544", "size": 543, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Matrix/Traversable.hs", "max_stars_repo_name": "eklinkhammer/neural-algorithms", "max_stars_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Matrix/Traversable.hs", "max_issues_repo_name": "eklinkhammer/neural-algorithms", "max_issues_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Matrix/Traversable.hs", "max_forks_repo_name": "eklinkhammer/neural-algorithms", "max_forks_repo_head_hexsha": "40ba7cd6ac293f9355fe086c1bd4be064c87fc8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5789473684, "max_line_length": 95, "alphanum_fraction": 0.7127071823, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.44503174950540164}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\n-- :set -fobject-code in GHCi\nmodule Picture where\n\nimport Foreign hiding (rotate)\nimport Foreign.C.Types\n\nimport Control.Applicative\n\nimport Data.Complex\n\ndefault (Int, Float, Integer)\n\n-- Strict\ndata Color =\n  Color\n    { r, g, b, a :: !Float\n    }\n  deriving (Show)\n\ndata CColor =\n  CColor\n    { rC, gC, bC :: !CUChar\n    }\n  deriving (Show)\n\ninstance Storable CColor where\n  alignment _ = 1\n  sizeOf _ = 3\n  peek ptr =\n    CColor <$> peekByteOff ptr 0 <*> peekByteOff ptr 1 <*> peekByteOff ptr 2\n  poke ptr (CColor d c i) = do\n    pokeByteOff ptr 0 d\n    pokeByteOff ptr 1 c\n    pokeByteOff ptr 2 i\n\ntype Point = (Float, Float)\n\ntype Image a = Point -> a\n\ntype Region = Image Bool\n\ntype Filter c = Image c -> Image c\n\ntype FilterC = Filter Color\n\ntype ImageC = Image Color\n\nrenderRegion :: Region -> Image Color\nrenderRegion r p =\n  if r p\n    then black\n    else white\n\ncOver :: Color -> Color -> Color\ncOver (Color r1 g1 b1 a1) (Color r2 g2 b2 a2) =\n  Color (h r1 r2) (h g1 g2) (h b1 b2) (h a1 a2)\n  where\n    h x1 x2 = x1 + (1 - a1) * x2\n\nbilerpBRBW = bilerpC black red blue white\n\nbilerpC ll lr ul ur (wx, wy) = lerpC wy (lerpC wx ll lr) (lerpC wx ul ur)\n\nover :: ImageC -> ImageC -> ImageC\ntop `over` bot = \\p -> top p `cOver` bot p\n\ninstance Semigroup Color where\n  (<>) = cOver\n\ninstance Monoid Color where\n  mempty = invisible\n\ninvisible = Color 0 0 0 0\n\nblack = Color 0 0 0 1\n\nwhite = Color 1 1 1 1\n\nred = Color 1 0 0 1\n\ngreen = Color 0 1 0 1\n\nblue = Color 0 0 1 1\n\nyellow = Color 1 1 0 1\n\ncond :: Image Bool -> Image c -> Image c -> Image c\ncond =\n  liftA3\n    (\\a b c ->\n       if a\n         then b\n         else c)\n\nlerpI :: Image Frac -> ImageC -> ImageC -> ImageC\nlerpI = liftA3 lerpC\n\nempty = const invisible\n\nwhiteI = const white\n\nblackI = const black\n\nredI = const red\n\nblueI = const blue\n\ngreenI = const green\n\nyellowI = const yellow\n\nblackWhiteIm reg = cond reg blackI whiteI\n\nblueYellowIm reg = cond reg blueI yellowI\n\ncrop :: Region -> FilterC\ncrop reg im = cond reg im mempty\n\ntype Warp = Point -> Point\n\ntype Vector = (Float, Float)\n\ntranslateP :: Vector -> Warp\ntranslateP (dx, dy) (x, y) = (x + dx, y + dy)\n\nscaleP :: Vector -> Warp\nscaleP (sx, sy) (x, y) = (sx * x, sy * y)\n\nuscaleP :: Float -> Warp\nuscaleP s = scaleP (s, s)\n\nrotateP :: Float -> Warp\nrotateP \u03b8 (x, y) = (x * cos \u03b8 - y * sin \u03b8, y * cos \u03b8 + x * sin \u03b8)\n\nudisk :: Region\nudisk p = distO p < 1\n\ninvWarp warp im = im . warp\n\ntranslate :: Vector -> Filter c\ntranslate (dx, dy) = invWarp (translateP (-dx, -dy))\n\nscale :: Vector -> Filter c\nscale (sx, sy) = invWarp (scaleP (1 / sx, 1 / sy))\n\n-- Laws\n-- uscale x . uscale y = uscale (x * y)\nuscale :: Float -> Filter c\nuscale s = invWarp (uscaleP (1 / s))\n\nrotate :: Float -> Filter c\nrotate \u03b8 = invWarp (rotateP (-\u03b8))\n\nswirlP :: Float -> Warp\nswirlP r p = rotateP (distO p * (2 * pi / r)) p\n\nswirl :: Float -> Filter c\nswirl r = invWarp (swirlP (-r))\n\nsquare n (x, y) = abs x <= n / 2 && abs y <= n / 2\n\n-- Figure to visually check orientation\ndisks =\n  renderRegion $\n  f <$> udisk <*> translate (2, 2) udisk <*> translate (3, 2) udisk <*> vstrip\n  where\n    f a b c d = a || b || c || d\n\n-- Figures from \"Functional Images\" by Conal Elliot.\nfig1 = renderRegion $ vstrip\n\nfig2 = renderRegion $ checker\n\nfig3 = renderRegion $ altRings\n\nfig4 = renderRegion $ polarChecker 10\n\nfig5 = renderRegion $ uscale 0.05 gasket\n\nfig6 = renderFrac $ wavDist\n\nfig7 = bilerpBRBW\n\nfig8 = lerpI wavDist (blackWhiteIm (polarChecker 10)) (blueYellowIm checker)\n\nfig9 = ybRings\n\nfig10 = renderRegion udisk\n\nfig11 = renderRegion $ swirl 1 vstrip\n\nfig13 t = renderRegion (swirlingXPos t)\n\nfig14 = renderRegion $ annulus 0.5\n\nfig17 = renderRegion $ shiftXor 2.6 altRings\n\nfig18 = renderRegion $ xorgon 8 (7 / 4) altRings\n\n-- Typo in original paper, 0.2 5 should be 0.25\nfig19 = crop (wedgeAnnulus 0.25 10) ybRings\n\nfig20 = crop (swirl 2 (wedgeAnnulus 0.25 10)) ybRings\n\nfig22 = translate (-20, -20) tiledBilerp\n\nfig23 = renderRegion $ uscale 3.5 (radInvert checker)\n\nfig24 = rippleRad 8 0.3 ybRings\n\nfig25 = \\t -> rippleRad 8 (cos t / 2) ybRings\n\nfig26 = rippleRad 8 0.3 $ cropRad 1 $ ybRings\n\nfig27 = cropRad 1 $ rippleRad 8 0.3 $ ybRings\n\nfig28 = swirl 8 $ rippleRad 5 0.3 $ cropRad 5 $ ybRings\n\n-- Typo in original paper, washer (1/2) (pi/2) 1 tiledBilerp\n-- TODO: Fix visual mismatch with paper.\nfig32 = washer (1 / 2) (pi / 2) tiledBilerp\n\n-- Convert an image to a static animation.\nstatic :: Image c -> Anim c\nstatic = const\n\n-- The main animation to run.\n-- mainAnim = static . renderFrac $ mandel\nmainAnim :: Anim Color\nmainAnim = fig32\n\ncalculate (x, y, t) = adjust (mainAnim t') (x', y')\n  where\n    duration = 5000 -- Duration of the animation in ms\n    range = 2 * pi -- Time range of the animation\n    -- Time normalized from 0 to 1\n    normalizedTime = fromIntegral (t `mod` duration) / fromIntegral duration\n    scaledTime = range * normalizedTime\n    -- scaledTime = fromIntegral t / 10000\n    (x', y', t') = (fromIntegral x, fromIntegral y, scaledTime)\n    adjust = adjustToWindow\n    -- Adjust an image to a window, by translating, scaling and flipping\n    adjustToWindow :: Filter c\n    adjustToWindow =\n      translate (screenWidth / 2, screenHeight / 2) .\n      uscale 60 . flipY\n    flipY p (x, y) = p (x, -y)\n\n(screenWidth, screenHeight) = (640, 480)\n\nforeign export ccall fillPixelBuffer :: Ptr CColor -> CInt -> IO ()\nfillPixelBuffer arr t = pokeArray arr (map calc l1)\n  where\n    l1 = [(x, y) | y <- [0 .. screenHeight - 1], x <- [0 .. screenWidth - 1]]\n    calc (x, y) =\n      CColor (truncate (255 * r)) (truncate (255 * g)) (truncate (255 * b))\n      where\n        Color r g b _ = calculate (x, y, t)\n\nchecker :: Region\nchecker (x, y) = even (floor x + floor y)\n\nvstrip :: Region\nvstrip (x, y) = abs x <= 1 / 2\n\noverlay :: ImageC -> ImageC -> ImageC\noverlay = liftA2 (<>)\n\n-- Sierpinski triangle\ngasket :: Region\ngasket (x, y) = floor x .|. floor y == (floor x :: Integer)\n\naltRings p = even (floor (distO p))\n\ndistO (x, y) = sqrt (x * x + y * y)\n\ntype Frac = Float -- in [0, 1]\n\nwavDist :: Image Frac\nwavDist p = (1 + cos (pi * distO p)) / 2\n\nybRings = lerpI wavDist blueI yellowI\n\nrenderFrac :: Image Frac -> ImageC\nrenderFrac f (x, y) = lerpC (f (x, y)) black white\n\nlerpC :: Frac -> Color -> Color -> Color\nlerpC w (Color r1 g1 b1 a1) (Color r2 g2 b2 a2) =\n  Color (h r1 r2) (h g1 g2) (h b1 b2) (h a1 a2)\n  where\n    h x1 x2 = w * x1 + (1 - w) * x2\n\nlighten x c = lerpC x c white\n\ndarken x c = lerpC x c black\n\ntype PolarPoint = (Float, Float)\n\nfromPolar :: Point -> PolarPoint\nfromPolar (\u03c1, \u03b8) = (\u03c1 * cos \u03b8, \u03c1 * sin \u03b8)\n\ntoPolar :: PolarPoint -> Point\ntoPolar (x, y) = (distO (x, y), atan2 y x)\n\npolarChecker :: Int -> Region\npolarChecker = polarize checker\n\npolarize :: Image c -> Int -> PolarPoint -> c\npolarize pat n = pat . sc . toPolar\n  where\n    sc (\u03c1, \u03b8) = (\u03c1, \u03b8 * n' / \u03c0)\n    \u03c0 = pi\n    n' = fromIntegral n\n\n-- Animations\ntype Time = Float\n\ntype Anim c = Time -> Image c\n\nswirlingXPos :: Anim Bool\nswirlingXPos t = swirl (t * t) xPos\n\nxPos :: Region\nxPos (x, y) = x > 0\n\n-- Region algebra\nintersect :: Region -> Region -> Region\nintersect = liftA2 (&&)\n\nunion :: Region -> Region -> Region\nunion = liftA2 (||)\n\nxorR :: Region -> Region -> Region\nxorR = liftA2 xor\n  where\n    xor True b = not b\n    xor _ b = b\n\ncompR :: Region -> Region\ncompR = fmap not\n\nuniverseR :: Region\nuniverseR = const True\n\nemptyR :: Region\nemptyR = const False\n\nr \\\\ r' = r `intersect` compR r'\n\nannulus :: Frac -> Region\nannulus inner = udisk \\\\ uscale inner udisk\n\nradReg :: Int -> Region\nradReg n = test . toPolar\n  where\n    test (r, a) = even (floor (a * fromIntegral n / pi))\n\nwedgeAnnulus :: Frac -> Int -> Region\nwedgeAnnulus inner n = annulus inner `intersect` radReg n\n\nshiftXor :: Float -> Region -> Region\nshiftXor r reg = reg' r `xorR` reg' (-r)\n  where\n    reg' d = translate (d, 0) reg\n\n-- Typo in the original paper, missing argument g\nxorgon :: Int -> Float -> Region -> Region\nxorgon n r g = xorRs (rf <$> [0 .. n - 1])\n  where\n    rf :: Int -> Region\n    rf i = translate (fromPolar (r, a)) g\n      where\n        a = fromIntegral i * 2 * pi / fromIntegral n\n\nxorRs :: [Region] -> Region\nxorRs = foldr xorR emptyR\n\ntileP :: Vector -> Warp\ntileP (w, h) (x, y) = (wrap' w x, wrap' h y)\n\ntiledBilerp = about (1 / 2, 1 / 2) (tile (1, 1)) bilerpBRBW\n\ntype HyperFilter c = Filter c -> Filter c\n\nabout :: Point -> HyperFilter c\nabout (x, y) filt = translate (x, y) . filt . translate (-x, -y)\n\nwrap :: Float -> Float -> Float\nwrap w x = w * fracPart (x / w)\n  where\n    fracPart t = t - fromIntegral (truncate t)\n\nwrap' :: Float -> Float -> Float\nwrap' w x = wrap w (x + w / 2) - w / 2\n\ntile :: Vector -> Filter c\ntile size = invWarp (tileP size)\n\nswirlP' r = polarWarp (\\(\u03c1, \u03b8) -> (\u03c1, \u03b8 + \u03c1 * (2 * pi / r)))\n\npolarWarp warp = fromPolar . warp . toPolar\n\nradInvertP :: Warp\nradInvertP = polarWarp (\\(\u03c1, \u03b8) -> (1 / \u03c1, \u03b8))\n\nradInvert :: Filter c\nradInvert = invWarp radInvertP\n\nrippleRadP :: Int -> Float -> Warp\nrippleRadP n s =\n  polarWarp $ (\\(\u03c1, \u03b8) -> (\u03c1 * (1 + s * sin (fromIntegral n * \u03b8)), \u03b8))\n\nrippleRad :: Int -> Float -> Filter c\nrippleRad n s = invWarp (rippleRadP n (-s))\n\ncropRad :: Float -> FilterC\ncropRad r = crop (uscale r udisk)\n\nwiggleRotateP :: Float -> Float -> Time -> Warp\nwiggleRotateP cycles \u03b8max t = polarWarp warp\n  where\n    warp (r, a) = (r, a + \u03b8max * sin (t + dt))\n      where\n        dt = 2 * pi * cycles * (r - 1 / 2)\n\nwiggleRotate :: Float -> Float -> Time -> Filter c\nwiggleRotate cycles \u03b8max t = invWarp (wiggleRotateP cycles \u03b8max t)\n\nwasher :: Float -> Float -> ImageC -> Time -> ImageC\nwasher cycles \u03b8max im t = cropRad 1 $ wiggleRotate cycles \u03b8max t $ im\n\n-- Constants\nmaxIter :: Int -- Max iterations\nmaxIter = 750\n\nwidth :: Int -- Image width\nheight :: Int -- Image height\nwidth = 400\n\nheight = 400\n\n-- Note: aspect ratio of (minX, minY), (maxX, maxY) must\n-- match aspect ratio of (width, height)\nminX :: Float -- Min x-coordinate of graph\nmaxX :: Float -- Max x-coordinate of graph\nminY :: Float -- Min y-coordinate of graph\nmaxY :: Float -- Max y-coordinate of graph\n-- For the zoomed in part of the Mandelbrot:\n--minX = -0.826341244461360116\n--maxX = -0.8026423086165848822\n--minY = -0.2167936114403439588\n--maxY = -0.193094675595568725\n--For a full view of the mandelbrot\nminX = -2.5\n\nmaxX = 1.5\n\nminY = -2\n\nmaxY = 2\n\n-- The actual fractal part. It basically works on a matrix, which we\n-- will call M, that represents a grid of points on the\n-- graph. Essentially, M[i, j] is (xList[j], yList[i])\nxList :: [Float]\nyList :: [Float]\nxList = [minX,(minX + ((maxX - minX) / (fromIntegral width - 1))) .. maxX]\n\nyList =\n  reverse [minY,(minY + ((maxY - minY) / (fromIntegral height - 1))) .. maxY]\n\netaFraction :: Complex Float -> Float\netaFraction z = (log (log (magnitude z))) / log 2\n\nsmoothEta :: Int -> Complex Float -> Float -- Smooth escape time algorithm value\nsmoothEta iter z = (fromIntegral iter - etaFraction z) / fromIntegral maxIter\n\n-- Gets the color for the point, in range [0, 1]\ncolor :: Int -> Complex Float -> Float\ncolor iter z = smoothEta iter z -- Smooth escape time algorithm (and invert)\n\n-- color iter z = fromIntegral iter / fromIntegral maxIter\ninterpolate :: Float -> Int -- Adds an interpolation curve for interpolating color\ninterpolate v = truncate ((v ^ 12) * 255) -- Polynomial curve\n\n-- interpolate v = chr (truncate(v * 255)) -- Linear\n-- The actual fractal algorithm!\nfrac :: Complex Float -> Complex Float -> Int -> Int\nfrac c@(x :+ y) z iter\n  | iter >= maxIter = 255 -- never escaped, return color value of 255\n  | let p = sqrt ((x - 0.25) ^ 2 + y ^ 2)\n     in x <= p - 2 * p ^ 2 + 0.25 && (x + 1) ^ 2 + y ^ 2 <= 0.625 = 255\n  | otherwise =\n    let z' = z * z + c\n     in if ((realPart z') * (realPart z') + (imagPart z') * (imagPart z')) > 4\n          then interpolate (color iter z')\n          else frac c z' (iter + 1)\n\nmandel :: Image Frac\nmandel (x, y) = fromIntegral (frac (x :+ y) (0 :+ 0) 0) / 255\n\n-- dotGridGradient :: Int -> Int -> Float -> Float -> IO Float\n-- dotGridGradient ix iy x y = do\n--   (v1, v2) <- do p' <- randomIO :: IO Float\n--                  let (_, p) = properFraction p'\n--                  pure (p, sqrt (1 - p ^ 2))\n--   let c1 = dx * v1\n--   let c2 = dy * v2\n--   let res = (c1 + c2)\n--   -- print res\n--   pure res\n--   where\n--     dx = x - fromIntegral ix\n--     dy = y - fromIntegral iy\n\n-- perlin :: Image (IO Frac)\n-- perlin (x, y) = do\n--   let (x0, sx) = properFraction x\n--   let (y0, sy) = properFraction y\n--   let x1 = x0 + 1\n--   let y1 = y0 + 1\n--   n0 <- dotGridGradient x0 y0 x y\n--   n1 <- dotGridGradient x1 y0 x y\n--   let ix0 = lerp n0 n1 sx\n--   n0' <- dotGridGradient x0 y1 x y\n--   n1' <- dotGridGradient x1 y1 x y\n--   let ix1 = lerp n0' n1' sx\n--   let res' = lerp ix0 ix1 sy\n--   let res = abs res'\n--   pure res\n--   where\n--     lerp a0 a1 w = (1.0 - w) * a0 + w * a1\n", "meta": {"hexsha": "5f12ddbcb0b74932b60cedf95d79013c18fa635b", "size": 12945, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Picture.hs", "max_stars_repo_name": "siraben/functional-images", "max_stars_repo_head_hexsha": "e7fd95ea6a4204ba688421885646d0191b5047a1", "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": "Picture.hs", "max_issues_repo_name": "siraben/functional-images", "max_issues_repo_head_hexsha": "e7fd95ea6a4204ba688421885646d0191b5047a1", "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": "Picture.hs", "max_forks_repo_name": "siraben/functional-images", "max_forks_repo_head_hexsha": "e7fd95ea6a4204ba688421885646d0191b5047a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.151119403, "max_line_length": 82, "alphanum_fraction": 0.6246427192, "num_tokens": 4504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.4447905455930102}}
{"text": "{-# LANGUAGE BangPatterns          #-}\n{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE FlexibleContexts      #-}\n\n-- This is a simple generative adversarial network to make pictures\n-- of numbers similar to those in MNIST.\n--\n-- It demonstrates a different usage of the library. Within about 15\n-- minutes it was producing examples like this:\n--\n--               --.\n--     .=-.--..#=###\n--     -##==#########.\n--     #############-\n--   -###-.=..-.-==\n--   ###-\n--   .###-\n--   .####...==-.\n--   -####=--.=##=\n--   -##=-     -##\n--             =##\n--           -##=\n--           -###-\n--         .####.\n--         .#####.\n-- ...---=#####-\n-- .=#########.         .\n--   .#######=.          .\n--     . =-.\n--\n-- It's a 5!\n--\nimport           Control.Applicative\nimport           Control.Monad\nimport           Control.Monad.Random\n\nimport           Codec.Compression.GZip ( decompress )\nimport           Data.Serialize ( Get )\nimport qualified Data.Serialize as Serialize\nimport qualified Data.ByteString.Lazy as B\n\nimport           Data.List ( foldl' )\nimport           Data.List.Split ( chunksOf )\nimport           Data.Maybe ( fromMaybe )\n#if ! MIN_VERSION_base(4,13,0)\nimport           Data.Semigroup ( (<>) )\n#endif\n\nimport           Data.Word ( Word32 , Word8 )\nimport qualified Data.Vector.Storable as V\n\nimport qualified Numeric.LinearAlgebra.Static as SA\nimport           Numeric.LinearAlgebra.Data ( toLists )\n\nimport           Options.Applicative\nimport           System.FilePath ( (</>) ) \n\nimport           Grenade\nimport           Grenade.Utils.OneHot\n\ntype Discriminator =\n  Network\n    '[ Convolution 1 10 5 5 1 1, Pooling 2 2 2 2, Relu\n     , Convolution 10 16 5 5 1 1, Pooling 2 2 2 2, Relu\n     , Reshape, FullyConnected 256 80, Logit, FullyConnected 80 1, Logit]\n    '[ 'D2 28 28\n     , 'D3 24 24 10, 'D3 12 12 10, 'D3 12 12 10\n     , 'D3 8 8 16, 'D3 4 4 16, 'D3 4 4 16\n     , 'D1 256, 'D1 80, 'D1 80, 'D1 1, 'D1 1]\n\ntype Generator =\n  Network\n    '[ FullyConnected 80 256, Relu, Reshape\n     , Deconvolution 16 10 5 5 2 2, Relu\n     , Deconvolution 10 1 8 8 2 2, Logit]\n    '[ 'D1 80\n     , 'D1 256, 'D1 256, 'D3 4 4 16\n     , 'D3 11 11 10, 'D3 11 11 10\n     , 'D2 28 28, 'D2 28 28 ]\n\nrandomDiscriminator :: MonadRandom m => m Discriminator\nrandomDiscriminator = randomNetwork\n\nrandomGenerator :: MonadRandom m => m Generator\nrandomGenerator = randomNetwork\n\ntrainExample :: LearningParameters -> Discriminator -> Generator -> S ('D2 28 28) -> S ('D1 80) -> ( Discriminator, Generator )\ntrainExample rate discriminator generator realExample noiseSource\n = let (generatorTape, fakeExample)       = runNetwork generator noiseSource\n\n       (discriminatorTapeReal, guessReal) = runNetwork discriminator realExample\n       (discriminatorTapeFake, guessFake) = runNetwork discriminator fakeExample\n\n       (discriminator'real, _)            = runGradient discriminator discriminatorTapeReal ( guessReal - 1 )\n       (discriminator'fake, _)            = runGradient discriminator discriminatorTapeFake guessFake\n       (_, push)                          = runGradient discriminator discriminatorTapeFake ( guessFake - 1)\n\n       (generator', _)                    = runGradient generator generatorTape push\n\n       newDiscriminator                   = foldl' (applyUpdate rate { learningRegulariser = learningRegulariser rate * 10}) discriminator [ discriminator'real, discriminator'fake ]\n       newGenerator                       = applyUpdate rate generator generator'\n   in ( newDiscriminator, newGenerator )\n\n\nganTest :: (Discriminator, Generator) -> Int -> FilePath -> LearningParameters -> IO (Discriminator, Generator)\nganTest (discriminator0, generator0) iterations dataDir rate = do\n  -- Note that for this example we use only the samples, and not the labels\n  trainData      <- fmap fst <$> readMNIST (dataDir </> \"train-images-idx3-ubyte.gz\")\n                                           (dataDir </> \"train-labels-idx1-ubyte.gz\")\n\n  foldM (runIteration trainData) ( discriminator0, generator0 ) [1..iterations]\n\n    where\n\n  showShape' :: S ('D2 a b) -> IO ()\n  showShape' (S2D mm) = putStrLn $\n    let m  = SA.extract mm\n        ms = toLists m\n        render n'  | n' <= 0.2  = ' '\n                   | n' <= 0.4  = '.'\n                   | n' <= 0.6  = '-'\n                   | n' <= 0.8  = '='\n                   | otherwise =  '#'\n\n        px = (fmap . fmap) render ms\n    in unlines px\n\n  runIteration :: [S ('D2 28 28)] -> (Discriminator, Generator) -> Int -> IO (Discriminator, Generator)\n  runIteration trainData ( !discriminator, !generator ) _ = do\n    trained'    <- foldM ( \\(!discriminatorX, !generatorX ) realExample ->\n                             trainExample rate discriminatorX generatorX realExample <$> randomOfShape )\n                         ( discriminator, generator ) trainData\n\n\n    showShape' . snd . runNetwork (snd trained') =<< randomOfShape\n\n    return trained'\n\ndata GanOpts = GanOpts FilePath Int LearningParameters (Maybe FilePath) (Maybe FilePath)\n\nmnist' :: Parser GanOpts\nmnist' = GanOpts <$> argument str (metavar \"DATADIR\")\n                 <*> option auto (long \"iterations\" <> short 'i' <> value 15)\n                 <*> (LearningParameters\n                       <$> option auto (long \"train_rate\" <> short 'r' <> value 0.01)\n                       <*> option auto (long \"momentum\" <> value 0.9)\n                       <*> option auto (long \"l2\" <> value 0.0005)\n                       )\n                 <*> optional (strOption (long \"load\"))\n                 <*> optional (strOption (long \"save\"))\n\n\nmain :: IO ()\nmain = do\n  GanOpts mnist iter rate load save <- execParser (info (mnist' <**> helper) idm)\n  putStrLn \"Training stupidly simply GAN\"\n  nets0 <- case load of\n    Just loadFile -> netLoad loadFile\n    Nothing -> (,) <$> randomDiscriminator <*> randomGenerator\n\n  nets1 <- ganTest nets0 iter mnist rate\n  case save of\n    Just saveFile -> B.writeFile saveFile $ Serialize.runPutLazy (Serialize.put nets1)\n    Nothing -> return ()\n\n\n-- Adapted from https://github.com/tensorflow/haskell/blob/master/tensorflow-mnist/src/TensorFlow/Examples/MNIST/Parse.hs\n-- Could also have used Data.IDX, although that uses a different Vector variant from that need for fromStorable\nreadMNIST :: FilePath -> FilePath -> IO [(S ( 'D2 28 28), S ( 'D1 10))]\nreadMNIST iFP lFP = do\n  labels  <- readMNISTLabels lFP\n  samples <- readMNISTSamples iFP\n  return $ zip\n    (fmap (fromMaybe (error \"bad samples\") . fromStorable) samples)\n    (fromMaybe (error \"bad labels\") . oneHot . fromIntegral <$> labels)\n\n-- | Check's the file's endianess, throwing an error if it's not as expected.\ncheckEndian :: Get ()\ncheckEndian = do\n  magic <- Serialize.getWord32be\n  when (magic `notElem` ([2049, 2051] :: [Word32]))\n    $ error \"Expected big endian, but image file is little endian.\"\n\n-- | Reads an MNIST file and returns a list of samples.\nreadMNISTSamples :: FilePath -> IO [V.Vector Double]\nreadMNISTSamples path = do\n  raw <- decompress <$> B.readFile path\n  either fail ( return . fmap (V.map normalize) ) $ Serialize.runGetLazy getMNIST raw\n where\n  getMNIST :: Get [V.Vector Word8]\n  getMNIST = do\n    checkEndian\n    -- Parse header data.\n    cnt    <- fromIntegral <$> Serialize.getWord32be\n    rows   <- fromIntegral <$> Serialize.getWord32be\n    cols   <- fromIntegral <$> Serialize.getWord32be\n    -- Read all of the data, then split into samples.\n    pixels <- Serialize.getLazyByteString $ fromIntegral $ cnt * rows * cols\n    return $ V.fromList <$> chunksOf (rows * cols) (B.unpack pixels)\n\n  normalize :: Word8 -> Double\n  normalize = (/ 255) . fromIntegral\n  -- There are other normalization functions in the literature, such as\n  -- normalize = (/ 0.3081) . (`subtract` 0.1307) . (/ 255) . fromIntegral\n  -- but we need values in the range [0..1] for the showShape' pretty printer\n\n-- | Reads a list of MNIST labels from a file and returns them.\nreadMNISTLabels :: FilePath -> IO [Word8]\nreadMNISTLabels path = do\n  raw <- decompress <$> B.readFile path\n  either fail return $ Serialize.runGetLazy getLabels raw\n where\n  getLabels :: Get [Word8]\n  getLabels = do\n    checkEndian\n    -- Parse header data.\n    cnt <- fromIntegral <$> Serialize.getWord32be\n    -- Read all of the labels.\n    B.unpack <$> Serialize.getLazyByteString cnt\n\n\nnetLoad :: FilePath -> IO (Discriminator, Generator)\nnetLoad modelPath = do\n  modelData <- B.readFile modelPath\n  either fail return $\n    Serialize.runGetLazy (Serialize.get :: Get (Discriminator, Generator)) modelData\n", "meta": {"hexsha": "87e505b39b31c6ae6675d49a488edc1650141691", "size": 8727, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/gan-mnist.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/main/gan-mnist.hs", "max_issues_repo_name": "jrp2014/grenade", "max_issues_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main/gan-mnist.hs", "max_forks_repo_name": "jrp2014/grenade", "max_forks_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6163793103, "max_line_length": 181, "alphanum_fraction": 0.6100607311, "num_tokens": 2316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4447433299205378}}
{"text": "{-|\nModule      : MachineLearning.TIR\nDescription : TIR expression data structures\nCopyright   : (c) Fabricio Olivetti de Franca, 2022\nLicense     : GPL-3\nMaintainer  : fabricio.olivetti@gmail.com\nStability   : experimental\nPortability : POSIX\n\nThe TIR expression  represents a function of the form:\n\n\\[\nf(x) = g(\\sum_{i}{w_i \\cdot t_i(\\prod_{j}{x_j^{k_{ij}})}} / (1 + \\sum_{i}{w_i \\cdot t_i(\\prod_{j}{x_j^{k_{ij}})}})\n\\]\n\nwith \\(t_i\\) being a transformation function, \\(g\\) an invertible function, \\(w_i\\) a linear coefficient, \\(k_{ij}\\) \nthe interaction strength.\n\nAny given expression can be represented by two lists of terms, with each term\nbeing composed of a transformatioon function and an interaction.\nThe transformation function is represented by a `Function` sum type.\nThe interaction is represented as a list of tuple of ints where the key is the \npredictor index and the value is the strength of the predictor in this\nterm. Strengths with a value of zero are omitted.\n-}\nmodule MachineLearning.TIR where\n\nimport Control.Evolution\nimport Control.Monad.State.Strict\nimport Data.List.Split\nimport Data.SRTree\nimport System.Random\nimport Control.DeepSeq                           (NFData, rnf)\nimport Data.List                                 (delete)\nimport Data.SRTree.Print                         (showDefault)\nimport Data.Vector                               (Vector)\nimport qualified Data.Vector             as V\nimport qualified Data.Vector.Storable    as VS\nimport qualified Numeric.LinearAlgebra   as LA\nimport MachineLearning.Utils.Config\n\n-- | `TIR` is a record type composed of the external\n-- function `_funY` of type `Function`, numerator `_p`\n-- and denominator `_q` of type `Sigma`\ndata TIR = TIR { _funY :: Function\n               , _p :: Sigma\n               , _q :: Sigma\n               } deriving Show\n\ninstance NFData TIR where\n  rnf _ = ()\n\n-- | `Sigma` is just a list of terms `Pi`\ntype Sigma = [Pi]\n-- | `Pi` is a triple composed of a coefficient, a `Function`\n-- and a list of tuples where `(ix, k)` represents `x ! ix ^ k`.\ntype Pi    = (Double, Function, [(Int, Int)])\n\n-- | generates a random integer within the specified range.\nrandomRng :: (Int, Int) -> Rnd Int\nrandomRng rng = state $ randomR rng\n{-# INLINE randomRng #-}\n\n-- | generates a random integer within the specified range excluding zero.\nrandomRngNZ :: (Int, Int) -> Rnd Int\nrandomRngNZ rng = do\n  x <- randomRng rng\n  if x == 0\n    then randomRngNZ rng\n    else pure x\n{-# INLINE randomRngNZ #-}\n\n-- | picks a random element from a list.\nrandomFrom :: [a] -> Rnd a\nrandomFrom xs = do\n  ix <- randomRng (0, length xs - 1)\n  pure (xs !! ix)\n{-# INLINE randomFrom #-}\n\n-- | returns a random index of variables provided by the mutation configuration.\nrandomVar :: MutationCfg -> Rnd (Maybe Int, MutationCfg)\nrandomVar params = do\n  let vars = _vars params\n      n    = length vars\n  ix <- randomRng (0, n)\n  if ix == n\n     then pure (Nothing, params)\n     else do let x = vars !! ix\n             pure (Just x, params{ _vars=delete x vars })\n\n-- | returns a list of random interactions (tuples of variables indeces and exponentes)\n-- with parameters provided by the mutation configuration.\nrandomVars :: MutationCfg -> Rnd [(Int, Int)]\nrandomVars params = do\n  (v, params') <- randomVar params\n  k            <- randomRngNZ $ _kRange params\n  case v of\n    Nothing  -> pure []\n    Just var -> do vs <- randomVars params'\n                   pure $ (var, k) : vs\n\n-- | returns a random `Pi`\nrandomPi :: MutationCfg -> Rnd (Maybe Pi)\nrandomPi params = do\n  pis <- randomVars params\n  f   <- randomFrom $ _funs params\n  if null pis\n    then pure Nothing\n    else pure $ Just (1.0, f, pis)\n\n-- | returns a random `Sigma`\nrandomSigma :: MutationCfg -> Int -> Rnd (Sigma, Int)\nrandomSigma params budget | budget <= 0 = pure ([], budget)\nrandomSigma params budget = do\n  n <- randomRng (0, budget)\n  if n == budget\n     then pure ([], budget)\n     else do term             <- randomPi params\n             (terms, budget') <- randomSigma params (budget - spentBudget term)\n             case term of\n               Nothing -> pure (terms, budget')\n               Just t  -> pure (t:terms, budget')\n\n  where\n    spentBudget Nothing           = 0\n    spentBudget (Just (_, _, ps)) = 1 -- length ps\n\n-- | returns a random `TIR` expression\nrandomTIR :: MutationCfg -> Rnd TIR\nrandomTIR params = do\n  yf           <- randomFrom $ _yfuns params\n  (p, budget') <- randomSigma params $ _budget params\n  (q, _)       <- randomSigma params budget'\n  if null p\n    then randomTIR params\n    else pure (TIR yf p q)\n\n-- | We store thee dataset as a vector of columns. \n-- Each vector is stored a `Storable`-based vector.\ntype Column a   = LA.Vector a\n\n-- | A dataset is a `Vector` of `Column`\ntype Dataset a  = Vector (Column a)\n\n-- | A constraint is a function that gets a symbolic tree\n-- as an input and returns non negative `Double` representing\n-- how much a constraint was violated.\ntype Constraint = SRTree Int Double -> Double\n\n-- | An individual in the population is composed of\n-- the chromossome, a vector of fitness, a list of\n-- coefficients (for multiclass problems it stores\n-- one vector of coefficient per class),\n-- the constraint violation, the size of the expression,\n-- and the penalty value.\ndata Individual = Individual { _chromo  :: TIR\n                             , _fit     :: [Double]\n                             , _weights :: [LA.Vector Double]\n                             , _constr  :: Double\n                             , _len     :: Int\n                             , _penalty :: Double\n                             }\n\n-- | creates an unevaluated individual.\ncreateIndividual :: TIR -> Individual\ncreateIndividual tir = Individual tir [] [] 0.0 0 0.0\n\n-- | calculates the penalized fitness.\npenalizedFit :: Individual -> Double\npenalizedFit t = (head . _fit) t + _penalty t\n{-# INLINE penalizedFit #-}\n\n-- | replaces the coefficients of a TIR expression\nreplaceConsts :: TIR -> V.Vector Double -> TIR\nreplaceConsts (TIR g p q) ws = TIR g p' q'\n  where\n    (p', ws1) = runState (traverse replaceWeight p) (V.toList ws)\n    (q', ws2) = runState (traverse replaceWeight q) ws1\n\nreplaceWeight :: Pi -> State [Double] Pi\nreplaceWeight (w, g, h) = state $ \\ws -> case ws of\n                                           (wi:ws') -> ((wi, g, h), ws')\n                                           []       -> error $ show h -- ((w, g, h), [])\n\ninstance Eq Individual where\n    t1 == t2 = penalizedFit t1 == penalizedFit t2 \ninstance Ord Individual where\n    t1 <= t2 = penalizedFit t1 <= penalizedFit t2\n\ninstance NFData Individual where\n  rnf _ = ()\n\ninstance Solution Individual where\n  _getFitness = head . _fit\n  _isFeasible = (<1e-12) . _constr\n\n-- | creates a symbolic tree from a TIR expression.\nassembleTree :: Double -> TIR -> SRTree Int Double\nassembleTree bias (TIR f p q) = Fun f ((Const bias + assemble p) / (1 + assemble q))\n  where\n    -- assemble :: Sigma ix val -> SRTree ix val\n    assemble []      = 0\n    assemble [p']    = mk p'\n    assemble (p':ps) = mk p' + assemble ps\n\n    -- mk :: Pi ix val -> SRTree ix val\n    mk (v, g, ts) = Const v * Fun g (foldr (\\(ix, k) acc -> acc * Pow (Var ix) k) 1 ts)\n\n-- | pretty print a solution.\nprettyPrintsolution :: Individual -> String\nprettyPrintsolution sol | Prelude.null (_fit sol) = error \"unevaluated solution\"\nprettyPrintsolution sol = concat [ \"Expression:\\n\", (showDefault . assembleTree bias . _chromo) sol, \"\\n\"\n                                 , \"Fitness: \", (show . head . _fit) sol, \"\\n\"\n                                 , \"Constraints: \", (show . _constr) sol, \"\\n\"\n                                 , \"Length: \", (show . _len) sol, \"\\n\"\n                                 , \"Penalty: \", (show . _penalty) sol, \"\\n\"\n                                 ]\n\n  where bias = V.head $ VS.convert $ head $ _weights sol\n", "meta": {"hexsha": "a13cca5adbeb7b592e511b55858f7ab3f8097fdb", "size": 7878, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/TIR.hs", "max_stars_repo_name": "folivetti/tir", "max_stars_repo_head_hexsha": "5db7c8fa62975f7ce901fce68a560156b2dc6745", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MachineLearning/TIR.hs", "max_issues_repo_name": "folivetti/tir", "max_issues_repo_head_hexsha": "5db7c8fa62975f7ce901fce68a560156b2dc6745", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MachineLearning/TIR.hs", "max_forks_repo_name": "folivetti/tir", "max_forks_repo_head_hexsha": "5db7c8fa62975f7ce901fce68a560156b2dc6745", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8090909091, "max_line_length": 117, "alphanum_fraction": 0.6164001015, "num_tokens": 2069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.44449921263101794}}
{"text": "{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n-- | Basic types used throughout the library.\n--\n--   Includes a probability type (based on sampling functions, with a tweak for\n--   collected samples) and associated instances, as well as types used for\n--   MCMC.\n\nmodule Math.Probably.Types where\n\nimport Control.Applicative\nimport Control.Monad.State.Strict\nimport Numeric.LinearAlgebra\nimport System.Random.Mersenne.Pure64\n\ntype Seed = PureMT\n\ndata Prob a =\n    Sampler { unSampler :: Seed -> (a, Seed) }\n  | Samples [a]\n\ninstance Functor Prob where\n  fmap f (Sampler sf) = Sampler $ \\rs -> let (x,rs') = sf rs in (f x, rs')\n  fmap f (Samples xs) = Samples $ map f xs\n \ninstance Applicative Prob where\n  pure x = Sampler (\\rs-> (x, rs))\n  (Sampler sff) <*> (Sampler sfx) = Sampler $ \\rs -> \n    let (f ,rs') = sff rs \n        (x, rs'') = sfx rs' \n    in (f x, rs'')\n  _ <*> _ = error \"Prob (<*>): unsupported pattern\"\n\ninstance Monad Prob where\n  return = pure\n  (Sampler sf) >>= f = Sampler $ \\rs-> \n    let (x, rs'::Seed) = sf rs \n        nextProb = f x\n    in case nextProb of\n         Sampler g -> g rs'\n         Samples xs -> primOneOf xs rs'\n\n  (Samples xs) >>= f = Sampler $ \\rs-> \n    let (x, rs'::Seed) = primOneOf xs rs\n        nextProb = f x\n    in case nextProb of\n         Sampler g -> g rs'\n         Samples ys -> primOneOf ys rs'\n\nprimOneOf :: [a] -> Seed -> (a, Seed)\nprimOneOf xs seed \n  = let (u, nextSeed) = randomDouble seed\n        idx = floor $ realToFrac u * realToFrac (length xs )\n    in (xs !! idx, nextSeed)\n\ntype DiscreteParams   = Vector Int\ntype ContinuousParams = Vector Double\ntype Parameters       = (DiscreteParams, ContinuousParams)\n\ntype LogObjective     = Parameters -> Double\ntype Gradient         = ContinuousParams -> ContinuousParams\n\ntype Particle         = (ContinuousParams, ContinuousParams)\n\ntype Transition t     = StateT (Chain t) Prob Parameters\n\n-- | State of a Markov chain.  Note that the objective function itself is\n--   included in the state, which allows the possibility of annealing schedules\n--   and the like.\ndata Chain t = Chain {\n    parameterSpacePosition :: Parameters\n  , objectiveFunction      :: Target\n  , objectiveValue         :: Double\n  , tunables               :: t\n  }\n\n-- | A target to sample, consisting of a log objective function and possibly\n--   its gradient.  The gradient is only taken with respect to continuous\n--   parameters.\ndata Target = Target {\n    logObjective :: Parameters -> Double\n  , gradient     :: Maybe (ContinuousParams -> ContinuousParams)\n  }\n\n-- | Convenience constructor for targets and gradients.\ncreateTargetWithGradient :: LogObjective -> Gradient -> Target\ncreateTargetWithGradient f g = Target f (Just g)\n\n-- | Convenience constructor for targets without gradients.\ncreateTargetWithoutGradient :: LogObjective -> Target\ncreateTargetWithoutGradient f = Target f Nothing\n\nhandleGradient :: Maybe t -> t\nhandleGradient Nothing  = error \"handleGradient: no gradient provided\"\nhandleGradient (Just g) = g\n\n-- | The dual-averaging implementation of NUTS requires quite a few tuning\n--   parameters, which are all held in this type.\ndata DualAveragingParameters = DualAveragingParameters {\n    mAdapt    :: !Int\n  , delta     :: !Double\n  , mu        :: !Double\n  , gammaP    :: !Double\n  , tau0      :: !Double\n  , kappa     :: !Double\n  , daStep    :: !Double\n  , daStepAvg :: !Double\n  , daH       :: !Double\n  } deriving (Eq, Show)\n\ndefaultDualAveragingParameters :: Double -> Int -> DualAveragingParameters\ndefaultDualAveragingParameters e burnInPeriod = DualAveragingParameters {\n    mu        = log (10 * e)\n  , delta     = 0.5\n  , mAdapt    = burnInPeriod\n  , gammaP    = 0.05\n  , tau0      = 10\n  , kappa     = 0.75\n  , daStep    = e\n  , daStepAvg = e\n  , daH       = 0\n  }\n\n", "meta": {"hexsha": "490decb9e5476487bf02b7498935654db06f625a", "size": 3823, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/Types.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Math/Probably/Types.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Probably/Types.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 30.584, "max_line_length": 79, "alphanum_fraction": 0.6531519749, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4444255751632046}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TemplateHaskell       #-}\n\nmodule Lib where\n\nimport           Control.Monad.Except                      (MonadError,\n                                                            runExceptT,\n                                                            throwError)\nimport           Control.Monad.IO.Class                    (MonadIO, liftIO)\nimport           Data.ByteString                           (ByteString)\nimport           Data.FileEmbed                            (embedFile)\nimport           Data.Monoid                               ((<>))\nimport           Data.Scientific                           (Scientific,\n                                                            toRealFloat)\nimport           Debug.Trace\nimport           GHC.TypeLits                              ()\nimport           Graphics.Plot                             (mplot)\nimport           Graphics.Rendering.Chart.Backend.Diagrams (toFile)\nimport           Graphics.Rendering.Chart.Easy             (def, layout_title,\n                                                            line, plot, points,\n                                                            re, (.=))\nimport           Numeric.GSL.Minimization                  (MinimizeMethod (NMSimplex),\n                                                            MinimizeMethodD (SteepestDescent, VectorBFGS2),\n                                                            minimizeD,\n                                                            minimizeV,\n                                                            minimizeVD)\nimport           Numeric.LinearAlgebra                     (Container, accum,\n                                                            matFunc, tr, ( #> ),\n                                                            (<.>))\nimport qualified Numeric.LinearAlgebra                     as Matrix\nimport           Numeric.LinearAlgebra.Data                (Matrix, Vector,\n                                                            asColumn, asRow,\n                                                            cols, cond,\n                                                            dropColumns,\n                                                            dropRows, rows,\n                                                            takeColumns,\n                                                            takeRows, (><),\n                                                            (|||))\nimport qualified Numeric.LinearAlgebra.Data                as MData\nimport           Numeric.LinearAlgebra.Static              (L, dim, matrix, mul)\nimport qualified Numeric.LinearAlgebra.Static              as Static\nimport           Text.Megaparsec                           (Dec, ParseError,\n                                                            Token, char,\n                                                            newline, parse,\n                                                            sepBy)\nimport           Text.Megaparsec.ByteString                (Parser)\nimport           Text.Megaparsec.Lexer                     (number)\n\ndata Error =\n  ParseFailed (ParseError (Token ByteString) Dec)\n  deriving (Show, Eq)\n\n------------------------------------------------------------\n-- Parsing.\nrawDataParser :: Parser [[Scientific]]\nrawDataParser =\n  filter (not . null) <$> (number `sepBy` char ',') `sepBy` newline\n\ntoMatrix :: [[Scientific]] -> Matrix Double\ntoMatrix = Matrix.fromLists . fmap (fmap toRealFloat)\n\nwineData :: ByteString\nwineData = $(embedFile \"data/wine.data\")\n\nwineParser :: Parser (Matrix Double)\nwineParser = toMatrix <$> rawDataParser\n\nloadData\n  :: (MonadError Error m, MonadIO m)\n  => m (Matrix Double)\nloadData = either (throwError . ParseFailed) pure (parse wineParser \"\" wineData)\n\n------------------------------------------------------------\n-- Matrices\na :: L 3 2\na = matrix [1 .. 6]\n\nb :: L 2 1\nb = matrix [1 .. 2]\n\nc :: L 3 1\nc = mul a b\n\n------------------------------------------------------------\n-- Linear Regression\ninitialTheta :: Int -> Vector Double\ninitialTheta n = MData.vector $ replicate n 0\n\n------------------------------------------------------------\n-- Charts\nsignal :: [Double] -> [(Double, Double)]\nsignal xs =\n  [(x, (sin (x * 3.14159 / 45) + 1) / 2 * sin (x * 3.14159 / 5)) | x <- xs]\n\nwriteChart :: IO ()\nwriteChart =\n  toFile def \"example.svg\" $ do\n    layout_title .= \"Amplitude Modulation\"\n    plot (line \"am\" [signal [0,0.5 .. 800]])\n    plot (points \"am points\" (signal [0,7 .. 800]))\n\n------------------------------------------------------------\n-- Main\nmain :: IO ()\nmain = do\n  result <-\n    runExceptT $ do\n      dataset <- loadData\n      process dataset\n  print result\n\ndata Result = Result\n  { crossValidationSet    :: Matrix Double\n  , crossValidationResult :: Vector Double\n  , finalTheta            :: Vector Double\n  , finalHyp              :: Vector Double\n  , finalCost             :: Double\n  } deriving (Show)\n\nprocess\n  :: (MonadIO m, MonadError Error m)\n  => Matrix Double -> m Result\nprocess dataSet = do\n  let is n v = cond v n 0 1 0\n  let target = 1\n  let scale :: Matrix Double =\n        accum\n          (MData.ident 13)\n          (*)\n          [((0, 0), 0.1), ((3, 3), 0.1), ((4, 4), 0.01), ((12, 12), 0.001)]\n  let m = rows dataSet\n  let f = cols dataSet\n  let y = is target $ MData.flatten $ takeColumns 1 dataSet\n  let x = Matrix.col (replicate m 1.0) ||| ((dropColumns 1 dataSet) <> scale)\n  let cvSize = 10\n  let trainingX = dropRows cvSize x\n  let cvX = takeRows cvSize x\n  let trainingY = MData.fromList $ drop cvSize $ MData.toList y\n  let cvY = MData.fromList $ take cvSize $ MData.toList y\n  let theta = initialTheta f\n  let (finalTheta, path) =\n        minimizeVD\n          SteepestDescent -- VectorBFGS2\n          10e-6\n          50\n          10e-6\n          0.1\n          (costFn x y)\n          (gradFn x y)\n          theta\n  pure $\n    Result\n      cvX\n      cvY\n      finalTheta\n      (hypothesis cvX finalTheta)\n      (costFn cvX cvY finalTheta)\n\nsigmoid\n  :: Floating a\n  => a -> a\nsigmoid term = 1.0 / (1.0 + exp (-term))\n\nhypothesis :: Matrix Double -> Vector Double -> Vector Double\nhypothesis x theta = sigmoid (x #> theta)\n\ncostFn :: Matrix Double -> Vector Double -> Vector Double -> Double\ncostFn x y theta = traceShowId $ all\n  where\n    all :: Double\n    all = vsum (leftTerm - rightTerm) / fromIntegral (rows x)\n    h = hypothesis x theta\n    leftTerm = (-y) * log h\n    rightTerm = (1.0 - y) * log (1.0 - h)\n\ngradFn :: Matrix Double -> Vector Double -> Vector Double -> Vector Double\ngradFn x y theta = (tr x #> (hypothesis x theta - y)) / fromIntegral (rows x)\n\nvsum :: Vector Double -> Double\nvsum = sum . MData.toList\n", "meta": {"hexsha": "405cd20a83e4c9146a655504d5476fba617b874b", "size": 6931, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "krisajenkins/sketch", "max_stars_repo_head_hexsha": "54289f580f74ac040da7323c0b2d830b18e7fbcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-17T17:34:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-17T17:34:19.000Z", "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "krisajenkins/sketch", "max_issues_repo_head_hexsha": "54289f580f74ac040da7323c0b2d830b18e7fbcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lib.hs", "max_forks_repo_name": "krisajenkins/sketch", "max_forks_repo_head_hexsha": "54289f580f74ac040da7323c0b2d830b18e7fbcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2634408602, "max_line_length": 107, "alphanum_fraction": 0.4547684317, "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4442374009375453}}
{"text": "#!/usr/bin/env stack\n-- stack runghc --package reanimate\n{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\n\nimport           Codec.Picture.Types\nimport           Control.Lens                  ()\nimport           Control.Monad\nimport           Data.Function\nimport           Data.List\nimport           Data.List.NonEmpty            (NonEmpty)\nimport qualified Data.List.NonEmpty            as NE\nimport           Data.Maybe\nimport           Data.Ratio\nimport qualified Data.Text                     as T\nimport           Data.Tuple\nimport qualified Data.Vector                   as V\nimport           Debug.Trace\nimport           Linear.Matrix                 hiding (trace)\nimport           Linear.Metric\nimport           Linear.V2\nimport           Linear.V3\nimport           Linear.Vector\nimport           Numeric.LinearAlgebra         hiding (polar, scale, (<>))\nimport qualified Numeric.LinearAlgebra         as Matrix\nimport           Numeric.LinearAlgebra.HMatrix hiding (polar, scale, (<>))\nimport           Reanimate\nimport           Reanimate.Animation\nimport           Reanimate.Math.Balloon\nimport           Reanimate.Math.Common\nimport           Reanimate.Math.Triangulate\nimport           Reanimate.Math.Polygon\nimport           Reanimate.Math.EarClip\nimport           Reanimate.Math.SSSP\nimport           Reanimate.Math.Render\nimport           Reanimate.Math.Visibility\nimport           Reanimate.Math.Compatible\nimport           Reanimate.Morph.Common\nimport           Reanimate.Morph.Linear\nimport           Reanimate.Morph.LeastDifference\nimport           Reanimate.PolyShape           (svgToPolygons)\nimport           Reanimate.Debug\nimport qualified Reanimate.Math.Compatible as Compat\n\nextraPoints = 0\n\n-- p1 = pScale 2 $ pAtCenter $ pAddPoints extraPoints (pSetOffset shape13 0)\n-- p1 = pSetOffset (addPoints 2 shape13) 0\n-- p2 = pScale 0.5 $ centerPolygon shape20\n-- p1 = centerPolygon shape2\n-- p2 = pScale 2 $ pAtCenter $ pAddPoints extraPoints (pSetOffset shape14 0 )\n\n-- p1 = pAddPoints extraPoints (pAtCenter $ unsafeSVGToPolygon 0.1 $ scale 6 $ latex \"S\")\n-- p2 = pAddPoints extraPoints (pAtCenter $ unsafeSVGToPolygon 0.1 $ scale 6 $ latex \"C\")\np1 = pAddPoints extraPoints (pAtCenter $ unsafeSVGToPolygon 0.1 $ scale 6 $ latex \"X\")\np2 = pAddPoints extraPoints (pAtCenter $ unsafeSVGToPolygon 0.1 $ scale 6 $ latex \"I\")\n\np1_ = castPolygon p1\np2_ = castPolygon p2\npolys = triangulate_ p1_ p2_\np1_circ = circumference (map fst polys') p1_\np2_circ = circumference (map snd polys') p2_\n\npolys' = alignPolygons polys p1_ p2_\npolys'' = compatTriagPairs polys'\n\n-- (p1_circ, p2_circ) = closestLinearCorrespondence p1_circ' p2_circ'\n\n-- (p1s, p2s) = unzip $ triangulate p1 p2\n\nmain :: IO ()\n-- main = reanimate $ playTraces $ seq (last $ triangulate [] p1 p2) ()\nmain = reanimate $ scene $ do\n  bg <- newSpriteSVG $ mkBackground \"black\"\n  spriteZ bg (-1)\n\n  -- let leastDiffTrig = triangulate p1 p2\n  let lst = polys'\n  -- let lst = take 10 $ uncurry Compat.compatiblyTriangulateP (polys'!!3) -- polys''\n  -- let lst = polys''\n  forM_ (zip [0..] lst {-([polys''!!2]++p_snd)-}) $ \\(n,(l, r)) -> do\n    let c = promotePixel $ turbo (n/fromIntegral (length lst-1))\n    newSpriteSVG_ $ \n      translate (-2) 0 $ withFillColorPixel c $ mkGroup\n      [ polygonShape (castPolygon l)\n      -- , polygonNumDots (castPolygon l)\n      ]\n    newSpriteSVG_ $ \n      translate 2 0 $ withFillColorPixel c $ mkGroup\n      [ polygonShape (castPolygon r)\n      -- , polygonNumDots (castPolygon r)\n      ]\n    nums <- newSpriteSVG $ mkGroup\n      [ translate (-2) 0 $ polygonNumDots (castPolygon l)\n      , translate 2 0 $ polygonNumDots (castPolygon r)\n      ]\n    wait (1/60)\n    destroySprite nums\n  \n  -- fork $ play $ staticFrame (1/60) $ mkGroup\n  --   [ translate 2 0 $ mkGroup\n  --     [ withFillColor \"grey\" $ polygonShape p2_circ\n  --     , polygonNumDots p2_circ\n  --     ]\n  --   , translate 6 0 $ mkGroup\n  --     [ withFillColor \"grey\" $ polygonShape p2\n  --     , polygonNumDots p2\n  --     ]\n  --   ]\n  -- play $ staticFrame (1/60) $ mkGroup\n  --   [ translate (-2) 0 $ mkGroup\n  --     [ withFillColor \"grey\" $ polygonShape p1_circ\n  --     , polygonNumDots p1_circ\n  --     ]\n  --   , translate (-6) 0 $ mkGroup\n  --     [ withFillColor \"grey\" $ polygonShape p1\n  --     , polygonNumDots p1\n  --     ]\n  --   ]\n\n\nshowP p = mkGroup\n  [ withFillColor \"grey\" $ polygonShape p\n  , polygonNumDots p ]\n", "meta": {"hexsha": "862b9b3ee6194d98fa08de741fa49c13e5f06bbb", "size": 4417, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "videos/morph/least-difference.hs", "max_stars_repo_name": "cdodev/reanimate", "max_stars_repo_head_hexsha": "ccc69c0d834b821ec6469c1ecee9cb88c39c1704", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 577, "max_stars_repo_stars_event_min_datetime": "2020-07-04T23:45:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:44:36.000Z", "max_issues_repo_path": "videos/morph/least-difference.hs", "max_issues_repo_name": "cdodev/reanimate", "max_issues_repo_head_hexsha": "ccc69c0d834b821ec6469c1ecee9cb88c39c1704", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 91, "max_issues_repo_issues_event_min_datetime": "2020-06-25T03:32:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:14:42.000Z", "max_forks_repo_path": "videos/morph/least-difference.hs", "max_forks_repo_name": "cdodev/reanimate", "max_forks_repo_head_hexsha": "ccc69c0d834b821ec6469c1ecee9cb88c39c1704", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2020-07-05T13:30:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T09:41:00.000Z", "avg_line_length": 35.336, "max_line_length": 89, "alphanum_fraction": 0.6284808694, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4442373955268554}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE LambdaCase          #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators       #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE TypeApplications    #-}\n\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\nmodule Neldermead (\n  Simplex(..)\n  , haftkaGurdalSimplex\n  ) where\n\nimport Data.Ord (comparing)\nimport Data.Function (on)\nimport Data.Bool (bool)\nimport Data.Maybe (fromMaybe)\nimport Data.Monoid (Sum)\nimport qualified Data.Foldable as FLD\nimport qualified Data.Proxy as PXY\nimport Data.Coerce\n\nimport Control.Arrow ((&&&))\nimport Control.Monad.State.Strict\n\nimport qualified Numeric.Interval.NonEmpty as IVL\n\nimport qualified Data.Finite as F\nimport Data.Singletons (Sing, sing, fromSing)\nimport Data.Singletons.TypeLits\n\nimport qualified Data.Vector.Sized as V\nimport qualified Data.Vector.Storable.Sized as SV\n--import qualified Data.Vector.Mutable.Sized as MV\nimport Numeric.LinearAlgebra.Static\nimport Numeric.LinearAlgebra.Static.Vector\nimport GHC.TypeNats\n\nimport qualified Control.Lens as L\nimport qualified Control.Lens.Iso as LI\nimport qualified Control.Lens.Traversal as LT\n\n--TODO in future - mark Vertex with the objective function\n--in any constructor, must take objective and then mark it\n\n--TODO in future, allow more flexibility in objective?\n--TODO better field names or allow overloaded\n--TODO lenses\ndata NMVertex n = NMVertex { getX :: !(R n)\n                           , getFx :: \u211d\n                           }\n\nnewtype NMSimplex n = NMSimplex { fOrderedVertices :: V.Vector (n + 1) (NMVertex n) }\n\nnewtype Simplex n = Simplex { xA :: L n (n + 1) }\n    deriving (Show)\n\nnewtype BoxConstraints n = BoxConstraints { unBoxConstraints :: V.Vector n (IVL.Interval \u211d) }\n\ndata NMScalars = NMScalars {\n  reflectWeight :: \u211d\n  , expandWeight :: \u211d\n  , contractWeight :: \u211d\n  , shrinkWeight :: \u211d\n}\n\n--TODO convergeTest should be monadic to allow writing details\n--\ndata NMEnv n = MEnv {\n  scalars :: NMScalars\n  , simplexConvergeTest :: NMSimplex n -> Bool\n}\n\nnewtype OnBounds = OnBounds { unOnBounds :: Bool }\n\nmakeNMVertex :: KnownNat n => (R n -> \u211d) -> R n -> NMVertex n\nmakeNMVertex f x = NMVertex { getX = x, getFx = f x }\n\n--TODO actually need to change case 2 to keep if better than second worst (not best)\nnextNMSimplex :: forall n. (KnownNat n, 1 <= n) \n  => NMScalars -> (R n -> \u211d) -> NMSimplex n -> NMSimplex n\nnextNMSimplex env f (NMSimplex vtxs)\n  | comparing getFx vtxReflect vtxl == LT = undefined --expand case\n  | comparing getFx vtxReflect vtxl2 == LT = undefined -- just keep swap out reflect and re-order\n  | otherwise = undefined --shrink case\n  where\n    vtxl = V.head vtxs\n    vtxl2 = V.index vtxs $ F.natToFinite (PXY.Proxy @1)\n    vtxh = V.last vtxs\n    xc = centroid $ getX <$> FLD.toList vtxs\n    vtxReflect = makeNMVertex f $ affineCombWith (getX vtxh) (reflectWeight env) xc\n\n\n\n--TODO may need MonadReader and MonadState, and allow objective to be in any monad\nrVecIso :: KnownNat n => LI.Iso' (R n) (SV.Vector n \u211d)\nrVecIso = LI.iso rVec vecR\n\nprojectToBox :: KnownNat n => BoxConstraints n -> R n -> R n\nprojectToBox (BoxConstraints bc) = \n  L.over rVecIso $ SV.imap $ IVL.clamp . V.index bc\n\n-- Return bool is weather any dimension was clamped\nprojectToBoxState :: KnownNat n \n  => BoxConstraints n -> R n -> State OnBounds (R n)\nprojectToBoxState (BoxConstraints bc) = L.mapMOf rVecIso \n  $ SV.imapM $ \\i x -> do\n    let bci = V.index bc i\n    modify $ coerce (|| x `IVL.notMember` bci)\n    return $ IVL.clamp bci x\n\n\n--awkward because cant deconstruct interval into inf sup\n--and cant zip storable and not storable\nrightAngledSimplexInBox :: forall n. KnownNat n \n  => BoxConstraints n -> R n -> R n -> Simplex n\nrightAngledSimplexInBox (BoxConstraints bc) step x0 = Simplex\n  $ ((x0 `outer` 1) + diag step') ||| col x0\n  where\n    (step' :: R n) = vecR\n      $ SV.generate\n      $ \\i -> let stepBounds = V.index bc i - IVL.singleton (SV.index vx0 i)\n                  si = abs $ SV.index vstep i\n              in clampStep ((IVL.inf &&& IVL.sup) stepBounds) si\n    clampStep (stepLb, stepUb) stepi \n      | stepi <= stepUb = stepi\n      | -stepi >= stepLb = -stepi\n      | -stepLb < stepUb = max 0 $ 0.5 * stepUb\n      | otherwise = min 0 $ 0.5 * stepLb\n    vstep = rVec step\n    vx0 = rVec x0\n    \n\nhaftkaGurdalSimplex :: forall n. KnownNat n => \u211d -> R n -> Simplex n\nhaftkaGurdalSimplex size x0 = Simplex . colsL \n  $ V.generate $ \\j -> x0 L.& rVecIso L.%~ (SV.imap $ \\i x -> x + step i j)\n  where\n    step i j\n      | toInteger j == toInteger n' = 0\n      | toInteger j == toInteger i = q + (c * l)\n      | otherwise = q\n    q = c * (sqrt (l + 1) - 1)\n    c = size / (l * sqrt 2)\n    l = fromIntegral n'\n    n' = fromSing $ (sing :: Sing n)\n\n\ncentroid :: forall n t. (KnownNat n, Foldable t) => t (R n) -> R n\ncentroid = (/l) . FLD.foldl' (+) 0\n  where\n    l = fromIntegral . fromSing $ (sing :: Sing n)\n\n\ncentroidL :: forall m n. (KnownNat m, KnownNat n) => L m n -> R m\ncentroidL = (#> (1.0 / l))\n  where\n    l = fromIntegral . fromSing $ (sing :: Sing m)\n\n\nrealWithinRelTol :: \u211d -> \u211d -> \u211d -> Bool\nrealWithinRelTol relTol x y = (<= 0.5 * (x `absAdd` y)) . abs $ x - y\n  where absAdd = (+) `on` abs\n\nrealWithinTols :: Maybe \u211d -> Maybe \u211d -> \u211d -> \u211d -> Bool\nrealWithinTols relTol absTol x y = relTolCheck && absTolCheck \n  where \n    relTolCheck = fromMaybe True \n      $ (\\t -> realWithinRelTol t x y) <$> relTol\n    absTolCheck = fromMaybe True $ (<= abs (x - y)) <$> absTol\n\n\nsimplexRadiusTo :: (KnownNat n, Foldable t) => t (R n) -> R n -> R n\nsimplexRadiusTo xs c = vecR \n  $ SV.generate \n  $ \\i -> FLD.foldl' (\\acc -> (max `on` abs) acc . distci i . rVec) 0 xs\n  where \n    distci i v = SV.index v i - SV.index vc i\n    vc = rVec c\n\n\n--center + max step to given vertex for each dimension\nsimplexRadiusToL :: KnownNat n => Simplex n -> R n -> R n\nsimplexRadiusToL (Simplex xs) c = vecR $ SV.generate (V.index v)\n  where \n    v = (SV.maximumBy (comparing abs) . rVec) <$> lRows xsDiff -- Vector, need to convert to (R n)\n    xsDiff = xs - (c `outer` 1) -- vector not promoted to matrix\n\naffineCombWith :: KnownNat n => R n -> \u211d -> R n -> R n\naffineCombWith x cy y = x + rnScale cy (y - x)\n\n--put in helper class, maybe use coerce or something\nrnScale :: KnownNat n => \u211d -> R n -> R n\nrnScale c = L.over rVecIso $ SV.map (c *)\n\n\n--TODO write version using mean\n--toRows, map mean, list to vec\ncentroidL2 :: forall m n. Sing m -> Sing n -> L m n -> R m\ncentroidL2 (sm@SNat) (sn@SNat) = (#> (1.0 / l))\n  where\n    l = fromIntegral . fromSing $ (sing :: Sing m)\n\n", "meta": {"hexsha": "085852c367e92229811a7992031e8e6fb71e64c9", "size": 6753, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neldermead.hs", "max_stars_repo_name": "brnzhg/howod", "max_stars_repo_head_hexsha": "712f2842fe48edab3ea2645325512e540e683cf1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Neldermead.hs", "max_issues_repo_name": "brnzhg/howod", "max_issues_repo_head_hexsha": "712f2842fe48edab3ea2645325512e540e683cf1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Neldermead.hs", "max_forks_repo_name": "brnzhg/howod", "max_forks_repo_head_hexsha": "712f2842fe48edab3ea2645325512e540e683cf1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4663461538, "max_line_length": 98, "alphanum_fraction": 0.6469717163, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4439600693292915}}
{"text": "module EvalSpec (spec) where\n\nimport           Control.Monad.Error\nimport           Data.Complex\nimport           Data.Either\nimport           Data.IORef\nimport           Data.Ratio\nimport           Env\nimport           Eval\nimport           Read\nimport           System.IO.Unsafe\nimport           Test.Hspec\nimport           Types\n\n\n-- same as Main.hs\nprimitiveBindings :: IO Env\nprimitiveBindings = nullEnv >>= flip bindVars (map makePrimitiveFunc primitives)\n  where makePrimitiveFunc (var, func) = (var, PrimitiveFunc func)\n\nrunIOThrowsToLispVal :: IOThrowsError LispVal -> IO LispVal\nrunIOThrowsToLispVal action = fmap extractValue (runErrorT action)\n\nexprToVal :: String -> IOThrowsError LispVal\nexprToVal expr = liftThrows $ readExpr expr\n\nevalExpr :: Env -> String -> IO LispVal\nevalExpr env expr = runIOThrowsToLispVal $ exprToVal expr >>= eval env\n\nre expr = unsafePerformIO $ do\n  env <- primitiveBindings\n  evalExpr env expr\n\nle expr = unsafePerformIO $ do\n  env <- primitiveBindings\n  evalString env expr\n\n\nspec :: Spec\nspec = do\n  describe \"eval\" $ do\n    it \"evaluates functions\" $ do\n      re \"(+ 1 2 3)\" `shouldBe` Number 6\n      re \"(- 3 1)\" `shouldBe` Number 2\n      re \"(- 10 1 2)\" `shouldBe` Number 7\n      re \"(* 1 2 3 4 5)\" `shouldBe` Number 120\n      re \"(/ 23 7)\" `shouldBe` Number 3\n      re \"(/ 51 7 3)\" `shouldBe` Number 2\n      re \"(mod 7 3)\" `shouldBe` Number 1\n      re \"(quotient 7 3)\" `shouldBe` Number 2\n      re \"(remainder 7 3)\" `shouldBe` Number 1\n      re \"(symbol? 'a)\" `shouldBe` Bool True\n      re \"(symbol? 1)\" `shouldBe` Bool False\n      re \"(string? \\\"foo\\\")\" `shouldBe` Bool True\n      re \"(string? 1)\" `shouldBe` Bool False\n      re \"(number? 1)\" `shouldBe` Bool True\n      re \"(number? 'a)\" `shouldBe` Bool False\n      re \"(boolean? #t)\" `shouldBe` Bool True\n      re \"(boolean? 'f)\" `shouldBe` Bool False\n\n      re \"(= 1 1)\" `shouldBe` Bool True\n      re \"(= 1 2)\" `shouldBe` Bool False\n      re \"(> 1 0)\" `shouldBe` Bool True\n      re \"(> 1 2)\" `shouldBe` Bool False\n      re \"(< 1 0)\" `shouldBe` Bool False\n      re \"(< 1 2)\" `shouldBe` Bool True\n      re \"(/= 1 1)\" `shouldBe` Bool False\n      re \"(/= 1 2)\" `shouldBe` Bool True\n      re \"(>= 1 2)\" `shouldBe` Bool False\n      re \"(>= 1 1)\" `shouldBe` Bool True\n      re \"(<= 1 0)\" `shouldBe` Bool False\n      re \"(<= 1 1)\" `shouldBe` Bool True\n      re \"(&& #t #t)\" `shouldBe` Bool True\n      re \"(&& #t #f)\" `shouldBe` Bool False\n      re \"(&& #f #f)\" `shouldBe` Bool False\n      re \"(|| #t #t)\" `shouldBe` Bool True\n      re \"(|| #t #f)\" `shouldBe` Bool True\n      re \"(|| #f #f)\" `shouldBe` Bool False\n\n    it \"string?\" $ do\n      re \"(string=? \\\"a\\\" \\\"a\\\")\" `shouldBe` Bool True\n      re \"(string=? \\\"a\\\" \\\"b\\\")\" `shouldBe` Bool False\n      re \"(string<? \\\"a\\\" \\\"a\\\")\" `shouldBe` Bool False\n      re \"(string<? \\\"a\\\" \\\"b\\\")\" `shouldBe` Bool True\n      re \"(string>? \\\"a\\\" \\\"a\\\")\" `shouldBe` Bool False\n      re \"(string>? \\\"c\\\" \\\"b\\\")\" `shouldBe` Bool True\n      re \"(string<=? \\\"b\\\" \\\"a\\\")\" `shouldBe` Bool False\n      re \"(string<=? \\\"b\\\" \\\"b\\\")\" `shouldBe` Bool True\n      re \"(string>=? \\\"a\\\" \\\"b\\\")\" `shouldBe` Bool False\n      re \"(string>=? \\\"b\\\" \\\"b\\\")\" `shouldBe` Bool True\n\n    it \"if\" $ do\n      re \"(if (> 2 3) \\\"foo\\\" \\\"bar\\\")\" `shouldBe` String \"bar\"\n      re \"(if (= 3 3) (+ 2 3 (- 5 1)) \\\"unequal\\\")\" `shouldBe` Number 9\n\n    it \"car, cdr\" $ do\n      re \"(cdr '(a simple test))\" `shouldBe` List [Atom \"simple\", Atom \"test\"]\n      re \"(car (cdr '(a simple test)))\" `shouldBe` Atom \"simple\"\n      re \"(car '((this is) a test))\" `shouldBe` List [Atom \"this\", Atom \"is\"]\n      re \"(cons '(this is) 'test)\" `shouldBe` DottedList [List [Atom \"this\", Atom \"is\"]] (Atom \"test\")\n      re \"(cons '(this is) '())\" `shouldBe` List [List [Atom \"this\", Atom \"is\"]]\n\n    it \"eqv?\" $ do\n      re \"(eqv? 1 3)\" `shouldBe` Bool False\n      re \"(eqv? 3 3)\" `shouldBe` Bool True\n      re \"(eqv? 'atom 'atom)\" `shouldBe` Bool True\n\n    it \"equal?\" $ do\n      re \"(equal? 123 123)\" `shouldBe` Bool True\n      re \"(equal? 123 \\\"123\\\")\" `shouldBe` Bool True\n      re \"(equal? 123 \\\"foo\\\")\" `shouldBe` Bool False\n\n    it \"throws\" $ do\n      le \"(symbol? 1 2)\" `shouldStartWith` \"Expected 1 args;\"\n      le \"(string? 1 2)\" `shouldStartWith` \"Expected 1 args;\"\n      le \"(number? 1 2)\" `shouldStartWith` \"Expected 1 args;\"\n      le \"(boolean? 1 2)\" `shouldStartWith` \"Expected 1 args;\"\n      le \"(+ 2 \\\"two\\\")\" `shouldStartWith` \"Invalid type:\"\n      le \"(+ 2)\" `shouldStartWith` \"Expected 2 args;\"\n      le \"(what? 2)\" `shouldBe` \"Getting an unbound variable: : what?\"\n      le \"(if 1 2 3)\" `shouldStartWith` \"Invalid type:\"\n\n  describe \"env\" $ do\n    it \"defines functions\" $ do\n      env <- primitiveBindings\n\n      evalExpr env \"(define (f x y) (+ x y))\"\n      unsafePerformIO (evalExpr env \"(f 1 2)\") `shouldBe` Number 3\n\n      evalExpr env \"(define (factorial x) (if (= x 1) 1 (* x (factorial (- x 1)))))\"\n      unsafePerformIO (evalExpr env \"(factorial 10)\") `shouldBe` Number 3628800\n\n      evalExpr env \"(define (counter inc) (lambda (x) (set! inc (+ x inc)) inc))\"\n      evalExpr env \"(define my-count (counter 5))\"\n      unsafePerformIO (evalExpr env \"(my-count 3)\") `shouldBe` Number 8\n      unsafePerformIO (evalExpr env \"(my-count 6)\") `shouldBe` Number 14\n      unsafePerformIO (evalExpr env \"(my-count 5)\") `shouldBe` Number 19\n\n    it \"fails if function is not defined\" $\n      le \"(f 1 2)\" `shouldBe` \"Getting an unbound variable: : f\"\n\n    it \"defines functions\" $ do\n      env <- primitiveBindings\n      evalExpr env \"(define (f x y) (+ x y))\"\n      unsafePerformIO (evalExpr env \"(f 1 2)\") `shouldBe` Number 3\n\n    it \"fails if function is not defined\" $\n      le \"(f 1 2)\" `shouldBe` \"Getting an unbound variable: : f\"\n", "meta": {"hexsha": "03d733cf3bd58667ba6e04a11cfd5647f5610585", "size": 5735, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/EvalSpec.hs", "max_stars_repo_name": "fand/wyas48-stack", "max_stars_repo_head_hexsha": "256ef168c0914aa8d09e85a9533fc8f8347e48ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/EvalSpec.hs", "max_issues_repo_name": "fand/wyas48-stack", "max_issues_repo_head_hexsha": "256ef168c0914aa8d09e85a9533fc8f8347e48ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/EvalSpec.hs", "max_forks_repo_name": "fand/wyas48-stack", "max_forks_repo_head_hexsha": "256ef168c0914aa8d09e85a9533fc8f8347e48ca", "max_forks_repo_licenses": ["BSD-3-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.4899328859, "max_line_length": 102, "alphanum_fraction": 0.5731473409, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.44373128421121233}}
{"text": "module Algebra\n    (Adjoin (..)\n    ,FreeGroup (..)\n    ,Group (..)\n    ,Z2\n    ,plugIn\n    ,Algebra\n    ,represent\n    ,cutoff\n    ,module N\n    ) where\n\nimport Algebra.Adjoin\nimport Algebra.Group\nimport Algebra.FreeGroup\nimport Algebra.Z2\nimport Numeric.LinearAlgebra as N\n\ntype Algebra = Adjoin Z2 FreeGroup\n{--type Algegra' = [(Z2,Vector Z,FreeGroup)]\n\nplush :: (Z2,Vector Z,FreeGroup) -> Algebra' -> Algebra'\nplush e [] = [e]\nplush e1@(z1,v1,g1) (e2@(z2,v2,g2):ls) = if v1 == v2 && g1 == g2 then (if z1+z2 == 0 then (0,N.fromList $ map (\\_ -> 0) $ N.tolist v1,mempty) else (z1+z2,v1,g1)):ls else e2:(plush e1 ls)\n\ninstance Num Algebra' where\n    l1 + l2 = map (\\e -> plush e l2) l1\n    l1 * l2 = sum $ map (\\(z1,v1,g1) -> map (\\(z2,v2,g2) -> (z1*z2,v1+v2,g1<>g2)) l2) l1\n    abs = map (\\(z,v,g) -> (abs z,v,g))\n    signum = map (\\(z,v,g) -> (signum z,v,g))\n--    fromInteger x = [(fromInteger x,\n-}\ncutoff :: R\ncutoff = 0.0000000001\n\nplugIn :: (Eq f,Fractional f) => (Char -> Adjoin f FreeGroup) -> Adjoin f FreeGroup -> Adjoin f FreeGroup\nplugIn f = adjPlugIn (groupPlugIn f)\n\nrepresent :: [Char] -> Algebra -> Maybe [Vector Z]\nrepresent [] _ = Nothing\nrepresent elems expr = do\n                        { chain <- pairPlusChain expr\n                        ; vectors <- mapM (\\(_,g) -> toPseudoVector g) chain\n                        ; return $ map (\\l -> (length elems) |> [toEnum $ maybe 0 id $ lookup (elems !! i) l | i <- [0..]]) vectors\n                        }\n", "meta": {"hexsha": "f7a569ba47b9f55fd93e3c61f98df1defe4f4563", "size": 1474, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Algebra.hs", "max_stars_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_stars_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "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/Algebra.hs", "max_issues_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_issues_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-08T23:05:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T19:21:55.000Z", "max_forks_repo_path": "src/Algebra.hs", "max_forks_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_forks_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0434782609, "max_line_length": 186, "alphanum_fraction": 0.5651289009, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4435870171653579}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n\nmodule School.Types.FloatEq\n( FloatEq(..)\n, compareDouble\n) where\n\nimport Numeric.LinearAlgebra (Element)\nimport Numeric.LinearAlgebra.Data (Matrix, Vector, cols, toList, toLists)\nimport School.Train.TrainState (HandlerStore(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitGradient (UnitGradient(..))\nimport School.Unit.UnitParams (UnitParams(..))\n\nclass FloatEq a where\n  (~=) :: a -> a -> Bool\n  (~/) :: a -> a -> Bool\n  x ~= y = not (x ~/ y)\n  x ~/ y = not (x ~= y)\n\ninstance FloatEq Int where\n  (~=) = (==)\n\ninstance (FloatEq a) => FloatEq (Maybe a) where\n  Nothing ~= Nothing = True\n  (Just x) ~= (Just y) = x ~= y\n  _ ~= _ = False\n\ncompareDouble :: Double -> Double -> Double -> Bool\ncompareDouble prec d1 d2 = if abs d1 < prec\n  then abs d2 < prec\n  else abs ((d2 - d1) / d1) < prec\n\ndoubleEq :: Double -> Double -> Bool\ndoubleEq = compareDouble 5e-11\n\ninstance FloatEq Double where\n  (~=) = doubleEq\n\ninstance (FloatEq a) => FloatEq [a] where\n  l ~= m = (length l == length m)\n        && and (zipWith (~=) l m)\n\nmToList :: (Element a) => Matrix a -> [a]\nmToList = concat . toLists\n\ninstance (Element a, FloatEq a) => FloatEq (Matrix a) where\n  m1 ~= m2 = (cols m1 == cols m2)\n          && (mToList m1 ~= mToList m2)\n\ninstance (Element a, FloatEq a) => FloatEq (Vector a) where\n  v1 ~= v2 = toList v1 ~= toList v2\n\ninstance (FloatEq b) => FloatEq (Either a b) where\n  (Left _) ~= (Left _) = True\n  (Right res1) ~= (Right res2) = res1 ~= res2\n  _ ~= _ = False\n\ninstance (Element a, FloatEq a) => FloatEq (UnitActivation a) where\n  (BatchActivation m1) ~= (BatchActivation m2) = m1 ~= m2\n  _ ~= _ = False\n\ninstance (Element a, FloatEq a) => FloatEq (UnitGradient a) where\n  (BatchGradient g1) ~= (BatchGradient g2) = g1 ~= g2\n  _ ~= _ = False\n\ninstance (Element a, FloatEq a) => FloatEq (UnitParams a) where\n  AffineParams { affineBias = b1, affineWeights = w1 } ~= AffineParams { affineBias = b2, affineWeights = w2 } =\n    b1 ~= b2 && w1 ~= w2\n  EmptyParams ~= EmptyParams = True\n  _ ~= _ = False\n\ninstance (FloatEq a) => FloatEq (HandlerStore a) where\n  (CostList l1) ~= (CostList l2) = l1 ~= l2\n  NoStore ~= NoStore = True\n  _ ~= _ = False\n", "meta": {"hexsha": "9b0bd28b0d53e3beba00b92768ef64bcb5dc9b67", "size": 2220, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/Types/FloatEq.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/School/Types/FloatEq.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/School/Types/FloatEq.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8311688312, "max_line_length": 112, "alphanum_fraction": 0.6342342342, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.44334689275576045}}
{"text": "{-# language GADTs #-}\n{-# language ConstraintKinds #-}\n{-# language FlexibleContexts #-}\n\n{-# language ScopedTypeVariables #-}\n{-# LANGUAGE QuasiQuotes #-}\n{-# language TypeApplications #-}\n\nmodule FFT where\n\nimport Feldspar\nimport Feldspar.Software hiding (Arr)\nimport Feldspar.Software.Verify\nimport Feldspar.Software.Compile\n\nimport Feldspar.Array.Vector\nimport Feldspar.Array.Buffered\n\nimport Data.Bits (Bits)\nimport Data.Complex (Complex)\n\nimport Data.Selection\nimport Data.Default.Class\n\nimport Control.Monad\n\n-- language-c-quote\nimport Language.C.Quote.GCC\nimport qualified Language.C.Syntax as C\n\n-- imperative-edsl\nimport qualified Language.Embedded.Backend.C  as Imp\n\nimport Prelude hiding ((==), (/=), (>=), length)\n\n--------------------------------------------------------------------------------\n-- * FFT\n--------------------------------------------------------------------------------\n\ntype SRef    a = Reference Software a\ntype SArr    a = Array  Software a\ntype SIArr   a = IArray Software a\ntype SStore  a = Store  Software a\ntype SSyntax a = Syntax SExp a\n\n-- | Collection of constraints for immutable arrays.\ntype Immutable arr a = (\n    Manifestable Software arr a\n  , Finite   SExp arr\n  , Indexed  SExp arr, ArrElem arr ~ a\n  , Slicable SExp arr\n  )\n\n--------------------------------------------------------------------------------\n-- ** Helper functions.\n\n-- | Creates a value of type @a@ where the lowest @n@ bits are ones.\noneBits :: (Bits a, Num (SExp a), SType' a)\n  => SExp Int32 -> SExp a\noneBits n = complement (ones .<<. n)\n\n-- | Check if the @i@'th bit of @a@ is a one.\ntestBit :: (Integral a, Bits a, Num (SExp a), SType' a) =>\n  SExp a -> SExp Index -> SExp Bool\ntestBit a i = i2b (a .&. (1 .<<. i2n i))\n\n-- | Flip the @i@'th bit of @a@.\nflipBit :: (Bits a, Num (SExp a), SType' a) =>\n  SExp a -> SExp Index -> SExp a\nflipBit a i = a `xor` (1 .<<. (i2n i))\n--  SExp Index -> SExp a -> SExp a\n--flipBit i a = a `xor` (1 .<<. (i2n i))\n\n-- | \nzeroBit :: (Bits a, Num (SExp a), SType' a) =>\n  SExp Index -> SExp a -> SExp a\nzeroBit i a = a + (a .&. (ones .<<. (i2n i)))\n\n-- | Zeroes all but the lowest @i@ bits in @a@.\nleastBits :: (Bits a, Num (SExp a), SType' a) =>\n  SExp Int32 -> SExp a -> SExp a\nleastBits i a = a .&. oneBits i\n\n-- | Two to the power of @n@, i.e. @2^n@.\npow2 :: (Num (SExp a), Bits a, SType' a)\n  => SExp Index -> SExp a\npow2  n = 1 .<<. i2n n\ntwoTo n = pow2 n\n\n--------------------------------------------------------------------------------\n-- ** Riffle network.\n\n-- | Riffle indices.\nrotBit :: SExp Index -> SExp Index -> SExp Index\nrotBit k i = lefts .|. rights\n  where\n    k'     = i2n k\n    ir     = i .>>. 1\n    rights = ir .&. oneBits k'\n    lefts  = (((ir .>>. k') .<<. 1) .|. (i .&. 1)) .<<. k'\n\n-- | Riffle network for a pully array.\nriffle :: (Immutable arr a, SSyntax a)\n  => SExp Index -> arr -> SPull a\nriffle k arr = Pull (length arr) $ \\i -> arr ! rotBit k i\n\n-- | \nrevBit :: (Immutable arr a, SSyntax a)\n  => SStore a -> SExp Length -> arr -> Software (SManifest a)\nrevBit st n vec = loopStore st 1 1 (n-1) (step) vec\n  where\n    step i arr = return $ riffle i arr\n    --step :: (Immutable arr a, SSyntax a) => SExp Index -> arr -> Software (SPush a)\n--    step i arr = return $ unroll 2 $ riffle i arr\n--    step k arr = return $ pairwise @Software (\\i -> (i, rotBit k i)) $ riffle k arr\n\n--------------------------------------------------------------------------------\n-- ** Twiddle factors.\n\n-- | \ntw :: (Floating a, SType' a, SType' (Complex a))\n  => SExp Index -> SExp Index -> SExp (Complex a)\ntw n k = polar 1 (-2 * pi * i2n k / i2n n)\n\n-- | \ntwids\n  :: ( Immutable ts  (SExp (Complex a))\n     , Immutable vec (SExp (Complex a))\n     , SType' a\n     , SType' (Complex a)\n     , RealFloat a\n     )\n  => ts\n  -> SExp Index\n  -> SExp Index\n  -> SExp Length\n  -> vec\n  -> SPull (SExp (Complex a))\ntwids ts n k l vec = Pull l $ \\i ->\n  let\n    j = (leastBits (i2n k) i) .<<. (n'-1-k')\n  in\n    (testBit i k) ? ((ts!j) * (vec!i)) $ (vec!i)\n  where\n    n' = i2n n\n    k' = i2n k\n\n--------------------------------------------------------------------------------\n-- ** Butterfly.\n\n-- | Butterfly network.\nbfly\n  :: ( Immutable vec (SExp (Complex a))\n     , RealFloat a\n     , SType' a\n     , SType' (Complex a)\n     )\n  => SExp Index -> vec -> SPull (SExp (Complex a))\nbfly k as = Pull (length as) $ \\i ->\n    let a = as ! i\n        b = as ! flipBit i k\n    in  (testBit i k) ? (b-a) $ (a+b)\n\n--------------------------------------------------------------------------------\n-- ** FFT Core.\n\n-- | Core of the FFT\nfftCore\n  :: ( Immutable ts  (SExp (Complex a))\n     , Immutable vec (SExp (Complex a))\n     , RealFloat a\n     , SType' a\n     , SType' (Complex a)\n     )\n  => SStore (SExp (Complex a))\n  -> ts\n  -> SExp Length\n  -> vec\n  -> Software (SManifest (SExp (Complex a)))\nfftCore st ts n vec =\n  let\n    step k = return . twids ts n k (length vec) . bfly k\n--    step k = return . pairwise @Software (\\i -> (i, flipBit i k)) . twids ts n k (length vec) . bfly k\n  in\n    do arr <- loopStore st ((i2n n :: SExp Int32)-1) (-1) 0 (step . i2n) vec\n--       revBit st n arr\n       return arr\n\n-- | Radix-2 Decimation-In-Frequency Fast Fourier Transformation of the given\n-- complex vector. The given vector must be power-of-two sized, (for example 2,\n-- 4, 8, 16, 32, etc.) The output is non-normalized.\nfft\n  :: ( Immutable vec (SExp (Complex a))\n     , RealFloat a\n     , SType' a\n     , SType' (Complex a)\n     )\n  => SExp Length\n  -> SStore (SExp (Complex a))\n  -> vec\n  -> Software (SManifest (SExp (Complex a)))\nfft n st vec =\n  do n  <- shareM (ilog2 (length vec))\n     ts <- manifestFresh $ Pull (pow2 (n-1)) (tw (pow2 n))\n     fftCore st ts n vec\n\n--------------------------------------------------------------------------------\n\nfftCore2 ::\n  SStore (SExp (Complex Double)) ->\n  SIArr (SExp (Complex Double)) ->\n  SExp Length ->\n  SPull (SExp (Complex Double)) ->\n  Software (SIArr (SExp (Complex Double)))\nfftCore2 store iarr exp pull = do\n  let iarrm :: SManifest (SExp (Complex Double))\n      iarrm = M iarr\n  (M ibrr) <- fftCore store iarrm exp pull\n  return ibrr\n\nfft2 ::\n  SExp Length ->\n  SStore (SExp (Complex Double)) ->\n  SPull (SExp (Complex Double)) ->\n  Software (SIArr (SExp (Complex Double)))\nfft2 n store pull = do\n  (M ts) <- manifestFresh $ Pull (twoTo (n-1)) (tw (twoTo n))\n  fftCore2 store ts n pull\n\n--------------------------------------------------------------------------------\n\nexample :: Software ()\nexample = do\n  size :: SExp Length <- fget stdin\n  n :: SExp Length <- fget stdin\n  assert (1 `shiftL` n == size) \"2^n == size\"\n  assert (size >= 2) \"not too small\"\n  st   :: SStore (SExp (Complex Double)) <- newInPlaceStore size\n  arr  :: SArr   (SExp (Complex Double)) <- newArr size\n  iarr :: SIArr  (SExp (Complex Double)) <- freezeArr arr\n  fft n st iarr\n  assert (value False) \"oh no\"\n  return ()\n\n--------------------------------------------------------------------------------\n\nbad :: Software ()\nbad = do\n  size :: SExp Length <- fget stdin\n  fprintf stdout \"%d\" (share size id)\n  return ()\n\n--------------------------------------------------------------------------------\n-- FFT Bench. Copy of https://github.com/Feldspar/raw-feldspar/blob/master/examples/FFT_bench.hs\n--------------------------------------------------------------------------------\n\nprintTime_def = [cedecl|\nvoid printTime(typename clock_t start, typename clock_t end)\n{\n  printf(\"CPU time (sec): %f\\n\", (double)(end-start) / CLOCKS_PER_SEC);\n}\n|]\n\nsizeOf_double_complex :: SExp Length\nsizeOf_double_complex = 16\n  \n-- | Measure the time for 100 runs of 'fftCore' (excluding initialization) for\n-- arrays of the given size\nbenchmark :: SExp Length -> Software ()\nbenchmark n = do\n  addInclude \"<stdio.h>\"\n  addInclude \"<string.h>\"\n  addInclude \"<time.h>\"\n\n  addDefinition printTime_def\n\n  start <- newObject \"clock_t\" False\n  end   <- newObject \"clock_t\" False\n\n  st :: SStore (SExp (Complex Double)) <- newStore n\n  inp <- unsafeFreezeStore n st\n  callProc \"memset\"\n      [ iarrArg (manifest inp)\n      , valArg (0 :: SExp Index)\n      , valArg (n*sizeOf_double_complex)\n      ]\n\n  n  <- shareM (ilog2 (length inp))\n  ts <- manifestFresh $ Pull (twoTo (n-1)) (tw (twoTo n))\n  -- Change `manifestFresh` to `return` to avoid pre-computing twiddle factors\n\n  callProcAssign start \"clock\" []\n\n  for 0 1 99 $ \\(_ :: SExp Index) ->\n    void $ fftCore st ts n inp\n\n  callProcAssign end \"clock\" []\n  callProc \"printTime\" [objArg start, objArg end]\n\nrunBenchmark n = runCompiled'\n    (def :: CompilerOpts) --{compilerAssertions = select []}\n    -- Note: important to turn off assertions when running the benchmarks\n    --       (in old Raw-Feldspar that is, Co-Feldspar gets rid of them)\n    def {Imp.externalFlagsPre = [\"-O3\"], Imp.externalFlagsPost = [\"-lm\"]}\n    (benchmark n)\n\n--------------------------------------------------------------------------------\n\ndummy :: Software ()\ndummy = do\n  size :: SExp Length <- fget stdin\n  n :: SExp Length <- fget stdin\n  assert (1 `shiftL` n == size) \"2^n == size\"\n  assert (size >= 2) \"not too small\"\n  st   :: SStore (SExp (Complex Double)) <- newInPlaceStore size\n  arr  :: SArr   (SExp (Complex Double)) <- newArr size\n  iarr :: SIArr  (SExp (Complex Double)) <- freezeArr arr\n  fft n st iarr\n  fft n st iarr\n  assert (value False) \"oh no\"\n  return ()\n\n--------------------------------------------------------------------------------\n", "meta": {"hexsha": "95cdf5595d56f02b462aa8e8c0949d3f5874b1d9", "size": 9459, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/FFT.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": "examples/FFT.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": "examples/FFT.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": 29.1944444444, "max_line_length": 104, "alphanum_fraction": 0.5393804842, "num_tokens": 2769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.44325002679451847}}
{"text": "{-# LANGUAGE CPP #-}\n--------------------------------------------------------------------------------\n{- |\nModule      :  Numeric.LinearAlgebra.HMatrix\nCopyright   :  (c) Alberto Ruiz 2006-14\nLicense     :  BSD3\nMaintainer  :  Alberto Ruiz\nStability   :  provisional\n\ncompatibility with previous version, to be removed\n\n-}\n--------------------------------------------------------------------------------\n\nmodule Numeric.LinearAlgebra.HMatrix (\n    module Numeric.LinearAlgebra,\n    (\u00a6),(\u2014\u2014),\u211d,\u2102,(<\u00b7>),app,mul, cholSH, mbCholSH, eigSH', eigenvaluesSH', geigSH'\n) where\n\nimport Numeric.LinearAlgebra\nimport Internal.Util\nimport Internal.Algorithms(cholSH, mbCholSH, eigSH', eigenvaluesSH', geigSH')\n#if MIN_VERSION_base(4,11,0)\nimport Prelude hiding ((<>))\n#endif\n\ninfixr 8 <\u00b7>\n(<\u00b7>) :: Numeric t => Vector t -> Vector t -> t\n(<\u00b7>) = dot\n\napp :: Numeric t => Matrix t -> Vector t -> Vector t\napp m v = m #> v\n\nmul :: Numeric t => Matrix t -> Matrix t -> Matrix t\nmul a b = a <> b\n\n", "meta": {"hexsha": "57e5cf1ee208b54f80682f77a8cc02d686994b71", "size": 979, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/HMatrix.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/LinearAlgebra/HMatrix.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/HMatrix.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 26.4594594595, "max_line_length": 81, "alphanum_fraction": 0.5505617978, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.44295640250528584}}
{"text": "module Main where\n\nimport System.Environment (getArgs)\nimport qualified Statistics.Test.Types as Stats\nimport Jakway.Blackjack.Random.Checks\nimport Jakway.Blackjack.Random.Options\nimport Jakway.Blackjack.Util (die)     -- ^ die is implemented here for compatibility with older GHC versions\nimport Jakway.Blackjack.AI\n\nmain :: IO ()\nmain = do\n    args <- getArgs\n    conf <- getConfig args\n\n    -- | TODO: make the RNG max range an option\n    let rngMaxRange = toInteger $ 2 ^ 25\n\n    let distrib = distribution conf\n        pval = pvalue conf\n        n = sampleSize conf\n        r = rngSampleSize conf\n        dealerAI = BasicDealer\n        playerAIs = [BasicPlayer]\n    \n    if (n <= 104) then die \"Samples must be >104.\" else return ()\n\n    case distrib of EvenDistribution -> testDeckEvenDistribution pval n dealerAI playerAIs >>= printResult\n                    RNGDistribution -> testRNGDistribution pval n r rngMaxRange dealerAI playerAIs >>= printResult\n                    _ -> die \"Fatal error, unknown test!\"\n\n\nprintResult :: Stats.TestResult -> IO ()\nprintResult (Stats.Significant) = putStrLn $ \"The test result is: Significant.  There is evidence to conclude that the deck IS NOT an unbiased source of randomness.\"\nprintResult (Stats.NotSignificant) = putStrLn $ \"The test result is: Not Significant.  There is insufficient evidence to conclude that the deck is not an unbiased source of randomness.\"\n", "meta": {"hexsha": "3289d9469e464fde2932e96876de426babf0eafe", "size": 1414, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "main/RandomnessChecker.hs", "max_stars_repo_name": "tjakway/haskell-blackjack", "max_stars_repo_head_hexsha": "f231d935070fc26f4fa4f77ede3f46f590ba96bb", "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": "main/RandomnessChecker.hs", "max_issues_repo_name": "tjakway/haskell-blackjack", "max_issues_repo_head_hexsha": "f231d935070fc26f4fa4f77ede3f46f590ba96bb", "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": "main/RandomnessChecker.hs", "max_forks_repo_name": "tjakway/haskell-blackjack", "max_forks_repo_head_hexsha": "f231d935070fc26f4fa4f77ede3f46f590ba96bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4, "max_line_length": 185, "alphanum_fraction": 0.7093352192, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.4428055963966551}}
{"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE Strict #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -Wno-orphans #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n\nimport qualified Data.Vector as V\nimport qualified NumHask.Array.Dynamic as D\nimport qualified NumHask.Array.Fixed as F\nimport qualified NumHask.Array.HMatrix as H\nimport qualified Numeric.LinearAlgebra as HMatrix\nimport Perf\nimport NumHask.Prelude as P hiding (option)\nimport Data.Text (unpack, Text)\nimport Options.Applicative\nimport Control.Monad\n\ndata RunType = RunMMult | RunDotSum | RunDotVector deriving (Eq, Show)\n\ndata StatType = StatAverage | StatMedian | StatBest deriving (Eq, Show)\n\ndata Options = Options\n  { optionRuns :: Int,\n    optionMSize :: Int,\n    optionMMult :: Bool,\n    optionDotSum :: Bool,\n    optionDotVector :: Bool,\n    optionStatType :: StatType\n  } deriving (Eq, Show)\n\noptions :: Parser Options\noptions = Options <$>\n  option auto (long \"runs\" <> short 'r' <> help \"number of runs to perform\") <*>\n  option auto (long \"matrix-size\" <> short 'm' <> help \"size of square matrix\") <*>\n  switch (long \"include matrix-multiplication calc\" <> short 'x') <*>\n  switch (long \"dot-sum\" <> help \"include dot sum (+) calc\" <> short 'd') <*>\n  switch (long \"dot-vector\" <> help \"include dot vector calc\" <> short 'v') <*>\n  stat\n\nopts :: ParserInfo Options\nopts = info (options <**> helper)\n  (fullDesc <> progDesc \"benchmark testing\" <> header \"A performance benchmark for numhask\")\n\nstat :: Parser StatType\nstat =\n  flag' StatBest (long \"best\" <> help \"report upper decile\") <|>\n  flag' StatMedian (long \"median\" <> help \"report median\") <|>\n  pure StatAverage\n\ntickStat :: StatType -> [Cycle] -> Text\ntickStat StatBest = tenth\ntickStat StatMedian = median\ntickStat StatAverage = average\n\nmain :: IO ()\nmain = do\n  o <- execParser opts\n  let !n = optionRuns o\n  let s = optionStatType o\n  _ <- warmup 100\n\n  putStrLn \"mmult 10x10\"\n\n  when (optionMMult o) $ do\n    runHMatrix s n\n    runNHHMatrix s n\n    runF s n\n    runD s n\n    when (optionDotSum o) (runFDS s n)\n\n  when (optionDotVector o) $ do\n    runDotV s n\n    runDotF s n\n    runDotD s n\n\nrunHMatrix :: StatType -> Int -> IO ()\nrunHMatrix s n = do\n  -- HMatrix 10x10 matrix multiplication\n  let ticksH x = ticks n (x HMatrix.<>) x\n  let !h10 = (10 HMatrix.>< 10) [1 :: HMatrix.R ..]\n  th10 <- ticksH h10\n  putStrLn $ unpack $ \"hmatrix \" <> tickStat s (fst th10)\n\nrunNHHMatrix :: StatType -> Int -> IO ()\nrunNHHMatrix s n = do\n  -- NumHask.Array.HMatrix\n  let ticksH' x = ticks n (x `H.mmult`) x\n  let !h'10 = [1 .. 100] :: H.Array '[10, 10] Double\n  th'10 <- ticksH' h'10\n  putStrLn $ unpack $ \"numhask-hmatrix \" <> tickStat s (fst th'10)\n\nrunF :: StatType -> Int -> IO ()\nrunF s n = do\n  -- NumHask.Array.Fixed\n  let ticksF x = ticks n (x `F.mmult`) x\n  let !f10 = [1 .. 100] :: F.Array '[10, 10] Double\n  tf10 <- ticksF f10\n  putStrLn $ unpack $ \"Fixed \" <> tickStat s (fst tf10)\n\nrunFDS :: StatType -> Int -> IO ()\nrunFDS s n = do\n  -- NumHask.Array.Fixed.dot\n  let ticksF x = ticks n (F.dot sum (+) x) x\n  let !f10 = [1 .. 100] :: F.Array '[10, 10] Double\n  tf10 <- ticksF f10\n  putStrLn $ unpack $ \"Fixed-dotsum \" <> tickStat s (fst tf10)\n\nrunD :: StatType -> Int -> IO ()\nrunD s n = do\n  -- NumHask.Array.Dynamic\n  let !d10 = D.fromFlatList [10, 10] [1 .. 100] :: D.Array Double\n  let ticksD x = ticks n (x `D.mmult`) x\n  td10 <- ticksD d10\n  putStrLn $ unpack $ \"Dynamic \" <> tickStat s (fst td10)\n\nrunDotV :: StatType -> Int -> IO ()\nrunDotV s n = do\n  -- Vector dot\n  let !vv = V.fromList [1 .. 100] :: V.Vector Double\n  let ticksDotv x = ticks n (sum . V.zipWith (*) x) x\n  tvd <- ticksDotv vv\n  putStrLn $ unpack $ \"Vector-dot \" <> tickStat s (fst tvd)\n\nrunDotF :: StatType -> Int -> IO ()\nrunDotF s n = do\n  -- Fixed Dot\n  let !vf = P.fromList [1 .. 100] :: F.Array '[100] Double\n  let ticksDotF x = ticks n (F.dot sum (+) x) x\n  tfd <- ticksDotF vf\n  putStrLn $ unpack $ \"Fixed-dot \" <> tickStat s (fst tfd)\n\nrunDotD :: StatType -> Int -> IO ()\nrunDotD s n = do\n  -- Dynamic Dot\n  let !vd = D.fromFlatList [100] [1 .. 100] :: D.Array Double\n  let !vd2 = D.fromFlatList [100] [101 .. 200] :: D.Array Double\n  let ticksDotD x = ticks n (D.dot sum (+) vd2) x\n  tdd <- ticksDotD vd\n  putStrLn $ unpack $ \"Dynamic-dot \" <> tickStat s (fst tdd)\n  pure ()\n", "meta": {"hexsha": "db4bb6be221eb5f19f6207d02f2564e7789ebaf0", "size": 4630, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench.hs", "max_stars_repo_name": "tonyday567/numhask-bench", "max_stars_repo_head_hexsha": "e330c34553b71cbe72b969f25557caa40a037af2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-05-19T13:53:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T08:19:10.000Z", "max_issues_repo_path": "bench.hs", "max_issues_repo_name": "tonyday567/numhask-bench", "max_issues_repo_head_hexsha": "e330c34553b71cbe72b969f25557caa40a037af2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench.hs", "max_forks_repo_name": "tonyday567/numhask-bench", "max_forks_repo_head_hexsha": "e330c34553b71cbe72b969f25557caa40a037af2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6622516556, "max_line_length": 92, "alphanum_fraction": 0.6440604752, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.442690370421656}}
{"text": "{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}\n\nimport qualified Prelude\n\nimport qualified Data.Complex as Complex\n\nimport Feldspar.Run\nimport Feldspar.Data.Vector\nimport Feldspar.Data.Buffered\n\nimport qualified Test.QuickCheck as QC\nimport qualified Test.QuickCheck.Monadic as QC\n\nimport Test.Tasty\nimport Test.Tasty.HUnit\nimport Test.Tasty.QuickCheck\n\nimport qualified Tut1_HelloWorld            as Tut1\nimport qualified Tut2_ExpressionsAndTypes   as Tut2\nimport qualified Tut3_Vectors               as Tut3\nimport qualified Tut4_MemoryManagement      as Tut4\nimport qualified Tut5_Matrices              as Tut5\nimport qualified Tut6_Testing               as Tut6\nimport qualified Tut7_ImperativeProgramming as Tut7\nimport qualified Tut8_SequentialVectors     as Tut8\nimport qualified Concurrent\nimport DFT\nimport FFT\n\n\n\nalmostEq a b\n    =          Complex.magnitude d Prelude.< 1e-7\n    Prelude.&& Complex.phase d     Prelude.< 1e-7\n  where\n    d = abs (a-b)\n\na ~= b = Prelude.and $ Prelude.zipWith almostEq a b\n\nwrapStore :: (Syntax a, Finite (vec a), MonadComp m) =>\n    (Store a -> vec a -> m b) -> vec a -> m b\nwrapStore f v = do\n    st <- newStore $ length v\n    f st v\n\nfftS u = wrapStore (flip fft u)  :: DManifest (Complex Double) -> _\nifftS  = wrapStore (flip ifft 1) :: DManifest (Complex Double) -> _\n\nprop_fft_dft dft' fft' = QC.monadicIO $ do\n    n   :: Int              <- QC.pick $ QC.choose (2,5)\n    inp :: [Complex Double] <- QC.pick $ QC.vector (2 Prelude.^ n)\n    outd <- QC.run $ dft' inp\n    outf <- QC.run $ fft' inp\n    QC.assert (outd ~= outf)\n\nprop_inverse f fi = QC.monadicIO $ do\n    n   :: Int              <- QC.pick $ QC.choose (2,5)\n    inp :: [Complex Double] <- QC.pick $ QC.vector (2 Prelude.^ n)\n    out1 <- QC.run $ f inp\n    out2 <- QC.run $ fi out1\n    QC.assert (inp ~= out2)\n\nprop_fib fb1 fb2 = QC.monadicIO $ do\n    n   <- QC.pick $ QC.choose (0,40)\n    fs1 <- QC.run $ fb1 n\n    fs2 <- QC.run $ fb2 n\n    QC.assert (fs1 Prelude.== fs2)\n\nmain =\n    marshalledM (return . dft)  $ \\dft'  ->\n    marshalledM (return . idft) $ \\idft' ->\n    marshalledM (fftS 1)        $ \\fft1  ->\n    marshalledM (fftS 2)        $ \\fft2  ->\n    marshalledM ifftS           $ \\ifft' ->\n\n    marshalled (return . Tut8.fibSeq) $ \\fb1 ->\n    marshalled (\\n -> return $ Pull n Tut2.fib) $ \\fb2 ->\n\n      defaultMain $ testGroup \"tests\"\n        [ testCase \"Tut1\"       Tut1.testAll\n        , testCase \"Tut2\"       Tut2.testAll\n        , testCase \"Tut3\"       Tut3.testAll\n        , testCase \"Tut4\"       Tut4.testAll\n        , testCase \"Tut5\"       Tut5.testAll\n        , testCase \"Tut6\"       Tut6.testAll\n        , testCase \"Tut7\"       Tut7.testAll\n        , testCase \"Tut8\"       Tut8.testAll\n        , testCase \"Concurrent\" Concurrent.testAll\n        , testProperty \"fft1_dft\" $ prop_fft_dft dft' fft1\n        , testProperty \"fft2_dft\" $ prop_fft_dft dft' fft2\n        , testProperty \"dft_idft\" $ prop_inverse dft' idft'\n        , testProperty \"fft_ifft\" $ prop_inverse fft1 ifft'\n        , testProperty \"fib\"      $ prop_fib fb1 fb2\n        ]\n\n  where\n    marshalledM = marshalled' def def {externalFlagsPost = [\"-lm\"]}\n\n", "meta": {"hexsha": "054b7a6ed8d982a29ced34bd39a1be341cb9bc31", "size": 3273, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Examples.hs", "max_stars_repo_name": "Abhiroop/mu-feldspar", "max_stars_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Examples.hs", "max_issues_repo_name": "Abhiroop/mu-feldspar", "max_issues_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Examples.hs", "max_forks_repo_name": "Abhiroop/mu-feldspar", "max_forks_repo_head_hexsha": "2a3afd53ea9d0139a4f33f0015321f84fddb5159", "max_forks_repo_licenses": ["BSD-3-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.7766990291, "max_line_length": 67, "alphanum_fraction": 0.6245035136, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.44243559108586544}}
{"text": "{-# LANGUAGE BangPatterns              #-}\r\n{-# LANGUAGE ExistentialQuantification #-}\r\n{-# LANGUAGE FlexibleContexts          #-}\r\n{-# LANGUAGE RecordWildCards           #-}\r\n{-# LANGUAGE ScopedTypeVariables       #-}\r\n\r\nmodule Main where\r\n\r\nimport           Control.Concurrent (threadDelay)\r\nimport           Control.Concurrent.Async\r\nimport           Control.Concurrent.MVar\r\nimport           Control.Monad\r\nimport           Data.IORef\r\nimport           Data.Time.Clock.POSIX\r\nimport           Data.Time.Units\r\nimport           Data.Vector (Vector, fromList)\r\nimport qualified Data.Vector as V (length)\r\nimport           Data.Word (Word32)\r\nimport           Network.QDisc.Fair\r\nimport           Network.Transport.TCP (QDisc (..), simpleOnePlaceQDisc, simpleUnboundedQDisc)\r\nimport           Statistics.Distribution\r\nimport           Statistics.Distribution.Exponential\r\nimport           Statistics.Distribution.Normal\r\nimport           Statistics.Distribution.Uniform\r\nimport qualified Statistics.Sample as Sample\r\nimport           System.Environment (getArgs)\r\nimport           System.Random.MWC\r\n\r\n-- | A writer is determined by some continuous distribution giving the duration\r\n--   (in microseconds) between successive data being made available.\r\ndata SimulationWriter = forall distr . ContGen distr => SimulationWriter distr\r\n\r\n-- | A reader is determined by some continuous distribution giving the duration\r\n--   (in microseconds) between successive reads (how long the reader thread\r\n--   works between taking events).\r\ndata SimulationReader = forall distr . ContGen distr => SimulationReader distr\r\n\r\ndata Scenario = Scenario {\r\n      sim_reader  :: SimulationReader\r\n    , sim_writers :: [SimulationWriter]\r\n    }\r\n\r\ndata SimulationParameters = SimulationParameters {\r\n      sim_scenario :: Scenario\r\n      -- | How long the simulation should run.\r\n    , sim_duration :: Second\r\n      -- | The QDisc to use.\r\n    , sim_qdisc    :: QDisc ()\r\n      -- | A seed for randomness.\r\n    , sim_seed     :: Word32\r\n    }\r\n\r\ntype Latency = Double\r\n\r\n-- | The output of a simulation is, for each writer, the samples of actual\r\n--   delays observed when trying to write: how long it was blocked on\r\n--   trying to enqueue. The number of samples is the number of writes it\r\n--   made.\r\ndata SimulationOutput = SimulationOutput {\r\n      sim_writer_outputs :: [Vector Latency]\r\n    }\r\n\r\ninstance Show SimulationOutput where\r\n    show (SimulationOutput vecs) = concat $ flip fmap vecs $ \\vec -> concat [\r\n          \"Samples (writes): \", show (V.length vec), \"\\n\"\r\n        , \"Latency (microseconds):\\n\"\r\n        , \"  Mean: \", show (Sample.mean vec), \"\\n\"\r\n        , \"  Std. Dev.: \", show (Sample.stdDev vec), \"\\n\\n\"\r\n        ]\r\n\r\ndata QDiscChoice = Fair | OnePlace | Unbounded\r\n\r\nmakeQDisc :: QDiscChoice -> IO (QDisc t)\r\nmakeQDisc choice = case choice of\r\n    Fair      -> fairQDisc (const (return Nothing))\r\n    Unbounded -> simpleUnboundedQDisc\r\n    OnePlace  -> simpleOnePlaceQDisc\r\n\r\nunfairScenario :: Scenario\r\nunfairScenario = Scenario {\r\n      -- Difference between fair and one-place is very clear here.\r\n      -- The two fast writers get the same number of writes in either case.\r\n      -- One-place gives the slow writer half as many writes, but fair gives\r\n      -- it a lot more. The cycle time (time to read from all 3 writers) is\r\n      -- the slow writer's write delay, so we expect that the slow writer\r\n      -- should be able to write on every cycle.\r\n      sim_reader = SimulationReader (uniformDistr 5000 5001)\r\n    , sim_writers = [\r\n            SimulationWriter (uniformDistr 4999 5000)\r\n          , SimulationWriter (uniformDistr 4999 5000)\r\n          , SimulationWriter (uniformDistr 14999 15000)\r\n          ]\r\n    }\r\n\r\n-- | A normally-distributed reader (mean and std. dev. configurable) and\r\n--   n exponentially-distributed writers (means configurable).\r\ntypicalScenario :: (Double, Double) -> [Double] -> Scenario\r\ntypicalScenario (rmean, rstd_dev) writers = Scenario {\r\n      sim_reader = SimulationReader (normalDistr rmean rstd_dev)\r\n    , sim_writers = flip fmap writers $ \\wmean -> SimulationWriter (exponential (1/wmean))\r\n    }\r\n\r\nsimpleSimulationParameters :: QDisc () -> Second -> Scenario -> SimulationParameters\r\nsimpleSimulationParameters qdisc duration scenario = SimulationParameters {\r\n      sim_scenario = scenario\r\n    , sim_duration = duration\r\n    , sim_qdisc = qdisc\r\n    , sim_seed = 42\r\n    }\r\n\r\n-- | Run a simulation.\r\nsimulate :: SimulationParameters -> IO SimulationOutput\r\nsimulate SimulationParameters{..} = do\r\n\r\n    let Scenario{..} = sim_scenario\r\n\r\n    -- All threads will wait on this.\r\n    -- Threads will loop, and at each iteration will read it. If it's True,\r\n    -- they'll stop.\r\n    startStop :: MVar Bool <- newEmptyMVar\r\n\r\n    -- Spawn the reader.\r\n    refs <- withAsync (reader 0 sim_reader) $ \\readerThread -> do\r\n        -- Spawn the writers.\r\n        writerThreadsAndRefs <- forM (zip [1..] sim_writers) $ \\(seed', sim_writer) -> do\r\n            (ref, doWrites) <- writer startStop seed' sim_writer\r\n            --withAsync doWrites $ \\thread -> return (ref, thread)\r\n            thread <- async doWrites\r\n            return (ref, thread)\r\n        -- Duration is in seconds.\r\n        putMVar startStop False\r\n        threadDelay $ fromIntegral sim_duration * 1000000\r\n        swapMVar startStop True\r\n        forM writerThreadsAndRefs $ \\(ref, thread) -> do\r\n            wait thread\r\n            return ref\r\n\r\n    -- Reader and writers are all killed. Results available in the IORefs.\r\n    vectors <- forM refs (fmap fromList . readIORef)\r\n\r\n    return $ SimulationOutput ((fmap . fmap) fromIntegral vectors)\r\n\r\n    where\r\n\r\n    reader :: Word32 -> SimulationReader -> IO ()\r\n    reader seed' (SimulationReader distribution) = do\r\n        gen <- initialize (fromList [sim_seed, seed'])\r\n        let readLoop = do\r\n                () <- qdiscDequeue sim_qdisc\r\n                -- Unlike for writers, the reader delays are always respected,\r\n                -- as the delay is independent of how long the reader waits for\r\n                -- a value from qdiscDequeue.\r\n                delay :: Microsecond <- fromIntegral . round <$> genContVar distribution gen\r\n                threadDelay (fromIntegral delay)\r\n                readLoop\r\n        readLoop\r\n\r\n    writer :: MVar Bool -> Word32 -> SimulationWriter -> IO (IORef [Microsecond], IO ())\r\n    writer control seed' (SimulationWriter distribution) = do\r\n        ref <- newIORef []\r\n        gen <- initialize (fromList [sim_seed, seed'])\r\n        -- The writer's distribution determines the duration between the points\r\n        -- in time when new data are made available, and this is independent\r\n        -- of how long it takes to actually do the write. For instance, if\r\n        -- the writer is blocked on enqueue for 2 seconds, and the distribution\r\n        -- says there will be data available every 1 second, then 2 data will\r\n        -- be immediately available after the enqueue finishes.\r\n        let writeLoop :: Microsecond -> IO ()\r\n            writeLoop surplusWait = do\r\n                stop <- readMVar control\r\n                unless stop $ do\r\n                    nextDelay :: Microsecond <- fromIntegral . round <$> genContVar distribution gen\r\n                    let actualDelay = nextDelay - surplusWait\r\n                    when (actualDelay > 0) $ do\r\n                        threadDelay (fromIntegral actualDelay)\r\n                    start <- getPOSIXTime\r\n                    qdiscEnqueue sim_qdisc undefined undefined ()\r\n                    end <- getPOSIXTime\r\n                    let latency :: Microsecond\r\n                        !latency = fromIntegral . round $ (realToFrac (end - start) :: Double) * 1000000\r\n                    modifyIORef' ref ((:) latency)\r\n                    let !surplusWait' = max 0 (surplusWait + latency - nextDelay)\r\n                    writeLoop surplusWait'\r\n        return (ref, writeLoop 0)\r\n\r\nmain :: IO ()\r\nmain = do\r\n    args <- getArgs\r\n    qdiscChoice <- case args of\r\n        \"unbounded\" : _ -> putStrLn \"Using unbounded QDisc\" >> return Unbounded\r\n        \"one_place\" : _ -> putStrLn \"Using one-place QDisc\" >> return OnePlace\r\n        _               -> putStrLn \"Using fair QDisc\" >> return Fair\r\n    duration :: Int <- case args of\r\n        _ : n : _ -> case reads n of\r\n            [(n', \"\")] -> return n'\r\n        _ -> return 10\r\n    qdisc <- makeQDisc qdiscChoice\r\n    --let scenario = typicalScenario (1000, 25) [800, 900, 1000, 1100, 1200]\r\n    let scenario = unfairScenario\r\n    results <- simulate $ simpleSimulationParameters qdisc (fromIntegral duration) scenario\r\n    putStrLn \"\"\r\n    print results\r\n", "meta": {"hexsha": "f34d2b2bf4efbc1308ba2e7c6ad8ad12f757792b", "size": 8712, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "networking/src/Network/QDisc/Simulation.hs", "max_stars_repo_name": "meanpeace52/Haskell-Cryptocurrency-Kami", "max_stars_repo_head_hexsha": "010366386e09eadfe3da71f17b1df282b1a62e0c", "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": "networking/src/Network/QDisc/Simulation.hs", "max_issues_repo_name": "meanpeace52/Haskell-Cryptocurrency-Kami", "max_issues_repo_head_hexsha": "010366386e09eadfe3da71f17b1df282b1a62e0c", "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": "networking/src/Network/QDisc/Simulation.hs", "max_forks_repo_name": "meanpeace52/Haskell-Cryptocurrency-Kami", "max_forks_repo_head_hexsha": "010366386e09eadfe3da71f17b1df282b1a62e0c", "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": 42.9162561576, "max_line_length": 105, "alphanum_fraction": 0.6241965106, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.44236386167027303}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes, FlexibleContexts, NamedFieldPuns #-}\n\nmodule School.TestUtils\n( CostFunc\n, addClasses\n, assertRight\n, def\n, diffCost\n, diffInput\n, doCost\n, dummyList\n, dummyMatrix\n, empty\n, fromLeft\n, fromRight\n, getRandDouble\n, isSorted\n, jTest\n, matIndexes\n, randomAffineParams\n, randomMatrix\n, randomMatrixL\n, randomNNInts\n, randomVector\n, singleClassOutput\n, testIOCatch\n, testState\n, unitCorrect\n, weight1\n, whenPrint\n) where\n\nimport Conduit (ConduitM, liftIO, runConduit)\nimport Control.Exception (catch)\nimport Control.Monad (when)\nimport Data.Default.Class (def)\nimport Data.Either (either)\nimport Data.List (sort)\nimport Data.Void (Void)\nimport Numeric.LinearAlgebra ((><), (|>), Element, IndexOf, Matrix, R, Vector, accum, assoc, fromColumns, fromList, fromRows, size, sumElements, toColumns)\nimport School.Train.AppTrain (AppTrain, runAppTrain)\nimport School.Train.TrainState (TrainState)\nimport School.Types.Slinky (Slinky)\nimport School.Unit.CostFunction (CostFunction(..))\nimport School.Unit.CostParams (CostParams)\nimport School.Unit.Unit (Unit(..))\nimport School.Unit.UnitGradient (UnitGradient(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitParams (UnitParams(..))\nimport School.Unit.WeightDecay (weightDecay)\nimport School.Utils.Double (doubleRange)\nimport System.Exit (ExitCode(..))\nimport System.Random (getStdRandom, randomR)\nimport Test.QuickCheck.Monadic (PropertyM, assert)\n\ntestIOCatch :: IO a -> PropertyM IO ExitCode\ntestIOCatch action = liftIO $\n  catch (action >> (return ExitSuccess))\n        return\n\n\nassertRight :: (b -> Bool)\n            -> Either a b\n            -> PropertyM IO ()\nassertRight f = either (const $ assert False)\n                       (\\x -> assert $ f x)\n\ntestState :: ConduitM () Void (AppTrain R) b\n          -> TrainState R\n          -> PropertyM IO (Either String (b, TrainState R))\ntestState conduit state =\n  liftIO . (runAppTrain state) . runConduit $ conduit\n\nisSorted :: (Ord a) => [a] -> Bool\nisSorted xs = xs == (reverse . sort $ xs)\n\ndummyList :: (Num a) => Int -> Int -> [a]\ndummyList r c = map fromIntegral [ r*i + j | i <- [1..r], j <- [1..c] ]\n\ndummyMatrix :: Int -> Int -> Matrix Double\ndummyMatrix r c = r >< c $ dummyList r c\n\ngetRandDouble :: IO Double\ngetRandDouble =\n  getStdRandom (randomR doubleRange)\n\nrandomNNInts :: Int -> Int -> IO [Int]\nrandomNNInts maxInt n =\n  sequence . (replicate n) $ getStdRandom (randomR (0, maxInt))\n\nmatMax :: Double\nmatMax = 1e3\n\nrandomMatrix :: Int -> Int -> IO (Matrix R)\nrandomMatrix nRows nCols = do\n  let nEls = nRows * nCols\n  inputList <- sequence . (replicate nEls) $ getStdRandom (randomR (-matMax, matMax))\n  return $ (nRows >< nCols) inputList\n\nrandomMatrixL :: Double -> Int -> Int -> IO (Matrix R)\nrandomMatrixL limit nRows nCols = do\n  let nEls = nRows * nCols\n  inputList <- sequence . (replicate nEls) $ getStdRandom (randomR (-limit, limit))\n  return $ (nRows >< nCols) inputList\n\nrandomVector :: Int -> IO (Vector R)\nrandomVector n = do\n  inputList <- sequence . (replicate n) $ getStdRandom (randomR (-matMax, matMax))\n  return $ n |> inputList\n\nrandomAffineParams :: Int\n                   -> Int\n                   -> IO (UnitParams R)\nrandomAffineParams fSize oSize = do\n  affineBias <- randomVector oSize\n  affineWeights <- randomMatrix oSize fSize\n  return AffineParams { affineBias\n                      , affineWeights\n                      }\n\ntoPrint :: (Show a) => String -> a -> IO ()\ntoPrint tag val = putStrLn $ tag ++ \" \" ++ (show val)\n\nwhenPrint :: (Show a) => Bool -> [String] -> [a] -> IO ()\nwhenPrint cond tags vals = do\n  when cond (sequence_ $ zipWith toPrint tags vals)\n\ntype CostFunc = UnitActivation R -> Double\n\njTest :: CostFunc\njTest (BatchActivation m) = sumElements m\njTest _ = 0\n\ndiffInput :: Unit R\n          -> UnitParams R\n          -> UnitActivation R\n          -> Double\n          -> IndexOf Matrix\n          -> Double\ndiffInput unit params input eps idx =\n  (jAdd - jSub) / (2*eps) where\n    outAdd = apply unit params (alterInput eps idx input)\n    outSub = apply unit params (alterInput (-eps) idx input)\n    jAdd = jTest outAdd\n    jSub = jTest outSub\n\nfromRight :: b -> Either a b -> b\nfromRight b = either (const b) id\n\nfromLeft :: a -> Either a b -> a\nfromLeft b = either id (const b)\n\ndiffCost :: CostFunction R m\n         -> UnitActivation R\n         -> Double\n         -> IndexOf Matrix\n         -> Slinky CostParams\n         -> Double\ndiffCost costFunc input eps idx costParams = let\n  jAdd = computeCost costFunc (alterInput eps idx input) costParams\n  jSub = computeCost costFunc (alterInput (-eps) idx input) costParams\n  in (fromRight 0 jAdd - fromRight 0 jSub) / (2*eps)\n\nalterInput :: AlterInput\nalterInput change idx (BatchActivation m) =\n  BatchActivation $ accum m (+) [(idx, change)]\nalterInput _ _ _ = ApplyFail \"alterInput error\"\n\ntype AlterInput = Double\n               -> IndexOf Matrix\n               -> UnitActivation R\n               -> UnitActivation R\n\nmatIndexes :: Int -> Int -> [IndexOf Matrix]\nmatIndexes r c = [ (j, k) | j <- [0..r-1], k <- [0..c-1] ]\n\nempty :: (Element a) => Matrix a\nempty = (0><0) []\n\nweight1 :: (Monad m) => CostFunction R m\nweight1 = weightDecay 1\n\ndoCost :: (Element a, Num a)\n       => CostFunction a m\n       -> UnitActivation a\n       -> Slinky CostParams\n       -> (a, UnitGradient a)\ndoCost costFunction activation params =\n  fromRight (0, BatchGradient empty) result where\n    result = do\n      cost <- computeCost costFunction activation params\n      grad <- derivCost costFunction activation params\n      return (cost, grad)\n\nappCol :: (Element a)\n       => Vector a\n       -> Matrix a\n       -> Matrix a\nappCol v =\n  fromColumns . (flip (++) $ [v]) . toColumns\n\naddClasses :: (Element a, Num a)\n           => [Int]\n           -> Matrix a\n           -> Matrix a\naddClasses classes mat = appCol v mat where\n  v = fromList . (map fromIntegral) $ classes\n\nsingleClassOutput :: Int -> [Int] -> UnitActivation R\nsingleClassOutput nClasses =\n  BatchActivation . fromRows . (map (\\idx -> assoc nClasses 0 [(idx, 1)]))\n\nunitCorrect :: [Int] -> Unit R\nunitCorrect classes = Unit { apply, deriv } where\n  apply _ (BatchActivation input) =\n    singleClassOutput n classes\n    where (_, n) = size input\n  apply _ _ = ApplyFail \"\"\n  deriv = undefined\n", "meta": {"hexsha": "be9deff964613abab97d5d5e22470897ec58105d", "size": 6317, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/School/TestUtils.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/School/TestUtils.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/School/TestUtils.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7136363636, "max_line_length": 155, "alphanum_fraction": 0.6588570524, "num_tokens": 1741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.44221166009268864}}
{"text": "{-# LANGUAGE DeriveGeneric, DeriveAnyClass, FlexibleContexts, FlexibleInstances, TypeSynonymInstances #-}\n\nmodule Neural.FF where\n\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Control.Parallel.Strategies\nimport Data.List.Split\nimport qualified Data.Ix as I\nimport qualified Data.Vector as V\nimport GHC.Generics\nimport Numeric.LinearAlgebra\nimport System.Random\n\nimport Neural.Util\nimport Numeric.Extra\n\ninstance Show (a -> b) where show a = \"function\"\n\ndata FFLayerOptions = FFLayerOptions {\n  -- # of slices\n  layerDepth :: Int,\n\n  -- z_j -> y_j\n  layerActivationFn :: [Matrix Double] -> [Matrix Double],\n\n  -- z_j -> yPrime_j\n  layerActivationFnDeriv :: [Matrix Double] -> [Matrix Double],\n\n  -- Pooling functions \n  pooling :: (Int,Int) -> [Matrix Double] -> [Matrix Double],\n  poolingBP :: (Int,Int) -> [Matrix Double] -> [Matrix Double] -> [Matrix Double],\n  poolSize :: (Int,Int)\n  }\n\ndata FFLayer = FFLayer {\n  weights :: [Matrix Double],\n  biases :: [Matrix Double],\n\n  -- x_j -> (w_j, b_j) -> z_j\n  zFn :: [Matrix Double] -> ([Matrix Double], [Matrix Double]) -> [Matrix Double],\n  yFn :: [Matrix Double] -> [Matrix Double],\n  \n  -- nabla_b_j -> x_j -> nabla_w_j\n  nablaW :: [Matrix Double] -> [Matrix Double] -> [Matrix Double],\n\n  -- delta_j -> x_j -> nabla_b_j\n  nablaB :: [Matrix Double] -> [Matrix Double] -> [Matrix Double],\n  \n  -- nabla_b_j -> z_i-> w_j -> delta_i\n  backprop :: [Matrix Double] -> [Matrix Double] -> [Matrix Double] -> [Matrix Double]\n    } deriving (Show, Generic, NFData)\n\ndata FFNetwork = FFNetwork {\n  layers :: V.Vector(FFLayer)\n  } deriving (Show, Generic, NFData)\n\n\n-- descs is a list of [(spawner, dims, options)]\nspawnFFNetwork :: [((Int, Int) -> (Int, Int) -> FFLayerOptions -> FFLayerOptions -> IO (FFLayer),\n                   (Int, Int), (Int, Int), FFLayerOptions)] -> IO (FFNetwork)\nspawnFFNetwork descs = liftM (FFNetwork . V.fromList)\n                       $ zipWithM (\\(ls_j, dims_i, dims_j, opts_j) opts_i ->\n                                    ls_j dims_i dims_j opts_i opts_j)\n                       (tail descs) (map (\\(_,_,_,opts_) -> opts_) descs)\n                       \n-- Parallel matrix multiplication; left operand is split into rows.\n(<||#>) :: (Matrix Double) -> (Matrix Double) -> (Matrix Double)\nx <||#> y = fromRows $ parMap rdeepseq (<# y) $ toRows x\n\n-- Same as above, but right operand is split into columns\n(<#||>) :: (Matrix Double) -> (Matrix Double) -> (Matrix Double)\nx <#||> y = fromColumns $ parMap rdeepseq (x #>) $ toColumns y\n\n-- Parallel dense matrix/vector product.\n-- (m><n) #||> (n) -> (m)\n(#||>) :: (Matrix Double) -> (Vector Double) -> (Vector Double)\nx #||> y = fromList $ parMap rdeepseq (<.> y) $ toRows x\n\n-- Idk what this product is called but is sure as hell is parallel\n-- splits second operand into a list\n-- I should really see if this is faster than <#||>\n-- (m) <.||> (n) -> (m,n)\n(<.||>) :: (Vector Double) -> (Vector Double) -> (Matrix Double)\nx <.||> y = fromColumns $ parMap rdeepseq (\\y_i -> scale y_i x) (toList y)\n\n-- feeds forward, collecting layer activations.\n-- note y, z are reversed.\n-- net -> x_1 -> ([y_n, .. y_1, x_1], [z_n, .. z_1])\nff :: FFNetwork -> [Matrix Double] -> (V.Vector([Matrix Double]), V.Vector([Matrix Double]))\nff net x = V.foldl activator (V.singleton x, V.empty) $ layers net\n  where activator (y, z) (FFLayer w b zf yf _ _ _) =\n          (\\(y_j, z_j) -> (y_j `V.cons` y, z_j `V.cons` z)) $ (\\a -> (yf a, a)) $ zf (V.head y) (w, b)\n\n-- ff that only returns final output of the net.\n-- net -> x_1 -> y_n\nffOut :: FFNetwork -> [Matrix Double] -> [Matrix Double]\nffOut net x = V.head $ fst $ ff net x\n\n-- feeds forward, then passes error backwards\nbp :: FFNetwork -> [Matrix Double] -> [Matrix Double] -> [([Matrix Double], [Matrix Double])]\nbp net expected x = V.foldl passBack [(nabla_w_n, nabla_b_n)] kit\n  where passBack ((nabla_w_k, nabla_b_k) : nablas) (x_j, z_j, layer_k, layer_j) =\n          (nabla_w_j, nabla_b_j) : (nabla_w_k, nabla_b_k) : nablas\n          where nabla_w_j = (nablaW layer_j) nabla_b_j x_j\n                nabla_b_j = (nablaB layer_j) delta_j z_j\n                delta_j = (backprop layer_k) nabla_b_k z_j (weights layer_k)\n\n        -- passBack sees these args:\n        -- y[n-1 .. 1], z[n-1 .. 1], layers[n .. 2], layers[n-1 .. 1]\n        kit = V.zip4 (V.tail $ V.tail y) (V.tail z) (V.reverse $ V.tail $ ls) (V.reverse $ V.init ls)\n        nabla_w_n = (nablaW $ V.last $ ls) nabla_b_n (y V.! 1)\n        nabla_b_n = zipWith (-) (y V.! 0) expected\n        ls = layers net\n        (y, z) = ff net x\n\n\n                     \n-- Error/cost functions.\n\n{-\ncrossEntropyDelta :: [Matrix Double] -> [Matrix Double] -> [Matrix Double]\ncrossEntropyDelta = zipWith (-)\n\ncrossEntropyError :: [Matrix Double] -> [Matrix Double] -> [Double]\ncrossEntropyError x y = map (\\(x,y) -> sumElements $ - ((y * (cmap log x)) + (1.0 - y) * (cmap log $ 1.0 - x)))\n                        $ zip x y\n-}\n\n-- Convert an output value to an actual output of the net\n-- i.e. '5' -> [0,0,0,0,0,1,0,...]\nbuildOutput :: Int -> Int -> [Matrix Double]\nbuildOutput i len = [(len><1) (map (\\x -> if x == i then 1.0 else 0.0) [0..len - 1])]\n\n-- Convert a net's output to an integer output value\n-- uses max value of the net.\n-- i.e. [0,0.5,0.25,-0.1,0.999999,...] -> '4'\nconvertOutput :: [Matrix Double] -> Int\nconvertOutput output = (\\(i,j) -> i) $ maxIndex $ head output\n        \n-- For a given test set, return the number the net gets correct \nevaluate :: FFNetwork -> [((Matrix Double), Int)] -> Double -> Int\nevaluate net testSet reg =\n  sum $ parMap rdeepseq\n  (\\(input, expected) ->\n    let output = ffOut net [input]\n    in if convertOutput output == expected then 1 else 0) testSet\n\n-- perform stochastic gradient descent on the net.\n-- each sample data is a tuple of (input, expected output) where the output is an integer representing the desired result.\n-- maxClassIndex is the max classification ID any output can produce\n-- eta is the learning rate.\n-- reg is the regularization parameter (for L2 reg)\nsgd :: FFNetwork -> StdGen -> [((Matrix Double), Int)] -> Int -> Int -> Double -> Double -> ((FFNetwork, [((Matrix Double), Int)]), StdGen)\nsgd net gen trainingSet maxClassIndex batchSize eta reg = ((newNet, newTrainingSet), newGen)\n  where newNet = foldl applyBatch net $ chunksOf batchSize newTrainingSet\n        applyBatch net batch =\n          net { layers = \n                  V.zipWith (\\layer (nabla_w, nabla_b) ->\n                             layer {\n                                -- apply the changes to each layer of the net.\n                                weights = zipWith adjustWeights (weights layer) nabla_w,\n                                biases = zipWith adjustBiases (biases layer) nabla_b\n                                }) (layers net)\n                  -- backpropagate each member of the batch, summing the resulting change in the net.\n                  -- this will yield [(nw, nb) ...] for each layer of the net.\n                  $ V.fromList\n                  $ (\\(batch1 : batches) ->\n                      foldl (zipWith (\\(nw,nb) (dnw,dnb) -> (zipWith (+) nw dnw, zipWith (+) nb dnb)))\n                      batch1 batches)\n                  $ parMap rdeepseq\n                  (\\(input, expected) ->\n                    bp net (buildOutput expected $ maxClassIndex + 1) [input]) batch\n              }\n\n        -- hmatrix gets a little confused when (Num a, Matrix b) => a * b happens\n        -- so use `scale` for now.             \n        adjustWeights w nabla_w = (scale (1.0 - eta * reg / (fromIntegral $ length trainingSet)) w)\n                                  - (scale (eta / (fromIntegral batchSize)) nabla_w)\n        adjustBiases b nabla_b = b - (scale (eta / (fromIntegral batchSize)) nabla_b)\n\n        -- cost = 0.5 * reg * l2_norm_sq * (fromIntegral batchSize) / (fromIntegral $ length trainingSet)\n        -- l2_norm_sq = V.sum $ V.map (\\l -> sum $ parMap rdeepseq (\\w -> sumElements $ w * w) $ weights l) $ layers net\n          \n        (newTrainingSet, newGen) = shuffle' trainingSet gen\n", "meta": {"hexsha": "555ee6ee8bb2bf21d5595fcfa25549699057b6cd", "size": 8085, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neural/FF.hs", "max_stars_repo_name": "dlhawkins94/jinko-no", "max_stars_repo_head_hexsha": "45fc9fcabc1d3699d9022bbffb5264aaee64baf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Neural/FF.hs", "max_issues_repo_name": "dlhawkins94/jinko-no", "max_issues_repo_head_hexsha": "45fc9fcabc1d3699d9022bbffb5264aaee64baf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Neural/FF.hs", "max_forks_repo_name": "dlhawkins94/jinko-no", "max_forks_repo_head_hexsha": "45fc9fcabc1d3699d9022bbffb5264aaee64baf4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4677419355, "max_line_length": 139, "alphanum_fraction": 0.5955473098, "num_tokens": 2313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.4415781566963474}}
{"text": "-----------------------------------------------------------------------------\n-- |\n-- Module      :  Numeric.GSL.Vector\n-- Copyright   :  (c) Alberto Ruiz 2007\n-- License     :  GPL-style\n--\n-- Maintainer  :  Alberto Ruiz <aruiz@um.es>\n-- Stability   :  provisional\n-- Portability :  portable (uses FFI)\n--\n-- Low level interface to vector operations.\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.GSL.Vector (\n    sumF, sumR, sumQ, sumC,\n    prodF, prodR, prodQ, prodC,\n    dotF, dotR, dotQ, dotC,\n    FunCodeS(..), toScalarR, toScalarF, toScalarC, toScalarQ,\n    FunCodeV(..), vectorMapR, vectorMapC, vectorMapF, vectorMapQ,\n    FunCodeSV(..), vectorMapValR, vectorMapValC, vectorMapValF, vectorMapValQ,\n    FunCodeVV(..), vectorZipR, vectorZipC, vectorZipF, vectorZipQ,\n    RandDist(..), randomVector\n) where\n\nimport Data.Packed.Internal.Common\nimport Data.Packed.Internal.Signatures\nimport Data.Packed.Internal.Vector\n\nimport Data.Complex\nimport Foreign.Marshal.Alloc(free)\nimport Foreign.Marshal.Array(newArray)\nimport Foreign.Ptr(Ptr)\nimport Foreign.C.Types\nimport System.IO.Unsafe(unsafePerformIO)\n\nfromei x = fromIntegral (fromEnum x) :: CInt\n\ndata FunCodeV = Sin\n              | Cos\n              | Tan\n              | Abs\n              | ASin\n              | ACos\n              | ATan\n              | Sinh\n              | Cosh\n              | Tanh\n              | ASinh\n              | ACosh\n              | ATanh\n              | Exp\n              | Log\n              | Sign\n              | Sqrt\n              deriving Enum\n\ndata FunCodeSV = Scale\n               | Recip\n               | AddConstant\n               | Negate\n               | PowSV\n               | PowVS\n               deriving Enum\n\ndata FunCodeVV = Add\n               | Sub\n               | Mul\n               | Div\n               | Pow\n               | ATan2\n               deriving Enum\n\ndata FunCodeS = Norm2\n              | AbsSum\n              | MaxIdx\n              | Max\n              | MinIdx\n              | Min\n              deriving Enum\n\n------------------------------------------------------------------\n\n-- | sum of elements\nsumF :: Vector Float -> Float\nsumF x = unsafePerformIO $ do\n           r <- createVector 1\n           app2 c_sumF vec x vec r \"sumF\"\n           return $ r @> 0\n\n-- | sum of elements\nsumR :: Vector Double -> Double\nsumR x = unsafePerformIO $ do\n           r <- createVector 1\n           app2 c_sumR vec x vec r \"sumR\"\n           return $ r @> 0\n\n-- | sum of elements\nsumQ :: Vector (Complex Float) -> Complex Float\nsumQ x = unsafePerformIO $ do\n           r <- createVector 1\n           app2 c_sumQ vec x vec r \"sumQ\"\n           return $ r @> 0\n\n-- | sum of elements\nsumC :: Vector (Complex Double) -> Complex Double\nsumC x = unsafePerformIO $ do\n           r <- createVector 1\n           app2 c_sumC vec x vec r \"sumC\"\n           return $ r @> 0\n\nforeign import ccall unsafe \"gsl-aux.h sumF\" c_sumF :: TFF\nforeign import ccall unsafe \"gsl-aux.h sumR\" c_sumR :: TVV\nforeign import ccall unsafe \"gsl-aux.h sumQ\" c_sumQ :: TQVQV\nforeign import ccall unsafe \"gsl-aux.h sumC\" c_sumC :: TCVCV\n\n-- | product of elements\nprodF :: Vector Float -> Float\nprodF x = unsafePerformIO $ do\n           r <- createVector 1\n           app2 c_prodF vec x vec r \"prodF\"\n           return $ r @> 0\n\n-- | product of elements\nprodR :: Vector Double -> Double\nprodR x = unsafePerformIO $ do\n           r <- createVector 1\n           app2 c_prodR vec x vec r \"prodR\"\n           return $ r @> 0\n\n-- | product of elements\nprodQ :: Vector (Complex Float) -> Complex Float\nprodQ x = unsafePerformIO $ do\n           r <- createVector 1\n           app2 c_prodQ vec x vec r \"prodQ\"\n           return $ r @> 0\n\n-- | product of elements\nprodC :: Vector (Complex Double) -> Complex Double\nprodC x = unsafePerformIO $ do\n           r <- createVector 1\n           app2 c_prodC vec x vec r \"prodC\"\n           return $ r @> 0\n\nforeign import ccall unsafe \"gsl-aux.h prodF\" c_prodF :: TFF\nforeign import ccall unsafe \"gsl-aux.h prodR\" c_prodR :: TVV\nforeign import ccall unsafe \"gsl-aux.h prodQ\" c_prodQ :: TQVQV\nforeign import ccall unsafe \"gsl-aux.h prodC\" c_prodC :: TCVCV\n\n-- | dot product\ndotF :: Vector Float -> Vector Float -> Float\ndotF x y = unsafePerformIO $ do\n           r <- createVector 1\n           app3 c_dotF vec x vec y vec r \"dotF\"\n           return $ r @> 0\n\n-- | dot product\ndotR :: Vector Double -> Vector Double -> Double\ndotR x y = unsafePerformIO $ do\n           r <- createVector 1\n           app3 c_dotR vec x vec y vec r \"dotR\"\n           return $ r @> 0\n\n-- | dot product\ndotQ :: Vector (Complex Float) -> Vector (Complex Float) -> Complex Float\ndotQ x y = unsafePerformIO $ do\n           r <- createVector 1\n           app3 c_dotQ vec x vec y vec r \"dotQ\"\n           return $ r @> 0\n\n-- | dot product\ndotC :: Vector (Complex Double) -> Vector (Complex Double) -> Complex Double\ndotC x y = unsafePerformIO $ do\n           r <- createVector 1\n           app3 c_dotC vec x vec y vec r \"dotC\"\n           return $ r @> 0\n\nforeign import ccall unsafe \"gsl-aux.h dotF\" c_dotF :: TFFF\nforeign import ccall unsafe \"gsl-aux.h dotR\" c_dotR :: TVVV\nforeign import ccall unsafe \"gsl-aux.h dotQ\" c_dotQ :: TQVQVQV\nforeign import ccall unsafe \"gsl-aux.h dotC\" c_dotC :: TCVCVCV\n\n------------------------------------------------------------------\n\ntoScalarAux fun code v = unsafePerformIO $ do\n    r <- createVector 1\n    app2 (fun (fromei code)) vec v vec r \"toScalarAux\"\n    return (r `at` 0)\n\nvectorMapAux fun code v = unsafePerformIO $ do\n    r <- createVector (dim v)\n    app2 (fun (fromei code)) vec v vec r \"vectorMapAux\"\n    return r\n\nvectorMapValAux fun code val v = unsafePerformIO $ do\n    r <- createVector (dim v)\n    pval <- newArray [val]\n    app2 (fun (fromei code) pval) vec v vec r \"vectorMapValAux\"\n    free pval\n    return r\n\nvectorZipAux fun code u v = unsafePerformIO $ do\n    r <- createVector (dim u)\n    app3 (fun (fromei code)) vec u vec v vec r \"vectorZipAux\"\n    return r\n\n---------------------------------------------------------------------\n\n-- | obtains different functions of a vector: norm1, norm2, max, min, posmax, posmin, etc.\ntoScalarR :: FunCodeS -> Vector Double -> Double\ntoScalarR oper =  toScalarAux c_toScalarR (fromei oper)\n\nforeign import ccall unsafe \"gsl-aux.h toScalarR\" c_toScalarR :: CInt -> TVV\n\n-- | obtains different functions of a vector: norm1, norm2, max, min, posmax, posmin, etc.\ntoScalarF :: FunCodeS -> Vector Float -> Float\ntoScalarF oper =  toScalarAux c_toScalarF (fromei oper)\n\nforeign import ccall unsafe \"gsl-aux.h toScalarF\" c_toScalarF :: CInt -> TFF\n\n-- | obtains different functions of a vector: only norm1, norm2\ntoScalarC :: FunCodeS -> Vector (Complex Double) -> Double\ntoScalarC oper =  toScalarAux c_toScalarC (fromei oper)\n\nforeign import ccall unsafe \"gsl-aux.h toScalarC\" c_toScalarC :: CInt -> TCVV\n\n-- | obtains different functions of a vector: only norm1, norm2\ntoScalarQ :: FunCodeS -> Vector (Complex Float) -> Float\ntoScalarQ oper =  toScalarAux c_toScalarQ (fromei oper)\n\nforeign import ccall unsafe \"gsl-aux.h toScalarQ\" c_toScalarQ :: CInt -> TQVF\n\n------------------------------------------------------------------\n\n-- | map of real vectors with given function\nvectorMapR :: FunCodeV -> Vector Double -> Vector Double\nvectorMapR = vectorMapAux c_vectorMapR\n\nforeign import ccall unsafe \"gsl-aux.h mapR\" c_vectorMapR :: CInt -> TVV\n\n-- | map of complex vectors with given function\nvectorMapC :: FunCodeV -> Vector (Complex Double) -> Vector (Complex Double)\nvectorMapC oper = vectorMapAux c_vectorMapC (fromei oper)\n\nforeign import ccall unsafe \"gsl-aux.h mapC\" c_vectorMapC :: CInt -> TCVCV\n\n-- | map of real vectors with given function\nvectorMapF :: FunCodeV -> Vector Float -> Vector Float\nvectorMapF = vectorMapAux c_vectorMapF\n\nforeign import ccall unsafe \"gsl-aux.h mapF\" c_vectorMapF :: CInt -> TFF\n\n-- | map of real vectors with given function\nvectorMapQ :: FunCodeV -> Vector (Complex Float) -> Vector (Complex Float)\nvectorMapQ = vectorMapAux c_vectorMapQ\n\nforeign import ccall unsafe \"gsl-aux.h mapQ\" c_vectorMapQ :: CInt -> TQVQV\n\n-------------------------------------------------------------------\n\n-- | map of real vectors with given function\nvectorMapValR :: FunCodeSV -> Double -> Vector Double -> Vector Double\nvectorMapValR oper = vectorMapValAux c_vectorMapValR (fromei oper)\n\nforeign import ccall unsafe \"gsl-aux.h mapValR\" c_vectorMapValR :: CInt -> Ptr Double -> TVV\n\n-- | map of complex vectors with given function\nvectorMapValC :: FunCodeSV -> Complex Double -> Vector (Complex Double) -> Vector (Complex Double)\nvectorMapValC = vectorMapValAux c_vectorMapValC\n\nforeign import ccall unsafe \"gsl-aux.h mapValC\" c_vectorMapValC :: CInt -> Ptr (Complex Double) -> TCVCV\n\n-- | map of real vectors with given function\nvectorMapValF :: FunCodeSV -> Float -> Vector Float -> Vector Float\nvectorMapValF oper = vectorMapValAux c_vectorMapValF (fromei oper)\n\nforeign import ccall unsafe \"gsl-aux.h mapValF\" c_vectorMapValF :: CInt -> Ptr Float -> TFF\n\n-- | map of complex vectors with given function\nvectorMapValQ :: FunCodeSV -> Complex Float -> Vector (Complex Float) -> Vector (Complex Float)\nvectorMapValQ oper = vectorMapValAux c_vectorMapValQ (fromei oper)\n\nforeign import ccall unsafe \"gsl-aux.h mapValQ\" c_vectorMapValQ :: CInt -> Ptr (Complex Float) -> TQVQV\n\n-------------------------------------------------------------------\n\n-- | elementwise operation on real vectors\nvectorZipR :: FunCodeVV -> Vector Double -> Vector Double -> Vector Double\nvectorZipR = vectorZipAux c_vectorZipR\n\nforeign import ccall unsafe \"gsl-aux.h zipR\" c_vectorZipR :: CInt -> TVVV\n\n-- | elementwise operation on complex vectors\nvectorZipC :: FunCodeVV -> Vector (Complex Double) -> Vector (Complex Double) -> Vector (Complex Double)\nvectorZipC = vectorZipAux c_vectorZipC\n\nforeign import ccall unsafe \"gsl-aux.h zipC\" c_vectorZipC :: CInt -> TCVCVCV\n\n-- | elementwise operation on real vectors\nvectorZipF :: FunCodeVV -> Vector Float -> Vector Float -> Vector Float\nvectorZipF = vectorZipAux c_vectorZipF\n\nforeign import ccall unsafe \"gsl-aux.h zipF\" c_vectorZipF :: CInt -> TFFF\n\n-- | elementwise operation on complex vectors\nvectorZipQ :: FunCodeVV -> Vector (Complex Float) -> Vector (Complex Float) -> Vector (Complex Float)\nvectorZipQ = vectorZipAux c_vectorZipQ\n\nforeign import ccall unsafe \"gsl-aux.h zipQ\" c_vectorZipQ :: CInt -> TQVQVQV\n\n-----------------------------------------------------------------------\n\ndata RandDist = Uniform  -- ^ uniform distribution in [0,1)\n              | Gaussian -- ^ normal distribution with mean zero and standard deviation one\n              deriving Enum\n\n-- | Obtains a vector of pseudorandom elements from the the mt19937 generator in GSL, with a given seed. Use randomIO to get a random seed.\nrandomVector :: Int      -- ^ seed\n             -> RandDist -- ^ distribution\n             -> Int      -- ^ vector size\n             -> Vector Double\nrandomVector seed dist n = unsafePerformIO $ do\n    r <- createVector n\n    app1 (c_random_vector (fi seed) ((fi.fromEnum) dist)) vec r \"randomVector\"\n    return r\n\nforeign import ccall unsafe \"random_vector\" c_random_vector :: CInt -> CInt -> TV\n", "meta": {"hexsha": "db340415c2e56dd275d1b1b1b9eddc9f294556af", "size": 11270, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Vector.hs", "max_stars_repo_name": "curiousleo/liquidhaskell", "max_stars_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 941, "max_stars_repo_stars_event_min_datetime": "2015-01-13T10:51:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:32:32.000Z", "max_issues_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Vector.hs", "max_issues_repo_name": "curiousleo/liquidhaskell", "max_issues_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 1300, "max_issues_repo_issues_event_min_datetime": "2015-01-01T05:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:11:03.000Z", "max_forks_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Vector.hs", "max_forks_repo_name": "curiousleo/liquidhaskell", "max_forks_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 145, "max_forks_repo_forks_event_min_datetime": "2015-01-12T08:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:29:30.000Z", "avg_line_length": 34.3597560976, "max_line_length": 139, "alphanum_fraction": 0.6179236912, "num_tokens": 3049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.44149043886518835}}
{"text": "module HLearn.Optimization.Conic\n    where\n\nimport Control.DeepSeq\nimport Control.Monad\nimport Control.Monad.Random\nimport Control.Monad.ST\nimport Data.List\nimport Data.List.Extras\nimport Debug.Trace\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as VM\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector.Generic.Mutable as VGM\nimport qualified Data.Vector.Algorithms.Intro as Intro\nimport Numeric.LinearAlgebra hiding ((<>))\nimport qualified Numeric.LinearAlgebra as LA\nimport Data.Random.Normal\n\nimport HLearn.Algebra\nimport qualified HLearn.Optimization.Common as Recipe\nimport qualified HLearn.Optimization.LineMinimization as LineMin\n\n-------------------------------------------------------------------------------\n\nconicprojection :: Matrix Double -> Matrix Double\nconicprojection m = cmap realPart $ u LA.<> lambda' LA.<> trans u \n    where\n        lambda' = cmap (\\x -> if realPart x < 0 then 0 else x) lambda\n        lambda = diagRect 0 l (VG.length l) (VG.length l)\n        (l,u) = eig m\n\n-------------------------------------------------------------------------------\n\ndata RandomConicPersuit a = RandomConicPersuit\n    { _stdgen :: !StdGen\n    , _soln :: !a\n    , _fx :: !(Scalar a)\n    , _solnlast :: !a\n    }\n\n-- data OptInfo a = OptInfo\n--     { _stdgen :: !StdGen\n--     , _x :: !a\n--     , _fx :: \n--     , _xold :: !a\n--     }\n\nitr :: Int -> (tmp -> a) -> (tmp -> Bool) -> (tmp -> tmp) -> tmp -> a\nitr i result stop step init = --trace (\"i=\"++show i++\"; fx=\"++show (_fx init)) $ --trace (\"i=\"++show i++\"; init=\"++show init) $ \n  if i==0 || stop init\n    then result init\n    else itr (i-1) result stop step (step init)\n\nrandomConicPersuit f x0 = _soln $ itr 10 id (\\x -> False) (step_RandomConicPersuit f) init\n    where\n        init = RandomConicPersuit\n            { _stdgen = mkStdGen $ round $ sumElements x0\n            , _soln = x0\n            , _fx = f x0\n            , _solnlast = x0\n            }\n\nconicProjection f x0 = _soln $ argmin _fx [itr 1 id (\\x -> False) (step_RandomConicPersuit f) (init i) | i <- [0..10]]\n    where\n        init i = RandomConicPersuit\n            { _stdgen = mkStdGen $ i+(round $ sumElements x0)\n            , _soln = x0\n            , _fx = f x0\n            , _solnlast = x0\n            }\n\nstop_RandomConicPersuit (RandomConicPersuit stdgen soln fx solnlast) = undefined\n\nstep_RandomConicPersuit f (RandomConicPersuit stdgen soln fx solnlast) = --trace (\"lambda = \"++show lambda++ \"; phi=\"++show phi) $ \n    ret\n    where\n--         (x', stdgen') = runRand ((LA.fromList . take (rows soln)) `liftM` getRandomRs (-1,1)) stdgen\n        normL 0 (xs,g) = (xs,g)\n        normL i (xs,g) = normL (i-1) (x:xs,g')\n            where\n                (x,g') = normal g\n\n        (x'std, stdgen') = normL (rows soln) ([],stdgen)\n        x' = VS.fromList x'std\n--         (lambda,phi::Matrix Double) = eigSH soln\n--         q = (diag $ cmap (sqrt.abs) lambda) LA.<> phi\n--         x' = (scale (1-kappa) q - scale kappa (ident (rows q))) LA.<> LA.fromList x'std\n--         kappa = 1e-4\n\n        y' = asColumn x' LA.<> asRow x'\n--         y' = asColumn (LA.fromList x') LA.<> asRow (LA.fromList x')\n\n        g_alpha alpha = f $ scale alpha y' + soln\n        alpha_hat = error \"step_randomConic\" -- LineMin._x $ runOptimization $ LineMin.brent g_alpha (LineMin.lineBracket g_alpha 0 1)\n\n        alpha_hat_y' = scale alpha_hat y'\n        g_beta beta = f $ alpha_hat_y' + scale beta soln\n        beta_hat = error \"step_randomConic\" -- LineMin._x $ LineMin.brent g_beta (LineMin.lineBracket g_beta 0 1)\n\n        soln' = alpha_hat_y' + scale beta_hat soln\n\n        ret = RandomConicPersuit\n            { _stdgen = stdgen'\n            , _soln = soln'\n            , _fx = f soln'\n            , _solnlast = soln\n            }\n\n", "meta": {"hexsha": "25fd94b784770b19c1e7f368a6db801745faee1b", "size": 3899, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HLearn/Optimization/Conic.hs", "max_stars_repo_name": "Heather/HLearn", "max_stars_repo_head_hexsha": "56e0dfedbabea6d4bdeb91bb47b46a578559a092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1427, "max_stars_repo_stars_event_min_datetime": "2015-01-06T05:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T11:18:27.000Z", "max_issues_repo_path": "src/HLearn/Optimization/Conic.hs", "max_issues_repo_name": "Heather/HLearn", "max_issues_repo_head_hexsha": "56e0dfedbabea6d4bdeb91bb47b46a578559a092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2015-02-06T22:36:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-21T20:11:59.000Z", "max_forks_repo_path": "src/HLearn/Optimization/Conic.hs", "max_forks_repo_name": "Heather/HLearn", "max_forks_repo_head_hexsha": "56e0dfedbabea6d4bdeb91bb47b46a578559a092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 147, "max_forks_repo_forks_event_min_datetime": "2015-01-06T09:07:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T18:54:08.000Z", "avg_line_length": 34.8125, "max_line_length": 134, "alphanum_fraction": 0.5829699923, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.812867299704166, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.44127581110097236}}
{"text": "{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Turtle where\n\nimport Control.Monad.State\n-- import Control.Monad.Trans.Class\nimport Numeric.LinearAlgebra.HMatrix hiding (scale, (!))\nimport qualified Graphics.Rendering.OpenGL as GL\nimport Foreign.Storable\nimport GLCode\nimport Sketch\n-- import Points\nimport Lines\nimport Triangles\nimport Data.Array\nimport Debug.Trace\n\nclamp :: Float -> Float -> Float -> Float\nclamp a b x | x < a = a\n            | x > b = b\n            | otherwise = x\n\nlerp :: Float -> Float -> Float -> Float\nlerp a b x = (1-x)*a+x*b\n\nlinstep :: Float -> Float -> Float -> Float\nlinstep a b x = clamp 0.0 1.0 ((x-a)/(b-a))\n\nsmoothstep :: Float -> Float -> Float -> Float\nsmoothstep a b x =\n    let t = clamp 0.0 1.0 ((x-a)/(b-a))\n    in t*t*(3.0-2.0*t)\n\nv2f :: Real a => a -> a -> GL.Vertex2 Float\nv2f x y = GL.Vertex2 (realToFrac x) (realToFrac y)\n\nv3f :: Real a => a -> a -> a -> GL.Vertex3 Float\nv3f x y z = GL.Vertex3 (realToFrac x) (realToFrac y) (realToFrac z)\n\nv4f :: Real a => a -> a -> a -> a -> GL.Vertex4 Float\nv4f x y z w = GL.Vertex4 (realToFrac x) (realToFrac y) (realToFrac z) (realToFrac w)\n\ntranslation :: (Fractional a, Storable a) => a -> a -> a -> Matrix a\ntranslation x y z = (4 >< 4) [ 1.0, 0.0, 0.0, 0.0,\n                               0.0, 1.0, 0.0, 0.0,\n                               0.0, 0.0, 1.0, 0.0,\n                               x  , y  , z  , 1.0 ]\n\nscaling :: (Fractional a, Storable a) => a -> a -> a -> Matrix a\nscaling x y z = (4 >< 4) [ x  , 0.0, 0.0, 0.0,\n                           0.0, y  , 0.0, 0.0,\n                           0.0, 0.0, z  , 0.0,\n                           0.0, 0.0, 0.0, 1.0 ]\n\nrotation :: (Fractional a, Storable a, Floating a) => a -> Matrix a\nrotation theta = let c = cos theta\n                     s = sin theta\n                 in (4 >< 4) [ c, s, 0.0, 0.0,\n                               -s, c, 0.0, 0.0,\n                               0.0, 0.0, 1.0, 0.0,\n                               0.0, 0.0, 0.0, 1.0]\n\nrectangle :: (Float, Float, Float) -> Float -> Float -> SketchMonad ()\nrectangle (r, g, b) w h = do\n    drawTriangle \"turtle\"\n        \"vPosition\" (rectangleVertices w h)\n        \"color\" [v4f r g b 1.0, v4f r g b 1.0, v4f r g b 1.0,\n                 v4f r g b 1.0, v4f r g b 1.0, v4f r g b 1.0]\n\n\ndrawPath :: (Float, Float, Float) -> [(Float, Float)] -> SketchMonad ()\ndrawPath (r, g, b) vs = do    \n    drawLine \"turtle\"\n        \"vPosition\" (map (uncurry v2f) vs)\n        \"color\" (replicate (length vs) (v4f r g b 1.0))\n\nplotPath :: (Float, Float, Float) -> Int -> (Float -> (Float, Float)) -> Float -> Float -> SketchMonad ()\nplotPath rgb n f t0 t1 = do\n    let scale = (t1-t0)/fromIntegral n\n    drawPath rgb [f t | i <- [0..n],\n                        let t = t0+scale*fromIntegral i]\n\nconstRectangle :: (Float, Float, Float) -> Float -> Float -> SketchMonad ()\nconstRectangle (r, g, b) w h = do\n    drawTriangle \"turtle\"\n        \"vPosition\" (rectangleVertices w h)\n        \"color\" [v4f r g b 1.0, v4f r g b 1.0, v4f r g b 1.0,\n                 v4f r g b 1.0, v4f r g b 1.0, v4f r g b 1.0]\n\nrectangleVertices :: Float -> Float -> [GL.Vertex2 Float]\nrectangleVertices w h =\n        [v2f (-0.5*w) (-0.5*h), v2f (0.5*w) (-0.5*h), v2f (0.5*w) (0.5*h),\n         v2f (-0.5*w) (-0.5*h), v2f (0.5*w) (0.5*h), v2f (-0.5*w) (0.5*h)]\n\nrotate :: (Floating t, Numeric t, MonadState (Matrix t) m) => t -> m ()\nrotate angle = modify (rotation angle `mul`)\n\nscale :: (Fractional t, Numeric t, MonadState (Matrix t) m) => t -> t -> t -> m ()\nscale s t u = modify (scaling s t u `mul`)\n\ntranslate :: (Fractional t, Numeric t, MonadState (Matrix t) m) => t -> t -> t -> m ()\ntranslate u v w = modify (translation u v w `mul`)\n\nsave :: StateT (Matrix Float) (StateT World IO) () -> StateT (Matrix Float) (StateT World IO) ()\nsave c = do\n    m <- get\n    a <- c\n    put m\n    setTransform\n    return a\n\nsetTransform :: StateT (Matrix Float) (StateT World IO) ()\nsetTransform = do\n    transform <- get\n    lift $ setUniform \"turtle\"\n               \"transform\" transform\n\nsetTransformPoint :: StateT (Matrix Float) (StateT World IO) ()\nsetTransformPoint = do\n    transform <- get\n    lift $ setUniform \"turtle_point\"\n               \"transform\" transform\n\narrow :: (Float, Float, Float) -> Float -> Float -> Float -> Float -> SketchMonad ()\narrow (r, g, b) thickness headLength headWidth length = do\n--     let thickness = 0.01\n    constRectangle (r, g, b) length thickness\n    drawTriangle \"turtle\"\n        \"vPosition\" [v2f (0.5*length) (-0.5*headWidth), v2f (0.5*length+headLength) 0, v2f (0.5*length) (0.5*headWidth)]\n        \"color\" [v4f r g b 1.0, v4f r g b 1.0,\n                 v4f r g b 1.0]\n\ngrid :: Int -> Int -> Float -> Float ->\n        (Int -> Int -> StateT (Matrix Float) (StateT World IO) ()) ->\n        StateT (Matrix Float) (StateT World IO) ()\ngrid m n dx dy f =\n    forM_ [0..(m-1)] $ \\i ->\n        forM_ [0..(n-1)] $ \\j -> save $ do\n            let x = dx*fromIntegral i\n            let y = dy*fromIntegral j\n            translate x y 0\n            setTransform\n            f i j\n\ndrawVectorField drawArrow m n dx dy vx vy = drawVectorField' drawArrow m n dx dy $ interpVelocityField vx vy\n\ndrawVectorField' drawArrow m n dx dy f =\n    grid m n dx dy $ \\i j -> do\n        let (vx, vy) = f (fromIntegral i) (fromIntegral j)\n        let theta = atan2 vy vx\n        let r = sqrt (vx*vx+vy*vy)\n        save $ do\n            modify ((rotation theta) `mul`)\n            transform <- get\n            lift $ setUniform \"turtle\"\n                              \"transform\" transform\n            lift $ drawArrow r\n\ntype ColorMap = Float -> GL.Vertex4 Float\n\ndrawDensityField :: ColorMap -> Int -> Int -> Float -> Float -> Array (Int, Int) Float -> StateT (Matrix Float) (StateT World IO) ()\ndrawDensityField cmap m n dx dy a =\n    grid m n dx dy $ \\i j -> do\n        let ip = (i+1) `mod` m\n        let jp = (j+1) `mod` m\n        lift $ drawTriangle \"turtle\"\n                            \"vPosition\" [v2f 0.0 0.0, v2f dx 0.0, v2f dx dy,\n                                         v2f 0.0 0.0, v2f dx dy, v2f 0.0 dy]\n                            \"color\"     [cmap (a!(i, j)), cmap (a!(ip, j)), cmap (a!(ip, jp)),\n                                         cmap (a!(i, j)), cmap (a!(ip, jp)), cmap (a!(i, jp))]\n\ncoolwarm :: Float -> Float -> Float -> GL.Vertex4 Float\ncoolwarm a b x = \n    let mid = 0.5*(a+b)\n    in if x > mid\n        then let t = smoothstep mid b x in v4f 1.0 (1.0-t) (1.0-t) 1.0\n        else let t = smoothstep mid a x in v4f (1.0-t) (1.0-t) 1.0 1.0\n\n-- Interpolate velocity onto uniform grid from staggered grid\n-- Let's say velocity field defined by\n-- vx!(x, y) = v (x-0.5) y\n-- vy!(x, y) = v x (y-0.5)\n--\n-- So, for example, (v x y)_x = vx!(x,y)+vx!(x+1,y)\ninterpVelocity :: Array (Int, Int) Float -> Array (Int, Int) Float -> Array (Int, Int) (Float, Float)\ninterpVelocity vx vy =\n    let (_, (nx, ny)) = bounds vx\n    in array ((0, 0), (nx, ny)) [((i, j), (0.5*(vx!(ip, j)+vx!(i, j)), 0.5*(vy!(i, jp)+vy!(i, j)))) |\n                                 i <- [0..nx],\n                                 j <- [0..ny],\n                                 let ip = (i+1) `mod` (nx+1),\n                                 let jp = (j+1) `mod` (ny+1)]\n\ninterpVelocityField :: Array (Int, Int) Float -> Array (Int, Int) Float -> Float -> Float -> (Float, Float)\ninterpVelocityField vx vy x y =\n    (interpScalarField vx (x+0.5) y, interpScalarField vy x (y+0.5))\n--     let (_, (nx, ny)) = bounds vx\n--         x = x0+0.5\n--         y = y0+0.5\n--         ix = floor x `mod` nx\n--         iy = floor y `mod` ny\n--         ixp = (ix+1) `mod` nx\n--         iyp = (iy+1) `mod` ny\n--         fx = x-fromIntegral ix\n--         fy = y-fromIntegral iy\n--         vx00 = lerp (vx!(ix, iy)) (vy!(ixp, iy))\n--     in (lerp (vx!(ix, iy)) (vx!(ixp, iy)) fx,\n--         lerp (vy!(ix, iy)) (vy!(ix, iyp)) fy)\n\ninterpScalarField :: Array (Int, Int) Float -> Float -> Float -> Float\ninterpScalarField p x y =\n    let (_, (nx, ny)) = bounds p\n        ix = floor x `mod` nx\n        iy = floor y `mod` ny\n        ixp = (ix+1) `mod` nx\n        iyp = (iy+1) `mod` ny\n        fx = x-fromIntegral ix\n        fy = y-fromIntegral iy\n        p00 = p!(ix, iy)\n        p01 = p!(ix, iyp)\n        p10 = p!(ixp, iy)\n        p11 = p!(ixp, iyp)\n        p0 = lerp p00 p01 fy\n        p1 = lerp p10 p11 fy\n    in lerp p0 p1 fx\n\ndivergence :: Array (Int, Int) Float -> Array (Int, Int) Float -> Array (Int, Int) (Float, Float)\ndivergence vx vy =\n    let (_, (nx, ny)) = bounds vx\n    in array ((0, 0), (nx, ny)) [((i, j), (vx!(ip, j)-vx!(i, j), vy!(i, jp)-vy!(i, j))) |\n                                 i <- [0..nx],\n                                 j <- [0..ny],\n                                 let ip = (i+1) `mod` (nx+1),\n                                 let jp = (j+1) `mod` (ny+1)]\n\ngrad :: Array (Int, Int) Float -> (Array (Int, Int) Float, Array (Int, Int) Float)\ngrad p =\n    let (_, (nx, ny)) = bounds p\n        vx = array ((0, 0), (nx, ny)) [((i, j), p!(ip, j)-p!(i, j)) |\n                                      i <- [0..nx],\n                                      j <- [0..ny],\n                                      let ip = (i+1) `mod` (nx+1)]\n        vy = array ((0, 0), (nx, ny)) [((ix, iy), p!(ix, iyp)-p!(ix, iy)) |\n                                      ix <- [0..nx],\n                                      iy <- [0..ny],\n                                      let iyp = (iy+1) `mod` (ny+1)]\n    in (vx, vy)\n\nintegrate :: (Float -> Float -> (Float, Float)) -> Float -> Float -> Int -> Float -> [(Float, Float)]\nintegrate v x y 0 dt = []\nintegrate v x y n dt = (x, y) : \n    let (vx, vy) = v x y\n    in integrate v (x+dt*vx) (y+dt*vy) (n-1) dt\n\nduringAndAfter :: Monad m => Float -> Float -> Float -> (Float -> m ()) -> m ()\nduringAndAfter t t0 t1 m = \n    if t < t0\n        then return ()\n        else if t > t1\n            then m 1\n            else m ((t-t0)/(t1-t0))\n\nbeforeAndDuring :: Monad m => Float -> Float -> Float -> (Float -> m ()) -> m ()\nbeforeAndDuring t t0 t1 m =\n    if t > t1\n        then return ()\n        else if t < t0\n            then m 1\n            else m ((t-t1)/(t0-t1))\n", "meta": {"hexsha": "563ccea0e54ed4459664bbd6a814fea350dbabdd", "size": 10179, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/ex5/Turtle.hs", "max_stars_repo_name": "dpiponi/SketchBox", "max_stars_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-23T01:58:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-23T01:58:44.000Z", "max_issues_repo_path": "examples/ex5/Turtle.hs", "max_issues_repo_name": "dpiponi/SketchBox", "max_issues_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ex5/Turtle.hs", "max_forks_repo_name": "dpiponi/SketchBox", "max_forks_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5608856089, "max_line_length": 132, "alphanum_fraction": 0.4911091463, "num_tokens": 3429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4408669138791906}}
{"text": "-- | Now we plot!\n\nmodule QuickHullDraw where\n\nimport           Control.Arrow\nimport           Data.List\nimport qualified Data.Vector             as V\nimport qualified Data.Vector.Unboxed     as UV\nimport           Graphics.Rendering.Plot\nimport           Numeric.LinearAlgebra   (Vector (..))\nimport           QuickHull\nimport           System.Environment\nimport           System.Random\n\nmain :: IO ()\nmain = do\n  [d] <- getArgs\n  let vectors =\n        V.fromList .\n        map UV.fromList .\n        chop 2 . take ((* 2) $ read d :: Int) . randomRs (0 :: Double, 100) $\n          mkStdGen 0\n      (rxL, rxH) = (0, 100)\n      (ryL, ryH) = (0, 100)\n      (vx, vy) = convertPoints vectors\n      hull' = qhull2D vectors\n      (hx, hy) =\n        convertPoints . V.fromList $ hull'\n  writeFigure PNG (\"QHullTest\" ++ d ++ \"Points\" ++ \".png\") (600, 600) (testFig vx vy hx hy (rxL, rxH) (ryL, ryH))\n\nconvertPoints :: V.Vector (UV.Vector Double) -> (Vector Double, Vector Double)\nconvertPoints =\n  (V.convert *** V.convert) .\n  V.unzip . V.map (UV.unsafeHead &&& UV.unsafeLast)\n\ntestFig :: Series\n        -> Series\n        -> Series\n        -> Series\n        -> (Double, Double)\n        -> (Double, Double)\n        -> Figure ()\ntestFig xs ys hx hy (rxL, rxH) (ryL, ryH) = do\n  withTextDefaults $ setFontFamily \"OpenSymbol\"\n  withTitle $ setText \"2D Convex Hull with QuickHull!\"\n  setPlots 1 1\n  withPlot (1, 1) $\n    do\n      setDataset [(xs, point ys (Asterisk, red)), (hx, point hy (Box, purple))]\n      addAxis XAxis (Side Lower) $ withAxisLabel $ setText \"x-axis\"\n      addAxis YAxis (Side Lower) $ withAxisLabel $ setText \"y-axis\"\n      addAxis XAxis (Value 0) $ return ()\n      setRange XAxis Lower Linear (rxL - 5) (rxH + 5)\n      setRange YAxis Lower Linear (ryL - 5) (ryH + 5)\n\nchop :: Int -> [a] -> [[a]]\nchop n =\n  unfoldr\n    (\\v -> if null v\n             then Nothing\n             else Just $ splitAt n v)\n", "meta": {"hexsha": "c10f5d23f44a682bd8ad42795742cc1ae93b631c", "size": 1910, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/QuickHullDraw.hs", "max_stars_repo_name": "emmanueldenloye/QuickHull", "max_stars_repo_head_hexsha": "73411a840c940d538269f1129666ace8e763c22e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-02-26T05:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T18:04:59.000Z", "max_issues_repo_path": "src/QuickHullDraw.hs", "max_issues_repo_name": "emmanueldenloye/QuickHull", "max_issues_repo_head_hexsha": "73411a840c940d538269f1129666ace8e763c22e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-02-26T05:50:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-26T05:50:32.000Z", "max_forks_repo_path": "src/QuickHullDraw.hs", "max_forks_repo_name": "emmanueldenloye/QuickHull", "max_forks_repo_head_hexsha": "73411a840c940d538269f1129666ace8e763c22e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-02-26T05:16:26.000Z", "max_forks_repo_forks_event_max_datetime": "2016-02-26T05:16:26.000Z", "avg_line_length": 30.8064516129, "max_line_length": 113, "alphanum_fraction": 0.5743455497, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4404504662288912}}
{"text": "module InterpSpec where\n\nimport Commons\nimport Data.Complex (Complex (..))\nimport Data.Map.Strict (union)\nimport Data.Maybe (fromJust)\nimport Debug.Trace (traceShowId)\nimport HashedExpression.Internal.Expression\nimport HashedExpression.Internal.Normalize\nimport HashedExpression.Internal.Utils\nimport HashedExpression.Interp\nimport HashedExpression.Operation hiding (product, sum)\nimport qualified HashedExpression.Operation\nimport HashedExpression.Prettify\nimport Test.Hspec\nimport Test.QuickCheck (property)\nimport Var\nimport Prelude hiding ((^))\n\n-- |\nprop_AddScalarR :: SuiteScalarR -> SuiteScalarR -> Bool\nprop_AddScalarR (Suite exp1 valMaps1) (Suite exp2 valMaps2) =\n  eval valMaps (exp1 + exp2) == eval valMaps exp1 + eval valMaps exp2\n  where\n    valMaps = valMaps1 `union` valMaps2\n\n-- |\nprop_MultiplyScalarR :: SuiteScalarR -> SuiteScalarR -> Bool\nprop_MultiplyScalarR (Suite exp1 valMaps1) (Suite exp2 valMaps2) =\n  eval valMaps (exp1 * exp2) == eval valMaps exp1 * eval valMaps exp2\n  where\n    valMaps = valMaps1 `union` valMaps2\n\n-- |\nprop_AddScalarC :: SuiteScalarC -> SuiteScalarC -> Bool\nprop_AddScalarC (Suite exp1 valMaps1) (Suite exp2 valMaps2) =\n  eval valMaps (exp1 + exp2) == eval valMaps exp1 + eval valMaps exp2\n  where\n    valMaps = valMaps1 `union` valMaps2\n\n-- |\nprop_MultiplyScalarC :: SuiteScalarC -> SuiteScalarC -> Bool\nprop_MultiplyScalarC (Suite exp1 valMaps1) (Suite exp2 valMaps2) =\n  eval valMaps (exp1 * exp2) == eval valMaps exp1 * eval valMaps exp2\n  where\n    valMaps = valMaps1 `union` valMaps2\n\n-- |\nprop_RotateOneR1 :: SuiteOneR -> Bool\nprop_RotateOneR1 (Suite exp valMaps) =\n  eval valMaps (rotate 0 exp) == eval valMaps exp\n\n-- |\nprop_RotateOneR2 :: SuiteOneR -> Int -> Bool\nprop_RotateOneR2 (Suite exp valMaps) amount =\n  eval valMaps (f exp) == eval valMaps exp\n  where\n    f = rotate amount . rotate (- amount)\n\n-- |\nprop_RotateOneR3 :: SuiteOneR -> Int -> Int -> Bool\nprop_RotateOneR3 (Suite exp valMaps) amount1 amount2 =\n  eval valMaps (f1 exp) == eval valMaps (f2 exp)\n  where\n    f1 = rotate amount1 . rotate amount2\n    f2 = rotate (amount1 + amount2)\n\n-- |\nprop_RotateTwoR1 :: SuiteTwoR -> Bool\nprop_RotateTwoR1 (Suite exp valMaps) =\n  eval valMaps (rotate (0, 0) exp) == eval valMaps exp\n\n-- |\nprop_RotateTwoR2 :: SuiteTwoR -> (Int, Int) -> Bool\nprop_RotateTwoR2 (Suite exp valMaps) (offset1, offset2) =\n  eval valMaps (f exp) == eval valMaps exp\n  where\n    f = rotate (offset1, offset2) . rotate (- offset1, - offset2)\n\n-- |\nprop_RotateTwoR3 :: SuiteTwoR -> (Int, Int) -> (Int, Int) -> Bool\nprop_RotateTwoR3 (Suite exp valMaps) amount1 amount2 =\n  eval valMaps (f1 exp) == eval valMaps (f2 exp)\n  where\n    f1 = rotate amount1 . rotate amount2\n    f2 = rotate (fst amount1 + fst amount2, snd amount1 + snd amount2)\n\nspec :: Spec\nspec =\n  describe \"Interp spec\" $ do\n    specify \"prop_Add Scalar R\" $ property prop_AddScalarR\n    specify \"prop_Multiply Scalar R\" $ property prop_MultiplyScalarR\n    specify \"prop_Add Scalar C\" $ property prop_AddScalarC\n    specify \"prop_Multiply Scalar C\" $ property prop_MultiplyScalarC\n    specify \"prop_Rotate One R rotate 0 should stay the same\" $\n      property prop_RotateOneR1\n    specify \"prop_Rotate One R rotate a and -a should stay the same\" $\n      property prop_RotateOneR2\n    specify\n      \"prop_Rotate One R rotate a then rotate b should equal rotate (a + b)\"\n      $ property prop_RotateOneR3\n    specify \"prop_Rotate Two R rotate (0, 0) should stay the same\" $\n      property prop_RotateTwoR1\n    specify \"prop_Rotate Two R rotate a and -a should stay the same\" $\n      property prop_RotateTwoR2\n    specify\n      \"prop_Rotate Two R rotate a then rotate b should equal rotate (a + b)\"\n      $ property prop_RotateTwoR3\n", "meta": {"hexsha": "191e5be427d5e9862734d0a19ed28331b44925bc", "size": 3730, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/InterpSpec.hs", "max_stars_repo_name": "Turboscient/HashedExpression", "max_stars_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-30T00:10:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T21:31:19.000Z", "max_issues_repo_path": "test/InterpSpec.hs", "max_issues_repo_name": "Turboscient/HashedExpression", "max_issues_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-23T19:22:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-26T18:47:55.000Z", "max_forks_repo_path": "test/InterpSpec.hs", "max_forks_repo_name": "Turboscient/HashedExpression", "max_forks_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-05-25T00:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T00:37:36.000Z", "avg_line_length": 34.2201834862, "max_line_length": 76, "alphanum_fraction": 0.7252010724, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4403065036169311}}
{"text": "{-# LANGUAGE ConstraintKinds, ScopedTypeVariables, TypeApplications, AllowAmbiguousTypes, NoImplicitPrelude,\n    GeneralizedNewtypeDeriving, FlexibleContexts\n#-}\nmodule LinRel where\n\nimport Numeric.LinearAlgebra\nimport Prelude hiding ((<>))\nimport Debug.Trace\ntype BEnum a = (Enum a, Bounded a) \nenumAll :: (BEnum a) => [a] -- What about Void?\nenumAll = [minBound .. maxBound]\n\n\n\n-- A Hacked \"Void\" type to get card @Void = 0\ndata Void = Void' | Void'' -- SORRY MOM.\ninstance Enum Void where\n  fromEnum Void' =  1\n  fromEnum Void'' = 0\n  toEnum 1 = Void'\n  toEnum 0 = Void''\ninstance Bounded Void where\n  maxBound = Void''\n  minBound = Void'\n\ninstance (Enum a, Enum b, Bounded a) => Enum (Either a b) where\n  fromEnum (Left a) = fromEnum a\n  fromEnum (Right b) = fromEnum b + fromEnum (maxBound @a) + 1\n  toEnum n | n <= ((fromEnum (maxBound @a)) - (fromEnum (minBound @a))) = Left (toEnum n)\n           | otherwise = Right (toEnum (n - fromEnum (maxBound @a))) \n\n\ninstance (Bounded a, Bounded b) => Bounded (Either a b) where\n  maxBound = Right maxBound\n  minBound = Left minBound\n\ncard :: forall a. (BEnum a) => Int\ncard = (fromEnum (maxBound @a)) - (fromEnum (minBound @a)) + 1\n\n-- HLinRel holds A x = b constraint\ndata HLinRel a b = HLinRel (Matrix Double) (Vector Double) deriving Show\n\n-- x = A l + b. Generator constraint. \ndata VLinRel a b = VLinRel (Matrix Double) (Vector Double) deriving Show\n\n\n-- f(x) = xQx + bx\ndata QuadOp a b = QuadOp (Matrix Double) (Vector Double)\n{-\nqid :: QuadOp a a\nqid = ? -- a = a ? Need Relations too.\n\nqcompose :: QuadOp b c -> QuadOp a b -> QuadOp a c\nqcompose (QuadOp q c) (QuadOp q' c') = QuadOp q'' c'' where\n        where \n                ca = card @a\n                cb = card @b \n                cc = card @c\n                a = subMatrix (cb, cb) q\n                b = subMatrix (cb,cc) q\n                c = subMatrix (cc, cb) q\n                d = subMatrix (cc,cc) q\n                a' = subMatrix (ca, ca) q'\n                b' = subMatrix (ca, cb) q'\n                c' = subMatrix (cb, ca  q'\n                d' = subMatrix (cb, cb) q'\n                m = - (a + d')\n                q'' = fromBlocks [[a' + b' <> m </> c'   , b' <> m </> c ],  -- can memoize some of this\n                                  [b <> m </> c' , d - ]]\n                \n                a'' =  a' - b' <> m </> c'\n                [v1', v2'] = takesV [ca,cb] c'\n                [v1,  v2] = takesV [cb, cc] c\n                v3 = (v2' + v1) \n                c'' = vJoin [v1' + m </> c #>  v3, ]\n\n        -}\n    {-\n    \n    Any cost outside the constraint space is irrelevant.\n    Q = V m V where m is fullrank.\n    c = Vc also\n\n    minimal sets\n    -}    \n        \n        -- break into pieces, form schur complement.\n\n-- if A x = b then x is in the nullspace + a vector b' solves the equation\nh2v :: HLinRel a b -> VLinRel a b\nh2v (HLinRel a b) = VLinRel a' b' where\n        b' = a <\\> b -- least squares solution\n        a' = nullspace a\n\n-- if x = A l + b, then A' . x = A' A l + A' b = A' b because A' A = 0\nv2h :: VLinRel a b -> HLinRel a b\nv2h (VLinRel a' b') = HLinRel a b where\n        b = a #> b' -- matrix multiply\n        a = tr $ nullspace (tr a') -- orthogonal space to range of a.\n\nhid :: forall a. BEnum a => HLinRel a a\nhid =  HLinRel (i ||| (- i)) (vzero s) where \n                            s = card @a\n                            i = ident s\n\nvzero :: Konst Double d c => d -> c Double\nvzero = konst 0\n\nhcompose :: forall a b c. (BEnum a, BEnum b, BEnum c) => HLinRel b c -> HLinRel a b -> HLinRel a c\nhcompose (HLinRel m b) (HLinRel m' b') = let a'' = fromBlocks [[       ma',           mb' ,    0       ],\n                                                               [         0 ,    mb,        mc          ]] in\n                                         let b'' = vjoin [b', b] in \n                                         let (VLinRel q p) = h2v (HLinRel a'' b'') in -- kind of a misuse\n                                         let q' = (takeRows ca q)  -- drop rows belonging to @b\n                                                       === \n                                                  (dropRows (ca + cb) q) in\n                                         let [x,y,z] =  takesV [ca,cb,cc] p in\n                                         let p'=  vjoin [x,z] in -- rebuild without rows for @b\n                                         v2h (VLinRel q' p') -- reconstruct HLinRel\n                                       where \n                                           ca = card @a\n                                           cb = card @b \n                                           cc = card @c\n                                           sb = size b -- number of constraints in first relation\n                                           sb' = size b' -- number of constraints in second relation\n                                           ma' = takeColumns ca m'\n                                           mb' = dropColumns ca m'\n                                           mb = takeColumns cb m\n                                           mc = dropColumns cb m\n\n(<<<) :: forall a b c. (BEnum a, BEnum b, BEnum c) => HLinRel b c -> HLinRel a b -> HLinRel a c\n(<<<) = hcompose\n-- stack the constraints\nhmeet :: HLinRel a b -> HLinRel a b -> HLinRel a b\nhmeet (HLinRel a b) (HLinRel a' b') = HLinRel (a === a') (vjoin [b,b'])\n\n\n\n\n{- If they don't meet are we still ok? \n\nI am not sure. Might be weird corner cases?\n\n-}\n\nhjoin :: HLinRel a b -> HLinRel a b -> HLinRel a b\nhjoin v w = v2h $ vjoin' (h2v v) (h2v w)\n\n-- hmatrix took vjoin from me :(\n-- joining means combining generators and adding a new generator\n-- Closed under affine combination l * x1 + (1 - l) * x2 \nvjoin' :: VLinRel a b -> VLinRel a b -> VLinRel a b\nvjoin' (VLinRel a b) (VLinRel a' b') = VLinRel (a ||| a' ||| (asColumn (b - b'))) b\n\n-- no constraints, everything\n-- trivially true\nhtop :: forall a b. (BEnum a, BEnum b) => HLinRel a b \nhtop = HLinRel (vzero (1,ca + cb)) (konst 0 1) where \n                                      ca = card @a\n                                      cb = card @b \n{-\nhbottom :: forall a b. (BEnum a, BEnum b) => HLinRel a b \nhbottom = HLinRel (vzero (1,ca + cb)) (konst 1 1) where \n                                      ca = card @a\n                                      cb = card @b       \n                                      -}                                \n-- all the constraints! Only the origin.\n-- no. it should be the empty set. Impossible to satisfy.\n-- 0 x = 1 is impossible\n-- not gonna play nice.\n{-\nhbottom :: forall a b. (BEnum a, BEnum b) => HLinRel a b \nhbottom = HLinRel (ident (ca + cb)) (konst 0 (ca + cb)) where \n                                    ca = card @a\n                                    cb = card @b  \n  -}                            \n\nhconverse :: forall a b. (BEnum a, BEnum b) => HLinRel a b -> HLinRel b a \nhconverse (HLinRel a b) = HLinRel ( (dropColumns ca a) |||  (takeColumns ca a)) b where \n    ca = card @a\n    cb = card @b  \n\n    -- this is numerically unacceptable\n-- forall l. A' ( A l + b) == b'\nvhsub :: VLinRel a b -> HLinRel a b -> Bool\nvhsub (VLinRel a b) (HLinRel a' b') = (naa' <=  1e-10 * (norm_2 a') * (norm_2 a)  ) && ((norm_2 ((a' #> b) - b')) <= 1e-10 * (norm_2 b')  ) where\n          naa' = norm_2 (a' <> a)\n\nhsub :: HLinRel a b -> HLinRel a b -> Bool\nhsub h1 h2 = vhsub (h2v h1) h2\n\nheq :: HLinRel a b -> HLinRel a b -> Bool\nheq a b = (hsub a b) && (hsub b a)\n\n\ninstance Ord (HLinRel a b) where\n  (<=) = hsub\n  (>=) = flip hsub \n\ninstance Eq (HLinRel a b) where\n  (==) = heq\n\n\n-- I can't do this right?\n-- hcomplement :: HLinRel a b -> HLinRel a b\n-- hcomplement  \n\nhpar :: HLinRel a b -> HLinRel c d -> HLinRel (Either a c) (Either b d)\nhpar (HLinRel mab v) (HLinRel mcd v') = HLinRel (fromBlocks [ [mab, 0], [0 , mcd]]) (vjoin [v, v']) where\n\n\nhassoc :: forall a b c. (BEnum a, BEnum b, BEnum c) => HLinRel (Either (Either a b) c) (Either a (Either b c))\nhassoc = HLinRel m v where HLinRel m v = hid @((Either (Either a b) c))\n\nhassoc' :: forall a b c. (BEnum a, BEnum b, BEnum c) => HLinRel  (Either a (Either b c)) (Either (Either a b) c)\nhassoc' = HLinRel m v where HLinRel m v = hid @((Either (Either a b) c))\n\n{-\n        -- Void is unit for Either.\n-- void has no inhabitants.... This is a bad boy.\n\n\nhcup :: HLinRel Void (Either a a)\nhcap :: HLinRel (Either a a) Void\n\n\n\n\n-}\nhleft :: forall a b. (BEnum a, BEnum b) => HLinRel a (Either a b)\nhleft = HLinRel ( i ||| (- i) ||| (konst 0 (ca,cb))) (konst 0 ca) where \n    ca = card @a\n    cb = card @b  \n    i = ident ca\n\nhright :: forall a b. (BEnum a, BEnum b) => HLinRel b (Either a b)\nhright = HLinRel ( i ||| (konst 0 (cb,ca)) ||| (- i) ) (konst 0 cb) where \n    ca = card @a\n    cb = card @b  \n    i = ident cb\n\n\nhfan ::  forall a b c. BEnum a => HLinRel a b -> HLinRel a c -> HLinRel a (Either b c)\nhfan (HLinRel m v) (HLinRel m' v') = HLinRel (fromBlocks [ [ma, mb, 0], [ma', 0, mc']]) (vjoin [v,v']) where\n        ca = card @a\n        ma = takeColumns ca m \n        mb = dropColumns ca m \n        ma' = takeColumns ca m' \n        mc' = dropColumns ca m' \n\n\nhdump :: HLinRel a Void\nhdump = HLinRel 0 0\n{-\nhlabsorb :: HLinRel a b -> HLinRel (Either Void a) b\nhlabsorb (HLinRel m v) = (HLinRel m v)\n-}\nhlabsorb ::forall a. BEnum a => HLinRel (Either Void a) a\nhlabsorb = HLinRel m v where (HLinRel m v) = hid @a \n\nhtrans :: HLinRel a (Either b c) -> HLinRel (Either a b) c \nhtrans (HLinRel m v) = HLinRel m v\n\nhswap :: forall a b. (BEnum a, BEnum b) => HLinRel (Either a b) (Either b a)\nhswap = HLinRel (fromBlocks [[ia ,0,0 ,-ia], [0, ib,-ib,0]]) (konst 0 (ca + cb)) where \n        ca = card @a\n        cb = card @b  \n        ia = ident ca\n        ib = ident cb\n\n\nhsum :: forall a. BEnum a => HLinRel (Either a a) a\nhsum = HLinRel ( i ||| i ||| - i ) (konst 0 ca)  where \n        ca = card @a \n        i= ident ca\n\nhdup :: forall a. BEnum a => HLinRel a (Either a a)\nhdup = HLinRel (fromBlocks [[i, -i,0 ], [i, 0, -i]]) (konst 0 (ca + ca))  where \n        ca = card @a \n        i= ident ca\n\n-- hcup :: forall a. BEnum a => HLinRel Void (Either a a)\n-- hcup = -- or mainulate hid\n\n-- hcap :: forall a. BEnum a => HLinRel (Either a a) Void\n\n-- smart constructors\nhLinRel :: forall a b. (BEnum a, BEnum b) => Matrix Double -> Vector Double -> Maybe (HLinRel a b) \nhLinRel m v | cols m == (ca + cb) && (size v == rows m)  = Just (HLinRel m v)\n            |  otherwise = Nothing  where \n                 ca = card @a\n                 cb = card @b  \n\n-- a 2d space at every wire or current and voltage.\ndata IV = I | V deriving (Show, Enum, Bounded, Eq, Ord)\n\n\nresistor :: Double -> HLinRel IV IV\nresistor r = HLinRel ( (2><4)  [ 1,0,-1,   0,\n                                 r, 1, 0, -1]) (konst 0 2)  \n\nbridge :: Double -> HLinRel (Either IV IV) (Either IV IV)\nbridge r = HLinRel (  (4><8) [ 1,0, 1,  0, -1, 0, -1,  0, -- current conservation\n                               0, 1, 0, 0, 0, -1 , 0,  0, --voltage maintained\n                               0, 0, 0, 1, 0,  0,  0, -1, -- voltage maintained\n                               r, 1, 0,-1, -r,  0,  0, 0  ]) (konst 0 4)  \nshort = bridge 0\n\n\n\nfirst :: BEnum c => HLinRel a b -> HLinRel (Either a c) (Either b c)\nfirst f = hpar f hid \n\nsecond :: BEnum a => HLinRel b c -> HLinRel (Either a b) (Either a c)\nsecond f = hpar hid f\n\ntype HLinRel2D u d l r = HLinRel (Either u l) (Either d r)\n\n\n{-\nA stencil  of 2d resistors for tiling\n\n\n          u\n          /\n          \\\n          /\n         |\nl -/\\/\\/----/\\/\\/\\-  r\n         |\n         /\n         \\\n         /\n         |\n         d\n\n\n        -}\nstencil :: HLinRel2D IV IV IV IV\nstencil = (hpar r10 r10) <<< short <<< (hpar r10 r10) where r10 = resistor 10\n\nhoricomp :: forall w w' w'' w''' a b c. (BEnum w, BEnum w', BEnum a, BEnum w''', BEnum b, BEnum w'', BEnum c ) => HLinRel2D w' w'' b c -> HLinRel2D w w''' a b -> HLinRel2D (Either w' w) (Either w'' w''') a c\nhoricomp f g = hcompose f' g' where \n               f' :: HLinRel (Either (Either w' w''') b) (Either (Either w'' w''') c)\n               f' = (first hswap) <<< hassoc' <<< (hpar hid f) <<< hassoc <<<  (first hswap) \n               g' :: HLinRel (Either (Either w' w) a) (Either (Either w' w''') b)\n               g' = hassoc' <<< (hpar hid g) <<< hassoc\n\n\nrotate :: (BEnum w, BEnum w', BEnum a, BEnum b) => HLinRel2D w w' a b -> HLinRel2D a b w w'                                      \nrotate f = hswap <<< f <<< hswap\n\nvertcomp :: (BEnum w, BEnum w', BEnum a, BEnum d, BEnum b, BEnum w'', BEnum c ) => HLinRel2D w'  w'' c d -> HLinRel2D w w' a b -> HLinRel2D w w'' (Either c a) (Either d b)\nvertcomp f g = rotate (horicomp (rotate f)  (rotate g) ) \n\n{-\ntraceV :: ->\ntraceH :: ->\n\n\n  -}\n\nstencil2 = vertcomp h h where h = stencil `horicomp` stencil\n\n\n\n{- Legendre transformations in thermo are for open systems. SOmething to that -}\n{- Dependent sources. Well, these are goddamn cheating.\nWe could do it though\n|   |\nI   alpha I\n|   |\n\nsmall signal models of transistor, op amps etc\n\n\ngyrator - would need polynomials from caps and inds\nwould be kind of nice for boundary models\n\nkron instead of dsum - Quantum fields\nKron relation might be nice for discussing remnant space of topological matter\n\n\n\n-}\n\n{-\n\nA wire in a circuit has a potential (questionably) and a current running through it\nSo our wires should have both of these variables.\n\n-}\nnewtype VProbe = VProbe () deriving (Enum, Bounded, Show, Eq, Ord)\nvprobe :: HLinRel IV VProbe\nvprobe = HLinRel ( (2><3)  [1,0,0,\n                            0,1,-1]) (konst 0 2)                \n\nvsource :: Double -> HLinRel IV IV\nvsource v = HLinRel ( (2><4) [ 1,0,-1,   0,\n                               0, 1, 0, -1]) (fromList [0,v])  \n\nisource :: Double -> HLinRel IV IV\nisource i = HLinRel ( (2><4) [  1,0, -1,   0 , -- current conservation\n                                 1, 0, 0,  0]) (fromList [0,i])  \n\n\n-- the currents add, but the voltages dup. sum and dup are dual\n-- Or should it be |--|   a parallel short?\n-- Ad then we could open circuit one of them and absorb the Void\n-- to derive this\ncmerge :: HLinRel (Either IV IV) IV\ncmerge = HLinRel ( (3><4)  [1, 0, 1, 0, -1, 0,\n                            0,1,0,0,0 ,  -1  ,\n                            0,0,0,1, 0, -1])  (konst 0 3)\n\nopen :: HLinRel IV Void\nopen = HLinRel ( (1><2) [1,0]) (konst 0 1)\n\n\ncap :: HLinRel  (Either IV IV) Void\ncap  = hcompose open cmerge\n\ncup :: HLinRel Void (Either IV IV)\ncup = hconverse cap\n\nground :: HLinRel IV Void\nground = HLinRel ( (1><2) [ 0 , 1 ]) (vzero 1) \n\n-- resistors in parallel.\n\nex1 = hcompose (bridge 10) (bridge 10)\nex2 = hcompose (resistor 10) (resistor 30) -- resistors in series.\nr20 :: HLinRel IV IV\nr20 = resistor 20\n\ndivider :: Double -> Double -> HLinRel (Either IV IV) (Either IV IV)\ndivider r1 r2 = hcompose (bridge r2) (hpar (resistor r1) hid) \n\n{-\ntype StateCoState s = Either s s\ntype ValueD s = s\n\n\ndynamics :: HLinRel (Either SHOState Control) SHOState\ndynamics = HLinRel ((2><5)  [ 1,  dt, 0, -1 ,  0,\n                              -dt, 1, dt, 0, -1 ])  (vzero 2)\n   where dt = 0.01  \n\n-- labsorb <<< (par initial_cond id)\n-}\n\n\n-- state of an oscillator\ndata SHOState = X | P deriving (Show, Enum, Bounded, Eq, Ord)\ndata Control = F  deriving (Show, Enum, Bounded, Eq, Ord)\n-- Costate newtype wrapper\nnewtype Co a = Co a deriving (Show, Enum, Bounded, Eq, Ord)\n\ntype M = Matrix Double\ndynamics :: forall x u. (BEnum x, BEnum u) =>  Matrix Double -> Matrix Double ->  \n  HLinRel (Either x u) x\ndynamics a b =  HLinRel (a ||| b ||| -i )  (vzero cx) where\n  cx = card @x\n  cu = card @u\n  i = ident cx\n\ninitial_cond :: forall x. BEnum x => Vector Double-> HLinRel Void x\ninitial_cond x0 =  HLinRel i x0 where\n  cx = card @x\n  i = ident cx\n\nvalueUpdate :: forall x l. (BEnum x, BEnum l) =>  M -> M -> HLinRel (Either x l) l\nvalueUpdate a q = HLinRel ((tr a) ||| q ||| i)  (vzero cl) where\n  cl = card @l\n  i = ident cl  \n\noptimal_u :: forall u l. (BEnum u, BEnum l) => \n     M -> M -> HLinRel u l\noptimal_u r b = HLinRel (r ||| tr b) (vzero cu) where\n  cu = card @u\n \nstep :: forall x u l. (BEnum x, BEnum u, BEnum l) => M -> M -> M -> M \n        -> HLinRel (Either x l) (Either x l)\nstep a b r q = \n  f5 <<< f4 <<< hassoc' <<< f3 <<< f2 <<< hassoc <<< f1 where\n  f1 :: HLinRel (Either x l) (Either (Either x x) l)\n  f1 = first hdup\n  f2 :: HLinRel (Either x (Either x l)) (Either x l)\n  f2 = second (valueUpdate a q)\n  f3 ::  HLinRel (Either x l) (Either x (Either l l))\n  f3 = second hdup\n  f4 ::  HLinRel (Either (Either x l) l) (Either (Either x u) l)\n  f4 = first (second (hconverse (optimal_u r b)))\n  f5 ::  HLinRel (Either (Either x u) l) (Either x l)\n  f5 = first (dynamics a b)\n\n-- iterate (hcompose (step a b r q)) :: [HLinRel (Either x l) (Either x l)]\n\n\n\n {-\nstep :: forall x l. (BEnum x, BEnum l) => \n   HLinRel (State + ValueD) (State + ValueD)\nstep a b q r =                \n= dynamics, \n  valueUpdate <<< fst\n  second optimal_u\n  par (par hid cup) hid\n   ::  , optimal_u\n-}\n{-\ncost :: HLinRel (Either (Co SHOState) SHOState Control) (Co SHOState)\ncost = HLinRel ((2><5) [ 1,  0, 0,  -1 ,  0,\n                        -dt, 1,  dt,  0,  -1 ])  (vzero 2)\n-}\n\n\n\n\n\n{-\n\nIs there a reasonable intepretation of kron?\n\n-}\n{-\neverything can be definedc inefficiently via v2s and h2v functions\n\nright division\n\n-}\n\n    {-\nCall them affine relations\n\nJoin and meet aren't union and intersection.\nThey are the affine closure of union and intersection.\n\n\n\n\nLinear has some niceness.\nHomgeonous coordinates usually do.\nFor clarity and familiaryt I have chosebn not to do it this way\nOr maybe I will do it?\n\npar\n\n\n-}\n\n\n{-\n\nimport numpy as np\n\n\ndef meet(a,b):\n    pass\ndef compose(a,b): # a after b\n    assert(a.inN == b.outN)\n\n    combo = np.block([[a.constraints, np.zeros((a.constraints.shape[0] , b.inN) )     ],\n                      [np.zeros((b.constraints.shape[0] , a.outN)) ,      b.constraints]])\n    print(combo)\n    gens = LinRel(a.inN + a.outN, b.outN, gens=combo).gens\n    print(\"gens\",gens) \n    gens = np.vstack((gens[:a.outN, :], gens[-b.inN: , :]) )\n    print(gens)\n    return LinRel(a.outN, b.inN, gens=gens)\ndef top(outN, inN):\n    return LinRel(outN, inN, constraints = np.array([[]]))\ndef bottom(outN, inN):\n    return LinRel(outN, inN, gens = np.array([[]]))\n\ndef converse(a):\n    return LinRel(a.inN, a.outN, np.hstack((a.constraints[:, a.inN:], a.constraints[:, :a.inN])))\ndef complement(a):\n    return LinRel(a.outN, a.inN, constraints = a.gens.T.conj())\n\ndef right_div(a,b):\n    pass # return complement( compose(a, complement(b)) ) # something like this\ndef inclusion(a,b):\n    \n    s = a.constraints @ b.gens\n    np.all(a.constraints @ b.gens <= tol )\n\n    if rcond is None:\n        rcond = np.finfo(s.dtype).eps * max(max(a.shape), max(b.shape))\n        tol = max(np.amax(a), np.amax(b))\n        tol = np.amax(s) * rcond\ndef fromMat(mat):\n    (outN, inN) = mat.shape\n    return LinRel(inN, outN,constraints = np.hstack((mat,-np.eye(outN))))\ndef id(N):\n    return fromMat(np.eye(N))\n# make 0,1 first index for in/out? Oh, but then in out have to be same size.\n# A[0, ...] @ x + A[1, ...] @ y = 0   \n# Then I can form the kron of linear relations. \n# store sperate A B matrices? A @in + B @ out\nclass LinRel():\n    def __init__(self, outN, inN, constraints = None, gens = None, rcond=None):\n        #assert(inN <= constraints.shape[1])\n        self.inN = inN\n        self.outN = outN\n        if constraints is not None: #baiscally scipy.linalg.null_space\n            u, s, vh = np.linalg.svd(constraints, full_matrices=True)\n            M, N = u.shape[0], vh.shape[1]\n            if rcond is None:\n                rcond = np.finfo(s.dtype).eps * max(M, N)\n            tol = np.amax(s) * rcond\n            num = np.sum(s > tol, dtype=int)\n            self.gens = vh[num:,:].T.conj()\n            self.constraints = vh[:num,:]\n        if gens is not None: #basically scipy.linalg.orth\n            u, s, vh = np.linalg.svd(gens, full_matrices=True)\n            M, N = u.shape[0], vh.shape[1]\n            if rcond is None:\n                rcond = np.finfo(s.dtype).eps * max(M, N)\n            tol = np.amax(s) * rcond\n            num = np.sum(s > tol, dtype=int)\n            self.gens = u[:, :num]\n            self.constraints = u[:, num:].T.conj()\n\n    def shape(self):\n        return (self.outN, self.inN)\n    def size(self):\n        return self.outN + self.inN\n    # operator overloadings\n    def __matmul__(a,b):\n        return compose(a,b)\n    def __invert__(a): # ~\n        return complement(a)\n    def __or__(a,b): # an argument could be made for + and *\n        return join(a,b)\n    def __and__(a,b):\n        return meet(a,b)\n    def __sub__(a,b):\n        return  (a) & (-b)\n    def __le__(a,b): # Are the others automatic?\n        return inclusion(a,b)\n    def __str__(self):\n        return \" Constraints: \\n%s, \\nGens:\\n %s\\n\" % (str(self.constraints), str(self.gens))\n\n\n\n\nex = LinRel(1,2, np.array([[3,4,0]]))\ne2 = LinRel(2,1, np.array([[3,4,0]]))\n\nassert(np.all(LinRel(1,2, ex.constraints).constraints == ex.constraints) )\nprint( ex.constraints @ ex.gens)\nassert(np.all( np.abs(ex.constraints @ ex.gens) <= 1e-15) )\nprint(ex @ e2)\nprint(e2 @ ex)\nprint(e2 @ id(e2.inN))\n\n'''\nQuadratic optimization can be mixed in.\nQuad && LinRel\n\nAffineRel = maintain homgenous coord, or always insert 1 -1 keeping homoeg coord\n+ discrete? Maintain a couple copies of \n\n\n'''\n\n\nLinear relations\nhrep - Ax = 0\nor\nvrep - y = sum x_i\n\nhrep <-> vrep = row echelon\n\nin and out variables. In and out subspaces.\nin : [] - list of indices\nout : []\n\nin is a vrep of input space.\n\nin = projection/injection matrix n x d\nout = projection/injection matrix. (d-n) x d\nin * out = 0. orthogonal\n\nauxiliary variables allowed\n\ncompose relations\nin1 out1\nin2 out2\n\nin = d x n\nstack out1 and in2 into matrix. with them equal.\n\nnp.hstack(A1, out1 - in2, A2)\nin = no.hatck(in, zeores)\nin = no.hatck(zeores, out)\n\ndrect sum as monoidal product\nblock([ A, 0  ],\n      [ 0, A  ])\nin = [in1, in2]\nout = [out1, out2]\n\nconverse = flip in out\n\nmeet = combine the two constraint matrices\njoin = convert? combine in out?\n\n1-d as unit object\n<= is subspace ordering\n\nnegation = orthogonalization\ndivision => \n\n\na linear problem is a linear relation of 1-d.\n\nuse in1 and out2 as new in/out\n\nfan \nsnd(30,10) = project bottom 10 = idetnity matrix stacked.\nfst(30, 10) project top 10\nid(20)\nid(n) = LinRel(np.zeros(0,2*n), [zeros, eye], [eye, zero] ) \nid(n) = LinRel((0,n), eye(n), eye(n)  )\n        LinRel [I, -I], [I, 0], [0,I]\n\n\"internal\" space\nclass LinRel():\n    def __init__(A, in, out):\n\nsvd(in * A , smallest )\n1 - A*A\n\nAx + By = 0\n\nvstack adds constraints\nhstack adds variables\n\ndef idRel(n):\n  return LinRel(sparse.lil_matrix((0,n)), n, n)\ndef mapRel(A):\n  (r,c) = A.shape\n  newA = sparse.hstack(A, - sparse.eye(r))\n  return LinRel(newA, r, c) \n\nclass LinRelV():\nclass LinRelH():\n\nclass LinRel():\n  def init(self,A, in, out):\n    self.A = A\n    self.in = in\n    self.out = out\n  def compose(self, b):\n    assert(self.out == b.in, \"Shapes must match\")\n    \n    i = sparse.eye(b.in)\n    cons = sparse.hstack([0, i, -i, 0])\n    ina = self.A[:,:self.in]\n    auxa = self.A[:,self.in:-self.out]\n    outa = self.A[:,-self.out:]\n    inb = b.A[:,:b.in]\n    auxb = b.A[:,b.in:-b.out]\n    outb = b.A[:,-b.out:]\n\n    newA = sparse.bmat(  [[ina, auxa, outa, 0, 0,    0],\n                          [0  , 0   , i,   -i, 0 ,   0]\n                          [0,  0,   0,    inb, auxb,outb]])\n    LinRel(newA, self.in, b.out)\n  def meet(self,b):\n    #hmm. I suppose we acutlaly should split the thing apart again\n    assert(self.in == b.in)\n    assert(self.out == b.out)\n    assert()\n    newA = sparse.vstack([self.A, b.A])\n    return ()\n  def complement(self):\n    linalg.svd(self.A)\n    return LinRel(get_nonzeroeigs)\n  def __negate__(self):\n    return self.complement()\n  def rdiv(self):\n  def transpose():\n    self.converse()\n  def T():\n    self.converse()\n  \n  # the svd gives you most of what you need?\n  def inclusion():\n    x = linalg.nullspace(self.A)\n    return b.A @ x == 0 #check that every generator is in. Makes sense. Except numrically is trash.\n  def __leq__(self):\n    self.inclusion(b)\n\n  \n\n  def converse(rel):\n      newA = np.hstack( [ rel.A[:,-rel.out: ] , rel.A[:,rel.in:-rel.out], rel.A[:,:rel.in ] ])\n      return LinRel(newA, rel.out, rel.in)\n\n\ncompose(A)\nlinalg.nullspace(A)\nrange?\n\n\n\n(cons1,d1) = self.A.shape\n(cons2,d2) = b.A.shape\nconstrain = np.hstack \nnewA = sparse.vstack \n\n\nusing bigM I can encode the complement of a H-polytope \nbut then what?\nI do it again I guess?\n\n\ncomplementation of relation ->\nAt least one must be inverted.\n\npolytope inclusion\n-> search for point not in B.\nOr, do sandardinni encoding\n\nReally It should generate new variables for an instantiation.\nSnd should not reuse the same variables every time.\nclass PolyRel()\n  invars = []\n  constraints = [] # store >= values, not full constraints?\n  outvars = []\n  def __init__():\n    all fresh variables\n  def compose(self,b):\n    PolyRel(self.constraints + self., invars = outvars )\n  def complement():\n    zs = []\n    for c in constraints:\n      z, constraints = reify(c)\n      # z = cvx.Variable(1, boolean=True) # actually make same shape as c\n      # c += c + M * z\n    sum(zs) >= 1 # one or more constraints is disatisfied.\n  def rdiv():\n\nyeah. We should use a dsl, compile it, then encode it.\ndata Rel a b where\n  Compose ::\n  Complement ::\n  Converse ::\n\n\nrelu\n\nl1 >= 0\nl2 >= 0\nl1 <= M * z\nl2 <= M * (1 - z)\nx = lambda1 - lambda2\ny = lambda1\n\nMaybe insetado f subspaces, we should be thinking ellipses and svd.\n\n\n\n-}", "meta": {"hexsha": "57f167b3d6770508e30c49c16ea6e82bcab75c37", "size": 25597, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/LinRel.hs", "max_stars_repo_name": "philzook58/ConvexCat", "max_stars_repo_head_hexsha": "ba2162c9bf19a026758441ffd2023e5af1cd8e2d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-11-15T22:38:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T14:42:47.000Z", "max_issues_repo_path": "src/LinRel.hs", "max_issues_repo_name": "philzook58/ConvexCat", "max_issues_repo_head_hexsha": "ba2162c9bf19a026758441ffd2023e5af1cd8e2d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinRel.hs", "max_forks_repo_name": "philzook58/ConvexCat", "max_forks_repo_head_hexsha": "ba2162c9bf19a026758441ffd2023e5af1cd8e2d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.523644752, "max_line_length": 207, "alphanum_fraction": 0.5489705825, "num_tokens": 8331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.439979246272994}}
{"text": "\nimport Test.Framework\nimport Test.Framework.Providers.QuickCheck2\n\nimport Vector\nimport STVector\nimport Matrix\nimport STMatrix\nimport Statistics\n\nmain :: IO ()\nmain = defaultMain tests\n  where\n    tests = [ tests_Vector\n            , tests_STVector\n            , tests_Matrix\n            , tests_STMatrix\n            , tests_Statistics\n            ]\n", "meta": {"hexsha": "9e236629ce36a37f0a6249616fcd193aa3de93f5", "size": 351, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Main.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "tests/Main.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Main.hs", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 17.55, "max_line_length": 43, "alphanum_fraction": 0.6552706553, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.43997076443975436}}
{"text": "-----------------------------------------------------------\n-- |\n-- module:                      Math.Complex\n-- copyright:                   (c) 2017 HE, Tao\n-- license:                     MIT\n-- maintainer:                  sighingnow@gmail.com\n--\n-- Coordinate `Data.Complex` with foundation's numeric and primitive type support.\n--\n{-# OPTIONS_GHC -Wno-orphans #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MagicHash #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UnboxedTuples #-}\n\nmodule Math.Complex\n  ( Complex (..)\n  , conjugate\n  ) where\n\nimport Foundation\nimport Foundation.Class.Storable\nimport Foundation.Primitive\n\nimport Data.Complex (Complex(..), conjugate)\nimport GHC.Exts\n\ninstance Additive a => Additive (Complex a) where\n    azero = azero :+ azero\n    (a :+ b) + (c :+ d) = (a + c) :+ (b + d)\n\ninstance (Subtractive a, Difference a ~ a) => Subtractive (Complex a) where\n    type Difference (Complex a) = (Complex a)\n    (a :+ b) - (c :+ d) = (a - c) :+ (b - d)\n\ninstance (Additive a, Subtractive a, Difference a ~ a, Multiplicative a) => Multiplicative (Complex a) where\n    midentity = midentity :+ azero\n    (a :+ b) * (c :+ d) = (a * c - b * d) :+ (b * c + a * d)\n\ninstance (Additive a, Subtractive a, Difference a ~ a, Divisible a) => Divisible (Complex a) where\n    (a :+ b) / (c :+ d) = ((a * c + b * d) / (c * c + d * d)) :+ ((b * c - a * d) / (c * c + d * d))\n\noffsetComplex :: Offset (Complex a) -> (# Int#, Int# #)\noffsetComplex !(Offset (I# i)) = (# n, n +# 1# #)\n    where !n = uncheckedIShiftL# i 1#\n\n{-# INLINE offsetComplex #-}\n\ninstance PrimType (Complex Float) where\n    primSizeInBytes _ = primSizeInBytes (Proxy :: Proxy Float) + primSizeInBytes (Proxy :: Proxy Float)\n    {-# INLINE primSizeInBytes #-}\n\n    primShiftToBytes _ = 3 -- TODO may be wrong\n    {-# INLINE primShiftToBytes #-}\n\n    primBaUIndex ba n = F# (indexFloatArray# ba n1) :+ F# (indexFloatArray# ba n2)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primBaUIndex #-}\n\n    primMbaURead mba n = primitive $ \\s1 -> let !(# s2, r1 #) = readFloatArray# mba n1 s1\n                                                !(# s3, r2 #) = readFloatArray# mba n2 s2\n                                             in (# s3, F# r1 :+ F# r2 #)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primMbaURead #-}\n\n    primMbaUWrite mba n ((F# w1) :+ (F# w2)) = primitive $ \\s1 -> let !s2 = writeFloatArray# mba n1 w1 s1\n                                                                   in (# writeFloatArray# mba n2 w2 s2, () #)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primMbaUWrite #-}\n\n    primAddrIndex addr n = F# (indexFloatOffAddr# addr n1) :+ F# (indexFloatOffAddr# addr n2)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primAddrIndex #-}\n\n    primAddrRead addr n = primitive $ \\s1 -> let !(# s2, r1 #) = readFloatOffAddr# addr n1 s1\n                                                 !(# s3, r2 #) = readFloatOffAddr# addr n2 s2\n                                              in (# s3, F# r1 :+ F# r2 #)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primAddrRead #-}\n\n    primAddrWrite addr n ((F# w1) :+ (F# w2)) = primitive $ \\s1 -> let !s2 = writeFloatOffAddr# addr n1 w1 s1\n                                                                    in (# writeFloatOffAddr# addr n2 w2 s2, () #)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primAddrWrite #-}\n\ninstance PrimType (Complex Double) where\n    primSizeInBytes _ = primSizeInBytes (Proxy :: Proxy Double) + primSizeInBytes (Proxy :: Proxy Double)\n    {-# INLINE primSizeInBytes #-}\n\n    primShiftToBytes _ = 5 -- TODO may be wrong\n    {-# INLINE primShiftToBytes #-}\n\n    primBaUIndex ba n = D# (indexDoubleArray# ba n1) :+ D# (indexDoubleArray# ba n2)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primBaUIndex #-}\n\n    primMbaURead mba n = primitive $ \\s1 -> let !(# s2, r1 #) = readDoubleArray# mba n1 s1\n                                                !(# s3, r2 #) = readDoubleArray# mba n2 s2\n                                             in (# s3, D# r1 :+ D# r2 #)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primMbaURead #-}\n\n    primMbaUWrite mba n ((D# w1) :+ (D# w2)) = primitive $ \\s1 -> let !s2 = writeDoubleArray# mba n1 w1 s1\n                                                                   in (# writeDoubleArray# mba n2 w2 s2, () #)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primMbaUWrite #-}\n\n    primAddrIndex addr n = D# (indexDoubleOffAddr# addr n1) :+ D# (indexDoubleOffAddr# addr n2)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primAddrIndex #-}\n\n    primAddrRead addr n = primitive $ \\s1 -> let !(# s2, r1 #) = readDoubleOffAddr# addr n1 s1\n                                                 !(# s3, r2 #) = readDoubleOffAddr# addr n2 s2\n                                              in (# s3, D# r1 :+ D# r2 #)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primAddrRead #-}\n\n    primAddrWrite addr n ((D# w1) :+ (D# w2)) = primitive $ \\s1 -> let !s2 = writeDoubleOffAddr# addr n1 w1 s1\n                                                                    in (# writeDoubleOffAddr# addr n2 w2 s2, () #)\n        where !(# n1, n2 #) = offsetComplex n\n    {-# INLINE primAddrWrite #-}\n\ninstance Storable (Complex Float) where\n    peek (Ptr addr) = primAddrRead addr (Offset 0)\n    poke (Ptr addr) = primAddrWrite addr (Offset 0)\n\ninstance Storable (Complex Double) where\n    peek (Ptr addr) = primAddrRead addr (Offset 0)\n    poke (Ptr addr) = primAddrWrite addr (Offset 0)\n\ninstance StorableFixed (Complex Float) where\n    size _ = size (Proxy :: Proxy Float) + size (Proxy :: Proxy Float)\n    alignment _ = alignment (Proxy :: Proxy Float)\n\ninstance StorableFixed (Complex Double) where\n    size _ = size (Proxy :: Proxy Double) + size (Proxy :: Proxy Double)\n    alignment _ = alignment (Proxy :: Proxy Double)\n", "meta": {"hexsha": "919f0c613997f309aa9e9594d7bf033d7e41d4e0", "size": 6029, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "math-foreign/src/Math/Complex.hs", "max_stars_repo_name": "sighingnow/computations", "max_stars_repo_head_hexsha": "f358abb136227912c94457e241d0966419d2b619", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-09-08T11:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:57:33.000Z", "max_issues_repo_path": "math-foreign/src/Math/Complex.hs", "max_issues_repo_name": "sighingnow/computations", "max_issues_repo_head_hexsha": "f358abb136227912c94457e241d0966419d2b619", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math-foreign/src/Math/Complex.hs", "max_forks_repo_name": "sighingnow/computations", "max_forks_repo_head_hexsha": "f358abb136227912c94457e241d0966419d2b619", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-04T11:37:33.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-04T11:37:33.000Z", "avg_line_length": 43.0642857143, "max_line_length": 114, "alphanum_fraction": 0.5335876596, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.43964755489367763}}
{"text": "-- |\n-- Tests for data serialization instances\nmodule Tests.Serialization where\n\nimport Data.Binary (Binary,decode,encode)\nimport Data.Aeson  (FromJSON,ToJSON,Result(..),toJSON,fromJSON)\nimport Data.Typeable\n\nimport Statistics.Distribution.Beta           (BetaDistribution)\nimport Statistics.Distribution.Binomial       (BinomialDistribution)\nimport Statistics.Distribution.CauchyLorentz\nimport Statistics.Distribution.ChiSquared     (ChiSquared)\nimport Statistics.Distribution.Exponential    (ExponentialDistribution)\nimport Statistics.Distribution.FDistribution  (FDistribution)\nimport Statistics.Distribution.Gamma          (GammaDistribution)\nimport Statistics.Distribution.Geometric\nimport Statistics.Distribution.Hypergeometric\nimport Statistics.Distribution.Laplace        (LaplaceDistribution)\nimport Statistics.Distribution.Normal         (NormalDistribution)\nimport Statistics.Distribution.Poisson        (PoissonDistribution)\nimport Statistics.Distribution.StudentT\nimport Statistics.Distribution.Transform      (LinearTransform)\nimport Statistics.Distribution.Uniform        (UniformDistribution)\nimport Statistics.Types\n\nimport Test.Tasty            (TestTree, testGroup)\nimport Test.Tasty.QuickCheck (testProperty)\nimport Test.QuickCheck         as QC\n\nimport Tests.Helpers\nimport Tests.Orphanage ()\n\n\ntests :: TestTree\ntests = testGroup \"Test for data serialization\"\n  [ serializationTests (T :: T (CL Float))\n  , serializationTests (T :: T (CL Double))\n  , serializationTests (T :: T (PValue Float))\n  , serializationTests (T :: T (PValue Double))\n  , serializationTests (T :: T (NormalErr Double))\n  , serializationTests (T :: T (ConfInt   Double))\n  , serializationTests' \"T (Estimate NormalErr Double)\" (T :: T (Estimate NormalErr Double))\n  , serializationTests' \"T (Estimate ConfInt Double)\" (T :: T (Estimate ConfInt   Double))\n  , serializationTests (T :: T (LowerLimit Double))\n  , serializationTests (T :: T (UpperLimit Double))\n    -- Distributions\n  , serializationTests (T :: T BetaDistribution        )\n  , serializationTests (T :: T CauchyDistribution      )\n  , serializationTests (T :: T ChiSquared              )\n  , serializationTests (T :: T ExponentialDistribution )\n  , serializationTests (T :: T GammaDistribution       )\n  , serializationTests (T :: T LaplaceDistribution     )\n  , serializationTests (T :: T NormalDistribution      )\n  , serializationTests (T :: T UniformDistribution     )\n  , serializationTests (T :: T StudentT                )\n  , serializationTests (T :: T (LinearTransform NormalDistribution))\n  , serializationTests (T :: T FDistribution           )\n  , serializationTests (T :: T BinomialDistribution       )\n  , serializationTests (T :: T GeometricDistribution      )\n  , serializationTests (T :: T GeometricDistribution0     )\n  , serializationTests (T :: T HypergeometricDistribution )\n  , serializationTests (T :: T PoissonDistribution        )\n  ]\n\n\nserializationTests\n  :: (Eq a, Typeable a, Binary a, Show a, Read a, ToJSON a, FromJSON a, Arbitrary a)\n  => T a -> TestTree\nserializationTests t = serializationTests' (typeName t) t\n\n-- Not all types are Typeable, unfortunately\nserializationTests'\n  :: (Eq a, Binary a, Show a, Read a, ToJSON a, FromJSON a, Arbitrary a)\n  => String -> T a -> TestTree\nserializationTests' name t = testGroup (\"Tests for: \" ++ name)\n  [ testProperty \"show/read\" (p_showRead t)\n  , testProperty \"binary\"    (p_binary   t)\n  , testProperty \"aeson\"     (p_aeson    t)\n  ]\n\n\n\np_binary :: (Eq a, Binary a) => T a -> a -> Bool\np_binary _ a = a == (decode . encode) a\n\np_showRead :: (Eq a, Read a, Show a) => T a -> a -> Bool\np_showRead _ a = a == (read . show) a\n\np_aeson :: (Eq a, ToJSON a, FromJSON a) => T a -> a -> Bool\np_aeson _ a = Data.Aeson.Success a == (fromJSON . toJSON) a\n", "meta": {"hexsha": "410b9cd0ede88fa25425e4bd7f0f21553b973768", "size": 3781, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/Serialization.hs", "max_stars_repo_name": "haskell/statistics", "max_stars_repo_head_hexsha": "a2aa25181e50cd63db4a785c20c973a3c4dd5dac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-11T23:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:33:10.000Z", "max_issues_repo_path": "tests/Tests/Serialization.hs", "max_issues_repo_name": "haskell/statistics", "max_issues_repo_head_hexsha": "a2aa25181e50cd63db4a785c20c973a3c4dd5dac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-26T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:27:01.000Z", "max_forks_repo_path": "tests/Tests/Serialization.hs", "max_forks_repo_name": "haskell/statistics", "max_forks_repo_head_hexsha": "a2aa25181e50cd63db4a785c20c973a3c4dd5dac", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-12-14T09:59:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:04:37.000Z", "avg_line_length": 41.5494505495, "max_line_length": 92, "alphanum_fraction": 0.708013753, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4396475477652647}}
{"text": "{-# OPTIONS_GHC -Wall #-}\n\n-- | 'Distribution' avoids a name clash with 'Data.Distributive'\nmodule Plankton.Distribution\n  ( Distribution\n  ) where\n\nimport Data.Complex (Complex(..))\nimport Plankton.Additive\nimport Plankton.Multiplicative\nimport Protolude (Bool(..), Double, Float, Int, Integer)\n\n-- | Distribution (and annihilation) laws\n--\n-- > a * (b + c) == a * b + a * c\n-- > (a + b) * c == a * c + b * c\n-- > a * zero == zero\n-- > zero * a == zero\nclass (Additive a, MultiplicativeMagma a) =>\n      Distribution a\n\ninstance Distribution Double\n\ninstance Distribution Float\n\ninstance Distribution Int\n\ninstance Distribution Integer\n\ninstance Distribution Bool\n\ninstance (AdditiveGroup a, Distribution a) => Distribution (Complex a)\n", "meta": {"hexsha": "6e0112ef1e19686bc07dee45727c1b9ac3107a04", "size": 737, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Plankton/Distribution.hs", "max_stars_repo_name": "chessai/plankton", "max_stars_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T05:38:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:38:15.000Z", "max_issues_repo_path": "src/Plankton/Distribution.hs", "max_issues_repo_name": "chessai/plankton", "max_issues_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Plankton/Distribution.hs", "max_forks_repo_name": "chessai/plankton", "max_forks_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3333333333, "max_line_length": 70, "alphanum_fraction": 0.6919945726, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4396061168065352}}
{"text": "module Ray where\n\nimport Numeric.Vector\nimport Numeric.Scalar\nimport Types\nimport Object.Tri (asList)\n\ncreateHit :: Object -> Tri -> Ray -> Double -> (Double, Double, Double) -> Vec3d -> RayHit\ncreateHit obj tri ray dist (a, b, c) pos = let abc3 = map (fromScalar . scalar) [a, b, c] :: [Vec3d]\n                                               abc2 = map (fromScalar . scalar) [a, b, c] :: [Vec2d]\n                                               tex = sum $ zipWith (*) abc2 $ map v_getTexCoord $ asList tri\n                                               normal = sum $ zipWith (*) abc3 $ map v_getNormal $ asList tri\n                                               tangent = sum $ zipWith (*) abc3 $ map v_getTangent $ asList tri\n                                               bitangent = tangent \u00d7 normal\n                                               color = sum $ zipWith (*) abc3 $ map v_getColor $ asList tri\n\n                                           in  RayHit { rh_getPos = pos\n                                                      , rh_getRay = ray\n                                                      , rh_getDistance = dist\n                                                      , rh_getTri = tri\n                                                      , rh_getObj = obj\n                                                      , rh_getShader = o_getShader obj\n                                                      , rh_getTexCoord = tex\n                                                      , rh_getNormal = normal\n                                                      , rh_getTangent = tangent\n                                                      , rh_getBitangent = bitangent\n                                                      , rh_getColor = color\n                                                      }\n", "meta": {"hexsha": "9692a60aa4f2754aa97a04198f8ede67cfe2d5c1", "size": 1816, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Ray.hs", "max_stars_repo_name": "craigmc08/haskell-raytracer", "max_stars_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Ray.hs", "max_issues_repo_name": "craigmc08/haskell-raytracer", "max_issues_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Ray.hs", "max_forks_repo_name": "craigmc08/haskell-raytracer", "max_forks_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.6206896552, "max_line_length": 111, "alphanum_fraction": 0.3419603524, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.43939664239833065}}
{"text": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n\n\nmodule Cas.Misc where\n\nimport           PreludeCustom\nimport           Data.Function\nimport           Data.List hiding (intersect)\nimport           Debug.Trace\nimport           Data.Foldable\nimport           Data.Ratio\nimport           Data.Complex.Generic\n\nfoldlFst :: (a -> b -> a) -> a -> [(b,c)] -> (a,c)\nfoldlFst f a =  bimap (foldl f a) head . unzip\n\ndebug :: (Show a) => String -> a -> a\ndebug s = (\\x -> trace (s <> \" \" <> show x ) x )\n\n\nshowQ = (==1) . denominator ?>>> show . numerator\n                             ||> ((<>) <$> (<>\"/\") . show . numerator\n                                       <*> show . denominator)\n\n\nshowImg y = bool \"\" (showQ y) (y/=1) <> \"i\"\n\nshowF (x':+y') = case (x',y') of\n               (0,0) -> \"0\"\n               (x,0) -> showQ x\n               (0,y) -> showImg y\n               (x,y) -> \"(\" <> showQ x <> \"+\" <> showImg y <> \")\"\n\n\n\n-- data QWrapperForShow = QWrapperForShow { unwrapQ :: Rational }\n\n-- instance Show QWrapperForShow where\n--     show (QWrapperForShow q) = showQ q\n\n-- showF :: Complex Rational -> String\n-- showF (x:+y)= show $ (QWrapperForShow x) :+ (QWrapperForShow y)\n--\n\nwrap :: String -> String\nwrap s = \"(\" <> s <> \")\"\n\n\nwrapshow :: (Show a) => a -> String\nwrapshow = wrap . show\n\nstableGroupOn :: (Ord b) => (a -> b) -> [a] -> [[a]]\nstableGroupOn f = fmap fromJust\n                . (fmap . flip lookup\n                    <$> fmap (f . head &&& id)\n                      . groupBy ((==) `on` f)\n                      . sortBy  (comparing f)\n                    <*> nub\n                      . fmap f )\n\nstableGroup :: (Ord a) => [a] -> [[a]]\nstableGroup = stableGroupOn id\n", "meta": {"hexsha": "addcab2166285e8722045e4da1c9326d4d2f0933", "size": 1712, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cas/Misc.hs", "max_stars_repo_name": "vcanadi/cas", "max_stars_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-20T22:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-20T22:42:53.000Z", "max_issues_repo_path": "src/Cas/Misc.hs", "max_issues_repo_name": "vcanadi/cas", "max_issues_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cas/Misc.hs", "max_forks_repo_name": "vcanadi/cas", "max_forks_repo_head_hexsha": "7680b3aacb1ee2816ec0f5775b9c2f1c73e3dfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.75, "max_line_length": 69, "alphanum_fraction": 0.4719626168, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.4393356577280819}}
{"text": "{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables, NoMonomorphismRestriction, BangPatterns, FlexibleInstances, ViewPatterns #-}\nmodule Math.Probably.RandIO where\n\nimport qualified Math.Probably.PDF as PDF\nimport Math.Probably.Sampler\nimport Math.Probably.MCMC hiding (traceIt)\nimport Math.Probably.StochFun\nimport Math.Probably.FoldingStats\nimport Math.Probably.Sampler\nimport qualified Control.Monad.State.Strict as S\nimport System.IO\nimport qualified Data.Packed.Matrix as L\nimport Control.Monad.Trans\nimport Control.Monad\nimport Data.IORef\nimport qualified Numeric.LinearAlgebra as L\nimport Math.Probably.NelderMead\n\nimport qualified Data.Vector.Storable as V\nimport Statistics.Autocorrelation\n\nimport Text.Printf\nimport Data.List\nimport Control.Monad.Par\n\nimport Debug.Trace\n\ntype RIO = S.StateT Seed IO\n\nrunRIO :: RIO a -> IO a\nrunRIO mx = do\n  sd <- getSeedIO\n  S.evalStateT mx sd\n  \nio :: IO a -> RIO a\nio = liftIO\n\nsample :: Sampler a -> RIO a\nsample (Sam f) = do sd <- S.get\n                    let (x,sd') = f sd\n                    S.put sd'\n                    return x\n\nupdate :: IORef a -> (a->Sampler a) -> RIO ()\nupdate rf sm = do\n  x <- io $ readIORef rf\n  newx <- sample $ sm x\n  io $ writeIORef rf newx\n\nrunChainRIO :: Int -> (a->String) -> a -> (a->Sampler a) -> RIO [a]\nrunChainRIO n showit init sam = do\n    seed <- S.get\n    (nseed, xs) <- io $ go n seed init []\n    S.put nseed\n    return xs\n     where go 0 s x xs = return (s, xs)\n           go nn s x xs = do let (!xx, !ns) = unSam (sam x) s\n                             when(nn `rem` chsz==0) $ \n                                 putStrLn $ show (((n-nn) `div` chsz)*2)++\"%: \" ++showit xx\n                             go (nn-1) ns xx $ xx:xs\n           chsz = n `div` 50\n\ndata AdaMetRunPars = AdaMetRunPars \n     { nmTol :: Double,\n       displayIt :: Maybe (L.Vector Double -> String),\n       verboseNM :: Bool,\n       amnsam :: Int,\n       initw:: Int -> Double,\n       minNM ::Int,\n       maxNM ::Int }\n\ndefaultAM = AdaMetRunPars 0.5 Nothing False 1000 (const 0.02) 100 1000\n\ntraceit s x = trace (s++show x) x\n\n\ngetInitialCov :: Sampler (L.Vector Double)\n              -> (L.Vector Double -> Double) \n              -> RIO (Double, L.Vector Double, L.Matrix Double)\ngetInitialCov inisam posteriorL = go 500 where \n  pdfv v = posteriorL v\n  go n | n < 1 \n         = error $ \"can't find suitable initial conditions. Try a narrower prior\"\n       | otherwise =  do\n    initialv <- sample inisam\n    let iniSimplex = genInitial (negate . pdfv) [] (const 0.02)  $ initialv\n    if any (nanOrInf . snd) iniSimplex\n       then go (n-1)\n       else runNM n iniSimplex\n  runNM n iniSimplex = do  \n    let finalSim = goNm (negate . pdfv) [] 0.01 100 1000 iniSimplex \n        (maxPost,hess) = hessianFromSimplex (negate . pdfv) [] [] finalSim \n    if any nanOrInf $ concat $ L.toLists hess\n       then go (n-10)\n       else getCov finalSim hess\n  getCov finalSim hess = do\n    let cor = case L.mbCholSH $ hess of \n            Just _ -> L.inv hess\n            Nothing -> case L.mbCholSH $ PDF.posdefify hess of\n                         Just _ -> L.inv $ PDF.posdefify hess\n                         Nothing -> L.diag $ L.mapVector (recip) \n                                           $ L.takeDiag $ hess\n        initV = fst $ head $ finalSim\n    return (negate $ snd $ head $ finalSim, \n            initV, cor)\n\nlaplaceApprox :: AdaMetRunPars -> PDF.PDF (L.Vector Double) -> [Int] -> [((Int, Int), Double)] \n              -> L.Vector Double -> (L.Vector Double, Maybe (L.Matrix Double), Simplex)\nlaplaceApprox (AdaMetRunPars nmtol dispit verbnm nsam initw minNM maxNM) pdf isInt fixed init =\n     let iniSim = genInitial (negate . pdf) isInt initw $ init\n         finalSim = {-if verbnm then goNmVerbose (negate . pdf) isInt nmtol minNM maxNM iniSim \n                              else -} goNm (negate . pdf) isInt nmtol minNM maxNM iniSim \n\n         (maxPost,hess) = hessianFromSimplex (negate . pdf) isInt fixed finalSim \n--     io $ print maxPost\n         mbcor = case L.mbCholSH $ hess of \n                   Just _ -> Just $ L.inv hess\n                   Nothing -> case L.mbCholSH $ PDF.posdefify hess of\n                                 Just _ -> Just $ L.inv $ PDF.posdefify hess\n                                 Nothing -> Just $ L.diag $ L.mapVector (recip) $ L.takeDiag $ hess\n         initV = fst $ head $ finalSim\n     in (initV, mbcor, finalSim)\n\nnmAdaMet :: AdaMetRunPars -> PDF.PDF (L.Vector Double) -> [Int] -> [((Int, Int), Double)] \n            -> L.Vector Double -> RIO [L.Vector Double]\nnmAdaMet (AdaMetRunPars nmtol dispit verbnm nsam initw minNM maxNM ) pdf isInt fixed init = do\n     let iniSim = genInitial (negate . pdf) isInt initw $ init\n     io $ print iniSim\n     let finalSim =  goNm (negate . pdf) isInt nmtol minNM maxNM iniSim\n     io $ print finalSim\n     let (maxPost,hess) = hessianFromSimplex (negate . pdf) isInt fixed finalSim \n--     io $ print maxPost\n     io $ putStrLn \"hessian\"\n     io $ print hess\n\n     let mbcor = case L.mbCholSH hess of \n                   Just _ -> Just $ L.inv hess\n                   Nothing -> Nothing  \n     io $ putStrLn \"maybe inverse hess\"                                          \n     io $ print mbcor\n     let initV = centroid finalSim\n     let mbcorChol = mbcor >>= L.mbCholSH \n     case (mbcor, mbcorChol) of\n       (Just cor, Just _) ->  do --io $ putStrLn \"chol cor\"\n                                 --io $ print $ L.inv cor\n                                 let ampar = AMPar initV initV cor 2.4 (pdf initV) 0 0\n                                 runAdaMetRIO nsam True ampar pdf\n       _         -> do iniampar <- sample $ initialAdaMet 100 (const 5e-3) pdf initV\n                       froampar <- runAndDiscard (nsam*2) (show . ampPar) iniampar $ adaMet False pdf\n                       runAdaMetRIO (nsam*2) True froampar pdf\n      \n                                      \n\nrunAdaMetRIO :: Int -> Bool -> AMPar -> PDF.PDF (L.Vector Double) -> RIO [L.Vector Double]\nrunAdaMetRIO n freeze ampar pdf = do\n    seed <- S.get\n    (nseed, xs) <- io $ go n seed ampar []\n    S.put nseed\n    return xs\n     where go 0 s amp vs = do print $ amp\n                              return (s, reverse vs)\n           go nn s amp vs = do let (!ampn, !ns) = unSam (adaMet freeze pdf amp) s\n                               when(nn `rem` chsz==0) $ \n                                   putStrLn $ show (((n-nn) `div` chsz)*2)++\"%: \" ++showV (ampPar ampn) ++\" LH=\"++printf \"%.3g\" (pdf (ampPar ampn)) ++ \" accept=\"++acceptS ampn\n                               go (nn-1) ns (ampn) $ (ampPar ampn):vs\n           chsz = n `div` 50\n\nrunAdaMetRioESS :: Int -> Bool -> AMPar -> PDF.PDF (L.Vector Double) -> RIO [L.Vector Double]\nrunAdaMetRioESS want_ess freeze ampar pdf = do\n    seed <- S.get\n    (nseed, xs, amp) <- io $ go 200 seed ampar []\n    S.put nseed\n    return xs\n     where go (0::Int) s amp vs = goChunks s amp vs\n           go nn s amp vs = do let (!ampn, !ns) = unSam (adaMet freeze pdf amp) s\n                               go (nn-1) ns (ampn) $ (ampPar ampn):vs\n \n           goChunks s amp [] = do \n              (nseed, xs, namp) <- go 200 s amp []\n              goChunks nseed namp xs\n           goChunks s amp xs = do\n              let have_ess = min (realToFrac $ count_accept amp) \n                                 $ calcESS  want_ess xs \n                  drawn = length xs\n              putStrLn $ show $ ampPar amp\n              putStrLn $ \"ESS=\"++show have_ess++\" from \"++show drawn\n                       ++\" drawn accept ratio=\"++acceptS amp\n              if have_ess > realToFrac want_ess\n                 then return (s, xs, amp)\n                 else do\n                   let need_ess = min (realToFrac $ want_ess `div` 5) \n                                    $ max 1 \n                                    $ realToFrac want_ess - have_ess\n                       samples_per_es = realToFrac drawn/have_ess\n                       to_do = max 50 $ min 2000 $ samples_per_es * need_ess\n                   putStrLn $ \"now doing \"++ show to_do\n                   go (round to_do) s amp xs \n\nrunFixMetRioESS :: Double -> Int -> AMPar -> PDF.PDF (L.Vector Double) -> RIO [L.Vector Double]\nrunFixMetRioESS factor want_ess ampar pdf = do\n    seed <- S.get\n    (nseed, xs, amp) <- io $ go 200 seed ampar []\n    S.put nseed\n    return xs\n     where go (0::Int) s amp vs = goChunks s amp vs\n           go nn s amp vs = do let (!ampn, !ns) = unSam (fixedMet factor pdf amp) s\n                               go (nn-1) ns (ampn) $ (ampPar ampn):vs\n \n           goChunks s amp [] = do \n              (nseed, xs, namp) <- go 200 s amp []\n              goChunks nseed namp xs\n           goChunks s amp xs = do\n              let have_ess = min (realToFrac $ count_accept amp) \n                             $ calcESS want_ess xs\n                  drawn = length xs\n              --putStrLn $ show $ ampPar amp\n              putStrLn $ \"ESS=\"++show have_ess++\" from \"++show drawn\n                       ++\" drawn accept ratio=\"++acceptS amp\n              if have_ess > realToFrac want_ess\n                 then return (s, xs, amp)\n                 else do\n                   let need_ess = min (realToFrac $ want_ess `div` 5) \n                                    $ max 1 \n                                    $ realToFrac want_ess - have_ess\n                       samples_per_es = realToFrac drawn/have_ess\n                       to_do = max 50 $ min 2000 $ samples_per_es * need_ess * 1.2\n                   putStrLn $ \"now doing \"++ show to_do\n                   go (round to_do) s amp xs \n\nrunFixMetRioToFile :: Int -> Int -> String -> Double -> AMPar \n                      -> PDF.PDF (L.Vector Double) -> RIO ()\nrunFixMetRioToFile samples thinn fileNm factor ampar pdf = do\n    seed <- S.get\n    h <- io $ openFile (fileNm) WriteMode \n    nseed <- io $ go h samples seed ampar []\n    S.put nseed\n    return ()\n     where go h (0::Int) s amp vs = return s\n           go h nn s amp vs = do let (!ampn, !ns) = unSam (fixedMet factor pdf amp) s\n                                 when (nn `rem` thinn == 0) $ do\n                                     hPutStrLn h $ show $ L.toList $ ampPar ampn\n                                 go h (nn-1) ns (ampn) $ (ampPar ampn):vs\n\n\nrunFixMetRio :: Double -> Int -> AMPar -> PDF.PDF (L.Vector Double) -> RIO [L.Vector Double]\nrunFixMetRio factor samples ampar pdf = do\n    seed <- S.get\n    (nseed, xs, amp) <- io $ go samples seed ampar []\n    S.put nseed\n    return xs\n     where go (0::Int) s amp vs = return (s,vs, amp)\n           go nn s amp vs = do let (!ampn, !ns) = unSam (fixedMet factor pdf amp) s\n                               go (nn-1) ns (ampn) $ (ampPar ampn):vs\n \nrunFixMetRioBurn :: Double -> Int -> AMPar -> PDF.PDF (L.Vector Double) -> RIO AMPar\nrunFixMetRioBurn factor burn ampar pdf = do\n    seed <- S.get\n    (nseed, amp) <- io $ go burn seed ampar\n    S.put nseed\n    return amp\n     where go (0::Int) s amp  = return (s,amp)\n           go nn s amp  = do let (!ampn, !ns) = unSam (fixedMet factor pdf amp) s\n                             go (nn-1) ns (ampn) \n \ntraceHead vs = trace (\"head=\"++(show $ vs L.@> 0)) vs  \n\nmost_es_per_s = 10\n\ncalcESS :: Int -> [L.Vector Double] -> Double\ncalcESS  want_ess mcmcOut \n   | L.dim (head mcmcOut) <  want_ess * most_es_per_s * 2\n      = calcESSprim mcmcOut\n   | otherwise \n      = let thinFactor = L.dim (head mcmcOut) `div` ( want_ess * most_es_per_s)\n        in calcESSprim $ map (thinV $ thinFactor - 1) mcmcOut\n\nthinV 0   =  id\nthinV thin = V.ifilter $ \\ix _ -> ix `mod` thin == 0\n\n--thinV thin v = V.generate ((V.length v `div` (thin+1))+1) $ \\i -> (V.!) v  (i*(thin))\n\n\ncalcESSprim ::  [L.Vector Double] -> Double\ncalcESSprim mcmcOut = \n  let ndims = L.dim $ head mcmcOut\n      len = realToFrac (length mcmcOut) \n      acfs = mapP (\\i->  V.sum $ V.takeWhile (>0.1) $ fst3 $ autocorrelation $ V.fromList $ map (L.@>i) mcmcOut) [0..ndims-1]\n      ess = foldl1' min $ flip map acfs $ \\acfsum-> (len/(1+2*acfsum)) -- realToFrac samples/(1+2*acfsum)\n  in ess\n\nmapP :: NFData b => (a-> b) -> [a] -> [b]\nmapP f xs = runPar $ \n  forM xs (spawn . return . f) >>= mapM get\n\nrunAdaMetRIOtoFile :: Int -> Int -> String -> Bool -> AMPar -> PDF.PDF (L.Vector Double) -> RIO ()\nrunAdaMetRIOtoFile n thinn fileNm freeze ampar pdf = do\n    seed <- S.get\n    h <- io $ openFile (fileNm) WriteMode \n    (nseed) <- io $ go h n seed ampar\n    S.put nseed\n    return ()\n    --return xs\n     where go h 0 s amp  = do print $ amp\n                              return s --  return (s, reverse vs)\n           go h nn s amp = do let (!ampn, !ns) = unSam (adaMet freeze pdf amp) s\n                              when(nn `rem` chsz==0) $ \n                                   putStrLn $ show (((n-nn) `div` chsz)*2)++\"%: \" ++\n                                              showV (ampPar ampn) ++\" LH=\"++\n                                              printf \"%.3g\" (pdf (ampPar ampn)) ++ \n                                              \" accept=\"++acceptS ampn\n                              when (nn `rem` thinn == 0) $ do\n                                   hPutStrLn h $ show $ L.toList $ ampPar ampn\n                              go h (nn-1) ns (ampn) \n           chsz = n `div` 50\n\n\nshowV v = \"<\"++intercalate \",\" (map (printf \"%.4g\") $ L.toList v)++\">\"\nacceptS ampar  | count ampar == 0 = \"0/0\"\n               | otherwise = printf \"%.3g\" (rate::Double) ++ \" (\"++show yes++\"/\"++show total++\")\"where\n   rate = realToFrac (yes) / realToFrac (total)\n   yes = count_accept ampar\n   total = count ampar\n\nampParRate ampar  | count ampar == 0 = 0\n                  | otherwise = rate where\n   rate = realToFrac (yes) / realToFrac (total)\n   yes = count_accept ampar\n   total = count ampar\n\n\nrunAdaMetRIOInterleaveInitial :: Int -> Bool -> L.Matrix Double -> AMPar -> PDF.PDF (L.Vector Double) -> RIO [L.Vector Double]\nrunAdaMetRIOInterleaveInitial n freeze cov ampar pdf = do\n    seed <- S.get\n    (nseed, xs) <- io $ go n seed ampar []\n    S.put nseed\n    return xs\n     where go 0 s amp vs = do print $ amp\n                              return (s, vs)\n           go nn s amp vs = do let (!ampn, !ns) = unSam (adaMetInterleaveInitial freeze cov pdf amp) s\n                               when(nn `rem` chsz==0) $ \n                                   putStrLn $ show (((n-nn) `div` chsz)*2)++\"%: \" ++show (ampPar ampn)-- ++\" LH=\"++show (pdf (ampPar ampn))\n                               go (nn-1) ns ampn $ (ampPar ampn):vs\n           chsz = n `div` 50\n    \n\nrunChainStat :: Int -> (Fold a b) -> a -> (a->Sampler a) -> RIO b\nrunChainStat n (F acc fldini k _) ini sam = do\n    seed <- S.get\n    let (nseed, stat) = go n seed fldini ini \n    S.put nseed\n    return stat\n     where go 0 s y x = (s, k y)\n           go nn s y x = let (xx, ns) = unSam (sam x) s\n                         in go (nn-1) ns (acc y xx) xx\n\n\nrunAndWriteTo :: String -> Int -> (a -> String) -> a -> (a->Sampler a) -> RIO a\nrunAndWriteTo fnm n showit x sam = do\n    h <- io $ openFile fnm WriteMode\n    seed <- S.get\n    (y,nseed) <- io $ runChainPrim h n showit seed x sam\n    io $ hClose h\n    S.put nseed\n    return y \n\nrunChainPrim :: Handle -> Int -> (a -> String) -> Seed -> a -> (a->Sampler a) -> IO (a, Seed)\nrunChainPrim h n showit seed x sam = go n seed x\n   where go 0 s x = return (x,s)\n         go nn s x = do\n            let (y, ns) = unSam (sam x) s\n            hPutStrLn h $ showit y\n            when(nn `rem` chsz==0) $ \n              putStrLn $ show (((n-nn) `div` chsz)*2)++\"%: \"++showit y\n            go (nn-1) ns y \n         chsz = n `div` 50\n\nrunOnce :: a -> (a->Sampler a) -> RIO a\nrunOnce init sam = runAndDiscardPrim 1 init sam\n\n\nrunAndDiscard :: Int -> (a->String) -> a -> (a->Sampler a) -> RIO a\n--runAndDiscard = runAndDiscardPrim\nrunAndDiscard 0 _ x _ = return x\nrunAndDiscard n showit x sam = do\n    go 50 x\n where chunksz = n `div` 50\n       go 0 x = io (putStr \"\\n\") >> return x\n       go n x = do\n          x' <- runAndDiscardPrim chunksz x sam\n          io $ putStrLn $ show ((50-n)*2+2)++\"%: \"++showit x'\n          go (n-1) x' \n\nrunMeanVar :: Floating b => Int -> (a->b) -> a -> (a->Sampler a) -> RIO (b,b)\nrunMeanVar n conv init sam = do\n   xs <- sample $ runChainS n init sam\n   return $ both meanF stdDevF `runStat` map conv xs\n   \n\n\nrunAndDiscardPrim :: Int -> a -> (a->Sampler a) -> RIO a\nrunAndDiscardPrim n init sam = do\n   seed <- S.get\n   let (x,nseed) = runPrim seed n init sam\n   S.put nseed\n   return x\n\nrunPrim :: Seed -> Int -> a -> (a->Sampler a) -> (a,Seed)\nrunPrim s 0 x _ = (x,s)\nrunPrim s n x sam = let (x', s') = unSam (sam x) s\n                    in runPrim s' (n-1) x' sam\n\nmetSample2P :: Show a => String -> (Double -> a -> a -> Sampler a) \n               -> PDF.PDF (a,b) -> (Param a,b) -> Sampler (Param a)\nmetSample2P st prop p (par@(Param j t tt _ curw ada ini xi),y) \n    = let accept xi pi pstar | notNanInf2 pi pstar =  min 1 $ exp (pstar - pi)\n                             | otherwise = cond [(nanOrInf pi && nanOrInf pstar, \n                                                        error $ \"metropolisLnP \"++st++\" pi pi pstar :\"++\n                                                                show (pi,pstar)++\"\\n\"++\n                                                                show xi),\n                                                 (nanOrInf pstar, -1), -- never accept\n                                                 (nanOrInf pi, 2)] $ error \"metropolisLn: the impossible happend\"\n      in  do\n        let (nextw, nj, nt) = calcNextW ada curw j t tt\n        u <-  unitSample \n        xstar <- prop nextw ini xi\n        let pstar = p (xstar,y) \n        let pi = p (xi,y) \n        return $ if u < accept par pi pstar\n                      then Param (nj+1) (nt+1) (tt+1) pstar nextw ada ini xstar\n                      else Param nj (nt+1) (tt+1) pi nextw ada ini xi\nmetSample2PC :: Show a => String -> (Double -> a -> a -> Sampler a) \n               -> PDF.PDF (a,b) -> (Param a,b) -> Sampler (Param a)\nmetSample2PC st prop p (par@(Param j t tt lhi curw ada ini xi),y) \n    = let accept xi pi pstar | notNanInf2 pi pstar =  min 1 $ exp (pstar - pi)\n                             | otherwise = cond [(nanOrInf pi && nanOrInf pstar, \n                                                        error $ \"metropolisLnP \"++st++\" pi pi pstar :\"++\n                                                                show (pi,pstar)++\"\\n\"++\n                                                                show xi),\n                                                 (nanOrInf pstar, -1), -- never accept\n                                                 (nanOrInf pi, 2)] $ error \"metropolisLn: the impossible happend\"\n      in  do\n        let (nextw, nj, nt) = calcNextW ada curw j t tt\n        u <-  unitSample \n        xstar <- prop nextw ini xi\n        let pstar = p (xstar,y) \n        let pi = if notNanInf lhi then lhi else p (xi,y)\n        return $ if u < accept par pi pstar\n                      then Param (nj+1) (nt+1) (tt+1) pstar nextw ada ini xstar\n                      else Param nj (nt+1) (tt+1) pi nextw ada ini xi\n\n\n\nbestOfTwoCov inisam posterior = do\n   set1@(postval1,_,_) <- getInitialCov inisam posterior\n   set2@(postval2,_,_) <- getInitialCov inisam posterior\n   if postval1>postval2 -- I THINK\n      then return set1\n      else return set2\n\n\nmkAMPar init cov initp = AMPar init init cov 2.4 initp 10 5\n\ninitAdaMetFromCov nsam pdf initv retries cov = do\n  --lift $ putStrLn $ \"starting from existing cov; try number \"++ show retries\n  iniampar <- sample $ initialAdaMetFromCov nsam (pdf) initv\n                                                 (PDF.posdefify $ cov) \n  --lift $ print iniampar\n  let rate = realToFrac (count_accept iniampar) / realToFrac nsam\n  case () of\n     _ | retries > 8 -> do lift $ putStrLn \"initals ok.\" \n                           return iniampar\n     _ | rate > 0.5 -> initAdaMetFromCov nsam pdf initv (retries +1) $ L.scale 2 cov \n     _ | rate > 0.40 -> initAdaMetFromCov nsam pdf initv (retries +1) $ L.scale 1.5 cov \n     _ | rate < 0.025 ->  initAdaMetFromCov nsam pdf initv (retries +1) $ L.scale 0.1 cov \n     _ | rate < 0.04 ->  initAdaMetFromCov nsam pdf initv (retries +1) $ L.scale 0.2 cov \n     _ | rate < 0.12 ->  initAdaMetFromCov nsam pdf initv (retries +1) $ L.scale 0.3 cov \n     _ | rate < 0.16 ->  initAdaMetFromCov nsam pdf initv (retries +1) $ L.scale 0.5 cov \n     _ | rate < 0.20 ->  initAdaMetFromCov nsam pdf initv (retries +1) $ L.scale 0.8 cov \n     _ | otherwise -> do lift $ putStrLn \"initals ok.\" \n                         return iniampar  \n", "meta": {"hexsha": "1815151e0e314a413e777a836a844f98dc48046b", "size": 20636, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/Probably/RandIO.hs", "max_stars_repo_name": "glutamate/probably", "max_stars_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:19:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:44.000Z", "max_issues_repo_path": "Math/Probably/RandIO.hs", "max_issues_repo_name": "glutamate/probably", "max_issues_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/Probably/RandIO.hs", "max_forks_repo_name": "glutamate/probably", "max_forks_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9022869023, "max_line_length": 175, "alphanum_fraction": 0.526167862, "num_tokens": 6151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021787, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4391257674460709}}
{"text": "module Read (\n  readExpr,\n  readExprList\n) where\n\nimport           Control.Monad\nimport           Control.Monad.Error\nimport           Data.Complex\nimport           Data.Ratio\nimport           Numeric\nimport           Text.ParserCombinators.Parsec\nimport           Types\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\nescapedChar :: Parser Char\nescapedChar = char '\\\\' >> oneOf \"\\\\\\\"nrt\"\n\nparseString :: Parser LispVal\nparseString = do\n  char '\"'\n  x <- many $ escapedChar <|> noneOf \"\\\"\\\\\"\n  char '\"'\n  return $ String x\n\nparseBool :: Parser LispVal\nparseBool = do\n  string \"#\"\n  x <- oneOf \"tf\"\n  return $ case x of\n    't' -> Bool True\n    'f' -> Bool False\n\nparseAtom :: Parser LispVal\nparseAtom = do\n  first <- letter <|> symbol\n  rest <- many (letter <|> digit <|> symbol)\n  return $ Atom $ first:rest\n\nparseHex :: Parser LispVal\nparseHex = do\n  try $ string \"#x\"\n  x <- many1 hexDigit\n  return $ Number $ fst $ head $ readHex x\n\nparseDigits :: Parser LispVal\nparseDigits = do\n  try $ char '#'\n  second <- oneOf \"odb\"\n  rest <- many1 digit\n  return $ Number $ case second of\n    'o' -> fst $ head $ readOct rest\n    'd' -> read rest\n    'b' -> parseBin 0 rest\n\nparseBin :: Integer -> String -> Integer\nparseBin acc \"\"     = acc\nparseBin acc (x:xs) = parseBin (acc * 2 + (if x == '0' then 0 else 1)) xs\n\nparseDecimal :: Parser LispVal\nparseDecimal = (Number . read) <$> many1 digit\n\nparseNumber :: Parser LispVal\nparseNumber = try $ parseHex <|> parseDecimal <|> parseDigits\n-- try\u3092\u5916\u3059\u3068\u3001 #t \u3092\u89e3\u91c8\u3067\u304d\u305a\u306b\u843d\u3061\u308b\u306e\u3067\u6ce8\u610f\n\nparseCharacter :: Parser LispVal\nparseCharacter = do\n  try $ string \"#\\\\\"\n  value <- try (string \"newline\" <|> string \"space\")\n    <|> do\n      x <- anyChar\n      notFollowedBy alphaNum\n      return [x]\n  return $ Character $ case value of\n    \"newline\" -> '\\n'\n    \"space\"   -> ' '\n    _         -> head value\n\nparseFloat :: Parser LispVal\nparseFloat = do\n  x <- many1 digit\n  char '.'\n  y <- many1 digit\n  return $ Float $ fst . head $ readFloat (x ++ \".\" ++ y)\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 <|> parseDecimal\n  char '+'\n  y <- try parseFloat <|> parseDecimal\n  char 'i'\n  return $ Complex (toDouble x :+ toDouble y)\n\ntoDouble :: LispVal -> Double\ntoDouble(Float f)  = f\ntoDouble(Number n) = fromIntegral n\n\nparseList ::Parser LispVal\nparseList = List <$> sepBy parseExpr spaces\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n  head <- endBy parseExpr spaces\n  tail <- char '.' >> spaces >> parseExpr\n  return $ DottedList head tail\n\nparseQuoted :: Parser LispVal\nparseQuoted = do\n  char '\\''\n  x <- parseExpr\n  return $ List [Atom \"quote\", x]\n\nparseExpr :: Parser LispVal\nparseExpr = parseAtom\n  <|> parseString\n  <|> try parseComplex\n  <|> try parseFloat\n  <|> try parseRatio\n  <|> try parseNumber\n  <|> parseQuoted\n  <|> do\n    char '('\n    x <- try parseList <|> parseDottedList\n    char ')'\n    return x\n  <|> try parseBool\n  <|> try parseCharacter\n\nreadOrThrow :: Parser a -> String -> ThrowsError a\nreadOrThrow parser input = case parse parser \"lisp\" input of\n  Left err  -> throwError $ Parser err\n  Right val -> return val\n\nreadExpr :: String -> ThrowsError LispVal\nreadExpr = readOrThrow parseExpr\n\nreadExprList :: String -> ThrowsError [LispVal]\nreadExprList = readOrThrow (endBy parseExpr spaces)\n", "meta": {"hexsha": "8b0d572ba0d90ec8d9e6a2bc15bc54f3468ce037", "size": 3415, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Read.hs", "max_stars_repo_name": "fand/wyas48-stack", "max_stars_repo_head_hexsha": "256ef168c0914aa8d09e85a9533fc8f8347e48ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Read.hs", "max_issues_repo_name": "fand/wyas48-stack", "max_issues_repo_head_hexsha": "256ef168c0914aa8d09e85a9533fc8f8347e48ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Read.hs", "max_forks_repo_name": "fand/wyas48-stack", "max_forks_repo_head_hexsha": "256ef168c0914aa8d09e85a9533fc8f8347e48ca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0743243243, "max_line_length": 73, "alphanum_fraction": 0.6380673499, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4387271747454298}}
{"text": "{-|\nModule      : GMM\nDescription : Definition of the Gaussian Mixture Model and Metropolis hatings sampler.\nCopyright   : (c) Julian Kopka Larsen, 2015\nStability   : experimental\n\n\n-}\nmodule GMM (\n    X,\n    getElement\n) where\n\n\nimport GHC.Arr (range)\nimport Data.List (foldl')\nimport Data.Array\nimport System.Random\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Util hiding ((!))\nimport Debug.Trace\n\nimport Distributions -- (lnormalInvWishart, lMixNormWish, delta, Expr)\nimport Partition (Partition, Component, Move, naivefromNk, genMoves, applyMove, group)\n\nimport Math (X)\n\ntype Chain = [Partition]\n\ntype Likelihood = (X -> Double)\n\ntype Proposal = (Move, Double)\n\nprops :: Int -> Int -> Int -> [Proposal]\nprops seed n k = zip moves rand_accepts\n                where rand_accepts = randomRs (0.0,1.0) (mkStdGen seed) :: [Double]\n                      moves = genMoves seed n k\n\nsample :: (Partition -> Move -> Double) -> Partition -> Proposal -> Partition\nsample f prev_state (m, accept_prop)\n    | accept_prop < f prev_state m = new_state -- trace (\"(\" ++ (show $ a!(node m)) ++ \"->\" ++ (show $ comp m) ++   \")\" ++ \"Accepted: \" ++ show (f a m)) b\n    | otherwise                    = prev_state -- trace (\"(\" ++ (show $ a!(node m)) ++ \"->\" ++ (show $ comp m) ++   \")\" ++ \"Rejected: \" ++ show (f a m)) a\n                                    where new_state = applyMove prev_state m\n\ngetElement :: X -> Int -> Int -> Int -> Partition\ngetElement x seed k nSamples = foldl' sampler start $ take nSamples (props seed n k)\n                      where n = length x\n                            start = naivefromNk n k\n                            sampler = sample $ acceptanceRatio dq\n                            dq = dlNormW x\n\nacceptanceRatio :: (Partition -> Partition -> Double) -> Partition -> Move -> Double\nacceptanceRatio dq x m = exp (dq x' x)\n                        where x' = applyMove x m\n\n\n\n\n\n\n", "meta": {"hexsha": "b66d87c9b6c10e0394ea801d4c23e6a104bd3b7b", "size": 1916, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "GMM/src/GMM.hs", "max_stars_repo_name": "juliankopkalarsen/FpStats", "max_stars_repo_head_hexsha": "2a9d1cdec7cc9621da2cc7c9972fbf85a1d2f683", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GMM/src/GMM.hs", "max_issues_repo_name": "juliankopkalarsen/FpStats", "max_issues_repo_head_hexsha": "2a9d1cdec7cc9621da2cc7c9972fbf85a1d2f683", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GMM/src/GMM.hs", "max_forks_repo_name": "juliankopkalarsen/FpStats", "max_forks_repo_head_hexsha": "2a9d1cdec7cc9621da2cc7c9972fbf85a1d2f683", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4098360656, "max_line_length": 155, "alphanum_fraction": 0.5918580376, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4384936793806192}}
{"text": "module CategoricDefinitions where\n\nimport Prelude hiding (id, (.))\nimport qualified Prelude as P\nimport GHC.Exts\nimport Data.Kind (Type)\nimport Data.NumInstances.Tuple\n\nimport Numeric.LinearAlgebra.Array\nimport Numeric.LinearAlgebra.Array.Util\n\n{-\nUnfortunately, there is a known bug which prevents quantifying constraints involving type families.\nhttps://gitlab.haskell.org/ghc/ghc/issues/14860\nThis results in all the functions below having a list of constraints AllAllowed k [...]\n-}\n\n-- Standard haskell way to define a category\nclass Category (k :: Type -> Type -> Type) where\n    type Allowed k a :: Constraint\n    type Allowed k a = ()\n\n    id  :: Allowed k a => a `k` a\n    (.) :: AllAllowed k [a, b, c] => b `k` c -> a `k` b -> a `k` c\n\n-- By monoidal here we mean symmetric monoidal category\nclass Category k => Monoidal (k :: Type -> Type -> Type) where\n    -- unit object in haskell is ()\n    x :: AllAllowed k [a, b, c, d, (a, b), (c, d)]\n      => (a `k` c) -> (b `k` d) -> ((a, b) `k` (c, d))\n    assocL :: AllAllowed k [a, b, c, (a, b), ((a, b), c), (b, c), (a, (b, c))]\n           => ((a, b), c) `k` (a, (b, c))\n    assocR :: AllAllowed k [a, b, c, (a, b), ((a, b), c), (b, c), (a, (b, c))]\n           => (a, (b, c)) `k` ((a, b), c)\n    unitorL :: Allowed k a\n            => ((), a) `k` a\n    unitorL' :: Allowed k a -- inverse of unitorL\n            => a `k` ((), a)\n    -- could also potentially add right unitor and their inverses\n    swap :: AllAllowed k [a, b, (a, b), (b, a)]\n         => (a, b) `k` (b, a)\n\nclass Monoidal k => Cartesian k where\n    type AllowedCar k a :: Constraint\n    type AllowedCar k a = ()\n\n    exl :: AllowedCar k b => (a, b) `k` a\n    exr :: AllowedCar k a => (a, b) `k` b\n    dup :: AllowedCar k a => a `k` (a, a)\n    counit :: AllowedCar k a => a `k` ()\n\nclass Category k => Cocartesian k where\n    type AllowedCoCar k a :: Constraint\n    type AllowedCoCar k a = Allowed k a\n\n    inl :: AllowedCoCar k b => a `k` (a, b)\n    inr :: AllowedCoCar k a => b `k` (a, b)\n    jam :: AllowedCoCar k a => (a, a) `k` a\n    unit :: AllowedCoCar k a => () `k` a\n\n{-\nThis is a hacky way of modelling a weak 2-category which is needed for Para.\nNotice the tick' after class name\n(.*) corresponds to id\n(.-) corresponds to . (sequential comp)\n(.|) corresponds to `x` (parallel comp)\n\nIdeally, we'd like to specify in code that given any symmetric monoidal category C we can construct _another_ symmetric monoidal category called Para(C), but sometimes dreams will have to be dreams.\n-}\n\nclass Category' (k :: Type -> Type -> Type -> Type) where\n    type Allowed' k a :: Constraint\n    type Allowed' k a = ()\n\n    (.*) :: (Allowed' k a) => k () a a\n    (.-) :: AllAllowed' k [p, q, a, b, c, (q, p), (p, q), ((p, q), a), ((q, p), a), (q, (p, a)), (q, b), (p, a)]\n          => k q b c -> k p a b -> k (p, q) a c\n\n-- the constraints are unfortunately very ugly\nclass Category' k => Monoidal' (k :: Type -> Type -> Type -> Type) where\n    (.|) :: AllAllowed' k [a, b, c, d, p, q, ((p, q), (a, b)), ((p, a), (q, b)), (c, d), (p, a), (q, b), (p, (q, (a, b))), (p, ((q, a), b)), (p, ((a, q), b)), (p, (a, (q, b))), (a, (q, b)), ((a, q), b), (a, q), ((q, a), b), (q, a), (q, (a, b)), (a, b), (p, q)]\n      => k p a c -> k q b d -> k (p, q) (a, b) (c, d)\n\n-- Sequential composition of parametrized functions\n(.--) :: (Monoidal k, _)\n    => (q, b) `k` c\n    -> (p, a) `k` b\n    -> ((p, q), a) `k` c\ng .-- f = g . (id `x` f) . assocL . (swap `x` id)\n\n-- Parallel composition of parametrized functions\n(.||) :: (Monoidal k, _)\n    => (p, a) `k` b\n    -> (q, c) `k` d\n    -> ((p, q), (a, c)) `k` (b, d)\nf .|| g = f `x` g . swapParam\n\n\n{-\nSwap map for monoidal product of parametrized functions, basically bracket bookkeeping.\nRead from top to bottom\n(a b) (c d)\na (b, (c, d))\na ((b, c), d)\na ((c, b), d)\na (c, (b, d))\n(a c) (b d)\n-}\nswapParam :: (Monoidal k, _) => ((a, b), (c, d)) `k` ((a, c), (b, d))\nswapParam = assocR . (id `x` assocL) . (id `x` (swap `x` id)) . (id `x` assocR) . assocL\n\n\n--------------------------------------\n\nclass Additive a where\n    zero :: a\n    (^+) :: a -> a -> a\n\nclass NumCat (k :: Type -> Type -> Type) a where\n    negateC :: a `k` a\n    addC :: (a, a) `k` a\n    mulC :: (a, a) `k` a\n    increaseC :: a -> a `k` a -- curried add, add a single number\n\nclass FloatCat (k :: Type -> Type -> Type) a where\n    expC :: a `k` a\n\nclass FractCat (k :: Type -> Type -> Type) a where\n    recipC :: a `k` a\n\nclass Scalable (k :: Type -> Type -> Type) a where\n    scale :: a -> (a `k` a)\n\ntype Tensor = NArray None Double\n\n-------------------------------------\n-- Instances\n-------------------------------------\n\ninstance Category (->) where\n    id    = \\a -> a\n    g . f = \\a -> g (f a)\n\ninstance Monoidal (->) where\n    f `x` g = \\(a, b) -> (f a, g b)\n    assocL = \\((a, b), c) -> (a, (b, c))\n    assocR = \\(a, (b, c)) -> ((a, b), c)\n    unitorL = \\((), a) -> a\n    unitorL' = \\a -> ((), a)\n    swap = \\(a, b) -> (b, a)\n\ninstance Cartesian (->) where\n    exl = \\(a, _) -> a\n    exr = \\(_, b) -> b\n    dup = \\a -> (a, a)\n    counit = \\_ -> ()\n\ninstance Num a => NumCat (->) a where\n    negateC = negate\n    addC = uncurry (+)\n    mulC = uncurry (*)\n    increaseC a = (+a)\n\ninstance Floating a => FloatCat (->) a where\n    expC = exp\n\ninstance Fractional a => FractCat (->) a where\n    recipC = recip\n\n-------------------------------------\n\ninstance Additive () where\n    zero = ()\n    () ^+ () = ()\n\ninstance {-# OVERLAPPABLE #-} Num a => Additive a where\n    zero = 0\n    (^+) = (+)\n\ninstance (Additive a, Additive b) => Additive (a, b) where\n    zero = (zero, zero)\n    (a1, b1) ^+ (a2, b2) = (a1 ^+ a2, b1 ^+ b2)\n\n\n-------------------------------------\n\n(/\\) :: (Cartesian k, _) => b `k` c -> b `k` d -> b `k` (c, d)\nf /\\ g = (f `x` g) . dup\n\n(\\/) :: (Monoidal k, Cocartesian k, _) => a `k` c -> b `k` c -> (a, b) `k` c\nf \\/ g = jam . (f `x` g)\n\nfork :: (Cartesian k, _) => (b `k` c,  b `k` d) -> b `k` (c, d)\nfork (f, g) = f /\\ g\n\nunfork :: (Cartesian k, _) => b `k` (c, d) -> (b `k` c, b `k` d)\nunfork h = (exl . h, exr . h)\n\njoin :: (Monoidal k, Cocartesian k, _) => (a `k` c, b `k` c) -> (a, b) `k` c\njoin (f, g) = f \\/ g\n\nunjoin :: (Cocartesian k, _) => (a, b) `k` c -> (a `k` c, b `k` c)\nunjoin h = (h . inl, h . inr)\n\ndivide :: (Monoidal k, FractCat k a, _) => k (a, a) a\ndivide = mulC . (id `x` recipC)\n-------------------------------------\n\ntype family AllAllowed k xs :: Constraint where\n    AllAllowed k '[] = ()\n    AllAllowed k (x : xs) = (Allowed k x, AllAllowed k xs)\n\ntype family AllAllowed' k xs :: Constraint where\n    AllAllowed' k '[] = ()\n    AllAllowed' k (x : xs) = (Allowed' k x, AllAllowed' k xs)\n", "meta": {"hexsha": "c386583ab5abb1d381d54514b8227d50978746ec", "size": 6666, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CategoricDefinitions.hs", "max_stars_repo_name": "bgavran/Categorical_Deep_Learning", "max_stars_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2018-10-09T03:00:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:59:37.000Z", "max_issues_repo_path": "src/CategoricDefinitions.hs", "max_issues_repo_name": "bgavran/Functional_Deep_Learning", "max_issues_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CategoricDefinitions.hs", "max_forks_repo_name": "bgavran/Functional_Deep_Learning", "max_forks_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-12-19T06:19:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T02:52:48.000Z", "avg_line_length": 30.8611111111, "max_line_length": 260, "alphanum_fraction": 0.500750075, "num_tokens": 2423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.4382624122449831}}
{"text": "{-# LANGUAGE FlexibleContexts,\n             MultiParamTypeClasses #-}\n\nmodule Network.Trainer\n( Trainer(..)\n, CostFunction\n, CostFunction'\n, TrainingData\n, Selection\n, StopCondition\n\n, quadraticCost\n, quadraticCost'\n, minibatch\n, online\n\n, trainNTimes\n, trainUntilErrorLessThan\n, trainUntil\n) where\n\nimport Network.Network\nimport Network.Neuron\nimport Network.Layer\n\nimport System.Random\nimport System.Random.Shuffle (shuffle')\nimport Data.List.Split (chunksOf)\nimport Numeric.LinearAlgebra\n\n-- | Trainer is a typeclass for all trainer types - a trainer will take in\n--   an instance of itself, a network, a list of training data, and return a\n--   new network trained on the data.\nclass (Network n) => Trainer a n where\n  fit :: Selection -> a -> n -> [TrainingData] -> n\n  evaluate :: a -> n -> TrainingData -> Double\n\n-- | A CostFunction is used for evaluating a network's performance on a given\n--   input\ntype CostFunction = Vector Double -> Vector Double -> Double\n\n-- | A CostFunction' (derivative) is used in backPropagation\ntype CostFunction' = Vector Double -> Vector Double -> Vector Double\n\n-- | A tuple of (input, expected output)\ntype TrainingData = (Vector Double, Vector Double)\n\n-- | A selection function for performing gradient descent\ntype Selection = [TrainingData] -> [[TrainingData]]\n\n-- | A predicate (given a network, trainer, a list of training\n--   data, and the number of [fit]s performed) that\n--   tells the trainer to stop training\ntype StopCondition t n = n -> t -> [TrainingData] -> Int -> Bool\n\n-- | The quadratic cost function (1/2) * sum (y - a) ^ 2\nquadraticCost :: Vector Double -> Vector Double -> Double\nquadraticCost y a = sumElements $ 0.5 * (a - y) ** 2\n\n-- | The derivative of the quadratic cost function sum (y - a)\nquadraticCost' :: Vector Double -> Vector Double -> Vector Double\nquadraticCost' y a = a - y\n\n-- | The minibatch function becomes a Selection when partially applied\n--   with the minibatch size\nminibatch :: Int -> [TrainingData] -> [[TrainingData]]\nminibatch size = chunksOf size\n\n-- | If we want to train the network online\nonline :: [TrainingData] -> [[TrainingData]]\nonline = minibatch 1\n\n-- | This function returns true if the error of the network is less than\n--   a given error value, given a network, a trainer, a list of\n--   training data, and a counter (should start with 0)\n--   Note: Is there a way to have a counter with a recursive function\n--         without providing 0?\nnetworkErrorLessThan :: (Trainer t n) => Double -> n -> t -> [TrainingData] -> Int -> Bool\nnetworkErrorLessThan err network trainer dat _ = meanError < err\n  where meanError = (sum errors) / fromIntegral (length errors)\n        errors = map (evaluate trainer network) dat\n\n-- | Given a network, a trainer, a list of training data,\n--   and N, this function trains the network with the list of\n--   training data N times\ntrainNTimes :: (Trainer t n, RandomGen g) => g -> n -> t -> Selection -> [TrainingData] -> Int -> n\ntrainNTimes g network trainer s dat n =\n  trainUntil g network trainer s dat completion 0\n  where completion _ _ _ n' = (n == n')\n\n-- | Given a network, a trainer, a list of training data,\n--   and an error value, this function trains the network with the list of\n--   training data until the error of the network (calculated\n--   by averaging the errors of each training data) is less than\n--   the given error value\ntrainUntilErrorLessThan :: (Trainer t n, RandomGen g) => g -> n -> t -> Selection -> [TrainingData] -> Double -> n\ntrainUntilErrorLessThan g network trainer s dat err =\n  trainUntil g network trainer s dat (networkErrorLessThan err) 0\n\n-- | This function trains a network until a given TrainCompletionPredicate\n--   is satisfied.\ntrainUntil :: (Trainer t n, RandomGen g) => g -> n -> t -> Selection -> [TrainingData] -> StopCondition t n -> Int -> n\ntrainUntil g network trainer s dat completion n =\n  if completion network trainer dat n\n    then network\n    else trainUntil g' network' trainer s (shuffle' dat (length dat) g'') completion (n+1)\n    where network' = fit s trainer network dat\n          (g', g'') = split g\n", "meta": {"hexsha": "3063da7e8ea4b0673c6ca68100c214eca1080eee", "size": 4108, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Network/Trainer.hs", "max_stars_repo_name": "AkatsukiSirius/LambdaNet", "max_stars_repo_head_hexsha": "24386af14e3e7855a80664f1ee6b48b938aa3811", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-06T12:58:43.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-06T12:58:43.000Z", "max_issues_repo_path": "Network/Trainer.hs", "max_issues_repo_name": "world-admin/LambdaNet", "max_issues_repo_head_hexsha": "24386af14e3e7855a80664f1ee6b48b938aa3811", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Network/Trainer.hs", "max_forks_repo_name": "world-admin/LambdaNet", "max_forks_repo_head_hexsha": "24386af14e3e7855a80664f1ee6b48b938aa3811", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:39:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:39:55.000Z", "avg_line_length": 37.6880733945, "max_line_length": 119, "alphanum_fraction": 0.7044790652, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4382624122449829}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE ConstrainedClassMethods #-}\n{-# LANGUAGE QuantifiedConstraints #-}\n\nmodule MLP.Network (\n   AllCon,\n   ArrList(..),\n   arrLast,\n   Weights(..),\n   Net(..),\n   scalarR,\n   scalarL,\n   MLP(..),\n   Learn(..),\n   NetInstance\n) where\n\nimport GHC.TypeLits ( KnownNat, Nat, natVal )\nimport Numeric.LinearAlgebra.Static\n    ( R,\n      L,\n      (#>),\n      (<\u00b7>),\n      matrix,\n      uniformSample,\n      unrow,\n      vector,\n      tr,\n      Domain(outer) )\nimport Fcf ( Eval )\nimport Fcf.Data.List (Snoc, Last)\nimport Data.Singletons\n    ( Proxy(Proxy), SingI(sing), SingKind(fromSing) )\nimport Data.Kind (Constraint, Type)\nimport Control.Monad.Random.Class (MonadRandom(..))\nimport Numeric.Natural ( Natural )\nimport Unsafe.Coerce ( unsafeCoerce )\nimport Data.Proxy ( Proxy(Proxy) )\n\ntype family AllCon (f :: k -> Constraint) (ks :: [k]) :: Constraint where\n   AllCon _1 '[] = () :: Constraint\n   AllCon f (k ': ks) = (f k, AllCon f ks) :: Constraint\n\ndata ArrList (e :: Nat -> Type) (a :: [Nat]) where\n   Nil :: ArrList e '[]\n   Cons :: (KnownNat o, Show (e o)) => e o -> ArrList e os -> ArrList e (o ': os)\n\narrLast :: forall (o :: Nat) (e :: Nat -> Type) (a :: [Nat]). (AllCon KnownNat a, KnownNat o) \n           => ArrList e a -> Maybe (e o)\narrLast Nil = Nothing\narrLast (Cons a as@(Cons _ _)) = arrLast as\narrLast (Cons (a :: e o1) Nil) \n   | natVal (Proxy @o1) == natVal (Proxy @o) = Just (unsafeCoerce a)\n   | otherwise = Nothing\n\ninstance Show (ArrList e a) where\n   show Nil = \"Nil\"\n   show (Cons a x) = \"Cons \" ++ show a ++ show x\n\n\ndata Weights (i :: Nat) (o :: Nat) = Weights {\n   inputs :: !(L o i),\n   bias :: !(R o)\n}\n\ninstance (KnownNat i, KnownNat  o) => Show (Weights i o) where\n   show (Weights i b) = \"\\n[ Weights \\n\" ++ show i ++ \"\\n, Bias \\n\" ++ show b ++ \"]\\n\"\n\nrndWeights :: (KnownNat i, KnownNat o, MonadRandom m) => m (Weights i o)\nrndWeights = do\n   (s1,s2) <- (,) <$> getRandom <*> getRandom\n\n   let w = uniformSample s1 (-1) 1\n       b = unrow $ uniformSample s2 (-1) 1\n       \n   pure (Weights w b)\n\ndata Net (i :: Nat) (hs :: [Nat]) (o :: Nat) where\n   SLayer :: !(Weights i o) -> Net i '[] o\n   MLayers :: !(Weights i h) -> !(Net h hs o) -> Net i (h ': hs) o\n\ninstance AllCon KnownNat (i ': o ': hs) => Show (Net i hs o) where\n   show (SLayer l) = \"SLayer ->\" ++ show l ++ \"\\n\"\n   show (MLayers l n) = \"MLayers ->\" ++ show l ++ \"\\n\" ++ show n\n\nscalarR :: forall n. KnownNat n => Double -> R n\nscalarR d = vector (replicate numElems d)\n   where\n      numElems = fromIntegral . natVal $ Proxy @n\n\nscalarL :: forall n m. (KnownNat n, KnownNat m) => Double -> L n m\nscalarL d = matrix (replicate numElems d)\n   where\n      numElems = product . map fromIntegral . fromSing $ sing @'[n, m] \n\nclass MLP a where\n   type Topo a :: [Nat]\n   type Arr a :: Nat -> Type\n   type DimI a :: Nat\n   type DimO a :: Nat\n   type Layer a :: Nat -> Nat -> Type\n\n   layerOut :: (KnownNat i, KnownNat o) \n            => Layer a i o -> Arr a i -> Arr a o\n   \n   newLayer :: (KnownNat i, KnownNat o) \n               => Double -> Arr a i -> Arr a o -> Layer a i o -> Layer a i o\n\n   netError :: Arr a (DimO a) -> Arr a (DimO a) -> Double\n\nclass MLP a => Learn a where\n   create :: MonadRandom m => m a\n\n   topo :: a -> [Natural]\n\n   netOut :: Arr a (DimI a) -> a -> ArrList (Arr a) (Topo a)\n\n   mkDeltas :: ArrList (Arr a) (Topo a) -> Arr a (DimO a) -> a -> ArrList (Arr a) (Topo a)\n   \n   newNet :: Double -> Arr a (DimI a) -> ArrList (Arr a) (Topo a) -> ArrList (Arr a) (Topo a) -> a -> a\n\ninstance AllCon KnownNat (i ': o ': hs)\n         => MLP (Net i hs o) where\n   \n   type Topo  (Net i hs o) = Eval (Snoc hs o)\n   type Arr   (Net i hs o) = R\n   type DimI  (Net i hs o) = i\n   type DimO  (Net i hs o) = o\n   type Layer (Net i hs o) = Weights\n\n   layerOut :: (KnownNat w, KnownNat n) => Weights w n -> R w -> R n\n   layerOut l i = sigmoid $ (inputs l #> i) + bias l\n      where\n         sigmoid x = 1 / (1 + exp (-x))\n\n   newLayer :: (KnownNat w, KnownNat n)\n               => Double -> R w -> R n -> Weights w n -> Weights w n\n   newLayer lr i delta l = Weights (w - errW) (b - errB)\n      where\n         w = inputs l\n         b = bias l\n         errW = scalarL lr * (delta `outer` i)\n         errB = scalarR lr * delta\n\n   netError :: KnownNat o => R o -> R o -> Double\n   netError expOut actOut = 1 <\u00b7> ((expOut - actOut) ** 2)\n\n-- this dummy type can be used to help find the correct MLP instance\n-- in functions layerOut, newLayer\ntype NetInstance = Net 0 '[] 0\n\ninstance (KnownNat i, KnownNat o)\n         => Learn (Net i '[] o) where\n\n   create :: MonadRandom m => m (Net i '[] o)\n   create = SLayer <$> rndWeights\n\n   topo :: Net i '[] o -> [Natural]\n   topo _ = [fromSing (sing @o)]\n\n   netOut :: R i -> Net i '[] o -> ArrList R '[o]\n   netOut i (SLayer l) = Cons (layerOut @NetInstance l i) Nil\n\n   mkDeltas :: ArrList R '[o] -> R o -> Net i '[] o -> ArrList R '[o]\n   mkDeltas (Cons lo Nil) expOut (SLayer l) = Cons (dsn * dso) Nil\n      where\n         dsn = lo * (1 - lo)\n         dso = lo - expOut\n\n   newNet :: Double -> R i -> ArrList R '[o] -> ArrList R '[o] -> Net i '[] o -> Net i '[] o\n   newNet lr i (Cons delta Nil) _ (SLayer l) = SLayer (newLayer @NetInstance lr i delta l)\n\ninstance (AllCon KnownNat (i ': o ': h ': hs),\n         Learn (Net h hs o))\n         => Learn (Net i (h ': hs) o) where\n\n   create :: forall i h hs o m. (MonadRandom m, KnownNat i, KnownNat h, Learn (Net h hs o)) \n             => m (Net i (h ': hs) o)\n   create = MLayers <$> (rndWeights @i @h) <*> create @(Net h hs o)\n\n   topo :: Net i (h ': hs) o -> [Natural]\n   topo (MLayers _ n) = fromSing (sing @h) : topo n\n\n   netOut :: hhs ~ (h ': hs) => R i -> Net i hhs o -> ArrList R (Topo (Net i hhs o))\n   netOut i (MLayers l n) = Cons lo (netOut lo n)\n      where\n         lo = layerOut @NetInstance l i\n\n   mkDeltas :: hhs ~ (h ': hs) => \n               ArrList R (Topo (Net i hhs o)) -> R o -> Net i hhs o -> ArrList R (Topo (Net i hhs o))\n   mkDeltas (Cons lo lor) expOut (MLayers l nxt) =\n      case nxt of\n         SLayer lnxt -> let dd@(Cons d _) = mkDeltas lor expOut nxt \n                            dso = tr (inputs lnxt) #> d\n                          in Cons (dsn * dso) dd\n         \n         MLayers lnxt _ -> let dd@(Cons d _) = mkDeltas lor expOut nxt \n                               dso = tr (inputs lnxt) #> d\n                             in Cons (dsn * dso) dd\n      where\n         dsn = lo * (1 - lo)\n\n   newNet :: Double -> \n             R i ->\n             ArrList R (Topo (Net i (h ': hs) o)) ->\n             ArrList R (Topo (Net i (h ': hs) o)) ->\n             Net i (h ': hs) o ->\n             Net i (h ': hs) o\n   newNet lr i (Cons d ds) (Cons lo los) (MLayers l n) =\n      MLayers (newLayer @NetInstance lr i d l) (newNet lr lo ds los n)\n\n\nlayer1 :: Weights 2 3\nlayer1 = Weights (matrix [1..6]) (vector [1..3])\n\nlayer2 :: Weights 3 5\nlayer2 = Weights (matrix [1..15]) (vector [1..5])\n\nnetwork :: Net 2 '[3] 5\nnetwork = MLayers layer1 $ SLayer layer2", "meta": {"hexsha": "f1e49f47602230753a8fc41857e24e1c952d5aa4", "size": 7368, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MLP/Network.hs", "max_stars_repo_name": "ovanr/Typed-MLP", "max_stars_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MLP/Network.hs", "max_issues_repo_name": "ovanr/Typed-MLP", "max_issues_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MLP/Network.hs", "max_forks_repo_name": "ovanr/Typed-MLP", "max_forks_repo_head_hexsha": "c6cf0d5295048f0aa4bfe9b4628ccb59cb92b80c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8961038961, "max_line_length": 103, "alphanum_fraction": 0.5489956569, "num_tokens": 2371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4379619032810181}}
{"text": "{-# LANGUAGE TemplateHaskell     #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ConstraintKinds     #-}\n{-# LANGUAGE TypeOperators       #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\nmodule Test.Grenade.Layers.Internal.Pooling where\n\nimport           Grenade.Layers.Internal.Pooling\n\nimport           Numeric.LinearAlgebra hiding (uniformSample, konst, (===))\n\nimport           Hedgehog\nimport qualified Hedgehog.Gen as Gen\nimport qualified Hedgehog.Range as Range\n\nimport qualified Test.Grenade.Layers.Internal.Reference as Reference\nimport           Test.Hedgehog.Compat\n\nprop_poolForwards_poolBackwards_behaves_as_reference =\n  let ok extent kernel = [stride | stride <- [1..extent], (extent - kernel) `mod` stride == 0]\n      output extent kernel stride = (extent - kernel) `div` stride + 1\n  in  property $ do\n        height   <- forAll $ choose 2 100\n        width    <- forAll $ choose 2 100\n        kernel_h <- forAll $ choose 1 (height - 1)\n        kernel_w <- forAll $ choose 1 (width - 1)\n        stride_h <- forAll $ Gen.element (ok height kernel_h)\n        stride_w <- forAll $ Gen.element (ok width kernel_w)\n        input    <- forAll $ (height >< width) <$> Gen.list (Range.singleton $ height * width) (Gen.realFloat $ Range.linearFracFrom 0 (-100) 100)\n\n        let outFast       = poolForward 1 height width kernel_h kernel_w stride_h stride_w input\n        let retFast       = poolBackward 1 height width kernel_h kernel_w stride_h stride_w input outFast\n\n        let outReference  = Reference.poolForward kernel_h kernel_w stride_h stride_w (output height kernel_h stride_h) (output width kernel_w stride_w) input\n        let retReference  = Reference.poolBackward kernel_h kernel_w stride_h stride_w  input outReference\n\n        outFast === outReference\n        retFast === retReference\n\n\ntests :: IO Bool\ntests = checkParallel $$(discover)\n", "meta": {"hexsha": "017087fedaf512fdeca78a6a3957bc0fa740b693", "size": 1951, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/Internal/Pooling.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1527, "max_stars_repo_stars_event_min_datetime": "2016-06-23T13:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T05:22:00.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/Internal/Pooling.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2016-06-27T22:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T17:50:09.000Z", "max_forks_repo_path": "test/Test/Grenade/Layers/Internal/Pooling.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": 42.4130434783, "max_line_length": 158, "alphanum_fraction": 0.6776012301, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.4377591177151266}}
{"text": "{-|\nModule : Network\n|-}\nmodule Network\n  ( Net(..)\n  , createNet\n  , saveNetwork\n  , loadNetwork\n  ) where\n\nimport Numeric.LinearAlgebra\nimport Specs\nimport System.Random\n\n\n-- | data representing Network\ndata Net = Net {\n    numLayers :: Int -- ^ Number of layers in Network\n  , sizes :: [Int] -- ^ Sizes of each layer\n  , biases :: [Matrix Double] -- ^ Bias Matrix's of each layer\n  , weights :: [Matrix Double] -- ^ Weight Matrix's of each layer\n  } deriving (Eq, Show)\n\n\n-- | Generate random small numbers\nsmallRandoms :: Int -> [Double]\nsmallRandoms seed = map (/100) (randoms (mkStdGen seed))\n\n\n-- | Create Matrix with random weigths\nrandomWeightMatrix :: Int -> Int -> Int -> Matrix Double\nrandomWeightMatrix numInputs numOutputs seed = (numOutputs><numInputs) weights\n    where weights = take (numOutputs*numInputs) (smallRandoms seed)\n\n\n-- | Create new Network for given sizes of layers\ncreateNet :: [Int] -- ^ Sizes of each layer\n          -> IO Net\ncreateNet sizes = do\n   let b = (\\ x -> randomWeightMatrix 1 x 7) <$> tail sizes\n   let w = (\\ (x, y) -> randomWeightMatrix x y 7) <$> zip (init sizes) (tail sizes)\n   let net = Net{numLayers = length sizes, sizes = sizes, biases = b, weights = w}\n   return net\n\n\n-- | Change Network to String for saving\ntoString :: Net -> String\ntoString net = nL ++ s ++ b ++ w\n  where\n    nL = show (numLayers net) ++ \" \\n\"\n    s = foldr ((\\ a b -> a (' ' : b)) . shows) \"\\n\" (sizes net)\n    b = foldr1 (++) (foldr ((\\ a b -> a (' ' : b)) . shows) \"\\n\" <$> (foldr1 (++) <$> (toLists <$> biases net)))\n    w = foldr1 (++) (foldr ((\\ a b -> a (' ' : b)) . shows) \"\\n\" <$> (foldr1 (++) <$> (toLists <$> weights net)))\n\n\n-- | Save Network to file\nsaveNetwork :: Net -- ^ Network to save\n            -> FilePath -- ^ FilePath for saving\n            -> IO ()\nsaveNetwork net file = writeFile file (toString net)\n\n\n-- | Change line from file to list of Doubles\nlineToListDouble :: String -> [Double]\nlineToListDouble line = (\\ x -> read x :: Double) <$> words line\n\n\n-- | Load Network from file\nloadNetwork :: FilePath -- ^ FilePath to saved network\n            -> IO Net\nloadNetwork file = do\n  content <- readFile file\n  let contentLines = lines content\n  let numLayers = (read (contentLines !! 0) :: Int)\n  let sizes = (\\x-> read x :: Int) <$> (words (contentLines !! 1))\n  let ba = (contentLines !!) <$> [2..numLayers]\n  let b = (\\ (x, y) -> (y><1) x :: Matrix Double) <$> zip (lineToListDouble <$> ba) (tail sizes)\n  let we = (contentLines !!) <$> [(numLayers+1)..(numLayers+numLayers-1)]\n  let w  = (\\ (x, y, z) -> (z><y) x :: Matrix Double) <$> zip3 (lineToListDouble <$> we) (init sizes) (tail sizes)\n  return Net{numLayers = length sizes, sizes = sizes, biases = b, weights = w}", "meta": {"hexsha": "d70519c0c8799528a3ec50b30fe9be039dcc02d6", "size": 2727, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Network.hs", "max_stars_repo_name": "Malenczuk/HuskNet", "max_stars_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-29T22:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-29T22:04:24.000Z", "max_issues_repo_path": "src/Network.hs", "max_issues_repo_name": "Malenczuk/HuskNet", "max_issues_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Network.hs", "max_forks_repo_name": "Malenczuk/HuskNet", "max_forks_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0875, "max_line_length": 114, "alphanum_fraction": 0.6105610561, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.43688902187353096}}
{"text": "{- Assignment 1\n - Name: Talha Amjad\n - Date: \n -}\nmodule Assign_1_ExtraCredit where\n\n-- import Data.Complex -- TODO uncomment me to use built-in Complex type\n-- see https://www.stackage.org/haddock/lts-8.24/base-4.9.1.0/Data-Complex.html\n\nmacid = \"amjadt1\"\n\n", "meta": {"hexsha": "0410d4ac808f7d928ab6114b2b8c97e1dfb36ec1", "size": 259, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Assign_1_ExtraCredit.hs", "max_stars_repo_name": "Talha2000/Cubic-Equation-Solver", "max_stars_repo_head_hexsha": "ab369a362eb63fbe123c213dec4d6e0c5352d8f2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Assign_1_ExtraCredit.hs", "max_issues_repo_name": "Talha2000/Cubic-Equation-Solver", "max_issues_repo_head_hexsha": "ab369a362eb63fbe123c213dec4d6e0c5352d8f2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Assign_1_ExtraCredit.hs", "max_forks_repo_name": "Talha2000/Cubic-Equation-Solver", "max_forks_repo_head_hexsha": "ab369a362eb63fbe123c213dec4d6e0c5352d8f2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5833333333, "max_line_length": 79, "alphanum_fraction": 0.7142857143, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.4368777201063262}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes                      #-}\n{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE DefaultSignatures                        #-}\n{-# LANGUAGE DeriveDataTypeable                       #-}\n{-# LANGUAGE DeriveFoldable                           #-}\n{-# LANGUAGE DeriveFunctor                            #-}\n{-# LANGUAGE DeriveGeneric                            #-}\n{-# LANGUAGE DeriveTraversable                        #-}\n{-# LANGUAGE DerivingVia                              #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE FunctionalDependencies                   #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving               #-}\n{-# LANGUAGE MultiParamTypeClasses                    #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE StandaloneDeriving                       #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeFamilies                             #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE UndecidableInstances                     #-}\n{-# OPTIONS_GHC -Wno-redundant-constraints            #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n-- |\n-- Module      : Numeric.Opto.Update\n-- Copyright   : (c) Justin Le 2019\n-- License     : BSD3\n--\n-- Maintainer  : justin@jle.im\n-- Stability   : experimental\n-- Portability : non-portable\n--\n-- A unified interface for values in vector spaces that can be added and\n-- scaled (purely and also in-place), and measured.\nmodule Numeric.Opto.Update (\n    Linear(..), sumLinear, gAdd, gZeroL, gScale\n  , Metric(..), gDot, gNorm_inf, gNorm_0, gNorm_1, gNorm_2, gQuadrance\n  , LinearInPlace(..), sumLinearInPlace\n  , linearWit\n  ) where\n\nimport           Control.DeepSeq\nimport           Control.Monad.Primitive\nimport           Data.Coerce\nimport           Data.Complex\nimport           Data.Data\nimport           Data.Finite\nimport           Data.Foldable\nimport           Data.Function\nimport           Data.Maybe\nimport           Data.Mutable\nimport           Data.Semigroup\nimport           Data.Vinyl hiding                   ((:~:))\nimport           GHC.Generics                        (Generic)\nimport           GHC.TypeLits\nimport           Generics.OneLiner\nimport           Numeric.Opto.Ref\nimport           Unsafe.Coerce\nimport qualified Data.Vector.Generic                 as VG\nimport qualified Data.Vector.Generic.Mutable.Sized   as SVGM\nimport qualified Data.Vector.Generic.Sized           as SVG\nimport qualified Numeric.LinearAlgebra               as UH\nimport qualified Numeric.LinearAlgebra.Static        as H\nimport qualified Numeric.LinearAlgebra.Static.Vector as H\n\n-- | If @a@ is an instance of @'Linear' c@, you can /add/ together values\n-- of @a@, and /scale/ them using @c@s.\n--\n-- For example, if you have a vector of doubles, you can add them together\n-- component-wise, and scale them by multiplying every item by the scalar.\n--\n-- Mathematically, this means that @a@ forms something like a module or\n-- vector space over @c@, where @c@ can be any 'Num' instance.\nclass Num c => Linear c a | a -> c where\n    -- | Add together @a@s.  Should be associative.\n    --\n    -- @\n    -- x .+. (y .+. z) == (x .+. y) .+. z\n    -- @\n    --\n    -- If @a@ is an instance of 'Num', this can be just 'Prelude.+'.\n    (.+.) :: a -> a -> a\n\n    -- | The \"zero\" @a@, meant to form an identity with '.+.'.\n    --\n    -- @\n    -- x .+. zeroL == x\n    -- zeroL .+. y == y\n    -- @\n    --\n    -- If @a@ is an instance of 'Num', this can be just 0.\n    zeroL :: a\n\n    -- | Scale an @a@ by a factor @c@.  Should distribute over '.+.'.\n    --\n    -- @\n    -- a .* (x .+. y) == (a .* x) .+. (a .* y)\n    -- a .* (b .* c)  == (a * b) .* c\n    -- @\n    (.*)  :: c -> a -> a\n\n    infixl 6 .+.\n    infixl 7 .*\n\n    default (.+.) :: (ADTRecord a, Constraints a (Linear c)) => a -> a -> a\n    (.+.) = gAdd @c\n\n    default zeroL :: (ADTRecord a, Constraints a (Linear c)) => a\n    zeroL = gZeroL @c\n\n    default (.*) :: (ADTRecord a, Constraints a (Linear c)) => c -> a -> a\n    (.*)  = gScale\n\n-- | Sum over a 'Foldable' container of @'Linear' c a@\nsumLinear :: (Linear c a, Foldable t) => t a -> a\nsumLinear = foldl' (.+.) zeroL\n\n-- | An implementation of '.+.' that works for records where every field is\n-- an instance of @'Linear' c@ (that is, every field is additive and can be\n-- scaled by the same @c@).\ngAdd :: forall c a. (ADTRecord a, Constraints a (Linear c)) => a -> a -> a\ngAdd = binaryOp @(Linear c) (.+.)\n\n-- | An implementation of 'zeroL' that works for records where every field\n-- is an instance of @'Linear' c@ (that is, every field is additive and can\n-- be scaled by the same @c@).\ngZeroL :: forall c a. (ADTRecord a, Constraints a (Linear c)) => a\ngZeroL = nullaryOp @(Linear c) zeroL\n\n-- | An implementation of '.*' that works for records where every field\n-- is an instance of @'Linear' c@ (that is, every field is additive and can\n-- be scaled by the same @c@).\ngScale :: forall c a. (ADTRecord a, Constraints a (Linear c)) => c -> a -> a\ngScale c = unaryOp @(Linear c) (c .*)\n\n-- | Class for values supporting an inner product and various norms.\nclass Linear c a => Metric c a where\n    infixl 7 <.>\n    -- | Sum of component-wise product\n    (<.>)    :: a -> a -> c\n    -- | Maximum absolute component.  Is undefined if no components exist.\n    norm_inf :: a -> c\n    -- | Number of non-zero components\n    norm_0   :: a -> c\n    -- | Sum of absolute components\n    norm_1   :: a -> c\n    -- | Square root of sum of squared components\n    norm_2    :: a -> c\n    -- | Sum of squared components\n    quadrance :: a -> c\n\n    default (<.>) :: (ADT a, Constraints a (Metric c)) => a -> a -> c\n    (<.>) = gDot\n    default norm_inf :: (ADT a, Constraints a (Metric c), Ord c) => a -> c\n    norm_inf = gNorm_inf\n    default norm_0 :: (ADT a, Constraints a (Metric c)) => a -> c\n    norm_0 = gNorm_0\n    default norm_1 :: (ADT a, Constraints a (Metric c)) => a -> c\n    norm_1 = gNorm_1\n    default norm_2 :: Floating c => a -> c\n    norm_2 = sqrt . quadrance\n    default quadrance :: (ADT a, Constraints a (Metric c)) => a -> c\n    quadrance = gQuadrance\n\n-- | An implementation of 'gDot' that works for records where every field\n-- is an instance of @'Metric' c@.\ngDot :: forall c a. (ADT a, Constraints a (Metric c), Num c) => a -> a -> c\ngDot x = getSum . mzipWith @(Metric c) (\\x' -> Sum . (x' <.>)) x\n\n-- | An implementation of 'norm_inf' that works for records where every\n-- field is an instance of @'Metric' c@.\ngNorm_inf :: forall c a. (ADT a, Constraints a (Metric c), Ord c) => a -> c\ngNorm_inf = getMax\n          . fromMaybe (error \"norm_inf: Divergent infinity norm\")\n          . getOption\n          . gfoldMap @(Metric c) (Option . Just . Max . abs . norm_inf)\n\n-- | An implementation of 'norm_0' that works for records where every field\n-- is an instance of @'Metric' c@.\ngNorm_0 :: forall c a. (ADT a, Constraints a (Metric c), Num c) => a -> c\ngNorm_0 = getSum . gfoldMap @(Metric c) (Sum . norm_0)\n\n-- | An implementation of 'norm_1' that works for records where every field\n-- is an instance of @'Metric' c@.\ngNorm_1 :: forall c a. (ADT a, Constraints a (Metric c), Num c) => a -> c\ngNorm_1 = getSum . gfoldMap @(Metric c) (Sum . norm_1)\n\n-- | An implementation of 'norm_2' that works for records where every field\n-- is an instance of @'Metric' c@.\ngNorm_2 :: forall c a. (ADT a, Constraints a (Metric c), Floating c) => a -> c\ngNorm_2 = sqrt . gQuadrance\n\n-- | An implementation of 'quadrance' that works for records where every\n-- field is an instance of @'Metric' c@.\ngQuadrance :: forall c a. (ADT a, Constraints a (Metric c), Num c) => a -> c\ngQuadrance = getSum . gfoldMap @(Metric c) (Sum . quadrance)\n\n-- | Instaces of 'Linear' that support certain in-place mutations.\n-- Inspired by the BLAS Level 1 API.  A @'LinearInPlace' m v c a@ means\n-- that @v@ is a mutable reference to an @a@ that can be updated as an\n-- action in monad @m@.\nclass (Mutable s a, Linear c a) => LinearInPlace s c a where\n    -- | Add a value in-place.\n    (.+.=) :: (PrimMonad m, PrimState m ~ s) => Ref s a -> a -> m ()\n\n    -- | Scale a value in-place.\n    (.*=)  :: (PrimMonad m, PrimState m ~ s) => Ref s a -> c -> m ()\n\n    -- | Add a scaled value in-place.\n    (.*+=) :: (PrimMonad m, PrimState m ~ s) => Ref s a -> (c, a) -> m ()\n\n    r .+.= x      = modifyRef' r (.+. x)\n    r  .*= c      = modifyRef' r (c .*)\n    r .*+= (c, x) = modifyRef' r ((c .* x) .+.)\n\n    infix 4 .+.=\n    infix 4 .*=\n    infix 4 .*+=\n\n-- | Given some starting reference @v@, add every item in a foldable\n-- container into that reference in-place.\nsumLinearInPlace :: (LinearInPlace s c a, Foldable t, PrimMonad m, PrimState m ~ s) => Ref s a -> t a -> m ()\nsumLinearInPlace v = mapM_ (v .+.=)\n\n-- | Newtype wrapper that gives \"simple\" 'Linear', 'Metric', and\n-- 'LinearInPlace' instances for instances of 'Num'.\n--\n-- This can be used with the /-XDerivingVia/ extension:\n--\n-- @\n-- deriving via (LinearNum Double) instance Linear Double Double\n-- deriving via (LinearNum Double) instance Metric Double Double\n-- instance Ref s Double v => LinearInPlace s v Double Double\n-- @\nnewtype LinearNum a = LinearNum { getLinearNum :: a }\n  deriving ( Show, Eq, Ord\n           , Functor, Foldable, Traversable\n           , Enum, Bounded\n           , Num, Fractional, Floating, Real, Integral, RealFrac, RealFloat\n           , Generic, Typeable, Data\n           )\ninstance NFData a => NFData (LinearNum a)\n\ninstance Num a => Linear a (LinearNum a) where\n    (.+.) = (+)\n    zeroL = 0\n    (.*)  = coerce ((*) :: a -> a -> a)\ninstance Num a => Metric a (LinearNum a) where\n    (<.>)     = coerce ((*) :: a -> a -> a)\n    norm_inf  = coerce (abs :: a -> a)\n    norm_0    = coerce (abs . signum :: a -> a)\n    norm_1    = coerce (abs :: a -> a)\n    norm_2    = coerce (abs :: a -> a)\n    quadrance = coerce ((^ (2 :: Int)) :: a -> a)\n\nderiving via (LinearNum Int)         instance Linear Int Int\nderiving via (LinearNum Integer)     instance Linear Integer Integer\nderiving via (LinearNum Rational)    instance Linear Rational Rational\nderiving via (LinearNum Float)       instance Linear Float Float\nderiving via (LinearNum Double)      instance Linear Double Double\nderiving via (LinearNum (Complex a)) instance RealFloat a => Linear (Complex a) (Complex a)\n\nderiving via (LinearNum Int)         instance Metric Int Int\nderiving via (LinearNum Integer)     instance Metric Integer Integer\nderiving via (LinearNum Rational)    instance Metric Rational Rational\nderiving via (LinearNum Float)       instance Metric Float Float\nderiving via (LinearNum Double)      instance Metric Double Double\nderiving via (LinearNum (Complex a)) instance RealFloat a => Metric (Complex a) (Complex a)\n\ninstance Mutable s Int                        => LinearInPlace s Int Int\ninstance Mutable s Integer                    => LinearInPlace s Integer Integer\ninstance Mutable s Rational                   => LinearInPlace s Rational Rational\ninstance Mutable s Float                      => LinearInPlace s Float Float\ninstance Mutable s Double                     => LinearInPlace s Double Double\ninstance (Mutable s (Complex a), RealFloat a) => LinearInPlace s (Complex a) (Complex a)\n\ninstance (Num a, VG.Vector v a, KnownNat n) => Linear a (SVG.Vector v n a) where\n    (.+.)    = (+)\n    zeroL    = 0\n    c .* xs  = SVG.map (c *) xs\n\ninstance (Floating a, Ord a, VG.Vector v a, KnownNat n) => Metric a (SVG.Vector v n a) where\n    xs <.> ys = SVG.sum (xs * ys)\n    norm_inf  = SVG.foldl' (\\x y -> max (abs x) y) 0\n    norm_0    = fromIntegral . SVG.length\n    norm_1    = SVG.sum . abs\n    quadrance = SVG.sum . (^ (2 :: Int))\n\ninstance (Num a, mv ~ VG.Mutable v, VG.Vector v a, KnownNat n)\n      => LinearInPlace s a (SVG.Vector v n a) where\n    r .+.= xs = flip SVG.imapM_ xs $ \\i x ->\n      SVGM.modify r (+ x) i\n    r .*= c = forM_ finites $ \\i ->\n      SVGM.modify r (c *) i\n    r .*+= (c, xs) = flip SVG.imapM_ xs $ \\i x ->\n      SVGM.modify r (+ (c * x)) i\n\ninstance KnownNat n => Linear Double (H.R n) where\n    (.+.)   = (+)\n    zeroL   = 0\n    c .* xs = H.konst c * xs\ninstance KnownNat n => Metric Double (H.R n) where\n    (<.>)     = (H.<.>)\n    norm_inf  = H.norm_Inf\n    norm_0    = H.norm_0\n    norm_1    = H.norm_1\n    norm_2    = H.norm_2\n    quadrance = (**2) . H.norm_2\ninstance KnownNat n => LinearInPlace s Double (H.R n) where\n    MR v .+.= x = v .+.= H.rVec x\n    MR v  .*= c = v  .*= c\n    MR v .*+= (c, x) = v .*+= (c, H.rVec x)\n\ninstance (KnownNat n, KnownNat m) => Linear Double (H.L n m) where\n    (.+.)   = (+)\n    zeroL   = 0\n    c .* xs = H.konst c * xs\ninstance (KnownNat n, KnownNat m) => Metric Double (H.L n m) where\n    (<.>)     = (UH.<.>) `on` UH.flatten . H.extract\n    norm_inf  = UH.maxElement . H.extract . abs\n    norm_0    = sum . map norm_0 . H.toRows\n    norm_1    = UH.sumElements . H.extract\n    norm_2    = UH.norm_2 . UH.flatten . H.extract\n    quadrance = (**2) . norm_2\ninstance (KnownNat n, KnownNat k) => LinearInPlace s Double (H.L n k) where\n    ML v .+.= x = v .+.= H.lVec x\n    ML v  .*= c = v  .*= c\n    ML v .*+= (c, x) = v .*+= (c, H.lVec x)\n\ninstance (Linear c a, Linear c b) => Linear c (a, b) where\ninstance (Linear c a, Linear c b, Linear c d) => Linear c (a, b, d) where\ninstance (Linear c a, Linear c b, Linear c d, Linear c e) => Linear c (a, b, d, e) where\ninstance (Linear c a, Linear c b, Linear c d, Linear c e, Linear c f) => Linear c (a, b, d, e, f) where\n\ninstance (Metric c a, Metric c b, Ord c, Floating c) => Metric c (a, b)\ninstance (Metric c a, Metric c b, Metric c d, Ord c, Floating c) => Metric c (a, b, d)\ninstance (Metric c a, Metric c b, Metric c d, Metric c e, Ord c, Floating c) => Metric c (a, b, d, e)\ninstance (Metric c a, Metric c b, Metric c d, Metric c e, Metric c f, Ord c, Floating c) => Metric c (a, b, d, e, f)\n\ninstance (Mutable s (a, b), Linear c a, Linear c b) => LinearInPlace s c (a, b)\ninstance (Mutable s (a, b, d), Linear c a, Linear c b, Linear c d) => LinearInPlace s c (a, b, d)\ninstance (Mutable s (a, b, d, e), Linear c a, Linear c b, Linear c d, Linear c e) => LinearInPlace s c (a, b, d, e)\ninstance (Mutable s (a, b, d, e, f), Linear c a, Linear c b, Linear c d, Linear c e, Linear c f) => LinearInPlace s c (a, b, d, e, f)\n\ninstance Linear c (f a) => Linear c (Rec f '[a]) where\n    x :& RNil .+. y :& RNil = (x .+. y) :& RNil\n    zeroL = zeroL :& RNil\n    c .* (x :& RNil) = (c .* x) :& RNil\n\ninstance (Linear c (f a), Linear c (Rec f (b ': bs))) => Linear c (Rec f (a ': b ': bs)) where\n    x :& xs .+. y :& ys = (x .+. y) :& (xs .+. ys)\n    zeroL = zeroL :& zeroL\n    c .* (x :& xs) = (c .* x) :& (c .* xs)\n\ninstance Metric c (f a) => Metric c (Rec f '[a]) where\n    (x :& RNil) <.> (y :& RNil) = x <.> y\n    norm_inf (x :& RNil) = norm_inf x\n    norm_0 (x :& RNil) = norm_0 x\n    norm_1 (x :& RNil) = norm_1 x\n    norm_2 (x :& RNil) = norm_2 x\n    quadrance (x :& RNil) = quadrance x\n\ninstance (Floating c, Ord c, Metric c (f a), Metric c (Rec f (b ': bs))) => Metric c (Rec f (a ': b ': bs)) where\n    (<.>) = undefined\n    norm_inf (x :& xs) = norm_0 x `max` norm_0 xs\n    norm_0 (x :& xs) = norm_0 x + norm_0 xs\n    norm_1 (x :& xs) = norm_1 x + norm_1 xs\n    norm_2 = sqrt . quadrance\n    quadrance (x :& xs) = quadrance x + quadrance xs\n\ninstance LinearInPlace s c (f a) => LinearInPlace s c (Rec f '[a]) where\n    (RecRef v :& RNil) .+.= (x :& RNil)    = v .+.= x\n    (RecRef v :& RNil) .*=  c              = v .*=  c\n    (RecRef v :& RNil) .*+= (c, x :& RNil) = v .*+= (c, x)\n\ninstance ( LinearInPlace s c (f a)\n         , LinearInPlace s c (Rec f (b ': bs))\n         )\n        => LinearInPlace s c (Rec f (a ': b ': bs)) where\n    (RecRef v :& vs) .+.= (x :& xs)    = do v .+.= x; vs .+.= xs\n    (RecRef v :& vs) .*=  c            = do v .*=  c; vs .*=  c\n    (RecRef v :& vs) .*+= (c, x :& xs) = do v .*+= (c, x); vs .*+= (c, xs)\n\n-- | If @a@ and @b@ are both 'Linear' instances, then if @a@ is equal to\n-- @b@, their scalars @c@ and @d@ must also be equal.  This is necessary\n-- because GHC isn't happy with the functional dependency for some reason.\nlinearWit\n    :: forall a c d. (Linear c a, Linear d a)\n    => (c :~: d)\nlinearWit = unsafeCoerce Refl\n", "meta": {"hexsha": "d3bdcf8d8eea62baff39815ab63602ed5f691ff2", "size": 16397, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Opto/Update.hs", "max_stars_repo_name": "mstksg/opto", "max_stars_repo_head_hexsha": "ffdd862e858cd00581eee3b0b81e07d80d617cff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-01-23T06:32:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:23.000Z", "max_issues_repo_path": "src/Numeric/Opto/Update.hs", "max_issues_repo_name": "mstksg/opto", "max_issues_repo_head_hexsha": "ffdd862e858cd00581eee3b0b81e07d80d617cff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T00:08:27.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T02:10:12.000Z", "max_forks_repo_path": "src/Numeric/Opto/Update.hs", "max_forks_repo_name": "mstksg/opto", "max_forks_repo_head_hexsha": "ffdd862e858cd00581eee3b0b81e07d80d617cff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8290816327, "max_line_length": 133, "alphanum_fraction": 0.5713850095, "num_tokens": 5025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4366899783718048}}
{"text": "module Parser (readExpr, readExprList) where\n\nimport Types\n\nimport Numeric\nimport Data.Ratio\nimport Data.Complex\nimport Control.Monad.Error\nimport Text.ParserCombinators.Parsec hiding (spaces)\n\n----------\n-- Helpers\n----------\nsymbol :: Parser Char\nsymbol = oneOf \"!#$%&|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\nescapedChar :: Parser String\nescapedChar = do backslash <- char '\\\\'\n                 escaped <- oneOf \"nrt\\\"\\\\\"\n                 return [backslash, escaped]\n\n----------------\n-- Token parsers\n----------------\nparseString :: Parser LispVal\nparseString = do _ <- char '\"'\n                 x <- many (noneOf \"\\\"\") <|> escapedChar\n                 _ <- char '\"'\n                 return $ String x\n\nparseAtom :: Parser LispVal\nparseAtom = do first <- letter <|> symbol\n               rest <- many (letter <|> digit <|> symbol)\n               let atom = first:rest\n               return $ Atom atom\n\n\nparseNumber :: Parser LispVal\nparseNumber = fmap (Number . read) (many1 digit)\n\nparseHashPrefix :: Parser LispVal\nparseHashPrefix = char '#' >> (parseOctal\n                               <|> parseDec\n                               <|> parseHex\n                               <|> parseBin\n                               <|> parseChar\n                               <|> parseBool)\n\n\n-- Simple types parsing\nparseNumberHelper prefix filter reader = do char prefix\n                                            number <- many1 filter\n                                            return $ (Number . reader) number\n    \nparseOctal :: Parser LispVal\nparseOctal = parseNumberHelper 'o' octDigit (fst . head . readOct)\n\nparseHex :: Parser LispVal\nparseHex = parseNumberHelper 'h' hexDigit (fst . head . readHex)\n\nparseDec :: Parser LispVal\nparseDec = parseNumberHelper 'd' digit read\n\nparseBin :: Parser LispVal\nparseBin = parseNumberHelper 'b' (oneOf \"01\") binToDec\n  where binToDec = foldl (\\acc x -> acc * 2 + (if x == '0' then 0 else 1)) 0\n\nparseChar :: Parser LispVal\nparseChar = fmap Character (char '\\\\' >> anyChar)\n\nparseBool :: Parser LispVal\nparseBool = fmap (Bool . (== 't')) (oneOf \"ft\")\n\nparseFloat :: Parser LispVal\nparseFloat = do whole <- many1 digit\n                _ <- char '.'\n                rest <- many1 digit\n                return $ Float $ read (whole ++ \".\" ++ rest)\n\nparseComplex :: Parser LispVal\nparseComplex = do real <- parseNumber <|> parseFloat\n                  _ <- char '+'\n                  imag <- parseNumber <|> parseFloat\n                  _ <- char 'i'\n                  return $ Complex (toDouble real :+ toDouble imag)\n              where toDouble (Float d) = d\n                    toDouble (Number n) = fromInteger n\n                    toDouble n = error $ \"Expected a number, received: \" ++ show n\n\nparseRational :: Parser LispVal\nparseRational = do nom <- parseNumber\n                   _ <- char '/'\n                   den <- parseNumber\n                   return $ Rational (toNum nom % toNum den)\n                where toNum (Number n) = n\n                      toNum n = error $ \"Expected a number, received: \" ++ show n\n\n-- Recursive type parsing\nparseList :: Parser LispVal\nparseList = fmap List $ sepBy parseExp spaces\n\nparseDottedList :: Parser LispVal\nparseDottedList = do car <- endBy parseExp spaces\n                     cdr <- char '.' >> spaces >> parseExp\n                     return $ DottedList car cdr\n\nparseLists :: Parser LispVal\nparseLists = do _ <- char '('\n                x <- try parseList <|> parseDottedList\n                _ <- char ')'\n                return x\n\nparseQuoted :: Parser LispVal\nparseQuoted = char '\\'' >> parseExp >>= (\\e -> return $ List [Atom \"quote\", e])\n\n\nparseExp :: Parser LispVal\nparseExp = parseHashPrefix\n           <|> parseAtom\n           <|> parseString\n           <|> try parseFloat\n           <|> try parseComplex\n           <|> try parseRational\n           <|> parseNumber\n           <|> parseQuoted\n           <|> parseLists\n\n\nreadOrThrow :: Parser a -> String -> ThrowsError a\nreadOrThrow parser input = case parse parser \"lisp\" input of\n  Left  err -> throwError $ Parser err\n  Right val -> return val\n\nreadExpr = readOrThrow parseExp\nreadExprList = readOrThrow (endBy parseExp spaces)\n", "meta": {"hexsha": "9d049df079b8f30dc0b4f5043cef82043a40567a", "size": 4212, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Parser.hs", "max_stars_repo_name": "kimsnj/writeAscheme", "max_stars_repo_head_hexsha": "3c2e064235349406562e6bfcb786b7f9917fdace", "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/Parser.hs", "max_issues_repo_name": "kimsnj/writeAscheme", "max_issues_repo_head_hexsha": "3c2e064235349406562e6bfcb786b7f9917fdace", "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/Parser.hs", "max_forks_repo_name": "kimsnj/writeAscheme", "max_forks_repo_head_hexsha": "3c2e064235349406562e6bfcb786b7f9917fdace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3021582734, "max_line_length": 82, "alphanum_fraction": 0.5536562203, "num_tokens": 978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4366633537379375}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule Releaser.Demand.Ops\n  ( demandUniformIn3To15FixedDds\n  , demandConst9FixedDds\n  , demandConst10FixedDds\n  , demandConst11FixedDds\n  , demandUnif95_175\n  , demandUnif78_158\n  , demandExp135\n  , demandExp118\n  , demandExp105\n  ) where\n\n\nimport           Statistics.Distribution.Exponential\nimport           Statistics.Distribution.Uniform\n\nimport           SimSim\n\nimport           Releaser.Demand.Type\nimport           Releaser.SettingsPeriod\nimport           Releaser.Util\n\ndds :: Integer\ndds = 7\n\ndueDateSlack :: Time\ndueDateSlack = fromInteger dds * periodLength\n\n\ndemandUniformIn3To15FixedDds :: ConfigDemand\ndemandUniformIn3To15FixedDds = ConfigDemand (\"U(3,15) with DDS=\" <> tshow dueDateSlack) dds (\\sim -> generateOrdersUniform sim 3 15 dueDateSlack)\n\ndemandConst9FixedDds :: ConfigDemand\ndemandConst9FixedDds = ConfigDemand (\"Const(9) with DDS=\" <> tshow dueDateSlack) dds (\\sim -> generateOrdersUniform sim 9 9 dueDateSlack)\n\ndemandConst10FixedDds :: ConfigDemand\ndemandConst10FixedDds = ConfigDemand (\"Const(10) with DDS=\" <> tshow dueDateSlack) dds (\\sim -> generateOrdersUniform sim 10 10 dueDateSlack)\n\n\ndemandConst11FixedDds :: ConfigDemand\ndemandConst11FixedDds = ConfigDemand (\"Const(11) with DDS=\" <> tshow dueDateSlack) dds (\\sim -> generateOrdersUniform sim 11 11 dueDateSlack)\n\n\ndemandUnif95_175 :: ConfigDemand\ndemandUnif95_175 =\n  ConfigDemand\n    (\"Uniform interarrival-time w/ Unif(95,175) with DDS=\" <> tshow dueDateSlack)\n    dds\n    (\\sim ->\n       let pts = productTypes sim\n        in generateOrdersFixedDueDateSlack sim (uniformDistr 0.098958333 0.182291667) (uniformDistr 0.5001 (fromIntegral (length pts) + 0.4999)) dueDateSlack)\n\ndemandUnif78_158 :: ConfigDemand\ndemandUnif78_158 =\n  ConfigDemand\n    (\"Uniform interarrival-time w/ Unif(78,158) with DDS=\" <> tshow dueDateSlack)\n    dds\n    (\\sim ->\n       let pts = productTypes sim\n        in generateOrdersFixedDueDateSlack sim (uniformDistr (78 / 960) (158 / 960)) (uniformDistr 0.5001 (fromIntegral (length pts) + 0.4999)) dueDateSlack)\n\ndemandExp118 :: ConfigDemand\ndemandExp118 =\n  ConfigDemand\n    (\"Exponential interarrival-time w/ Exp(118) with DDS=\" <> tshow dueDateSlack)\n    dds\n    (\\sim ->\n       let pts = productTypes sim\n        in generateOrdersFixedDueDateSlack sim (exponential (960 / 118)) (uniformDistr 0.5001 (fromIntegral (length pts) + 0.4999)) dueDateSlack)\n\ndemandExp135 :: ConfigDemand\ndemandExp135 =\n  ConfigDemand\n    (\"Exponential interarrival-time w/ Exp(135) with DDS=\" <> tshow dueDateSlack)\n    dds\n    (\\sim ->\n       let pts = productTypes sim\n        in generateOrdersFixedDueDateSlack sim (exponential (960 / 135)) (uniformDistr 0.5001 (fromIntegral (length pts) + 0.4999)) dueDateSlack)\n\n\ndemandExp105 :: ConfigDemand\ndemandExp105 =\n  ConfigDemand\n    (\"Exponential interarrival-time w/ Exp(105) with DDS=\" <> tshow dueDateSlack)\n    dds\n    (\\sim ->\n       let pts = productTypes sim\n           -- test :: IO ()\n           -- test = do\n           --   nrs <- foldM (\\xs _ -> do\n           --                  x <- generateOrdersFixedDueDateSlack sim (exponential (960 / 105)) (uniformDistr 0.5001 (fromIntegral (length pts) + 0.4999)) dueDateSlack\n           --                  return $ length x : xs\n           --              ) [] [0..10000]\n           --   putStrLn $ \"res: \" ++ show (fromIntegral (sum nrs) / fromIntegral (length nrs))\n        in generateOrdersFixedDueDateSlack sim (exponential (960 / 105)) (uniformDistr 0.5001 (fromIntegral (length pts) + 0.4999)) dueDateSlack)\n\n\n-- interArrivalTimeDistribution :: UniformDistribution\n-- interArrivalTimeDistribution = uniformDistr (61.935483871/960) (274.285714286/960)\n\n-- productTypeDistribution :: UniformDistribution\n-- productTypeDistribution = uniformDistr 1 2\n\n-- demandExponential\n\n  -- generateOrdersFixedDueDateSlack sim interArrivalTimeDistribution productTypeDistribution dueDateSlack\n", "meta": {"hexsha": "ecfe3954848bcfeb996d7dd457ab4ddd814b23b5", "size": 3925, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Releaser/Demand/Ops.hs", "max_stars_repo_name": "schnecki/borl-releaser", "max_stars_repo_head_hexsha": "8ab5c4d73456daa3f26628315ad7a562b25e42d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Releaser/Demand/Ops.hs", "max_issues_repo_name": "schnecki/borl-releaser", "max_issues_repo_head_hexsha": "8ab5c4d73456daa3f26628315ad7a562b25e42d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Releaser/Demand/Ops.hs", "max_forks_repo_name": "schnecki/borl-releaser", "max_forks_repo_head_hexsha": "8ab5c4d73456daa3f26628315ad7a562b25e42d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0091743119, "max_line_length": 169, "alphanum_fraction": 0.7052229299, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4366132605682514}}
{"text": "{-# LANGUAGE OverloadedStrings   #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module :\n-- Copyright : (c) 2013 Boyun Tang\n-- License : BSD-style\n-- Maintainer : tangboyun@hotmail.com\n-- Stability : experimental\n-- Portability : ghc\n--\n--\n--\n-----------------------------------------------------------------------------\nmodule Main where\n\nimport           Control.Arrow\nimport           Data.Colour.Names\nimport           Data.Colour.Palette.BrewerSet\nimport qualified Data.HashMap.Strict           as H\nimport qualified Data.List                     as L\nimport qualified Data.Text                     as T\nimport qualified Data.Text.IO                  as T\nimport qualified Data.Text.Read                as T\nimport qualified Data.Vector                   as V\nimport qualified Data.Vector.Unboxed           as UV\nimport           Diagrams.Backend.Cairo\nimport           Diagrams.HeatMap\nimport           Diagrams.HeatMap.Type\nimport           Diagrams.Prelude\nimport           Statistics.Quantile\nimport           Statistics.Sample\nimport           System.Environment\nimport           System.FilePath\n\n\ncluDiffOpt :: ClustOpt\ncluDiffOpt = ClustOpt\n  { colorOpt = color2\n  , rowCluster = Nothing -- Just (eucDis,UPGMA,LeftTree)\n  , colCluster = Just (eucDis,UPGMA,BottomTree)}\n\ncolor1 = let cSet = brewerSet RdBu 11\n         in Three (cSet !! 9) white (cSet !! 1)\n\ncolor2 = Three green black red\n\nmkPara w h i j (a,b,c) = Para\n  { clustOpt = cluDiffOpt\n  , colorVal = ColorVal a b c\n  , matrixHeight = h\n  , matrixWidth = w\n  , rowTreeHeight = 0.2 * min w h\n  , colTreeHeight = 0.2 * min w h\n  , rowFontSize = 0.8 * h / i\n  , colFontSize = 0.6 * w / j\n  , legendFontSize = 0.5 * w * 0.1\n  , fontName = \"Arial\"\n  , colorBarPos = Horizontal\n  , tradeOff = Quality\n  , colTreeLineWidth = 0.5\n  , rowTreeLineWidth = 0.5\n  }\n\neucDis :: (UV.Unbox a, Num a) => UV.Vector a -> UV.Vector a -> a\neucDis vec1 vec2 = UV.sum $ UV.zipWith (\\v1 v2 -> (v1-v2)*(v1-v2)) vec1 vec2\n\ntoZscore :: UV.Vector Double -> UV.Vector Double\ntoZscore vec =\n    let (m,v) = meanVarianceUnb vec\n    in UV.map (\\e -> (e - m) / sqrt v ) vec\n\nparseTSV :: Bool -> FilePath -> FilePath -> IO Dataset\nparseTSV doNormalization datFile labelFile = do\n    sampleHash <- T.readFile labelFile >>=\n                  return . H.fromList .\n                  map (((!! 0) &&& (!! 1)) . T.split (== '\\t')) .\n                  T.lines .\n                  T.filter (/= '\\r')\n    T.readFile datFile >>=\n        return .\n        (\\(h:ts) ->\n          let sIDs = V.fromList $ tail h\n              grIDs = V.map (sampleHash `myIdx`) sIDs\n              gIDs = V.fromList $ map head ts\n              j = V.length sIDs\n              i = V.length gIDs\n              func = if doNormalization\n                     then toZscore\n                     else id\n              datum = UV.concat $ map (func . UV.fromList . map (fst . fromRight . T.double) . tail) ts\n              m = Matrix i j RowMajor datum\n          in Dataset (Just gIDs) (Just sIDs) (Just grIDs) m\n        ) . map (T.split (== '\\t')) . T.lines . T.filter (/= '\\r')\n  where\n    myIdx h k = if k `H.member` h\n                then h H.! k\n                else error $ show k\n    fromRight :: Show a => Either a b -> b\n    fromRight (Right b) = b\n    fromRight (Left a) = error $ show a\n\nmain :: IO ()\nmain = do\n   doNormal:w:h:datFile:labelFile:_ <- getArgs\n   dataset <- parseTSV (read doNormal) datFile labelFile\n   let vMin = continuousBy medianUnbiased 1 100 $ dat $ datM $ dataset\n       vMean = if (read doNormal)\n               then 0\n               else continuousBy medianUnbiased 50 100 $ dat $ datM $ dataset\n       vMax = continuousBy medianUnbiased 99 100 $ dat $ datM $ dataset\n       j = fromIntegral $ nCol $ datM dataset\n       i = fromIntegral $ nRow $ datM dataset\n       para = mkPara (read w) (read h) i j (vMin,vMean,vMax)\n   renderCairo (replaceExtension datFile \"pdf\") (mkWidth 600) $ pad 1.03 $ fst $ plotHeatMap para dataset\n\n", "meta": {"hexsha": "75778afd5c105fec7f73c8c83583b8f573bc2e75", "size": 4042, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/mkHeatmap.hs", "max_stars_repo_name": "tangboyun/diagrams-heatmap", "max_stars_repo_head_hexsha": "f9088eabbc44073ae2a0d3e5933d6df7fd507ad6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/mkHeatmap.hs", "max_issues_repo_name": "tangboyun/diagrams-heatmap", "max_issues_repo_head_hexsha": "f9088eabbc44073ae2a0d3e5933d6df7fd507ad6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/mkHeatmap.hs", "max_forks_repo_name": "tangboyun/diagrams-heatmap", "max_forks_repo_head_hexsha": "f9088eabbc44073ae2a0d3e5933d6df7fd507ad6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-07T11:35:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T11:35:48.000Z", "avg_line_length": 34.547008547, "max_line_length": 105, "alphanum_fraction": 0.5554181098, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4365667794125081}}
{"text": "{-# LANGUAGE CPP, TypeSynonymInstances, FlexibleInstances #-}\n\nmodule MyVectorType (module MyVectorType\n#ifdef VECTOR_HMATRIX\n , Matrix.toLists, Matrix.fromLists\n , Matrix.trans\n , Vector.toList, Vector.fromList\n , Vector.dim\n , Numeric.Container.vXm, Numeric.Container.sumElements\n#endif\n)\nwhere\n\n\n#ifdef VECTOR_HMATRIX\nimport qualified Data.Packed.Vector as Vector\nimport qualified Data.Packed.Matrix as Matrix \nimport qualified Numeric.Container\nimport Numeric.Container (Element, Container)\nimport Numeric.LinearAlgebra () -- instances\ntype Vector = Vector.Vector\ntype Matrix = Matrix.Matrix\ninstance Ord (Matrix Double) where\n    compare a b = compare (Matrix.toLists a) (Matrix.toLists b)\ncmap :: (Element b, Container c e) => (e -> b) -> c e -> c b\ncmap a  = Numeric.Container.cmap a\n\nadd :: Container c e => c e -> c e -> c e\nadd a = Numeric.Container.add a\n\ntransFix :: Matrix Double -> Matrix Double\ntransFix = id\n\n-- concat :: (Storable a) => [Vector a] -> Vector a\nconcat :: [Vector Double] -> Vector Double\nconcat = Vector.join\n#endif\n\n#ifdef VECTOR_VECTOR\nimport Data.Vector.Binary () -- instances\nimport Data.List (transpose)\n#ifdef VECTOR_DDOT\nimport Foreign.C.Types\nimport Foreign\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Storable.Internal as VI\n#else\nimport qualified Data.Vector as V\n#endif\n\ntype Vector a = V.Vector a\ntype Matrix a = [Vector a]\n\n#ifdef VECTOR_DDOT\nforeign import ccall \"cblas_ddot\" cblas_ddot :: CInt -> Ptr CDouble -> CInt -> Ptr CDouble -> CInt -> CDouble\nvDOTv :: Vector Double -> Vector Double -> Double\nvDOTv v1 v2 = let (fptr'1,len1) = V.unsafeToForeignPtr0 (V.unsafeCast v1)\n                  (fptr'2,len2) = V.unsafeToForeignPtr0 (V.unsafeCast v2)\n                  ptr'v1 = VI.getPtr fptr'1\n                  ptr'v2 = VI.getPtr fptr'2\n                  r = (cblas_ddot (fromIntegral len1) ptr'v1 1 ptr'v2 1)\n              in realToFrac r\nvXm :: Vector Double -> Matrix Double -> Vector Double\nvXm v m = V.fromList $ map (vDOTv v) m\n#else\nvXm :: Vector Double -> Matrix Double -> Vector Double\nvXm v m = V.fromList $ map (\\ vm -> V.sum $ V.zipWith (*) v vm) m\n#endif\n\nadd :: Vector Double -> Vector Double -> Vector Double\nadd = V.zipWith (+)\n\ncmap :: (Double -> Double) -> Vector Double -> Vector Double\ncmap = V.map\n\ntoLists :: Matrix Double -> [[Double]]\ntoLists = map V.toList\nfromLists :: [[Double]] -> Matrix Double\nfromLists = map V.fromList\ntrans :: Matrix Double -> Matrix Double\ntrans = fromLists . transpose . toLists\n\ntransFix :: Matrix Double -> Matrix Double\ntransFix = trans\n\ntoList :: Vector Double -> [Double]\ntoList = V.toList\nfromList :: [Double] -> Vector Double\nfromList = V.fromList\n\nsumElements :: Vector Double -> Double\nsumElements = V.sum\n\ndim :: Vector Double -> Int\ndim = V.length\n\nconcat :: [Vector a] -> Vector a\nconcat = V.concat\n#endif\n\n-- #ifdef VECTOR_DPH\n-- import qualified Prelude\n-- import Prelude ((.), ($))\n-- -- import Data.Array.Parallel\n-- -- import Data.Array.Parallel.Prelude\n-- import Data.Array.Parallel.Prelude.Double\n-- import Data.Array.Parallel.Prelude.Int (Int)\n-- import Data.Array.Parallel.Unlifted as V\n-- import Data.List (transpose)\n--  \n-- type Vector a = V.Array a\n-- type Matrix a = [Vector a]\n--  \n-- vXm :: Vector Double -> Matrix Double -> Vector Double\n-- vXm v m = Prelude.map (\\ vm -> V.sum $ V.zipWith (*) v vm) m\n--  \n-- add :: Vector Double -> Vector Double -> Vector Double\n-- add = V.zipWith (+)\n--  \n-- cmap :: (Double -> Double) -> Vector Double -> Vector Double\n-- cmap = V.map\n--  \n-- toLists :: Matrix Double -> [[Double]]\n-- toLists = V.toList . V.map V.toList\n-- fromLists :: [[Double]] -> Matrix Double\n-- fromLists = V.map V.fromList . V.fromList\n-- trans :: Matrix Double -> Matrix Double\n-- trans = fromLists . transpose . toLists\n--  \n-- transFix :: Matrix Double -> Matrix Double\n-- transFix = trans\n--  \n-- toList :: Vector Double -> [Double]\n-- toList = V.toList\n-- fromList :: [Double] -> Vector Double\n-- fromList = V.fromList\n--  \n-- sumElements :: Vector Double -> Double\n-- sumElements = V.sum\n--  \n-- dim :: Vector Double -> Int\n-- dim = V.length\n--  \n-- #endif\n\n\n\n", "meta": {"hexsha": "99bdedb63cb72fd9bd4e1692badc7e3b3d9ad27b", "size": 4133, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/MyVectorType.hs", "max_stars_repo_name": "Tener/deeplearning-thesis", "max_stars_repo_head_hexsha": "c56866bf6f48db3185b4b62348d292bf39a7a2af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-07-12T21:56:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T22:42:27.000Z", "max_issues_repo_path": "lib/MyVectorType.hs", "max_issues_repo_name": "Tener/deeplearning-thesis", "max_issues_repo_head_hexsha": "c56866bf6f48db3185b4b62348d292bf39a7a2af", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/MyVectorType.hs", "max_forks_repo_name": "Tener/deeplearning-thesis", "max_forks_repo_head_hexsha": "c56866bf6f48db3185b4b62348d292bf39a7a2af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-02-03T20:45:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-19T11:44:51.000Z", "avg_line_length": 27.9256756757, "max_line_length": 109, "alphanum_fraction": 0.6757803049, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.43636886128100205}}
{"text": "{-# LANGUAGE BangPatterns      #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE Strict            #-}\n{-# LANGUAGE StrictData        #-}\nmodule Utils.BLAS where\n\nimport           Data.Complex\nimport           Data.Vector.Storable            as VS\nimport           Foreign.CUDA.BLAS               as BLAS\nimport           Foreign.CUDA.Driver             as CUDA\nimport           Foreign.Marshal\nimport           Numerical.HBLAS.BLAS.FFI\nimport           Numerical.HBLAS.BLAS.FFI.Level1\nimport           Numerical.HBLAS.BLAS.FFI.Level3\n\ntype BLASMMT e\n   = Int -> Int -> Int -> VS.Vector e -> VS.Vector e -> IO (VS.Vector e)\n   \ntype BLASDOTU e = VS.Vector e -> VS.Vector e -> IO e\n\nclass BLAS a where\n  gemmBLAS :: BLASMMT a\n  dotuBLAS :: BLASDOTU a\n\n \ninstance BLAS Double where\n  {-# INLINE gemmBLAS #-}\n  gemmBLAS m' n' k' a b = do\n    let output = VS.replicate (m' * n') 0\n        !m = fromIntegral m'\n        !n = fromIntegral n'\n        !k = fromIntegral k'\n    unsafeWith a $ \\aPtr ->\n      unsafeWith b $ \\bPtr ->\n        unsafeWith output $ \\cPtr ->\n          cblas_dgemm_safe\n            (encodeOrder BLASRowMajor)\n            (encodeTranspose BlasNoTranspose)\n            (encodeTranspose BlasNoTranspose)\n            m\n            n\n            k\n            1\n            aPtr\n            k\n            bPtr\n            n\n            0\n            cPtr\n            n\n    return output\n  {-# INLINE dotuBLAS #-}\n  dotuBLAS vec1 vec2 =\n    unsafeWith vec1 $ \\ptr1 ->\n      unsafeWith vec2 $ \\ptr2 ->\n        cblas_ddot_safe (fromIntegral . VS.length $ vec1) ptr1 1 ptr2 1\n\ninstance BLAS (Complex Double) where\n  {-# INLINE gemmBLAS #-}\n  gemmBLAS m' n' k' a b = do\n    let output = VS.replicate (m' * n') 0\n        !m = fromIntegral m'\n        !n = fromIntegral n'\n        !k = fromIntegral k'\n    with 1 $ \\alphaPtr ->\n      with 0 $ \\betaPtr ->\n        unsafeWith a $ \\aPtr ->\n          unsafeWith b $ \\bPtr ->\n            unsafeWith output $ \\cPtr ->\n              cblas_zgemm_safe\n                (encodeOrder BLASRowMajor)\n                (encodeTranspose BlasNoTranspose)\n                (encodeTranspose BlasNoTranspose)\n                m\n                n\n                k\n                alphaPtr\n                aPtr\n                k\n                bPtr\n                n\n                betaPtr\n                cPtr\n                n\n    return output\n  {-# INLINE dotuBLAS #-}\n  dotuBLAS vec1 vec2 = do\n    let output = VS.singleton 0\n    unsafeWith vec1 $ \\ptr1 ->\n      unsafeWith vec2 $ \\ptr2 ->\n        unsafeWith output $ \\outPtr ->\n          cblas_zdotu_safe\n            (fromIntegral . VS.length $ vec1)\n            ptr1\n            1\n            ptr2\n            1\n            outPtr\n    return . VS.head $ output\n\n\n\ntype CUBLASMMT a b e\n   = Handle -> Int -> Int -> Int -> a e -> b e -> IO (VS.Vector e)\n\nclass CUBLAS a where\n  gemmCuBLAS :: CUBLASMMT DevicePtr DevicePtr a\n\ninstance CUBLAS Float where\n  {-# INLINE gemmCuBLAS #-}\n  gemmCuBLAS handle !m !n !k matA matB = do\n    let !sizeC = m * n\n        output = VS.replicate sizeC 0\n    with 1 $ \\alpha ->\n      with 0 $ \\beta ->\n        CUDA.allocaArray sizeC $ \\matC ->\n          unsafeWith output $ \\outputPtr -> do\n            sgemm handle N N n m k alpha matB n matA k beta matC n\n            CUDA.peekArray sizeC matC outputPtr\n    return output\n\ninstance CUBLAS Double where\n  {-# INLINE gemmCuBLAS #-}\n  gemmCuBLAS handle !m !n !k matA matB = do\n    let !sizeC = m * n\n        output = VS.replicate sizeC 0\n    with 1 $ \\alpha ->\n      with 0 $ \\beta ->\n        CUDA.allocaArray sizeC $ \\matC ->\n          unsafeWith output $ \\outputPtr -> do\n            dgemm handle N N n m k alpha matB n matA k beta matC n\n            CUDA.peekArray sizeC matC outputPtr\n    return output\n\ninstance CUBLAS (Complex Float) where\n  {-# INLINE gemmCuBLAS #-}\n  gemmCuBLAS handle !m !n !k matA matB = do\n    let !sizeC = m * n\n        output = VS.replicate sizeC 0\n    with 1 $ \\alpha ->\n      with 0 $ \\beta ->\n        CUDA.allocaArray sizeC $ \\matC ->\n          unsafeWith output $ \\outputPtr -> do\n            cgemm handle N N n m k alpha matB n matA k beta matC n\n            CUDA.peekArray sizeC matC outputPtr\n    return output\n\ninstance CUBLAS (Complex Double) where\n  {-# INLINE gemmCuBLAS #-}\n  gemmCuBLAS handle !m !n !k matA matB = do\n    let !sizeC = m * n\n        output = VS.replicate sizeC 0\n    with 1 $ \\alpha ->\n      with 0 $ \\beta ->\n        CUDA.allocaArray sizeC $ \\matC ->\n          unsafeWith output $ \\outputPtr -> do\n            zgemm handle N N n m k alpha matB n matA k beta matC n\n            CUDA.peekArray sizeC matC outputPtr\n    return output\n\n{-# INLINE unsafeWithGPU #-}\nunsafeWithGPU :: (Storable e) => VS.Vector e -> (DevicePtr e -> IO b) -> IO b\nunsafeWithGPU vec f = do\n  let !len = VS.length vec\n  CUDA.allocaArray len $ \\devPtr -> do\n    unsafeWith vec $ \\ptr -> CUDA.pokeArray len ptr devPtr\n    f devPtr\n\n{-# INLINE gemmCuBLAS10 #-}\ngemmCuBLAS10 :: (CUBLAS e, Storable e) => CUBLASMMT VS.Vector DevicePtr e\ngemmCuBLAS10 handle m n k a matB =\n  unsafeWithGPU a $ \\matA -> gemmCuBLAS handle m n k matA matB\n\n{-# INLINE gemmCuBLAS01 #-}\ngemmCuBLAS01 :: (CUBLAS e, Storable e) => CUBLASMMT DevicePtr VS.Vector e\ngemmCuBLAS01 handle m n k matA b =\n  unsafeWithGPU b $ \\matB -> gemmCuBLAS handle m n k matA matB\n\n{-# INLINE gemmCuBLAS11 #-}\ngemmCuBLAS11 :: (CUBLAS e, Storable e) => CUBLASMMT VS.Vector VS.Vector e\ngemmCuBLAS11 handle m n k a b =\n  unsafeWithGPU a $ \\matA ->\n    unsafeWithGPU b $ \\matB -> gemmCuBLAS handle m n k matA matB\n", "meta": {"hexsha": "038acc5a4eb34e529885dd9c30576930aa7ab867", "size": 5559, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Utils/BLAS.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/Utils/BLAS.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/Utils/BLAS.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 30.2119565217, "max_line_length": 77, "alphanum_fraction": 0.5653894585, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.43636885505561884}}
{"text": "{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE RecordWildCards       #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-|\nModule      : Grenade.Layers.Deconvolution\nDescription : Deconvolution layer\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n\nA deconvolution layer is in many ways a convolution layer in reverse.\nIt learns a kernel to apply to each pixel location, spreading it out\ninto a larger layer.\n\nThis layer is important for image generation tasks, such as GANs on\nimages.\n-}\nmodule Grenade.Layers.Deconvolution (\n    Deconvolution (..)\n  , Deconvolution' (..)\n  ) where\n\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Serialize\nimport           Data.Singletons.TypeLits hiding (natVal)\n\nimport           GHC.TypeLits\n\nimport Control.DeepSeq (NFData (..))\n\n\nimport           Numeric.LinearAlgebra hiding ( uniformSample, konst )\nimport qualified Numeric.LinearAlgebra as LA\nimport           Numeric.LinearAlgebra.Static hiding ((|||), build, toRows)\n\nimport           Grenade.Core\nimport           Grenade.Layers.Internal.Convolution\nimport           Grenade.Layers.Internal.Update\n\n-- | A Deconvolution layer for a neural network.\n--   This uses the im2col Convolution trick popularised by Caffe.\n--\n--   The Deconvolution layer is a way of spreading out a single response\n--   into a larger image, and is useful in generating images.\n--\ndata Deconvolution :: Nat -- Number of channels, for the first layer this could be RGB for instance.\n                   -> Nat -- Number of filters, this is the number of channels output by the layer.\n                   -> Nat -- The number of rows in the kernel filter\n                   -> Nat -- The number of column in the kernel filter\n                   -> Nat -- The row stride of the Deconvolution filter\n                   -> Nat -- The columns stride of the Deconvolution filter\n                   -> * where\n  Deconvolution :: ( KnownNat channels\n                   , KnownNat filters\n                   , KnownNat kernelRows\n                   , KnownNat kernelColumns\n                   , KnownNat strideRows\n                   , KnownNat strideColumns\n                   , KnownNat kernelFlattened\n                   , kernelFlattened ~ (kernelRows * kernelColumns * filters))\n                 => !(L kernelFlattened channels) -- The kernel filter weights\n                 -> !(L kernelFlattened channels) -- The last kernel update (or momentum)\n                 -> Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns\n\ninstance NFData (Deconvolution c f k k' s s') where \n  rnf (Deconvolution a b) = rnf a `seq` rnf b `seq` ()\n\n\ndata Deconvolution' :: Nat -- Number of channels, for the first layer this could be RGB for instance.\n                    -> Nat -- Number of filters, this is the number of channels output by the layer.\n                    -> Nat -- The number of rows in the kernel filter\n                    -> Nat -- The number of column in the kernel filter\n                    -> Nat -- The row stride of the Deconvolution filter\n                    -> Nat -- The columns stride of the Deconvolution filter\n                    -> * where\n  Deconvolution' :: ( KnownNat channels\n                  , KnownNat filters\n                  , KnownNat kernelRows\n                  , KnownNat kernelColumns\n                  , KnownNat strideRows\n                  , KnownNat strideColumns\n                  , KnownNat kernelFlattened\n                  , kernelFlattened ~ (kernelRows * kernelColumns * filters))\n               => !(L kernelFlattened channels) -- The kernel filter gradient\n               -> Deconvolution' channels filters kernelRows kernelColumns strideRows strideColumns\n\ninstance NFData (Deconvolution' c f k k' s s') where \n  rnf (Deconvolution' a) = rnf a `seq` ()\n\n\ninstance Show (Deconvolution c f k k' s s') where\n  show (Deconvolution a _) = renderConv a\n    where\n      renderConv mm =\n        let m  = extract mm\n            ky = fromIntegral $ natVal (Proxy :: Proxy k)\n            rs = LA.toColumns m\n            ms = map (take ky) $ toLists . reshape ky <$> rs\n\n            render n'  | n' <= 0.2  = ' '\n                       | n' <= 0.4  = '.'\n                       | n' <= 0.6  = '-'\n                       | n' <= 0.8  = '='\n                       | otherwise =  '#'\n\n            px = (fmap . fmap . fmap) render ms\n        in unlines $ foldl1 (zipWith (\\a' b' -> a' ++ \"   |   \" ++ b')) $ px\n\ninstance ( KnownNat c\n         , KnownNat f\n         , KnownNat k\n         , KnownNat k'\n         , KnownNat s\n         , KnownNat s'\n         , KnownNat ((k * k') * f)\n         , KnownNat ((k * k') * c)\n         , KnownNat (c * ((k * k') * f))) => RandomLayer (Deconvolution c f k k' s s') where\n  createRandomWith m gen = do\n    wN <- getRandomMatrix i i m gen\n    let mm = konst 0\n    return $ Deconvolution wN mm\n    where i = natVal (Proxy :: Proxy ((k * k') * c))\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * filters)\n         ) => UpdateLayer (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) where\n  type Gradient (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) = (Deconvolution' channels filters kernelRows kernelColumns strideRows strideColumns)\n  runUpdate LearningParameters {..} (Deconvolution oldKernel oldMomentum) (Deconvolution' kernelGradient) =\n    let (newKernel, newMomentum) = descendMatrix learningRate learningMomentum learningRegulariser oldKernel kernelGradient oldMomentum\n    in Deconvolution newKernel newMomentum\n\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * filters)\n         ) => Serialize (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) where\n  put (Deconvolution w _) = putListOf put . toList . flatten . extract $ w\n  get = do\n      let f  = fromIntegral $ natVal (Proxy :: Proxy channels)\n      wN    <- maybe (fail \"Vector of incorrect size\") return . create . reshape f . LA.fromList =<< getListOf get\n      let mm = konst 0\n      return $ Deconvolution wN mm\n\n-- | A two dimentional image may have a Deconvolution filter applied to it\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , ((inputRows - 1) * strideRows) ~ (outputRows - kernelRows)\n         , ((inputCols - 1) * strideCols) ~ (outputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * filters)\n         , KnownNat (outputRows * filters)\n         ) => Layer (Deconvolution 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) where\n  type Tape (Deconvolution 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\n-- | A two dimentional image may have a Deconvolution filter applied to it\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , ((inputRows - 1) * strideRows) ~ (outputRows - kernelRows)\n         , ((inputCols - 1) * strideCols) ~ (outputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * 1)\n         , KnownNat (outputRows * 1)\n         ) => Layer (Deconvolution 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) where\n  type Tape (Deconvolution 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D fore :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D fore)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\n-- | A two dimentional image may have a Deconvolution filter applied to it\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , ((inputRows - 1) * strideRows) ~ (outputRows - kernelRows)\n         , ((inputCols - 1) * strideCols) ~ (outputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * 1)\n         , KnownNat (outputRows * 1)\n         , KnownNat channels\n         ) => Layer (Deconvolution channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) where\n  type Tape (Deconvolution channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D fore :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D fore)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1))\n\n-- | A three dimensional image (or 2d with many channels) can have\n--   an appropriately sized Deconvolution filter run across it.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , KnownNat channels\n         , ((inputRows - 1) * strideRows) ~ (outputRows - kernelRows)\n         , ((inputCols - 1) * strideCols) ~ (outputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * filters)\n         , KnownNat (outputRows * filters)\n         ) => Layer (Deconvolution channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) where\n\n  type Tape (Deconvolution channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (Deconvolution kernel _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n\n        c  = vid2col 1 1 1 1 ix iy ex\n\n        mt = c LA.<> tr ek\n\n        r  = col2vid kx ky sx sy ox oy mt\n        rs = fromJust . create $ r\n    in  (S3D input, S3D rs)\n  runBackwards (Deconvolution kernel _) (S3D input) (S3D dEdy) =\n    let ex = extract input\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n\n        c  = vid2col 1 1 1 1 ix iy ex\n\n        eo = extract dEdy\n        ek = extract kernel\n\n        vs = vid2col kx ky sx sy ox oy eo\n\n        kN = fromJust . create . tr $ tr c LA.<> vs\n\n        dW = vs LA.<> ek\n\n        xW = col2vid 1 1 1 1 ix iy dW\n    in  (Deconvolution' kN, S3D . fromJust . create $ xW)\n\n\n-------------------- GNum instances --------------------\n\n\ninstance (KnownNat strideCols,KnownNat strideRows,KnownNat kernelCols,KnownNat kernelRows,KnownNat filters,KnownNat channels,KnownNat ((kernelRows * kernelCols) * filters),KnownNat\n                          ((kernelRows * kernelCols) * channels)) => GNum (Deconvolution channels filters kernelRows kernelCols strideRows strideCols) where\n  n |* (Deconvolution w m) = Deconvolution (fromRational n * w) m\n  (Deconvolution w m) |+ (Deconvolution w2 m2)  = Deconvolution (fromRational 0.5 * (w+w2)) (fromRational 0.5 * (m+m2))\n  gFromRational r = Deconvolution (fromRational r) (fromRational r)\n\n\ninstance (KnownNat strideCols,KnownNat strideRows,KnownNat kernelCols,KnownNat kernelRows,KnownNat filters,KnownNat channels,KnownNat ((kernelRows * kernelCols) * filters),KnownNat\n                          ((kernelRows * kernelCols) * channels)) => GNum (Deconvolution' channels filters kernelRows kernelCols strideRows strideCols) where\n  _ |* (Deconvolution' g) = Deconvolution' g\n  (Deconvolution' g) |+ (Deconvolution' g2)  = Deconvolution' (fromRational 0.5 * (g+g2)) \n  gFromRational r = Deconvolution' (fromRational r)\n\n  \n", "meta": {"hexsha": "58c6d1a2e0e997963ef60c3b6a0750406359d4c5", "size": 14231, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Deconvolution.hs", "max_stars_repo_name": "koenigmaximilian/grenade", "max_stars_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Grenade/Layers/Deconvolution.hs", "max_issues_repo_name": "koenigmaximilian/grenade", "max_issues_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Deconvolution.hs", "max_forks_repo_name": "koenigmaximilian/grenade", "max_forks_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6121794872, "max_line_length": 198, "alphanum_fraction": 0.6346707891, "num_tokens": 3632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4361847682315388}}
{"text": "module SchemeParser \n  (readExpr,\n   readExprList) where\n\nimport Text.ParserCombinators.Parsec hiding (spaces)\nimport Control.Monad\nimport Numeric\nimport Data.Ratio\nimport Data.Complex\nimport qualified Data.Vector as V\nimport CommonTypes\nimport Control.Monad.Except\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany space\n\nescapedCharacters :: Parser Char\nescapedCharacters = do\n                      char '\\\\'\n                      x <- oneOf \"\\\\\\\"nrt\"\n                      return $ case x of\n                                 '\\\\' -> x\n                                 '\"'  -> x\n                                 'n'  -> '\\n'\n                                 't'  -> '\\t'\n                                 'r'  -> '\\r'\n\nparseString :: Parser LispVal\nparseString = do\n               char '\"'\n               x <- many $ escapedCharacters <|> noneOf \"\\\\\\\"\"\n               char '\"'\n               return $ String x\n\nparseBool :: Parser LispVal\nparseBool = try $ do\n              char '#'\n              (char 't' >> return (Bool True)) <|> (char 'f' >> return (Bool False))\n\nparseAtom :: Parser LispVal\nparseAtom = do\n             first <- letter <|> symbol\n             rest <- many $ letter <|> digit <|> symbol\n             let atom = first:rest\n             return $ Atom atom\n\nparseDecimal :: Parser LispVal\nparseDecimal = Number . read <$> many1 digit\n\nmyParseDecimal :: Parser LispVal\nmyParseDecimal = many1 digit >>= (return . Number . read)\n\nparseDecimal2 :: Parser LispVal\nparseDecimal2 = do\n                  try $ string \"#d\"\n                  x <- many1 digit\n                  (return . Number . read) x\n\nparseOct :: Parser LispVal\nparseOct = do\n              try $ string \"#o\"\n              x <- many1 octDigit\n              (return . Number . oct2dig) x\n\nparseHex :: Parser LispVal\nparseHex = do\n            try $ string \"#x\"\n            x <- many1 hexDigit\n            (return . Number . hex2dig) x\n\nparseBin :: Parser LispVal\nparseBin = do\n            try $ string \"#b\"\n            x <- many1 $ oneOf \"10\"\n            (return . Number . bin2dig) x\n\noct2dig x = fst $ head $ readOct x\n\nhex2dig x = fst $ head $ readHex x\n\nbin2dig  = bin2dig' 0\nbin2dig' digint \"\" = digint\nbin2dig' digint (x:xs) = let old = 2 * digint + (if x == '0' then 0 else 1)\n                            in bin2dig' old xs\n\nparseNumber :: Parser LispVal\nparseNumber = myParseDecimal\n              <|> parseDecimal2\n              <|> parseHex\n              <|> parseBin\n              <|> parseOct\n\nparseCharacter :: Parser LispVal\nparseCharacter = do\n                  try $ string \"#\\\\\"\n                  value <- try (string \"newline\" <|> string \"space\")\n                    <|> do { x <- anyChar; notFollowedBy alphaNum ; return [x]}\n                  return $ Character $ case value of \n                                         \"space\"    -> ' '\n                                         \"newline\"  -> '\\n'\n                                         otherwise  -> (head value)\n\nparseFloat :: Parser LispVal\nparseFloat = do\n              x <- many1 digit\n              char '.'\n              y <- many1 digit\n              return $ Float (fst.head $ readFloat (x++\".\"++y))\n\nparseRatio :: Parser LispVal\nparseRatio = do\n              x <- many1 digit\n              char '/'\n              y <- many1 digit\n              return $ Ratio (read x % read y)\n\ntoDouble :: LispVal -> Double\ntoDouble (Float d) = d\ntoDouble (Number n) = fromInteger n\n  \nparseComplex :: Parser LispVal\nparseComplex = do\n                x <- (try parseFloat <|> parseDecimal)\n                char '+'\n                y <- (try parseFloat <|> parseDecimal)\n                char 'i'\n                return $ Complex (toDouble x :+ toDouble y)\n\nparseList :: Parser LispVal\nparseList = liftM List $ sepBy parseExpr spaces\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n                   head <- endBy parseExpr spaces\n                   tail <- char '.' >> spaces >> parseExpr \n                   return $ DottedList head tail\n\nparseQuoted :: Parser LispVal\nparseQuoted = do\n               char '\\''\n               x <- parseExpr \n               return $ List [Atom \"quote\", x]\n\nparseQuasiQuoted :: Parser LispVal\nparseQuasiQuoted = do\n                    char '`'\n                    x <- parseExpr\n                    return $ List [Atom \"quasiquote\", x]\n\nparseUnQuote :: Parser LispVal\nparseUnQuote = do\n                char ','\n                x <- parseExpr\n                return $ List [Atom \"unquote\", x]\n\nparseVector :: Parser LispVal\nparseVector = do \n                vectorValues <- sepBy parseExpr spaces\n                return $ Vector (V.fromList vectorValues)\n\nparseExpr :: Parser LispVal\nparseExpr = parseAtom\n            <|> parseString\n            <|> try parseComplex\n            <|> try parseFloat\n            <|> try parseRatio\n            <|> try parseNumber\n            <|> try parseBool\n            <|> try parseCharacter\n            <|> parseQuoted \n            <|> parseQuasiQuoted\n            <|> parseUnQuote\n            <|> try  (do\n                        string \"#(\"\n                        x <- parseVector \n                        char ')'\n                        return x)\n            <|> do \n                  char '('\n                  x <- try parseList <|> parseDottedList \n                  char ')'\n                  return x\n\nreadOrThrow :: Parser a -> String -> ThrowsError a\nreadOrThrow parser input = case parse parser \"lisp\" input of\n                   Left err  -> throwError $ Parser err\n                   Right val -> return val\n\nreadExpr = readOrThrow parseExpr\nreadExprList = readOrThrow (endBy parseExpr spaces)\n", "meta": {"hexsha": "30826664d088a96f28ac062812e82864207cb096", "size": 5673, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SchemeParser.hs", "max_stars_repo_name": "Xcode23/scheme-interpreter", "max_stars_repo_head_hexsha": "71eaebfe4a26798111a1a1c8aee20d7d3db69c12", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SchemeParser.hs", "max_issues_repo_name": "Xcode23/scheme-interpreter", "max_issues_repo_head_hexsha": "71eaebfe4a26798111a1a1c8aee20d7d3db69c12", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SchemeParser.hs", "max_forks_repo_name": "Xcode23/scheme-interpreter", "max_forks_repo_head_hexsha": "71eaebfe4a26798111a1a1c8aee20d7d3db69c12", "max_forks_repo_licenses": ["BSD-3-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.2422680412, "max_line_length": 84, "alphanum_fraction": 0.4909219108, "num_tokens": 1300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4355352674579237}}
{"text": "{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n{-# LANGUAGE DataKinds, FlexibleContexts, FlexibleInstances, GADTs        #-}\n{-# LANGUAGE MultiParamTypeClasses, NoMonomorphismRestriction             #-}\n{-# LANGUAGE OverloadedStrings, PolyKinds, TypeApplications, TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances                                         #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults -fno-warn-orphans -Wall #-}\nmodule Main where\nimport Cases\n\nimport           Algebra.Bridge.Singular\nimport           Algebra.Field.Prime\nimport           Algebra.Prelude.Core\nimport           Control.Monad                   (void)\nimport qualified Data.Text                       as T\nimport qualified Data.Vector.Unboxed             as V\nimport           Prelude                         (read)\nimport           Statistics.Resampling\nimport           Statistics.Resampling.Bootstrap\nimport           Statistics.Types\nimport qualified System.Random.MWC               as Rand\n\nbenchIdeal :: IsSingularPolynomial poly => Text -> Ideal poly -> IO Double\nbenchIdeal fun i = fmap ((/1000) . read . T.unpack) $ singular $\n  toProg fun i\n\ntoProg :: (SingularOrder (Arity poly) (MOrder poly), SingularCoeff (Coefficient poly), IsOrderedPolynomial poly) => Text -> Ideal poly -> Text\ntoProg fun i =\n  let expr = funE fun [idealE' i]\n  in prettySingular $ do\n    directC \"system(\\\"--ticks-per-sec\\\", 1000000)\"\n    void $ ringC \"R\" expr\n    declOnlyC IdealT \"G\"\n    directC \"timer=1\"\n    directC \"int t=rtimer\"\n    letC \"G\" expr\n    directC \"print(rtimer-t)\"\n    directC \"exit\"\n\nanalyse :: (IsSingularPolynomial poly) => String -> Text -> Ideal poly -> IO ()\nanalyse lab fun ideal = do\n  gen <- Rand.create\n  i2Gr <- V.replicateM 50 $ benchIdeal fun ideal\n  res  <- resample gen [Mean, StdDev] 1000 i2Gr\n  let [Estimate mn (ConfInt lbmn ubmn _) ,Estimate dv _]\n        = bootstrapBCA cl95 i2Gr res\n  putStrLn lab\n  mapM_ (putStrLn . ('\\t':))\n    [\"Mean:\\t\" ++ show mn ++ \"(ms)\"\n    ,\"MeanLB:\\t\" ++ show lbmn\n    ,\"MeanUB:\\t\" ++ show ubmn\n    ,\"StdDev:\\t\" ++ show dv\n    ]\n\nrunTestCases :: (IsMonomialOrder n o, KnownNat n)\n             => String -> Ideal (OrderedPolynomial Rational o n) -> IO ()\nrunTestCases lab i = do\n  analyse (lab ++ \" (Q, Lex, Sing(gr))\") \"groebner\" $ fmap (changeOrder Lex) i\n  analyse (lab ++ \" (Q, Lex, Sing(sba))\") \"sba\" $ fmap (changeOrder Lex) i\n  analyse (lab ++ \" (Q, Grevlex, Sing(gr))\") \"groebner\" $ fmap (changeOrder Grevlex) i\n  analyse (lab ++ \" (Q, Grevlex, Sing(sba))\") \"sba\" $ fmap (changeOrder Grevlex) i\n  analyse (lab ++ \" (F_65521, Lex, Sing(gr))\") \"groebner\" $ fmap (mapCoeff ratToF . changeOrder Lex) i\n  analyse (lab ++ \" (F_65521, Lex, Sing(sba))\") \"sba\" $ fmap (mapCoeff ratToF . changeOrder Lex) i\n  analyse (lab ++ \" (F_65521, Grevlex, Sing(gr))\") \"groebner\" $ fmap (mapCoeff ratToF . changeOrder Grevlex) i\n  analyse (lab ++ \" (F_65521, Grevlex, Sing(sba))\") \"sba\" $ fmap (mapCoeff ratToF . changeOrder Grevlex) i\n\nmain :: IO ()\nmain = do\n  runTestCases \"Cyclic-4\" $ cyclic (sing :: Sing 4)\n  runTestCases \"Cyclic-5\" $ cyclic (sing :: Sing 5)\n  runTestCases \"Cyclic-6\" $ cyclic (sing :: Sing 6)\n  runTestCases \"Katsura-5\" $ katsura (sing :: Sing 5)\n  runTestCases \"Katsura-6\" $ katsura (sing :: Sing 6)\n  runTestCases \"Katsura-7\" $ katsura (sing :: Sing 7)\n\nratToF :: Rational -> F 65521\nratToF = modRat'\n", "meta": {"hexsha": "cf9e9f533621db9805ffe343be4da2b4d84e1bdd", "size": 3341, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "halg-algorithms/bench/singular-heavy-bench.hs", "max_stars_repo_name": "ldr709/computational-algebra", "max_stars_repo_head_hexsha": "3576a27006a5bb3af28849a6042e245312c4a864", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "halg-algorithms/bench/singular-heavy-bench.hs", "max_issues_repo_name": "ldr709/computational-algebra", "max_issues_repo_head_hexsha": "3576a27006a5bb3af28849a6042e245312c4a864", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "halg-algorithms/bench/singular-heavy-bench.hs", "max_forks_repo_name": "ldr709/computational-algebra", "max_forks_repo_head_hexsha": "3576a27006a5bb3af28849a6042e245312c4a864", "max_forks_repo_licenses": ["BSD-3-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.3896103896, "max_line_length": 142, "alphanum_fraction": 0.6297515714, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.43544671214572644}}
{"text": "{-# LANGUAGE Strict, OverloadedStrings #-}\nmodule GradeParser (\n    outOf\n  , outOfSafe\n  , eachOutOf\n  , eachOutOfSafe\n  , stats\n  , histOutput\n  , printStats\n  , printStatsHist\n  ) where\n\nimport qualified Data.ByteString as B\nimport Grade\nimport qualified Data.Vector as T\nimport Data.Csv hiding ((.=))\nimport ShowByteString\nimport qualified Data.HashMap.Strict as M\nimport Control.Monad.Reader\nimport Control.Applicative\nimport Histogram\nimport Data.List\nimport Statistics.Sample\nimport CSVmonad\nimport System.Process\n\n\noutOf :: Field -> Double -> CSVmonad Grade\noutOf s o = ReaderT (\\v -> ((/. o) <$> v .: s) <|> pure (absent o))\n\neachOutOf s o = ReaderT (\\v -> sequence (map (parseGrade o) $ M.elems $ M.filterWithKey (\\k _ -> B.isPrefixOf s k) v))\n\n\noutOfSafe :: Field -> Double -> CSVmonad Grade\noutOfSafe s o = ReaderT (\\v -> (chkGrade o <$> v .: s) <|> pure (absent o))\n\neachOutOfSafe s o = ReaderT (\\v -> sequence (map (parseGradeSafe o) $ M.elems $ M.filterWithKey (\\k _ -> B.isPrefixOf s k) v))\n\nchkGrade :: Double -> Double -> Grade\nchkGrade o n = if n <= o && n >= 0 then n /. o else  outoferror\n\nchkGrade' :: Double -> Double -> Grade\nchkGrade' _ _ = outoferror\n\nparseGrade o g = ((/.o) <$> parseField g) <|> pure (absent o)\n\nparseGradeSafe o g = (chkGrade o <$> parseField g) <|> pure (absent o)\n\n\n\ngetRight (Right x) = x\ngetRight (Left e) = error $ show e\n\n\n\nstats :: (T.Vector Double -> b) -> CSVmonad Grade -> T.Vector NamedRecord -> Either GradeErrors b\nstats f l v = fmap f $ sequence $ T.filter isNotAbsent $ fmap (marksEither . getRight . runParser .  runReaderT l ) v\n  where isNotAbsent (Left (Absent _)) = False\n        isNotAbsent _ = True\n\nhistOutput :: Double -> FilePath -> CSVmonad Grade -> T.Vector NamedRecord -> IO ()\nhistOutput m s l v = case stats (histogram (assignBin m) . T.toList) l v of\n                        Right a -> histToChart s a >> writeHist \"distribution.txt\" a >> callCommand \"perl -lane 'print $F[0], \\\"\\t\\\", \\\"=\\\" x ($F[1] / 1)' distribution.txt\" >> return ()\n                        --Right a -> histToChart s a >> writeHist \"distribution.txt\" a >> createProcess (shell \"perl -lane 'print $F[0], \\\"\\t\\\", \\\"=\\\" x ($F[1] / 1)' distribution.txt\") >> return ()\n                        Left e -> print e\n\n\neitherPrintDouble (Right x) = print $ roundTo 1 x\neitherPrintDouble (Left x) = print x\n\nprintStat n s l y = putStrLn n >> eitherPrintDouble (stats s l y) >> putStrLn \"\"\n\n--printStats l y = do printStat \"The Mean\" mean l y\n--                    printStat \"The Standard deviation\" stdDev l y\n--                    printStat \"The Median\" median l y\n--                    histOutput 10 \"histogram.png\" l y\n--\n--printStats l y = do let m = getRight $ stats mean l y\n--                    let s = getRight $ stats stdDev l y\n--                    let me = getRight $ stats median l y\n--                    printStat \"The Mean\" mean l y\n--                    printStat \"The Standard deviation\" stdDev l y\n--                    printStat \"The Median\" median l y\n--                    histOutput 5 \"histogram.png\" l y\n--                    let sugg= (\"      O: \" ++ show (roundTo 1 $ m + 1.65*s) ++\"\\n      \"++ \"A: \" ++ show (roundTo 1 $ m + 0.85*s) ++\"\\n      \"++ \"B: \" ++ show (roundTo 1 $ m) ++\"\\n      \"++ \"C: \" ++ show (roundTo 1 $ m - s) ++\"\\n      \"++ \"D: \" ++ show (roundTo 1 $ me / 2))\n--                    putStrLn sugg\n--                    writeFile \"suggested\" sugg\n\nprintStats = printStatsHist 10\nprintStatsHist  h l y = do let m = getRight $ stats mean l y\n                           let s = getRight $ stats stdDev l y\n                           let me = getRight $ stats median l y\n                           printStat \"The Mean\" mean l y\n                           printStat \"The Standard deviation\" stdDev l y\n                           printStat \"The Median\" median l y\n                           histOutput h \"histogram.png\" l y\n                           let sugg= (\"      O: \" ++ show (roundTo 1 $ m + 1.65*s) ++\"\\n      \"++ \"A: \" ++ show (roundTo 1 $ m + 0.85*s) ++\"\\n      \"++ \"B: \" ++ show (roundTo 1 $ m) ++\"\\n      \"++ \"C: \" ++ show (roundTo 1 $ m - s) ++\"\\n      \"++ \"D: \" ++ show (roundTo 1 $ me / 2))\n                           putStrLn \"  \"\n                           putStrLn \"Suggested grades:\"\n                           putStrLn sugg\n                           writeFile \"suggested\" sugg\n\n\nround' x | f < 0.5 = i\n         | otherwise = i + 1\n         where i = floor x\n               f = x - fromIntegral i\n\nroundTo n f = fromInteger (round' $ f * (10^n)) / (10.0^^n)\n\n\nmedian :: T.Vector Double -> Double\nmedian xs = sort (T.toList xs) !! n\n  where n = T.length xs `div` 2\n", "meta": {"hexsha": "8f293d46b27dc7c898e0b8792e9acac4b2323762", "size": 4658, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GradeParser.hs", "max_stars_repo_name": "sejdm/Grades", "max_stars_repo_head_hexsha": "15a932abff1e6debea6e4986b242e18e8293a0f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GradeParser.hs", "max_issues_repo_name": "sejdm/Grades", "max_issues_repo_head_hexsha": "15a932abff1e6debea6e4986b242e18e8293a0f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GradeParser.hs", "max_forks_repo_name": "sejdm/Grades", "max_forks_repo_head_hexsha": "15a932abff1e6debea6e4986b242e18e8293a0f4", "max_forks_repo_licenses": ["BSD-3-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.5043478261, "max_line_length": 281, "alphanum_fraction": 0.5465865178, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.43534451743529273}}
{"text": "-- |\n-- Module    : Statistics.Distribution.Poisson.Internal\n-- Copyright : (c) 2011 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- Internal code for the Poisson distribution.\n\nmodule Statistics.Distribution.Poisson.Internal\n    (\n      probability, poissonEntropy\n    ) where\n\nimport Data.List (unfoldr)\nimport Numeric.MathFunctions.Constants (m_sqrt_2_pi, m_tiny, m_epsilon)\nimport Numeric.SpecFunctions (logGamma, stirlingError {-, choose, logFactorial -})\nimport Numeric.SpecFunctions.Extra (bd0)\n\n-- | An unchecked, non-integer-valued version of Loader's saddle point\n-- algorithm.\nprobability :: Double -> Double -> Double\nprobability 0      0     = 1\nprobability 0      1     = 0\nprobability lambda x\n  | isInfinite lambda    = 0\n  | x < 0                = 0\n  | x <= lambda * m_tiny = exp (-lambda)\n  | lambda < x * m_tiny  = exp (-lambda + x * log lambda - logGamma (x+1))\n  | otherwise            = exp (-(stirlingError x) - bd0 x lambda) /\n                           (m_sqrt_2_pi * sqrt x)\n\n-- -- | Compute entropy using Theorem 1 from \"Sharp Bounds on the Entropy\n-- -- of the Poisson Law\".  This function is unused because 'directEntorpy'\n-- -- is just as accurate and is faster by about a factor of 4.\n-- alyThm1 :: Double -> Double\n-- alyThm1 lambda =\n--   sum (takeWhile (\\x -> abs x >= m_epsilon * lll) alySeries) + lll\n--   where lll = lambda * (1 - log lambda)\n--         alySeries =\n--           [ alyc k * exp (fromIntegral k * log lambda - logFactorial k)\n--           | k <- [2..] ]\n\n-- alyc :: Int -> Double\n-- alyc k =\n--   sum [ parity j * choose (k-1) j * log (fromIntegral j+1) | j <- [0..k-1] ]\n--   where parity j\n--           | even (k-j) = -1\n--           | otherwise  = 1\n\n-- | Returns [x, x^2, x^3, x^4, ...]\npowers :: Double -> [Double]\npowers x = unfoldr (\\y -> Just (y*x,y*x)) 1\n\n-- | Returns an upper bound according to theorem 2 of \"Sharp Bounds on\n-- the Entropy of the Poisson Law\"\nalyThm2Upper :: Double -> [Double] -> Double\nalyThm2Upper lambda coefficients =\n  1.4189385332046727 + 0.5 * log lambda +\n  zipCoefficients lambda coefficients\n\n-- | Returns the average of the upper and lower bounds according to\n-- theorem 2.\nalyThm2 :: Double -> [Double] -> [Double] -> Double\nalyThm2 lambda upper lower =\n  alyThm2Upper lambda upper + 0.5 * (zipCoefficients lambda lower)\n\nzipCoefficients :: Double -> [Double] -> Double\nzipCoefficients lambda coefficients =\n  (sum $ map (uncurry (*)) (zip (powers $ recip lambda) coefficients))\n\n-- Mathematica code deriving the coefficients below:\n--\n-- poissonMoment[0, s_] := 1\n-- poissonMoment[1, s_] := 0\n-- poissonMoment[k_, s_] :=\n--   Sum[s * Binomial[k - 1, j] * poissonMoment[j, s], {j, 0, k - 2}]\n--\n-- upperSeries[m_]  :=\n--  Distribute[Integrate[\n--    Sum[(-1)^(j - 1) *\n--      poissonMoment[j, \\[Lambda]] / (j * (j - 1)* \\[Lambda]^j),\n--     {j, 3, 2 m - 1}],\n--    \\[Lambda]]]\n--\n-- lowerSeries[m_] :=\n--  Distribute[Integrate[\n--    poissonMoment[\n--      2 m + 2, \\[Lambda]] / ((2 m +\n--         1)*\\[Lambda]^(2 m + 2)), \\[Lambda]]]\n--\n-- upperBound[m_] := upperSeries[m] + (Log[2*Pi*\\[Lambda]] + 1)/2\n--\n-- lowerBound[m_] := upperBound[m] + lowerSeries[m]\n\nupperCoefficients4 :: [Double]\nupperCoefficients4 = [1/12, 1/24, -103/180, -13/40, -1/210]\n\nlowerCoefficients4 :: [Double]\nlowerCoefficients4 = [0,0,0, -105/4, -210, -2275/18, -167/21, -1/72]\n\nupperCoefficients6 :: [Double]\nupperCoefficients6 = [1/12, 1/24, 19/360, 9/80, -38827/2520,\n                      -74855/1008, -73061/2520, -827/720, -1/990]\n\nlowerCoefficients6 :: [Double]\nlowerCoefficients6 = [0,0,0,0,0, -3465/2, -45045, -466235/4, -531916/9,\n                      -56287/10, -629/11, -1/156]\n\nupperCoefficients8 :: [Double]\nupperCoefficients8 = [1/12, 1/24, 19/360, 9/80, 863/2520, 1375/1008,\n                      -3023561/2520, -15174047/720, -231835511/5940,\n                      -18927611/1320, -58315591/60060, -23641/3640,\n                      -1/2730]\n\nlowerCoefficients8 :: [Double]\nlowerCoefficients8 = [0,0,0,0,0,0,0, -2027025/8, -15315300, -105252147,\n                      -178127950, -343908565/4, -10929270, -3721149/14,\n                      -7709/15, -1/272]\n\nupperCoefficients10 :: [Double]\nupperCoefficients10 = [1/12, 1/24, 19/360, 9,80, 863/2520, 1375/1008,\n                       33953/5040, 57281/1440, -2271071617/11880,\n                       -1483674219/176, -31714406276557/720720,\n                       -7531072742237/131040, -1405507544003/65520,\n                       -21001919627/10080, -1365808297/36720,\n                       -26059/544, -1/5814]\n\nlowerCoefficients10 :: [Double]\nlowerCoefficients10 = [0,0,0,0,0,0,0,0,0,-130945815/2, -7638505875,\n                       -438256243425/4, -435477637540, -3552526473925/6,\n                       -857611717105/3, -545654955967/12, -5794690528/3,\n                       -578334559/42, -699043/133, -1/420]\n\nupperCoefficients12 :: [Double]\nupperCoefficients12 = [1/12, 1/24, 19/360, 863/2520, 1375/1008,\n                       33953/5040, 57281/1440, 3250433/11880,\n                       378351/176, -37521922090657/720720,\n                       -612415657466657/131040, -3476857538815223/65520,\n                       -243882174660761/1440, -34160796727900637/183600,\n                       -39453820646687/544, -750984629069237/81396,\n                       -2934056300989/9576, -20394527513/12540,\n                       -3829559/9240, -1/10626]\n\nlowerCoefficients12 :: [Double]\nlowerCoefficients12 = [0,0,0,0,0,0,0,0,0,0,0,\n                       -105411381075/4, -5270569053750, -272908057767345/2,\n                       -1051953238104769, -24557168490009155/8,\n                       -3683261873403112, -5461918738302026/3,\n                       -347362037754732, -2205885452434521/100,\n                       -12237195698286/35, -16926981721/22,\n                       -6710881/155, -1/600]\n\n-- | Compute entropy directly from its definition. This is just as accurate\n-- as 'alyThm1' for lambda <= 1 and is faster, but is slow for large lambda,\n-- and produces some underestimation due to accumulation of floating point\n-- error.\ndirectEntropy :: Double -> Double\ndirectEntropy lambda =\n  negate . sum $\n  takeWhile (< negate m_epsilon * lambda) $\n  dropWhile (not . (< negate m_epsilon * lambda)) $\n  [ let x = probability lambda k in x * log x | k <- [0..]]\n\n-- | Compute the entropy of a Poisson distribution using the best available\n-- method.\npoissonEntropy :: Double -> Double\npoissonEntropy lambda\n  | lambda == 0 = 0\n  | lambda <= 10 = directEntropy lambda\n  | lambda <= 12 = alyThm2 lambda upperCoefficients4 lowerCoefficients4\n  | lambda <= 18 = alyThm2 lambda upperCoefficients6 lowerCoefficients6\n  | lambda <= 24 = alyThm2 lambda upperCoefficients8 lowerCoefficients8\n  | lambda <= 30 = alyThm2 lambda upperCoefficients10 lowerCoefficients10\n  | otherwise = alyThm2 lambda upperCoefficients12 lowerCoefficients12\n", "meta": {"hexsha": "76a0e5ddcc3ed09628d9c569026fb098b39cabb4", "size": 6978, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Poisson/Internal.hs", "max_stars_repo_name": "vaerksted/statistics", "max_stars_repo_head_hexsha": "435152619b968948733672a18946794b7fd92a98", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Distribution/Poisson/Internal.hs", "max_issues_repo_name": "vaerksted/statistics", "max_issues_repo_head_hexsha": "435152619b968948733672a18946794b7fd92a98", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Distribution/Poisson/Internal.hs", "max_forks_repo_name": "vaerksted/statistics", "max_forks_repo_head_hexsha": "435152619b968948733672a18946794b7fd92a98", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 39.202247191, "max_line_length": 82, "alphanum_fraction": 0.6102034967, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.43512912773127727}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Grenade.Layers.Internal.Update (\n    descendMatrix\n  , descendVector\n  ) where\n\nimport           Data.Maybe ( fromJust )\nimport qualified Data.Vector.Storable as U ( unsafeToForeignPtr0, unsafeFromForeignPtr0 )\n\nimport           Foreign ( mallocForeignPtrArray, withForeignPtr )\nimport           Foreign.Ptr ( Ptr )\nimport           GHC.TypeLits\n\nimport           Numeric.LinearAlgebra ( Vector, flatten )\nimport           Numeric.LinearAlgebra.Static\nimport qualified Numeric.LinearAlgebra.Devel as U\n\nimport           System.IO.Unsafe ( unsafePerformIO )\n\ndescendMatrix :: (KnownNat rows, KnownNat columns) => Double -> Double -> Double -> L rows columns -> L rows columns -> L rows columns -> (L rows columns, L rows columns)\ndescendMatrix rate momentum regulariser 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)     = descendUnsafe 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  (fromJust . create $ mw, fromJust . create $ mm)\n\ndescendVector :: (KnownNat r) => Double -> Double -> Double -> R r -> R r -> R r -> (R r, R r)\ndescendVector rate momentum regulariser weights gradient lastUpdate =\n  let len          = size weights\n      weights'     = extract weights\n      gradient'    = extract gradient\n      lastUpdate'  = extract lastUpdate\n      (vw, vm)     = descendUnsafe len rate momentum regulariser weights' gradient' lastUpdate'\n  in  (fromJust $ create vw, fromJust $ create vm)\n\ndescendUnsafe :: Int -> Double -> Double -> Double -> Vector Double -> Vector Double -> Vector Double -> (Vector Double, Vector Double)\ndescendUnsafe 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_cpu len rate momentum regulariser wPtr' gPtr' lPtr' outWPtr' outMPtr'\n\n    return (U.unsafeFromForeignPtr0 outWPtr len, U.unsafeFromForeignPtr0 outMPtr len)\n\nforeign import ccall unsafe\n    descend_cpu\n      :: Int -> Double -> Double -> Double -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double -> IO ()\n\n", "meta": {"hexsha": "0f46ff20e67ec3a2076aa2dde4513de1acd4fe57", "size": 3171, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/Update.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/Internal/Update.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/Internal/Update.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": 44.661971831, "max_line_length": 170, "alphanum_fraction": 0.6704509618, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4350732469730729}}
{"text": "{-# LANGUAGE Strict     #-}\n{-# LANGUAGE StrictData #-}\nmodule FokkerPlanck.Analytic\n  ( R2S1RP(..)\n  , computePji\n  , computePjiCorner\n  , computePjiCorner'\n  ) where\n\nimport           Data.Complex\nimport           Data.List               as L\nimport           Numeric.GSL.Polynomials\nimport           Text.Printf\n\n\ndata R2S1RP = R2S1RP\n  { xR2S1RP, yR2S1RP, thetaR2S1RP, gammaR2S1RP :: Double\n  } deriving (Show)\n             \ninstance Eq R2S1RP where\n  (==) (R2S1RP x1 y1 theta1 _) (R2S1RP x2 y2 theta2 _) =\n    (x1 == x2) && (y1 == y2)\n\n{-# INLINE computeCoefficients #-}\ncomputeCoefficients :: R2S1RP -> R2S1RP -> (Double, Double, Double)\ncomputeCoefficients (R2S1RP x_i y_i theta_i _) (R2S1RP x_j y_j theta_j gamma) =\n  let x = x_j - x_i\n      y = y_j - y_i\n      a = (2 + cos (theta_j - theta_i)) / 3\n      b =\n        (x * (cos theta_j + cos theta_i) + y * (sin theta_j + sin theta_i)) /\n        gamma\n      c = (x ^ 2 + y ^ 2) / (gamma ^ 2)\n   in (a, b, c)\n\n{-# INLINE solveCubicEquation #-}\nsolveCubicEquation :: Double -> Double -> Double -> Double -> [Complex Double]\nsolveCubicEquation a b c d =\n  let x0 = b ^ 2 - 3 * a * c\n      x1 = 2 * b ^ 3 - 9 * a * b * c + 27 * a ^ 2 * d\n      x2 = x1 ^ 2 - 4 * x0 ^ 3\n      y =\n        if x2 >= 0\n          then ((x1 + sqrt x2) / 2) ** (1 / 3) :+ 0\n          else ((x1 :+ sqrt (abs x2)) / (2 :+ 0)) ** (1 / 3)\n      z = (-0.5) :+ 0.8660254037844386 -- (sqrt 3) / 2\n  in [ ((b :+ 0) + z ^ k * y + (x0 :+ 0) / (z ^ k * y)) / ((-3) * a :+ 0)\n     | k <- [0 .. 2]\n     ]\n\n{-# INLINE isRealPositive #-}\nisRealPositive :: Complex Double -> Bool\nisRealPositive (a :+ b) = (a > 0) && (abs b < 1e-10)\n\n{-# INLINE computePjit #-}\ncomputePjit ::\n     Double -> Double -> (Double, Double, Double) -> Double -> Double\ncomputePjit sigma tau (a, b, c) t =\n  3 * exp ((-6) * (a * (t ^ 2) - b * t + c) / (sigma * (t ^ 3))) *\n  exp (-t / tau) /\n  sqrt ((pi * sigma) ^ 3 * (t ^ 7) / 2)\n\ncomputePji :: Double -> Double -> R2S1RP -> R2S1RP -> Double\ncomputePji sigma tau x_i x_j =\n  if x_i == x_j\n    then 0\n    else let coef@(a, b, c) = computeCoefficients x_i x_j\n             roots' =\n               polySolve [9 * c / sigma, -6 * b / sigma, 3 * a / sigma, -7 / 4]\n             roots = L.filter isRealPositive roots'\n             (pOpt, tOpt) =\n               L.maximumBy (\\x y -> compare (fst x) (fst y)) .\n               L.map\n                 (\\root ->\n                    let realRoot = realPart root\n                     in (computePjit sigma tau coef realRoot, realRoot)) $\n               roots\n             f =\n               sqrt\n                 (2 * pi * (tOpt ^ 5) /\n                  (12 * (3 * c - b * tOpt) / sigma + 7 * (tOpt ^ 3) / 2))\n          in f * pOpt\n\n\n{-# INLINE findIntersectionPoint #-}\nfindIntersectionPoint :: Double -> R2S1RP -> Maybe Double\nfindIntersectionPoint delta (R2S1RP x y theta _)\n  | theta == pi || theta == 0 || z < delta = Nothing\n  | otherwise = Just z\n  where\n    z = x - y / tan theta\n\n{-# INLINE rotate #-}\nrotate :: (Double,Double) -> Double -> (Double,Double)\nrotate (x, y) theta =\n  (x * cos theta - y * sin theta, x * sin theta + y * cos theta)\n\n{-# INLINE computePjiCorner #-}\ncomputePjiCorner :: Double -> Double -> Double -> [Double] -> R2S1RP -> Double\ncomputePjiCorner delta sigma tau orientations point@(R2S1RP x y theta gamma) =\n  case findIntersectionPoint delta point of\n    Nothing -> 0\n    Just z ->\n      let p1 = computePji sigma tau (R2S1RP 0 0 0 gamma) (R2S1RP z 0 0 gamma)\n                      -- (newX, newY) = rotate (x - z, y) (-theta)\n                      -- p2 =\n                      --   computePji\n                      --     sigma\n                      --     tau\n                      --     (R2S1RP 0 0 0 gamma)\n                      --     (R2S1RP newX newY 0 gamma)\n          p2 = computePji sigma tau (R2S1RP z 0 theta gamma) point\n                      -- p1 = L.foldl' (\\s ori -> s + computePji sigma tau\n                      --   (R2S1RP 0 0 0 gamma) (R2S1RP z 0 ori gamma)) 0\n                      --   orientations p2 = L.foldl' (\\s ori -> s +\n                      --   computePji sigma tau (R2S1RP z 0 ori gamma)\n                      --   point) 0 orientations\n       in p1 * p2\n\n\n{-# INLINE computePjiCorner' #-}\ncomputePjiCorner' :: Double -> Double -> Double -> Double -> [Double] -> R2S1RP -> Double\ncomputePjiCorner' delta sigma tau threshold orientations point@(R2S1RP x y theta gamma) =\n  case findIntersectionPoint delta point of\n    Nothing -> 0\n    Just z ->\n      let p1 = computePji sigma tau (R2S1RP 0 0 0 gamma) (R2S1RP z 0 0 gamma)\n       in if p1 < threshold\n            then 0\n            else let p11 =\n                       L.foldl'\n                         (\\s ori ->\n                            s +\n                            computePji\n                              sigma\n                              tau\n                              (R2S1RP 0 0 0 gamma)\n                              (R2S1RP z 0 ori gamma))\n                         0\n                         orientations\n                                               -- p2 = computePji sigma tau (R2S1RP z 0 theta gamma) point\n                     p2 =\n                       L.foldl'\n                         (\\s ori ->\n                            s +\n                            computePji\n                              sigma\n                              tau\n                              (R2S1RP x y (theta + pi) gamma)\n                              (R2S1RP z 0 ori gamma)\n                                                -- point\n                          )\n                         0\n                         orientations\n                                       -- p3 =\n                                       --   L.foldl'\n                                       --     (\\s ori ->\n                                       --        s +\n                                       --        computePji\n                                       --          sigma\n                                       --          tau\n                                       --          (R2S1RP 0 0 0 gamma)\n                                       --          (R2S1RP z 0 ori gamma) *\n                                       --        computePji\n                                       --          sigma\n                                       --          tau\n                                       --          (R2S1RP z 0 theta gamma)\n                                       --          point)\n                                       --     0\n                                       --     orientations\n                  in p11 * p2\n", "meta": {"hexsha": "d975013e96d99398d514bb0ae678bd80ad493a7b", "size": 6609, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/Analytic.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/Analytic.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/Analytic.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 38.4244186047, "max_line_length": 106, "alphanum_fraction": 0.4083825087, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.43496402445681387}}
{"text": "module Scheme.Parser where\n\nimport Control.Monad (unless, void)\nimport Control.Monad.Except (MonadError (throwError))\nimport Data.Array (listArray)\nimport qualified Data.ByteString as BS\nimport qualified Data.Char as C\nimport Data.Complex (Complex ((:+)))\nimport Data.Ratio ((%))\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Text.Read (hexadecimal)\nimport Data.Word (Word8)\nimport Scheme.Types (Number (..), SchemeError (..), SchemeResult, SchemeVal (..))\nimport Text.Megaparsec\nimport Text.Megaparsec.Char\nimport qualified Text.Megaparsec.Char.Lexer as L\n\nnewtype ParserError = Unimplemented Text deriving (Show, Eq, Ord)\n\ninstance ShowErrorComponent ParserError where\n  showErrorComponent (Unimplemented text) = T.unpack text <> \" is not implemented\"\n\ntype Parser = Parsec ParserError Text\n\nsc :: Parser ()\nsc =\n  L.space\n    space1\n    (L.skipLineComment \";\")\n    (L.skipBlockCommentNested \"#|\" \"|#\")\n\nlexeme :: Parser a -> Parser a\nlexeme = L.lexeme sc\n\nsymbol :: Text -> Parser Text\nsymbol = L.symbol sc\n\nparens :: Parser a -> Parser a\nparens = between (symbol \"(\") (symbol \")\")\n\nbrackets :: Parser a -> Parser a\nbrackets = between (symbol \"[\") (symbol \"]\")\n\nbraces :: Parser a -> Parser a\nbraces = between (symbol \"{\") (symbol \"}\")\n\npInteger :: Parser Integer\npInteger = L.signed (return ()) L.decimal\n\npBinaryInteger :: Parser Integer\npBinaryInteger = chunk \"#b\" >> L.binary\n\npOctalInteger :: Parser Integer\npOctalInteger = chunk \"#o\" >> L.octal\n\npDecimalInteger :: Parser Integer\npDecimalInteger = chunk \"#d\" >> L.decimal\n\npHexadecimalInteger :: Parser Integer\npHexadecimalInteger = chunk \"#x\" >> L.hexadecimal\n\ninteger :: Parser Number\ninteger =\n  Integer\n    <$> ( choice\n            [ pInteger,\n              pBinaryInteger,\n              pOctalInteger,\n              pDecimalInteger,\n              pHexadecimalInteger\n            ]\n            <?> \"integer\"\n        )\n\npReal :: Parser Double\npReal = L.signed (return ()) L.float\n\npDouble :: Parser Number\npDouble = Real <$> (pReal <?> \"double\")\n\npRational :: Parser Number\npRational = do\n  numerator <- pInteger\n  void (char '/')\n  denominator <- pInteger\n  -- TODO: Fix error if denominator is 0\n  return $ Rational (numerator % denominator)\n\npComplex :: Parser Number\npComplex = do\n  real <- pNan' <|> pInfinity' <|> try pReal <|> (fromInteger <$> pInteger)\n  void (char '+')\n  imag <- try pReal <|> fromInteger <$> pInteger <|> read \"NaN\" <$ chunk \"nan.0\" <|> read \"Infinity\" <$ chunk \"inf.0\"\n  void (char 'i')\n  return $ Complex (real :+ imag)\n\npInfinity' :: Parser Double\npInfinity' =\n  read \"Infinity\" <$ chunk \"+inf.0\"\n    <|> read \"-Infinity\" <$ chunk \"-inf.0\"\n\npInfinity :: Parser Number\npInfinity = Real <$> pInfinity'\n\npNan' :: Parser Double\npNan' = read \"NaN\" <$ chunk \"+nan.0\"\n\npNan :: Parser Number\npNan = Real <$> pNan'\n\npExact :: Parser Number\npExact = do\n  void (try $ chunk \"#e\")\n  num <- number'\n  case num of\n    x@(Integer _) -> return x\n    x@(Rational _) -> return x\n    (Real x) -> return $ Rational (toRational x)\n    _ -> customFailure $ Unimplemented \"Exactness for complex numbers\"\n\npInexact :: Parser Number\npInexact = do\n  void (try $ chunk \"#i\")\n  num <- number'\n  case num of\n    x@(Real _) -> return x\n    (Integer x) -> return $ Real (fromInteger x)\n    (Rational x) -> return $ Real (fromRational x)\n    _ -> customFailure $ Unimplemented \"Exactness for complex numbers\"\n\nnumber' :: Parser Number\nnumber' = choice (map (try . lexeme) [pComplex, pRational, pDouble, integer, pInfinity, pNan, pExact, pInexact])\n\nnumber :: Parser SchemeVal\nnumber = Number <$> number'\n\npSymbol :: Parser SchemeVal\npSymbol = try $ do\n  ident <- lexeme (T.pack <$> start <> rest <?> \"identifier\")\n  if ident == \".\"\n    then empty\n    else return $ Symbol ident\n  where\n    extendedSymbols = satisfy (`elem` ['!', '$', '%', '&', '*', '+', '-', '.', '/', ':', '<', '=', '>', '?', '@', '^', '_', '~'])\n    start = some (letterChar <|> extendedSymbols)\n    rest = many (alphaNumChar <|> extendedSymbols)\n\npString :: Parser SchemeVal\npString = lexeme $ String . T.pack <$> (char '\"' *> manyTill L.charLiteral (char '\"'))\n\npChar :: Parser SchemeVal\npChar = do\n  void (try $ chunk \"#\\\\\")\n  chr <- many asciiChar\n  case chr of\n    \"alarm\" -> return $ Character '\\BEL'\n    \"backspace\" -> return $ Character '\\BS'\n    \"delete\" -> return $ Character '\\DEL'\n    \"escape\" -> return $ Character '\\ESC'\n    \"newline\" -> return $ Character '\\LF'\n    \"null\" -> return $ Character '\\NUL'\n    \"return\" -> return $ Character '\\CR'\n    \"space\" -> return $ Character ' '\n    \"tab\" -> return $ Character '\\HT'\n    _ -> pChar' chr\n\npChar' :: [Char] -> Parser SchemeVal\npChar' [c] = pure (Character c) <?> \"char\"\npChar' ('x' : hex) = case hexadecimal (T.pack hex) of\n  Right n -> return (Character <$> C.chr $ fst n) <?> \"hex char\"\n  _ -> empty\npChar' _ = empty\n\nboolean :: Parser SchemeVal\nboolean =\n  choice $\n    map\n      lexeme\n      [ Boolean True <$ chunk \"#t\",\n        Boolean False <$ chunk \"#f\"\n      ]\n\npPairList :: Parser SchemeVal\npPairList = try $\n  parens $ do\n    ls <- pExpr `sepEndBy` sc <?> \"dotted pair car\"\n    dot <- optional (symbol \".\" >> pExpr) <?> \"pair\"\n    pure $ case dot of\n      Nothing -> List ls\n      Just (List c) -> List (ls ++ c)\n      Just (PairList car cdr) -> PairList (ls ++ car) cdr\n      Just val -> PairList ls val\n\npList :: Parser SchemeVal\npList = List <$> try (parens (pExpr `sepEndBy` sc)) <?> \"list\"\n\npVector :: Parser SchemeVal\npVector = do\n  void (try $ symbol \"#(\")\n  ls <- pExpr `sepEndBy` sc\n  void (symbol \")\")\n  return $ Vector (listArray (0, length ls - 1) ls)\n\npBytevector :: Parser SchemeVal\npBytevector = do\n  void (try $ symbol \"#u8(\")\n  ls <- pInteger `sepEndBy` sc\n  void (symbol \")\")\n  return $ Bytevector (BS.pack $ map toByte ls)\n  where\n    toByte num = fromInteger num :: Word8\n\npQuote :: Parser SchemeVal\npQuote = do\n  void (try $ lexeme $ char '\\'')\n  expr <- pExpr\n  return $ List [Symbol \"quote\", expr]\n\npQuasiquote :: Parser SchemeVal\npQuasiquote = do\n  void (try $ lexeme $ char '`')\n  expr <- pExpr\n  return $ List [Symbol \"quasiquote\", expr]\n\npUnquote :: Parser SchemeVal\npUnquote = do\n  void (try $ lexeme $ char ',')\n  expr <- pExpr\n  return $ List [Symbol \"unquote\", expr]\n\npUnquoteSplicing :: Parser SchemeVal\npUnquoteSplicing = do\n  void (try $ lexeme $ chunk \",@\")\n  expr <- pExpr\n  return $ List [Symbol \"unquote-splicing\", expr]\n\npExpr :: Parser SchemeVal\npExpr =\n  number\n    <|> pChar\n    <|> pSymbol\n    <|> pString\n    <|> boolean\n    <|> pList\n    <|> pPairList\n    <|> pVector\n    <|> pBytevector\n    <|> pQuote\n    <|> pQuasiquote\n    <|> pUnquoteSplicing\n    <|> pUnquote\n    <?> \"expression\"\n\nparseExpr :: FilePath -> Text -> Either SchemeError SchemeVal\nparseExpr file input = case runParser pExpr file input of\n  Right out -> Right out\n  Left err -> Left $ ParserError (T.pack $ errorBundlePretty err)\n\nparseInput :: Text -> SchemeResult SchemeVal\nparseInput = parseExpr \"file\"\n\nparseFile :: FilePath -> Text -> Either SchemeError SchemeVal\nparseFile = parseExpr\n\nparseOrThrow :: Parser a -> Text -> SchemeResult a\nparseOrThrow parser input =\n  let checkEmpty = do\n        rest <- getInput\n        unless (T.null rest) $ fail $ \"Non-empty: \" ++ T.unpack rest\n      parser' = parser <* checkEmpty\n   in case runParser parser' \"scheme\" input of\n        Right val -> return val\n        Left err -> throwError $ ParserError (T.pack $ errorBundlePretty err)\n\nreadExpr :: Text -> SchemeResult SchemeVal\nreadExpr = parseOrThrow pExpr\n\nreadManyExpr :: Text -> SchemeResult [SchemeVal]\nreadManyExpr = parseOrThrow $ some pExpr\n", "meta": {"hexsha": "9f4ac0393b434f96299d2dfd8e947c141652d6cd", "size": 7587, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Scheme/Parser.hs", "max_stars_repo_name": "sondr3/scheme-hs", "max_stars_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-04T10:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T10:40:57.000Z", "max_issues_repo_path": "lib/Scheme/Parser.hs", "max_issues_repo_name": "sondr3/scheme-hs", "max_issues_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Scheme/Parser.hs", "max_forks_repo_name": "sondr3/scheme-hs", "max_forks_repo_head_hexsha": "8bf2481ff617a7103f93b12e112b643fb5a8f173", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 129, "alphanum_fraction": 0.6370106762, "num_tokens": 2155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4347368130522986}}
{"text": "#if __GLASGOW_HASKELL__ >= 701\n{-# LANGUAGE Safe #-}\n#endif\n\nmodule Complex (\n        Complex((:+)), realPart, imagPart, conjugate, \n        mkPolar, cis, polar, magnitude, phase \n    ) where\n\nimport Data.Complex\n", "meta": {"hexsha": "ad9b3281b246df808131fa18a8013f5af6bf40c7", "size": 213, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "libraries/haskell98/Complex.hs", "max_stars_repo_name": "emorins/nahc", "max_stars_repo_head_hexsha": "eb18f1f22c99eae0cb58a8a674a2d58434476376", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/haskell98/Complex.hs", "max_issues_repo_name": "emorins/nahc", "max_issues_repo_head_hexsha": "eb18f1f22c99eae0cb58a8a674a2d58434476376", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-11-11T09:02:10.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-14T01:41:29.000Z", "max_forks_repo_path": "libraries/haskell98/Complex.hs", "max_forks_repo_name": "emorins/nahc", "max_forks_repo_head_hexsha": "eb18f1f22c99eae0cb58a8a674a2d58434476376", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3636363636, "max_line_length": 54, "alphanum_fraction": 0.6431924883, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.43471185363309706}}
{"text": "module STCR2Z2T0S0EndPoint where\n\nimport           Control.Monad             as M\nimport           Data.Array.Repa           as R\nimport           Data.Binary               (decodeFile)\nimport           Data.Complex\nimport           Data.List                 as L\nimport           DFT.Plan\nimport           FokkerPlanck.DomainChange\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.IO\nimport           Image.Transform           (normalizeValueRange)\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           System.Random\nimport           Text.Printf\nimport           Types\nimport           Utils.Array\nimport           Utils.Parallel\n\nmain = do\n  args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:scale0FreqsStr:scaleFreqsStr:histFilePath:numIterationStr:writeSourceFlagStr:cutoffRadiusEndPointStr:cutoffRadiusStr:reversalFactorStr:cStr:patchNormFlagStr:patchNormSizeStr:approximatedEigenValueStr:shape2DStr:segmentsFilePath:segIdxStr:useFFTWWisdomFlagStr:fftwWisdomFileName:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      theta0Freq = read theta0FreqsStr :: Double\n      theta0Freqs = [-theta0Freq .. theta0Freq]\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scale0Freq = read scale0FreqsStr :: Double\n      scaleFreq = read scaleFreqsStr :: Double\n      scale0Freqs = [-scale0Freq .. scale0Freq]\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      numIteration = read numIterationStr :: Int\n      writeSourceFlag = read writeSourceFlagStr :: Bool\n      cutoffRadiusEndPoint = read cutoffRadiusEndPointStr :: Int\n      cutoffRadius = read cutoffRadiusStr :: Int\n      reversalFactor = read reversalFactorStr :: Double\n      patchNormFlag = read patchNormFlagStr :: Bool\n      patchNormSize = read patchNormSizeStr :: Int\n      approximatedEigenValue = read approximatedEigenValueStr :: Double\n      shape2D@(Points _ minDist _) = read shape2DStr :: Points Shape2D\n      segIdx = read segIdxStr :: Int\n      useFFTWWisdomFlag = read useFFTWWisdomFlagStr :: Bool\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/STCR2Z2T0S0EndPoint\"\n      a = 20 :: Int\n      b = 5 :: Int\n      c = read cStr :: Int\n      endPointFilePath =\n        folderPath </>\n        (printf\n           \"EndPoint_%d_%d_%d_%d_%d_%d_%.2f_%.2f_%d_%d_%d_%f.dat\"\n           numPoint\n           (round thetaFreq :: Int)\n           (round scaleFreq :: Int)\n           (round maxScale :: Int)\n           (round tao :: Int)\n           cutoffRadiusEndPoint\n           thetaSigma\n           scaleSigma\n           a\n           b\n           c\n           reversalFactor)\n      fftwWisdomFilePath = folderPath </> fftwWisdomFileName\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  radialArr <-\n    if flag\n      then R.map magnitude . getNormalizedHistogramArr <$>\n           decodeFile histFilePath\n      else do\n        putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n        solveMonteCarloR2Z2T0S0Radial\n          numThread\n          numTrail\n          maxTrail\n          numPoint\n          numPoint\n          thetaSigma\n          scaleSigma\n          maxScale\n          tao\n          theta0Freqs\n          thetaFreqs\n          scale0Freqs\n          scaleFreqs\n          histFilePath\n          (emptyHistogram\n             [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n             , L.length scale0Freqs\n             , L.length theta0Freqs\n             , L.length scaleFreqs\n             , L.length thetaFreqs\n             ]\n             0)\n  arrR2Z2T0S0 <-\n    computeUnboxedP $\n    computeR2Z2T0S0ArrayRadial\n      (PinwheelHollow0 10)\n      (cutoff cutoffRadius radialArr)\n      numPoint\n      numPoint\n      1\n      maxScale\n      thetaFreqs\n      scaleFreqs\n      theta0Freqs\n      scale0Freqs\n  plan <-\n    makeR2Z2T0S0Plan emptyPlan useFFTWWisdomFlag fftwWisdomFilePath arrR2Z2T0S0\n  -- (plan, pathNormMethod) <-\n  --   makePatchNormFilter plan' numPoint numPoint patchNormFlag patchNormSize\n      -- minDist = 8\n      -- kanizsaTriangle1 =\n      --   makeShape2D $ Points (-30, -30) minDist (Corner 30 60 80) --(PacMan 30 60 50)  --(Ehrenstein 8 15 40)  -- (IncompleteCircle 0 60 50 ) -- (TJunction 45 50) -- (PacMan 0 60 100 ) -- (Corner 0 60 100) --(KanizsaTriangle1 0 480 160 80)\n  -- ys <-\n  --   (\\aa -> aa L.!! segIdx) <$> decodeFile segmentsFilePath :: IO [(Int, Int)]\n  let pointSet = makeShape2D shape2D\n      shapeArr =\n        getShape2DRepaArray\n          numPoint\n          numPoint\n          (L.map\n             (\\(x, y) ->\n                (x + fromIntegral numPoint / 2, y + fromIntegral numPoint / 2))\n             pointSet)\n      xs =\n        L.map (\\(x, y) -> R2S1RPPoint (x, y, 0, 1)) . getShape2DIndexList $\n        pointSet\n      -- (xAvg, yAvg) =\n      --   (\\(as, bs) ->\n      --      ( round $\n      --        (fromIntegral . L.sum $ as) / (fromIntegral . L.length $ as)\n      --      , round $\n      --        (fromIntegral . L.sum $ bs) / (fromIntegral . L.length $ bs))) .\n      --   L.unzip $\n      --   ys\n      -- centeredYs = L.map (\\(x, y) -> (x - xAvg, y - yAvg)) ys\n      -- xs = L.map (\\(x, y) -> R2S1RPPoint (x, y, 0, 1)) centeredYs\n      -- shapeArr =\n      --   L.head . cluster2Array numPoint numPoint $\n      --   [L.map (\\(x, y) -> (x + div numPoint 2, y + div numPoint 2)) centeredYs]\n      -- pointSet = L.map (\\(x, y) -> (fromIntegral x, fromIntegral y)) centeredYs\n  let bias = computeBiasR2T0S0 numPoint numPoint theta0Freqs scale0Freqs xs\n      eigenVec =\n        computeInitialEigenVectorR2T0S0\n          numPoint\n          numPoint\n          theta0Freqs\n          scale0Freqs\n          thetaFreqs\n          scaleFreqs\n          xs\n  plotImageRepa (folderPath </> \"Shape.png\") . ImageRepa 8 $ shapeArr\n  endPointFlag <- doesFileExist endPointFilePath\n  completionFieldR2Z2'' <-\n    if endPointFlag\n      then readRepaArray endPointFilePath\n      else (do putStrLn \"Couldn't find the endpoint data. Start computing...\"\n               arrR2Z2T0S0EndPoint <-\n                 computeUnboxedP $\n                 computeR2Z2T0S0ArrayRadial\n                   -- pinwheel\n                   -- (pinwheelHollowNonzeronCenter 16) \n                   (PinwheelHollow0 4)\n                   (cutoff cutoffRadiusEndPoint radialArr)\n                   numPoint\n                   numPoint\n                   1\n                   maxScale\n                   thetaFreqs\n                   scaleFreqs\n                   theta0Freqs\n                   scale0Freqs\n               pathNormMethod <-\n                 if patchNormFlag\n                   then do\n                     let points =\n                           createIndex2D .\n                           L.map\n                             (\\(i, j) ->\n                                (i + div numPoint 2, j + div numPoint 2)) .\n                           getShape2DIndexList $\n                           pointSet\n                         ys =\n                           pointCluster\n                             (connectionMatrixP\n                                (ParallelParams numThread 1)\n                                (minDist + 1)\n                                points) $\n                           points\n                     M.zipWithM_\n                       (\\i ->\n                          plotImageRepa\n                            (folderPath </> (printf \"Cluster%03d.png\" i)) .\n                          ImageRepa 8)\n                       [1 :: Int ..] .\n                       cluster2Array numPoint numPoint $\n                       ys\n                     return . PowerMethodConnection $ ys\n                   else return PowerMethodGlobal\n               (R.foldAllP max 0 . R.map magnitude $ arrR2Z2T0S0EndPoint) >>=\n                 print\n               completionFieldR2Z2' <-\n                 powerMethodR2Z2T0S0Reversal\n                   plan\n                   folderPath\n                   numPoint\n                   numPoint\n                   numOrientation\n                   thetaFreqs\n                   theta0Freqs\n                   numScale\n                   scaleFreqs\n                   scale0Freqs\n                   maxScale\n                   arrR2Z2T0S0EndPoint\n                   pathNormMethod\n                   numIteration\n                   writeSourceFlag\n                   (printf\n                      \"_%d_%d_%d_%d_%d_%d_%.2f_%.2f_%f_EndPoint\"\n                      numPoint\n                      (round thetaFreq :: Int)\n                      (round scaleFreq :: Int)\n                      (round maxScale :: Int)\n                      (round tao :: Int)\n                      cutoffRadiusEndPoint\n                      thetaSigma\n                      scaleSigma\n                      reversalFactor)\n                   0.5\n                   reversalFactor\n                   bias\n                   eigenVec\n               -- writeRepaArray endPointFilePath completionFieldR2Z2'\n               return completionFieldR2Z2')\n  let completionFieldR2Z2 = R.zipWith (*) completionFieldR2Z2'' bias\n      endpointBias = rotateBiasR2Z2T0S0 180 theta0Freqs completionFieldR2Z2\n      -- endpointBias =\n      --   R.zipWith\n      --     (+)\n      --     (rotateBiasR2Z2T0S0 90 theta0Freqs completionFieldR2Z2)\n      --     (rotateBiasR2Z2T0S0 (-90) theta0Freqs completionFieldR2Z2)\n                    -- rotateBiasR2Z2T0S0 0 theta0Freqs . R.traverse completionFieldR2Z2 id $ \\f idx@(Z :. _ :. _ :. i :. j) ->\n                    --   if (sqrt . fromIntegral $\n                    --       (i - div numPoint 2) ^ 2 + (j - div numPoint 2) ^ 2) >\n                    --      35\n                    --     then 0\n                    --     else f idx\n      biasMag =\n        R.sumS .\n        R.sumS .\n        rotate4D .\n        rotate4D .\n        R.map magnitude .\n        r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs $\n        endpointBias\n  plotImageRepa (folderPath </> \"EndPointBias.png\") .\n    ImageRepa 8 . computeS . R.extend (Z :. (1 :: Int) :. All :. All) $\n    biasMag\n  printf \"%f %f\\n\" reversalFactor (R.sumAllS biasMag)\n  -- powerMethodR2Z2T0S0BiasReversal\n  --   plan\n  --   folderPath\n  --   numPoint\n  --   numPoint\n  --   numOrientation\n  --   thetaFreqs\n  --   theta0Freqs\n  --   numScale\n  --   scaleFreqs\n  --   scale0Freqs\n  --   arrR2Z2T0S0\n  --   -- numIteration\n  --   10\n  --   writeSourceFlag\n  --   (printf\n  --      \"_%d_%d_%d_%d_%d_%d_%.2f_%.2f\"\n  --      numPoint\n  --      (round thetaFreq :: Int)\n  --      (round scaleFreq :: Int)\n  --      (round maxScale :: Int)\n  --      (round tao :: Int)\n  --      cutoffRadius\n  --      thetaSigma\n  --      scaleSigma)\n  --   0.1\n  --   (computeS endpointBias)\n  --   (R.fromFunction\n  --      (Z :. (L.length thetaFreqs) :. (L.length scaleFreqs) :.\n  --       (L.length theta0Freqs) :.\n  --       (L.length scale0Freqs) :.\n  --       numPoint :.\n  --       numPoint) $ \\(Z :. k :. l :. _ :. _ :. i :. j) ->\n  --      if k == div (L.length thetaFreqs) 2 && l == div (L.length scaleFreqs) 2\n  --        then 1 / (fromIntegral $ (L.length theta0Freqs * L.length scale0Freqs)) :+\n  --             0\n  --        else 0)\n", "meta": {"hexsha": "6ba2cfaeba0799ce619edbbc3112a76e36712fe4", "size": 11781, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z2T0S0EndPoint/STCR2Z2T0S0EndPoint.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/STCR2Z2T0S0EndPoint/STCR2Z2T0S0EndPoint.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/STCR2Z2T0S0EndPoint/STCR2Z2T0S0EndPoint.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 37.6389776358, "max_line_length": 446, "alphanum_fraction": 0.5289024701, "num_tokens": 3151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519378, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.43466629164962495}}
{"text": "{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Main where\n\nimport MNIST.Prelude\nimport MNIST.DataSet\nimport Numeric.LinearAlgebra.Static hiding (dot)\nimport Numeric.Backprop\n\nimport qualified Data.Vector.Generic             as VG\nimport qualified Data.Vector                     as V\nimport qualified Generics.SOP                    as SOP\nimport qualified Numeric.LinearAlgebra           as HM\nimport qualified System.Random.MWC               as MWC\nimport qualified System.Random.MWC.Distributions as MWC\n\n-- | type-combinators alias for the terminal constructor\nnil :: Prod f '[]\nnil = \u00d8\n\n-- ========================================================================= --\n-- Internal structure of our FF neural net\n\ndata Layer i o = Layer\n  { _lWeights :: !(L o i)\n  , _lBiases  :: !(R o)\n  } deriving (Show, Generic)\n\ninstance SOP.Generic (Layer i o)\ninstance NFData (Layer i o)\n\ndata Network i h1 h2 o = Net\n  { _nLayer1 :: !(Layer i  h1)\n  , _nLayer2 :: !(Layer h1 h2)\n  , _nLayer3 :: !(Layer h2 o)\n  } deriving (Show, Generic)\n\ninstance SOP.Generic (Network i h1 h2 o)\ninstance NFData (Network i h1 h2 o)\n\n-- ========================================================================= --\n-- type classes\n\ntype KnownNat4 i h1 h2 o = (KnownNat i, KnownNat h1, KnownNat h2, KnownNat o)\ntype KnownNat2 i o = (KnownNat i, KnownNat o)\n\n\ninstance KnownNat2 i o => Num (Layer i o) where\n  Layer w1 b1 + Layer w2 b2 = Layer (w1 + w2) (b1 + b2)\n  Layer w1 b1 - Layer w2 b2 = Layer (w1 - w2) (b1 - b2)\n  Layer w1 b1 * Layer w2 b2 = Layer (w1 * w2) (b1 * b2)\n  abs    (Layer w b)        = Layer (abs    w) (abs    b)\n  signum (Layer w b)        = Layer (signum w) (signum b)\n  negate (Layer w b)        = Layer (negate w) (negate b)\n  fromInteger x = Layer (fromInteger x) (fromInteger x)\n\ninstance KnownNat4 i h1 h2 o => Num (Network i h1 h2 o) where\n  Net a b c + Net d e f = Net (a + d) (b + e) (c + f)\n  Net a b c - Net d e f = Net (a - d) (b - e) (c - f)\n  Net a b c * Net d e f = Net (a * d) (b * e) (c * f)\n  abs    (Net a b c)    = Net (abs    a) (abs    b) (abs    c)\n  signum (Net a b c)    = Net (signum a) (signum b) (signum c)\n  negate (Net a b c)    = Net (negate a) (negate b) (negate c)\n  fromInteger x         = Net (fromInteger x) (fromInteger x) (fromInteger x)\n\ninstance KnownNat2 i o => Fractional (Layer i o) where\n  Layer w1 b1 / Layer w2 b2 = Layer (w1 / w2) (b1 / b2)\n  recip (Layer w b)         = Layer (recip w) (recip b)\n  fromRational x            = Layer (fromRational x) (fromRational x)\n\ninstance KnownNat4 i h1 h2 o => Fractional (Network i h1 h2 o) where\n  Net a b c / Net d e f = Net (a / d) (b / e) (c / f)\n  recip (Net a b c)     = Net (recip a) (recip b) (recip c)\n  fromRational x        = Net (fromRational x) (fromRational x) (fromRational x)\n\ninstance KnownNat n => MWC.Variate (R n) where\n  uniform g = randomVector <$> MWC.uniform g <*> pure Uniform\n  uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance KnownNat2 m n => MWC.Variate (L m n) where\n  uniform g = uniformSample <$> MWC.uniform g <*> pure 0 <*> pure 1\n  uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance KnownNat2 i o => MWC.Variate (Layer i o) where\n  uniform g = Layer <$> MWC.uniform g <*> MWC.uniform g\n  uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\ninstance KnownNat4 i h1 h2 o => MWC.Variate (Network i h1 h2 o) where\n  uniform g = Net <$> MWC.uniform g <*> MWC.uniform g <*> MWC.uniform g\n  uniformR (l, h) g = (\\x -> x * (h - l) + l) <$> MWC.uniform g\n\n\n-- ========================================================================= --\n-- Basic math functions with back propagation\n\nmatVec :: forall m n . (KnownNat m, KnownNat n) => Op '[ L m n, R n ] (R m)\nmatVec = op2' $ \\m v -> (forward m v, backward m v)\n  where\n    forward :: L m n -> R n -> R m\n    forward m v = m #> v\n\n    backward :: L m n -> R n -> Maybe (R m) -> (L m n, R n)\n    backward m v (fromMaybe 1 -> g) = (g `outer` v, tr m #> g)\n\n\ndot :: forall n . KnownNat n => Op '[ R n, R n ] Double\ndot = op2' $ \\x y -> (forward x y, backward x y)\n  where\n    forward :: R n -> R n -> Double\n    forward x y = x <.> y\n\n    backward :: R n -> R n -> Maybe Double -> (R n, R n)\n    backward x y = \\case\n      Nothing -> (y, x)\n      Just g  -> (konst g * y, x * konst g)\n\n\nscale :: forall n . KnownNat n => Op '[ Double, R n ] (R n)\nscale = op2' $ \\a x -> (forward a x, backward a x)\n  where\n    forward :: Double -> R n -> R n\n    forward a x = konst a * x\n\n    backward :: Double -> R n -> Maybe (R n) -> (Double, R n)\n    backward a x = \\case\n      Nothing -> (HM.sumElements (extract x      ), konst a    )\n      Just g  -> (HM.sumElements (extract (x * g)), konst a * g)\n\n\nvsum :: forall n . KnownNat n => Op '[ R n ] Double\nvsum = op1' $ \\x -> (forward x, backward)\n  where\n    forward :: R n -> Double\n    forward = HM.sumElements . extract\n\n    backward :: Maybe Double -> R n\n    backward = maybe 1 konst\n\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\n\n-- ========================================================================= --\n-- run backpropagation\ntype LayerCtx i o = '[R i, Layer i o]\ntype NetCtx i h1 h2 o = '[ R i, Network i h1 h2 o ]\n\nrunLayer :: forall i o s . (KnownNat i, KnownNat o) => BPOp s '[ R i, Layer i o ] (R o)\nrunLayer = withInps $ \\(decombinate -> (x, l)) -> do\n  w :< b :< _ <- partsVar gTuple l\n  y <- opVar matVec (w :< x :< nil)\n  return $ y + b\n  where\n    decombinate\n      :: Prod (BVar s (LayerCtx i o)) '[R i, Layer i o]\n      -> (BVar s (LayerCtx i o) (R i), BVar s (LayerCtx i o) (Layer i o))\n    decombinate (x :< l :< _) = (x, l)\n\n\nrunNetwork :: KnownNat4 i h1 h2 o => BPOp s (NetCtx i h1 h2 o) (R o)\nrunNetwork = withInps $ \\(x :< n :< _) -> do\n  l1 :< l2 :< l3 :< _ <- partsVar gTuple n\n\n  y <- bindVar $ liftB (bpOp runLayer) (x :< l1 :< nil)\n  -- or\n  z <- bindVar $ (bpOp runLayer) .$ (logistic y :< l2 :< nil)\n  -- or\n  r <- (bpOp runLayer) ~$ (logistic z :< l3 :< nil)\n\n  bpOp softmax ~$ only r\n  where\n    softmax :: KnownNat n => BPOp s '[ R n ] (R n)\n    softmax = withInps $ \\(x :< _) -> do\n      expX <- bindVar (exp x)\n      totX <- vsum ~$ (expX :< nil)\n      scale        ~$ (1 / totX :< expX :< nil)\n\n\nrunNetOnInp :: KnownNat4 i h1 h2 o => Network i h1 h2 o -> R i -> R o\nrunNetOnInp n x = evalBPOp runNetwork (x ::< n ::< nil)\n\n\ngradNet :: KnownNat4 i h1 h2 o => Network i h1 h2 o -> R i -> Network i h1 h2 o\ngradNet n x = case gradBPOp runNetwork (x ::< n ::< nil) of\n    _gradX ::< gradN ::< nil -> gradN\n\n\n-- ========================================================================= --\n\n-- crossEntropy :: forall s n . KnownNat n => R n -> BPOp s '[ R n ] Double\n-- crossEntropy targ = withInps $ \\(r :< _) ->\n--   negate (dot ~$ (log r :< only t))\n--   where\n--     t :: BVar s '[R n] (R n)\n--     t = constVar targ\n\n\ncrossEntropyI :: forall s n . KnownNat n => R n -> BPOpI s '[ R n ] Double\ncrossEntropyI targ (r :< _) = negate (dot .$ (log r :< only t))\n  where\n    t :: BVar s '[R n] (R n)\n    t = constVar targ\n\n\nsoftMaxCrossEntropy :: forall s n . KnownNat n => R n -> BPOp s '[ R n ] Double\nsoftMaxCrossEntropy targ = withInps $ \\(r :< \u00d8) -> do\n  bindVar $ realToFrac tsum * log (vsum .$ (only r)) - (dot .$ (r :< t :< nil))\n  where\n    tsum :: Double\n    tsum = HM.sumElements . extract $ targ\n\n    t :: BVar s '[R n] (R n)\n    t = constVar targ\n\n\nsoftMaxCrossEntropyI :: forall s n . KnownNat n => R n -> BPOpI s '[ R n ] Double\nsoftMaxCrossEntropyI targ (r :< \u00d8) =\n  realToFrac tsum * log (vsum .$ (only r)) - (dot .$ (r :< t :< nil))\n  where\n    tsum :: Double\n    tsum = HM.sumElements . extract $ targ\n\n    t :: BVar s '[R n] (R n)\n    t = constVar targ\n\n\ntrainStep\n  :: forall i h1 h2 o. KnownNat4 i h1 h2 o\n  => Double\n  -> R i\n  -> R o\n  -> Network i h1 h2 o\n  -> Network i h1 h2 o\ntrainStep r !x !t !n =\n  case gradBPOp o (x ::< n ::< nil) of\n    (_ :< I gN :< _) -> n - (realToFrac r * gN)\n  where\n    o :: BPOp s '[ R i, Network i h1 h2 o ] Double\n    o = do\n      y <- runNetwork\n      implicitly (crossEntropyI t) -$ (y :< nil)\n\ntrainList\n  :: KnownNat4 i h1 h2 o\n  => Double\n  -> [(R i, R o)]\n  -> Network i h1 h2 o\n  -> Network i h1 h2 o\ntrainList r = flip $ foldl' (\\n (x,y) -> trainStep r x y n)\n\ntestNet\n  :: forall i h1 h2 o. KnownNat4 i h1 h2 o\n  => [(R i, R o)]\n  -> Network i h1 h2 o\n  -> Double\ntestNet xs n = sum (map (\\(i,o) -> test i o) xs) / fromIntegral (length xs)\n  where\n    test :: R i -> R o -> Double\n    test x (extract->t) = fromIntegral . fromEnum $\n      HM.maxIndex t == HM.maxIndex (extract r)\n      where\n        r :: R o\n        r = evalBPOp runNetwork (x ::< n ::< nil)\n\n\nmain :: IO ()\nmain = MWC.withSystemRandom $ \\g -> do\n  -- initialize data and network\n  !trainingSet <- trainingDataBp\n  !testSet     <- testDataBp\n  !net0        <- MWC.uniformR @(Network 784 300 100 9) (-0.5, 0.5) g\n\n  flip evalStateT net0 . forM_ [1..100] $ \\e -> do\n    trainingSet' <- liftIO . fmap V.toList $ MWC.uniformShuffle (V.fromList trainingSet) g\n    liftIO $ printf \"[Epoch %d]\\n\" (e :: Int)\n\n    forM_ ([1..] `zip` chunksOf batch trainingSet') $ \\(b, chnk) -> StateT $ \\n0 -> do\n      printf \"(Batch %d)\\n\" (b :: Int)\n\n      -- t0 <- getCurrentTime\n      n' <- evaluate . force $ trainList rate chnk n0\n      -- t1 <- getCurrentTime\n      -- printf \"Trained on %d points in %s.\\n\" batch (show (t1 `diffUTCTime` t0))\n\n      let trainScore = testNet chnk    n'\n          testScore  = testNet testSet n'\n      printf \"Training error:   %.2f%%\\n\" ((1 - trainScore) * 100)\n      -- printf \"Validation error: %.2f%%\\n\" ((1 - testScore ) * 100)\n\n      return ((), n')\n  where\n    rate = 0.0001\n    batch = 100\n\n  --  go :: StateT (Network 784 300 100 9) IO ()\n  --  go = do\n  --    e <- get\n\n--\n--   -- Test\n--   let testPreds = map (take 3 testSet) $ \\(x, _) -> evalBPOp runNetwork (x ::< net0 ::< nil)\n--\n--   liftIO $ forM_ ([0..3] :: [Int]) $ \\i -> do\n--       -- T.putStrLn $ drawMNIST $ testImages !! i\n--       putStrLn $ \"\\n\" ++ \"expected \" ++ show (testLabels !! i)\n--       putStrLn $         \"     got \" ++ show (testPreds !! i)\n--\n--\n", "meta": {"hexsha": "29f4e7ba6b659fca961b7107c64a7cc71a63067b", "size": 10089, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/MNIST/Backprop/Accelerate.hs", "max_stars_repo_name": "stites/haskell-mnist-benchmarks", "max_stars_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/MNIST/Backprop/Accelerate.hs", "max_issues_repo_name": "stites/haskell-mnist-benchmarks", "max_issues_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/MNIST/Backprop/Accelerate.hs", "max_forks_repo_name": "stites/haskell-mnist-benchmarks", "max_forks_repo_head_hexsha": "00dda97e764d078f9ed6989faf0b8a7f2553260f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6504854369, "max_line_length": 95, "alphanum_fraction": 0.5407869957, "num_tokens": 3481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4346662890677762}}
{"text": "{-# LANGUAGE UndecidableInstances,ScopedTypeVariables,FlexibleContexts,RankNTypes,NoMonomorphismRestriction #-}\nimport Numeric.LinearAlgebra hiding ((><))\nimport Control.Applicative\nimport Foreign.Cholesky\nimport Linear.Metric\nimport Data.Functor.Compose\nimport qualified Data.Foldable as F\nimport Space.Class\nimport Linear.Vector\nimport Linear.V1\nimport Data.Profunctor\nimport Data.Monoid\nimport Linear.V2\nimport Test.QuickCheck\nimport Data.Distributive\nimport Linear.V3\nimport Linear.V4\nimport Linear.Quaternion\nimport Linear.Matrix\nimport Foreign.Cholesky\nimport Vectorization\nimport Control.Lens\nimport Kalman\n\nimport Test.Tasty\nimport Test.Tasty.SmallCheck as SC\nimport Test.Tasty.QuickCheck as QC\nimport Test.Tasty.HUnit\n\n-- Aided Inertial Navigation -- Example 5.4\n\npe0 = (V2 (V2 100 0) (V2 0 100))\nxe0 = V2 0 (0 :: Double)\nse0 = (xe0,sqrtM pe0)\nsc0 = (xe0,pe0)\n\nsqrtM = unRight . potrf\n\nqr0 = (V2 (V2 0.1 0 ) (V2 0 0.1))\n\n\nhe0 :: V2 Double -> V1 Double\nhe0 (V2 x _) = V1 x\nhe1 (V2 _ y) = V1 y\nhe2 (V2 x y) = V1 (x*0.7 + 0.3*y)\nhe3 (V2 x y) = V1 (x*0.5 + y*0.5)\n\nf t a (V2 x y) = (V2 y a )\nm0 = (he0,re0,ye0)\nm1 = (he1,re1,ye1)\nm2 = (he2,re2,ye2)\nm3 = (he3,re3,ye3)\n\nmlist = [m0,m1,m2,m3]\n\nre0 :: V1 (V1 Double)\nre0 = 1\nre1 = 1\nre2 = 1\nre3 = 1\n\nhn x = (distribute $ V4 (he0 x)(he1 x) (he2 x) (he3 x))^. _x\n\nrn = V4\n       (V4 1 0 0  0 )\n       (V4 0 1 0 0 )\n       (V4 0 0 1 0)\n       (V4 0 0 0 1)\n\nV1 yn = distribute (V4 ye0 ye1 ye2 ye3)\n\nye0 = V1 10.24\nye1 = V1 21.20\nye2 = V1 13.91\nye3 = V1 14.84\n\nmeasure' (h,r,y) = sqrtMeasure h r y\nsef = foldr measure' se0 (reverse mlist)\n\nmain = defaultMain tests\ntests :: TestTree\ntests = testGroup \"Tests\" [properties ]\nproperties = testGroup \"Property\" [quick] -- ,small]\n\nquick = testGroup \"(checked by QuickCheck)\"\n    [ QC.testProperty \"x == sqrt x * sqrt x\"  propSquare\n    , QC.testProperty \"measureState \" propState    \n    , QC.testProperty \"measureCovariance\" propCovariance\n    , QC.testProperty \"propMulti\" propMulti\n    ]\n{-\nsmall = testGroup \"(checked by SmallCheck)\"\n  [ SC.testProperty \"x == sqrt x * sqrt x\"  propSquare\n  ]\n-}\n\nnewtype Square f a = Square {unSquare :: (f (f a) )}\n\ninstance (Traversable f ,Show (f (f a)) ) => Show (Square f a ) where \n    show  = show . unSquare \n\ninstance (R f,Floating a , Fractional a ,Num a , Arbitrary a, Arbitrary (f (f a)) ) => Arbitrary (Square f a ) where\n    arbitrary = fmap (Square . squareT)  tgen\n        where tgen = arbitrary :: Gen (f (f a))\n            \n\ninstance (Num a ,Arbitrary a )=> Arbitrary (V2 a)  where\n    arbitrary = V2 <$> (((+1).abs) <$> arbitrary ) <*> (((+1).abs) <$>  arbitrary)\n \ninstance (Num a ,Arbitrary a )=> Arbitrary (V1 a)  where\n    arbitrary = fmap (pure . (+1) . abs ) arbitrary\n    \nsquareNeg :: (Num a, R f) => f a -> f (f a)\nsquareNeg v = mult v (fmap negate v) \n\npropCovariance (Square re0 ) ye1 s1 (Square s2) =  nearEqual (snd sc2) (squareT $ snd se2)\n    where\n        se2 = sqrtMeasure he1 (sqrtM re0) ye1 (s1,sqrtM s2) \n        sc2 = measure he1 re0 ye1 (s1,s2) \n\n\npropSquare :: Square V2 Double -> Bool\npropSquare (Square x)  = nearEqual x (distribute sq !*! sq)\n    where sq = sqrtM x\n\npropMulti s1 (Square s2) =  nearEqualP t (fst sn1) (fst sn2)   &&   nearEqualP (t+3) (snd sn1) (snd sn2)\n    where\n        t = 7\n        sn2 = sqrtMeasure hn (sqrtM rn) yn (s1,sqrtM s2) \n        m1 (h,y) = sqrtMeasure h (sqrtM re0) y \n        l = reverse [(he0,ye0),(he1,ye1),(he2,ye2),(he3,ye3)]\n        sn1 = foldr m1 (s1,sqrtM s2) l \n\npropState (Square re0 ) ye1 s1 (Square s2) = nearEqual (fst sc2) (fst se2) -- && nearEqual (snd sc2) (squareT $ snd se2)\n    where\n        se2 = sqrtMeasure he1 (sqrtM re0) ye1 (s1,sqrtM s2) \n        sc2 = measure he1 re0 ye1 (s1,s2) \n\n\nnearEqualP t x y = abs (x - y) < eps*(abs x) && abs (y - x) < eps*(abs y) \n    where eps = 10^t*2.220446049250313e-16\n\nnearEqual x y = abs (x - y) < eps*(abs x) && abs (y - x) < eps*(abs y) \n    where eps = 1000000*2.220446049250313e-16\n\n", "meta": {"hexsha": "09e2d1730da2f44c31091bfae203016bcf1b0366", "size": 3956, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Test.hs", "max_stars_repo_name": "massudaw/mtk", "max_stars_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Test.hs", "max_issues_repo_name": "massudaw/mtk", "max_issues_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test.hs", "max_forks_repo_name": "massudaw/mtk", "max_forks_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.095890411, "max_line_length": 120, "alphanum_fraction": 0.6362487361, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.43466628390407863}}
{"text": "module Language.Scheme.Parser where\n\nimport Language.Scheme.Types\nimport Language.Scheme.Error\nimport Language.Scheme.Error.Types\n\nimport Text.ParserCombinators.Parsec hiding (spaces)\nimport Numeric (readHex, readInt, readOct, readFloat)\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\nimport Data.Complex (Complex((:+)))\nimport Data.Ratio ((%))\nimport Control.Monad.Except (throwError)\n\nsymbol :: Parser Char\nsymbol = oneOf \"!#$%&|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\nescapedChars :: Parser Char\nescapedChars = do\n  char '\\\\'\n  x <- oneOf \"\\\\\\\"nrt\"\n  return x\n\nparseString :: Parser LispVal\nparseString = do\n  char '\"'\n  x <- many $ escapedChars <|> noneOf \"\\\"\\\\\"\n  char '\"'\n  return $ String x\n\nparseAtom :: Parser LispVal\nparseAtom = do\n  first <- letter <|> symbol\n  rest <- many $ letter <|> digit <|> symbol\n  let atom = first:rest\n  return $ Atom atom\n\nparseHash :: Parser LispVal\nparseHash = do\n  c <- hashchar\n  case c of\n    -- Will always be one of these values since\n    -- hashchar parses only these characters\n    't' -> return $ Bool True\n    'f' -> return $ Bool False\n    'd' -> parseNumber\n    'x' -> parseNumberHex\n    'o' -> parseNumberOct\n    'b' -> parseNumberBin\n    '\\\\' -> parseChar\n\nparseChar :: Parser LispVal\nparseChar = do\n  c <- anyChar\n  return $ Character c\n\ngetDouble :: String -> Double\ngetDouble = getValue . readFloat\n\ntoDouble :: LispVal -> Double\ntoDouble (Number (Real f))  = f\ntoDouble (Number (Integer n)) = fromIntegral n\n\nparseReal :: Parser LispVal\nparseReal = liftM (Number . Real . getDouble) float\n    where float = (++) <$> digits <*> decimal\n          decimal = (:) <$> char '.' <*> digits\n\nparseRational :: Parser LispVal\nparseRational = do\n  numer <- digits\n  char '/'\n  denom <- digits\n  return $ Number $ Rational ((read numer) % (read denom))\n\nparseComplex :: Parser LispVal\nparseComplex = do\n  x <- (try parseReal <|> parseInteger)\n  char '+'\n  y <- (try parseReal <|> parseInteger)\n  char 'i'\n  return $ Number $ Complex (toDouble x :+ toDouble y)\n\ndigits :: Parser String\ndigits = many1 digit\n\nhashchar :: Parser Char\nhashchar = char '#' >> oneOf \"boxdtf\\\\\"\n\n-- Gets the value from a read function such as readHex\n-- Since the parser handles parsing we know it will always\n-- produce a value if the parser successes\ngetValue :: [(a, String)] -> a\ngetValue [(x,_)] = x\ngetValue _       = error \"Should not happen\"\n\nhexToNum :: (Num a, Eq a) => String -> a\nhexToNum = getValue . readHex\n\noctToNum :: (Num a, Eq a) => String -> a\noctToNum = getValue . readOct\n\nbinToNum :: (Num a, Eq a) => String -> a\nbinToNum = getValue . readBin\n\nisBinChar :: Char -> Bool\nisBinChar '0' = True\nisBinChar '1' = True\nisBinChar _   = False\n\nbinCharToInt :: Char -> Int\nbinCharToInt '0' = 0\nbinCharToInt '1' = 1\nbinCharToInt _   = error \"Not a binary character\"\n\nreadBin :: (Num a, Eq a) => ReadS a\nreadBin = readInt 2 isBinChar binCharToInt\n\nbinDigits :: Parser String\nbinDigits = many1 $ oneOf \"01\"\n\nhexDigits :: Parser String\nhexDigits = many1 hexDigit\n\noctDigits :: Parser String\noctDigits = many1 octDigit\n\nparseNumberBin :: Parser LispVal\nparseNumberBin = liftM (Number . Integer . binToNum) binDigits\n\nparseNumberHex :: Parser LispVal\nparseNumberHex = liftM (Number . Integer . hexToNum) hexDigits\n\nparseNumberOct :: Parser LispVal\nparseNumberOct = liftM (Number . Integer . octToNum) octDigits\n\nparseInteger :: Parser LispVal\nparseInteger = liftM (Number . Integer . read) digits\n\nparseNumber :: Parser LispVal\nparseNumber = try parseReal <|> try parseRational <|> try parseComplex <|> parseInteger\n\nparseList :: Parser LispVal\nparseList = liftM List $ sepBy parseExpr spaces\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n  head <- endBy parseExpr spaces\n  tail <- char '.' >> spaces >> parseExpr\n  return $ DottedList head tail\n\nparseQuoted :: Parser LispVal\nparseQuoted = do\n  char '\\''\n  x <- parseExpr\n  return $ List [Atom \"quote\", x]\n\nparseExpr :: Parser LispVal\nparseExpr = parseHash\n            <|> parseAtom\n            <|> parseString\n            <|> parseNumber\n            <|> parseQuoted\n            <|> do char '('\n                   x <- try parseList <|> parseDottedList\n                   char ')'\n                   return x\n\nreadExpr :: String -> ThrowsError LispVal\nreadExpr input = case parse parseExpr \"lisp\" input of\n                   Left err -> throwError $ Parser err\n                   Right val  -> return val\n", "meta": {"hexsha": "632e664477516dd2f0d2f6974632bfd7b24f5a68", "size": 4441, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Language/Scheme/Parser.hs", "max_stars_repo_name": "stefaneng/scheme48", "max_stars_repo_head_hexsha": "5ddea0e3ca615c90cb60d47eed40faa366672a73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-26T07:45:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T07:45:37.000Z", "max_issues_repo_path": "src/Language/Scheme/Parser.hs", "max_issues_repo_name": "stefaneng/scheme48", "max_issues_repo_head_hexsha": "5ddea0e3ca615c90cb60d47eed40faa366672a73", "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/Language/Scheme/Parser.hs", "max_forks_repo_name": "stefaneng/scheme48", "max_forks_repo_head_hexsha": "5ddea0e3ca615c90cb60d47eed40faa366672a73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-26T07:45:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T07:45:42.000Z", "avg_line_length": 25.2329545455, "max_line_length": 87, "alphanum_fraction": 0.6624634091, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.43398749518696916}}
{"text": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Main where\nimport Control.Monad.ST\nimport Control.Monad.Trans.Reader\nimport System.Random.MWC\nimport Data.Word\nimport Data.Maybe (isJust)\nimport Control.Monad (replicateM)\nimport Control.Monad.State\nimport System.Exit\nimport Data.List (sort)\nimport qualified Data.Vector.Generic hiding (replicateM, sum, product)\nimport Statistics.Distribution\nimport Statistics.Distribution.Exponential\nimport Graphics.Rendering.Chart\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Data.Default.Class\nimport Control.Lens\n\n-- Ereignis Objekt\ndata Event = Arrival {\n    time :: Double,\n    customersWaiting :: Int\n  } | Departure {\n    time :: Double,\n    customersWaiting :: Int,\n    waitingTime :: Double\n  }deriving (Show)\n\ndata Simulation = Simulation [Double] Double (Maybe Double)\n\n-- exponentiell verteilten Zufallswert f\u00fcr die Bedienzeit\nrndServiceTime :: Rand Double\nrndServiceTime = genContV $ exponential 0.9\n\n-- Zeit bis zur n\u00e4chsten Ankunft eines Kunden\nrndTimeNextCustomer :: Rand Double\nrndTimeNextCustomer = genContV $ exponential 0.6 -- (1/0.6)\n\ndeparture :: Int -> Simulation -> IO [Event]\ndeparture n (Simulation [] _ _) = exitWith (ExitFailure 1)\ndeparture n (Simulation _ _ Nothing) = exitWith (ExitFailure 1)\ndeparture n (Simulation (wc:ws) nc (Just t)) = do\n    let l = length ws -- get amount of waiting customers\n    st <- if l == 0 then return Nothing else Just <$> (+) t <$> runRandIO rndServiceTime -- service time of the arrived customer\n    (Departure t l (t-wc):) <$> step (n-1) (Simulation ws nc st) -- create the event\n\narrival :: Int -> Simulation -> IO [Event]\narrival n (Simulation wc t st) = do\n    nc <- (+) t <$> runRandIO rndTimeNextCustomer  -- when the next customer will arrive\n    let dp = wc ++ [t] -- times of waiting customers\n    st <- if isJust st then return st else Just <$> (+) t <$> runRandIO rndServiceTime  -- service time of the arrived customer if there is not already a customer served\n    (Arrival t (length dp):) <$> step (n-1) (Simulation dp nc st) -- create the event\n\nisArrival :: Simulation -> Bool\nisArrival (Simulation [] _ _) = True\nisArrival (Simulation _ _ Nothing) = True\nisArrival (Simulation _ ac (Just dc)) = ac <= dc\n\nstep :: Int -> Simulation -> IO [Event]\nstep 0 _ = return []\nstep n sim = if isArrival sim\n             then arrival n sim\n             else departure n sim\n\nrunSim :: Int -> IO [Event]\nrunSim n = step n (Simulation [] 0 Nothing)\n\nmain = do\n    events <-  runSim 100\n    let xy = map (\\e -> (time e, customersWaiting e)) events\n    let formattedData = concat $ map format $ zipWith (\\a b -> (a, fst b, snd b)) ((head xy):(init xy)) $ zip xy ((tail xy) ++ [last xy])\n    renderableToFile def \"simulation.svg\" $ chart $ formattedData\n    putStrLn $ (\"Maximale Wartezeit: \" ++) . show $ maximum $ [ w | x@(Departure _ _ w) <- events ]\n    putStrLn $ (\"Maximale Anzahl wartender Kunden: \" ++) . show $ maximum $ map customersWaiting events\n  where\n    format ((t1, cw1), (t2, cw2), (t3, cw3)) = [(average t1 t2, cw1), (average t1 t2, cw2), (average t2 t3, cw2)]\n    average x y = (x+y)/2\n\n\n\n\ntype Rand0 s a = ReaderT (Gen s) (ST s) a\ntype Rand a = (forall s. Rand0 s a)  -- the random-sampling monad\n\n-- Draw from the continuous distribution d\ngenContV d = ask >>= genContVar d\n\n-- Provide a seed for the PRNG and return a draw from the random sampler\nrunRandV :: Data.Vector.Generic.Vector v Word32 => Rand a -> v Word32 -> a\nrunRandV rand seeds =\n  runST $ initialize seeds >>= runReaderT rand\n\n-- Seed the PRNG with data from the system's fast source of pseudo-random numbers,\n-- then return a draw from the random sampler\nrunRandIO :: Rand a -> IO a\nrunRandIO rand = do\n  gen <- createSystemRandom\n  seeds <- fromSeed <$> save gen\n  return $ runRandV rand seeds\n\n-- Render plot\n\nchart xs = toRenderable layout\n  where\n    plot = plot_lines_values .~ [xs]\n             $ def\n    layout = layout_title .~ \"Wartende Kunden\"\n           $ layout_x_axis . laxis_title .~ \"Zeit\"\n           $ layout_y_axis . laxis_title .~ \"Kunden\"\n           $ layout_plots .~ [toPlot plot]\n           $ def", "meta": {"hexsha": "28d2b8d821f09a6a7e4edadaf78f876f9c1297fe", "size": 4137, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "simulation32/Main.hs", "max_stars_repo_name": "Zortaniac/simulation", "max_stars_repo_head_hexsha": "569b45fbaca75acc9af5fadbdcf613cee504244b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation32/Main.hs", "max_issues_repo_name": "Zortaniac/simulation", "max_issues_repo_head_hexsha": "569b45fbaca75acc9af5fadbdcf613cee504244b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation32/Main.hs", "max_forks_repo_name": "Zortaniac/simulation", "max_forks_repo_head_hexsha": "569b45fbaca75acc9af5fadbdcf613cee504244b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2894736842, "max_line_length": 169, "alphanum_fraction": 0.681653372, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4339874951869691}}
{"text": "{-# LANGUAGE BangPatterns               #-}\n{-# LANGUAGE DeriveFoldable             #-}\n{-# LANGUAGE DeriveFunctor              #-}\n{-# LANGUAGE DeriveGeneric              #-}\n{-# LANGUAGE DeriveTraversable          #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses      #-}\n{-# LANGUAGE RankNTypes                 #-}\n{-# LANGUAGE ScopedTypeVariables        #-}\n{-# LANGUAGE StandaloneDeriving         #-}\n{-# LANGUAGE TemplateHaskell            #-}\n{-# LANGUAGE TypeFamilies               #-}\n\n{-|\nModule: Data.Semiring\nDescription: Haskell semirings\nLicense: MIT\nMaintainer: mail@doisinkidney.com\nStability: experimental\n-}\nmodule Data.Semiring\n  (\n   -- * Semiring classes\n   Semiring(..)\n  ,StarSemiring(..)\n  ,mulFoldable\n  ,addFoldable\n  ,\n   -- * Helper classes\n   HasPositiveInfinity(..)\n  ,HasNegativeInfinity(..)\n  ,DetectableZero(..)\n  ,\n   -- * Monoidal wrappers\n   Add(..)\n  ,Mul(..)\n  ,\n   -- * Ordering wrappers\n   Max(..)\n  ,Min(..)\n  ,\n   -- * Matrix wrapper\n   Matrix(..)\n  ,transpose\n  ,mulMatrix\n  ,rows\n  ,cols)\n  where\n\nimport           Data.Complex                (Complex)\nimport           Data.Fixed                  (Fixed, HasResolution)\nimport           Data.Functor.Identity       (Identity (..))\nimport           Data.Int                    (Int16, Int32, Int64, Int8)\nimport           Data.Ratio                  (Ratio)\nimport           Data.Scientific             (Scientific)\nimport           Data.Time.Clock             (DiffTime, NominalDiffTime)\nimport           Data.Word                   (Word16, Word32, Word64, Word8)\nimport           Foreign.C.Types             (CChar, CClock, CDouble, CFloat,\n                                              CInt, CIntMax, CIntPtr, CLLong,\n                                              CLong, CPtrdiff, CSChar,\n                                              CSUSeconds, CShort, CSigAtomic,\n                                              CSize, CTime, CUChar, CUInt,\n                                              CUIntMax, CUIntPtr, CULLong,\n                                              CULong, CUSeconds, CUShort,\n                                              CWchar)\nimport           Foreign.Ptr                 (IntPtr, WordPtr)\nimport           Numeric.Natural             (Natural)\nimport           System.Posix.Types          (CCc, CDev, CGid, CIno, CMode,\n                                              CNlink, COff, CPid, CRLim, CSpeed,\n                                              CSsize, CTcflag, CUid, Fd)\n\nimport           Data.Semigroup              hiding (Max (..), Min (..))\n\nimport           Data.Coerce\nimport           Data.Typeable               (Typeable)\nimport           Foreign.Storable            (Storable)\nimport           GHC.Generics                (Generic, Generic1)\n\nimport           Data.Functor.Classes\nimport           Data.Semiring.TH\n\nimport           Data.Map.Strict             (Map)\nimport qualified Data.Map.Strict             as Map\n\nimport           Data.Set                    (Set)\nimport qualified Data.Set                    as Set\n\nimport           Data.Hashable\nimport qualified Data.HashMap.Strict         as HashMap\nimport qualified Data.HashSet                as HashSet\n\nimport qualified Data.Vector                 as Vector\nimport qualified Data.Vector.Generic         as G\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Storable        as StorableVector\nimport qualified Data.Vector.Unboxed         as UnboxedVector\nimport qualified Data.Vector.Unboxed.Base    as U\n\nimport           Control.DeepSeq\n\nimport           Numeric.Log                 hiding (sum)\nimport qualified Numeric.Log\nimport           Numeric.Log.Signed\n\nimport           Control.Applicative\nimport           Data.Foldable\nimport           Data.Traversable\n\nimport           Data.Semiring.Newtype\nimport           GHC.Base                    (build)\n\n\n-- $setup\n-- >>> import Data.Function\n\n-- | A <https://en.wikipedia.org/wiki/Semiring Semiring> is like the\n-- the combination of two 'Data.Monoid.Monoid's. The first\n-- is called '<+>'; it has the identity element 'zero', and it is\n-- commutative. The second is called '<.>'; it has identity element 'one',\n-- and it must distribute over '<+>'.\n--\n-- = Laws\n-- == Normal 'Monoid' laws\n--\n-- @(a '<+>' b) '<+>' c = a '<+>' (b '<+>' c)\n--'zero' '<+>' a = a '<+>' 'zero' = a\n--(a '<.>' b) '<.>' c = a '<.>' (b '<.>' c)\n--'one' '<.>' a = a '<.>' 'one' = a@\n--\n-- == Commutativity of '<+>'\n-- @a '<+>' b = b '<+>' a@\n--\n-- == Distribution of '<.>' over '<+>'\n-- @a '<.>' (b '<+>' c) = (a '<.>' b) '<+>' (a '<.>' c)\n--(a '<+>' b) '<.>' c = (a '<.>' c) '<+>' (b '<.>' c)@\n--\n-- == Annihilation\n-- @'zero' '<.>' a = a '<.>' 'zero' = 'zero'@\n--\n-- An ordered semiring follows the laws:\n--\n-- @x '<=' y => x '<+>' z '<=' y '<+>' z\n--x '<=' y => x '<+>' z '<=' y '<+>' z\n--'zero' '<=' z '&&' x '<=' y => x '<.>' z '<=' y '<.>' z '&&' z '<.>' x '<=' z '<.>' y@\nclass Semiring a  where\n    {-# MINIMAL zero , one , (<.>) , (<+>) #-}\n    -- | The identity of '<+>'.\n    zero\n        :: a\n    -- | The identity of '<.>'.\n    one\n        :: a\n    -- | An associative binary operation, which distributes over '<+>'.\n    infixl 7 <.>\n    (<.>) :: a -> a -> a\n    -- | An associative, commutative binary operation.\n    infixl 6 <+>\n    (<+>) :: a -> a -> a\n    -- | Takes the sum of the elements of a list. Analogous to 'sum'\n    -- on numbers, or 'or' on 'Bool's.\n    --\n    -- >>> add [1..5]\n    -- 15\n    -- >>> add [False, False]\n    -- False\n    -- >>> add [False, True]\n    -- True\n    -- >>> add [True, undefined]\n    -- True\n    add\n        :: [a] -> a\n    add = foldl' (<+>) zero\n    {-# INLINE add #-}\n    -- | Takes the product of the elements of a list. Analogous to\n    -- 'product' on numbers, or 'and' on 'Bool's.\n    --\n    -- >>> mul [1..5]\n    -- 120\n    -- >>> mul [True, True]\n    -- True\n    -- >>> mul [True, False]\n    -- False\n    -- >>> mul [False, undefined]\n    -- False\n    mul\n        :: [a] -> a\n    mul = foldl' (<.>) one\n    {-# INLINE mul #-}\n\n-- | The product of the contents of a 'Foldable'.\nmulFoldable :: (Foldable f, Semiring a) => f a -> a\nmulFoldable = mul . toList\n{-# INLINE mulFoldable #-}\n\n-- | The sum of the contents of a 'Foldable'.\naddFoldable :: (Foldable f, Semiring a) => f a -> a\naddFoldable = add . toList\n{-# INLINE addFoldable #-}\n\n\n-- | A <https://en.wikipedia.org/wiki/Semiring#Star_semirings Star semiring>\n-- adds one operation, 'star' to a 'Semiring', such that it follows the\n-- law:\n--\n-- @'star' x = 'one' '<+>' x '<.>' 'star' x = 'one' '<+>' 'star' x '<.>' x@\n--\n-- For the semiring of types, this is equivalent to a list. When looking\n-- at the 'Applicative' and 'Control.Applicative.Alternative' classes as\n-- (near-) semirings, this is equivalent to the\n-- 'Control.Applicative.many' operation.\n--\n-- Another operation, 'plus', can be defined in relation to 'star':\n--\n-- @'plus' x = x '<.>' 'star' x@\n--\n-- This should be recognizable as a non-empty list on types, or the\n-- 'Control.Applicative.some' operation in\n-- 'Control.Applicative.Alternative'.\nclass Semiring a =>\n      StarSemiring a  where\n    star :: a -> a\n    plus :: a -> a\n    star x = one <+> plus x\n    {-# INLINE star #-}\n    plus x = x <.> star x\n    {-# INLINE plus #-}\n\n-- | Useful for operations where zeroes may need to be discarded: for instance\n-- in sparse matrix calculations.\nclass Semiring a =>\n      DetectableZero a  where\n    -- | 'True' if x is 'zero'.\n    isZero\n        :: a -> Bool\n\nisZeroEq\n    :: (Semiring a, Eq a)\n    => a -> Bool\nisZeroEq = (zero ==)\n{-# INLINE isZeroEq #-}\n\n--------------------------------------------------------------------------------\n-- Infinites\n--------------------------------------------------------------------------------\n-- | A class for semirings with a concept of \"infinity\". It's important that\n-- this isn't regarded as the same as \"bounded\":\n-- @x '<+>' 'positiveInfinity'@ should probably equal 'positiveInfinity'.\nclass HasPositiveInfinity a  where\n    -- | A positive infinite value\n    positiveInfinity\n        :: a\n    -- | Test if a value is positive infinity.\n    isPositiveInfinity\n        :: a -> Bool\n\ndefaultPositiveInfinity\n    :: RealFloat a\n    => a\ndefaultPositiveInfinity = 1 / 0\n{-# INLINE defaultPositiveInfinity #-}\n\ndefaultIsPositiveInfinity\n    :: RealFloat a\n    => a -> Bool\ndefaultIsPositiveInfinity x = isInfinite x && x > 0\n{-# INLINE defaultIsPositiveInfinity #-}\n\n-- | A class for semirings with a concept of \"negative infinity\". It's important\\\n-- that this isn't regarded as the same as \"bounded\":\n-- @x '<+>' 'negativeInfinity'@ should probably equal 'negativeInfinity'.\nclass HasNegativeInfinity a  where\n    -- | A negative infinite value\n    negativeInfinity\n        :: a\n    -- | Test if a value is negative infinity.\n    isNegativeInfinity\n        :: a -> Bool\n\ndefaultIsNegativeInfinity\n    :: RealFloat a\n    => a -> Bool\ndefaultIsNegativeInfinity x = isInfinite x && x < 0\n{-# INLINE defaultIsNegativeInfinity #-}\n\ndefaultNegativeInfinity\n    :: RealFloat a\n    => a\ndefaultNegativeInfinity = negate (1 / 0)\n{-# INLINE defaultNegativeInfinity #-}\n\ninstance HasPositiveInfinity Double where\n    positiveInfinity = defaultPositiveInfinity\n    isPositiveInfinity = defaultIsPositiveInfinity\n    {-# INLINE positiveInfinity #-}\n    {-# INLINE isPositiveInfinity #-}\n\ninstance HasNegativeInfinity Double where\n    negativeInfinity = defaultNegativeInfinity\n    isNegativeInfinity = defaultIsNegativeInfinity\n    {-# INLINE negativeInfinity #-}\n    {-# INLINE isNegativeInfinity #-}\n\ninstance HasPositiveInfinity Float where\n    positiveInfinity = defaultPositiveInfinity\n    isPositiveInfinity = defaultIsPositiveInfinity\n    {-# INLINE positiveInfinity #-}\n    {-# INLINE isPositiveInfinity #-}\n\ninstance HasNegativeInfinity Float where\n    negativeInfinity = defaultNegativeInfinity\n    isNegativeInfinity = defaultIsNegativeInfinity\n    {-# INLINE negativeInfinity #-}\n    {-# INLINE isNegativeInfinity #-}\n\ninstance HasPositiveInfinity CDouble where\n    positiveInfinity = defaultPositiveInfinity\n    isPositiveInfinity = defaultIsPositiveInfinity\n    {-# INLINE positiveInfinity #-}\n    {-# INLINE isPositiveInfinity #-}\n\ninstance HasNegativeInfinity CDouble where\n    negativeInfinity = defaultNegativeInfinity\n    isNegativeInfinity = defaultIsNegativeInfinity\n    {-# INLINE negativeInfinity #-}\n    {-# INLINE isNegativeInfinity #-}\n\ninstance HasPositiveInfinity CFloat where\n    positiveInfinity = defaultPositiveInfinity\n    isPositiveInfinity = defaultIsPositiveInfinity\n    {-# INLINE positiveInfinity #-}\n    {-# INLINE isPositiveInfinity #-}\n\ninstance HasNegativeInfinity CFloat where\n    negativeInfinity = defaultNegativeInfinity\n    isNegativeInfinity = defaultIsNegativeInfinity\n    {-# INLINE negativeInfinity #-}\n    {-# INLINE isNegativeInfinity #-}\n\n--------------------------------------------------------------------------------\n-- Instances\n--------------------------------------------------------------------------------\ninstance Semiring Bool where\n    one = True\n    zero = False\n    (<+>) = (||)\n    (<.>) = (&&)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance StarSemiring Bool where\n    star _ = True\n    plus = id\n    {-# INLINE star #-}\n    {-# INLINE plus #-}\n\ninstance DetectableZero Bool where\n    isZero = not\n    {-# INLINE isZero #-}\n\ninstance Semiring () where\n    one = ()\n    zero = ()\n    _ <+> _ = ()\n    _ <.> _ = ()\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance DetectableZero () where\n    isZero _ = True\n    {-# INLINE isZero #-}\n\ninstance StarSemiring () where\n    star _ = ()\n    plus _ = ()\n    {-# INLINE star #-}\n    {-# INLINE plus #-}\n\n-- | A polynomial in /x/ can be defined as a list of its coefficients,\n-- where the /i/th element is the coefficient of /x^i/. This is the\n-- semiring for such a list. Adapted from\n-- <https://pdfs.semanticscholar.org/702d/348c32133997e992db362a19697d5607ab32.pdf here>.\n--\n-- Effort is made to allow some of these functions to fuse. The reference\n-- implementation is:\n--\n-- @\n-- 'one' = ['one']\n-- 'zero' = []\n-- [] '<+>' ys = ys\n-- xs '<+>' [] = xs\n-- (x:xs) '<+>' (y:ys) = x '<+>' y : (xs '<+>' ys)\n-- _ '<.>' [] = []\n-- xs '<.>' ys = 'foldr' f [] xs where\n--   f x zs = 'map' (x '<.>') ys '<+>' ('zero' : zs)\n-- @\ninstance Semiring a =>\n         Semiring [a] where\n    one = [one]\n    zero = []\n    (<+>) = listAdd\n    xs <.> ys\n      | null ys = []\n      | otherwise = foldr f [] xs\n      where\n        f x zs = foldr (g x) id ys (zero : zs)\n        g x y a (z:zs) = x <.> y <+> z : a zs\n        g x y a []     = x <.> y : a []\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n    {-# INLINE one #-}\n    {-# INLINE zero #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped [] Int #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped [] Word #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped [] Double #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped [] Int #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped [] Word #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped [] Double #-}\n\n\nlistAdd :: Semiring a => [a] -> [a] -> [a]\nlistAdd [] ys         = ys\nlistAdd xs []         = xs\nlistAdd (x:xs) (y:ys) = (x <+> y) : listAdd xs ys\n{-# NOINLINE [0] listAdd #-}\n{-# SPECIALISE listAdd :: BinaryWrapped [] Int #-}\n{-# SPECIALISE listAdd :: BinaryWrapped [] Word #-}\n{-# SPECIALISE listAdd :: BinaryWrapped [] Double #-}\n\n-- a definition of addition which can be fused on its left argument\nlistAddFBL :: Semiring a => ListBuilder a -> [a] -> [a]\nlistAddFBL xf = xf f id  where\n  f x xs (y:ys) = x <+> y : xs ys\n  f x xs []     = x : xs []\n\ntype FBL a = ListBuilder a -> [a] -> [a]\n{-# SPECIALISE listAddFBL :: FBL Int #-}\n{-# SPECIALISE listAddFBL :: FBL Word #-}\n{-# SPECIALISE listAddFBL :: FBL Double #-}\n\n-- a definition of addition which can be fused on its right argument\nlistAddFBR :: Semiring a => [a] -> ListBuilder a -> [a]\nlistAddFBR xs' yf = yf f id xs' where\n  f y ys (x:xs) = x <+> y : ys xs\n  f y ys []     = y : ys []\n\ntype FBR a = [a] -> ListBuilder a -> [a]\n{-# SPECIALISE listAddFBR :: FBR Int #-}\n{-# SPECIALISE listAddFBR :: FBR Word #-}\n{-# SPECIALISE listAddFBR :: FBR Double #-}\n\ntype ListBuilder a = forall b. (a -> b -> b) -> b -> b\n\n{-# RULES\n\"listAddFB/left\"  forall (g :: ListBuilder a). listAdd (build g) = listAddFBL g\n\"listAddFB/right\" forall xs (g :: ListBuilder a). listAdd xs (build g) = listAddFBR xs g\n  #-}\n\ninstance StarSemiring a => StarSemiring [a] where\n    star [] = one\n    star (x:xs) = r where\n      r = xst : map (xst <.>) (xs <.> r)\n      xst = star x\n    {-# SPECIALISE star :: [Bool] -> [Bool] #-}\n    {-# SPECIALISE star :: [Min Double]  -> [Min Double] #-}\n    {-# SPECIALISE star :: [Max Double]  -> [Max Double] #-}\n\ninstance DetectableZero a =>\n         DetectableZero [a] where\n    isZero = all isZero\n    {-# INLINE isZero #-}\n\ninstance Semiring a =>\n         Semiring (Vector.Vector a) where\n    one = Vector.singleton one\n    zero = Vector.empty\n    xs <+> ys =\n        case compare (Vector.length xs) (Vector.length ys) of\n            EQ -> Vector.zipWith (<+>) xs ys\n            LT -> Vector.unsafeAccumulate (<+>) ys (Vector.indexed xs)\n            GT -> Vector.unsafeAccumulate (<+>) xs (Vector.indexed ys)\n    signal <.> kernel\n      | Vector.null signal = Vector.empty\n      | Vector.null kernel = Vector.empty\n      | otherwise = Vector.generate (slen + klen - 1) f\n      where\n        f n =\n            foldl'\n                (\\a k ->\n                      a <+>\n                      Vector.unsafeIndex signal k <.>\n                      Vector.unsafeIndex kernel (n - k))\n                zero\n                [kmin .. kmax]\n          where\n            !kmin = max 0 (n - (klen - 1))\n            !kmax = min n (slen - 1)\n        !slen = Vector.length signal\n        !klen = Vector.length kernel\n    {-# SPECIALISE (<.>) :: BinaryWrapped Vector.Vector Double #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped Vector.Vector Int #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped Vector.Vector Word #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped Vector.Vector Double #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped Vector.Vector Int #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped Vector.Vector Word #-}\n\ninstance DetectableZero a => DetectableZero (Vector.Vector a) where\n    isZero = Vector.all isZero\n\ninstance (UnboxedVector.Unbox a, Semiring a) =>\n         Semiring (UnboxedVector.Vector a) where\n    one = UnboxedVector.singleton one\n    zero = UnboxedVector.empty\n    xs <+> ys =\n        case compare (UnboxedVector.length xs) (UnboxedVector.length ys) of\n            EQ -> UnboxedVector.zipWith (<+>) xs ys\n            LT -> UnboxedVector.unsafeAccumulate (<+>) ys (UnboxedVector.indexed xs)\n            GT -> UnboxedVector.unsafeAccumulate (<+>) xs (UnboxedVector.indexed ys)\n    signal <.> kernel\n      | UnboxedVector.null signal = UnboxedVector.empty\n      | UnboxedVector.null kernel = UnboxedVector.empty\n      | otherwise = UnboxedVector.generate (slen + klen - 1) f\n      where\n        f n =\n            foldl'\n                (\\a k ->\n                      a <+>\n                      UnboxedVector.unsafeIndex signal k <.>\n                      UnboxedVector.unsafeIndex kernel (n - k))\n                zero\n                [kmin .. kmax]\n          where\n            kmin = max 0 (n - (klen - 1))\n            kmax = min n (slen - 1)\n        slen = UnboxedVector.length signal\n        klen = UnboxedVector.length kernel\n    {-# SPECIALISE (<.>) :: BinaryWrapped UnboxedVector.Vector Double #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped UnboxedVector.Vector Int #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped UnboxedVector.Vector Word #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped UnboxedVector.Vector Double #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped UnboxedVector.Vector Int #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped UnboxedVector.Vector Word #-}\n\ninstance (UnboxedVector.Unbox a, DetectableZero a) => DetectableZero (UnboxedVector.Vector a) where\n    isZero = UnboxedVector.all isZero\n\ninstance (StorableVector.Storable a, Semiring a) =>\n         Semiring (StorableVector.Vector a) where\n    one = StorableVector.singleton one\n    zero = StorableVector.empty\n    xs <+> ys =\n        case compare lxs lys of\n            EQ -> StorableVector.zipWith (<+>) xs ys\n            LT -> StorableVector.unsafeAccumulate_ (<+>) ys (StorableVector.enumFromN 0 lxs) xs\n            GT -> StorableVector.unsafeAccumulate_ (<+>) xs (StorableVector.enumFromN 0 lys) ys\n      where\n        lxs = StorableVector.length xs\n        lys = StorableVector.length ys\n    signal <.> kernel\n      | StorableVector.null signal = StorableVector.empty\n      | StorableVector.null kernel = StorableVector.empty\n      | otherwise = StorableVector.generate (slen + klen - 1) f\n      where\n        f n =\n            foldl'\n                (\\a k ->\n                      a <+>\n                      StorableVector.unsafeIndex signal k <.>\n                      StorableVector.unsafeIndex kernel (n - k))\n                zero\n                [kmin .. kmax]\n          where\n            kmin = max 0 (n - (klen - 1))\n            kmax = min n (slen - 1)\n        slen = StorableVector.length signal\n        klen = StorableVector.length kernel\n    {-# SPECIALISE (<.>) :: BinaryWrapped StorableVector.Vector Double #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped StorableVector.Vector Int #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped StorableVector.Vector Word #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped StorableVector.Vector Double #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped StorableVector.Vector Int #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped StorableVector.Vector Word #-}\n\ninstance (StorableVector.Storable a, DetectableZero a) =>\n         DetectableZero (StorableVector.Vector a) where\n    isZero = StorableVector.all isZero\n\ninstance (Monoid a, Ord a) =>\n         Semiring (Set a) where\n    (<+>) = Set.union\n    zero = Set.empty\n    one = Set.singleton mempty\n    xs <.> ys = foldMap (flip Set.map ys . mappend) xs\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n\ninstance (Monoid a, Hashable a, Eq a) => Semiring (HashSet.HashSet a) where\n    (<+>) = HashSet.union\n    zero = HashSet.empty\n    one = HashSet.singleton mempty\n    xs <.> ys = foldMap (flip HashSet.map ys . mappend) xs\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n\ninstance (Ord a, Monoid a, Semiring b) =>\n         Semiring (Map a b) where\n    one = Map.singleton mempty one\n    {-# INLINE one #-}\n    zero = Map.empty\n    {-# INLINE zero #-}\n    (<+>) = Map.unionWith (<+>)\n    {-# INLINE (<+>) #-}\n    xs <.> ys =\n        Map.fromListWith\n            (<+>)\n            [ (mappend k l, v <.> u)\n            | (k,v) <- Map.toList xs\n            , (l,u) <- Map.toList ys ]\n    {-# INLINE (<.>) #-}\n\ninstance (Hashable a, Monoid a, Semiring b, Eq a) =>\n         Semiring (HashMap.HashMap a b) where\n    one = HashMap.singleton mempty one\n    {-# INLINE one #-}\n    zero = HashMap.empty\n    {-# INLINE zero #-}\n    (<+>) = HashMap.unionWith (<+>)\n    {-# INLINE (<+>) #-}\n    xs <.> ys =\n        HashMap.fromListWith\n            (<+>)\n            [ (mappend k l, v <.> u)\n            | (k,v) <- HashMap.toList xs\n            , (l,u) <- HashMap.toList ys ]\n    {-# INLINE (<.>) #-}\n\ninstance (Monoid a, Ord a) =>\n         DetectableZero (Set a) where\n    isZero = Set.null\n    {-# INLINE isZero #-}\n\ninstance (Monoid a, Hashable a, Eq a) =>\n         DetectableZero (HashSet.HashSet a) where\n    isZero = HashSet.null\n\ninstance (Precise a, RealFloat a) => Semiring (Log a) where\n    (<.>) = (*)\n    {-# INLINE (<.>) #-}\n    (<+>) = (+)\n    {-# INLINE (<+>) #-}\n    one = Exp 0\n    {-# INLINE one #-}\n    zero = Exp (-(1/0))\n    {-# INLINE zero #-}\n    add = Numeric.Log.sum\n    {-# INLINE add #-}\n\n    {-# SPECIALISE (<.>) :: BinaryWrapped Log Double #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped Log Double #-}\n\ninstance (Precise a, RealFloat a) => DetectableZero (Log a) where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance (Precise a, RealFloat a) => Semiring (SignedLog a) where\n    (<.>) = (*)\n    {-# INLINE (<.>) #-}\n    (<+>) = (+)\n    {-# INLINE (<+>) #-}\n    one = SLExp True 0\n    {-# INLINE one #-}\n    zero = SLExp False (-(1/0))\n    {-# INLINE zero #-}\n\n    {-# SPECIALISE (<.>) :: BinaryWrapped SignedLog Double #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped SignedLog Double #-}\n\ninstance (Precise a, RealFloat a) => DetectableZero (SignedLog a) where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n--------------------------------------------------------------------------------\n-- Addition and multiplication newtypes\n--------------------------------------------------------------------------------\n\n-- | Monoid under '<+>'. Analogous to 'Data.Monoid.Sum', but uses the\n-- 'Semiring' constraint, rather than 'Num'.\nnewtype Add a = Add\n    { getAdd :: a\n    } deriving (Eq,Ord,Read,Show,Bounded,Generic,Generic1,Num,Enum,Typeable\n               ,Storable,Fractional,Real,RealFrac,Functor,Foldable,Traversable\n               ,Semiring,DetectableZero,StarSemiring)\n\ninstance Eq1 Add where\n    liftEq = coerce\n    {-# INLINE liftEq #-}\n\ninstance Ord1 Add where\n    liftCompare = coerce\n    {-# INLINE liftCompare #-}\n\ninstance Show1 Add where\n    liftShowsPrec = showsNewtype \"Add\" \"getAdd\"\n    {-# INLINE liftShowsPrec #-}\n\ninstance Read1 Add where\n    liftReadsPrec = readsNewtype \"Add\" \"getAdd\"\n    {-# INLINE liftReadsPrec #-}\n\n-- | Monoid under '<.>'. Analogous to 'Data.Monoid.Product', but uses the\n-- 'Semiring' constraint, rather than 'Num'.\nnewtype Mul a = Mul\n    { getMul :: a\n    } deriving (Eq,Ord,Read,Show,Bounded,Generic,Generic1,Num,Enum,Typeable\n               ,Storable,Fractional,Real,RealFrac,Functor,Foldable,Traversable\n               ,Semiring,DetectableZero,StarSemiring)\n\ninstance Eq1 Mul where\n    liftEq = coerce\n    {-# INLINE liftEq #-}\n\ninstance Ord1 Mul where\n    liftCompare = coerce\n    {-# INLINE liftCompare #-}\n\ninstance Show1 Mul where\n    liftShowsPrec = showsNewtype \"Mul\" \"getMul\"\n    {-# INLINE liftShowsPrec #-}\n\ninstance Read1 Mul where\n    liftReadsPrec = readsNewtype \"Mul\" \"getMul\"\n    {-# INLINE liftReadsPrec #-}\n\ninstance Semiring a =>\n         Semigroup (Add a) where\n    (<>) = (coerce :: WrapBinary Add a) (<+>)\n    {-# INLINE (<>) #-}\n\ninstance Semiring a =>\n         Semigroup (Mul a) where\n    (<>) = (coerce :: WrapBinary Mul a) (<.>)\n    {-# INLINE (<>) #-}\n\ninstance Semiring a =>\n         Monoid (Add a) where\n    mempty = Add zero\n    {-# INLINE mempty #-}\n    mappend = (<>)\n    {-# INLINE mappend #-}\n    mconcat = (coerce :: ([a] -> a) -> [Add a] -> Add a) add\n    {-# INLINE mconcat #-}\n\ninstance Semiring a =>\n         Monoid (Mul a) where\n    mempty = Mul one\n    {-# INLINE mempty #-}\n    mappend = (<>)\n    {-# INLINE mappend #-}\n    mconcat = (coerce :: ([a] -> a) -> [Mul a] -> Mul a) mul\n    {-# INLINE mconcat #-}\n\n--------------------------------------------------------------------------------\n-- Traversable newtype\n--------------------------------------------------------------------------------\n-- | A suitable definition of a square matrix for certain types which are both\n-- 'Applicative' and 'Traversable'. For instance, given a type like so:\n--\n-- >>> :{\n-- data Quad a = Quad a a a a deriving Show\n-- instance Functor Quad where\n--     fmap f (Quad w x y z) = Quad (f w) (f x) (f y) (f z)\n-- instance Applicative Quad where\n--     pure x = Quad x x x x\n--     Quad fw fx fy fz <*> Quad xw xx xy xz =\n--         Quad (fw xw) (fx xx) (fy xy) (fz xz)\n-- instance Foldable Quad where\n--     foldr f b (Quad w x y z) = f w (f x (f y (f z b)))\n-- instance Traversable Quad where\n--     traverse f (Quad w x y z) = Quad <$> f w <*> f x <*> f y <*> f z\n-- :}\n--\n-- The newtype performs as you would expect:\n--\n-- >>> getMatrix one :: Quad (Quad Integer)\n-- Quad (Quad 1 0 0 0) (Quad 0 1 0 0) (Quad 0 0 1 0) (Quad 0 0 0 1)\n--\n-- 'ZipList's are another type which works with this newtype:\n--\n-- >>> :{\n-- let xs = (Matrix . ZipList . map ZipList) [[1,2],[3,4]]\n--     ys = (Matrix . ZipList . map ZipList) [[5,6],[7,8]]\n-- in (map getZipList . getZipList . getMatrix) (xs <.> ys)\n-- :}\n-- [[19,22],[43,50]]\nnewtype Matrix f g a = Matrix\n    { getMatrix :: f (g a)\n    } deriving (Generic,Generic1,Typeable,Functor,Foldable,Traversable)\n\ninstance (Applicative f, Applicative g) =>\n         Applicative (Matrix f g) where\n    pure = Matrix #. pure . pure\n    (<*>) =\n        (coerce :: (f (g (a -> b)) -> f (g a) -> f (g b)) -> Matrix f g (a -> b) -> Matrix f g a -> Matrix f g b)\n            (liftA2 (<*>))\n\ninstance (Traversable f, Applicative f, Semiring a, f ~ g) =>\n         Semiring (Matrix f g a) where\n    (<.>) = (coerce :: Binary (f (g a)) -> Binary (Matrix f g a)) mulMatrix\n    (<+>) = liftA2 (<+>)\n    zero = pure zero\n    one =\n        (coerce :: (f (g a) -> f (g a)) -> Matrix f g a -> Matrix f g a)\n            (imap (\\i -> imap (\\j z -> if i == j then o else z))) zero\n      where\n        imap f = snd . mapAccumL (\\ !i x -> (i + 1, f i x)) (0 :: Int)\n        o :: a\n        o = one\n\ninstance (Traversable f, Applicative f, DetectableZero a, f ~ g) =>\n         DetectableZero (Matrix f g a) where\n    isZero = all isZero\n\n-- | Transpose the matrix.\ntranspose :: (Applicative g, Traversable f) => Matrix f g a -> Matrix g f a\ntranspose (Matrix xs) = Matrix (sequenceA xs)\n\n-- | Multiply two matrices.\nmulMatrix\n    :: (Applicative n, Traversable m, Applicative m, Applicative p, Semiring a)\n    => n (m a) -> m (p a) -> n (p a)\nmulMatrix xs ys = fmap (\\row -> fmap (addFoldable . liftA2 (<.>) row) cs) xs\n  where\n    cs = sequenceA ys\n\n\n-- | Convert the matrix to a nested list, in row-major form.\nrows :: (Foldable f, Foldable g) => Matrix f g a -> [[a]]\nrows = foldr ((:) . toList) [] . getMatrix\n\n-- | Convert the matrix to a nested list, in column-major form.\ncols :: (Foldable f, Foldable g) => Matrix f g a -> [[a]]\ncols = foldr (foldr f (const [])) (repeat []) . getMatrix where\n  f e a (x:xs) = (e:x) : a xs\n  f _ _ []     = []\n\ninstance (Show1 f, Show1 g) =>\n         Show1 (Matrix f g) where\n    liftShowsPrec (sp :: Int -> a -> ShowS) sl =\n        showsNewtype \"Matrix\" \"getMatrix\" liftedTwiceSP liftedTwiceSL\n      where\n        liftedOnceSP :: Int -> g a -> ShowS\n        liftedOnceSP = liftShowsPrec sp sl\n        liftedOnceSL :: [g a] -> ShowS\n        liftedOnceSL = liftShowList sp sl\n        liftedTwiceSP :: Int -> f (g a) -> ShowS\n        liftedTwiceSP = liftShowsPrec liftedOnceSP liftedOnceSL\n        liftedTwiceSL :: [f (g a)] -> ShowS\n        liftedTwiceSL = liftShowList liftedOnceSP liftedOnceSL\n\ninstance (Read1 f, Read1 g) =>\n         Read1 (Matrix f g) where\n    liftReadsPrec (rp :: Int -> ReadS a) rl =\n        readsNewtype \"Matrix\" \"getMatrix\" liftedTwiceRP liftedTwiceRL\n      where\n        liftedOnceRP :: Int -> ReadS (g a)\n        liftedOnceRP = liftReadsPrec rp rl\n        liftedOnceRL :: ReadS [g a]\n        liftedOnceRL = liftReadList rp rl\n        liftedTwiceRP :: Int -> ReadS (f (g a))\n        liftedTwiceRP = liftReadsPrec liftedOnceRP liftedOnceRL\n        liftedTwiceRL :: ReadS [f (g a)]\n        liftedTwiceRL = liftReadList liftedOnceRP liftedOnceRL\n\ninstance (Eq1 f, Eq1 g) =>\n         Eq1 (Matrix f g) where\n    liftEq (eq :: a -> b -> Bool) =\n        coerce (liftEq (liftEq eq) :: f (g a) -> f (g b) -> Bool)\n\ninstance (Ord1 f, Ord1 g) => Ord1 (Matrix f g) where\n    liftCompare (cmp :: a -> b -> Ordering) =\n        coerce (liftCompare (liftCompare cmp) :: f (g a) -> f (g b) -> Ordering)\n\ninstance (Show1 f, Show1 g, Show a) => Show (Matrix f g a) where\n    showsPrec = showsPrec1\n\ninstance (Read1 f, Read1 g, Read a) => Read (Matrix f g a) where\n    readsPrec = readsPrec1\n\ninstance (Eq1 f, Eq1 g, Eq a) => Eq (Matrix f g a) where\n    (==) = eq1\n\ninstance (Ord1 f, Ord1 g, Ord a) => Ord (Matrix f g a) where\n    compare = compare1\n\n--------------------------------------------------------------------------------\n-- Ord wrappers\n--------------------------------------------------------------------------------\n-- | The \"<https://ncatlab.org/nlab/show/tropical+semiring Tropical>\" or\n-- min-plus semiring. It is a semiring where:\n--\n-- @'<+>'  = 'min'\n--'zero' = \u221e\n--'<.>'  = '<+>'\n--'one'  = 'zero'@\n--\n-- Note that we can't use 'Data.Semigroup.Min' from 'Data.Semigroup'\n-- because annihilation needs to hold:\n--\n-- @\u221e '<+>' x = x '<+>' \u221e = \u221e@\n--\n-- Taking \u221e to be 'maxBound' would break the above law. Using 'positiveInfinity'\n-- to represent it follows the law.\nnewtype Min a = Min\n    { getMin :: a\n    } deriving (Eq,Ord,Read,Show,Bounded,Generic,Generic1,Num,Enum,Typeable\n               ,Storable,Fractional,Real,RealFrac,Functor,Foldable,Traversable\n               ,NFData)\n\n-- | The \"<https://ncatlab.org/nlab/show/max-plus+algebra Arctic>\"\n-- or max-plus semiring. It is a semiring where:\n--\n-- @'<+>'  = 'max'\n--'zero' = -\u221e\n--'<.>'  = '<+>'\n--'one'  = 'zero'@\n--\n-- Note that we can't use 'Data.Semigroup.Max' from 'Data.Semigroup'\n-- because annihilation needs to hold:\n--\n-- @-\u221e '<+>' x = x '<+>' -\u221e = -\u221e@\n--\n-- Taking -\u221e to be 'minBound' would break the above law. Using\n-- 'negativeInfinity' to represent it follows the law.\nnewtype Max a = Max\n    { getMax :: a\n    } deriving (Eq,Ord,Read,Show,Bounded,Generic,Generic1,Num,Enum,Typeable\n               ,Storable,Fractional,Real,RealFrac,Functor,Foldable,Traversable\n               ,NFData)\n\ninstance Eq1 Max where\n    liftEq = coerce\n    {-# INLINE liftEq #-}\n\ninstance Ord1 Max where\n    liftCompare = coerce\n    {-# INLINE liftCompare #-}\n\ninstance Show1 Max where\n    liftShowsPrec = showsNewtype \"Max\" \"getMax\"\n    {-# INLINE liftShowsPrec #-}\n\ninstance Read1 Max where\n    liftReadsPrec = readsNewtype \"Max\" \"getMax\"\n    {-# INLINE liftReadsPrec #-}\n\ninstance Eq1 Min where\n    liftEq = coerce\n    {-# INLINE liftEq #-}\n\ninstance Ord1 Min where\n    liftCompare = coerce\n    {-# INLINE liftCompare #-}\n\ninstance Show1 Min where\n    liftShowsPrec = showsNewtype \"Min\" \"getMin\"\n    {-# INLINE liftShowsPrec #-}\n\ninstance Read1 Min where\n    liftReadsPrec = readsNewtype \"Min\" \"getMin\"\n    {-# INLINE liftReadsPrec #-}\n\ninstance Ord a =>\n         Semigroup (Max a) where\n    (<>) = (coerce :: WrapBinary Max a) max\n    {-# INLINE (<>) #-}\n    stimes = stimesIdempotent\n    {-# SPECIALISE (<>) :: BinaryWrapped Max Double #-}\n\ninstance Ord a =>\n         Semigroup (Min a) where\n    (<>) = (coerce :: WrapBinary Min a) min\n    {-# INLINE (<>) #-}\n    stimes = stimesIdempotent\n    {-# SPECIALISE (<>) :: BinaryWrapped Min Double #-}\n\n-- | >>> (getMax . foldMap Max) [1..10]\n-- 10.0\ninstance (Ord a, HasNegativeInfinity a) =>\n         Monoid (Max a) where\n    mempty = Max negativeInfinity\n    mappend = (coerce :: WrapBinary Max a) max\n    {-# INLINE mempty #-}\n    {-# INLINE mappend #-}\n    {-# SPECIALISE mappend :: BinaryWrapped Max Double #-}\n\n-- | >>> (getMin . foldMap Min) [1..10]\n-- 1.0\ninstance (Ord a, HasPositiveInfinity a) =>\n         Monoid (Min a) where\n    mempty = Min positiveInfinity\n    mappend = (coerce :: WrapBinary Min a) min\n    {-# INLINE mempty #-}\n    {-# INLINE mappend #-}\n    {-# SPECIALISE mappend :: BinaryWrapped Min Double #-}\n\ninstance (Semiring a, Ord a, HasNegativeInfinity a) =>\n         Semiring (Max a) where\n    (<+>) = (coerce :: WrapBinary Max a) max\n    zero = Max negativeInfinity\n    (<.>) = (coerce :: WrapBinary Max a) (<+>)\n    one = Max zero\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\n    {-# SPECIALISE (<+>) :: BinaryWrapped Max Double #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped Max Double #-}\n\ninstance (Semiring a, Ord a, HasPositiveInfinity a) =>\n         Semiring (Min a) where\n    (<+>) = (coerce :: WrapBinary Min a) min\n    zero = Min positiveInfinity\n    (<.>) = (coerce :: WrapBinary Min a) (<+>)\n    one = Min zero\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n    {-# SPECIALISE (<+>) :: BinaryWrapped Min Double #-}\n    {-# SPECIALISE (<.>) :: BinaryWrapped Min Double #-}\n\ninstance (Semiring a, Ord a, HasPositiveInfinity a, HasNegativeInfinity a) =>\n         StarSemiring (Max a) where\n    star (Max x)\n      | x > zero = Max positiveInfinity\n      | otherwise = Max zero\n    {-# SPECIALISE star :: Max Double  -> Max Double  #-}\n\ninstance (Semiring a, Ord a, HasPositiveInfinity a, HasNegativeInfinity a) =>\n         StarSemiring (Min a) where\n    star (Min x)\n      | x < zero = Min negativeInfinity\n      | otherwise = Min zero\n    {-# SPECIALISE star :: Min Double  -> Min Double  #-}\n\ninstance (Semiring a, Ord a, HasPositiveInfinity a) =>\n         DetectableZero (Min a) where\n    isZero (Min x) = isPositiveInfinity x\n    {-# INLINE isZero #-}\n\ninstance (Semiring a, Ord a, HasNegativeInfinity a) =>\n         DetectableZero (Max a) where\n    isZero (Max x) = isNegativeInfinity x\n    {-# INLINE isZero #-}\n\nnewtype instance U.Vector (Min a) = V_Min (U.Vector a)\nnewtype instance U.MVector s (Min a) = MV_Min (U.MVector s a)\n\ninstance U.Unbox a =>\n         M.MVector U.MVector (Min a) where\n    {-# INLINE basicLength #-}\n    {-# INLINE basicUnsafeSlice #-}\n    {-# INLINE basicOverlaps #-}\n    {-# INLINE basicUnsafeNew #-}\n    {-# INLINE basicUnsafeRead #-}\n    {-# INLINE basicUnsafeWrite #-}\n    basicLength =\n        (coerce :: (U.MVector s a -> Int) -> U.MVector s (Min a) -> Int)\n            M.basicLength\n    basicUnsafeSlice =\n        (coerce :: (Int -> Int -> U.MVector s a -> U.MVector s a) -> Int -> Int -> U.MVector s (Min a) -> U.MVector s (Min a))\n            M.basicUnsafeSlice\n    basicOverlaps =\n        (coerce :: (U.MVector s a -> U.MVector s a -> Bool) -> U.MVector s (Min a) -> U.MVector s (Min a) -> Bool)\n            M.basicOverlaps\n    basicUnsafeNew n =\n        fmap\n            (coerce :: U.MVector s a -> U.MVector s (Min a))\n            (M.basicUnsafeNew n)\n    basicUnsafeRead (MV_Min xs) i =\n        fmap (coerce :: a -> Min a) (M.basicUnsafeRead xs i)\n    basicUnsafeWrite =\n        (coerce :: (U.MVector s a -> Int -> a -> m ()) -> U.MVector s (Min a) -> Int -> Min a -> m ())\n            M.basicUnsafeWrite\n    basicInitialize =\n        (coerce :: (U.MVector s a -> m ()) -> U.MVector s (Min a) -> m ())\n            M.basicInitialize\n\ninstance U.Unbox a =>\n         G.Vector U.Vector (Min a) where\n    {-# INLINE basicUnsafeFreeze #-}\n    {-# INLINE basicUnsafeThaw #-}\n    {-# INLINE basicLength #-}\n    {-# INLINE basicUnsafeSlice #-}\n    {-# INLINE basicUnsafeIndexM #-}\n    basicUnsafeFreeze (MV_Min xs) =\n        fmap\n            (coerce :: U.Vector a -> U.Vector (Min a))\n            (G.basicUnsafeFreeze xs)\n    basicUnsafeThaw (V_Min xs) =\n        fmap\n            (coerce :: U.MVector s a -> U.MVector s (Min a))\n            (G.basicUnsafeThaw xs)\n    basicLength =\n        (coerce :: (U.Vector a -> Int) -> U.Vector (Min a) -> Int)\n            G.basicLength\n    basicUnsafeSlice =\n        (coerce :: (Int -> Int -> U.Vector a -> U.Vector a) -> Int -> Int -> U.Vector (Min a) -> U.Vector (Min a))\n            G.basicUnsafeSlice\n    basicUnsafeIndexM (V_Min xs) i =\n        fmap (coerce :: a -> Min a) (G.basicUnsafeIndexM xs i)\n\nnewtype instance U.Vector (Max a) = V_Max (U.Vector a)\nnewtype instance U.MVector s (Max a) = MV_Max (U.MVector s a)\n\ninstance U.Unbox a =>\n         M.MVector U.MVector (Max a) where\n    {-# INLINE basicLength #-}\n    {-# INLINE basicUnsafeSlice #-}\n    {-# INLINE basicOverlaps #-}\n    {-# INLINE basicUnsafeNew #-}\n    {-# INLINE basicUnsafeRead #-}\n    {-# INLINE basicUnsafeWrite #-}\n    basicLength =\n        (coerce :: (U.MVector s a -> Int) -> U.MVector s (Max a) -> Int)\n            M.basicLength\n    basicUnsafeSlice =\n        (coerce :: (Int -> Int -> U.MVector s a -> U.MVector s a) -> Int -> Int -> U.MVector s (Max a) -> U.MVector s (Max a))\n            M.basicUnsafeSlice\n    basicOverlaps =\n        (coerce :: (U.MVector s a -> U.MVector s a -> Bool) -> U.MVector s (Max a) -> U.MVector s (Max a) -> Bool)\n            M.basicOverlaps\n    basicUnsafeNew n =\n        fmap\n            (coerce :: U.MVector s a -> U.MVector s (Max a))\n            (M.basicUnsafeNew n)\n    basicUnsafeRead (MV_Max xs) i =\n        fmap (coerce :: a -> Max a) (M.basicUnsafeRead xs i)\n    basicUnsafeWrite =\n        (coerce :: (U.MVector s a -> Int -> a -> m ()) -> U.MVector s (Max a) -> Int -> Max a -> m ())\n            M.basicUnsafeWrite\n    basicInitialize =\n        (coerce :: (U.MVector s a -> m ()) -> U.MVector s (Max a) -> m ())\n            M.basicInitialize\n\ninstance U.Unbox a =>\n         G.Vector U.Vector (Max a) where\n    {-# INLINE basicUnsafeFreeze #-}\n    {-# INLINE basicUnsafeThaw #-}\n    {-# INLINE basicLength #-}\n    {-# INLINE basicUnsafeSlice #-}\n    {-# INLINE basicUnsafeIndexM #-}\n    basicUnsafeFreeze (MV_Max xs) =\n        fmap\n            (coerce :: U.Vector a -> U.Vector (Max a))\n            (G.basicUnsafeFreeze xs)\n    basicUnsafeThaw (V_Max xs) =\n        fmap\n            (coerce :: U.MVector s a -> U.MVector s (Max a))\n            (G.basicUnsafeThaw xs)\n    basicLength =\n        (coerce :: (U.Vector a -> Int) -> U.Vector (Max a) -> Int)\n            G.basicLength\n    basicUnsafeSlice =\n        (coerce :: (Int -> Int -> U.Vector a -> U.Vector a) -> Int -> Int -> U.Vector (Max a) -> U.Vector (Max a))\n            G.basicUnsafeSlice\n    basicUnsafeIndexM (V_Max xs) i =\n        fmap (coerce :: a -> Max a) (G.basicUnsafeIndexM xs i)\n--------------------------------------------------------------------------------\n-- (->) instance\n--------------------------------------------------------------------------------\n-- | The @(->)@ instance is analogous to the one for 'Monoid'.\ninstance Semiring b =>\n         Semiring (a -> b) where\n    zero = const zero\n    {-# INLINE zero #-}\n    one = const one\n    {-# INLINE one #-}\n    (f <+> g) x = f x <+> g x\n    {-# INLINE (<+>) #-}\n    (f <.> g) x = f x <.> g x\n    {-# INLINE (<.>) #-}\n\ninstance StarSemiring b =>\n         StarSemiring (a -> b) where\n    star = (.) star\n    {-# INLINE star #-}\n    plus = (.) plus\n    {-# INLINE plus #-}\n\n--------------------------------------------------------------------------------\n-- Endo instance\n--------------------------------------------------------------------------------\n-- | This is /not/ a true semiring. In particular, it requires the\n-- underlying monoid to be commutative, and even then, it is only a near\n-- semiring. It is, however, extremely useful. For instance, this type:\n--\n-- @forall a. 'Endo' ('Endo' a)@\n--\n-- Is a valid encoding of church numerals, with addition and\n-- multiplication being their semiring variants.\ninstance Monoid a =>\n         Semiring (Endo a) where\n    zero = Endo mempty\n    Endo f <+> Endo g = Endo (f `mappend` g)\n    one = mempty\n    (<.>) = mappend\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance (Monoid a, Eq a) =>\n         StarSemiring (Endo a) where\n    star (Endo f) = Endo converge\n      where\n        converge x = go x\n          where\n            go inp =\n                mappend\n                    x\n                    (if inp == next\n                         then inp\n                         else go next)\n              where\n                next = mappend x (f inp)\n\ninstance (Enum a, Bounded a, Eq a, Monoid a) =>\n         DetectableZero (Endo a) where\n    isZero (Endo f) = all (mempty ==) (map f [minBound .. maxBound])\n\n--------------------------------------------------------------------------------\n-- Instances for Bool wrappers\n--------------------------------------------------------------------------------\ninstance Semiring Any where\n    (<+>) = coerce (||)\n    zero = Any False\n    (<.>) = coerce (&&)\n    one = Any True\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance StarSemiring Any where\n    star _ = Any True\n    plus = id\n    {-# INLINE star #-}\n    {-# INLINE plus #-}\n\ninstance Semiring All where\n    (<+>) = coerce (||)\n    zero = All False\n    (<.>) = coerce (&&)\n    one = All True\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance StarSemiring All where\n    star _ = All True\n    plus = id\n    {-# INLINE star #-}\n    {-# INLINE plus #-}\n\ninstance DetectableZero Any where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero All where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\n--------------------------------------------------------------------------------\n-- Boring instances\n--------------------------------------------------------------------------------\n\ninstance Semiring Int where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Int8 where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Int16 where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Int32 where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Int64 where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Integer where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Word where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Word8 where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Word16 where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Word32 where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Word64 where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Float where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Double where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Scientific where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring DiffTime where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring NominalDiffTime where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CUIntMax where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CIntMax where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CUIntPtr where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CIntPtr where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CSUSeconds where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CUSeconds where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CTime where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CClock where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CSigAtomic where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CWchar where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CSize where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CPtrdiff where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CDouble where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CFloat where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CULLong where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CLLong where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CULong where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CLong where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CUInt where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CInt where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CUShort where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CShort where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CUChar where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CSChar where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CChar where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring IntPtr where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring WordPtr where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Fd where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CRLim where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CTcflag where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CSpeed where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CCc where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CUid where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CNlink where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CGid where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CSsize where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CPid where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring COff where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CMode where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CIno where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring CDev where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring Natural where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Integral a =>\n         Semiring (Ratio a) where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring a => Semiring (Product a) where\n    one = Product one\n    {-# INLINE one #-}\n    zero = Product zero\n    {-# INLINE zero #-}\n    (<+>) = (coerce :: WrapBinary Product a) (<+>)\n    {-# INLINE (<+>) #-}\n    (<.>) = (coerce :: WrapBinary Product a) (<.>)\n    {-# INLINE (<.>) #-}\n\ninstance Semiring a => Semiring (Sum a) where\n    one = Sum one\n    {-# INLINE one #-}\n    zero = Sum zero\n    {-# INLINE zero #-}\n    (<+>) = (coerce :: WrapBinary Sum a) (<+>)\n    {-# INLINE (<+>) #-}\n    (<.>) = (coerce :: WrapBinary Sum a) (<.>)\n    {-# INLINE (<.>) #-}\n\ninstance RealFloat a =>\n         Semiring (Complex a) where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance HasResolution a =>\n         Semiring (Fixed a) where\n    one = 1\n    zero = 0\n    (<+>) = (+)\n    (<.>) = (*)\n    {-# INLINE zero #-}\n    {-# INLINE one #-}\n    {-# INLINE (<+>) #-}\n    {-# INLINE (<.>) #-}\n\ninstance Semiring a => Semiring (Identity a) where\n    one = Identity one\n    {-# INLINE one #-}\n    zero = Identity zero\n    {-# INLINE zero #-}\n    (<+>) = (coerce :: WrapBinary Identity a) (<+>)\n    {-# INLINE (<+>) #-}\n    (<.>) = (coerce :: WrapBinary Identity a) (<.>)\n    {-# INLINE (<.>) #-}\n\ninstance DetectableZero Int where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Int8 where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Int16 where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Int32 where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Int64 where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Integer where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Word where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Word8 where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Word16 where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Word32 where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Word64 where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Float where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Double where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Scientific where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero DiffTime where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero NominalDiffTime where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CUIntMax where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CIntMax where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CUIntPtr where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CIntPtr where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CSUSeconds where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CUSeconds where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CTime where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CClock where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CSigAtomic where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CWchar where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CSize where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CPtrdiff where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CDouble where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CFloat where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CULLong where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CLLong where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CULong where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CLong where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CUInt where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CInt where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CUShort where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CShort where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CUChar where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CSChar where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CChar where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero IntPtr where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero WordPtr where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Fd where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CRLim where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CTcflag where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CSpeed where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CCc where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CUid where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CNlink where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CGid where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CSsize where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CPid where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero COff where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CMode where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CIno where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero CDev where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance DetectableZero Natural where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance Integral a =>\n         DetectableZero (Ratio a) where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\nderiving instance DetectableZero a => DetectableZero (Product a)\n\nderiving instance DetectableZero a => DetectableZero (Sum a)\n\ninstance RealFloat a =>\n         DetectableZero (Complex a) where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\ninstance HasResolution a =>\n         DetectableZero (Fixed a) where\n    isZero = isZeroEq\n    {-# INLINE isZero #-}\n\nderiving instance DetectableZero a => DetectableZero (Identity a)\n\n--------------------------------------------------------------------------------\n-- Very boring instances\n--------------------------------------------------------------------------------\n$(traverse semiringIns [2 .. 15])\n\n$(traverse starIns [2 .. 15])\n\n$(traverse zeroIns [2 .. 15])\n", "meta": {"hexsha": "810e354cd8cc0da67321a96b792ee7db9516a2c5", "size": 60990, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Semiring.hs", "max_stars_repo_name": "oisdk/semiring", "max_stars_repo_head_hexsha": "c02cdd2192c8887f4266b8a3295d908ae8b61dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-02-12T21:22:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T02:09:34.000Z", "max_issues_repo_path": "src/Data/Semiring.hs", "max_issues_repo_name": "conal/semiring-num", "max_issues_repo_head_hexsha": "33afe2e76a3854c52bc80179ca61c8f28ceb4d06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-11-02T20:37:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-23T21:00:02.000Z", "max_forks_repo_path": "src/Data/Semiring.hs", "max_forks_repo_name": "conal/semiring-num", "max_forks_repo_head_hexsha": "33afe2e76a3854c52bc80179ca61c8f28ceb4d06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-04-19T19:40:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-24T04:13:36.000Z", "avg_line_length": 27.8493150685, "max_line_length": 126, "alphanum_fraction": 0.5209870471, "num_tokens": 17205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.43396322861211595}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n{-# LANGUAGE TypeFamilies        #-}\n\n\n--\n-- Note: Input files can be downloaded at https://www.kaggle.com/scolianni/mnistasjpg\n--\n--\n-- This is a simple generative adversarial network to make pictures\n-- of numbers similar to those in MNIST.\n--\n-- It demonstrates a different usage of the library. Within about 15\n-- minutes it was producing examples like this:\n--\n--               --.\n--     .=-.--..#=###\n--     -##==#########.\n--     #############-\n--   -###-.=..-.-==\n--   ###-\n--   .###-\n--   .####...==-.\n--   -####=--.=##=\n--   -##=-     -##\n--             =##\n--           -##=\n--           -###-\n--         .####.\n--         .#####.\n-- ...---=#####-\n-- .=#########.         .\n--   .#######=.          .\n--     . =-.\n--\n-- It's a 5!\n--\nimport           Control.Applicative\nimport           Control.DeepSeq\nimport           Control.Monad\nimport           Control.Monad.Random\nimport           Control.Monad.Trans.Except\n\nimport qualified Data.Attoparsec.Text         as A\nimport qualified Data.ByteString              as B\nimport           Data.List                    (foldl')\nimport           Data.Serialize\nimport qualified Data.Text                    as T\nimport qualified Data.Text.IO                 as T\nimport qualified Data.Vector.Storable         as V\n\nimport           Numeric.LinearAlgebra.Data   (toLists)\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport           Options.Applicative\n\nimport           Grenade\nimport           Grenade.Utils.OneHot\n\ntype Discriminator =\n  Network\n    '[ Convolution 'WithoutBias 'NoPadding 1 10 5 5 1 1, Pooling 2 2 2 2, Relu\n     , Convolution 'WithoutBias 'NoPadding 10 16 5 5 1 1, Pooling 2 2 2 2, Relu\n     , Reshape, FullyConnected 256 80, Logit, FullyConnected 80 1, Logit]\n    '[ 'D2 28 28\n     , 'D3 24 24 10, 'D3 12 12 10, 'D3 12 12 10\n     , 'D3 8 8 16, 'D3 4 4 16, 'D3 4 4 16\n     , 'D1 256, 'D1 80, 'D1 80, 'D1 1, 'D1 1]\n\ntype Generator =\n  Network\n    '[ FullyConnected 80 256, Relu, Reshape\n     , Deconvolution 16 10 5 5 2 2, Relu\n     , Deconvolution 10 1 8 8 2 2, Logit]\n    '[ 'D1 80\n     , 'D1 256, 'D1 256, 'D3 4 4 16\n     , 'D3 11 11 10, 'D3 11 11 10\n     , 'D2 28 28, 'D2 28 28 ]\n\nrandomDiscriminator :: IO Discriminator\nrandomDiscriminator = randomNetwork\n\nrandomGenerator :: IO Generator\nrandomGenerator = randomNetwork\n\ntrainExample :: Optimizer opt -> Discriminator -> Generator -> S ('D2 28 28) -> S ('D1 80) -> ( Discriminator, Generator )\ntrainExample opt discriminator generator realExample noiseSource\n = let (generatorTape, fakeExample)       = runNetwork generator noiseSource\n\n       (discriminatorTapeReal, guessReal) = runNetwork discriminator realExample\n       (discriminatorTapeFake, guessFake) = runNetwork discriminator fakeExample\n\n       (discriminator'real, _)            = runGradient discriminator discriminatorTapeReal ( guessReal - 1 )\n       (discriminator'fake, _)            = runGradient discriminator discriminatorTapeFake guessFake\n       (_, push)                          = runGradient discriminator discriminatorTapeFake ( guessFake - 1)\n\n       (generator', _)                    = runGradient generator generatorTape push\n\n       !newDiscriminator                   = force $ foldl' (applyUpdate $ sgdUpdateLearningParamters opt) discriminator [ discriminator'real, discriminator'fake ]\n       !newGenerator                       = force $ applyUpdate opt generator generator'\n   in ( newDiscriminator, newGenerator )\n  where sgdUpdateLearningParamters :: Optimizer opt -> Optimizer opt\n        sgdUpdateLearningParamters (OptSGD rate mom reg) = OptSGD rate mom (reg * 10)\n        sgdUpdateLearningParamters o                     = o\n\n\nganTest :: (Discriminator, Generator) -> Int -> FilePath -> Optimizer opt -> ExceptT String IO (Discriminator, Generator)\nganTest (discriminator0, generator0) iterations trainFile opt = do\n  !trainData      <- fmap fst <$> readMNIST trainFile\n\n  lift $ foldM (runIteration trainData) ( discriminator0, generator0 ) [1..iterations]\n\n    where\n\n  showShape' :: S ('D2 a b) -> IO ()\n  showShape' (S2D mm) = putStrLn $\n    let m  = SA.extract mm\n        ms = toLists m\n        render n'  | n' <= 0.2  = ' '\n                   | n' <= 0.4  = '.'\n                   | n' <= 0.6  = '-'\n                   | n' <= 0.8  = '='\n                   | otherwise =  '#'\n\n        px = (fmap . fmap) render ms\n    in unlines px\n\n  runIteration :: [S ('D2 28 28)] -> (Discriminator, Generator) -> Int -> IO (Discriminator, Generator)\n  runIteration trainData ( !discriminator, !generator ) _ = do\n    trained'    <- foldM ( \\(!discriminatorX, !generatorX ) realExample -> do\n                      trainExample opt discriminatorX generatorX realExample <$> randomOfShape\n                     ) ( discriminator, generator ) trainData\n\n\n    showShape' . snd . runNetwork (snd trained') =<< randomOfShape\n\n    return trained'\n\ndata GanOpts = GanOpts FilePath Int Bool (Optimizer 'SGD) (Optimizer 'Adam) (Maybe FilePath) (Maybe FilePath)\n\nmnist' :: Parser GanOpts\nmnist' = GanOpts <$> argument str (metavar \"TRAIN\")\n                 <*> option auto (long \"iterations\" <> short 'i' <> value 15)\n                 <*> flag False True (long \"use-adam\" <> short 'a')\n                 <*> (OptSGD\n                       <$> option auto (long \"train_rate\" <> short 'r' <> value 0.01)\n                       <*> option auto (long \"momentum\" <> value 0.9)\n                       <*> option auto (long \"l2\" <> value 0.0005)\n                       )\n                 <*> (OptAdam\n                       <$> option auto (long \"alpha\" <> short 'r' <> value 0.001)\n                       <*> option auto (long \"beta1\" <> value 0.9)\n                       <*> option auto (long \"beta2\" <> value 0.999)\n                       <*> option auto (long \"epsilon\" <> value 1e-4)\n                       <*> option auto (long \"lambda\" <> value 1e-3)\n                      )\n                 <*> optional (strOption (long \"load\"))\n                 <*> optional (strOption (long \"save\"))\n\n\nmain :: IO ()\nmain = do\n  GanOpts mnist iter useAdam sgd adam load save <- execParser (info (mnist' <**> helper) idm)\n  putStrLn \"Training stupidly simply GAN\"\n  nets0 <-\n    case load of\n      Just loadFile -> netLoad loadFile\n      Nothing       -> (,) <$> randomDiscriminator <*> randomGenerator\n  res <-\n    if useAdam\n      then runExceptT $ ganTest nets0 iter mnist adam\n      else runExceptT $ ganTest nets0 iter mnist sgd\n  case res of\n    Right nets1 ->\n      case save of\n        Just saveFile -> B.writeFile saveFile $ runPut (put nets1)\n        Nothing       -> return ()\n    Left err -> putStrLn err\n\nreadMNIST :: FilePath -> ExceptT String IO [(S ('D2 28 28), S ('D1 10))]\nreadMNIST mnist = ExceptT $ do\n  mnistdata <- T.readFile mnist\n  return $ traverse (A.parseOnly parseMNIST) (tail $ T.lines mnistdata)\n\nparseMNIST :: A.Parser (S ('D2 28 28), S ('D1 10))\nparseMNIST = do\n  Just lab <- oneHot <$> A.decimal\n  pixels   <- many (A.char ',' >> A.double)\n  image    <- maybe (fail \"Parsed row was of an incorrect size\") pure (fromStorable . V.fromList $ fmap realToFrac pixels)\n  return (image, lab)\n\nnetLoad :: FilePath -> IO (Discriminator, Generator)\nnetLoad modelPath = do\n  modelData <- B.readFile modelPath\n  either fail return $ runGet (get :: Get (Discriminator, Generator)) modelData\n", "meta": {"hexsha": "cc0a55276301153feadbb60cc9f6dfe4ee62bfcb", "size": 7533, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/gan-mnist.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "examples/main/gan-mnist.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main/gan-mnist.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4776119403, "max_line_length": 163, "alphanum_fraction": 0.5722819594, "num_tokens": 2021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.433553913867304}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module     : Data.AEq\n-- Copyright  : Copyright (c) 2010, Patrick Perry <patperry@gmail.com>\n-- License    : BSD3\n-- Maintainer : Patrick Perry <patperry@gmail.com>\n-- Stability  : experimental\n--\n-- A type class for approximate and exact equalilty comparisons and instances\n-- for common data types.\nmodule Data.AEq (\n    AEq(..),\n    ) where\n\nimport Foreign\nimport Foreign.C.Types\nimport Data.Complex\nimport Numeric.IEEE\n\ninfix 4 ===, ~==\n\n-- | Types with approximate and exact equality comparisons.\nclass Eq a => AEq a where\n    -- | An exact equality comparison.\n    --\n    -- For real 'IEEE' types, two values are equivalent in the\n    -- following cases:\n    --\n    --   * both values are @+0@;\n    --\n    --   * both values are @-0@;\n    --\n    --   * both values are nonzero and equal to each other\n    --     (according to '==');\n    --\n    --   * both values are @NaN@ with the same payload and sign.\n    --\n    -- For complex 'IEEE' types, two values are equivalent if their\n    -- real and imaginary parts are equivalent.\n    --\n    (===) :: a -> a -> Bool\n    (===) = (==)\n    {-# INLINE (===) #-}\n\n    -- | An approximate equality comparison operator.\n    --\n    -- For real 'IEEE' types, two values are approximately equal in the\n    -- following cases:\n    --\n    --   * at least half of their significand bits agree;\n    --\n    --   * both values are less than 'epsilon';\n    --\n    --   * both values are @NaN@.\n    --\n    -- For complex 'IEEE' types, two values are approximately equal in the\n    -- followiing cases:\n    --\n    --   * their magnitudes are approximately equal and the angle between\n    --     them is less than @32*'epsilon'@;\n    --\n    --   * both magnitudes are less than 'epsilon';\n    --\n    --   * both have a @NaN@ real or imaginary part.\n    --\n    -- Admitedly, the @32@ is a bit of a hack.  Future versions of the\n    -- library may switch to a more principled test of the angle.\n    --\n    (~==) :: a -> a -> Bool\n    (~==) = (==)\n    {-# INLINE (~==) #-}\n\napproxEqIEEE :: (IEEE a) => a -> a -> Bool\napproxEqIEEE x y =\n    ( sameSignificandBits x y >= d\n    || (abs x < epsilon && abs y < epsilon)\n    || (isNaN x && isNaN y)\n    )\n  where\n    d = (floatDigits x + 1) `div` 2\n{-# INLINE approxEqIEEE #-}\n\nidenticalComplexIEEE :: (IEEE a) => Complex a -> Complex a -> Bool\nidenticalComplexIEEE (x1 :+ y1) (x2 :+ y2) =\n    (identicalIEEE x1 x2) && (identicalIEEE y1 y2)\n{-# INLINE identicalComplexIEEE #-}\n\napproxEqComplexIEEE :: (IEEE a) => Complex a -> Complex a -> Bool\napproxEqComplexIEEE z1 z2 = let\n    (r1,c1) = polar z1\n    (r2,c2) = polar z2\n    angle = abs (c1 - c2)\n    in ( ( approxEqIEEE r1 r2\n         && (angle < 32*epsilon || angle > 2*(pi - 16*epsilon) || isNaN angle)\n         )\n       || (r1 < epsilon && r2 < epsilon)\n       )\n{-# INLINE approxEqComplexIEEE #-}\n\ninstance AEq Float where\n    (===) = identicalIEEE\n    {-# INLINE (===) #-}\n    (~==) = approxEqIEEE\n    {-# INLINE (~==) #-}\n\ninstance AEq Double where\n    (===) = identicalIEEE\n    {-# INLINE (===) #-}\n    (~==) = approxEqIEEE\n    {-# INLINE (~==) #-}\n\ninstance AEq (Complex Float) where\n    (===) = identicalComplexIEEE\n    {-# INLINE (===) #-}\n    (~==) = approxEqComplexIEEE\n    {-# INLINE (~==) #-}\n\ninstance AEq (Complex Double) where\n    (===) = identicalComplexIEEE\n    {-# INLINE (===) #-}\n    (~==) = approxEqComplexIEEE\n    {-# INLINE (~==) #-}\n\ninstance AEq CFloat where\n    (===) = identicalIEEE\n    {-# INLINE (===) #-}\n    (~==) = approxEqIEEE\n    {-# INLINE (~==) #-}\n\ninstance AEq CDouble where\n    (===) = identicalIEEE\n    {-# INLINE (===) #-}\n    (~==) = approxEqIEEE\n    {-# INLINE (~==) #-}\n\ninstance AEq (Complex CFloat) where\n    (===) = identicalComplexIEEE\n    {-# INLINE (===) #-}\n    (~==) = approxEqComplexIEEE\n    {-# INLINE (~==) #-}\n\ninstance AEq (Complex CDouble) where\n    (===) = identicalComplexIEEE\n    {-# INLINE (===) #-}\n    (~==) = approxEqComplexIEEE\n    {-# INLINE (~==) #-}\n\ninstance AEq Bool\ninstance AEq Char\ninstance AEq Int\ninstance AEq Int8\ninstance AEq Int16\ninstance AEq Int32\ninstance AEq Int64\ninstance AEq Integer\ninstance AEq Ordering\ninstance AEq Word\ninstance AEq Word8\ninstance AEq Word16\ninstance AEq Word32\ninstance AEq Word64\ninstance AEq ()\ninstance AEq WordPtr\ninstance AEq IntPtr\ninstance AEq (StablePtr a)\ninstance AEq (Ptr a)\ninstance AEq (FunPtr a)\ninstance AEq (ForeignPtr a)\ninstance AEq CChar\ninstance AEq CSChar\ninstance AEq CUChar\ninstance AEq CShort\ninstance AEq CUShort\ninstance AEq CInt\ninstance AEq CUInt\ninstance AEq CLong\ninstance AEq CULong\ninstance AEq CPtrdiff\ninstance AEq CSize\ninstance AEq CWchar\ninstance AEq CSigAtomic\ninstance AEq CLLong\ninstance AEq CULLong\ninstance AEq CIntPtr\ninstance AEq CUIntPtr\ninstance AEq CIntMax\ninstance AEq CUIntMax\ninstance AEq CClock\ninstance AEq CTime\n\neqListsWith :: (a -> a -> Bool) -> [a] -> [a] -> Bool\neqListsWith f (x:xs) (y:ys) = f x y && eqListsWith f xs ys\neqListsWith _ [] [] = True\neqListsWith _ _  _  = False\n{-# INLINE eqListsWith #-}\n\ninstance (AEq a) => AEq [a] where\n    (===) = eqListsWith (===)\n    {-# INLINE (===) #-}\n    (~==) = eqListsWith (~==)\n    {-# INLINE (~==) #-}\n\ninstance (AEq a) => AEq (Maybe a) where\n    (===) Nothing  Nothing  = True\n    (===) (Just x) (Just y) = (===) x y\n    (===) _ _ = False\n    {-# INLINE (===) #-}\n\n    (~==) Nothing  Nothing  = True\n    (~==) (Just x) (Just y) = (~==) x y\n    (~==) _ _ = False\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b) => AEq (Either a b) where\n    (===) (Left a1)  (Left a2)  = (===) a1 a2\n    (===) (Right b1) (Right b2) = (===) b1 b2\n    (===) _ _ = False\n    {-# INLINE (===) #-}\n\n    (~==) (Left a1)  (Left a2)  = (~==) a1 a2\n    (~==) (Right b1) (Right b2) = (~==) b1 b2\n    (~==) _ _ = False\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b) => AEq (a,b) where\n    (===) (a1,b1) (a2,b2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1) (a2,b2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c) => AEq (a,b,c) where\n    (===) (a1,b1,c1) (a2,b2,c2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1) (a2,b2,c2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d) => AEq (a,b,c,d) where\n    (===) (a1,b1,c1,d1) (a2,b2,c2,d2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1) (a2,b2,c2,d2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e) => AEq (a,b,c,d,e) where\n    (===) (a1,b1,c1,d1,e1) (a2,b2,c2,d2,e2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1) (a2,b2,c2,d2,e2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f) => AEq (a,b,c,d,e,f) where\n    (===) (a1,b1,c1,d1,e1,f1) (a2,b2,c2,d2,e2,f2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1) (a2,b2,c2,d2,e2,f2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g) => AEq (a,b,c,d,e,f,g) where\n    (===) (a1,b1,c1,d1,e1,f1,g1) (a2,b2,c2,d2,e2,f2,g2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1) (a2,b2,c2,d2,e2,f2,g2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g, AEq h) => AEq (a,b,c,d,e,f,g,h) where\n    (===) (a1,b1,c1,d1,e1,f1,g1,h1) (a2,b2,c2,d2,e2,f2,g2,h2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        && ((===) h1 h2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1,h1) (a2,b2,c2,d2,e2,f2,g2,h2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        && ((~==) h1 h2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g, AEq h, AEq i) => AEq (a,b,c,d,e,f,g,h,i) where\n    (===) (a1,b1,c1,d1,e1,f1,g1,h1,i1) (a2,b2,c2,d2,e2,f2,g2,h2,i2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        && ((===) h1 h2)\n        && ((===) i1 i2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1,h1,i1) (a2,b2,c2,d2,e2,f2,g2,h2,i2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        && ((~==) h1 h2)\n        && ((~==) i1 i2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g, AEq h, AEq i, AEq j) => AEq (a,b,c,d,e,f,g,h,i,j) where\n    (===) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        && ((===) h1 h2)\n        && ((===) i1 i2)\n        && ((===) j1 j2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        && ((~==) h1 h2)\n        && ((~==) i1 i2)\n        && ((~==) j1 j2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g, AEq h, AEq i, AEq j, AEq k) => AEq (a,b,c,d,e,f,g,h,i,j,k) where\n    (===) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        && ((===) h1 h2)\n        && ((===) i1 i2)\n        && ((===) j1 j2)\n        && ((===) k1 k2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        && ((~==) h1 h2)\n        && ((~==) i1 i2)\n        && ((~==) j1 j2)\n        && ((~==) k1 k2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g, AEq h, AEq i, AEq j, AEq k, AEq l) => AEq (a,b,c,d,e,f,g,h,i,j,k,l) where\n    (===) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2,l2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        && ((===) h1 h2)\n        && ((===) i1 i2)\n        && ((===) j1 j2)\n        && ((===) k1 k2)\n        && ((===) l1 l2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2,l2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        && ((~==) h1 h2)\n        && ((~==) i1 i2)\n        && ((~==) j1 j2)\n        && ((~==) k1 k2)\n        && ((~==) l1 l2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g, AEq h, AEq i, AEq j, AEq k, AEq l, AEq m) => AEq (a,b,c,d,e,f,g,h,i,j,k,l,m) where\n    (===) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2,l2,m2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        && ((===) h1 h2)\n        && ((===) i1 i2)\n        && ((===) j1 j2)\n        && ((===) k1 k2)\n        && ((===) l1 l2)\n        && ((===) m1 m2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2,l2,m2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        && ((~==) h1 h2)\n        && ((~==) i1 i2)\n        && ((~==) j1 j2)\n        && ((~==) k1 k2)\n        && ((~==) l1 l2)\n        && ((~==) m1 m2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g, AEq h, AEq i, AEq j, AEq k, AEq l, AEq m, AEq n) => AEq (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where\n    (===) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2,l2,m2,n2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        && ((===) h1 h2)\n        && ((===) i1 i2)\n        && ((===) j1 j2)\n        && ((===) k1 k2)\n        && ((===) l1 l2)\n        && ((===) m1 m2)\n        && ((===) n1 n2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2,l2,m2,n2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        && ((~==) h1 h2)\n        && ((~==) i1 i2)\n        && ((~==) j1 j2)\n        && ((~==) k1 k2)\n        && ((~==) l1 l2)\n        && ((~==) m1 m2)\n        && ((~==) n1 n2)\n        )\n    {-# INLINE (~==) #-}\n\ninstance (AEq a, AEq b, AEq c, AEq d, AEq e, AEq f, AEq g, AEq h, AEq i, AEq j, AEq k, AEq l, AEq m, AEq n, AEq o) => AEq (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where\n    (===) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2,l2,m2,n2,o2) =\n        (  ((===) a1 a2)\n        && ((===) b1 b2)\n        && ((===) c1 c2)\n        && ((===) d1 d2)\n        && ((===) e1 e2)\n        && ((===) f1 f2)\n        && ((===) g1 g2)\n        && ((===) h1 h2)\n        && ((===) i1 i2)\n        && ((===) j1 j2)\n        && ((===) k1 k2)\n        && ((===) l1 l2)\n        && ((===) m1 m2)\n        && ((===) n1 n2)\n        && ((===) o1 o2)\n        )\n    {-# INLINE (===) #-}\n\n    (~==) (a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1,n1,o1) (a2,b2,c2,d2,e2,f2,g2,h2,i2,j2,k2,l2,m2,n2,o2) =\n        (  ((~==) a1 a2)\n        && ((~==) b1 b2)\n        && ((~==) c1 c2)\n        && ((~==) d1 d2)\n        && ((~==) e1 e2)\n        && ((~==) f1 f2)\n        && ((~==) g1 g2)\n        && ((~==) h1 h2)\n        && ((~==) i1 i2)\n        && ((~==) j1 j2)\n        && ((~==) k1 k2)\n        && ((~==) l1 l2)\n        && ((~==) m1 m2)\n        && ((~==) n1 n2)\n        && ((~==) o1 o2)\n        )\n    {-# INLINE (~==) #-}\n", "meta": {"hexsha": "5defbfe3d50a06f115179040108bef9ac1891c23", "size": 16133, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/AEq.hs", "max_stars_repo_name": "bjornbm/hs-ieee754-nolibm", "max_stars_repo_head_hexsha": "f44d55f062929b49de9d39299d4da1b86adab3c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-05-08T20:54:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T16:58:43.000Z", "max_issues_repo_path": "Data/AEq.hs", "max_issues_repo_name": "bjornbm/hs-ieee754-nolibm", "max_issues_repo_head_hexsha": "f44d55f062929b49de9d39299d4da1b86adab3c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2015-01-08T17:13:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-11T15:53:43.000Z", "max_forks_repo_path": "Data/AEq.hs", "max_forks_repo_name": "bjornbm/hs-ieee754-nolibm", "max_forks_repo_head_hexsha": "f44d55f062929b49de9d39299d4da1b86adab3c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-04-18T18:58:52.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-06T20:39:46.000Z", "avg_line_length": 27.3904923599, "max_line_length": 159, "alphanum_fraction": 0.3861650034, "num_tokens": 6528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.43348151711684}}
{"text": "module NeuralNetwork.Types where\n\nimport Numeric.LinearAlgebra.Data (R, Vector)\nimport Numeric.Natural (Natural)\n\nnewtype Layer = Layer\n  { numUnits :: Natural\n  } deriving (Eq, Show)\n\ndata Network = Network\n  { inputLayer :: Layer\n  , hiddenLayer :: [Layer]\n  , outputLayer :: Layer\n  } deriving (Eq, Show)\n", "meta": {"hexsha": "8a03af843172e73595f65d31ebc803c248e7d8cd", "size": 308, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NeuralNetwork/Types.hs", "max_stars_repo_name": "sebashack/mlToolBox", "max_stars_repo_head_hexsha": "b5566277833f5ec3341f2165f48cdc5429cbea7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NeuralNetwork/Types.hs", "max_issues_repo_name": "sebashack/mlToolBox", "max_issues_repo_head_hexsha": "b5566277833f5ec3341f2165f48cdc5429cbea7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NeuralNetwork/Types.hs", "max_forks_repo_name": "sebashack/mlToolBox", "max_forks_repo_head_hexsha": "b5566277833f5ec3341f2165f48cdc5429cbea7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-03T23:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T22:33:11.000Z", "avg_line_length": 20.5333333333, "max_line_length": 45, "alphanum_fraction": 0.7077922078, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4334815095986183}}
{"text": "module Main where\n\nimport Softbody\nimport qualified Data.Array.Accelerate as A\nimport Data.Array.Accelerate.LLVM.Native as CPU\nimport Data.Complex\nimport Graphics.Gloss\nimport Graphics.Gloss.Data.ViewPort\nimport Graphics.Gloss.Data.Color\n\nhs_new_v = CPU.runN new_v\n\nupdate_v :: C -> V -> Double -> Double -> V\nupdate_v c v t d = hs_new_v c v (A.fromList A.Z $ [t :+ 0]) (A.fromList A.Z $ [d :+ 0])\n\n---\n\ndisplay_v :: (V, C) -> Picture\ndisplay_v (v, c) = pictures [nodePictures, edgePictures]\n  where\n    complexToFloatTuple (real :+ imag) = (realToFrac real, realToFrac imag)\n    nodeList = A.toList v\n\n    rectangleAt x y = translate x y $ rectangleSolid 10 10\n    nodePictures = pictures (map (\\(pi, delta, alpha, rho) -> uncurry rectangleAt $ complexToFloatTuple pi) nodeList)\n\n    nodePairsWithDistance = zip [(pi1, pi2) | (pi1, _, _, _) <- nodeList, (pi2, _, _, _) <- nodeList] (A.toList c)\n    edgeColor n = mixColors 10 n black red\n    edgePicture ((pi1, pi2), d) = color (edgeColor . realToFrac . abs $ (magnitude $ pi2 - pi1) - d) (line $ complexToFloatTuple <$> [pi1, pi2])\n    edgePictures = pictures (edgePicture <$> nodePairsWithDistance) \n\ntick_v :: ViewPort -> Float -> (V, C) -> (V, C)\ntick_v _ t (v, c) = (update_v c v (realToFrac t * 8) 1, c)\n\nmain :: IO ()\nmain = simulate\n  (InWindow \"https://aearnus.github.io/\" (800, 600) (0, 0))\n  (greyN 0.5)\n  120\n  (my_v, my_c)\n  display_v\n  tick_v\n  \n  \n  \n  \n  \n  \n", "meta": {"hexsha": "ef675df9e2c2caa71c8282e2573ebf00bf545f16", "size": 1426, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "Aearnus/softbody-accelerate", "max_stars_repo_head_hexsha": "c321947f3f173b3bd8584b8e758d0bbec5c3c978", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-20T02:57:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T02:57:19.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "Aearnus/softbody-accelerate", "max_issues_repo_head_hexsha": "c321947f3f173b3bd8584b8e758d0bbec5c3c978", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "Aearnus/softbody-accelerate", "max_forks_repo_head_hexsha": "c321947f3f173b3bd8584b8e758d0bbec5c3c978", "max_forks_repo_licenses": ["BSD-3-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.1020408163, "max_line_length": 144, "alphanum_fraction": 0.6577840112, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4334587912280618}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE QuasiQuotes #-}\n\nmodule Vectors where\n\nimport Feldspar\nimport Feldspar.Array.Vector\nimport Feldspar.Array.Buffered\n\nimport Feldspar.Software\nimport Feldspar.Software as Soft (icompile)\nimport Feldspar.Software.Compile\nimport Feldspar.Software.Marshal\n\nimport Feldspar.Hardware hiding (Arr, IArr, Ref)\nimport Feldspar.Hardware as Hard (icompile, icompileSig, icompileAXILite)\n\nimport Control.Monad (void)\nimport Data.Complex (Complex)\n\n-- language-c-quote\nimport Language.C.Quote.GCC\nimport qualified Language.C.Syntax as C\n\n-- imperative-edsl\nimport qualified Language.Embedded.Backend.C  as Imp\n\nimport Prelude hiding (take, drop, reverse, length, zip, zipWith, sum, tail, map)\n\n--------------------------------------------------------------------------------\n-- * ...\n--------------------------------------------------------------------------------\n\nsumLast5 :: SPull (SExp Word32) -> SExp Word32\nsumLast5 = sum . take 5 . reverse\n\n--------------------------------------------------------------------------------\n\ntest1 :: IO ()\ntest1 = Soft.icompile $ printf \"%d\" $ sumLast5 inp\n  where\n    inp :: SPull (SExp Word32)\n    inp = 0 ... 10\n\n--------------------------------------------------------------------------------\n-- * ...\n--------------------------------------------------------------------------------\n\ndot :: (Vector exp, Pully exp vec a, Num a, Syntax exp a) => vec -> vec -> a\ndot a b = sum $ zipWith (*) a b\n\ndotArr :: IArr (SExp Int32) -> IArr (SExp Int32) -> SExp Int32\ndotArr = dot\n\ndotProg :: Software ()\ndotProg = connectStdIO $ return . uncurry dotArr\n\ndotIO :: IO ()\ndotIO = Soft.icompile dotProg\n\n--------------------------------------------------------------------------------\n\nfir :: (Vector exp, Num a, Syntax exp a) => Pull exp a -> Pull exp a -> Pull exp a\nfir coeff = map (dot coeff . reverse) . tail . inits\n\nfirArr :: IArr (SExp Int32) -> IArr (SExp Int32) -> Pull SExp (SExp Int32)\nfirArr a b = fir (toPull a) (toPull b)\n\nfirProg :: Software ()\nfirProg = connectStdIO $ manifestFresh . uncurry firArr\n\nfirIO :: IO ()\nfirIO = Soft.icompile firProg\n\n--------------------------------------------------------------------------------\n\ntype SStore  a = Store  Software a\n\nprintTime_def = [cedecl|\nvoid printTime(typename clock_t start, typename clock_t end)\n{\n  printf(\"CPU time (sec): %f\\n\", (double)(end-start) / CLOCKS_PER_SEC);\n}\n|]\n\nsizeOf_double_complex :: SExp Length\nsizeOf_double_complex = 16\n\n-- | Measure the time for 100 runs of 'fftCore' (excluding initialization) for\n-- arrays of the given size\nbenchmark :: SExp Length -> Software ()\nbenchmark n = do\n  addInclude \"<stdio.h>\"\n  addInclude \"<string.h>\"\n  addInclude \"<time.h>\"\n  addDefinition printTime_def\n  start <- newObject \"clock_t\" False\n  end   <- newObject \"clock_t\" False\n  st1 :: SStore (SExp (Complex Double)) <- newStore n\n  inp1 <- unsafeFreezeStore n st1\n  callProc \"memset\"\n      [ iarrArg (manifest inp1)\n      , valArg (0 :: SExp Index)\n      , valArg (n*sizeOf_double_complex)\n      ]\n  st2 :: SStore (SExp (Complex Double)) <- newStore n\n  inp2 <- unsafeFreezeStore n st2\n  callProc \"memset\"\n      [ iarrArg (manifest inp1)\n      , valArg (0 :: SExp Index)\n      , valArg (n*sizeOf_double_complex)\n      ]  \n  callProcAssign start \"clock\" []\n\n  for 0 1 99 $ \\(_ :: SExp Index) ->\n    void $ manifestFresh (fir (toPull inp1) (toPull inp2))\n\n  callProcAssign end \"clock\" []\n  callProc \"printTime\" [objArg start, objArg end]\n\nrunBenchmark n = runCompiled'\n  (Imp.def :: CompilerOpts)\n  (Imp.def {Imp.externalFlagsPre = [\"-O3\"], Imp.externalFlagsPost = [\"-lm\"]})\n  (benchmark n)\n\nprintBenchmark n = Soft.icompile (benchmark n)\n\n--------------------------------------------------------------------------------\n\ndot_sig :: HSig (SArr Word32 -> SArr Word32 -> Signal Word32 -> ())\ndot_sig =\n  inputIArr 1 $ \\a ->\n  inputIArr 1 $ \\b ->\n  ret $ pure $ dot a b\n  -- `dot` is pure, so we lift its result.\n\ntest3 :: IO ()\ntest3 = Hard.icompileSig $ dot_sig\n  -- Seems the optimizer isn't happy, might be just my installation tho.\n\ntest4 :: IO ()\ntest4 = Hard.icompileAXILite $ dot_sig\n\n--------------------------------------------------------------------------------\n\ndot_mmap :: Software ()\ndot_mmap =\n  do dot <- mmap \"0x43C00000\" dot_sig\n     a :: Arr (SExp Word32) <- initArr [1]\n     b :: Arr (SExp Word32) <- initArr [1]\n     c :: Ref (SExp Word32) <- newRef\n     --\n     call dot (a >>: b >>: c >: nil)\n     --\n     result <- getRef c\n     printf \"dot: %d\\n\" result\n\ntest5 :: IO ()\ntest5 = Soft.icompile dot_mmap\n\n--------------------------------------------------------------------------------\n", "meta": {"hexsha": "f779bb81c7d292b0e3aa4a503327dac03ff45445", "size": 4753, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/Vectors.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": "examples/Vectors.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": "examples/Vectors.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": 28.6325301205, "max_line_length": 82, "alphanum_fraction": 0.5554386703, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4332057535446858}}
{"text": "{-# LANGUAGE CPP                 #-}\n{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE KindSignatures      #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell     #-}\n{-# LANGUAGE TypeOperators       #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\nmodule Test.Grenade.Layers.LRN where\n\nimport           Data.Singletons              ()\nimport           GHC.TypeLits\nimport           Hedgehog\nimport           Data.Proxy\nimport           Data.Kind (Type)\nimport           Test.Hedgehog.Hmatrix\nimport           Test.Grenade.Layers.Internal.Reference\nimport qualified System.Random.MWC as MWC\nimport           Control.DeepSeq\nimport           Control.Exception (evaluate)\nimport           Test.Hedgehog.Compat\nimport           Data.Serialize\nimport           Data.Either\n\nimport           Grenade.Core\nimport           Grenade.Layers.LRN\nimport           Grenade.Types\nimport           Numeric.LinearAlgebra.Data   as NLD hiding ((===))\nimport           Numeric.LinearAlgebra.Static as H hiding ((===))\n\nexpectedDepth1\n  = [\n      [0.99992500, 1.99940020, 2.99797659],\n      [3.99520671, 4.99064546, 5.98385086],\n      [6.97438480, 7.96181378, 8.94570965],\n      [1.09990018, 2.09930569, 3.09776755],\n      [4.09483851, 5.09007376, 6.08303166],\n      [7.07327453, 8.06036937, 9.04388861],\n      [1.19987041, 2.19920173, 3.19754459],\n      [4.19445196, 5.18947928, 6.18218531],\n      [7.17213277, 8.15888920, 9.14202759]\n    ]\n\nexpectedDepth2\n  = [\n      [0.99992500, 1.99940020, 2.99797659],\n      [3.99520671, 4.99064546, 5.98385086],\n      [6.97438480, 7.96181378, 8.94570965],\n\n      [1.09981771, 2.09867639, 3.09568020],\n      [4.08993980, 5.08057535, 6.06671955],\n      [7.04752047, 8.02214440, 8.98977845],\n\n      [1.19976155, 2.19847498, 3.19524425],\n      [4.18918085, 5.17940607, 6.16505399],\n      [7.14527441, 8.11923556, 9.08612680]\n    ]\n\nexpectedDepth3\n  = [\n      [0.99983428, 1.99873942, 2.99581955],\n      [3.99018517, 4.98095623, 5.96726513],\n      [6.94825962, 7.92310558, 8.89098967],\n\n      [1.09969897, 2.09791554, 3.09330926],\n      [4.08455479, 5.07034831, 6.04941408],\n      [7.02051070, 7.98243693, 8.93403711],\n\n      [1.19976155, 2.19847498, 3.19524425],\n      [4.18918085, 5.17940607, 6.16505399],\n      [7.14527441, 8.11923556, 9.08612680]\n    ]\n\nprop_lrn_forwards_fixed :: Property\nprop_lrn_forwards_fixed = property $ do\n  let ch1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n      ch2 = map (map (0.1 +)) ch1\n      ch3 = map (map (0.1 +)) ch2\n      dat = concat [ch1, ch2, ch3]\n      mat = (NLD.fromLists dat) :: NLD.Matrix RealNum\n\n      lrn   = LRN :: (LRN \"0.0001\" \"0.75\" \"1\" 1)\n      lrn'  = LRN :: (LRN \"0.0001\" \"0.75\" \"1\" 2)\n      lrn'' = LRN :: (LRN \"0.0001\" \"0.75\" \"1\" 3)\n\n      Just inp = (H.create mat) :: Maybe (H.L 9 3)\n      (out,   expMat)   = getOutput lrn   expectedDepth1 inp\n      (out',  expMat')  = getOutput lrn'  expectedDepth2 inp \n      (out'', expMat'') = getOutput lrn'' expectedDepth3 inp\n\n  out   `isSimilarMatrixTo` expMat   \n  out'  `isSimilarMatrixTo` expMat'  \n  out'' `isSimilarMatrixTo` expMat'' \n  where\n    -- Helper function to \n    getOutput :: (KnownSymbol a, KnownSymbol b, KnownSymbol k, KnownNat n) => LRN a b k n -> [[RealNum]] -> H.L 9 3 -> (Matrix RealNum, Matrix RealNum)\n    getOutput l e inp = (H.extract o, NLD.fromLists e)\n      where\n      (_, S3D o :: (S ('D3 3 3 3))) = runForwards l ((S3D inp) :: (S ('D3 3 3 3)))\n\ndata OpaqueLRN :: Type where\n  OpaqueLRN :: (KnownNat i) => LRN \"0.0001\" \"0.75\" \"1\" i -> OpaqueLRN\n\ngenOpaqueLRN :: Gen OpaqueLRN\ngenOpaqueLRN = do\n  s :: Integer <- choose 1 7\n  let Just s' = someNatVal s\n  case s' of\n      SomeNat (Proxy :: Proxy i') ->\n          return . OpaqueLRN $ (LRN :: LRN \"0.0001\" \"0.75\" \"1\" i')\n\nprop_lrn_forwards :: Property \nprop_lrn_forwards = property $ do\n  OpaqueLRN (lrn :: LRN \"0.0001\" \"0.75\" \"1\" n) <- blindForAll genOpaqueLRN\n  let n' = natVal (Proxy :: Proxy n)\n  source <- forAll $ genLists3D 5 11 7 -- 5 channels, 11 rows, 7 columns\n  let inp = S3D (H.fromList $ (concat . concat) source) :: S ('D3 11 7 5)\n      (_, o :: (S ('D3 11 7 5))) = runForwards lrn inp\n      out = naiveLRNForwards 0.0001 0.75 1 (fromIntegral n') source\n  \n  assert $ allClose o (S3D (H.fromList $ (concat . concat) out))\n\nprop_lrn_backwards :: Property \nprop_lrn_backwards = property $ do\n  OpaqueLRN (lrn :: LRN \"0.0001\" \"0.75\" \"1\" n) <- blindForAll genOpaqueLRN\n  let n' = natVal (Proxy :: Proxy n)\n  source <- forAll $ genLists3D 5 11 7 -- 5 channels, 11 rows, 7 columns\n  let inp = S3D (H.fromList $ (concat . concat) source) :: S ('D3 11 7 5)\n      (tape, o :: (S ('D3 11 7 5))) = runForwards lrn inp\n      ((),    d :: (S ('D3 11 7 5))) = runBackwards lrn tape o\n      out = naiveLRNForwards 0.0001 0.75 1 (fromIntegral n') source\n      back = naiveLRNBackwards 0.0001 0.75 1 (fromIntegral n') source out\n\n  assert $ allClose d (S3D (H.fromList $ (concat . concat) back))\n\nprop_lrn_show :: Property\nprop_lrn_show = withTests 1 $ property $ do\n  let lrn = LRN :: (LRN \"0.0001\" \"0.75\" \"1\" 1)\n  (show lrn) `seq` success\n\nprop_lrn_rnf :: Property\nprop_lrn_rnf = withTests 1 $ property $ do\n  let lrn = LRN :: (LRN \"0.0001\" \"0.75\" \"1\" 1)\n  (r :: ()) <- evalIO $ evaluate $ rnf lrn\n  r `seq` success\n\nprop_lrn_run_update :: Property\nprop_lrn_run_update = withTests 1 $ property $ do\n  source <- forAll $ genLists 12 17\n  gen <- evalIO MWC.create\n  (lrn :: LRN \"0.0001\" \"0.75\" \"1\" 1) <- evalIO $ createRandomWith UniformInit gen\n  let mat = (NLD.fromLists source) :: NLD.Matrix RealNum\n      Just inp = (H.create mat) :: Maybe (H.L 12 17)\n      (tape, o :: (S ('D3 3 17 4))) = runForwards lrn ((S3D inp) :: (S ('D3 3 17 4)))\n      (grad, _ :: (S ('D3 3 17 4))) = runBackwards lrn tape o\n  (runUpdate defSGD lrn grad) `seq` (runUpdate defAdam lrn grad) `seq` success\n  (reduceGradient @(LRN \"0.0001\" \"0.75\" \"1\" 1) [grad]) `seq` success\n\nprop_lrn_serializable :: Property\nprop_lrn_serializable = withTests 1 $ property $ do\n  gen <- evalIO MWC.create\n  (lrn :: LRN \"0.0001\" \"0.75\" \"1\" 1) <- evalIO $ createRandomWith UniformInit gen\n  let bs  = encode lrn\n      dec = decode bs :: Either String (LRN \"0.0001\" \"0.75\" \"1\" 1)\n  assert $ isRight dec\n  (put lrn) `seq` success\n\ntests :: IO Bool\ntests = checkParallel $$(discover)\n", "meta": {"hexsha": "1043e1706facb7cfee798edf1b541a6ed64ad932", "size": 6401, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Layers/LRN.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Layers/LRN.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Layers/LRN.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0, "max_line_length": 151, "alphanum_fraction": 0.6075613185, "num_tokens": 2394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.43265775569025283}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE Arrows, FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE DeriveGeneric #-}\n\nmodule Examples.MultiCamera where\n\nimport Control.Arrow hiding ((|||))\nimport Control.Monad (replicateM, forM)\nimport Control.Monad.Trans (MonadIO, liftIO, lift)\nimport Control.Monad.Bayes.Class (MonadSample, MonadCond, logCategorical)\nimport Control.Monad.Bayes.Sampler (SamplerIO, sampleIO)\n\nimport Data.Aeson hiding (Result)\nimport Data.Maybe (catMaybes)\n\nimport GHC.Generics (Generic)\n\nimport qualified Data.ByteString.Lazy.Char8 as BS (putStrLn)\n\nimport Numeric.LinearAlgebra.Static\n\nimport Inference (zdsparticles, zunheap)\nimport DelayedSampling (MDistr (..), children, state, State, MarginalT (..), SMarginalT(..), distr, typeOfDSDistr, DelayedInfer)\nimport qualified SymbolicDistr as DS\nimport DSProg (DeepForce (..), Result (..), Expr' (..), Expr, marginal, zdeepForce)\nimport Distributions (normal, poisson, sample, observe, bernoulli, replicateIID, passert, factor, uniformIntRange)\nimport MVDistributions (shuffleList, mvNormal, uniformNSphere)\nimport Util.ZStream (ZStream)\nimport qualified Util.ZStream as ZS\nimport Util.Ref (MonadState, Heap, emptyHeap, readRef)\n\nimport Numeric.SpecFunctions (logGamma)\nimport Numeric.Log (Log (Exp), ln)\n\nimport qualified Data.Vector.Storable as V (fromList)\n\nimport qualified Metaprob as MP\n\nnumCameras :: Int\nnumCameras = 2\n\nnumPoses :: Int\nnumPoses = 10\n\ntype CameraID = Int\ntype Pose = Int\n\ndata TrackG pv = Track\n  { posWH :: pv\n  , startTime :: Double\n  , trackID :: Int\n  , identity :: Int\n  , camera :: CameraID\n  }\n  deriving (Generic, Show)\n\ninstance ToJSON pv => ToJSON (TrackG pv)\n\ninstance DeepForce pv => DeepForce (TrackG pv) where\n  type Forced (TrackG pv) = TrackG (Forced pv)\n  deepForce (Track pv h t id c) = Track <$> deepForce pv <*> deepForce h <*> pure t <*> pure id <*> pure c\n  deepConst (Track pv h t id c) = Track (deepConst pv) (deepConst h) t id c\n\ntype STrack = TrackG (Expr (R 4))\ntype Track = TrackG (R 4)\ntype MarginalTrack = TrackG (Result (R 4))\n\ntype Appearance = Expr (R 10)\n\ntdiff :: Double\ntdiff = 1\n\nposWHCovBlocks :: Sym 2 -> Sym 2 -> Sym 4\nposWHCovBlocks pcov whcov = sym $\n  ((unSym pcov ||| (konst 0 :: Sq 2))\n        ===\n  ((konst 0 :: Sq 2) ||| unSym whcov))\n\nnewTrack'' :: MonadState Heap m => MonadSample m => Double -> Int -> Int -> Int -> m STrack\nnewTrack'' t tid id c = do\n  pv <- DS.sample (DS.mvNormal (Const mu) cov)\n  pure (Track pv t tid id c)\n  where\n  mu = (konst 0 :: R 2) # (konst 1 :: R 2)\n  cov = posWHCovBlocks (sym eye :: Sym 2) (0.2 * sym eye :: Sym 2)\n\nnewTrack :: MonadState Heap m => MonadSample m => [Appearance] -> Double -> Int -> m (STrack, [Appearance])\nnewTrack appearances t tid = do\n  camera <- sample (uniformIntRange numCameras)\n  newAppearance <- sample (bernoulli (1 / (fromIntegral (length appearances) + 1)))\n  (appearanceID, appearances') <- if newAppearance\n    then do\n         app <- DS.sample (DS.mvNormal (Const 0) (sym eye))\n         pure (length appearances, appearances ++ [app])\n    else do\n         appID <- sample (uniformIntRange (length appearances))\n         pure (appID, appearances)\n  newTrack <- newTrack'' t tid appearanceID camera\n  pure (newTrack, appearances')\n\n\ntrackMotion :: MonadState Heap m => MonadSample m => Double -> STrack -> m STrack\ntrackMotion tdiff track = do\n  pv' <- DS.sample (DS.mvNormal (MVMul (Const motionMatrix) (posWH track)) motionCov)\n  pure $ track { posWH = pv' }\n  where\n  motionMatrix = eye :: Sq 4\n  motionCov :: Sym 4\n  motionCov = sym (konst tdiff) * posWHCovBlocks (sym eye) (sym (konst 0.1 * eye))\n\ntrackSurvivalMotion :: MonadState Heap m => MonadSample m => Double -> STrack -> m (Maybe STrack)\ntrackSurvivalMotion tdiff track = do\n  survived <- sample (bernoulli (exp (- tdiff * deathRate)))\n  if survived\n    then Just <$> trackMotion tdiff track\n    else pure Nothing\n  where\n  deathRate = 0.02\n\ntrackMeasurement :: [Appearance] -> STrack -> DS.Distr (Expr (R 4), (R 10, Expr (R 1)))\ntrackMeasurement appearances track =\n  DS.indep (DS.mvNormal (posWH track) (sym eye)) $\n  DS.bind uniformNSphere $ \\pose ->\n    DS.mvNormal (MVMul (Const (row pose)) (appearances !! identity track)) (sym eye)\n\n-- Naive association\nassociationWithClutter :: forall a b. DeepForce b => DS.Distr [b] -> (a -> DS.Distr b) -> [a] -> DS.Distr [b]\nassociationWithClutter cluttersD obsD tracks = DS.Distr is iobs undefined where\n  is :: MonadState Heap m => MonadSample m => m [b]\n  is = do\n    clutter <- DS.sample cluttersD\n    observations <- mapM (DS.sample . obsD) tracks\n    shuffleList (observations ++ clutter)\n  defaultObserve :: DelayedInfer m => [Forced b] -> m ()\n  defaultObserve observations = do\n    passert (length tracks <= length observations)\n    observations' <- shuffleList observations\n    let (observations'', clutter) = splitAt (length tracks) observations'\n    mapM_ (\\(t, o) -> DS.observe (obsD t) o) (zip tracks observations'')\n    DS.observe cluttersD clutter\n  iobs :: DelayedInfer m => [Forced b] -> m ()\n  iobs = if True\n    then assocWithClutterCustomProposal cluttersD obsD tracks\n    else defaultObserve\n\nassocWithClutterCustomProposal :: DelayedInfer m => DeepForce b => DS.Distr [b] -> (a -> DS.Distr b) -> [a] -> [Forced b] -> m ()\nassocWithClutterCustomProposal cluttersD obsD allTracks allObservations = go allTracks allObservations where\n  numTracks = fromIntegral (length (allTracks))\n  numObservations = fromIntegral (length (allObservations))\n  go [] clutter = do\n    let numClutter = fromIntegral (length clutter)\n    factor (- (logGamma (numTracks + numClutter + 1) - logGamma (numClutter + 1)))\n    DS.observe cluttersD clutter\n  go (track : tracks) [] =\n    passert False\n  go (track : tracks) observations = do\n    let obsDistr = obsD track\n    lls <- map Exp <$> mapM (DS.score obsDistr) observations\n    let totalLL = sum lls\n    let adjLLs = map (/ totalLL) lls\n    i <- logCategorical (V.fromList adjLLs)\n    let (os1, obs : os2) = splitAt i observations\n    DS.observe obsDistr obs\n    factor (ln (recip (adjLLs !! i))) -- proposal correction\n    go tracks (os1 ++ os2)\n\n\ntracksMeasurement :: [Appearance] -> [STrack] -> DS.Distr [(Expr (R 4), (R 10, Expr (R 1)))]\ntracksMeasurement appearances = associationWithClutter cluttersDistr (trackMeasurement appearances)\n  where\n  cluttersDistr = DS.replicateIID (poisson amtClutter) clutterDistr\n  amtClutter :: Double\n  amtClutter = 1\n  clutterDistr :: DS.Distr (Expr (R 4), (R 10, Expr (R 1)))\n  clutterDistr = DS.indep (DS.mvNormal (Const ((konst 0 :: R 2) # (konst 1 :: R 2))) (sym eye))\n    $ DS.bind (mvNormal 0 (sym eye)) (\\_ -> DS.mvNormal (Const 0) (sym eye))\n\n-- NOTE: Currently, it is possible that we will generate a new track\n-- with the same identity and camera as an existing track.\n-- Should consider how to change the model so that this doesn't happen.\ntracksMotion :: MonadState Heap m => MonadSample m => Double -> Double -> [STrack] -> Int -> [Appearance] -> m ([STrack], Int, [Appearance])\ntracksMotion t tdiff tracks numTracks appearances = do\n  liveTracks <- catMaybes <$> mapM (trackSurvivalMotion tdiff) tracks\n  numNewTracks <- sample (poisson (birthRate * tdiff))\n  (newTracks, appearances') <- generateNewTracks appearances (numTracks + 1) numNewTracks\n  pure (liveTracks ++ newTracks, numTracks + numNewTracks, appearances')\n  where\n  generateNewTracks apps nt 0 = pure ([], apps)\n  generateNewTracks apps nt n = do\n    (newT, apps') <- newTrack apps t nt\n    (\\(x, y) -> (newT : x, y)) <$> generateNewTracks apps' (nt + 1) (n - 1)\n  birthRate = 0.1\n\n-- Note how extraneous state about the number of tracks and the time is kept hidden\nzstepGen :: MonadState Heap m => MonadSample m => ZStream (MP.Gen m) () ([STrack], [(CameraID, R 10, Expr (R 4), Expr (R 1))])\nzstepGen = ZS.fromStep stepf initState\n  where\n  initState :: (Double, [TrackG pv], Int, [Appearance])\n  initState = (0, [], 0, [])\n  stepf (t, tracks, numTracks, appearances) () = do\n    (tracks', newNumTracks, appearances') <- lift (tracksMotion t tdiff tracks numTracks appearances)\n    observations <- forM [0 .. numCameras - 1] $ \\camID -> do\n      obs <- (\"obs.\" ++ show camID) MP.~~ MP.dsPrim (tracksMeasurement appearances' (filter (\\t -> camera t == camID) tracks'))\n      return [ (camID, pose, pvwh, obsAppear) | (pvwh, (pose, obsAppear)) <- obs ]\n    return ((t + tdiff, tracks', newNumTracks, appearances'), (tracks', concat observations))\n\nprocessObservationsStream :: DelayedInfer m => ZStream m [(CameraID, R 10, R 4, R 1)] [MarginalTrack]\nprocessObservationsStream = proc observations -> do\n  (tracks', _) <- MP.zobserving zstepGen -< ((), \"obs\" MP.|-> MP.obs observations)\n  ZS.run -< mapM trackf tracks'\n  where\n  trackf :: DelayedInfer m => STrack -> m MarginalTrack\n  trackf track = do\n    Just pv <- marginal (posWH track)\n    pure $ track { posWH = pv }\n\ngenerateGroundTruth :: MonadState Heap m => MonadSample m => ZStream m () ([STrack], [(CameraID, R 10, Expr (R 4), Expr (R 1))])\ngenerateGroundTruth = ZS.liftM MP.sim zstepGen\n\nrunMTTPF :: Int -> ZStream SamplerIO () ([Track], [[MarginalTrack]], [(CameraID, R 10, R 4, R 1)])\nrunMTTPF numParticles = proc () -> do\n  (groundTruth, obs) <- zdeepForce generateGroundTruth -< ()\n  particles <- zdsparticles numParticles processObservationsStream -< obs\n  returnA -< (groundTruth, particles, obs)\n\nrunExample :: IO ()\nrunExample = sampleIO $ ZS.runStream (liftIO . BS.putStrLn . encode) (runMTTPF 100)", "meta": {"hexsha": "b726f325aa74c3d1dc434fd3ec03598e07f2f7b1", "size": 9465, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/Examples/MultiCamera.hs", "max_stars_repo_name": "psg-mit/probzelus-haskell", "max_stars_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-26T13:13:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T19:11:41.000Z", "max_issues_repo_path": "haskell/src/Examples/MultiCamera.hs", "max_issues_repo_name": "psg-mit/probzelus-haskell", "max_issues_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/src/Examples/MultiCamera.hs", "max_forks_repo_name": "psg-mit/probzelus-haskell", "max_forks_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5131578947, "max_line_length": 140, "alphanum_fraction": 0.6864236661, "num_tokens": 2793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4326317444630921}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\nmodule Analysis.FFT (auralDistance, peakList) where\n\n-- need to create frequency frames for peaks after the FFT has been applied\nimport Data.Complex\nimport Data.List\nimport Data.List.Split\nimport Data.Ord\nimport Data.Audio\nimport Numeric.Extra\nimport Data.Int\nimport Data.Array.IArray\nimport Numeric.Transform.Fourier.FFT\n\nimport Control.Parallel.Strategies\n\nimport Analysis.FFT_Py\n\nimport Types.Common\nimport qualified Settings as S\nimport Utils\n\nimport Shelly (shelly, silently, run)\nimport Data.String\n\nauralDistance :: (FilePath, AudioFormat) -> (FilePath, AudioFormat) -> IO Double\nauralDistance a1 a2 = do\n  ps1 <- peakList a1\n  ps2 <- peakList a2\n  -- since I am not looking at time shifting filter for now, I can zipWith over time to remove the time domain\n  -- NB this means the times need to line up 'exactly', ie this will not work well for real-world examples\n  --    but only for contrsucted examples where I apply the filter to the sample myself (eg in audacity)\n  --mapM_ plot $ take 5 $ zip (map sort ps1) (map sort ps2) \n  let \n    distances = zipWith (comparePeaks) (map sort ps1) (map sort ps2)\n    average ls = sum ls / genericLength ls\n  return $ average distances \n\nplot :: ([Peak], [Peak]) -> IO()\nplot (ps1, ps2) = do\n  writeFile \"tmp1.csv\" (listToCSV ps1)\n  writeFile \"tmp2.csv\" (listToCSV ps2)\n  results <- shelly $ silently $ run (fromString \"gnuplot\") \n               [ \"-p\"\n               , \"plotter.gnuplot\" ]\n  return ()\n  \n\ncomparePeaks ps1 ps2 = \n  sum $ zipWith comparePeak ps1 ps2\n\n-- TODO rethink how i do distances...\n-- | for a single time slice, do euclid distance treating (freq,amp) as (x,y)\n--   should always have the same number of points, but they might not lineup exactly...\n--   eg (3,0.1),(4,0.5),(5,0.5) vs (4,0.5),(5,0.5),(6,0.1) should be rated as fairly close\ncomparePeak :: Peak -> Peak -> Double\ncomparePeak peak1 peak2 = let\n  freq1 = intToDouble $ getFreq peak1\n  freq2 = intToDouble $ getFreq peak2\n  amp1 = getAmp peak1\n  amp2 = getAmp peak2\n in \n    {-if amp2 == 0\n    then 1000 --penalize zero files\n    else -}\n    --traceShow ((show freq1)++\" \"++(show amp1)++\", \"++(show freq2)++\" \"++(show amp2) ) \n    (euclidDistance (freq1,amp1) (freq2,amp2)) / 1000-- + 1/(amp2+0.00001)\n\n-- | break an audio file into time slices and i\n--   find the freq peaks that are most predominate for each time slice\npeakList :: (FilePath, AudioFormat) -> IO (OverTime (OverFreq Peak))\npeakList (fp,a) = do\n  peaks <- peakListPython fp\n  let normPeaks = normalize peaks\n  return $ getMainPeaks normPeaks\n\n-- | Scale so max over all time slices is 1\n--   note that this means some time slices will not have a max of 1\n--   another option is to normlize so that the integral of the fft is 1\nnormalize :: [[Peak]] -> [[Peak]]\nnormalize ps = let\n  maxPeak = maximum $ concatMap (map getAmp) ps\n  scaleFactor = 1 / maxPeak \n in\n  map (map (\\(frq,amp) -> (frq, amp* scaleFactor))) ps\n\n{-\n--takes wave file and turns it's values into list of Complex Doubles\nwavList :: AudioFormat -> OverTime Double\nwavList wav = let\n    l1 = sampleData wav\n  --takes at most a certain time frame\n  in take (16384*10) $ elems $ amap (toSample) l1\n\n-- mkFrames takes assocs of audio file and breaks it into 4096 sample (.09s) frames (overlapped by 50%)\nmkFrames :: OverTime Double -> OverTime (OverTime Double)\nmkFrames list1 =\n  if (length list1) < S.frameRes --Settings.framerate\n    then []\n    else (take S.frameRes list1):(mkFrames (drop S.overlap list1))\n\n-- | performs FFT on a list of samples, and conversts each sample to a list of peaks as the triple (freq,amp,phase)\n--   returns a list (in the time domain) of peaks (freq domain) \nconstellateAll :: OverTime (OverTime Double) -> OverTime (OverFreq Peak)\nconstellateAll timeSlices = let\n    -- what the heck does this do?\n    sparsifying n= foldr (.) id (replicate n (remove_every_nth 2))\n    ars1 = --sparsifying S.resolution $ \n               --why not length sample here?\n               map (\\samples -> listArray (0,(S.frameRes - 1)) samples) timeSlices\n    in map ((take (S.frameRes `div` 2)).assocs.constellate.rfft) ars1\n\n-- constellate takes results of FFT and turns it into (amp,phase) at each frequency point\nconstellate :: Array Int (Complex Double) -> Array Int (Double,Double)\nconstellate arr1 =\n  let list1 = assocs arr1\n      polar1 = map (polar.snd) list1 --TODO use amap for array\n      in listArray (0,((length list1) - 1)) polar1\n-}\n\n-- | with the full set of peaks for a list of frames,\n--   we want to essentially apply a filter to each time slice\n--   so that we only have the main peaks for that time slice\ngetMainPeaks :: OverTime (OverFreq Peak) -> OverTime (OverFreq Peak)\ngetMainPeaks ts =\n  map (findBiggestPeaks. freqBins) ts\n\n-- | partition a sample slice's peaks by freq into bins\n--   this allows for a bit of flexibilty in freq analysis\n--   ie dont need the exact same freqs to be the same\n--   sameness of frequency is determined by bin size\n--   NB the OverFreq interprtation seems to break down here\nfreqBins :: OverFreq Peak -> [[Peak]] \nfreqBins = chunksOf S.binSize \n\n-- | for a given sample slices' peaks in each freq bin, \n--   get the biggest (by amp) in each bin\n--   then take the biggest numPeaks of those\nfindBiggestPeaks :: [[Peak]] -> [Peak]\nfindBiggestPeaks ts = let\n   -- first sort each bin, and only take the largest\n   -- this eliminates the 'noisy' freqs nearby the peaks\n   largestPeaksPerBin = map (last.(sortBy (comparing getAmp))) ts\n   -- then we want to get the biggest peaks our of all the loudest bins (or 'freq areas')\n   -- so we first sort by loudest 'freq areas'\n   largestBinPerSampleSlice = reverse $ sortBy (comparing getAmp) largestPeaksPerBin\n  in \n   -- to find the S.numPeaks biggest peaks\n   take S.numPeaks $ largestBinPerSampleSlice\n\n-- listTriple turns tuple of int and tuple and makes it into a triple\nlistTriple :: [(a,(b,b))] -> [(a,b,b)]\nlistTriple xs = \n   map (\\(x,(y,z)) -> (x,y,z)) xs\n", "meta": {"hexsha": "4ba3358a5204482e24a5e0ffb4cd832c190462f1", "size": 5982, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "DSP-PBE/src/Analysis/FFT.hs", "max_stars_repo_name": "Yale-OMI/DSP-PBE", "max_stars_repo_head_hexsha": "073f366e8096004adeec5d2cde1cf3546c4690f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-03T02:36:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-03T02:36:39.000Z", "max_issues_repo_path": "DSP-PBE/src/Analysis/FFT.hs", "max_issues_repo_name": "Yale-OMI/DSP-PBE", "max_issues_repo_head_hexsha": "073f366e8096004adeec5d2cde1cf3546c4690f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2018-11-16T21:50:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-16T18:57:19.000Z", "max_forks_repo_path": "DSP-PBE/src/Analysis/FFT.hs", "max_forks_repo_name": "Yale-OMI/DSP-PBE", "max_forks_repo_head_hexsha": "073f366e8096004adeec5d2cde1cf3546c4690f5", "max_forks_repo_licenses": ["BSD-3-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.5935483871, "max_line_length": 115, "alphanum_fraction": 0.6959210966, "num_tokens": 1754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4324830317410691}}
{"text": "{-# LANGUAGE GADTs, NoImplicitPrelude, TypeFamilies,\nInstanceSigs, StandaloneDeriving, UndecidableInstances,\nScopedTypeVariables, FlexibleInstances, DataKinds,\nFunctionalDependencies, PolyKinds, \nTypeOperators, RankNTypes, ImpredicativeTypes, MultiParamTypeClasses,\nAllowAmbiguousTypes, TypeApplications, FlexibleContexts #-}\n--- \nmodule Main where\n\n\nimport qualified Data.Map.Strict as Map\nimport Prelude hiding ((.), id)\nimport Linear.Vector\nimport Data.Tuple\nimport Data.Complex\nimport Linear.Epsilon (nearZero)\nimport Control.Category\nimport Control.Monad ((<=<))\nimport GHC.TypeNats\nimport Data.Proxy\nimport Diag (mymain)\n-- import qualified Text.PrettyPrint.ANSI.Leijen as PP\nimport qualified Text.PrettyPrint.Boxes as B\n-- import Control.Arrow\n{-\ntype MapVec r k = Map.Map k r\n\nvadd :: (Ord k, Num r) => MapVec r k -> MapVec r k -> MapVec r k\nvadd = Map.unionWith (+)\n\nsmul :: (Ord k, Num r) => k -> MapVec r k -> MapVec r k\nsmul\n\n-- kmett alread did this stuff \n-}\n\n-- http://blog.sigfpe.com/2007/03/monads-vector-spaces-and-quantum.html\n\n\ndata W b a = W { runW :: [(a,b)] } deriving (Eq,Show,Ord)\ninstance Semigroup (W b a) where\n  (W x) <> (W y) = W (x <> y)\ninstance Monoid (W b a) where\n  mempty = W mempty \nmapW f (W l) = W $ map (\\(a,b) -> (a,f b)) l\ninstance Functor (W b) where\n    fmap f (W a) = W $ map (\\(a,p) -> (f a,p)) a\n\ninstance Num b => Applicative (W b) where\n  pure x = W [(x,1)]\n  (W fs) <*> (W xs) = W [(f x, a * b) | (f, a) <- fs, (x, b) <- xs] \n  -- the fs is a a vector of rows kind of.\n    -- error \"I don't feel like it\"\n\ninstance Num b => Monad (W b) where\n   return x = W [(x,1)]\n   l >>= f = W $ concatMap (\\(W d,p) -> map (\\(x,q)->(x,p*q)) d) (runW $ fmap f l)\n\na .* b = mapW (a*) b\n\ninstance (Eq a,Show a,Num b) => Num (W b a) where\n     W a + W b = W $ (a ++ b)\n     a - b = a + (-1) .* b\n     _ * _ = error \"Num is annoying\"\n     abs _ = error \"Num is annoying\"\n     signum _ = error \"Num is annoying\"\n     fromInteger a = if a==0 then W [] else error \"fromInteger can only take zero argument\"\n\ncollect :: (Ord a, Num b) => W b a -> W b a\ncollect = W . Map.toList . Map.fromListWith (+) . runW\n\ntrimZero = W . filter (\\(k,v) -> not $ nearZero v) . runW\nsimplify :: Ord a => Q a -> Q a\nsimplify = trimZero . collect\n-- filter (not . nearZero . snd)\n\ntype P a = W Double a\n\ntype Q a = W (Complex Double) a\n\nv1 :: Map.Map Bool Double \nv1 = zero\n\nboolbase :: [Map.Map Bool Double]\nboolbase = basis\n\ne1 = Map.singleton True 1.0\ne2 = Map.singleton False 1.0\n\n\nstar = mapW conjugate\n\n{-\nThere are two types of particles\n\n\n-}\ndata FibAnyon = Id | Tau\n-- I started using DataKinds and it ended up being a problem.\n\ndata A a \n\ndata Tau\ndata Id\ndata FibTree root leaves where\n   TTT :: FibTree Tau l -> FibTree Tau r -> FibTree Tau (l,r)\n   ITT :: FibTree Tau l -> FibTree Tau r -> FibTree Id (l,r) -- we would like to enforce that isingany can split into a b, but thisis tough\n   TIT :: FibTree Id l -> FibTree Tau r -> FibTree Tau (l,r)\n   TTI :: FibTree Tau l -> FibTree Id r -> FibTree Tau (l,r)\n   III :: FibTree Id l -> FibTree Id r -> FibTree Id (l,r)\n   -- III :: FibTree 'Id l -> FibTree 'Id l' -> FibTree 'Id (l,l') -- maybe shouldn't exist. uneccessary. Does really help for monoidal instance\n   TLeaf :: FibTree Tau Tau\n   ILeaf :: FibTree Id Id\n\n-- pretty printing would be hella nice\n--deriving instance Show (FibTree a b)\n\ninstance Show (FibTree a b) where\n  show = drawTree\nderiving instance Eq (FibTree a b)\n--deriving instance Ord (FibTree a b)\n{-\nr = PP.text \"\\\\\"\nl = PP.text \"/\"\nls = PP.group $ (PP.text \"  /\" <> PP.line <> PP.text \" /\" <> PP.line <>PP.text \"/\")\nrs = PP.group $ (PP.text \"\\\\\" <> PP.line <> PP.text \" \\\\\" <> PP.line <>PP.text \"  \\\\\")\n-}\n\nsp = B.char ' '\nl = B.char '/'\nr = B.char '\\\\'\nh = B.char '-'\nv = B.char '|'\nt = B.char 'T'\ni = B.char 'I'\nrs x =  (r  B.<> sp B.<> sp) B.//\n      (sp B.<> r  B.<> x) B.//\n      (sp B.<> sp  B.<> r)\nls x =  (sp  B.<> sp B.<> l) B.//\n      (x B.<> l  B.<> sp) B.//\n      (l B.<> sp  B.<> sp)\n\n\n{-\ndrawty = v B.// v B.// v B.// (h B.<> h B.<> h B.<> h)\ndrawb :: FibTree a b -> B.Box\ndrawb ILeaf = i\ndrawb TLeaf = t\ndrawb (TTT l r) = (drawb l) B.vcat   B.// ((drawb r)  B.<> v )\n-}\n-- PP.nest 2 l <> PP.line <> PP.nest 1 l <> PP.line <> l\n-- text \"Tau \\\\\"\n-- text \"Id \\\\\"\n\n-- From Data.Tree\n\ndraw :: FibTree a b -> [String]\ndraw (ITT l r) = \"I\" : drawSubTrees (l,r)\ndraw (TIT l r) = \"T\" : drawSubTrees (l,r)\ndraw (TTT l r) = \"T\" : drawSubTrees (l,r)\ndraw (TTI l r) = \"T\" : drawSubTrees (l,r)\ndraw (III l r) = \"I\" : drawSubTrees (l,r)\ndraw  ILeaf    = \"I\" : []\ndraw  TLeaf    = \"T\" : []\n\n-- drawSubTrees' [] = []\ndrawSubTrees' t =\n    \"|\" : shift \"`- \" \"   \" (draw t)\ndrawSubTrees (t,ts) =\n    \"|\" : shift \"+- \" \"|  \" (draw t) ++ drawSubTrees' ts\n\nshift first other = zipWith (++) (first : repeat other)\n\n{-\ndraw' ILeaf = [\"I\"]\ndraw' TLeaf = [\"T\"]\ndraw' (TTT l r) =  \" -\" ++ ((fmap . fmap) (\\s -> s ++ \"  |\") (draw' l)) ++ ([\"-+\"] ++ draw' r))\n-}\n-- drawex = drawb (TTT (TTT TLeaf TLeaf) TLeaf)\n\n\n-- | Neat 2-dimensional drawing of a tree.\ndrawTree :: FibTree a b -> String\ndrawTree  = unlines . draw\n\n-- | Neat 2-dimensional drawing of a forest.\n-- drawForest :: Forest String -> String\n-- drawForest  = unlines . map drawTree\n\ninstance Ord (FibTree a b) where\n  compare (ITT l r) (ITT l' r') | l < l' = LT\n                                | l > l' = GT\n                                | otherwise = compare r r'  \n  compare (ITT _ _) _ = LT\n  compare _ (ITT _ _) = GT\n  compare (TTI l r) (TTI l' r') | l < l' = LT\n                                | l > l' = GT\n                                | otherwise = compare r r' \n  compare (TIT l r) (TIT l' r') | l < l' = LT\n                                | l > l' = GT\n                                | otherwise = compare r r' \n  compare (TTT l r) (TTT l' r') | l < l' = LT\n                                | l > l' = GT\n                                | otherwise = compare r r' \n  compare (III l r) (III l' r') | l < l' = LT\n                                | l > l' = GT\n                                | otherwise = compare r r' \n\n  compare (TTI _ _) _ = LT\n  compare _ (TTI _ _) = GT\n  compare (TIT _ _) _ = LT\n  compare _ (TIT _ _) = GT\n  compare (TTT _ _) _ = LT\n  compare _ (TTT _ _) = GT\n  compare (III _ _) _ = LT\n  compare _ (III _ _) = GT\n  compare TLeaf TLeaf = EQ\n  compare ILeaf ILeaf = EQ\n  -- whoa. GHC is smart enough to realize some of these patterns can't happen\n  -- because of the types. \n\n{-\ninstance Enum (FibTree 'Tau (A 'Tau)) where\n  toEnum _ = TLeaf\n  fromEnum _ = 0\n-}\n{-\ninstance Enum (FibTree 'Id 'Id) where\n  toEnum _ = TLeaf\n  fromEnum _ = 0\n  -}\n-- and no inhabitants types?\n--instance Enum (FibTree d b), Enum (FibTree e c) => Enum (FibTree a (b,c))\n{-\ninstance (Enum (FibTree 'Tau b), \n  Enum (FibTree 'Tau c), \n  Enum (FibTree ' b), \n  Enum (FibTree 'Id c)) => Enum (FibTree 'Tau (b,c))\n  toEnum 0 = TTI\n  toEnum \n  fromEnum \n-}\n\n--instance Enum (FibTree a (b,c)) Enum (FibTree a (b,c))=> Enum (FibTree 'Id (b,c))\n\n-- (FibTree a (b,c))\n\n\ntype TreeFun a b c d = FibTree a b -> FibTree c d\n{-\nlmap :: (forall a. FibTree a b -> FibTree (a) c) -> (forall e. FibTree e (b,d) -> FibTree e (c,d)) --  forall (a :: FibAnyon). \nlmap f (ITT l r) = (ITT (f l) r) \nlmap f (TTI l r) = (TTI (f l) r)\nlmap f (TIT l r) = (TIT (f l) r)\nlmap f (TTT l r) = (TTT (f l) r)\n-}\nlmap :: (forall a. FibTree a b -> Q (FibTree a c)) -> (FibTree e (b,d) -> Q (FibTree e (c,d)))\nlmap f (ITT l r) = fmap (\\l' -> ITT l' r) (f l)\nlmap f (TTI l r) = fmap (\\l' -> TTI l' r) (f l)\nlmap f (TIT l r) = fmap (\\l' -> TIT l' r) (f l)\nlmap f (TTT l r) = fmap (\\l' -> TTT l' r) (f l)\nlmap f (III l r) = fmap (\\l' -> III l' r) (f l)\n{-\nrmap :: (forall a. FibTree a b -> FibTree a c) -> (forall e. FibTree e (d,b) -> FibTree e (d,c)) --  forall (a :: FibAnyon). \nrmap f (ITT l r) = ITT l (f r)\nrmap f (TTI l r) = TTI l (f r)\nrmap f (TIT l r) = TIT l (f r)\nrmap f (TTT l r) = TTT l (f r)\n-}\nrmap :: (forall a. FibTree a b -> Q (FibTree a c)) -> (FibTree e (d,b) -> Q (FibTree e (d,c)))\nrmap f (ITT l r) = fmap (\\r' -> ITT l r') (f r)\nrmap f (TTI l r) = fmap (\\r' -> TTI l r') (f r)\nrmap f (TIT l r) = fmap (\\r' -> TIT l r') (f r)\nrmap f (TTT l r) = fmap (\\r' -> TTT l r') (f r)\nrmap f (III l r) = fmap (\\r' -> III l r') (f r)\n\n\nfibswap :: FibTree a (l,l') -> FibTree a (l',l)\nfibswap (ITT l r) = (ITT r l) \nfibswap (TTI l r) = (TIT r l)\nfibswap (TIT l r) = (TTI r l)\nfibswap (TTT l r) = (TTT r l)\n\neye = 0 :+ 1\n\nbraid :: FibTree a (l,r) -> Q (FibTree a (r,l))\nbraid (ITT l r) = W [(ITT r l,  cis $ 4 * pi / 5)]  -- different scalar factors for trivial and non trivial fusion\nbraid (TTT l r) = W [(TTT r l,  (cis $ - 3 * pi / 5))]\nbraid (TTI l r) = pure $ TIT r l-- exchange with trivial means nothing\nbraid (TIT l r) = pure $ TTI r l\nbraid (III l r) = pure $ III r l\n\n-- The inverse of braid\nbraid' :: FibTree a (l,r) -> Q (FibTree a (r,l))\nbraid' = star . braid\n\n-- property \n-- braid (braid' v) == v\n-- braid' (braid v) == v\n\n{-\nfibassoc :: FibTree a ((c,d),e) -> FibTree a (c,(d,e))\nfibassoc (ITT l r) = (ITT r l) \nfibassoc (TTI l r) = (TIT r l)\nfibassoc (TIT l r) = (TTI r l)\nfibassoc (TTT l r) = (TTT r l)\n-}\n-- Looks like we need more constructors for the tree\n{-\nfmove :: FibTree a (c,(d,e)) -> FibTree a ((c,d),e)\n-- fmove (ITT  a  (TTI b c)) = ITI ( TTT  a b) c\nfmove (ITT  a  (TIT b c)) = ITT ( TTI  a b) c\nfmove (ITT  a  (TTT b c)) = ITT ( TTT  a b) c\n\nfmove (TTT  a  (TTI b c)) = TTI ( TTT  a b) c\nfmove (TTT  a  (TIT b c)) = TTT ( TTI  a b) c \nfmove (TTT  a  (TTT b c)) = TTT ( TTT  a b) c\n\nfmove (TIT  a  (TTI b c)) = TTI ( TIT  a b) c\n-- fmove (TIT  a  (TIT b c)) = TTT ( III  a b) c \nfmove (TIT  a  (TTT b c)) = TTT ( TIT  a b) c\n-}\n\nfmove :: FibTree a (c,(d,e)) -> Q (FibTree a ((c,d),e))\n-- fmove (ITT  a  (TTI b c)) = pure $ ITI ( TTT  a b) c -- pure (auto (auto a b) c) -- no maybe not. The internal one isn't auto\nfmove (ITT  a  (TIT b c)) = pure $ ITT ( TTI  a b) c\nfmove (ITT  a  (TTT b c)) = pure $ ITT ( TTT  a b) c\nfmove (ITT  a  (TTI b c)) = pure $ III ( ITT  a b) c\n\n\n\nfmove (TIT  a  (TTT b c)) = pure $ TTT ( TIT  a b) c\nfmove (TIT  a  (TTI b c)) = pure $ TTI ( TIT  a b) c\nfmove (TIT  a  (TIT b c)) = pure $ TIT ( III  a b) c\n\n-- fmove (TIT  a  (TIT b c)) = TTT ( III  a b) c\n-- the nontrivial ones have all tau on the leafs and root \n-- internal I\nfmove (TTI  a  (III b c)) = pure $ TTI ( TTI  a b) c\nfmove (TTI  a  (ITT b c)) = W [(TIT ( ITT  a b) c, tau)         , (TTT ( TTT  a b) c, sqrt tau)]\n-- internal T\nfmove (TTT  a  (TTT b c)) = W [(TIT ( ITT  a b) c, sqrt tau)  ,   (TTT ( TTT  a b) c, - tau   )]\nfmove (TTT  a  (TTI b c)) = pure $ TTI ( TTT  a b) c\nfmove (TTT  a  (TIT b c)) = pure $ TTT ( TTI  a b) c \n\nfmove (III  a  (ITT b c)) = pure $ ITT ( TIT  a b) c\nfmove (III  a  (III b c)) = pure $ III ( III  a b) c\n\n\n-- largely just a tranpose of the above case.\nfmove' :: FibTree a ((c,d),e) -> Q (FibTree a (c,(d,e)))\nfmove' (ITT ( TTI  a b) c) = pure $ (ITT  a  (TIT b c))\nfmove' (ITT ( TTT  a b) c) = pure $  (ITT  a  (TTT b c))\nfmove' (ITT ( TIT  a b) c) = pure $  (III  a  (ITT b c))\n\n--fmoveq (ITT  a  (TTT b c)) = pure $ \n\nfmove' (TTI ( TTT  a b) c) = pure $ (TTT  a  (TTI b c))\nfmove' (TTI ( TTI  a b) c) = pure $ (TTI  a  (III b c))\nfmove' (TTI ( TIT  a b) c) = pure $ TIT  a  (TTI b c)\n--fmoveq (TTT  a  (TTI b c)) = pure $ TTI ( TTT  a b) c\n\n\n\n--fmoveq (TTT  a  (TIT b c)) = pure $ TTT ( TTI  a b) c \nfmove' (TIT ( ITT  a b) c) = W [(TTI  a  (ITT b c), tau)         , (TTT  a  (TTT b c) , sqrt tau)]\nfmove' (TIT ( III  a b) c ) = pure $ TIT  a  (TIT b c)\n\n\nfmove' (TTT ( TTI  a b) c ) = pure $ TTT  a  (TIT b c)\nfmove' (TTT ( TIT  a b) c ) = pure $ TIT  a  (TTT b c)\nfmove' (TTT ( TTT  a b) c) = W [(TTI  a  (ITT b c), sqrt tau)  , (TTT  a  (TTT b c),   - tau  )]\n\nfmove' (III ( III  a b) c ) = pure $ III  a  (III b c)\nfmove' (III ( ITT  a b) c ) = pure $ ITT  a  (TTI b c)\n\n--fmoveq (TIT  a  (TTI b c)) = pure $ TTI ( TIT  a b) c\n-- fmove (TIT  a  (TIT b c)) = TTT ( III  a b) c\n-- the nontrivial ones have all tau on the leafs and root \n\n-- internal I\n\n\n--fmoveq (TTI  a  (ITT b c)) = W [(TIT ( ITT  a b) c, recip tau)         , (TTT ( TTT  a b) c, recip $ sqrt tau)]\n-- internal T\n\n--fmoveq (TTT  a  (TTT b c)) = W [(TIT ( ITT  a b) c, recip $ sqrt tau)  , (TTT ( TTT  a b) c,   - recip tau  )]\n\ncheckf :: Q (FibTree Tau ((Tau, Tau),Tau))\ncheckf = simplify $ fmove' (TIT (ITT TLeaf TLeaf) TLeaf) >>= fmove\ncheckf' = simplify $ fmove' (TTT (TTT TLeaf TLeaf) TLeaf) >>= fmove\n-- checkf''' = fmove' (TIT (ITT TLeaf TLeaf) TLeaf)\n-- checkf'' = fmove' (ITT (TTT TLeaf TLeaf) TLeaf) >>= fmove\n\n-- tau**2 + tau == 1\ntau :: Complex Double\ntau =  ((sqrt 5) - 1) / 2 :+ 0 -- 0.618 :+ 0\n\n--test1 = lmap fibswap\n-- test2 = lmap $ lmap fibswap\n-- test3 = rmap fmove\n\ntype Vec1 b r = [(b, r)]\n\nsmul :: Num r => r -> Vec1 b r -> Vec1 b r\nsmul s = map (\\(b,s') -> (b, s' * s))\n\nlinapply :: Num r => (a -> Vec1 b r) -> (Vec1 a r -> Vec1 b r) -- bind\nlinapply f [] = []\nlinapply f ((b,s) : xs) = smul s (f b) ++ linapply f xs\n\n\ndTTT :: FibTree a (Tau, Tau) -> Q (FibTree a Tau)\ndTTT (TTT _ _) = pure TLeaf\ndTTT _ = mempty\n{-\ndITT :: FibTree a (Tau, Tau) -> Q (FibTree a Id)\ndTTT (TTT _ _) = pure TLeaf\ndTTT _ = mempty\n-}\ndTTI :: FibTree a (Tau, Id) -> Q (FibTree a Tau) -- A dual tree of type  'tau (tau,'tau)\ndTTI (TTI _ _) =  pure TLeaf\ndTTI _ = mempty\n\ndTTT'''' = dot (TTT TLeaf TLeaf)\n-- I could do this as a typeclass. NOPE. don't need that garbage\n\n-- I think that incompatible FibTree a' a is empty by default vs unconstructible\n-- which is better?\ndot :: FibTree a (b, c) -> FibTree a' (b, c) -> Q (FibTree a' a)\ndot x@(TTI _ _) y@(TTI _ _) | x == y = pure TLeaf\n                             | otherwise = mempty\ndot x@(TIT _ _) y@(TIT _ _) | x == y = pure TLeaf\n                             | otherwise = mempty\ndot x@(TTT _ _) y@(TTT _ _) | x == y = pure TLeaf\n                            | otherwise = mempty\ndot x@(III _ _) y@(III _ _) | x == y = pure ILeaf\n                            | otherwise = mempty\ndot x@(ITT _ _) y@(ITT _ _) | x == y = pure ILeaf\n                            | otherwise = mempty\ndot _ _ = mempty \n\ntest5 = (pure $ TTT TLeaf TLeaf) >>= dTTT\ntest6 = (pure $ ITT TLeaf TLeaf) >>= dTTT\ntest7 v = do y <- rmap dTTI v  -- wait. What the hell am I doing?\n             lmap dTTT y\ntest8 v = rmap dTTT v  >>= dTTT\n-- Building from the leaves up...?\n-- you  hve to apply the deeper stuff before the upper stuff.\n--- So this is a dual tree with TTT in the right branch. Then TTT above that.\n-- In total (T,(T,T)) -> Tleaf.\n-- maybe we need to cps it.\ndTTT' :: (Q (FibTree a Tau) -> (Complex Double)) -> (FibTree a (Tau, Tau)) -> Complex Double\ndTTT' f = f . dTTT\n\ndTTT'' :: (FibTree a Tau -> Complex Double) -> FibTree a (Tau, Tau) -> Complex Double\ndTTT'' f = undefined\n\n-- sort of similar to bind in a way. lift function to a Q function\n-- (Q FibTree a ) -> (FibTree a -> Q FibTree b)  -> Q FibTree b\ndot' :: (FibTree a b -> Complex Double) -> Q (FibTree a b) -> Complex Double\ndot' f (W v) = sum $ map (\\(e,a) -> a * (f e)) v\n\ndTTT''' = dot' . dTTT''\n\n\npentagon1 ::  FibTree a (e,(d,(c,b))) -> Q (FibTree a (((e,d),c),b))\npentagon1 v =  do \n                 v1 <- fmove v\n                 fmove v1\n\n-- type annotations not necessary. For clarity.\npentagon2 :: FibTree a (b,(c,(d,e))) -> Q (FibTree a (((b,c),d),e))\npentagon2 v = do\n                v1 :: FibTree a (b,((c,d),e)) <- rmap fmove v\n                v2 :: FibTree a ((b,(c,d)),e) <- fmove v1\n                lmap fmove v2\n\n\n\nex3 = TTT TLeaf (TTI TLeaf (ITT TLeaf TLeaf))\nex1 = TTT TLeaf (TTT TLeaf (TTT TLeaf TLeaf))\npentagon =  simplify $ ((pentagon1 ex1) - (pentagon2 ex1))\npentagon' =  simplify $ ((pentagon1 ex3) - (pentagon2 ex3))\n\nhexagon1 :: FibTree a (b,(c,d)) -> Q (FibTree a ((d,b),c))\nhexagon1 v = do\n             v1 :: FibTree a ((b,c),d) <- fmove v\n             v2 :: FibTree a (d,(b,c)) <- braid v1\n             fmove v2  \n\nhexagon2 :: FibTree a (b,(c,d)) -> Q (FibTree a ((d,b),c))\nhexagon2 v = do\n             v1 :: FibTree a (b,(d,c)) <- rmap braid v\n             v2 :: FibTree a ((b,d),c) <- fmove v1\n             lmap braid v2  \n\n\nex4 = (TTI TLeaf (ITT TLeaf TLeaf))\nex2 = (TTT TLeaf (TTT TLeaf TLeaf))\nhexagon =  simplify $ ((hexagon1 ex2) - (hexagon2 ex2))\nhexagon' =  simplify $ ((hexagon1 ex4) - (hexagon2 ex4))\n\n-- hexagon2 :: FibTree a (b,(c,d)) -> Q (FibTree a (c,(d,b)))\n\n-- quickcheck forall v, pentagon1 v == pentagon2 v\n\n\n-- test9 = test8 $ pure $ TTT (TLeaf) ()\n-- Vec1 (FibTree 'Tau l) r -> Vec1 (FibTree 'Tau l') r -> Vec1 (FibTree 'Id (l,l')) r\n\n-- linearized tensor products\n--linITT :: Num r => Vec1 (FibTree 'Tau l) r -> Vec1 (FibTree 'Tau l') r -> Vec1 (FibTree 'Id (l,l')) r -- we would like to enforce that isingany can split into a b, but thisis tough\n--linITT = [ (ITT l r, s * s')  |  (l, s) <- v1 , (r, s') <- v2   ]\n\n-- class AutoNode c a b where\n      -- prod ::  FibTree a l -> FibTree b l' -> FibTree  c (l,l')\n{-\n instance AutoProd 'Tau 'Tau 'Tau\n    prod = TTT\n instance AutoProd 'Id 'Tau 'Tau\n    prod = ITT\n-- etc.\n\n-- I can't make a fst. It extracts a skolemized object.\n-- So I do need to do complete pattern matching? No. I CAN do this... ? Not always clear I'd want to?\nfibfst :: AutoNode a e _ => FibTree a (b,c) -> FibTree e b\n\n\n\n-}\nclass TProd a b c where\n  tprod :: Vec1 (FibTree a l) r -> Vec1 (FibTree b l') r -> Vec1 (FibTree c (l,l')) r \n\n-- tprod :: AutoNode a b c => Vec1 (FibTree a l) r -> Vec1 (FibTree b l') r -> Vec1 (FibTree c (l,l')) r \n--class Index tree n  -- reference leaf by number?\n\n-- class AutoFMove tree n \n\n{-\nlinTTI :: FibTree 'Tau l -> FibTree 'Id l' -> FibTree 'Tau (l,l')\nlinTIT :: FibTree 'Id l -> FibTree 'Tau l' -> FibTree 'Tau (l,l')\nlibTTT :: FibTree 'Tau l -> FibTree 'Tau l' -> FibTree 'Tau (l,l')\n-}\n(~*) :: r -> b -> (b,r) -- **, `smul`\n(~*) = flip (,) \n\n(~+) :: a -> [a] -> [a] -- ++ instead?\n(~+) = (:)\n\ntest4 = [1 ~* 'a', 2 ~* 'b'] -- eh. What's the point.\n-- test3 = (lmap . lmap) fibswap\n--lmap (ITT l r)\n-- ^+^\n-- zero\n-- \n\n\n-- TODOS\n\n\n-- Categorical Interface\n-- lmap, rmap vs second first.\n\n{-\npullLeft (Tau,x) = (Tau,x)\npullLeft (Id,x) = (Id,x)\npullLeft (a,b) = fmove ((a',c),b) where (a',c) = pullLeft a  \n-- ((a,b),c) = (, (b,c)) where (a',d) = pullLeft a\n-}\n{-\ntype family FMove' a where\n  FMove' ((a,b),c)  = (a,(b,c))\n\ntype family PullLeft a where\n  PullLeft Tau = Tau\n  PullLeft Id = Id\n  PullLeft (Tau,b) = (Tau,b)\n  PullLeft (Id,b) =  (Id,b)\n  PullLeft ((a,b),c)  = FMove' (PullLeft (a,b), c)\n\n-- Auto F Moves. / auto braid.\n\npullLeft :: (PullLeft (b,c) ~ (b',c')) => FibTree a (b,c) -> Q (FibTree a (b',c'))\npullLeft x@(TTT TLeaf _) = pure x\npullLeft (TTT l@(TTT _ _ ) r) =  do \n                      l' <- pullLeft l\n                      fmove' (TTT l' r)\n-}\nclass PullLeft a b | a -> b where -- | a -> b functional dependency causes errors?\n  pullLeft :: FibTree c a -> Q (FibTree c b)\n\ninstance PullLeft (Tau,c) (Tau,c) where\n  pullLeft = pure\n\ninstance PullLeft (Id,c) (Id,c) where\n  pullLeft = pure\n\n\ninstance PullLeft Tau Tau where\n  pullLeft = pure\n\ninstance PullLeft Id Id where\n  pullLeft = pure\n\ninstance (PullLeft (a,b) (a',b'), r ~ (a',(b',c))) => PullLeft ((a, b),c) r where\n  pullLeft t = do \n           t' <- lmap pullLeft t\n           fmove' t'\n{-\ninstance (PullLeft a a', r ~ (a',(b,c))) => PullLeft (a, (b,c)) r where\n  pullLeft t = lmap pullLeft t\n-}\n{-\ninstance (PullLeft a a', PullLeft (a',b) (a'',b''), ) => PullLeft (a,b) r where\n  pullLeft = lmap pullLeft t\n-}\n\n{-  pullLeft (TTT l r) =  do \n                        l' <- pullLeft l\n                        fmove' (TTT l' r)\n-}\n\nclass PullRight a b | a -> b where -- | a -> b functional dependency causes errors?\n  pullRight :: FibTree c a -> Q (FibTree c b)\n{-\ninstance (PullRight a a', r ~ ((b,c),a')) => PullRight ((b,c),a) r where\n  pullRight t = rmap pullRight t\n-}\ninstance PullRight Tau Tau where\n  pullRight = pure\n\ninstance PullRight Id Id where\n  pullRight = pure\n\n\ninstance PullRight (c,Tau) (c,Tau) where\n  pullRight = pure\n\ninstance PullRight (c,Id) (c,Id) where\n  pullRight = pure\n\ninstance (PullRight (a,b) (a',b'), r ~ ((c,a'),b')) => PullRight (c,(a, b)) r where\n  pullRight t = do \n           t' <- rmap pullRight t\n           fmove t'\n\n\n\ntype family Count a where\n  Count Tau = 1\n  Count Id = 1\n  Count (a,b) = (Count a) + (Count b)\n\ntype family LeftCount a where\n  LeftCount (a,b) = Count a\n\n-- The version without the explicit ordering supplied.\nclass LCA n a b c d | n a c -> b d where\n  lcamap :: (forall r. FibTree r b -> Q (FibTree r c)) -> (FibTree e a) -> Q (FibTree e d)\n{-\nlcamapP :: LCA n a b c d => Proxy n ->  (forall r. FibTree r b -> Q (FibTree r c)) -> (FibTree e a) -> Q (FibTree e d)\nlcamapP _ f x = lcamap f x\n-}\ninstance (lc ~ (LeftCount a), \n          gte ~ (CmpNat lc n),\n         LCA' n gte a b c d) => LCA n a b c d where\n  lcamap f x = lcamap' @n @gte f x\n\nclass LCA' n gte a b c d | n gte a c -> b d where\n  lcamap' :: (forall r. FibTree r b -> Q (FibTree r c)) -> (FibTree e a) -> Q (FibTree e d)\n\n-- we find b at the lca and pass it back up. c gets passed all the way down, d gets computed by rebuilding out of c.\n-- a drives the search.\ninstance (n' ~ (n - Count l), -- we're searching in the right subtree. Subtract the leaf number in the left subtree\n        lc ~ (LeftCount r), -- dip one left down to order which way we have to go next\n        gte ~ (CmpNat lc n'), -- Do we go left, right or havce we arrived in the next layer?\n        LCA' n' gte r b c d',  -- recurive call\n        d ~ (l,d') -- reconstruct total return type from recurive return type. left tree is unaffected by lcamapping\n        ) => LCA' n 'LT (l,r) b c d where\n    lcamap' f x = rmap (lcamap' @n' @gte f) x\n\ninstance (lc ~ (LeftCount l),\n          gte ~ (CmpNat lc n),\n          LCA' n gte l b c d',\n          d ~ (d',r)\n          ) => LCA' n 'GT (l,r) b c d where\n    lcamap' f x = lmap (lcamap' @n @gte f) x\n\ninstance (b ~ a, d ~ c) => LCA' n 'EQ a b c d where\n  lcamap' f x = f x\n\n\n\nclass LeafMap n gte a b c d | n gte a c -> b d where\n  leafmap :: (forall r. FibTree r b -> Q (FibTree r c)) -> (FibTree e a) -> Q (FibTree e d)\n\ninstance (n' ~ (n - Count l), -- we're searching in the right subtree. Subtract the leaf number in the left subtree\n        lc ~ (LeftCount r), -- dip one left down to order which way we have to go next\n        gte ~ (CmpNat lc n'), -- Do we go left, right or havce we arrived in the next layer?\n        LeafMap n' gte r b c d',  -- recurive call\n        d ~ (l,d') -- reconstruct total return type from recurive return type. left tree is unaffected by lcamapping\n        ) => LeafMap n 'LT (l,r) b c d where\n    leafmap f x = rmap (leafmap @n' @gte f) x\n\ninstance (lc ~ (LeftCount l),\n          gte ~ (CmpNat lc n),\n          LeafMap n gte l b c d',\n          d ~ (d',r)\n          ) => LeafMap n 'GT (l,r) b c d where\n    leafmap f x = lmap (leafmap @n @gte f) x\n\n-- In the equals case, we now continue onward.\ninstance (lc ~ (LeftCount l),\n          gte ~ (CmpNat lc n),\n          LeafMap n gte l b c d',\n          d ~ (d',r)\n          ) => LeafMap n 'EQ (l,r) b c d where\n    leafmap f x = lmap (leafmap @n @gte f) x\n\n-- base case\ninstance (b ~ Tau, d ~ c) => LeafMap 1 'EQ Tau b c d where\n  leafmap f x = f x\n\ninstance (b ~ Id, d ~ c) => LeafMap 1 'EQ Id b c d where\n  leafmap f x = f x\n\n-- split\n-- leafmap @3 (const (TTT TLeaf TLeaf)) \n-- need one last arbitrary left or right fmove to put the two on the same stalk\n-- neighbormap :: (LCA n a (l,r) (l',r') d, PullRight l (l',x), PullLeft r (y,r') ) => (FibTree.  -> Q FibTree) -> FibTree \n\n-- I need this to also work for (Tau, Tau)\n-- (Tau, yada yada)\n-- I.e. I need to do different things depending on \n\n\n-- Jesus. What a shitshow. But I don't see how to do better.\n-- a is starting tree\n-- b is extracted part\n-- c is transformed b\n-- d is recoustrcted a replacing b with c and rearranging.\nclass NeighborMap a b c d | a c -> b d where\n  nmap :: (forall r. FibTree r b -> Q (FibTree r c)) -> FibTree e a -> Q (FibTree e d)\n\ninstance NeighborMap ((l,x),(y,r)) (x,y) c ((l,c),r) where\n   nmap f x = do\n              x'  <- fmove x -- (((l',x),y),r')\n              x'' <- lmap fmove' x' -- ((l',(x,y)),r')\n              lmap (rmap f) x''\ninstance NeighborMap (Tau, (y,r)) (Tau, y)  c  (c,r) where\n   nmap f x = fmove x >>= lmap f\ninstance NeighborMap (Id, (y,r)) (Id, y) c (c,r) where\n   nmap f x = fmove x >>= lmap f\ninstance NeighborMap ((l,x), Tau) (x,Tau) c (l,c) where\n   nmap f x = fmove' x >>= rmap f\ninstance NeighborMap ((l,x), Id) (x,Id) c  (l,c) where\n   nmap f x = fmove' x >>= rmap f\ninstance NeighborMap (Tau, Tau) (Tau,Tau) c  c where\n   nmap f x = f x \ninstance NeighborMap (Id, Id) (Id,Id) c  c where\n   nmap f x = f x \ninstance NeighborMap (Tau, Id) (Tau,Id) c  c where\n   nmap f x = f x \ninstance NeighborMap (Id, Tau) (Id,Tau) c  c where\n   nmap f x = f x \n\n\nneighbormap :: forall n a b c d l l' r' x y e r z. (LCA n a b c d,\n   b ~ (l,r),\n   c ~ ((l',z),r'), \n   PullRight l (l',x),\n   PullLeft r (y,r')) => \n   (forall r. FibTree r (x,y) -> Q (FibTree r z)) -> FibTree e a -> Q (FibTree e d)\nneighbormap f z = lcamap @n @a @b @c @d (helper f) z\n\nhelper ::  (c ~ ((l',z),r'), \n   PullRight l (l',x),\n   PullLeft r (y,r')) => (forall r. FibTree r (x,y) -> Q (FibTree r z)) -> FibTree e (l,r) -> Q (FibTree e c)\nhelper f x = do\n            x' <- rootneighbor x\n            lmap (rmap f) x'                          \n\nrootneighbor :: (PullRight l (l',x), PullLeft r (y,r')) => FibTree e (l,r) -> Q (FibTree e ((l',(x,y)),r'))\nrootneighbor x = do \n                x' <- lmap pullRight x\n                x'' <- rmap pullLeft x' -- ((l',x),(y,r'))\n                x''' <- fmove x'' -- (((l',x),y),r')\n                lmap fmove' x''' -- ((l',(x,y)),r')\n\nneighbormap' :: forall n a b c d l l' r r' x y e z b'. (LCA n a b c d,\n   b ~ (l,r),\n   -- c ~ c',\n   -- c ~ ((l',z),r'), \n   PullRight l l',\n   PullLeft r r',\n   NeighborMap (l',r') b' z c) => \n   (forall r. FibTree r b' -> Q (FibTree r z)) -> FibTree e a -> Q (FibTree e d)\nneighbormap' f z = lcamap @n @a @b @c @d (\\x -> do\n                                          x'  <- lmap pullRight x\n                                          x'' <- rmap pullLeft x' \n                                          nmap f x'') z\n\nneighbormap'' :: forall n a b' z d c l l' r r' x y e b. (LCA n a b c d,\n   b ~ (l,r),\n   -- c ~ c',\n   -- c ~ ((l',z),r'), \n   PullRight l l',\n   PullLeft r r',\n   NeighborMap (l',r') b' z c) => \n   (forall r. FibTree r b' -> Q (FibTree r z)) -> FibTree e a -> Q (FibTree e d)\nneighbormap'' f z = lcamap @n @a @b @c @d (\\x -> do\n                                          x'  <- lmap pullRight x\n                                          x'' <- rmap pullLeft x' \n                                          nmap f x'') z\n\n\nt1 = neighbormap' @2 braid (TTT (TTI TLeaf ILeaf) (TTT TLeaf TLeaf)) \nt2 = neighbormap' @1 braid (TTT (TTI TLeaf ILeaf) (TTT TLeaf TLeaf)) \nt3 = neighbormap' @2 braid (TTT (TTT (TTT TLeaf TLeaf) TLeaf) (TTT TLeaf TLeaf)) \n\n                                      {-\nneighbormap p f z = let helper (x :: FibTree _ (l,r)) = do\n                                x' <- rootneighbor x\n                                lmap (rmap f) x'\n                    in\n                    lcamap helper z\n                    -}\n{-  lcamap \n((\\x -> do\n                                x' <- rootneighbor x\n                                lmap (rmap f) x'\n                                ) :: (forall s. FibTree s (l,r) -> Q (FibTree s c))) z\n-}\n\n{-(\\x -> do \n                            x' <- lmap pullRight x\n                            x'' <- rmap pullLeft x' -- ((l',x),(y,r'))\n                            x''' <- fmove x'' -- (((l',x),y),r')\n                            x4 <- lmap fmove' x''' -- ((l',(x,y)),r')\n                            lmap (lmap f) x4 -- ((l',z),r')\n                            ) z\n-}                         \n{-\n-- neighbormap f z = lcamap @n (\\x -> do \n                            x' <- lmap pullRight x\n                            x'' <- rmap pullLeft x'\n                            x''' <- fmove x''\n                            lmap? f x'''   ) z\n-}\n{-\nabraid :: forall n a b c d l l' r' x y e r z b'. (LCA n a b c d,\n   b ~ (l,r),\n   -- c ~ c',\n   -- c ~ ((l',z),r'), \n   PullRight l l',\n   PullLeft r r',\n   NeighborMap (l',r') (x,y) (y,x) c) => Q (FibTree e a) -> Q (FibTree e d)\n\n\n   -}\n\nabraid :: forall n a b c d l l' r r' x y e z b'. (LCA n a b c d,\n   b ~ (l,r),\n   -- c ~ c',\n   -- c ~ ((l',z),r'), \n   PullRight l l',\n   PullLeft r r',\n   NeighborMap (l',r') (x,y) (y,x) c) => \n   Q (FibTree e a) -> Q (FibTree e d)\nabraid x = x >>= (neighbormap' @n @a @b @c @d @l @l' @r @r' @x @y @e @(y,x) @(x,y)) braid\n\nabraid' :: forall n a b c d l l' r r' x y e z b'. (LCA n a b c d,\n   b ~ (l,r),\n   -- c ~ c',\n   -- c ~ ((l',z),r'), \n   PullRight l l',\n   PullLeft r r',\n   NeighborMap (l',r') (x,y) (y,x) c) => \n   Q (FibTree e a) -> Q (FibTree e d)\nabraid' x = x >>= (neighbormap' @n @a @b @c @d @l @l' @r @r' @x @y @e @(y,x) @(x,y)) braid'\n\n\n\n{-\nabraid\n  :: forall n a b c d l l' r r' x y e z b'. (LCA n a (l, r) c d, PullRight l l', PullLeft r r',\n      NeighborMap (l', r') (x, y) (y, x) c) =>\n     (FibTree e a) -> Q (FibTree e d)\nabraid x = neighbormap' @n @a @(l,r) @c @d @l @l' @r @r' braid x\n-}\n{-\nt4 = abraid @2 $\n     abraid @4 $\n     abraid @3 $\n     pure (TTT (TTT (TTT TLeaf TLeaf) TLeaf) (TTT TLeaf TLeaf)) \n-}\n{-\nndot' :: forall n a b c d l l' r r' x y e z b' a'. (LCA n a b c d,\n   b ~ (l,r),\n   -- c ~ c',\n   -- c ~ ((l',z),r'), \n   PullRight l l',\n   PullLeft r r',\n   NeighborMap (l',r') (x,y) a' c) => \n   FibTree a' (x,y) -> FibTree e a -> Q (FibTree e d)\n   -}\n-- ndot' x = (neighbormap' @n @a @b @c @d @l @l' @r @r' @x @y @e @a' @(x,y)) (dot' x)\n\nndot :: forall n a l r c d l' r' x y a' e. (LCA n a (l, r) c d, PullRight l l', PullLeft r r',\n      NeighborMap (l', r') (x, y) a' c) =>\n     FibTree a' (x, y) -> FibTree e a -> Q (FibTree e d) \nndot x = neighbormap' @n @a @(l,r) (dot x)\n\n-- This a b c d pattern is something like a lens. We are replacing \n-- piece of b with c which turns a into d. b is piece of a.\n-- s t a b\n\n-- quantified constraints\n--  (forall b' c'. (g a b' c' d , f b' b c c') => Compose f g a b c d\n\n\n\n\n\n-- (forall r. FibTree r b' -> Q (FibTree r z)) ->\n{-\nabraid' :: forall n a b c d l l' r r' x y e b'. (LCA n a b c d,\n   b ~ (l,r),\n   -- c ~ c',\n   -- c ~ ((l',z),r'), \n   PullRight l l',\n   PullLeft r r',\n   NeighborMap (l',r') (x,y) (y,x) c) => \n   FibTree e a -> Q (FibTree e d)\nabraid' = (neighbormap'' @n @a @(x,y) @(y,x) @d) braid\n-}\n\n\n\n{-\nabraid' :: forall n a b c d l l' r r' x y e z b'. (LCA n a b c d,\n   b ~ (l,r),\n   -- c ~ c',\n   -- c ~ ((l',z),r'), \n   PullRight l l',\n   PullLeft r r',\n   NeighborMap (l',r') (x,y) (y,x) c) => \n   FibTree e a -> Q (FibTree e d)\nabraid' = (neighbormap' @n @a @b @c @d @l @l' @r @r' @x @y @e @(y,x) @(x,y)) braid'\n-}\n\n\n\n{-\nabraid :: (LCA n a (l1, r) c d, PullRight l1 l'1, PullLeft r r',\n      NeighborMap (l'1, r') (l2, l'2) (l'2, l2) c) =>\n     FibTree e a -> Q (FibTree e d)\nabraid = neighbormap' braid\n-}\n-- autobraid = neighbormap braid\n-- autodot x = neighbormap (dot x)\n\n\n-- Build state monad to carry along the vector.\n-- should be able to do in applicative style, since data does not change structre of computation\n\n-- auto braid\n-- find least common ancestor\n-- pullLeft, and pullRight\n-- then braid\n\n\n-- stateful \n-- Pretty Print tree\n\n\n\n\n\n-- Operators.\nnewtype FibOp a b = FibOp (forall c. FibTree c a -> Q (FibTree c b))\ntype FibOp' c a b = FibTree c a -> Q (FibTree c b)\n\ninstance Category FibOp where\n  id = FibOp pure\n  (FibOp f) . (FibOp g) = FibOp (f <=< g) \n{-\ninstance Arrow FibOp where\n  arr = error \"No. No arr.\"\n  (***) = \n-}\n{-\nclass Monoidal k where\n  (***) :: k a b -> k c d -> k (a,c) (b,d)\n-}\ntensor :: Num r => (b -> c -> a) -> W r b -> W r c -> W r a\ntensor f (W xs) (W ys) =  W [ ( f x y , xc * yc ) | (x, xc) <- xs,  (y,yc) <- ys]\n\n-- tensor :: Num r => (b -> c -> a) -> b -> c -> W r a\n-- fg f g (TTT l r) = tensor TTT (f l) (g r) \n\n{-\ninstance Monoidal FibOp where\n  (***) :: FibOp a b -> FibOp c d -> FibOp (a,c) (b,d)\n  (FibOp f) *** (FibOp g) = FibOp fg where\n                               -- fg ::  (a,c) (b,d)\n                               fg :: FibTree e (a,c) -> Q (FibTree e (b,d))\n                               fg (TTT l r) = tensor TTT (f l) (g r) \n                               -- fg (ITT l r) = FibOp $ tensor ITT (f l) (g r) \n                               -- fg (TIT l r) = FibOp $ tensor TIT (f l) (g r) \n-}\n-- try to remove the issue of being in a instance. Which is kind of silly anyhow\n{-\n(****) :: FibOp' e a b -> FibOp' e c d -> FibOp' e (a,c) (b,d)\nf **** g = fg where\n                   -- fg ::  (a,c) (b,d)\n                 fg :: FibTree e (a,c) -> Q (FibTree e (b,d))\n                 fg (TTT l r) = tensor TTT (f l) (g r)\n                 fg (ITT l r) = tensor ITT (f l) (g r)\n-}\n(***) :: (forall e. FibOp' e a b) -> (forall e'. FibOp' e' c d)  -> FibOp' e'' (a,c) (b,d)\n(***) f g (TTT l r) = tensor TTT (f l) (g r)\n(***) f g (ITT l r) = tensor ITT (f l) (g r)\n(***) f g (TIT l r) = tensor TIT (f l) (g r)\n\nfirst = lmap\nsecond = rmap\n-- braid\n-- fmove\n\n-- cup, cap? dot'\n\n\n-- Is the problem that I'd trying to pattern match on kind of the output?\n -- densification\n\n-- Quickcheck props\n\n-- implement qubit abtraction\n\n-- Did I fall into a way to make end, co-end work as einstein notation?6\n-- The bounded meaning of forall and exists in the GADT context\n\nmain :: IO ()\nmain = mymain \n--return ()\n\n\n\n", "meta": {"hexsha": "c89745570cab66eebe8da61cbaff4fd8369c58c2", "size": 33545, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "philzook58/fib-anyon", "max_stars_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-01-14T10:48:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T08:35:00.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "philzook58/fib-anyon", "max_issues_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "philzook58/fib-anyon", "max_forks_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-11-15T07:42:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-02T15:15:28.000Z", "avg_line_length": 31.9172216936, "max_line_length": 182, "alphanum_fraction": 0.524966463, "num_tokens": 12625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4324708127429243}}
{"text": "{-# LANGUAGE BangPatterns,\n             ScopedTypeVariables,\n             RecordWildCards,\n             FlexibleContexts,\n             TypeFamilies,\n             GeneralizedNewtypeDeriving #-}\n\n\nmodule AI.HsANN.ComplexNetwork\n    (\n    -- * Types\n      ComplexNetwork(..)\n    , ActivationFunction\n    , ActivationFunctionDerivative\n    , Sample\n    , Samples\n    , (-->)\n\n    -- * Creating a neural network\n    , createComplexNetwork\n    , fromWeightMatrices\n\n    -- * Computing a neural network's output\n    , output\n    , sigmoid\n    , sigmoid'\n    , complexSigmoid\n    , complexSigmoid'\n    , randComplex\n\n    -- * Training a neural network\n    , trainUntil\n    , trainNTimes\n    , trainUntilErrorBelow\n    , quadError\n\n    -- * Loading and saving a neural network\n    , loadComplexNetwork\n    , saveComplexNetwork\n    ) where\n\nimport Codec.Compression.Zlib     (compress, decompress)\nimport Data.Binary                (Binary(..), encode, decode)\nimport Data.List                  (foldl')\nimport Foreign.Storable           (Storable)\nimport qualified Data.ByteString.Lazy  as B\nimport qualified Data.Vector           as V\nimport qualified Data.Complex as C\nimport Debug.Trace\n\nimport System.Random.MWC\nimport Numeric.LinearAlgebra\nimport Data.Functor ((<$>))\n\n-- | Our feed-forward neural network type. Note the 'Binary' instance, which means you can use\n--   'encode' and 'decode' in case you need to serialize your neural nets somewhere else than\n--   in a file (e.g over the network)\nnewtype ComplexNetwork a = ComplexNetwork\n                 { matrices   :: V.Vector (Matrix a) -- ^ the weight matrices\n                 } deriving Show\n\ninstance (Element a, Binary a) => Binary (ComplexNetwork a) where\n  put (ComplexNetwork ms) = put . V.toList $ ms\n  get = (ComplexNetwork . V.fromList) `fmap` get\n\n\n--instance (Complex a, Variate a) => Variate (Complex a) where\n--\tuniform g = uniform g :+ uniform g\n--\tuniformR (x,y) g = uniformR (x,y) g :+ uniformR (x,y) g\n\n\n\n\n-- | The type of an activation function, mostly used for clarity in signatures\ntype ActivationFunction a = a -> a\n\n-- | The type of an activation function's derivative, mostly used for clarity in signatures\ntype ActivationFunctionDerivative a = a -> a\n\n\n--\n\nrandComplex :: (Variate a, Num a) => IO(Complex a)\nrandComplex = withSystemRandom . asGenST $ \\gen -> do\n  r <- uniformR (-1,1) gen\n  i <- uniformR (-1,1) gen\n  return (r :+ i)\n\nrandComplexList :: (Variate a, Num a) => Int -> IO([Complex a])\nrandComplexList 0 = return []\nrandComplexList n = do\n  c <- randComplex\n  lst <- randComplexList (n-1)\n  return (c : lst)\n\nrandComplexMatrix :: (Variate a, Storable a, Num a) => (Int,Int) -> IO(Matrix (Complex a))\nrandComplexMatrix (rows,cols) = do\n  lst <- randComplexList (rows*cols)\n  return (reshape cols $ Numeric.LinearAlgebra.fromList lst)\n\n-- | The following creates a neural network with 'n' inputs and if 'l' is [n1, n2, ...]\n--   the net will have n1 neurons on the first layer, n2 neurons on the second, and so on\n--   ending with k neurons on the output layer, with random weight matrices as a courtesy of\n-- 'System.Random.MWC.uniformR'.\n-- > createComplexNetwork n l k\ncreateComplexNetwork :: (Variate a, Storable a, Num a) => Int -> [Int] -> Int -> IO (ComplexNetwork (Complex a))\ncreateComplexNetwork nInputs hiddens nOutputs =\n  fmap ComplexNetwork $ go dimensions V.empty\n  where\n        go [] !ms         = return ms\n        go ((!n,!m):ds) ms = do\n          !mat <- randComplexMatrix (n,m)\n          go ds (ms `V.snoc` mat)\n        dimensions      = zip (hiddens ++ [nOutputs]) $\n                              (nInputs : hiddens)\n{-# INLINE createComplexNetwork #-}\n\n\n\n-- | Creates a neural network with exactly the weight matrices given as input here.\n--   We don't check that the numbers of rows/columns are compatible, etc.\nfromWeightMatrices :: Storable a => V.Vector (Matrix (Complex a)) -> ComplexNetwork (Complex a)\nfromWeightMatrices ws = ComplexNetwork ws\n{-# INLINE fromWeightMatrices #-}\n\n-- The `join [input, 1]' trick  below is a courtesy of Alberto Ruiz\n-- <http://dis.um.es/~alberto/>. Per his words:\n--\n-- \"The idea is that the constant input in the first layer can be automatically transferred to the following layers\n-- by the learning algorithm (by setting the weights of a neuron to 1,0,0,0,...). This allows for a simpler\n-- implementation and in my experiments those networks are able to easily solve non linearly separable problems.\"\n\n\n--without the trick (of constant input)\n\noutput :: (Floating (Vector a), Product a, Storable a, Num (Vector a)) => ComplexNetwork a -> ActivationFunction a -> Vector a -> Vector a\noutput (ComplexNetwork{..}) act input = V.foldl' f input matrices\n  where f !inp m = mapVector act $ m <> inp\n{-# INLINE output #-}\n\n-- | Computes and keeps the output of all the layers of the neural network with the given activation function\noutputs :: (Floating (Vector a), Product a, Storable a, Num (Vector a)) => ComplexNetwork a -> ActivationFunction a -> Vector a -> V.Vector (Vector a)\noutputs (ComplexNetwork{..}) act input = V.scanl f input matrices\n  where f !inp m = mapVector act $ m <> inp\n{-# INLINE outputs #-}\n\n\nconju (x:+y) = x:+(-y)\n\ndeltas :: (Floating b, Floating (Vector a), Floating a, Product a, Storable a, Num (Vector a), Container Vector a, a ~ Complex b) => ComplexNetwork a -> ActivationFunctionDerivative a -> V.Vector (Vector a) -> Vector a -> V.Vector (Matrix a)\ndeltas (ComplexNetwork{..}) act' os expected = V.zipWith outer (V.tail ds) (V.init (V.map (mapVector conju) os))\n  where !dl = (V.last os - expected) * (deriv $ mapVector conju (V.last os)) -- = (out_last - target)*(f'(netin_last)) = dev_last * deriv(out_last) = partial_last\n        !ds = V.scanr f dl (V.zip os matrices) -- generates dev_i\n        f (!o, m) !del = deriv o * ((ctrans m) <> del) -- dev_k = deriv(out_k)*dev_k = deriv(out_k)*(WEIGHTS <> partial_k+1)\n        deriv = mapVector act'\n{-# INLINE deltas #-}\n\nupdateComplexNetwork :: (Floating b, Floating (Vector a), Floating a, Product a, Storable a, Num (Vector a), Container Vector a, a ~ Complex b) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> ComplexNetwork a -> Sample a -> ComplexNetwork a\nupdateComplexNetwork alpha act act' n@(ComplexNetwork{..}) (input, expectedOutput) = ComplexNetwork $ V.zipWith (+) matrices corr\n    where !xs = outputs n act input\n          !ds = deltas n act' xs expectedOutput\n          !corr = V.map (scale (-alpha)) ds\n{-# INLINE updateComplexNetwork #-}\n\n-- | Input vector and expected output vector\ntype Sample a = (Vector a, Vector a)\n\n-- | List of 'Sample's\ntype Samples a = [Sample a]\n\n-- | Handy operator to describe your learning set, avoiding unnecessary parentheses. It's just a synonym for '(,)'.\n--   Generally you'll load your learning set from a file, a database or something like that, but it can be nice for\n--   quickly playing with hnn or for simple problems where you manually specify your learning set.\n--   That is, instead of writing:\n--\n-- > samples :: Samples Double\n-- > samples = [ (fromList [0, 0], fromList [0])\n-- >           , (fromList [0, 1], fromList [1])\n-- >           , (fromList [1, 0], fromList [1])\n-- >           , (fromList [1, 1], fromList [0])\n-- >           ]\n--\n--   You can write:\n--\n-- > samples :: Samples Double\n-- > samples = [ fromList [0, 0] --> fromList [0]\n-- >           , fromList [0, 1] --> fromList [1]\n-- >           , fromList [1, 0] --> fromList [1]\n-- >           , fromList [1, 1] --> fromList [0]\n-- >           ]\n(-->) :: Vector a -> Vector a -> Sample a\n(-->) = (,)\n\nbackpropOnce :: (Floating (Vector a), Floating b, Floating a, Product a, Num (Vector a), Container Vector a, a ~ Complex b) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> ComplexNetwork a -> Samples a -> ComplexNetwork a\nbackpropOnce rate act act' n samples = foldl' (updateComplexNetwork rate act act') n samples\n{-# INLINE backpropOnce #-}\n\n-- | Generic training function.\n--\n-- The first argument is a predicate that will tell the backpropagation algorithm when to stop.\n-- The first argument to the predicate is the epoch, i.e the number of times the backprop has been\n-- executed on the samples. The second argument is /the current network/, and the third is the list of samples.\n-- You can thus combine these arguments to create your own criterion.\n--\n-- For example, if you want to stop learning either when the network's quadratic error on the samples,\n-- using the tanh function, is below 0.01, or after 1000 epochs, whichever comes first, you could\n-- use the following predicate:\n--\n-- > pred epochs net samples = if epochs == 1000 then True else quadError tanh net samples < 0.01\n--\n-- You could even use 'Debug.Trace.trace' to print the error, to see how the error evolves while it's learning,\n-- or redirect this to a file from your shell in order to generate a pretty graphics and what not.\n--\n-- The second argument (after the predicate) is the learning rate. Then come the activation function you want,\n-- its derivative, the initial neural network, and your training set.\n-- Note that we provide 'trainNTimes' and 'trainUntilErrorBelow' for common use cases.\ntrainUntil :: (Floating (Vector a), Floating b, Floating a, Product a, Num (Vector a), Container Vector a, a ~ Complex b) => (Int -> ComplexNetwork a -> Samples a -> Bool) -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> ComplexNetwork a -> Samples a -> ComplexNetwork a\ntrainUntil pr learningRate act act' net samples = go net 0\n  where go n !k | pr k n samples = n\n                | otherwise      = case backpropOnce learningRate act act' n samples of\n                                    n' -> go n' (k+1)\n{-# INLINE trainUntil #-}\n\n-- | Trains the neural network with backpropagation the number of times specified by the 'Int' argument,\n-- using the given learning rate (second argument).\ntrainNTimes :: (Floating (Vector a), Floating b, Floating a, Product a, Num (Vector a), Container Vector a, a ~ Complex b) => Int -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> ComplexNetwork a -> Samples a -> ComplexNetwork a\ntrainNTimes n = trainUntil (\\k _ _ -> k > n)\n{-# INLINE trainNTimes #-}\n\n-- | Quadratic error on the given training set using the given activation function. Useful to create\n-- your own predicates for 'trainUntil'.\nquadError :: (Floating (Vector a), Floating b, Floating a, Num (Vector a), Num (RealOf a), Product a, a ~ Complex b) => ActivationFunction a -> ComplexNetwork a -> Samples a -> RealOf a\nquadError act net samples = foldl' (\\err (inp, out) -> err + (norm2 $ output net act inp - out)) 0 samples\n{-# INLINE quadError #-}\n\n-- | Trains the neural network until the quadratic error ('quadError') comes below the given value (first argument),\n-- using the given learning rate (second argument).\n--\n-- /Note/: this can loop pretty much forever when you're using a bad architecture for the problem, or unappropriate activation\n-- functions.\ntrainUntilErrorBelow :: (Floating (Vector a), Floating b, Floating a, Product a, Num (Vector a), Ord a, Container Vector a, Num (RealOf a), a ~ RealOf a, Show a, a ~ Complex b) => a -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> ComplexNetwork a -> Samples a -> ComplexNetwork a\ntrainUntilErrorBelow x rate act = trainUntil (\\_ n s -> quadError act n s < x) rate act\n{-# INLINE trainUntilErrorBelow #-}\n\n-- | The sigmoid function:  1 / (1 + exp (-x))\nsigmoid :: Floating a => a -> a\nsigmoid !x = 1 / (1 + exp (-x))\n{-# INLINE sigmoid #-}\n\n-- | Derivative of the sigmoid function: sigmoid x * (1 - sigmoid x)\nsigmoid' :: Floating a => a -> a\nsigmoid' !x = case sigmoid x of\n  s -> s * (1 - s)\n{-# INLINE sigmoid' #-}\n\n\ncomplexSigmoid :: Floating a => Complex a -> Complex a\ncomplexSigmoid (x :+ y) = (sigmoid x) :+ (sigmoid y)\n\ncomplexSigmoid' :: Floating a => Complex a -> Complex a\ncomplexSigmoid' (x :+ y) = (sigmoid' x) :+ (sigmoid' y)\n\n-- | Loading a neural network from a file (uses zlib compression on top of serialization using the binary package).\n--   Will throw an exception if the file isn't there.\nloadComplexNetwork :: (Storable a, Element a, Binary a) => FilePath -> IO (ComplexNetwork a)\nloadComplexNetwork fp = decode . decompress <$> B.readFile fp\n{-# INLINE loadComplexNetwork #-}\n\n-- | Saving a neural network to a file (uses zlib compression on top of serialization using the binary package).\nsaveComplexNetwork :: (Storable a, Element a, Binary a) => FilePath -> ComplexNetwork a -> IO ()\nsaveComplexNetwork fp = B.writeFile fp . compress . encode\n{-# INLINE saveComplexNetwork #-}\n", "meta": {"hexsha": "e1908aeb7515103cf2ef92b30ce4359419c64475", "size": 12602, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AI/HsANN/ComplexNetwork.hs", "max_stars_repo_name": "EditResearch/HsANN", "max_stars_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AI/HsANN/ComplexNetwork.hs", "max_issues_repo_name": "EditResearch/HsANN", "max_issues_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AI/HsANN/ComplexNetwork.hs", "max_forks_repo_name": "EditResearch/HsANN", "max_forks_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1611721612, "max_line_length": 297, "alphanum_fraction": 0.6739406443, "num_tokens": 3215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4323954961967681}}
{"text": "module Deconvolution where\n\nimport           Control.Monad             as M\nimport           Control.Monad.Parallel    as MP\nimport           Data.Array.Repa           as R\nimport           Data.Binary\nimport           Data.Complex\nimport           Data.List                 as L\nimport           DFT.Plan\nimport           Filter.Utils\nimport           FokkerPlanck.DomainChange\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Graphics.Gnuplot.Simple\nimport           Image.IO\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Types\nimport           Utils.Array\n\nmain = do\n  args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:theta0FreqsStr:thetaFreqsStr:scale0FreqsStr:scaleFreqsStr:initDistStr:histFilePath:alphaStr:pinwheelFlagStr:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      theta0Freq = read theta0FreqsStr :: Double\n      theta0Freqs = [-theta0Freq .. theta0Freq]\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      initDist = read initDistStr :: [R2S1RPPoint]\n      scale0Freq = read scale0FreqsStr :: Double\n      scaleFreq = read scaleFreqsStr :: Double\n      scale0Freqs = [-scale0Freq .. scale0Freq]\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      alpha = read alphaStr :: Double\n      pinwheelFlag = read pinwheelFlagStr :: Bool\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/Deconvolution\"\n      (R2S1RPPoint (_, _, _, s)) = L.head initDist\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  radialArr <-\n    if flag\n      then R.map magnitude . getNormalizedHistogramArr <$>\n           decodeFile histFilePath\n      else do\n        putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n        solveMonteCarloR2Z2T0S0Radial\n          numThread\n          numTrail\n          maxTrail\n          numPoint\n          numPoint\n          thetaSigma\n          scaleSigma\n          maxScale\n          tao\n          theta0Freqs\n          thetaFreqs\n          scale0Freqs\n          scaleFreqs\n          histFilePath\n          (emptyHistogram\n             [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n             , L.length scale0Freqs\n             , L.length theta0Freqs\n             , L.length scaleFreqs\n             , L.length thetaFreqs\n             ]\n             0)\n  radialArrSink <-\n    R.map magnitude . getNormalizedHistogramArr <$> decodeFile histFilePath\n  arrR2Z2T0S0 <-\n    computeUnboxedP $\n    computeR2Z2T0S0ArrayRadial\n      radialArr\n      numPoint\n      numPoint\n      1\n      maxScale\n      thetaFreqs\n      scaleFreqs\n      theta0Freqs\n      scale0Freqs\n  arrR2Z2T0S0Sink <-\n    computeUnboxedP $\n    computeR2Z2T0S0ArrayRadial\n      (cutoff 24 radialArrSink)\n      numPoint\n      numPoint\n      1\n      maxScale\n      thetaFreqs\n      scaleFreqs\n      theta0Freqs\n      scale0Freqs\n  plan <- makeR2Z2T0S0Plan emptyPlan arrR2Z2T0S0\n  sourceDistArr <-\n    computeInitialDistributionR2T0S0\n      plan\n      numPoint\n      numPoint\n      theta0Freqs\n      scale0Freqs\n      maxScale\n      initDist\n  sourceDistArrR2S1RP <-\n    r2z2Tor2s1rpP numOrientation thetaFreqs numScale scaleFreqs $ sourceDistArr\n  let xIndex =\n        [ (fromIntegral i) * 360 / (fromIntegral numOrientation)\n        | i <- [0 .. numOrientation - 1]\n        ] :: [Double]\n      inputStyle =\n        L.zipWith\n          (\\(R2S1RPPoint (x', y', _, _)) i ->\n             let x = x' + center numPoint\n                 y = y' + center numPoint\n              in ( defaultStyle\n                     { plotType = LinesPoints\n                     , lineSpec =\n                         CustomStyle\n                           [LineTitle (printf \"(%d,%d)\" x y), PointType i]\n                     }\n                 , L.zip xIndex .\n                   R.toList . R.slice (R.map magnitude sourceDistArrR2S1RP) $\n                   (Z :. All :. (0 :: Int) :. x :. y)))\n          initDist\n          [1 ..]\n  plotPathsStyle [PNG (folderPath </> \"Input.png\"), Title \"Input\"] inputStyle\n  arrR2Z2T0S0F <-\n    dftR2Z2T0S0 plan .\n    computeS .\n    makeFilter2D .\n    R.traverse arrR2Z2T0S0\n      -- (R.traverse (arrR2Z2T0S0) id $ \\f idx@(Z :. _ :. _ :. _ :. _ :. a :. b) ->\n      --    if a == center numPoint && b == center numPoint\n      --      then 0\n      --      else f idx)\n      id $ \\f (Z :. tf' :. sf' :. t0f :. s0f :. i :. j) ->\n      let idx = (Z :. tf' :. sf' :. t0f :. s0f :. i :. j)\n       in if i == center numPoint && j == center numPoint &&\n             tf' == t0f\n                    -- tf' == div (L.length thetaFreqs) 2 &&\n                    -- sf' == div (L.length scaleFreqs) 2 &&\n                    -- t0f == div (L.length theta0Freqs) 2 &&\n                    -- s0f == div (L.length scale0Freqs) 2 \n            then f idx + (0.0 :+ 0)\n            else f idx\n  -- let arr' =\n  --       r2z2t0s0Tor2s1rps1rp\n  --         numOrientation\n  --         thetaFreqs\n  --         theta0Freqs\n  --         numScale\n  --         scaleFreqs\n  --         scale0Freqs\n  --         maxScale $\n  --       arrR2Z2T0S0Sink\n  --     arr'' =\n  --       r2s1rps1rpTor2z2t0s0\n  --         numOrientation\n  --         thetaFreqs\n  --         theta0Freqs\n  --         numScale\n  --         scaleFreqs\n  --         scale0Freqs\n  --         maxScale .\n  --       computeUnboxedS .\n  --       R.map\n  --         (\\x ->\n  --            let (m, p) = polar x\n  --             in if m == 0\n  --                  then 0\n  --                  else mkPolar (1 / m) p) $\n  --       arr'\n  arrR2Z2T0S0SinkF <-\n    dftR2Z2T0S0 plan .\n    computeS .\n    makeFilter2D . computeSinkFromSourceR2Z2T0S0 thetaFreqs theta0Freqs\n    $\n    arrR2Z2T0S0Sink\n  --   R.traverse\n  --     (-- computeSinkFromSourceR2Z2T0S0 thetaFreqs theta0Freqs $\n  --      arrR2Z2T0S0)\n  --     id $ \\f idx@(Z :. a :. b :. c :. d :. i :. j) ->\n  --     let (m, p) =\n  --           polar $\n  --           conjugate\n  --             (f (Z :. (L.length thetaFreqs - 1 - a) :.\n  --                 (L.length scaleFreqs - 1 - b) :.\n  --                 (L.length theta0Freqs - 1 - c) :.\n  --                 (L.length scale0Freqs - 1 - d) :.\n  --                 i :.\n  --                 j))\n  --      in if a == div (L.length thetaFreqs) 2 &&\n  --            b == div (L.length scaleFreqs) 2 &&\n  --            c == div (L.length theta0Freqs) 2 &&\n  --            d == div (L.length scale0Freqs) 2\n  --           then 1 + conjugate\n  --                       (f (Z :. (L.length thetaFreqs - 1 - a) :.\n  --                           (L.length scaleFreqs - 1 - b) :.\n  --                           (L.length theta0Freqs - 1 - c) :.\n  --                           (L.length scale0Freqs - 1 - d) :.\n  --                           i :.\n  --                           j))\n  --           else conjugate\n  --                  (f (Z :. (L.length thetaFreqs - 1 - a) :.\n  --                      (L.length scaleFreqs - 1 - b) :.\n  --                      (L.length theta0Freqs - 1 - c) :.\n  --                      (L.length scale0Freqs - 1 - d) :.\n  --                      i :.\n  --                      j))\n  -- Source field\n  sourceArr <- convolveR2T0S0 plan arrR2Z2T0S0F sourceDistArr\n  sourceR2Z2' <- R.sumP . R.sumS . rotateR2Z2T0S0Array $ sourceArr\n  sourceR2S1RP <-\n    r2z2Tor2s1rpP numOrientation thetaFreqs numScale scaleFreqs $ sourceR2Z2'\n  let sourceR2Z2 -- = sourceR2Z2'\n       =\n        R.traverse2 sourceR2Z2' sourceDistArr const $ \\f1 f2 idx@(Z :. a :. b :. c :. d) ->\n          let x = div (L.length theta0Freqs) 2\n              y = div (L.length scale0Freqs) 2\n           in if f2 (Z :. x :. y :. c :. d) == 0\n                then 0\n                else f1 idx\n      sourceStyle =\n        L.zipWith\n          (\\(R2S1RPPoint (x', y', _, _)) i ->\n             let x = x' + center numPoint\n                 y = y' + center numPoint\n              in ( defaultStyle\n                     { plotType = LinesPoints\n                     , lineSpec =\n                         CustomStyle\n                           [LineTitle (printf \"(%d,%d)\" x y), PointType i]\n                     }\n                 , L.zip xIndex .\n                   R.toList . R.slice (R.map magnitude sourceR2S1RP) $\n                   (Z :. All :. (0 :: Int) :. x :. y)))\n          initDist\n          [1 ..]\n  plotPathsStyle [PNG (folderPath </> \"Conv.png\"), Title \"Conv\"] sourceStyle\n  sourceField <-\n    fmap (computeS . R.extend (Z :. (1 :: Int) :. All :. All)) .\n    R.sumP .\n    R.sumS .\n    rotate4D .\n    rotate4D . r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs $\n    sourceR2Z2\n  plotImageRepaComplex (folderPath </> \"Source.png\") . ImageRepa 8 $ sourceField\n  -- Deconvolution\n  deconvSourceArr <- convolveR2T0S0 plan arrR2Z2T0S0SinkF . computeUnboxedS $ sourceR2Z2\n  deconvSourceR2Z2 <-\n    R.sumP . R.sumS . rotateR2Z2T0S0Array $ deconvSourceArr\n  deconvSourceField <-\n    fmap (computeS . R.extend (Z :. (1 :: Int) :. All :. All)) .\n    R.sumP .\n    R.sumS .\n    rotate4D .\n    rotate4D . r2z2Tor2s1rp numOrientation thetaFreqs numScale scaleFreqs $\n    deconvSourceR2Z2\n  plotImageRepaComplex (folderPath </> \"DeconvSource.png\") . ImageRepa 8 $\n    deconvSourceField\n  deconvSourceR2S1RP <-\n    r2z2Tor2s1rpP numOrientation thetaFreqs numScale scaleFreqs $\n    deconvSourceR2Z2\n  let outputStyle =\n        L.zipWith\n          (\\(R2S1RPPoint (x', y', _, _)) i ->\n             let x = x' + center numPoint\n                 y = y' + center numPoint\n              in ( defaultStyle\n                     { plotType = LinesPoints\n                     , lineSpec =\n                         CustomStyle\n                           [LineTitle (printf \"(%d,%d)\" x y), PointType i]\n                     }\n                 , L.zip xIndex .\n                   R.toList . R.slice (R.map magnitude deconvSourceR2S1RP) $\n                   (Z :. All :. (0 :: Int) :. x :. y)\n                     -- (R.sumS .\n                   --    R.backpermute\n                   --      (Z :. (L.length theta0Freqs) :. numPoint :. numPoint :.\n                   --       (L.length scale0Freqs))\n                   --      (\\(Z :. a :. b :. c :. d) -> (Z :. a :. d :. b :. c)) .\n                   --    R.map magnitude $\n                   --    deconvSourceR2S1RP) $\n                   -- (Z :. All :. x :. y)\n                  ))\n          initDist\n          [1 ..]\n  plotPathsStyle [PNG (folderPath </> \"Output.png\"), Title \"Output\"] outputStyle\n", "meta": {"hexsha": "1a935e4ca0378bb21ae7af7b807b4f2695c385c5", "size": 11027, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Deconvolution/Deconvolution.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/Deconvolution/Deconvolution.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/Deconvolution/Deconvolution.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.2730263158, "max_line_length": 247, "alphanum_fraction": 0.507481636, "num_tokens": 3291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4323433080772905}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Numeric.Signal.Internal\n-- Copyright   :  (c) Alexander Vivian Hugh McPhail 2010, 2014, 2015, 2016\n-- License     :  BSD3\n--\n-- Maintainer  :  haskell.vivian.mcphail <at> gmail <dot> com\n-- Stability   :  provisional\n-- Portability :  uses FFI\n--\n-- low-level interface\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.Signal.Internal (\n                Convolvable(..),\n                Filterable(..),\n                freqz,\n                pwelch,\n                hilbert\n                ) where\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Devel\n\n--import Numeric.LinearAlgebra.Linear\n\nimport qualified Numeric.GSL.Fourier as F\nimport Foreign\n\n--import Data.Complex\nimport Foreign.C.Types\n\nimport Prelude hiding(filter)\n\nimport System.IO.Unsafe(unsafePerformIO)\n\n-----------------------------------------------------------------------------\n\ninfixr 1 #\na # b = applyRaw a b\n{-# INLINE (#) #-}\n\n-----------------------------------------------------------------------------\n\ntype PD = Ptr Double                            \ntype PC = Ptr (Complex Double)                  \ntype PF = Ptr Float\n\n-----------------------------------------------------------------------------\n\nclass Convolvable a where\n    -- | convolve two containers, output is the size of the second argument, no zero padding\n    convolve :: a -> a -> a\n\n-----------------------------------------------------------------------------\n\nclass (Storable a, Container Vector a, Num (Vector a)\n      , Convert a, Floating (Vector a), RealElement a\n      , Num a)\n       => Filterable a where\n    -- | convert from Vector Double\n    fromDouble :: Vector Double -> Vector a\n--       b ~ ComplexOf a, Container Vector b, Convert b) => Filterable a where\n    -- | filter a signal\n    filter_ :: Vector a -- ^ zero coefficients\n            -> Vector a -- ^ pole coefficients\n            -> Vector a -- ^ input signal\n            -> Vector a -- ^ output signal\n    -- | coefficients of a Hamming window\n    hamming_ :: Int           -- ^ length\n           -> Vector a -- ^ the Hamming coeffficents\n    -- | the complex power : real $ v * (conj v)\n    complex_power_ :: Vector (Complex Double) -- ^ input\n                  -> Vector a                       -- ^ output\n     -- | resample, take one sample every n samples in the original\n    downsample_ :: Int -> Vector a -> Vector a\n    -- | the difference between consecutive elements of a vector\n    deriv_ :: Vector a -> Vector a\n    -- | unwrap the phase of signal (input expected to be within (-pi,pi)\n    unwrap_ :: Vector a -> Vector a\n    -- | evaluate a real coefficient polynomial for complex arguments\n    polyEval_ :: Vector a           -- ^ the real coefficients\n         -> Vector (Complex Double) -- ^ the points at which to be evaluated\n         -> Vector (Complex Double) -- ^ the values\n    -- | the cross covariance of two signals\n    cross_covariance_ :: Int            -- ^ maximum delay\n                     -> Vector a       -- ^ time series\n                     -> Vector a       -- ^ time series\n                     -> (a,a,Vector a) -- ^ (sd_x,sd_y,cross_covariance)\n    -- | the cumulative sum of a signal\n    cumulative_sum_ :: Vector a    -- ^ time series\n                    -> Vector a    -- ^ result\n\n-----------------------------------------------------------------------------\n\ninstance Convolvable (Vector Double) where\n    convolve x y = fst $ fromComplex $ F.ifft $ (F.fft (complex x) * F.fft (complex y))\n--    convolve = convolve_vector_double\n\nconvolve_vector_double c a = unsafePerformIO $ do\n                             r <- createVector (size a)\n                             (c # a # r # id) signal_vector_double_convolve #| \"signalDoubleConvolve\"\n                             return r\n\nforeign import ccall \"signal-aux.h vector_double_convolve\" signal_vector_double_convolve :: CInt -> PD -> CInt -> PD -> CInt -> PD -> IO CInt\n\ninstance Convolvable (Vector Float) where\n    convolve x y = single $ fst $ fromComplex $ F.ifft $ (F.fft (complex $ double x) * F.fft (complex $ double y))\n--    convolve = convolve_vector_double\n\nconvolve_vector_float c a = unsafePerformIO $ do\n                             r <- createVector (size a)\n                             (c # a # r # id ) signal_vector_float_convolve #| \"signalFloatConvolve\"\n                             return r\n\nforeign import ccall \"signal-aux.h vector_float_convolve\" signal_vector_float_convolve :: CInt -> PF -> CInt -> PF -> CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\ninstance Convolvable (Vector (Complex Double)) where\n    convolve x y = F.ifft $ (F.fft x * F.fft y)\n--    convolve = convolve_vector_complex\n\nconvolve_vector_complex c a = unsafePerformIO $ do\n                              r <- createVector (size a)\n                              (c # a # r # id) signal_vector_complex_convolve #| \"signalComplexConvolve\"\n                              return r\n\nforeign import ccall \"signal-aux.h vector_complex_convolve\" signal_vector_complex_convolve :: CInt -> PC -> CInt -> PC -> CInt -> PC -> IO CInt\n\ninstance Convolvable (Vector (Complex Float)) where\n    convolve x y = single $ F.ifft $ (F.fft (double x) * F.fft (double y))\n\n-----------------------------------------------------------------------------\n\ninstance Filterable Double where\n    fromDouble = id\n    filter_ = filterD\n    hamming_ = hammingD\n    complex_power_ = complex_powerD\n    downsample_ = downsampleD\n    deriv_ = derivD\n    unwrap_ = unwrapD\n    polyEval_ = polyEval\n    cross_covariance_ = crossCovarianceD\n    cumulative_sum_ = cumSumD\n\ninstance Filterable Float where\n    fromDouble = single\n    filter_ = filterF\n    hamming_ = hammingF\n    complex_power_ = complex_powerF\n    downsample_ = downsampleF\n    deriv_ = derivF\n    unwrap_ = unwrapF\n    polyEval_ c = polyEval (double c)\n    cross_covariance_ = crossCovarianceF\n    cumulative_sum_ = cumSumF\n\n-----------------------------------------------------------------------------\n\n-- | filters the signal\nfilterD :: Vector Double -- ^ zero coefficients\n       -> Vector Double -- ^ pole coefficients\n       -> Vector Double -- ^ input signal\n       -> Vector Double -- ^ output signal\nfilterD l k v = unsafePerformIO $ do\n               r <- createVector (size v)\n               (l # k # v # r # id) signal_filter_double #| \"signalFilter\"\n               return r\n\nforeign import ccall \"signal-aux.h filter_double\" signal_filter_double :: CInt -> PD -> CInt -> PD -> CInt -> PD -> CInt -> PD -> IO CInt\n\n-- | filters the signal\nfilterF :: Vector Float -- ^ zero coefficients\n       -> Vector Float -- ^ pole coefficients\n       -> Vector Float -- ^ input signal\n       -> Vector Float -- ^ output signal\nfilterF l k v = unsafePerformIO $ do\n               r <- createVector (size v)\n               (l # k # v # r # id) signal_filter_float #| \"signalFilter\"\n               return r\n\nforeign import ccall \"signal-aux.h filter_float\" signal_filter_float :: CInt -> PF -> CInt -> PF -> CInt -> PF -> CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | Hilbert transform with original vector as real value, transformed as imaginary\nhilbert :: Vector Double -> Vector (Complex Double)\nhilbert v = unsafePerformIO $ do\n            let r = complex v\n            -- could use (complex v) to make a complex vector in haskell rather than C\n            (r # id) signal_hilbert #| \"hilbert\"\n            return r\n\nforeign import ccall \"signal-aux.h hilbert\" signal_hilbert :: CInt -> PC -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | Welch (1967) power spectrum density using periodogram/FFT method\npwelch :: Int            -- ^ window size (multiple of 2)\n       -> Vector Double  -- ^ input signal\n       -> Vector Double  -- ^ power density  \npwelch w v = unsafePerformIO $ do\n             let r = konst 0.0 ((w `div` 2) + 1)\n             (complex v # r # id) (signal_pwelch $ fromIntegral w) #| \"pwelch\"\n             return r\n\nforeign import ccall \"signal-aux.h pwelch\" signal_pwelch :: CInt -> CInt -> PC -> CInt -> PD -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | coefficients of a Hamming window\nhammingD :: Int           -- ^ length\n        -> Vector Double -- ^ the Hamming coeffficents\nhammingD l \n    | l == 1          = konst 1.0 1\n    | otherwise       = unsafePerformIO $ do\n                        r <- createVector l\n                        (r # id) signal_hamming_double #| \"Hamming\"\n                        return r\n\nforeign import ccall \"signal-aux.h hamming_double\" signal_hamming_double :: CInt -> PD -> IO CInt\n\n-- | coefficients of a Hamming window\nhammingF :: Int           -- ^ length\n        -> Vector Float -- ^ the Hamming coeffficents\nhammingF l \n    | l == 1          = konst 1.0 1\n    | otherwise       = unsafePerformIO $ do\n                        r <- createVector l\n                        (r # id) signal_hamming_float #| \"Hamming\"\n                        return r\n\nforeign import ccall \"signal-aux.h hamming_float\" signal_hamming_float :: CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | determine the frequency response of a filter\n{-freqz :: (Filterable a, Storable a, Container Vector a, Convert a, RealElement a,\n         DoubleOf a ~ DoubleOf (RealOf b), RealElement c, c ~ DoubleOf a, c ~ DoubleOf (RealOf b),\n         b ~ Complex a, b ~ ComplexOf a, Convert b, Container Vector b,\n         Container Vector c, Convert c, b ~ ComplexOf a, b ~ ComplexOf c)\n        \u21d2 Vector a     -- ^ zero coefficients\n      -> Vector a       -- ^ pole coefficients\n      -> Vector a       -- ^ points (between 0 and 2*pi)\n      -> Vector a       -- ^ response\n-}\nfreqz :: (Filterable a, Complex Double ~ ComplexOf (DoubleOf a)\n        ,Filterable (DoubleOf a)) => \n        Vector a       -- ^ zero coefficients\n      -> Vector a       -- ^ pole coefficients\n      -> Vector a       -- ^ points (between 0 and 2*pi)\n      -> Vector a       -- ^ response\nfreqz b a w = let k = max (size b) (size a)\n                  hb = polyEval_ (postpad b k) (exp (scale (0 :+ 1) ((complex $ double w))))\n                  ha = polyEval_ (postpad a k) (exp (scale (0 :+ 1) ((complex $ double w))))\n              in complex_power_ (hb / ha)\n\npostpad v n = let d = size v\n              in if d < n then vjoin [v,(konst 0.0 (n-d))]\n              else v\n\n-----------------------------------------------------------------------------\n\n-- | evaluate a real coefficient polynomial for complex arguments\npolyEval :: Vector Double           -- ^ the real coefficients\n         -> Vector (Complex Double) -- ^ the points at which to be evaluated\n         -> Vector (Complex Double) -- ^ the values\npolyEval c z = unsafePerformIO $ do\n               r <- createVector (size z)\n               (c # z # r # id) signal_real_poly_complex_eval #| \"polyEval\"\n               return r\n\nforeign import ccall \"signal-aux.h real_poly_complex_eval\" signal_real_poly_complex_eval :: CInt -> PD -> CInt -> PC -> CInt -> PC -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | the complex power : real $ v * (conj v)\ncomplex_powerD :: Vector (Complex Double) -- ^ input\n              -> Vector Double           -- ^ output\ncomplex_powerD v = unsafePerformIO $ do\n                  r <- createVector (size v)\n                  (v # r # id) signal_complex_power_double #| \"complex_power\"\n                  return r\n\nforeign import ccall \"signal-aux.h complex_power_double\" signal_complex_power_double :: CInt -> PC -> CInt -> PD -> IO CInt\n\n-- | the complex power : real $ v * (conj v)\ncomplex_powerF :: Vector (Complex Double) -- ^ input\n              -> Vector Float             -- ^ output\ncomplex_powerF v = unsafePerformIO $ do\n                  r <- createVector (size v)\n                  (v # r # id) signal_complex_power_float #| \"complex_power\"\n                  return r\n\nforeign import ccall \"signal-aux.h complex_power_float\" signal_complex_power_float :: CInt -> PC -> CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | resample, take one sample every n samples in the original\ndownsampleD :: Int -> Vector Double -> Vector Double\ndownsampleD n v = unsafePerformIO $ do\n               r <- createVector (size v `div` n)\n               (v # r # id) (signal_downsample_double $ fromIntegral n) #| \"downsample\"\n               return r\n\nforeign import ccall \"signal-aux.h downsample_double\" signal_downsample_double :: CInt -> CInt -> PD -> CInt -> PD -> IO CInt\n\n-- | resample, take one sample every n samples in the original\ndownsampleF :: Int -> Vector Float -> Vector Float\ndownsampleF n v = unsafePerformIO $ do\n               r <- createVector (size v `div` n)\n               (v # r # id) (signal_downsample_float $ fromIntegral n) #| \"downsample\"\n               return r\n\nforeign import ccall \"signal-aux.h downsample_float\" signal_downsample_float :: CInt -> CInt -> PF -> CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | the difference between consecutive elements of a vector\nderivD :: Vector Double -> Vector Double\nderivD v = unsafePerformIO $ do\n          r <- createVector (size v - 1)\n          (v # r # id) (signal_diff_double) #| \"diff\"\n          return r\n\nforeign import ccall \"signal-aux.h vector_diff_double\" signal_diff_double :: CInt -> PD -> CInt -> PD -> IO CInt\n\n-- | the difference between consecutive elements of a vector\nderivF :: Vector Float -> Vector Float\nderivF v = unsafePerformIO $ do\n          r <- createVector (size v - 1)\n          (v # r # id) (signal_diff_float) #| \"diff\"\n          return r\n\nforeign import ccall \"signal-aux.h vector_diff_float\" signal_diff_float :: CInt -> PF -> CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | unwrap the phase of signal (input expected to be within (-pi,pi)\nunwrapD :: Vector Double -> Vector Double\nunwrapD v = unsafePerformIO $ do\n           r <- createVector $ size v\n           (v # r # id) signal_unwrap_double #| \"unwrap\"\n           return r\n\nforeign import ccall \"signal-aux.h unwrap_double\" signal_unwrap_double :: CInt -> PD -> CInt -> PD -> IO CInt\n\n-- | unwrap the phase of signal (input expected to be within (-pi,pi)\nunwrapF :: Vector Float -> Vector Float\nunwrapF v = unsafePerformIO $ do\n           r <- createVector $ size v\n           (v # r # id) signal_unwrap_float #| \"unwrap\"\n           return r\n\nforeign import ccall \"signal-aux.h unwrap_float\" signal_unwrap_float :: CInt -> PF -> CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\n-- | compute the cross covariance of two signals\ncrossCovarianceD :: Int -> Vector Double -> Vector Double -> (Double,Double,Vector Double)\ncrossCovarianceD l x y = unsafePerformIO $ do\n                           r <- createVector (2*l)\n                           alloca $ \\sx -> \n                               alloca $ \\sy -> do\n                                 (x # y # r # id) (signal_cross_covariance_double (fromIntegral l) sx sy) #| \"cross_covariance\"\n                                 sx' <- peek sx\n                                 sy' <- peek sy\n                                 return (sx',sy',r)\n\nforeign import ccall \"signal-aux.h cross_covariance_double\" \n        signal_cross_covariance_double :: CInt -> PD -> PD -> CInt -> PD -> CInt\n                                       -> PD -> CInt -> PD -> IO CInt\n\n-- | compute the cross covariance of two signals\ncrossCovarianceF :: Int -> Vector Float -> Vector Float -> (Float,Float,Vector Float)\ncrossCovarianceF l x y = unsafePerformIO $ do\n                           r <- createVector (2*l)\n                           alloca $ \\sx -> \n                               alloca $ \\sy -> do\n                                 (x # y # r # id) (signal_cross_covariance_float (fromIntegral l) sx sy) #| \"cross_covariance\"\n                                 sx' <- peek sx\n                                 sy' <- peek sy\n                                 return (sx',sy',r)\n\nforeign import ccall \"signal-aux.h cross_covariance_float\" \n        signal_cross_covariance_float :: CInt -> PF -> PF -> CInt -> PF -> CInt\n                                       -> PF -> CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\ncumSumD :: Vector Double -> Vector Double\ncumSumD v = unsafePerformIO $ do\n              r <- createVector (size v)\n              (v # r # id) signal_cum_sum_double #| \"cumSumD\"\n              return r\n\ncumSumF :: Vector Float -> Vector Float\ncumSumF v = unsafePerformIO $ do\n              r <- createVector (size v)\n              (v # r # id) signal_cum_sum_float #| \"cumSumF\"\n              return r\n\nforeign import ccall \"signal-aux.h cum_sum_double\"\n        signal_cum_sum_double :: CInt -> PD -> CInt -> PD -> IO CInt\nforeign import ccall \"signal-aux.h cum_sum_float\"\n        signal_cum_sum_float :: CInt -> PF -> CInt -> PF -> IO CInt\n\n-----------------------------------------------------------------------------\n\n\n\n", "meta": {"hexsha": "e3b240d7e2f94be797c900c5674711351f602282", "size": 17499, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/Signal/Internal.hs", "max_stars_repo_name": "amcphail/hsignal", "max_stars_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-05-27T06:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T23:12:53.000Z", "max_issues_repo_path": "lib/Numeric/Signal/Internal.hs", "max_issues_repo_name": "amcphail/hsignal", "max_issues_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-10-30T11:41:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T23:38:57.000Z", "max_forks_repo_path": "lib/Numeric/Signal/Internal.hs", "max_forks_repo_name": "amcphail/hsignal", "max_forks_repo_head_hexsha": "94bb05e77053a9284be98c281e0a21544437072b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8636363636, "max_line_length": 143, "alphanum_fraction": 0.5279158809, "num_tokens": 4002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4323433034360014}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveAnyClass        #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-|\nModule      : Grenade.Core.Softmax\nDescription : Softmax loss layer\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.Softmax (\n    Softmax (..)\n  , softmax\n  , softmax'\n  , SpecSoftmax (..)\n  , specSoftmax\n  , softmaxLayer\n  ) where\n\nimport           Data.Serialize\n\nimport           Control.DeepSeq                (NFData (..))\nimport           Data.Reflection                (reifyNat)\nimport           Data.Singletons\nimport           GHC.Generics                   (Generic)\nimport           GHC.TypeLits\nimport           Numeric.LinearAlgebra.Static   as LAS\n\nimport           Grenade.Core\nimport           Grenade.Dynamic\nimport           Grenade.Dynamic.Internal.Build\n\n-- | A Softmax layer\n--\n--   This layer is like a logit layer, but normalises\n--   a set of matricies to be probabilities.\n--\n--   One can use this layer as the last layer in a network\n--   if they need normalised probabilities.\ndata Softmax = Softmax\n  deriving (Show, Generic, NFData)\n\ninstance UpdateLayer Softmax where\n  type Gradient Softmax = ()\n  runUpdate _ _ _ = Softmax\n\ninstance RandomLayer Softmax where\n  createRandomWith _ _ = return Softmax\n\ninstance ( KnownNat i ) => Layer Softmax ('D1 i) ('D1 i) where\n  type Tape Softmax ('D1 i) ('D1 i) = S ('D1 i)\n\n  runForwards _ (S1D y) = (S1D y, S1D (softmax y))\n  runBackwards _ (S1D y) (S1D dEdy) = ((), S1D (softmax' y dEdy))\n\ninstance Serialize Softmax where\n  put _ = return ()\n  get = return Softmax\n\nsoftmax :: KnownNat i => LAS.R i -> LAS.R i\nsoftmax xs =\n  let xs' = LAS.dvmap exp xs\n      s   = LAS.dot xs' 1\n  in  LAS.dvmap (/ s) xs'\n\nsoftmax' :: KnownNat i => LAS.R i -> LAS.R i -> LAS.R i\nsoftmax' x grad =\n  let yTy = outer sm sm\n      d   = diag sm\n      g   = d - yTy\n  in  g #> grad\n    where\n  sm = softmax x\n\n-------------------- DynamicNetwork instance --------------------\n\ninstance FromDynamicLayer Softmax where\n  fromDynamicLayer inp _ Softmax = case tripleFromSomeShape inp of\n    (rows, 1, 1) -> SpecNetLayer $ SpecSoftmax rows\n    _ -> error \"Error in specification: The layer Softmax may only be used with 1D input!\"\n\ninstance ToDynamicLayer SpecSoftmax where\n  toDynamicLayer _ _ (SpecSoftmax rows) =\n    reifyNat rows $ \\(_ :: (KnownNat i) => Proxy i) ->\n    return $ SpecLayer Softmax (sing :: Sing ('D1 i)) (sing :: Sing ('D1 i))\n\n\n-- | Create a specification for a elu layer.\nspecSoftmax :: Integer -> SpecNet\nspecSoftmax = SpecNetLayer . SpecSoftmax\n\n\n-- | Add a Softmax layer to your build.\nsoftmaxLayer :: BuildM ()\nsoftmaxLayer = buildRequireLastLayerOut Is1D >>= buildAddSpec . SpecNetLayer . SpecSoftmax . fst3\n  where\n    fst3 (x, _, _) = x\n\n-------------------- GNum instances --------------------\n\n\ninstance GNum Softmax where\n  _ |* Softmax = Softmax\n  _ |+ Softmax = Softmax\n", "meta": {"hexsha": "cd0c9d161758102db1c24b48c08d4378d320c7fb", "size": 3172, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Softmax.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/Softmax.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/Softmax.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": 28.5765765766, "max_line_length": 97, "alphanum_fraction": 0.6232660782, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.43221308551726584}}
{"text": "module Statistics.GModeling.Models.HMM\n  (\n  ) where\n\nimport Statistics.GModeling.DSL\nimport Statistics.GModeling.Gibbs\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Mutable as MU\n\ndata HMM = Alpha | Beta | Transition\n         | Topic | Symbols | Symbol\n\nhmm :: Network HMM\nhmm =\n  [\n    Only Alpha            :-> Transition\n  , Only Beta             :-> Symbols\n  , (Transition :@ Topic) :-> Topic\n  , (Symbols :@ Topic)    :-> Symbol\n  ]\n\ntype D = V.Vector (U.Vector (Int,Int))\n\nreader :: D -> Reader HMM Int\nreader v = Reader\n  {\n    size = G.sum (G.map G.length v)\n  , readn = \\idx k ->\n      let (i,j) = indices G.! idx\n          (topic,symbol) = v G.! i G.! j\n          (prev_topic,_) = v G.! i G.! (j-1)\n      in case k of\n           Topic -> topic\n           Symbol -> symbol\n           Symbols -> topic\n           Transition -> if j==0\n                         -- reserve Topic 0 for initial distribution\n                         then 0\n                         else prev_topic\n  , copy = do\n      m <- G.mapM U.thaw v\n      return Writer\n        {\n          writen = \\idx k v -> do\n            let (i,j) = indices G.! idx\n            case k of\n              Topic -> do\n                (_,s) <- MU.unsafeRead (m G.! i) j\n                MU.unsafeWrite (m G.! i) j (v,s)\n        , readOnly = G.mapM U.freeze m >>= return . reader\n        }\n  }\n  where indices = U.fromList $ do\n          i <- [0..G.length v-1]\n          j <- [0..G.length (v G.! i)-1]\n          return (i,j)\n", "meta": {"hexsha": "fdfe4fe18d240cbed2288c1a12e0f24744a1eaec", "size": 1593, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/GModeling/Models/HMM.hs", "max_stars_repo_name": "nanonaren/gmodeling", "max_stars_repo_head_hexsha": "befb0f3cca0c212e368497e86f030aa96355be18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Statistics/GModeling/Models/HMM.hs", "max_issues_repo_name": "nanonaren/gmodeling", "max_issues_repo_head_hexsha": "befb0f3cca0c212e368497e86f030aa96355be18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/GModeling/Models/HMM.hs", "max_forks_repo_name": "nanonaren/gmodeling", "max_forks_repo_head_hexsha": "befb0f3cca0c212e368497e86f030aa96355be18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 68, "alphanum_fraction": 0.5109855618, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4321459614930073}}
{"text": "{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ExplicitForAll #-}\n--{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n--{-# LANGUAGE PartialTypeSignatures #-}\n{-# LANGUAGE RankNTypes #-}\n--{-# LANGUAGE RebindableSyntax #-}\n--{-# LANGUAGE ScopedTypeVariables #-}\n\n{-# LANGUAGE OverloadedLists #-}\n--{-# LANGUAGE NamedFieldPuns #-}\n{-# OPTIONS_GHC -XBangPatterns #-}\n\nmodule Test.Random ( testRandom ) where\n\nimport Prelude.Extended\n-- import Control.Monad.Eff (Eff)\n-- import Control.Monad.Eff.Console ( CONSOLE, log )\n-- import Control.Monad.Eff.Random ( RANDOM )\n-- import Data.List.Lazy ( replicateM )\nimport Data.Vector.Unboxed as A\n  ( zipWith, fromList )\n-- import Data.Traversable ( for )\n-- import Data.Tuple ( Tuple (..) )\nimport Statistics.Sample ( meanVariance )\nimport System.Random ( RandomGen, newStdGen )\nimport Data.Time.Clock\n-- import Text.Printf\n-- import Control.Parallel\n-- import Control.Parallel.Strategies\n\nimport Data.Cov ( chol, fromArray, toArray, (*.), Vec5 )\nimport FV.Fit ( fit )\nimport FV.Types ( VHMeas(..), HMeas(..), MMeas(..)\n  , invMass, fromQMeas, fitMomenta )\n\n{-- import qualified Graphics.Gnuplot.Frame.OptionSet as Opts --}\n{-- import Graphics.Histogram --}\n\n-- | Randomizable TypeClass to provide randomize method\n-- | for MC smearing of a measurement\nclass Randomizable a where\n  randomize :: RandomGen g => a -> g -> (a, g)\n-- | randomize a single helix parameters measurement, based on the cov matrix\n-- | return randomized helix\ninstance Randomizable HMeas where\n  randomize (HMeas h hh w0) g = (HMeas h' hh w0, g') where\n    (rs, g') = normals 5 g\n    r5 :: Vec5\n    r5 = fromArray rs\n    h' = fromArray $ A.zipWith (+) (toArray h) (toArray (chol hh *. r5))\n\n-- | randomize a vertex measurement by randomizing each helix parameter measurement\n-- | leaving the initial vertex untouched\ninstance Randomizable VHMeas where\n  randomize (VHMeas { vertex= v, helices= hl}) g =\n    (VHMeas { vertex= v, helices= hl' }, g') where\n      doit :: RandomGen g => HMeas -> (List HMeas, g) -> (List HMeas, g)\n      doit h (hs, g) = (hs', g') where\n        (h', g') = randomize h g\n        hs' = h' : hs\n      (hl', g') = foldr doit ([], g) hl\n\n-- calc fitted invariant mass of VHMeas\nfitm :: VHMeas -> Number\nfitm vm = m where\n  MMeas {m= m} = invMass <<< map fromQMeas <<< fitMomenta $ fit vm\n\ntestRandom ::Int\n             -> VHMeas\n             -> IO Text\ntestRandom cnt vm = do\n  g <- newStdGen\n  t0 <- getCurrentTime\n  let\n      mf = invMass <<< map fromQMeas <<< fitMomenta <<< fit $ vm\n      !mr = MMeas {m=m, dm=sqrt dm2}\n      (m, dm2) = meanVariance $ A.fromList ms\n      ls :: [Int]\n      ls = [0 .. (cnt-1)]\n      (ms, _) = foldl doit ([], g) ls where\n        doit :: RandomGen g => (List Number, g) -> Int -> (List Number, g)\n        doit (ms, g) _ = (ms', g') where\n          (vm', g') = randomize vm g\n          m = fitm vm'\n          ms' = m : ms\n  t1 <- getCurrentTime\n\n  -- ms = map func 1..cnt\n  -- func vm g = (m, g') where\n  --   (vm', g') = randomize vm g\n  --   m' = fitm vm'\n\n  pure $ \"Fit Mass  \" <> tshow mf\n       <> \"\\nMean Mass \" <> tshow mr\n       <> \"\\ntime: \"\n            <> to2fix (realToFrac (diffUTCTime t1 t0) :: Number)\n            <> \" seconds\"\n  {-- let hist = histogram binSturges (V.toList hf) --}\n  {-- _ <- plot \"invMass.png\" hist --}\n\n", "meta": {"hexsha": "53d2b459ada922be2b117b817f39d3ba12f8984a", "size": 3407, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Test/Random.hs", "max_stars_repo_name": "LATBauerdick/fv-hs", "max_stars_repo_head_hexsha": "0403030b8e10f0b56ae4ba023f8233bf8b4855b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-25T20:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-25T20:14:13.000Z", "max_issues_repo_path": "src/Test/Random.hs", "max_issues_repo_name": "LATBauerdick/fv-hs", "max_issues_repo_head_hexsha": "0403030b8e10f0b56ae4ba023f8233bf8b4855b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Test/Random.hs", "max_forks_repo_name": "LATBauerdick/fv-hs", "max_forks_repo_head_hexsha": "0403030b8e10f0b56ae4ba023f8233bf8b4855b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7596153846, "max_line_length": 83, "alphanum_fraction": 0.6166715586, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4319335684830815}}
{"text": "{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE QuantifiedConstraints #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\nmodule Q.Interpolation where\nimport qualified Q.SortedVector as SV\nimport Numeric.GSL.Interpolation\nimport qualified Numeric.LinearAlgebra as V (Vector, fromList)\nimport Foreign (Storable)\nimport Data.List\nclass (Ord k, Storable k, Storable v) => Interpolator a k v where\n  interpolate :: a -> [(k, v)] -> k -> v\n\nclass (Ord k, Storable k, Storable v) => InterpolatorV a k v where\n  interpolateV :: a -> SV.SortedVector k -> V.Vector v -> k -> v\n\ninstance (Ord k, Storable k, Storable v, InterpolatorV a k v) => Interpolator a k v where\n  interpolate a pts = interpolateV a xs' ys' where\n    (xs, ys) = (unzip . sortOn fst) pts\n    xs'      = SV.fromSortedList xs\n    ys'      = V.fromList ys\n", "meta": {"hexsha": "e9ba00ecfef856ed8fb88610e4bbfe1f0aea9ca0", "size": 872, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Q/Interpolation.hs", "max_stars_repo_name": "ghais/lowq", "max_stars_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-12-01T17:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T18:06:22.000Z", "max_issues_repo_path": "src/Q/Interpolation.hs", "max_issues_repo_name": "ghais/lowq", "max_issues_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Q/Interpolation.hs", "max_forks_repo_name": "ghais/lowq", "max_forks_repo_head_hexsha": "5631afb2002d49cbdd2f612908d48608e72cc7e1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9130434783, "max_line_length": 89, "alphanum_fraction": 0.6972477064, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.43183513660568396}}
{"text": "#!/usr/bin/env stack\n-- stack runghc --package reanimate\n{-# LANGUAGE OverloadedStrings #-}\nmodule Main where\n\nimport           Codec.Picture.Types\nimport           Control.Lens                  ()\nimport           Control.Monad\nimport           Data.Function\nimport           Data.List\nimport           Data.List.NonEmpty            (NonEmpty)\nimport qualified Data.List.NonEmpty            as NE\nimport           Data.Maybe\nimport           Data.Ratio\nimport qualified Data.Text                     as T\nimport           Data.Tuple\nimport qualified Data.Vector                   as V\nimport           Debug.Trace\nimport           Linear.Matrix                 hiding (trace)\nimport           Linear.Metric\nimport           Linear.V2\nimport           Linear.V3\nimport           Linear.Vector\nimport           Numeric.LinearAlgebra         hiding (polar, scale, (<>))\nimport qualified Numeric.LinearAlgebra         as Matrix\nimport           Numeric.LinearAlgebra.HMatrix hiding (polar, scale, (<>))\nimport           Reanimate\nimport           Reanimate.Animation\nimport           Reanimate.Math.Balloon\nimport           Reanimate.Math.Common\nimport           Reanimate.Math.Triangulate\nimport           Reanimate.Math.Polygon\nimport           Reanimate.Math.EarClip\nimport           Reanimate.Math.SSSP\nimport           Reanimate.Math.Render\nimport           Reanimate.Math.Visibility\nimport           Reanimate.Math.Compatible\nimport           Reanimate.Morph.Common\nimport           Reanimate.PolyShape           (svgToPolygons)\n\np :: Polygon\np = mkPolygon $ V.fromList [V2 (0 % 1) (0 % 1),V2 (1 % 1) (0 % 1),V2 (1 % 1) (1 % 1),V2 (2 % 1) (1 % 1),V2 (2 % 1) ((-1) % 1),V2 (3 % 1) ((-1) % 1),V2 (3 % 1) (2 % 1),V2 (0 % 1) (2 % 1)]\n\npCuts' :: Polygon -> [(Int,Int)]\npCuts' p =\n  [ (i, j)\n  | i <- [0 .. pSize p-1 ]\n  , j <- [i+2 .. pSize p-1 ]\n  , (j+1) `mod` pSize p /= i\n  , trace (\"Check: \" ++ show (i,j, pSize p)) $ pParent p i j == i ]\n\n-- p :: Polygon\n-- p = pScale 6 $ unsafeSVGToPolygon 0.1 $\n--   lowerTransformations $ pathify $ center $ latex \"$1$\"\n\nmain :: IO ()\nmain = reanimate $ sceneAnimation $ do\n  bg <- newSpriteSVG $ mkBackground \"black\"\n  spriteZ bg (-1)\n  newSpriteSVG_ $ translate 0 1 $ mkGroup\n    [ withFillColor \"grey\" $ polygonShape p\n    , polygonNumDots p\n    ]\n  forM_ (pCuts p) $ \\(l,r) -> do\n    play $ mkAnimation (1/60) $ \\_ -> mkGroup\n      [ translate (-3) 0 $ withFillColor \"grey\" $ polygonShape l\n      , translate (-3) 0 $ polygonNumDots l\n      , translate (3) 0 $ withFillColor \"grey\" $ polygonShape r\n      , translate (3) 0 $ polygonNumDots r\n      ]\n  -- wait 1\n  -- fork $ play $ drawTriangulation shape1 earCut'\n  --   # mapA (translate (-3) 0)\n  -- play $ drawTriangulation shape1 earClip'\n  --   # mapA (translate (3) 0)\n  return ()\n", "meta": {"hexsha": "4d5f05e2513bd638a0673580e30f1c17c26d8e75", "size": 2782, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "videos/morph/vis.hs", "max_stars_repo_name": "sureyeaah/reanimate", "max_stars_repo_head_hexsha": "9cf33b9444c5212f47e42497ad6e38d8e5e3b0d8", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "videos/morph/vis.hs", "max_issues_repo_name": "sureyeaah/reanimate", "max_issues_repo_head_hexsha": "9cf33b9444c5212f47e42497ad6e38d8e5e3b0d8", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "videos/morph/vis.hs", "max_forks_repo_name": "sureyeaah/reanimate", "max_forks_repo_head_hexsha": "9cf33b9444c5212f47e42497ad6e38d8e5e3b0d8", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1298701299, "max_line_length": 186, "alphanum_fraction": 0.5744069015, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.43180274095266225}}
{"text": "-- calculates nash equilibriums, does related backend stuff\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Game\n    ( gameSimplePartial, gameSimplePartialOpts, gameSimple\n    , calcPureEVs, calcEVSimpleCore, calcVarSimpleCore, calcSDSimpleCore\n    , gameComplex, resultComplex\n    , solvePure, solvePureBy, solvePureOn, solvePureZeroSum\n    , solvePureOptimal, solvePureOptimalZeroSum\n    , solveSimpleCoreNaive\n    , calcEVSimpleCoreNaive\n    , solveSimple, solveComplex\n    , resultComplex\n    , Game (Game, gameCName, attCName, defCName, gameData, outcomesC)\n    , Result (Result, evc, evr, sdc, sdr, weightsAtts, weightsDefs)\n    , ResultSimple  (ResultSimple, evSimpleCol, evSimpleRow, sdSimpleCol, sdSimpleRow, weightsColsSimple, weightsRowsSimple)\n    ) where\n\nimport GameData\n\nimport Data.List\nimport Data.List.Split\nimport Data.Function\nimport Data.Maybe\nimport Data.Text (Text, unpack)\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Safe\n\ntype EV = Double\ntype Var = Double\ntype SD = Double\ntype Weights = [Double]\ntype Coord = (Int,Int)\ntype RemovedElements = [Int]\ntype WeightedOption = (Opt, Opt, Double)\ntype BiWeightedOption = (Opt, Opt, Double, Double)\ntype PayoffsRaw = [[Double]]\ntype Payoffs = Matrix Double\n\ngameSimplePartial :: PayoffsRaw -> Payoffs\ngameSimplePartial = fromLists\n\ngameSimplePartialOpts :: [WeightedOption] -> PayoffsRaw\ngameSimplePartialOpts opts =\n    let\n        fst3 (x,_,_) = x\n        snd3 (_,x,_) = x\n        thd3 (_,_,x) = x\n        \n        cols = nub . map (fst . fst3) $ opts\n        rows = nub . map (fst . snd3) $ opts\n        grid = map (map thd3) . transpose . chunksOf (length rows) $ opts\n    in\n        grid\n\ngameSimple :: Text -> [Text] -> [Text] -> PayoffsRaw -> PayoffsRaw -> GameSimple\ngameSimple n c r m1 m2 = GameSimple n c r (fromLists m1) (fromLists m2) $ solveSimple m1 m2\n\ncalcPureEVs :: Payoffs -> Weights -> [EV]\ncalcPureEVs m cols = concat . toLists $ m Numeric.LinearAlgebra.<> (col (fmap (/ sum cols) cols))\n\ncalcEVSimpleCore :: Payoffs -> Weights -> Weights -> EV\ncalcEVSimpleCore m cols rows = (head . head . toLists $ (row rows) Numeric.LinearAlgebra.<> m Numeric.LinearAlgebra.<> (col cols))\n\ncalcVarSimpleCore :: Payoffs -> Weights -> Weights -> Var\ncalcVarSimpleCore mat cols rows = calcEVSimpleCore (cmap (\\x -> (x - calcEVSimpleCore mat cols rows)**2) mat) cols rows\n\ncalcSDSimpleCore :: Payoffs -> Weights -> Weights -> SD\ncalcSDSimpleCore a b = sqrt . calcVarSimpleCore a b\n\ngameComplex :: Text -> Text -> Text -> [BiWeightedOption] -> Game\ngameComplex t1 t2 t3 m = Game t1 t2 t3 (sort m) . resultComplex m $ solveComplex m\n\nresultComplex :: [(Opt, Opt, Double, Double)] -> ResultSimple -> Result\nresultComplex opts (ResultSimple evc evr sdc sdr cw rw) = do\n    let colnames = nub . map (fst . fst4) $ opts\n    let rownames = nub . map (fst . snd4) $ opts\n    Result evc evr sdc sdr (zip colnames cw) (zip rownames rw)\n\n\n-- from here on out, stuff for solving games\n\n\n\n-- the fundamental algorithm, given some ordering method to know which values are better\nsolvePureBy :: (Eq a) => (a -> a -> Ordering) -> [[a]] -> [[a]] -> [Coord]\nsolvePureBy f mc mr =\n    let\n        width = length . head $ mc\n        height = length mc\n        \n        -- column player: picks the highest columns for each row\n        mcIsBestResponse = map (\\col -> map (== maximumBy f col) col) mc\n        -- row player: picks the highest rows for each coloumn\n        mrIsBestResponse = transpose . map (\\row -> map (== maximumBy f row) row) . transpose $ mr\n        bestResponses = map (uncurry zip) $ zip mcIsBestResponse mrIsBestResponse\n        \n        coords = map (\\r -> map (\\c -> (c,r)) [0..width-1]) [0..height-1]\n        zipped = map (uncurry zip) $ zip coords bestResponses\n        zippedFiltered = map fst . filter (\\((x,y),(c,r)) -> and[c,r]) . concat $ zipped\n    in\n        zippedFiltered\n\n-- solvePureBy applied to mapped values\nsolvePureOn :: (Ord c) => (a -> c) -> (b -> c) -> [[a]] -> [[b]] -> [Coord]\nsolvePureOn f g mc mr = solvePureBy compare (map (map f) mc) (map (map g) mr)\n\nsolvePure :: (Ord a) => [[a]] -> [[a]] -> [Coord]\nsolvePure mc mr = solvePureOn id id mc mr\n\nsolvePureZeroSum :: (Ord a, Num a) => [[a]] -> [Coord]\nsolvePureZeroSum m = solvePureOn id negate m m\n\nevPure :: [[a]] -> Coord -> a\nevPure m (c,r) = (m!!c)!!r\n\nsolvePureOptimalBy :: (Ord a) => (a -> a -> Ordering) -> ([[a]] -> Coord -> a) -> [[a]] -> [[a]] -> Maybe Coord\nsolvePureOptimalBy f ev mc mr =\n    let\n        pures = solvePureBy f mc mr\n        -- note that we have already optimised the row choice per column choice, as these are all, by definition, nash equilibria\n        -- thus, simply choose the optimal nash equilibrium for column ev\n        bestPure = maximumByMay (compare `on` (\\p -> ev mc p)) pures\n    in\n        bestPure\n\nsolvePureOptimalOn :: (Ord c) => (a -> c) -> (b -> c) -> ([[c]] -> Coord -> c) -> [[a]] -> [[b]] -> Maybe Coord\nsolvePureOptimalOn f g ev mc mr = solvePureOptimalBy compare ev (map (map f) mc) (map (map g) mr)\n\nsolvePureOptimal :: (Ord a) => [[a]] -> [[a]] -> Maybe Coord\nsolvePureOptimal mc mr = solvePureOptimalOn id id evPure mc mr\n\nsolvePureOptimalZeroSum :: (Ord a, Num a) => [[a]] -> Maybe Coord\nsolvePureOptimalZeroSum m = solvePureOptimal m . map (map negate) $ m\n\n\nsolveSimpleCoreNaive :: Matrix Double -> Maybe Weights\nsolveSimpleCoreNaive m =\n    do\n        case (rows m, cols m) of\n            -- not really much choice\n            (_,1) -> return [1]\n            -- they only have one option, so zip your options to their position, get the best option's position, and pad a [1] with zeroes as appropriate to the position\n            (1,c) -> return . (\\n -> ((take n (repeat 0)) ++ [1] ++ (take (c - n - 1) (repeat 0)))) . fst . maximumBy (compare `on` snd) . zip [0..] . concat . toLists $ m\n            -- use linear algebra to find the weights such that unexploitable play is achieved, ie, the ev of each of the opponent's options is equal\n            _ -> let\n                        weights = normalise . concat . toLists $ ((pinv m) Numeric.LinearAlgebra.<> (((rows m)><1) (repeat (fromInteger 1))))\n                    in\n                        if all (>=0) weights\n                        then return weights\n                        else Nothing\n    where\n        normalise :: (Fractional a) => [a] -> [a]\n        normalise xs = map (/ (sum xs)) xs\n\ncalcEVSimpleCoreNaive :: Matrix Double -> Maybe EV\ncalcEVSimpleCoreNaive m = \n    do\n        wc <- solveSimpleCoreNaive m\n        wr <- solveSimpleCoreNaive . tr' $ m\n        return $ calcEVSimpleCore m wc wr\n\ngameSupports :: (Ord a, Num a) => [[a]] -> [[a]] -> [[((RemovedElements, RemovedElements), ([[a]], [[a]]))]]\ngameSupports m1 m2 =\n    let\n        widther = length . head\n        heighter = length\n        w = widther m1 - 1\n        h = heighter m1 - 1\n        \n        removeIndexes :: RemovedElements -> [a] -> [a]\n        removeIndexes [] xs = xs\n        removeIndexes _ [] = error \"Can't remove from an empty list!\"\n        removeIndexes [0] (x:xs) = xs\n        removeIndexes [n] (x:xs) = x:(removeIndexes [n-1] xs)\n        removeIndexes (n:ns) xs = removeIndexes (fmap (subtract 1) ns) (removeIndexes [n] xs)\n        \n        subm :: (RemovedElements,RemovedElements) -> [[a]] -> [[a]]\n        subm coords = map (removeIndexes (fst coords)) . removeIndexes (snd coords)\n        \n        supportsColsRaw = zip [0..] . init . subsequences $ [0..w] -- [[],[0],[1],...,[n],[0,1],[0,2],...,[0,n],[0,1,2],...]\n        supportsRowsRaw = zip [0..] . init . subsequences $ [0..h]\n        supportsPairs = map (\\(x,c) -> map (\\(y,r) -> ((c,r), (subm (c,r) m1, subm (c,r) m2))) supportsRowsRaw) supportsColsRaw\n    in\n        supportsPairs\n\ngameSupportsZeroSum :: (Ord a, Num a) => [[a]] -> [[((RemovedElements, RemovedElements), ([[a]], [[a]]))]]\ngameSupportsZeroSum m = gameSupports m (map (map negate) m)\n\nsupportIntoValidatedWeightsEVsSDs :: ((RemovedElements, RemovedElements), ([[Double]], [[Double]])) -> Maybe ((Weights, Weights), ((EV, EV), (SD, SD)))\nsupportIntoValidatedWeightsEVsSDs ((sc,sr), (mc,mr)) =\n    do\n        let (g1,g2) = (gameSimplePartial mc, tr' $ gameSimplePartial mr)\n        w1 <- solveSimpleCoreNaive g1\n        w2 <- solveSimpleCoreNaive g2\n        let ws = (addIndexes 0 sc w1, addIndexes 0 sr w2)\n        let evs = (calcEVSimpleCore g1 w1 w2, calcEVSimpleCore g2 w2 w1)\n        let sds = (calcSDSimpleCore g1 w1 w2, calcSDSimpleCore g2 w2 w1)\n        return (ws, (evs, sds))\n    where\n        addIndexes :: a -> [Int] -> [a] -> [a]\n        addIndexes _ [] xs = xs\n        addIndexes def [0] xs = def:xs\n        addIndexes _ _ [] = error \"Add index out of bounds\"\n        addIndexes def [n] (x:xs) = x:(addIndexes def [n-1] xs)\n        addIndexes def (n:ns) xs = addIndexes def ns (addIndexes def [n] xs)\n\n\nsupportsIntoValidatedWeightsEVsSDs :: [[((RemovedElements, RemovedElements), ([[Double]], [[Double]]))]] -> [[Maybe ((Weights, Weights), ((EV, EV), (SD, SD)))]]\nsupportsIntoValidatedWeightsEVsSDs = map (map supportIntoValidatedWeightsEVsSDs)\n\nsolveSimple :: [[Double]] -> [[Double]] -> ResultSimple\nsolveSimple mc mr =\n    let\n        sups = gameSupports mc mr\n        strats = supportsIntoValidatedWeightsEVsSDs sups\n        \n        maximumOn f = maximumBy (compare `on` f)\n        colEv = fmap (fst . fst . snd)\n        rowEv = fmap (snd . fst . snd)\n        \n        stratsBestResponses = map (maximumOn rowEv) strats\n        stratsBest = maximumOn colEv stratsBestResponses\n        \n        res (Just ((wc,wr),((evc,evr),(sdc,sdr)))) = ResultSimple evc evr sdc sdr wc wr\n    in\n        res stratsBest\n\nsolveComplex :: Ord a => [((a, Maybe Double), (a, Maybe Double), Double, Double)] -> ResultSimple\nsolveComplex gdata =\n    let\n        typeCheck ((_,c), (_,r), _, _) = (fromEnum . isNothing $ c) + ((2*) . fromEnum . isNothing $ r)\n        \n        pureStrategy :: Int -> Int -> [Double]\n        pureStrategy l x = take l ((take (x-1) . repeat $ 0) ++ (1:[0..]))\n        --  get all the subgame data and split it according to type: neither = Nothing, col = Nothing, row = Nothing, both = Nothing\n        --  evs :: [[((Text, Maybe Double), (Text, Maybe Double), Double)]]\n        evs = map (\\i -> filter (\\outcome -> typeCheck outcome == i) $ gdata) [0..3]\n    in\n        case evs of\n            [both, [], [], []]  -> do -- both are fixed, so we just copy the weights into the ResultSimple\n                let rows = nub . map (fst . fst4) $ both\n                let cols = nub . map (fst . snd4) $ both\n                let grid = transpose . chunksOf (length rows) $ both\n                let outsc = map (map thd4) grid\n                let outsr = map (map fth4) grid\n                \n                let gc = fromLists outsc\n                let gr = fromLists outsr\n                let cw = map (maybe (error \"???\") id . snd) . nub . map fst4 $ both\n                let rw = map (maybe (error \"???\") id . snd) . nub . map snd4 $ both\n                ResultSimple (calcEVSimpleCore gc cw rw) (calcEVSimpleCore gr cw rw) (calcSDSimpleCore gc cw rw) (calcSDSimpleCore gr cw rw) cw rw\n\n            [[], c, [], []]      -> do -- typeCheck 1 -> columns unfixed, rows fixed, evaluate columns\n                let cols = nub . map (fst . fst4) $ c -- each column option, in the form of name::Text\n                let rows = map (\\(a, Just b) -> (a,b)) . nub . map snd4 $ c -- each row option, in the form of (name, weight)::(Text, Double)\n                let grid = transpose . chunksOf (length rows) $ c\n                let outsc = map (map thd4) grid\n                let outsr = map (map fth4) grid\n                let gc = fromLists outsc\n                let gr = fromLists outsr\n                \n                let colStrats = map (pureStrategy . length $ cols) [0..length cols] -- every pure strategy to try against the fixed row strategy\n                let evs = map (\\strat -> calcEVSimpleCore gc strat (map snd rows)) colStrats -- every ev\n                \n                let (cw, ev) = maximumBy (compare `on` snd) . zip colStrats $ evs -- get the optimal pure strategy for the column player\n                let rw = map snd rows\n                ResultSimple ev (calcEVSimpleCore gr cw rw) (calcSDSimpleCore gc cw rw) (calcSDSimpleCore gr cw rw) cw rw\n\n            [[], [], r, []]      -> do -- the same as above, but cols fixed rows unfixed\n                let cols = map (\\(a, Just b) -> (a,b)) . nub . map fst4 $ r\n                let rows = nub . map (fst . snd4) $ r\n                let grid = transpose . chunksOf (length rows) $ r\n                let outsc = map (map thd4) grid\n                let outsr = map (map fth4) grid\n                let gc = fromLists outsc\n                let gr = fromLists outsr\n                \n                let rowStrats = map (pureStrategy . length $ rows) [0..length rows]\n                let evs = map (\\strat -> calcEVSimpleCore gr (map snd cols) strat) rowStrats\n                \n                let cw = map snd cols\n                let (rw, ev) = minimumBy (compare `on` snd) . zip rowStrats $ evs -- the defender wants to minimise the ev\n                ResultSimple (calcEVSimpleCore gc cw rw) ev (calcSDSimpleCore gc cw rw) (calcSDSimpleCore gr cw rw) cw rw\n\n            [[], [], [], neither]     -> do -- both are unfixed, so we just calculate it as a normal GameSimple\n                let cols = nub . map (fst . fst4) $ neither\n                let rows = nub . map (fst . snd4) $ neither\n                let grid = transpose . chunksOf (length rows) $ neither\n                let outsc = map (map thd4) grid\n                let outsr = map (map fth4) grid\n                \n                solveSimple outsc outsr\n                \n            _                      -> error \"both fixed and unfixed options for a single player\" -- no. don't. this makes no sense!!! the only reason i can even think you'd want to try is equivalent to just nesting in another mixup, so just do that.\n\nfst4 (x,_,_,_) = x\nsnd4 (_,x,_,_) = x\nthd4 (_,_,x,_) = x\nfth4 (_,_,_,x) = x\n", "meta": {"hexsha": "996a2b82603936cf90e5e8832ac92584f845c39d", "size": 14106, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Game.hs", "max_stars_repo_name": "StaccatoSemibreve/Mixup-Analyser", "max_stars_repo_head_hexsha": "50479a37f92ec8bed6a01e7d965edc582c19ad50", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Game.hs", "max_issues_repo_name": "StaccatoSemibreve/Mixup-Analyser", "max_issues_repo_head_hexsha": "50479a37f92ec8bed6a01e7d965edc582c19ad50", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Game.hs", "max_forks_repo_name": "StaccatoSemibreve/Mixup-Analyser", "max_forks_repo_head_hexsha": "50479a37f92ec8bed6a01e7d965edc582c19ad50", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4013157895, "max_line_length": 249, "alphanum_fraction": 0.5927264994, "num_tokens": 4057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.43180273372818545}}
{"text": "module Main where\n\nimport Numeric.LinearAlgebra\nimport Data.Function (on)\nimport Data.List (minimumBy)\n\nimport Lib\n\ntype MarcovChain = Vector R -> Vector R\n\ntype State = (Int,Int)\n\ntype Window = Int\n\ntype Steps = Int\n\ntype Data t = t State\n\ntype States t = t State\n\nclassify :: Steps -> [Double] -> [Int]\nclassify steps ds = map (roundToNearest . (* 100) . (/ maxValue)) ds\n  where\n    maxValue = maximum ds\n\n    increments = statePercents steps\n\n    roundToNearest :: Double -> Int\n    roundToNearest d = case dropWhile (\\(_,y) -> fromIntegral y <= d) $ zip increments (tail increments) of\n                          ((x,y):_) -> if d - fromIntegral x >= fromIntegral y - d then y else x\n                          _         -> last increments\n\nmakeMarcovChainFromData :: Foldable t => Window -> Steps -> Data t -> MarcovChain\nmakeMarcovChainFromData = undefined\n\nstateProduct :: Window -> Steps -> States []\nstateProduct winSize steps = [(i,j) | i <- statePercents steps, j <- [1..winSize]]\n\n\nstatePercents :: Steps -> [Int]\nstatePercents steps = [0,stepSize..200]\n  where\n    stepSize = round $ 200 / fromIntegral steps\n\npredict :: MarcovChain -> Vector R -> Vector R\npredict = ($)\n\nmain :: IO ()\nmain = print \"Crypto\"\n", "meta": {"hexsha": "07046a1411866b125774e2a9cd8184db7077c7b2", "size": 1220, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "FelixHolzwarth/MarkovPrediction", "max_stars_repo_head_hexsha": "ccbee88eaa7aa314f4fcf517714e5f1bf8403386", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "FelixHolzwarth/MarkovPrediction", "max_issues_repo_head_hexsha": "ccbee88eaa7aa314f4fcf517714e5f1bf8403386", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "FelixHolzwarth/MarkovPrediction", "max_forks_repo_head_hexsha": "ccbee88eaa7aa314f4fcf517714e5f1bf8403386", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4, "max_line_length": 107, "alphanum_fraction": 0.6459016393, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.43155954894175685}}
{"text": "module Statistics.Iteratee.Tests\n\nwhere\n\nimport Data.Iteratee as I\nimport Statistics.Iteratee as Si\nimport Statistics.Sample as St\nimport Test.Framework\nimport Test.Framework.Providers.QuickCheck2 (testProperty)\n\nimport Control.Monad.Identity\nimport qualified Data.Vector.Unboxed as V\n\ntests =\n  [ testGroup \"Sample\" $ map mkUnProp uns\n  ]\n\n-- Don't want to drag in more dependencies for just this.\nclass ApproxEq a where\n    approxEq :: Double -> a -> a -> Bool\n\ninstance ApproxEq Double where\n    approxEq tol d1 d2 = m == 0.0 || d/m < tol where\n      m = max (abs d1) (abs d2)\n      d = abs (d1 - d2)\n\ninstance (ApproxEq a, ApproxEq b) => ApproxEq (a,b) where\n    approxEq tol (l1,r1) (l2,r2) = approxEq tol l1 l2 && approxEq tol r1 r2\n\ninfix 4 ===\n(===) :: (ApproxEq a) => a -> a -> Bool\n(===) = approxEq {-pretty equal-}1.0e-10\n\nunsProp :: (ApproxEq a)\n        => (V.Vector Double -> a)\n        -> (Iteratee [Double] Identity a)\n        -> [Double]\n        -> Bool\nunsProp vec iter xs = if null xs then True\n    else vec (V.fromList xs) === (runIdentity $ run =<< enumPure1Chunk xs iter)\n    -- we're using Eq for doubles, which is always a bad idea...\n\n    -- also not checking empty vectors, because in some cases (range,\n    -- harmonicMean) we get NaN's or other funky values.\n\nmkUnProp (lbl, st, si) = testProperty lbl $ unsProp st si\n\n-- unary properties\nuns =\n  [ (\"mean\", St.mean, Si.mean)\n  , (\"range\", St.range, Si.range)\n  , (\"harmonic_mean\", St.harmonicMean, Si.harmonicMean)\n  , (\"variance\", St.fastVariance, Si.variance)\n  , (\"std_dev\", St.fastStdDev,   Si.stdDev)\n  ]\n", "meta": {"hexsha": "b4e5bf840f90f88bb80e9702744e689c83614299", "size": 1588, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Statistics/Iteratee/Tests.hs", "max_stars_repo_name": "JohnLato/iter-stats", "max_stars_repo_head_hexsha": "328bc988c8457904c863f721c686b3a296bc57d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-09T01:32:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-09T01:32:23.000Z", "max_issues_repo_path": "tests/Statistics/Iteratee/Tests.hs", "max_issues_repo_name": "JohnLato/iter-stats", "max_issues_repo_head_hexsha": "328bc988c8457904c863f721c686b3a296bc57d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Statistics/Iteratee/Tests.hs", "max_forks_repo_name": "JohnLato/iter-stats", "max_forks_repo_head_hexsha": "328bc988c8457904c863f721c686b3a296bc57d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-01-02T06:31:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T06:59:34.000Z", "avg_line_length": 28.3571428571, "max_line_length": 79, "alphanum_fraction": 0.6549118388, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.43105176511369364}}
{"text": "module HScheme.Parser where\n\nimport HScheme.Data\n\nimport Text.ParserCombinators.Parsec as P hiding ( spaces )\nimport Data.Char ( toUpper )\nimport Data.Ratio ( (%) )\nimport Data.Complex ( Complex((:+)) )\nimport Numeric ( readHex, readOct )\nimport Data.List ( foldl' )\nimport Control.Monad.Except\nimport qualified Data.Vector as V\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\nparseBool :: Parser Value\nparseBool = try $ do\n    char '#'\n    (char 't' >> return (Bool True)) <|> (char 'f' >> return (Bool False))\n\nparseString :: Parser Value\nparseString = do\n    char '\"'\n    x <- many (noneOf \"\\\"\" <|> escapeChar)\n    char '\"'\n    return $ String x\n    where\n        escapeChar :: Parser Char\n        escapeChar = do\n            oneOf \"nrt\\\\\" >>= \\case\n                'n' -> return '\\n'\n                'r' -> return '\\r'\n                't' -> return '\\t'\n                '\\\\'-> return '\\\\'\n\nparseChar :: Parser Value\nparseChar = do\n    try $ string \"#\\\\\"\n    chr <- (string \"newline\" <|> string \"space\") <|>\n        do\n            x <- anyChar \n            notFollowedBy alphaNum \n            return [x]\n    return $ Character $ case chr of\n        \"\\\\\" -> '\\n'\n        \"newline\" -> '\\n'\n        \"space\" -> ' '\n        _ -> head chr\n\nparseAtom :: Parser Value\nparseAtom = do\n    first <- letter <|> symbol\n    rest <- many (letter <|> digit <|> symbol)\n    let atom = first:rest\n    return $ case atom of\n        \"#t\" -> Bool True\n        \"#f\" -> Bool False\n        _    -> Atom atom\n\n{-\n    Parsing numbers\n-}\n\nparseDecimal :: Parser Value\nparseDecimal = do \n    sign <- option \"\" $ string \"-\" \n    many1 digit >>= (return . Number . read . (sign <>))\n\nparseDecimal' :: Parser Value\nparseDecimal' = try $ string \"#d\" >> many1 digit >>= (return . Number . read)\n\n-- | Parse hexadecimal number of form #x...\nparseHex :: Parser Value\nparseHex = try $ string \"#x\" >> many1 hexDigit >>= (return . Number . hexToDigit)\n    where\n        hexToDigit x = fst $ head $ readHex x\n\n-- | Parse octadecimal number of form #o...\nparseOct :: Parser Value\nparseOct = try $ string \"#o\" >> many1 octDigit >>= (return . Number . octToDigit)\n    where\n        octToDigit x = fst $ head $ readOct x\n\n-- | Parse binary of form #b...\nparseBin :: Parser Value\nparseBin = try $ string \"#b\" >> many1 (oneOf \"10\") >>= (return . Number . binToDigit)\n    where\n        binToDigit = foldl' binDigitToDigit 0\n            where\n                binDigitToDigit acc = \\case\n                    '1' -> 2 * acc + 1\n                    '0' -> 2 * acc + 0\n\nparseNumber :: Parser Value\nparseNumber = do\n    parseDecimal\n    <|> parseDecimal'\n    <|> parseHex\n    <|> parseOct\n    <|> parseBin\n\nparseFloat :: Parser Value\nparseFloat = try $ do\n    sign <- option \"\" $ string \"-\"\n    x <- many1 digit\n    y <- (:) <$> char '.' <*> many1 digit\n    return $ Float $ read $ sign <> x <> y\n\nparseRatio :: Parser Value\nparseRatio = try $ do\n    (Number x) <- parseDecimal\n    char '/'\n    (Number y) <- parseDecimal\n    return $ Ratio (x % y)\n\nparseComplex :: Parser Value\nparseComplex = try $ do\n    real <- parseFloat <|> parseNumber\n    char '+'\n    imiginary <- parseFloat <|> parseNumber\n    char 'i'\n    return $ Complex (toDouble real :+ toDouble imiginary)\n    where\n        toDouble (Float f) = realToFrac f\n        toDouble (Number n) = realToFrac n\n\nparseExpr :: Parser Value\nparseExpr = parseAtom\n    <|> parseString\n    <|> parseChar\n    <|> parseRatio\n    <|> parseComplex\n    <|> parseFloat\n    <|> parseNumber\n    <|> parseBool\n    <|> parseQuoted\n    <|> parseVector\n    <|> parseList\n\n{-\n    Recursive Parsers\n-}\n\nparseList :: Parser Value\nparseList = do\n    char '('\n    x <- try parseSpacesList <|> parseDottedList\n    char ')'\n    return x\n\nparseSpacesList :: Parser Value\nparseSpacesList = List <$> sepBy parseExpr spaces\n\nparseDottedList :: Parser Value\nparseDottedList = do\n    head <- endBy parseExpr spaces\n    tail <- char '.' >> spaces >> parseExpr\n    return $ DottedList head tail\n\nparseQuoted :: Parser Value\nparseQuoted = do\n    char '\\''\n    x <- parseExpr\n    return $ List [Atom \"quote\", x]\n\nparseVector :: Parser Value \nparseVector = do\n    try $ string \"#(\"\n    values <- sepBy parseExpr spaces\n    char ')'\n    return $ Vector (V.fromList values)\n\nreadExpr :: String -> ThrowsErr Value\nreadExpr input = case parse parseExpr \"\" input of\n    Left err -> throwError $ Parser err\n    Right val -> return val", "meta": {"hexsha": "025cb0c95122e6432682c66dd379da56eb350138", "size": 4455, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HScheme/Parser.hs", "max_stars_repo_name": "dvdvgt/hScheme", "max_stars_repo_head_hexsha": "861d1d22db332d0b2bc74a3544d6d77543fa7ca3", "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/HScheme/Parser.hs", "max_issues_repo_name": "dvdvgt/hScheme", "max_issues_repo_head_hexsha": "861d1d22db332d0b2bc74a3544d6d77543fa7ca3", "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/HScheme/Parser.hs", "max_forks_repo_name": "dvdvgt/hScheme", "max_forks_repo_head_hexsha": "861d1d22db332d0b2bc74a3544d6d77543fa7ca3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.75, "max_line_length": 85, "alphanum_fraction": 0.581369248, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.43084480683552956}}
{"text": "--Haskell Quil compiler\n--Copyright Laurence Emms 2018\n\nmodule Lib (compile) where\n\nimport Data.Complex\nimport Data.List\nimport Register\nimport Instruction\nimport ClassicalCircuit\nimport QuantumCircuit\nimport Util\n\ntestRXCircuit :: (Floating a, Show a, Ord a) => Circuit a\ntestRXCircuit = let parameters@[Left a] = [Left (MetaQubitRegister \"a\")]\n                    instructions = [(RX (ComplexConstant (5.0 :+ 10.0)) a)]\n                in Circuit \"TESTRX\" parameters instructions\n\nhadamardRotateXYZ :: (Floating a, Show a, Ord a) => Complex a -> Circuit a\nhadamardRotateXYZ rotation\n    = let parameters@[Left a, Left b, Right r, Left z] = [Left (MetaQubitRegister \"a\"), Left (MetaQubitRegister \"b\"), Right (MetaRegister \"r\"), Left (MetaQubitRegister \"z\")]\n          instructions = [(Hadamard a),\n                          (MeasureOut a r)] ++\n                          (ifC \"HROTXYZTHEN0\" \"HROTXYZEND0\"\n                               r\n                               [(RX (ComplexConstant rotation) z)]\n                               ([(Hadamard b),\n                                 (MeasureOut b r)] ++\n                                (ifC \"HROTXYZTHEN1\" \"HROTXYZEND1\"\n                                     r\n                                     [(RY (ComplexConstant rotation) z)]\n                                     [(RZ (ComplexConstant rotation) z)])))\n      in Circuit \"HROTXYZ\" parameters instructions\n\ncompile :: IO ()\ncompile = putStrLn \"Compiling quantum executable\" >>\n          --Test registers\n          putStrLn (show $ QubitRegister 10) >>\n          putStrLn (show $ Register 5) >>\n          putStrLn (show $ ComplexConstant (6.0 :+ 7.0)) >>\n          putStrLn (show $ ComplexConstant ((-8.0) :+ 1.0)) >>\n          putStrLn (show $ ComplexConstant (2.0 :+ (-3.0))) >>\n          putStrLn (show $ ComplexConstant ((-4.0) :+ (-6.0))) >>\n          --Test instructions\n          putStrLn (show $ CNot (QubitRegister 0) (QubitRegister 1)) >>\n          putStrLn (show $ PSwap (ComplexConstant (5.0 :+ (-3.2))) (QubitRegister 0) (QubitRegister 1)) >>\n          putStrLn (show $ Measure (QubitRegister 4)) >>\n          putStrLn (show $ MeasureOut (QubitRegister 4) (Register 5)) >>\n          --Test circuits\n          putStrLn (show $ DefCircuit bell) >>\n          putStrLn (show $ CallCircuit bell [Left (QubitRegister 5), Left (QubitRegister 3)]) >>\n          putStrLn (show $ DefCircuit testRXCircuit) >>\n          putStrLn (show $ CallCircuit testRXCircuit [Left (QubitRegister 1)]) >>\n          putStrLn (show $ DefCircuit xor) >>\n          putStrLn (show $ CallCircuit xor [Right (Register 0), Right (Register 1), Right (Register 2)]) >>\n          putStrLn (show $ DefCircuit halfAdder) >>\n          putStrLn (show $ CallCircuit halfAdder [Right (Register 0), Right (Register 1), Right (Register 2), Right (Register 3)]) >>\n          putStrLn (show $ DefCircuit adder) >>\n          putStrLn (show $ CallCircuit adder [Right (Register 0), Right (Register 1), Right (Register 2), Right (Register 3), Right (Register 4)]) >>\n          --Load the integer 53 into registers [0-31]\n          putStrLn (intercalate \"\\n\" (fmap show (loadIntToRegisters 53 0))) >>\n          --Load the integer 18 into registers [32-63]\n          putStrLn (intercalate \"\\n\" (fmap show (loadIntToRegisters 18 32))) >>\n          --Add [0-31] + [32-63] into [64-95]\n          let carry = 128\n              temp = 129\n          in putStrLn (intercalate \"\\n\" (fmap show (addRegisters carry temp 0 32 64))) >>\n          putStrLn (show $ DefCircuit (hadamardRotateXYZ (0.70710678118 :+ 0.70710678118))) >>\n          putStrLn (show $ CallCircuit (hadamardRotateXYZ (0.70710678118 :+ 0.70710678118)) [Left (QubitRegister 0), Left (QubitRegister 1), Right (Register 0), Left (QubitRegister 2)])\n", "meta": {"hexsha": "80d47f783eac9b8383e7485e2c2ef97891c86e45", "size": 3773, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "WhatTheFunctional/Hasquil", "max_stars_repo_head_hexsha": "e6b50fec6b779f8a8094ab5c52fdaa412b430829", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-06-08T09:02:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T14:09:15.000Z", "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "WhatTheFunctional/Hasquil", "max_issues_repo_head_hexsha": "e6b50fec6b779f8a8094ab5c52fdaa412b430829", "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/Lib.hs", "max_forks_repo_name": "WhatTheFunctional/Hasquil", "max_forks_repo_head_hexsha": "e6b50fec6b779f8a8094ab5c52fdaa412b430829", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-06-08T09:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T16:06:08.000Z", "avg_line_length": 53.9, "max_line_length": 185, "alphanum_fraction": 0.5767293931, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4307922789210955}}
{"text": "{-# LANGUAGE RecordWildCards #-}\nimport Data.Complex\nimport Control.Monad.Trans.Except\nimport Foreign.C.Types\nimport Data.Word\nimport System.IO\nimport Data.Monoid\n\nimport Control.Error.Util\nimport Data.Vector.Storable as VS hiding ((++))\nimport Data.Vector.Generic as VG hiding ((++))\nimport Pipes\nimport qualified Pipes.Prelude as P\nimport Foreign.Storable.Complex\n\nimport Options.Applicative\n\nimport SDR.Filter \nimport SDR.RTLSDRStream\nimport SDR.Util\nimport SDR.Demod\nimport SDR.Pulse\nimport SDR.Serialize\nimport SDR.ArgUtils\nimport SDR.CPUID\n\n--The filter coefficients are stored in another module\nimport Coeffs\n\ndata Options = Options {\n    frequency  :: Word32,\n    input      :: Maybe FilePath,\n    output     :: Maybe FilePath\n}\n\noptParser :: Parser Options\noptParser = Options \n          <$> option (fmap fromIntegral parseSize) (\n                 long \"frequency\"  \n              <> short 'f' \n              <> metavar \"FREQUENCY\" \n              <> help \"Frequency to tune to\"\n              )\n          <*> optional (strOption (\n                 long \"input\"   \n              <> short 'i' \n              <> metavar \"FILENAME\"  \n              <> help \"Input filename\"\n              ))\n          <*> optional (strOption (\n                 long \"output\"   \n              <> short 'o' \n              <> metavar \"FILENAME\"  \n              <> help \"Output filename\"\n              ))\n\nopt :: ParserInfo Options\nopt = info (helper <*> optParser) (fullDesc <> progDesc \"Receive and demodulate broadcast FM radio\" <> header \"RTLSDR FM\")\n\nbufNum     = 1\nbufLen     = 16384\nsamples    = fromIntegral (bufNum * bufLen) `quot` 2\ndecimation = 8\nsqd        = samples `quot` decimation\n\n{-\n    Sampling frequency of the input is 1280 khz\n    This is decimated by a factor of 8 and then demodulated\n    Sampling frequency of demodulated signal is 160 khz\n    Need audio output at 48 khz\n    Resampling factor is 48/160 == 3/10\n    FM pilot tone at 19khz (0.3958 * 48)\n    Start audio filter cutoff at 15khz (0.3125 * 48)\n-}\n\ndoIt Options{..} = do\n\n    info <- lift getCPUInfo\n\n    let rtlstream = do\n            str <- sdrStream (defaultRTLSDRParams frequency 1280000) bufNum bufLen\n            return $ str >-> P.map (interleavedIQUnsignedByteToFloatFast info) \n\n    let fileStream fname = lift $ do\n            h <- openFile fname ReadMode\n            return $ fromHandle samples h \n            --TODO: how do I ensure these handles get closed?\n\n    inputSpectrum <- maybe rtlstream fileStream input\n\n    let fileSink fname = do\n            h <- openFile fname ReadMode\n            return $ toHandle h \n\n    sink <- lift $ maybe pulseAudioSink fileSink output\n\n    deci <- lift $ fastDecimatorC info decimation coeffsRFDecim \n    resp <- lift $ fastResamplerR info 3 10 coeffsAudioResampler\n    filt <- lift $ fastFilterSymR info coeffsAudioFilter\n\n    --Build the pipeline\n    let pipeline :: Effect IO ()\n        pipeline =   inputSpectrum \n                 >-> firDecimator deci sqd \n                 >-> fmDemod\n                 >-> firResampler resp sqd \n                 >-> firFilter filt sqd\n                 >-> P.map (VG.map (* 0.2)) \n                 >-> sink\n\n    --Run the pipeline\n    lift $ runEffect pipeline\n\nmain = execParser opt >>= exceptT putStrLn return . doIt\n\n", "meta": {"hexsha": "05336b82d753c0469faacc9b469fb378a36df1e4", "size": 3278, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "fm/fm.hs", "max_stars_repo_name": "adamwalker/sdr-apps", "max_stars_repo_head_hexsha": "b44b9cac4f0ab857d5889141d94ae15aa3025896", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-06-04T20:12:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T03:45:31.000Z", "max_issues_repo_path": "fm/fm.hs", "max_issues_repo_name": "adamwalker/sdr-apps", "max_issues_repo_head_hexsha": "b44b9cac4f0ab857d5889141d94ae15aa3025896", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-06-04T20:11:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-11T14:58:03.000Z", "max_forks_repo_path": "fm/fm.hs", "max_forks_repo_name": "adamwalker/sdr-apps", "max_forks_repo_head_hexsha": "b44b9cac4f0ab857d5889141d94ae15aa3025896", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-08-05T07:05:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-13T00:56:23.000Z", "avg_line_length": 28.2586206897, "max_line_length": 122, "alphanum_fraction": 0.6116534472, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.43054810587291253}}
{"text": "{-# LANGUAGE Arrows              #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE RankNTypes          #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies        #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS -fplugin=Overloaded -fplugin-opt=Overloaded:Categories #-}\nmodule Main where\n\nimport Control.Monad      (when)\nimport Data.Word          (Word64)\nimport Numeric            (showFFloat)\nimport System.Environment (getArgs)\nimport Data.List (intercalate)\n\nimport qualified Control.Category\nimport qualified Numeric.LinearAlgebra  as LA\nimport qualified System.Random.SplitMix as SM\n\nimport Overloaded.Categories\nimport VectorSpace\n\n-- | A Function which computes value and derivative at the point.\nnewtype AD a b = AD (a -> (b, L a b))\n\ninstance Category AD where\n    id = AD (\\x -> (x, L id))\n\n    AD g . AD f = AD $ \\a ->\n        let (b, L f') = f a\n            (c, L g') = g b\n        in (c, L (g' . f'))\n\ninstance CategoryWith1 AD where\n    type Terminal AD = ()\n\n    terminal = AD (const ((), terminal))\n\ninstance CartesianCategory AD where\n    type Product AD = (,)\n\n    proj1 = AD (\\x -> (fst x, proj1))\n    proj2 = AD (\\x -> (snd x, proj2))\n\n    fanout (AD f) (AD g) = AD $ \\a ->\n        let (b, f') = f a\n            (c, g') = g a\n        in ((b, c), fanout f' g')\n\ninstance GeneralizedElement AD where\n    type Object AD a = a\n\n    konst x = AD (\\_ -> (x, L $ \\_ -> LZ))\n\nladd :: LinMap r (a, a) -> LinMap r a\nladd (LH f g) = LA f g\nladd (LV f g) = LV (ladd f) (ladd g)\nladd (LA a b) = LA (ladd a) (ladd b)\nladd LZ       = LZ\nladd (LD k)   = LV (LD k) (LD k)\n\nlmult :: Double -> Double -> LinMap r (a, a) -> LinMap r a\nlmult x y (LH f g) = LA (lmul y f) (lmul x g)\nlmult x y (LV f g) = LV (lmult x y f) (lmult x y g)\nlmult x y (LA f g) = LA (lmult x y f) (lmult x y g)\nlmult _ _ LZ       = LZ\nlmult x y (LD k)   = LV (LD (k * y)) (LD (k * x))\n\nplus :: AD (Double, Double) Double\nplus = AD $ \\(x,y) -> (x + y, L ladd)\n\nminus :: AD (Double, Double) Double\nminus = AD $ \\(x,y) -> (x - y, L $ lmult (-1) 1)\n\nmult :: AD (Double, Double) Double\nmult = AD $ \\(x,y) -> (x * y, L $ lmult x y)\n\nscale :: Double -> AD Double Double\nscale k = AD $ \\x -> (k * x, linear k)\n\nevaluateAD :: (HasDim a, HasDim b) => AD a b -> a -> (b, LA.Matrix Double)\nevaluateAD (AD f) x = let (y, f') = f x in (y, evalL f')\n\n-------------------------------------------------------------------------------\n-- Simple examples\n-------------------------------------------------------------------------------\n\nex1 :: AD Double Double\nex1 = plus %% fanout identity identity\n\nex2 :: AD Double Double\nex2 = mult %% fanout identity identity\n\n-------------------------------------------------------------------------------\n-- Quadratic function\n-------------------------------------------------------------------------------\n\nquad :: AD (Double, Double) Double\nquad = proc (x, y) -> do\n    x2  <- mult    -< (x, x)\n    y2  <- mult    -< (y, y)\n    tmp <- plus    -< (x2, y2)\n    z   <- konst 5 -< ()\n    plus -< (tmp, z)\n\n-------------------------------------------------------------------------------\n-- Newton\n-------------------------------------------------------------------------------\n\nfindZero :: AD Double Double -> Double -> [Double]\nfindZero f x0 = take 10 results\n  where\n    results = iterate go x0\n\n    go :: Double -> Double\n    go x =\n        let (y, m) = evaluateAD f x\n            [[y']] = LA.toLists m\n        in x - gamma * (y / y')\n\n    gamma = 0.1\n\n-------------------------------------------------------------------------------\n-- Gradient descent\n-------------------------------------------------------------------------------\n\ngradDesc :: forall a. VectorSpace a => AD a Double -> a -> [a]\ngradDesc f = iterate go where\n    go :: a -> a\n    go x =\n        let (_, m) = evaluateAD f x\n            [grad] = LA.toLists $ LA.tr $ LA.scale gamma m\n\n        in fromVector $ zipWith (-) (toVector x) grad\n\n    gamma = 0.1\n\n-------------------------------------------------------------------------------\n-- Random\n-------------------------------------------------------------------------------\n\nrandomDoubles :: Word64 -> [Double]\nrandomDoubles seed = go (SM.mkSMGen seed) where\n    go g = let (d, g') = SM.nextDouble g in d : go g'\n\n-------------------------------------------------------------------------------\n-- Dot\n-------------------------------------------------------------------------------\n\nclass VectorSpace' a where\n    sumN :: AD a Double\n    multN :: AD (a, a) a\n\ninstance (VectorSpace' a, VectorSpace' b) => VectorSpace' (a, b) where\n    sumN = proc (x, y) -> do\n        x' <- sumN -< x\n        y' <- sumN -< y\n        plus -< (x', y')\n\n    multN = proc ((x1, x2), (y1, y2)) -> do\n        z1 <- multN -< (x1, y1)\n        z2 <- multN -< (x2, y2)\n        identity -< (z1, z2)\n\ninstance VectorSpace' Double where\n    sumN  = identity\n    multN = mult\n\ndot :: VectorSpace' a => AD (a, a) Double\ndot = sumN %% multN\n\n-------------------------------------------------------------------------------\n-- ML stuff\n-------------------------------------------------------------------------------\n\ntanhAD :: AD Double Double\ntanhAD = AD $ \\x ->\n    let y = tanh x\n    in (y, linear (1 - y * y))\n\nsigmoidAD :: AD Double Double\nsigmoidAD = AD $ \\x ->\n    let y = 1 / (1 + exp (- x))\n    in (x, linear (y * (1 - y)))\n\n-- | weights for 2x1 connection. Two weights and bias.\ntype Weights' = ((Double, Double), Double)\n\n-- | Two internal neurons, and final output\ntype Weights = ((Weights', Weights'), Weights')\n\nstartWeights :: Weights\nstartWeights = fromVector $ randomDoubles 1337\n\nneuron :: AD (Weights', (Double, Double)) Double\nneuron = proc ((ws, bias), i) -> do\n    o <- dot -< (ws, i)\n    tanhAD %% plus -< (o, bias)\n\nnetwork :: AD (Weights, (Double, Double)) Double\nnetwork = proc (((w1, w2), w3), xy) -> do\n    u <- neuron  -< (w1, xy)\n    v <- neuron  -< (w2, xy)\n    neuron -< (w3, (u, v))\n\nnetworkError :: AD Weights Double\nnetworkError = proc ws -> do\n    -- xor!\n    s1 <- ex 1 1 0 -< ws\n    s2 <- ex 0 0 0 -< ws\n    s3 <- ex 1 0 1 -< ws\n    s4 <- ex 0 1 1 -< ws\n\n    sumN -< ((s1,s2), (s3, s4))\n  where\n    ex :: Double -> Double -> Double -> AD Weights Double\n    ex x y z = proc ws -> do\n         x1 <- konst x -< ()\n         y1 <- konst y -< ()\n         e1 <- konst z -< ()\n         a1 <- network -< (ws, (x1, y1))\n         r1 <- minus   -< (e1, a1)\n         mult -< (r1, r1)\n\ntrain :: Weights\ntrain = gradDesc networkError startWeights !! 500\n\n-------------------------------------------------------------------------------\n-- Main\n-------------------------------------------------------------------------------\n\nmain :: IO ()\nmain = do\n    putStrLn $ \"quad (2,3) = \" ++ show (evaluateAD quad (2,3))\n    putStrLn $ \"gradDesc quad (2,3) = \" ++ show (gradDesc quad (2,3) !! 30)\n\n    print $ evaluateAD tanhAD 1\n    print $ evaluateAD sigmoidAD 1\n\n    putStrLn \"Training the net (for xor)\"\n    let ws = train\n    putStrLn $ \"Parameters = \" ++ show (toVector ws)\n    putStrLn $ \"Error = \" ++ show (fst $ evaluateAD networkError ws)\n    let example xy =\n          putStrLn $ \"eval \" ++ show xy ++ \" = \" ++ showFFloat (Just 2) (fst $ evaluateAD network (ws, xy)) \"\"\n\n    example (0, 0)\n    example (0, 1)\n    example (1, 0)\n    example (1, 1)\n\n    args <- getArgs\n    when (\"plot\" `elem` args) $ do\n        putStrLn \"Outputting plot data: datafile.dat\"\n\n        let n = 20 :: Int\n        let points = [ fromIntegral x / fromIntegral n | x <- [0..n] ] :: [Double]\n\n        let output :: String\n            output = unlines\n                [ intercalate \"\\t\"\n                    [ show x\n                    , show y\n                    , show (fst (evaluateAD network (ws, (x, y))))\n                    ]\n                | x <- points\n                , y <- points\n                ]\n\n        writeFile \"datafile.dat\" output\n", "meta": {"hexsha": "9ef1a102564aed9bb420ede1c0d16acdd087b072", "size": 7841, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "example/AD.hs", "max_stars_repo_name": "Mikolaj/overloaded", "max_stars_repo_head_hexsha": "9290d9be88107c5032a4b229fd1d9ef177041c17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-09-08T14:56:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T01:13:15.000Z", "max_issues_repo_path": "example/AD.hs", "max_issues_repo_name": "Mikolaj/overloaded", "max_issues_repo_head_hexsha": "9290d9be88107c5032a4b229fd1d9ef177041c17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-09-17T00:58:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T10:40:44.000Z", "max_forks_repo_path": "example/AD.hs", "max_forks_repo_name": "Mikolaj/overloaded", "max_forks_repo_head_hexsha": "9290d9be88107c5032a4b229fd1d9ef177041c17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-14T23:17:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T23:17:25.000Z", "avg_line_length": 28.9335793358, "max_line_length": 110, "alphanum_fraction": 0.447519449, "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4305339932074079}}
{"text": "{-# LANGUAGE CPP                    #-}\n{-# LANGUAGE ConstraintKinds        #-}\n{-# LANGUAGE DataKinds              #-}\n{-# LANGUAGE DefaultSignatures      #-}\n{-# LANGUAGE FlexibleContexts       #-}\n{-# LANGUAGE FlexibleInstances      #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GADTs                  #-}\n{-# LANGUAGE MultiParamTypeClasses  #-}\n{-# LANGUAGE ParallelListComp       #-}\n{-# LANGUAGE PartialTypeSignatures  #-}\n{-# LANGUAGE PatternGuards          #-}\n{-# LANGUAGE Rank2Types             #-}\n{-# LANGUAGE ScopedTypeVariables    #-}\n{-# LANGUAGE TemplateHaskell        #-}\n{-# LANGUAGE TypeOperators          #-}\n{-# LANGUAGE TypeApplications       #-}\n{-# LANGUAGE TypeFamilies           #-}\n{-# LANGUAGE TypeSynonymInstances   #-}\n{-# LANGUAGE UndecidableInstances   #-} -- See below\n\n-- experiment\n-- {-# LANGUAGE PartialTypeSignatures #-}\n\n{-# OPTIONS_GHC -Wall #-}\n-- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP\n\n-- #define TESTING\n\n#ifdef TESTING\n{-# OPTIONS_GHC -fno-warn-unused-binds   #-} -- TEMP\n#endif\n\n-- #define GenericPowFFT\n\n----------------------------------------------------------------------\n-- | Generic FFT\n----------------------------------------------------------------------\n\nmodule ConCat.FFT\n  ( dft, FFT(..), DFTTy, genericFft, GFFT\n  -- -- Temporary while debugging\n  , twiddle, twiddles, omega, cis\n  , o8sq\n  ) where\n\nimport Prelude hiding (zipWith)\n\nimport Data.Complex\n-- import Control.Applicative (liftA2)\nimport GHC.Generics hiding (C,S)\n\nimport Data.Key (Zip(..))\nimport Data.Pointed\n\n#ifdef TESTING\nimport Data.Foldable (toList)\n-- import Test.QuickCheck (quickCheck)\nimport Test.QuickCheck.All (quickCheckAll)\nimport ShapedTypes.ApproxEq\n#endif\n\nimport ConCat.Misc (Unop,transpose,C,inGeneric1,inComp)\nimport ConCat.Sized\nimport ConCat.Scan (LScan,lproducts)\nimport ConCat.Pair\nimport ConCat.Free.LinearRow (($*))\n\n{--------------------------------------------------------------------\n    DFT\n--------------------------------------------------------------------}\n\ntype AS  h = (Pointed h, Zip h, LScan h)\ntype ASZ h = (AS h, Sized h)\n\n-- To resolve: Zip vs Applicative. traverse/transpose needs Applicative.\n\ndft :: forall f a. (ASZ f, Foldable f, RealFloat a) => Unop (f (Complex a))\ndft xs = omegas (size @f) $* xs\n{-# INLINE dft #-}\n\nomegas :: (AS f, AS g, RealFloat a) => Int -> g (f (Complex a))\nomegas = fmap powers . powers . omega\n-- omegas n = powers <$> powers (omega n)\n-- omegas n = powers <$> powers (exp (- i * 2 * pi / fromIntegral n))\n{-# INLINE omegas #-}\n\nomegas' :: forall f g a. (ASZ f, ASZ g, RealFloat a) => g (f (Complex a))\nomegas' = fmap powers (powers (cis (- 2 * pi / fromIntegral (size @(g :.: f)))))\n\n-- i :: Num a => Complex a\n-- i = 0 :+ 1\n\nomega :: RealFloat a => Int -> Complex a\nomega n = cis (- 2 * pi / fromIntegral n)\n-- omega n = exp (0 :+ (- 2 * pi / fromIntegral n))\n-- omega n = exp (- 2 * (0:+1) * pi / fromIntegral n)\n{-# INLINE omega #-}\n\n{--------------------------------------------------------------------\n    FFT\n--------------------------------------------------------------------}\n\ntype DFTTy f = forall a. RealFloat a => f (Complex a) -> FFO f (Complex a)\n\nclass FFT f where\n  type FFO f :: * -> *\n  fft :: DFTTy f\n  -- default fft :: ( Generic1 f, Generic1 (FFO f)\n  --                , FFT (Rep1 f), FFO (Rep1 f) ~ Rep1 (FFO f) ) => DFTTy f\n  -- fft = genericFft\n  -- Temporary hack to avoid newtype-like representation.\n  fftDummy :: f a\n  fftDummy = undefined\n\n-- TODO: Eliminate FFO, in favor of fft :: Unop (f (Complex a)).\n-- Use dft as spec.\n\ntwiddle :: forall g f a. (ASZ g, ASZ f, RealFloat a) => Unop (g (f (Complex a)))\n-- twiddle = (zipWith.zipWith) (*) twiddles\ntwiddle = (zipWith.zipWith) (*) omegas'\n-- twiddle = (zipWith.zipWith) (*) (omegas (size @(g :.: f)))\n{-# INLINE twiddle #-}\n\ntwiddles :: forall g f a. (ASZ g, ASZ f, RealFloat a) => g (f (Complex a))\ntwiddles = omegas (size @(g :.: f))\n{-# INLINE twiddles #-}\n\no8sq :: C\no8sq = omega (8 :: Int) ^ (2 :: Int)\n\n-- Powers of x, starting x^0. Uses 'LScan' for log parallel time\npowers :: (LScan f, Pointed f, Num a) => a -> f a\npowers = fst . lproducts . point\n{-# INLINE powers #-}\n\n-- TODO: Consolidate with powers in TreeTest and rename sensibly. Maybe use\n-- \"In\" and \"Ex\" suffixes to distinguish inclusive and exclusive cases.\n\n{--------------------------------------------------------------------\n    Generic support\n--------------------------------------------------------------------}\n\ninstance FFT Par1 where\n  type FFO Par1 = Par1\n  fft = id\n\n#if 0\ninTranspose :: (Traversable f', Traversable g, Applicative g', Applicative f)\n            => (f (g a) -> f' (g' a)) -> g (f a) -> g' (f' a)\ninTranspose = transpose <-- transpose\n\nffts' :: ( FFT g, Traversable f, Traversable g\n         , Applicative (FFO g), Applicative f, RealFloat a) =>\n     g (f (Complex a)) -> FFO g (f (Complex a))\nffts' = transpose . fmap fft . transpose\n#endif\n\n#if 0\n\ntranspose :: g (f C)     -> f (g C)\nfmap fft  :: f (g C)     -> f (FFO g C)\ntranspose :: f (FFO g C) -> FFO g (f C)\n\n#endif\n\ninstance ( Zip f,  Traversable f , Traversable g\n         , Applicative f, Applicative (FFO f), Applicative (FFO g), Zip (FFO g)\n         , Pointed f, Traversable (FFO g), Pointed (FFO g)\n         , FFT f, FFT g, LScan f, LScan (FFO g), Sized f, Sized (FFO g) )\n      => FFT (g :.: f) where\n  type FFO (g :.: f) = FFO f :.: FFO g\n  fft = inComp (traverse fft . twiddle . traverse fft . transpose)\n  -- fft = inComp (ffts' . transpose . twiddle . ffts')\n  {-# INLINE fft #-}\n\n#if 0\n  fft = Comp1 . transpose . fmap fft . twiddle . transpose . fmap fft . transpose . unComp1\n  fft = Comp1 . traverse fft . twiddle . traverse fft . transpose . unComp1\n\n-- Types in fft for (g :. f):\n  unComp1   :: (g :. f) a -> g  (f  a)\n  transpose :: g  (f  a)  -> f  (g  a)\n  fmap fft  :: f  (g  a)  -> f  (g' a)\n  transpose :: f  (g' a)  -> g' (f  a)\n  twiddle   :: g' (f  a)  -> g' (f  a)\n  fmap fft  :: g' (f  a)  -> g' (f' a)\n  transpose :: g' (f' a)  -> f' (g' a)\n  Comp1     :: f' (g' a)  -> (f' :. g') a\n#endif\n\n#if 0\n\n--   fft = inComp (ffts' . transpose . twiddle . ffts')\n\nffts'     :: g (f C)     -> FFO g (f C)\ntwiddle   :: FFO g (f C) -> FFO g (f C)\ntranspose :: FFO g (f C) -> f (FFO g C)\nffts'     :: f (FFO g C) -> FFO f (FFO g C)\n\n#endif\n\n-- -- Generalization of 'dft' to traversables. Note that liftA2 should\n-- -- work zippily (unlike with lists).\n-- dftT :: forall f a. (ASZ f, Traversable f, RealFloat a)\n--      => Unop (f (Complex a))\n-- dftT xs = out <$> indices\n--  where\n--    out k   = sum (liftA2 (\\ n x -> x * ok^n) indices xs) where ok = om ^ k\n--    indices = fst iota :: f Int\n--    om      = omega (size @f)\n-- {-# INLINE dftT #-}\n\n-- | Generic FFT\ngenericFft :: ( Generic1 f, Generic1 (FFO f)\n              , FFT (Rep1 f), FFO (Rep1 f) ~ Rep1 (FFO f) ) => DFTTy f\ngenericFft = inGeneric1 fft\n\ntype GFFT f = (Generic1 f, Generic1 (FFO f), FFT (Rep1 f), FFO (Rep1 f) ~ Rep1 (FFO f))\n\n#define GenericFFT(f,g) instance GFFT (f) => FFT (f) where { type FFO (f) = (g); fft = genericFft }\n\n-- #define GenericFFT(f,g) instance GFFT (f) => FFT (f) where { type FFO (f) = g; INLINE }\n\n-- TODO: Replace Applicative with Zippable.\n-- Can't, because Traversable needs Applicative.\n\n-- Perhaps dftT isn't very useful. Its result and argument types match, unlike fft.\n\n{--------------------------------------------------------------------\n    Specialized FFT instances.\n--------------------------------------------------------------------}\n\n-- I put the specific instances here in order to avoid an import loop between\n-- the LPow and RPow modules. I'd still like to find an elegant FFT that maps f\n-- to f, and then move the instances to RPow and LPow.\n\n-- Radix 2 butterfly\ninstance FFT Pair where\n  type FFO Pair = Pair\n  -- bogus \"non-exhaustive\" warning in ghc 8.0.2\n  -- fft (a :# b) = (a + b) :# (a - b)\n  fft = \\ (a :# b) -> (a + b) :# (a - b)\n  -- fft = dft\n  {-# INLINE fft #-}\n\n#ifdef TESTING\n\n#if 0\ntwiddles :: (ASZ g, ASZ f, RealFloat a) => g (f (Complex a))\n\nas :: f C\n(<.> as) :: f C -> C\ntwiddles :: f (f C)\n(<.> as) <$> twiddles :: f C\n#endif\n\n-- -- Binary dot product\n-- infixl 7 <.>\n-- (<.>) :: (Foldable f, Applicative f, Num a) => f a -> f a -> a\n-- u <.> v = sum (liftA2 (*) u v)\n\n{--------------------------------------------------------------------\n    Simple, quadratic DFT (for specification & testing)\n--------------------------------------------------------------------}\n\n-- Adapted from Dave's definition\ndftL :: RealFloat a => Unop [Complex a]\ndftL xs = [ sum [ x * ok^n | x <- xs | n <- [0 :: Int ..] ]\n          | k <- [0 .. length xs - 1], let ok = om ^ k ]\n where\n   om = omega (length xs)\n\n{--------------------------------------------------------------------\n    Tests\n--------------------------------------------------------------------}\n\n-- > powers 2 :: LTree N2 Int\n-- B (B (L ((1 :# 2) :# (4 :# 8))))\n-- > powers 2 :: LTree N3 Int\n-- B (B (B (L (((1 :# 2) :# (4 :# 8)) :# ((16 :# 32) :# (64 :# 128))))))\n\nfftl :: (FFT f, Foldable (FFO f), RealFloat a) => f (Complex a) -> [Complex a]\nfftl = toList . fft\n\ntype LTree = L.Pow Pair\ntype RTree = R.Pow Pair\n\ntype LC n = LTree n C\ntype RC n = RTree n C\n\np1 :: Pair C\np1 = 1 :# 0\n\ntw1 :: LTree N1 (Pair C)\ntw1 = twiddles\n\ntw2 :: RTree N2 (Pair C)\ntw2 = twiddles\n\ntw3 :: RTree N2 (RTree N2 C)\ntw3 = twiddles\n\ntw3' :: [[C]]\ntw3' = toList (toList <$> tw3)\n\n\n-- Adapted from Dave's testing\n\n-- test :: (FFT f, Foldable f, Foldable (FFO f)) => f C -> IO ()\n-- test fx =\n--   do ps \"\\nTesting input\" xs\n--      ps \"Expected output\" (dftL xs)\n--      ps \"Actual output  \" (toList (fft fx))\n--  where\n--    ps label z = putStrLn (label ++ \": \" ++ show z)\n--    xs = toList fx\n\n#if 0\nt0 :: LC N0\nt0 = L.fromList [1]\n\nt1 :: LC N1\nt1 = L.fromList [1, 0]\n\nt2s :: [LC N2]\nt2s = L.fromList <$>\n        [ [1,  0,  0,  0]  -- Delta\n        , [1,  1,  1,  1]  -- Constant\n        , [1, -1,  1, -1]  -- Nyquist\n        , [1,  0, -1,  0]  -- Fundamental\n        , [0,  1,  0, -1]  -- Fundamental w/ 90-deg. phase lag\n       ]\n\ntests :: IO ()\ntests = do test p1\n           test t0\n           test t1\n           mapM_ test t2s\n#endif\n\ninfix 4 ===\n(===) :: Eq b => (a -> b) -> (a -> b) -> a -> Bool\n(f === g) x = f x == g x\n\ninfix 4 =~=\n(=~=) :: ApproxEq b => (a -> b) -> (a -> b) -> a -> Bool\n(f =~= g) x = f x =~ g x\n\nfftIsDftL :: (FFT f, Foldable f, Foldable (FFO f), RealFloat a, ApproxEq a) =>\n             f (Complex a) -> Bool\nfftIsDftL = toList . fft =~= dftL . toList\n\ndftTIsDftL :: (ASZ f, Traversable f, RealFloat a, ApproxEq a) =>\n              f (Complex a) -> Bool\ndftTIsDftL = toList . dftT =~= dftL . toList\n\ndftIsDftL :: (ASZ f, Foldable f, RealFloat a, ApproxEq a) =>\n             f (Complex a) -> Bool\ndftIsDftL = toList . dft =~= dftL . toList\n\n-- -- TEMP:\n-- dftDft :: (ASZ f, Traversable f, RealFloat a, ApproxEq a) =>\n--           f (Complex a) -> ([Complex a], [Complex a])\n-- dftDft xs = (toList . dft $ xs, dftL . toList $ xs)\n\n{--------------------------------------------------------------------\n    Properties to test\n--------------------------------------------------------------------}\n\ntransposeTwiddleCommutes :: (ASZ g, Traversable g, ASZ f, (ApproxEq (f (g C))))\n                         => g (f C) -> Bool\ntransposeTwiddleCommutes =\n twiddle . transpose =~= transpose . twiddle\n\nprop_transposeTwiddle_L3P :: LTree N3 (Pair C) -> Bool\nprop_transposeTwiddle_L3P = transposeTwiddleCommutes\n\nprop_transposeTwiddle_R3P :: RTree N3 (Pair C) -> Bool\nprop_transposeTwiddle_R3P = transposeTwiddleCommutes\n\n-- dft tests fail. Hm!\n\n-- prop_dft_R3 :: RTree N3 C -> Bool\n-- prop_dft_R3 = dftIsDftL\n\n-- prop_dft_L3 :: LTree N3 C -> Bool\n-- prop_dft_L3 = dftIsDftL\n\nprop_dftT_p :: Pair C -> Bool\nprop_dftT_p = dftTIsDftL\n\nprop_dftT_L3 :: LTree N3 C -> Bool\nprop_dftT_L3 = dftTIsDftL\n\nprop_dftT_R3 :: RTree N3 C -> Bool\nprop_dftT_R3 = dftTIsDftL\n\nprop_fft_p :: Pair C -> Bool\nprop_fft_p = fftIsDftL\n\nprop_fft_L1 :: LTree N1 C -> Bool\nprop_fft_L1 = fftIsDftL\n\nprop_fft_L2 :: LTree N2 C -> Bool\nprop_fft_L2 = fftIsDftL\n\nprop_fft_L3 :: LTree N3 C -> Bool\nprop_fft_L3 = fftIsDftL\n\nprop_fft_L4 :: LTree N4 C -> Bool\nprop_fft_L4 = fftIsDftL\n\nprop_fft_R1 :: RTree N1 C -> Bool\nprop_fft_R1 = fftIsDftL\n\nprop_fft_R2 :: RTree N2 C -> Bool\nprop_fft_R2 = fftIsDftL\n\nprop_fft_R3 :: RTree N3 C -> Bool\nprop_fft_R3 = fftIsDftL\n\nprop_fft_R4 :: RTree N4 C -> Bool\nprop_fft_R4 = fftIsDftL\n\n-- TH oddity\nreturn []\n\nrunTests :: IO Bool\nrunTests = $quickCheckAll\n\n-- end of tests\n#endif\n\n", "meta": {"hexsha": "0a1eb6a0c0cfac7dec2f93640ab9ce7d1650b131", "size": 12528, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/src/ConCat/FFT.hs", "max_stars_repo_name": "kenranunderscore/concat", "max_stars_repo_head_hexsha": "632c3f37a969725053dc55ebec26f5b7aacf8c07", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-11T10:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:54:10.000Z", "max_issues_repo_path": "examples/src/ConCat/FFT.hs", "max_issues_repo_name": "con-kitty/concat", "max_issues_repo_head_hexsha": "6321dab53677de419f1b57302fe343c5a1341768", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/src/ConCat/FFT.hs", "max_forks_repo_name": "con-kitty/concat", "max_forks_repo_head_hexsha": "6321dab53677de419f1b57302fe343c5a1341768", "max_forks_repo_licenses": ["BSD-3-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.8, "max_line_length": 99, "alphanum_fraction": 0.5353607918, "num_tokens": 3996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4305339932074079}}
{"text": "module TextHistogram (\n  printHistogram,\n) where\n\nimport           Control.Monad (forM_, when)\nimport           Statistics.Test.ApproxRand\nimport           System.IO (hPutStrLn, stderr)\nimport           Text.Printf (printf)\n\nimport           Histogram\n\nprintHistogram :: Int -> TestResult -> IO ()\nprintHistogram bins result@(TestResult _ score _) =\n  case histogram bins result of\n    Left err   -> hPutStrLn stderr err\n    Right hist ->\n      let bucketSize = (fst $ hist !! 1) - (fst $ head hist)\n          bucketHalf = bucketSize / 2\n          charsPerDot = (maximum $ map snd hist) `div` 50 in\n            forM_ hist $ \\(label, freq) -> do\n              let blocks = freq `div` charsPerDot\n              when (blocks > 0) $ do\n                let lower = label - bucketHalf\n                let barChar = if score >= lower && score < lower + bucketSize then\n                            '\u2723'\n                          else\n                            '\u2588'\n                putStr $ printf \"%12.3e | \" $ lower + bucketHalf\n                putStrLn $ replicate blocks barChar\n\n", "meta": {"hexsha": "c158d96bb8a500565b57e45f70496baf4aa48573", "size": 1075, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "utils/TextHistogram.hs", "max_stars_repo_name": "danieldk/approx-rand-test", "max_stars_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-15T18:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-15T18:15:56.000Z", "max_issues_repo_path": "utils/TextHistogram.hs", "max_issues_repo_name": "danieldk/approx-rand-test", "max_issues_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/TextHistogram.hs", "max_forks_repo_name": "danieldk/approx-rand-test", "max_forks_repo_head_hexsha": "0bfc9a3f16381960bb0420264915f2baf2eea175", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6774193548, "max_line_length": 82, "alphanum_fraction": 0.5320930233, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.43051245090979035}}
{"text": "module STCR2Z2T0S0Edge where\n\nimport           Control.Arrow\nimport           Control.Monad\nimport           Data.Array.Repa         as R\nimport           Data.Binary             (decodeFile)\nimport           Data.Complex\nimport           Data.List               as L\nimport           DFT.Plan\nimport           Filter.Utils\nimport           FokkerPlanck.MonteCarlo\nimport           FokkerPlanck.Pinwheel\nimport           Image.Edge\nimport           Image.IO\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Types\n\n\nmain = do\n  args@(numPointStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:taoStr:numTrailStr:maxTrailStr:thetaFreqsStr:scaleFreqsStr:histFilePath:numIterationStr:writeSourceFlagStr:edgeFilePath:numNoisePointStr:scaleFactorStr:useFFTWWisdomFlagStr:fftwWisdomFileName:numThreadStr:_) <-\n    getArgs\n  print args\n  let numPoint = read numPointStr :: Int\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      maxScale = read maxScaleStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scaleFreq = read scaleFreqsStr :: Double\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      numIteration = read numIterationStr :: Int\n      writeSourceFlag = read writeSourceFlagStr :: Bool\n      numNoisePoint = read numNoisePointStr :: Int\n      scaleFactor = read scaleFactorStr :: Double\n      useFFTWWisdomFlag = read useFFTWWisdomFlagStr :: Bool\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/STCR2Z2T0S0Edge\"\n      fftwWisdomFilePath = folderPath </> fftwWisdomFileName\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  radialArr <-\n    if flag\n      then R.map magnitude . getNormalizedHistogramArr <$>\n           decodeFile histFilePath\n      else do\n        putStrLn \"Couldn't find a Green's function data. Start simulation...\"\n        solveMonteCarloR2Z2T0S0Radial\n          numThread\n          numTrail\n          maxTrail\n          numPoint\n          numPoint\n          thetaSigma\n          scaleSigma\n          maxScale\n          tao\n          thetaFreqs\n          thetaFreqs\n          scaleFreqs\n          scaleFreqs\n          histFilePath\n          (emptyHistogram\n             [ (round . sqrt . fromIntegral $ 2 * (div numPoint 2) ^ 2)\n             , L.length scaleFreqs\n             , L.length thetaFreqs\n             , L.length scaleFreqs\n             , L.length thetaFreqs\n             ]\n             0)\n  arrR2Z2T0S0 <-\n    computeUnboxedP $\n    computeR2Z2T0S0ArrayRadial\n      (PinwheelHollow0 4)\n      radialArr\n      numPoint\n      numPoint\n      1\n      maxScale\n      thetaFreqs\n      scaleFreqs\n      thetaFreqs\n      scaleFreqs\n  plan <-\n    makeR2Z2T0S0Plan emptyPlan useFFTWWisdomFlag fftwWisdomFilePath arrR2Z2T0S0\n  xs <- parseEdgeFile edgeFilePath\n  randomPonintSet <- generateRandomPointSet numNoisePoint numPoint numPoint\n  let (centerX, centerY) =\n        join (***) (\\x -> div x . L.length $ xs) .\n        L.foldl' (\\(a, b) (R2S1RPPoint (c, d, _, _)) -> (a + c, b + d)) (0, 0) $\n        xs\n      ys =\n        L.map\n          (\\(R2S1RPPoint (a, b, c, d)) ->\n             (R2S1RPPoint\n                ( round $ (fromIntegral $ a - centerX) / scaleFactor\n                , round $ (fromIntegral $ b - centerX) / scaleFactor\n                , c\n                , d)))\n          xs\n      zs =\n        L.map\n          (\\(R2S1RPPoint (a, b, c, d)) ->\n             (R2S1RPPoint (a - center numPoint, b - center numPoint, c, d)))\n          randomPonintSet\n      points = ys L.++ zs\n  let bias = computeBiasR2T0S0 numPoint numPoint thetaFreqs scaleFreqs points\n      eigenVec =\n        computeInitialEigenVectorR2T0S0\n          numPoint\n          numPoint\n          thetaFreqs\n          scaleFreqs\n          thetaFreqs\n          scaleFreqs\n          points\n  powerMethodR2Z2T0S0\n    plan\n    folderPath\n    numPoint\n    numPoint\n    numOrientation\n    thetaFreqs\n    numScale\n    scaleFreqs\n    maxScale\n    arrR2Z2T0S0\n    numIteration\n    writeSourceFlag\n    (printf\n       \"_%d_%d_%.2f_%.2f\"\n       (round maxScale :: Int)\n       (round tao :: Int)\n       thetaSigma\n       scaleSigma)\n    bias\n    eigenVec\n", "meta": {"hexsha": "7b793fc1884931c99f39c792da116c2c898df9af", "size": 4559, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCR2Z2T0S0Edge/STCR2Z2T0S0Edge.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/STCR2Z2T0S0Edge/STCR2Z2T0S0Edge.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/STCR2Z2T0S0Edge/STCR2Z2T0S0Edge.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.2260273973, "max_line_length": 300, "alphanum_fraction": 0.6049572275, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694177, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.4302919071792168}}
{"text": "{-# LANGUAGE DataKinds                  #-}\n{-# LANGUAGE FlexibleContexts           #-}\n{-# LANGUAGE FlexibleInstances          #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MagicHash                  #-}\n{-# LANGUAGE MultiParamTypeClasses      #-}\n{-# LANGUAGE StandaloneDeriving         #-}\n{-# LANGUAGE TypeFamilies               #-}\n{-# LANGUAGE TypeInType                 #-}\n{-# LANGUAGE UnboxedTuples              #-}\n{-# LANGUAGE UndecidableInstances       #-}\n{-# LANGUAGE ViewPatterns               #-}\n{-# OPTIONS_GHC -fno-warn-orphans       #-}\nmodule Numeric.Quaternion.Internal.QDouble\n    ( QDouble, Quater (..)\n    ) where\n\nimport qualified Control.Monad.ST                     as ST\nimport           Data.Coerce                          (coerce)\nimport           Numeric.Basics\nimport           Numeric.DataFrame.Internal.PrimArray\nimport qualified Numeric.DataFrame.ST                 as ST\nimport           Numeric.DataFrame.Type\nimport           Numeric.Quaternion.Internal\nimport           Numeric.Vector.Internal\n\ntype QDouble = Quater Double\n\nderiving instance PrimBytes (Quater Double)\nderiving instance PrimArray Double (Quater Double)\n\ninstance Quaternion Double where\n    newtype Quater Double = QDouble (Vector Double 4)\n    {-# INLINE packQ #-}\n    packQ = coerce (vec4 :: Double -> Double -> Double -> Double -> Vector Double 4)\n    {-# INLINE unpackQ# #-}\n    unpackQ# = coerce (unpackV4# :: Vector Double 4 -> (# Double, Double, Double, Double #))\n    {-# INLINE fromVecNum #-}\n    fromVecNum (unpackV3# -> (# x, y, z #))  = packQ x y z\n    {-# INLINE fromVec4 #-}\n    fromVec4 = coerce\n    {-# INLINE toVec4 #-}\n    toVec4 = coerce\n    {-# INLINE square #-}\n    square (unpackQ# -> (# x, y, z, w #)) = (x * x) + (y * y) + (z * z) + (w * w)\n    {-# INLINE im #-}\n    im (unpackQ# -> (# x, y, z, _ #)) = packQ x y z 0.0\n    {-# INLINE re #-}\n    re (unpackQ# -> (# _, _, _, w #)) = packQ 0 0 0 w\n    {-# INLINE imVec #-}\n    imVec (unpackQ# -> (# x, y, z, _ #)) = vec3 x y z\n    {-# INLINE taker #-}\n    taker (unpackQ# -> (# _, _, _, w #)) = w\n    {-# INLINE takei #-}\n    takei (unpackQ# -> (# x, _, _, _ #)) = x\n    {-# INLINE takej #-}\n    takej (unpackQ# -> (# _, y, _, _ #)) = y\n    {-# INLINE takek #-}\n    takek (unpackQ# -> (# _, _, z, _ #)) = z\n    {-# INLINE conjugate #-}\n    conjugate (unpackQ# -> (# x, y, z, w #))\n      = packQ (negate x) (negate y) (negate z) w\n    {-# INLINE rotScale #-}\n    rotScale (unpackQ# -> (# i, j, k, t #))\n             (unpackV3# -> (# x, y, z #))\n      = let l = t*t - i*i - j*j - k*k\n            d = 2.0 * ( i*x + j*y + k*z)\n            t2 = t * 2.0\n        in vec3 (l*x + d*i + t2 * (z*j - y*k))\n                (l*y + d*j + t2 * (x*k - z*i))\n                (l*z + d*k + t2 * (y*i - x*j))\n    {-# INLINE getRotScale #-}\n    getRotScale a b = case (# unpackV3# a, unpackV3# b #) of\n      (# _, (# 0, 0, 0 #) #) -> packQ 0 0 0 0\n      (# (# 0, 0, 0 #), _ #) -> let x = (1 / 0 :: Double) in packQ x x x x\n      (# (# a1, a2, a3 #), (# b1, b2, b3 #) #) ->\n        let ma = sqrt (a1*a1 + a2*a2 + a3*a3)\n            mb = sqrt (b1*b1 + b2*b2 + b3*b3)\n            d  = a1*b1 + a2*b2 + a3*b3\n            c  = sqrt (ma*mb + d)\n            ma2 = ma * 1.4142135623730951 -- sqrt 2.0\n            r  = recip (ma2 * c)\n            c' = sqrt (mb / ma) -- ratio of a and b for corner cases\n            r' = recip (sqrt ( negate (a1*b1 + a2*b2) ))\n        in case unpackV3# (cross a b) of\n          (# 0, 0, 0 #)\n              -- if a and b face the same direction, q is fully real\n            | d >= 0       -> packQ 0 0 0 c'\n              -- if a and b face opposite directions, find an orthogonal vector\n              -- prerequisites: w == 0  and  a\u00b7(x,y,z) == 0\n              -- corner cases: only one vector component is non-zero\n            | b1 == 0      -> packQ c' 0 0 0\n              -- otherwise set the last component to zero,\n              -- and get an orthogonal vector in 2D.\n            | otherwise    -> packQ (-b2*r') (b1*r') 0 0\n              -- NB: here we have some precision troubles\n              --     when a and b are close to parallel and opposite.\n          (# t1, t2, t3 #) -> packQ (t1 * r) (t2 * r) (t3 * r) (c / ma2)\n    {-# INLINE axisRotation #-}\n    axisRotation v a = case unpackV3# v of\n      (# 0, 0, 0 #) -> packQ 0 0 0 (negateUnless (abs a < M_PI) 1)\n      (# x, y, z #) ->\n        let c = cos (a * 0.5)\n            s = sin (a * 0.5)\n                / sqrt (x*x + y*y + z*z)\n        in packQ (x * s) (y * s) (z * s) c\n    {-# INLINE qArg #-}\n    qArg (unpackQ# -> (# x, y, z, w #)) = 2 * atan2 (sqrt (x*x + y*y + z*z)) w\n    {-# INLINE fromMatrix33 #-}\n    fromMatrix33 m = fromM 1\n      (ix# 0# m) (ix# 1# m) (ix# 2# m)\n      (ix# 3# m) (ix# 4# m) (ix# 5# m)\n      (ix# 6# m) (ix# 7# m) (ix# 8# m)\n\n    {-# INLINE fromMatrix44 #-}\n    fromMatrix44 m = fromM (ix# 15# m)\n      (ix# 0# m) (ix# 1# m) (ix# 2# m)\n      (ix# 4# m) (ix# 5# m) (ix# 6# m)\n      (ix# 8# m) (ix# 9# m) (ix# 10# m)\n\n    {-# INLINE toMatrix33 #-}\n    toMatrix33 (unpackQ# -> (# 0.0, 0.0, 0.0, w #))\n      = let x = w * w\n            f 0 = (# 3 :: Int , x #)\n            f k = (# k-1, 0 #)\n        in case gen# (CumulDims [9,3,1]) f 0 of\n            (# _, m #) -> m -- diag (scalar (w * w))\n    toMatrix33 (unpackQ# -> (# x', y', z', w' #)) =\n      let x = scalar x'\n          y = scalar y'\n          z = scalar z'\n          w = scalar w'\n          x2 = x * x\n          y2 = y * y\n          z2 = z * z\n          w2 = w * w\n          l2 = x2 + y2 + z2 + w2\n      in ST.runST $ do\n        df <- ST.newDataFrame\n        ST.writeDataFrameOff df 0 $ l2 - 2*(z2 + y2)\n        ST.writeDataFrameOff df 1 $ 2*(x*y + z*w)\n        ST.writeDataFrameOff df 2 $ 2*(x*z - y*w)\n        ST.writeDataFrameOff df 3 $ 2*(x*y - z*w)\n        ST.writeDataFrameOff df 4 $ l2 - 2*(z2 + x2)\n        ST.writeDataFrameOff df 5 $ 2*(y*z + x*w)\n        ST.writeDataFrameOff df 6 $ 2*(x*z + y*w)\n        ST.writeDataFrameOff df 7 $ 2*(y*z - x*w)\n        ST.writeDataFrameOff df 8 $ l2 - 2*(y2 + x2)\n        ST.unsafeFreezeDataFrame df\n    {-# INLINE toMatrix44 #-}\n    toMatrix44 (unpackQ# -> (# 0.0, 0.0, 0.0, w #)) = ST.runST $ do\n      df <- ST.newDataFrame\n      mapM_ (flip (ST.writeDataFrameOff df) 0) [0..15]\n      let w2 = scalar (w * w)\n      ST.writeDataFrameOff df 0 w2\n      ST.writeDataFrameOff df 5 w2\n      ST.writeDataFrameOff df 10 w2\n      ST.writeDataFrameOff df 15 1\n      ST.unsafeFreezeDataFrame df\n    toMatrix44 (unpackQ# -> (# x', y', z', w' #)) =\n      let x = scalar x'\n          y = scalar y'\n          z = scalar z'\n          w = scalar w'\n          x2 = x * x\n          y2 = y * y\n          z2 = z * z\n          w2 = w * w\n          l2 = x2 + y2 + z2 + w2\n      in ST.runST $ do\n        df <- ST.newDataFrame\n        ST.writeDataFrameOff df 0 $ l2 - 2*(z2 + y2)\n        ST.writeDataFrameOff df 1 $ 2*(x*y + z*w)\n        ST.writeDataFrameOff df 2 $ 2*(x*z - y*w)\n        ST.writeDataFrameOff df 3 0\n        ST.writeDataFrameOff df 4 $ 2*(x*y - z*w)\n        ST.writeDataFrameOff df 5 $ l2 - 2*(z2 + x2)\n        ST.writeDataFrameOff df 6 $ 2*(y*z + x*w)\n        ST.writeDataFrameOff df 7 0\n        ST.writeDataFrameOff df 8 $ 2*(x*z + y*w)\n        ST.writeDataFrameOff df 9 $ 2*(y*z - x*w)\n        ST.writeDataFrameOff df 10 $ l2 - 2*(y2 + x2)\n        ST.writeDataFrameOff df 11 0\n        ST.writeDataFrameOff df 12 0\n        ST.writeDataFrameOff df 13 0\n        ST.writeDataFrameOff df 14 0\n        ST.writeDataFrameOff df 15 1\n        ST.unsafeFreezeDataFrame df\n\n\n{- Calculate quaternion from a 3x3 matrix.\n\n   First argument is a constant; it is either 1 for a 3x3 matrix,\n   or m44 for a 4x4 matrix. I just need to multiply all components by\n   this number.\n\n   Further NB for the formulae:\n\n   d == square q == det m ** (1/3)\n   t == trace m  == 4 w w - d\n   m01 - m10 == 4 z w\n   m20 - m02 == 4 y w\n   m12 - m21 == 4 x w\n   m01 + m10 == 4 x y\n   m20 + m02 == 4 x z\n   m12 + m21 == 4 y z\n   m00 == + x x - y y - z z + w w\n   m11 == - x x + y y - z z + w w\n   m22 == - x x - y y + z z + w w\n   4 x x == d + m00 - m11 - m22\n   4 y y == d - m00 + m11 - m22\n   4 z z == d - m00 - m11 + m22\n   4 w w == d + m00 + m11 + m22\n -}\nfromM :: Double\n      -> Double -> Double -> Double\n      -> Double -> Double -> Double\n      -> Double -> Double -> Double\n      -> QDouble\nfromM c'\n  m00 m01 m02\n  m10 m11 m12\n  m20 m21 m22\n    | t > 0\n      = let dd = sqrt ( d + t )\n            is = c / dd\n        in packQ ((m12 - m21)*is) ((m20 - m02)*is) ((m01 - m10)*is) (c*dd)\n    | m00 > m11 && m00 > m22\n      = let dd = sqrt ( d + m00 - m11 - m22 )\n            is = c / dd\n        in packQ (c*dd) ((m01 + m10)*is) ((m02 + m20)*is) ((m12 - m21)*is)\n    | m11 > m22\n      = let dd = sqrt ( d - m00 + m11 - m22 )\n            is = c / dd\n        in packQ ((m01 + m10)*is) (c*dd) ((m12 + m21)*is) ((m20 - m02)*is)\n    | otherwise\n      = let dd = sqrt ( d - m00 - m11 + m22 )\n            is = c / dd\n        in packQ ((m02 + m20)*is) ((m12 + m21)*is) (c*dd) ((m01 - m10)*is)\n\n  where\n    -- normalizing constant\n    c = recip $ 2 * sqrt c'\n    -- trace\n    t = m00 + m11 + m22\n    -- cubic root of determinant\n    d = ( m00 * ( m11 * m22 - m12 * m21 )\n        - m01 * ( m10 * m22 - m12 * m20 )\n        + m02 * ( m10 * m21 - m11 * m20 )\n        ) ** 0.33333333333333333333333333333333\n\n\n\n\ninstance Num QDouble where\n    QDouble a + QDouble b\n      = QDouble (a + b)\n    {-# INLINE (+) #-}\n    QDouble a - QDouble b\n      = QDouble (a - b)\n    {-# INLINE (-) #-}\n    (unpackQ# -> (# a1, a2, a3, a4 #)) * (unpackQ# -> (# b1, b2, b3, b4 #))\n      = packQ ((a4 * b1) + (a1 * b4) + (a2 * b3) - (a3 * b2))\n              ((a4 * b2) - (a1 * b3) + (a2 * b4) + (a3 * b1))\n              ((a4 * b3) + (a1 * b2) - (a2 * b1) + (a3 * b4))\n              ((a4 * b4) - (a1 * b1) - (a2 * b2) - (a3 * b3))\n    {-# INLINE (*) #-}\n    negate (QDouble a) = QDouble (negate a)\n    {-# INLINE negate #-}\n    abs = packQ 0 0 0 . sqrt . square\n    {-# INLINE abs #-}\n    signum q@(unpackQ# -> (# x, y, z, w #))\n      | qd == 0   = q\n      | otherwise = case ix + iy + iz + iw + nn of\n        0 -> packQ (x * l) (y * l) (z * l) (w * l)\n        1 -> packQ (copysign 1 x) 0 0 0\n        2 -> packQ 0 (copysign 1 y) 0 0\n        4 -> packQ 0 0 (copysign 1 z) 0\n        8 -> packQ 0 0 0 (copysign 1 w)\n        _ -> packQ n n n n\n      where\n        n  = 0 / 0 :: Double\n        qd = x*x + y*y + z*z + w*w\n        ix = if isInfinite x then 1 else 0 :: Int\n        iy = if isInfinite y then 2 else 0 :: Int\n        iz = if isInfinite z then 4 else 0 :: Int\n        iw = if isInfinite w then 8 else 0 :: Int\n        nn = if isNaN x || isNaN y || isNaN z || isNaN w then 16 else 0 :: Int\n        l  = recip (sqrt qd)\n    {-# INLINE signum #-}\n    fromInteger = packQ 0 0 0 . fromInteger\n    {-# INLINE fromInteger #-}\n\n\ninstance Fractional QDouble where\n    {-# INLINE recip #-}\n    recip q@(unpackQ# -> (# x, y, z, w #)) = case negate (recip (square q)) of\n      c -> packQ (x * c) (y * c) (z * c) (negate (w * c))\n    {-# INLINE (/) #-}\n    a / b = a * recip b\n    {-# INLINE fromRational #-}\n    fromRational = packQ 0 0 0 . fromRational\n\n\ninstance Floating QDouble where\n    {-# INLINE pi #-}\n    pi = packQ 0 0 0 M_PI\n    {-# INLINE exp #-}\n    exp (unpackQ# -> (# x, y, z, w #))\n      | mv2 == 0  = packQ x y z ew\n      | otherwise = packQ (x * l) (y * l) (z * l) arg\n      where\n        mv2 = (x * x) + (y * y) + (z * z)\n        mv  = sqrt mv2\n        ew  = exp w\n        l   = ew * sin mv / mv\n        arg = ew * cos mv\n    {-# INLINE log #-}\n    log = log' (Vec3 1 0 0)\n    {-# INLINE sqrt #-}\n    sqrt = sqrt' (Vec3 1 0 0)\n    {-# INLINE sin #-}\n    sin (unpackQ# -> (# x, y, z, w #))\n      | mv2 == 0  = packQ x y z (sin w)\n      | otherwise = packQ (x * l) (y * l) (z * l) arg\n      where\n        mv2 = (x * x) + (y * y) + (z * z)\n        mv  = sqrt mv2\n        l   = cos w * sinh mv / mv\n        arg = sin w * cosh mv\n    {-# INLINE cos #-}\n    cos (unpackQ# -> (# x, y, z, w #))\n      | mv2 == 0  = packQ x y z (cos w)\n      | otherwise = packQ (x * l) (y * l) (z * l) arg\n      where\n        mv2 = (x * x) + (y * y) + (z * z)\n        mv  = sqrt mv2\n        l   = sin w * sinh mv / negate mv\n        arg = cos w * cosh mv\n    {-# INLINE tan #-}\n    tan (unpackQ# -> (# x, y, z, w #))\n      | mv2 == 0       = packQ x y z (tan w)\n      | isInfinite mv2 = signum (packQ x y z 0)\n      | otherwise      = packQ (x * l) (y * l) (z * l) arg\n      where\n        mv2 = (x * x) + (y * y) + (z * z)\n        mv = sqrt mv2\n        b = 2*mv\n        a = 2*w\n        sina = sin a\n        eb = exp (-b)\n        eb2 = eb*eb\n        d = 1 + eb2 + 2 * eb * cos a\n        rd = recip d\n        pa = M_PI - abs a\n        rd' = 2 / (b*b + pa*pa)\n        (l, arg) =\n          if d >= M_EPS\n          then ((1 - eb2) * rd / mv, 2 * sina * eb * rd)\n          else (2 * rd' , negate sina * rd')\n    {-# INLINE sinh #-}\n    sinh (unpackQ# -> (# x, y, z, w #))\n      | mv2 == 0  = packQ x y z (sinh w)\n      | otherwise = packQ (x * l) (y * l) (z * l) arg\n      where\n        mv2 = (x * x) + (y * y) + (z * z)\n        mv  = sqrt mv2\n        l   = cosh w * sin mv / mv\n        arg = sinh w * cos mv\n    {-# INLINE cosh #-}\n    cosh (unpackQ# -> (# x, y, z, w #))\n      | mv2 == 0  = packQ x y z (cosh w)\n      | otherwise = packQ (x * l) (y * l) (z * l) arg\n      where\n        mv2 = (x * x) + (y * y) + (z * z)\n        mv  = sqrt mv2\n        l   = sinh w * sin mv / mv\n        arg = cosh w * cos mv\n    {-# INLINE tanh #-}\n    tanh (unpackQ# -> (# x, y, z, w #))\n      | mv2 == 0       = packQ x y z (tanh w)\n      | isInfinite mv2 = packQ 0 0 0 (signum w)\n      | otherwise      = packQ (x * l) (y * l) (z * l) arg\n      where\n        mv2 = (x * x) + (y * y) + (z * z)\n        mv = sqrt mv2\n        b = 2*w\n        a = 2*mv\n        eb = exp (- abs b)\n        eb2 = eb*eb\n        d = 1 + eb2 + 2 * eb * cos a\n        rd = recip d\n        pa = M_PI - a\n        rd' = 2 / (b*b + pa*pa)\n        (l, arg) =\n          if d >= M_EPS\n          then (2 * sin a * eb * rd / mv, copysign (1 - eb2) b * rd)\n          else (2 * rd' , b * rd')\n    {-# INLINE asin #-}\n    -- The original formula:\n    -- asin q = -i * log (i*q + sqrt (1 - q*q))\n    -- below is a more numerically stable version.\n    asin (unpackQ# -> (# x, y, z, w #))\n      | v2 == 0   = if w2 <= 1\n                    then packQ x y z (asin w)\n                    else packQ l 0 0 arg\n      | otherwise  = packQ (x*c) (y*c) (z*c) arg\n      where\n        v2 = (x * x) + (y * y) + (z * z)\n        v = sqrt v2\n        w2 = w*w\n        w1qq = 0.5 *(1 - w2 + v2)       -- real part of (1 - q*q)/2\n        l1qq = sqrt (w1qq*w1qq + w2*v2) -- length of (1 - q*q)/2\n        sp2 = l1qq + w1qq\n        sn2 = l1qq - w1qq\n        sp = sqrt sp2\n        sn = copysign (sqrt sn2) w\n        -- choose a more stable (symbolically equiv) version\n        dp = if 2 * v2 <= sp2 then sp - v else v2 / ((sp + v)*(sn2 + v2))\n        dn = if 2 * w2 <= sn2 then w - sn else w2 / ((sn + w)*(sp2 + w2))\n        (wD, vD) = case compare w1qq 0 of\n            GT -> (dp, w * dp / sp)\n            LT -> (v * dn / sn, dn)\n            EQ -> (-v, w)\n        l = -0.5 * log (wD*wD + vD*vD)\n        c = l / v\n        arg = atan2 vD wD\n    {-# INLINE acos #-}\n    acos q = M_PI_2 - asin q\n    {-# INLINE atan #-}\n    -- atan q = i / 2 * log ( (i + q) / (i - q) )\n    atan (unpackQ# -> (# x, y, z, w #))\n      | v2 == 0   = packQ x y z (atan w)\n      | otherwise = packQ (x*c) (y*c) (z*c) arg\n      where\n        v2 = (x * x) + (y * y) + (z * z)\n        v = sqrt v2\n        w2 = w*w\n        q2 = w2 + v2\n        v' = v - 1\n        mzero = w2 + v'*v'\n        (c, arg) =\n          if mzero == 0\n          then ( sqrt maxFinite / v, 0)\n          else ( 0.25 * (log (1 + q2 + 2*v) - log mzero) / v\n               , 0.5 * atan2 (2*w) (1 - q2) )\n    {-# INLINE asinh #-}\n    -- The original formula:\n    -- asinh q = log (q + sqrt (q*q + 1))\n    -- below is a more numerically stable version.\n    asinh (unpackQ# -> (# x, y, z, w #))\n      | v2 == 0   = packQ x y z (asinh w)\n      | otherwise = packQ (x*c) (y*c) (z*c) arg\n      where\n        v2 = (x * x) + (y * y) + (z * z)\n        v = sqrt v2\n        w2 = w*w\n        w1qq = 0.5 *(1 + w2 - v2)       -- real part of (1 + q*q)/2\n        l1qq = sqrt (w1qq*w1qq + w2*v2) -- length of (1 + q*q)/2\n        sp2 = l1qq + w1qq\n        sn2 = l1qq - w1qq\n        sp = sqrt sp2\n        sn = copysign (sqrt sn2) w\n        -- choose a more stable (symbolically equiv) version\n        dp = if 2 * w >= - sp then w + sp else w2 / ((sp - w)*(w2 + sn2))\n        dn = if 2 * v <= - sn || sn >= 0\n                              then v + sn else v2 / ((v - sn)*(v2 + sp2))\n        (wD, vD) = case compare w1qq 0 of\n            GT -> (dp, v * dp / sp)\n            LT -> (w * dn / sn, dn)\n            EQ -> (w, v)\n        c = atan2 vD wD / v\n        arg = 0.5 * log (wD*wD + vD*vD)\n    {-# INLINE acosh #-}\n    -- The original formula:\n    -- asinh q = log (q + sqrt (q + 1) * sqrt (q - 1))\n    -- below is a more numerically stable version.\n    -- note, log (q + sqrt (q*q - 1)) would not work, because that would not\n    -- be the principal value.\n    acosh (unpackQ# -> (# x, y, z, w #))\n      | v2 == 0   = packQ x y z (acosh w)\n      | otherwise = packQ (x*c) (y*c) (z*c) arg\n      where\n        v2 = (x * x) + (y * y) + (z * z)\n        v = sqrt v2\n        w2 = w*w\n        w1qq = 0.5 *(w2 - v2 - 1)       -- real part of (q*q - 1)/2\n        l1qq = sqrt (w1qq*w1qq + w2*v2) -- length of (q*q - 1)/2\n        sp2 = l1qq + w1qq\n        sn2 = l1qq - w1qq\n        sp = sqrt sp2\n        sn = copysign (sqrt sn2) w\n        -- choose a more stable (symbolically equiv) version\n        dp = if 2 * w >= - sp then w + sp else w2 / ((w - sp)*(w2 + sn2))\n        dn = if 2 * v <= - sn || sn >= 0\n                              then v + sn else v2 / ((sn - v)*(v2 + sp2))\n        (wD, vD) = case compare w1qq 0 of\n            GT -> (dp, v * dp / sp)\n            LT -> (w * dn / sn, dn)\n            EQ -> (w, v)\n        c = atan2 vD wD / v\n        arg = 0.5 * log (wD*wD + vD*vD)\n    {-# INLINE atanh #-}\n    -- atanh q = 0.5 * log ( (1 + q) / (1 - q) )\n    atanh (unpackQ# -> (# x, y, z, w #))\n      | v2 ==  0  = packQ x y z (atanh w)\n      | otherwise = packQ (x*c) (y*c) (z*c) (copysign arg w)\n      where\n        v2 = (x * x) + (y * y) + (z * z)\n        v = sqrt v2\n        w2 = w*w\n        q2 = w2 + v2\n        w' = abs w - 1\n        c  = 0.5 * atan2 (2*v) (1 - q2) / v\n        arg = if w' == 0\n              then (1/0)\n              else 0.25 * (log (1 + q2 + 2 * abs w) - log (v2 + w'*w'))\n\n\n-- If q is negative real, provide a fallback axis to align log.\nlog' :: Vector Double 3 -> QDouble -> QDouble\nlog' r (unpackQ# -> (# x, y, z, w #))\n  = case (x * x) + (y * y) + (z * z) of\n    0.0 | w >= 0\n           -> packQ 0 0 0 (log w)\n        | Vec3 rx ry rz <- r\n           ->  packQ (M_PI*rx) (M_PI*ry) (M_PI*rz) (log (negate w))\n    mv2 -> case (# mv2 + w * w, sqrt mv2 #) of\n      (# q2, mv #) -> case atan2 mv w / mv of\n        l -> packQ (x * l) (y * l) (z * l) (0.5 * log q2)\n\n\n-- If q is negative real, provide a fallback axis to align sqrt.\nsqrt' :: Vector Double 3 -> QDouble -> QDouble\nsqrt' r (unpackQ# -> (# x, y, z, w #))\n  | v2 == 0 && w >= 0\n    = packQ x y z (sqrt w)\n  | v2 == 0\n  , Vec3 rx ry rz <- r\n  , sw <- sqrt (negate w)\n    = packQ (sw*rx) (sw*ry) (sw*rz) 0\n  | otherwise\n    = packQ (x * c) (y * c) (z * c) arg\n  where\n    v2 = (x * x) + (y * y) + (z * z)\n    mq = sqrt (v2 + w * w)\n    arg = sqrt $ 0.5 * if w >= 0 then mq + w else v2 / (mq - w)\n    c = 0.5 / arg\n\ninstance Eq QDouble where\n    {-# INLINE (==) #-}\n    QDouble a == QDouble b = a == b\n    {-# INLINE (/=) #-}\n    QDouble a /= QDouble b = a /= b\n", "meta": {"hexsha": "10ccc9b81f6ad4826fa0ad8e0196c3055ab547fa", "size": 19792, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "easytensor/src/Numeric/Quaternion/Internal/QDouble.hs", "max_stars_repo_name": "achirkin/fasttensor", "max_stars_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2017-06-30T04:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:46:17.000Z", "max_issues_repo_path": "easytensor/src/Numeric/Quaternion/Internal/QDouble.hs", "max_issues_repo_name": "achirkin/fasttensor", "max_issues_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-07-17T18:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T06:31:42.000Z", "max_forks_repo_path": "easytensor/src/Numeric/Quaternion/Internal/QDouble.hs", "max_forks_repo_name": "achirkin/fasttensor", "max_forks_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-08T20:44:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T22:08:04.000Z", "avg_line_length": 35.6612612613, "max_line_length": 92, "alphanum_fraction": 0.4428051738, "num_tokens": 7395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.43020928017642573}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule CPVO.IO.Reader.Ecalj.MMOM where\nimport CPVO.Numeric\nimport CPVO.IO\nimport CPVO.IO.Reader.Ecalj.Common\nimport CPVO.IO.Reader.Ecalj.DOS\n\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\nimport qualified Data.Text.Read as T\nimport Data.Either (rights)\n-------------------------\nimport Numeric.LinearAlgebra\n\nreadMMOM :: Int -> String -> IO [Double]\nreadMMOM nAtom foldernya = do\n    fLLMF <- fmap (T.unpack . head) $ getLastLLMF foldernya\n    putStrLn $ \"===================processed LLMF=\" ++ fLLMF\n    mmom <- fmap (map T.double) $ inshell2text $ concat [ \"mkdir -p temp; grep mmom \", fLLMF\n                                            ,\"| tail -n\", show (nAtom + 1)\n                                            ,\"| head -n\", show nAtom\n                                            ,\"| awk '{print $2}'\"\n                                          ]\n    sdtMMOM <- fmap (map T.double) $ inshell2text $ concat [ \"grep mmom \", fLLMF, \"| grep ehf | tail -1 | sed -e 's/^.*mmom=//g'| awk '{print $1}'\"\n                                          ]\n    return ( map fst $ rights $ concat [sdtMMOM,mmom])\n\n----------------------------------------------------------------------\n--getMMOM allArgs@(texFile:jd:jdHead:colAlign:xr:ymax':wTot:tumpuk:invS:tailer:foldernya:aos) = do\n\ngetMMOM :: [String] -> IO ()\ngetMMOM allArgs = do\n--getMMOM allArgs = do\n    putStrLn \"===start ==== CPVO.IO.Reader.Ecalj.MMOM: getMMOM ===\"\n    --(invStat, ymax, xmin, xmax, ctrlAtoms, uniqAtoms, ctrlAtomicAOs,jdTable, cleanedJdHead, foldernya, tailer,colAlign,texFile) <- readHeaderData allArgs\n    Right (invStat,_,_,_,ctrlAtoms,_, ctrlAtomicAOs,jdTable, cleanedJdHead,foldernya,tailer,_,texFile) <- readHeaderData allArgs\n\n    -------------------------------generating data------------------------\n    -------------------------------generating DOS data------------------------\n    totalDOS <- readTotalDOSText tailer foldernya\n    -------------------------------integrating DOS data-----------------------\n    let intgTot = map (\\i -> integrateToZero $ totalDOS \u00bf [0,i]) $ flipBy invStat [1,2] -- run it on spin [1,2]\n    putStrLn $ show intgTot\n    -------------------------------integrating PDOS data------------------------\n    let nAtom = length ctrlAtoms\n    -------------------------------generating PDOS data------------------------\n              -- map ditambah -1 karena input mengikuti gnuplot\n              -- input : d kolom 6-10\n              -- gnuplot : d kolom 6-10\n              -- hmatrix : d kolom 5-9\n\n  -------------------------------integrating PDOS data------------------------\n    putStrLn $ \"========invStat=\" ++ (show invStat)\n    (tMMomSD:mmomSD) <- fmap (map (* invStat)) $ readMMOM nAtom foldernya\n    putStrLn $ show $ map (showDouble (3::Integer)) mmomSD\n    putStrLn $ show tMMomSD\n    putStrLn \"==========show tMMomSD===========\"\n    pdosAtomicAll <- readPDOS invStat tailer foldernya ctrlAtomicAOs\n    let integratedAtomicPDOS = integrateAtomicPDOS pdosAtomicAll\n    let rIntgAll' = rendertable\n         $ (:) cleanedJdHead\n         $ (:) (concat [ [\"Total\" ]\n           , [\"  \"]\n           , map (showDouble (3::Integer)) $ (\\[t,iu,idn] -> [t,iu-idn,t-(iu-idn)]) $ (tMMomSD:intgTot)\n           ])\n         $ zipWith (\\a b -> a:b) (map show ([1,2..]::[Integer]))\n         $ zipWith (\\sdMom (intMom,(_,(j,_))) -> j:(map (showDouble (3::Integer)) [sdMom,intMom,sdMom-intMom])) mmomSD\n         $ map (\\(iu,idn,b) -> ((iu-idn),b) ) integratedAtomicPDOS\n    let rIntgAll = unlines  [\n                            rIntgAll'\n                            , jdTable\n                            ]\n    {-\n    resIntAll' <- markdownToTex rIntgAll\n    let resIntAll = T.replace \"\\\\}\" \"}\"\n                  $ T.replace \"\\\\{\" \"{\" $ T.pack\n                  $ unlines [\n                            \"\\\\begin{longtable}[]{\" ++ colAlign ++ \"}\"\n                            , unlines $ tail $ lines $ T.unpack resIntAll'\n                            ]\n    putStrLn rIntgAll\n    T.putStrLn resIntAll\n    -}\n    T.writeFile texFile $ T.pack rIntgAll\n    putStrLn \"===done CPVO.IO.Reader.Ecalj.MMOM: getMMOM ===\"\n", "meta": {"hexsha": "db6a296310e38c347d9cc2b9a5060a503199f829", "size": 4206, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CPVO/IO/Reader/Ecalj/MMOM.hs", "max_stars_repo_name": "hasanalrasyid/cpvoh", "max_stars_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CPVO/IO/Reader/Ecalj/MMOM.hs", "max_issues_repo_name": "hasanalrasyid/cpvoh", "max_issues_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CPVO/IO/Reader/Ecalj/MMOM.hs", "max_forks_repo_name": "hasanalrasyid/cpvoh", "max_forks_repo_head_hexsha": "d4e40c681a512b9ffb3f79ec46a4f4e5831e4165", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2584269663, "max_line_length": 155, "alphanum_fraction": 0.5045173562, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4301903068588016}}
{"text": "{-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE OverloadedStrings #-}\nmodule Lang.Parser where\n\nimport           Import                  hiding ( try )\nimport           Data.Attoparsec.Combinator\nimport           Data.Attoparsec.Text\nimport           Control.Monad.Except           ( MonadError(throwError) )\nimport           Data.Sequence                  ( fromList )\nimport           Data.Complex                   ( Complex((:+)) )\nimport           Data.Ratio                     ( (%) )\nimport           RIO.Partial                    ( read )\n\n\ndata Base = Bin | Oct | Dec | Hex\n\noneOf :: [Char] -> Parser Char\noneOf list = satisfy (`elem` list)\n\nnoneOf :: [Char] -> Parser Char\nnoneOf list = satisfy (`notElem` list)\n\nsymbol :: Parser Char\nsymbol = oneOf \"!#$%&|*+-/:<=>?@^_~\"\n\nskipSpaces :: Parser ()\nskipSpaces = skipMany space\n\nescaped :: Parser Char\nescaped = char '\\\\' *> oneOf \"\\\\\\\"\\'nrt\"\n\nparseChar :: Parser LispVal\nparseChar = \"#\\\\\" *> (name <|> letter <|> symbol <|> oneOf \"\\\\\\\"\\'\") <&> Char\n  where name = (\"space\" $> ' ') <|> (\"newline\" $> '\\n')\n\nparseString :: Parser LispVal\nparseString =\n  char '\"' *> many (noneOf \"\\\\\\\"\" <|> escaped) <* char '\"' <&> String\n\nparseAtom :: Parser LispVal\nparseAtom = do\n  firstLetter <- letter <|> symbol\n  rest        <- many (letter <|> digit <|> symbol)\n  let atom = firstLetter : rest\n  return $ case atom of\n    \"#t\" -> Bool True\n    \"#f\" -> Bool False\n    _    -> Atom atom\n\nradixPref :: Parser Base\nradixPref = char '#' *> (bin <|> oct <|> dec <|> hex)\n where\n  bin = char 'b' $> Bin\n  oct = char 'o' $> Oct\n  dec = char 'd' $> Dec\n  hex = char 'x' $> Hex\n\nparseBase :: (Integral a, Read a) => a -> [Char] -> a\nparseBase a list = parseBase' list 0\n where\n  parseBase' []      n = n\n  parseBase' (h : t) n = parseBase' t (n * a + parseDigit h)\n  parseDigit c | c == 'A' || c == 'a' = 10\n               | c == 'B' || c == 'b' = 11\n               | c == 'C' || c == 'c' = 12\n               | c == 'D' || c == 'd' = 13\n               | c == 'E' || c == 'e' = 14\n               | c == 'F' || c == 'f' = 15\n               | otherwise            = read [c]\n\nparseInteger :: Parser NumType\nparseInteger = Integer <$> do\n  pref <- option Dec radixPref\n  case pref of\n    Bin -> parseBase 2 <$> many1 digit\n    Oct -> parseBase 8 <$> many1 digit\n    Dec -> parseBase 10 <$> many1 digit\n    Hex -> parseBase 16 <$> many1 digit\n\nparseRational :: Parser NumType\nparseRational = (%) <$> (decimal <* \"/\") <*> decimal <&> Rational\n\nparseReal :: Parser NumType\nparseReal = double <&> Real\n\nparseComplex :: Parser NumType\nparseComplex =\n  (:+) <$> (double <* oneOf \"+-\") <*> (double <* char 'i') <&> Complex\n\nparseNumber :: Parser LispVal\nparseNumber =\n  try parseInteger\n    <|> try parseReal\n    <|> try parseRational\n    <|> try parseComplex\n    <&> Number\n\nparseList :: Parser LispVal -> Parser LispVal\nparseList recParser = do\n  char '(' *> skipSpaces\n  inits <- sepBy recParser skipSpaces\n  last  <- skipSpaces *> oneOf \".)\"\n  case last of\n    ')' -> return $ List inits\n    _ -> skipSpaces *> recParser <* skipSpaces <* char ')' <&> DottedList inits\n\nparseVector :: Parser LispVal -> Parser LispVal\nparseVector recParser =\n  \"#(\"\n    *>  skipSpaces\n    *>  sepBy recParser skipSpaces\n    <*  skipSpaces\n    <*  char ')'\n    <&> Vector\n    .   fromList\n\nparseQuotes :: Text -> LispVal -> Parser LispVal -> Parser LispVal\nparseQuotes c val recParser = do\n  _ <- string c\n  x <- recParser\n  return $ List [val, x]\n\nparseQuasiquote :: Parser LispVal -> Parser LispVal\nparseQuasiquote = parseQuotes \"`\" (Atom \"quasiquote\")\n\nparseQuote :: Parser LispVal -> Parser LispVal\nparseQuote = parseQuotes \"\\'\" (Atom \"quote\")\n\nparseUnquote :: Parser LispVal -> Parser LispVal\nparseUnquote = parseQuotes \",\" (Atom \"unquote\")\n\nparseUnquoteSplicing :: Parser LispVal -> Parser LispVal\nparseUnquoteSplicing = parseQuotes \",@\" (Atom \"unquote-splicing\")\n\nparseMetaVal :: Parser LispVal\nparseMetaVal = many1 letter <&> MetaVal\n\nparseMetaAtom :: Parser LispVal\nparseMetaAtom = \"atom:\" *> many1 letter <&> MetaAtom\n\nparseMetaList :: Parser LispVal\nparseMetaList = \"list:\" *> many1 letter <&> MetaList\n\nparseMetaVector :: Parser LispVal\nparseMetaVector = \"vec:\" *> many1 letter <&> MetaVector\n\nparseMetaString :: Parser LispVal\nparseMetaString = \"str:\" *> many1 letter <&> MetaString\n\nparseMeta :: Parser LispVal\nparseMeta =\n  char '@'\n    *> (   parseMetaAtom\n       <|> parseMetaList\n       <|> parseMetaVector\n       <|> parseMetaString\n       <|> parseMetaVal\n       )\n\nparseExpr :: Parser LispVal\nparseExpr =\n  try parseChar\n    <|> try parseString\n    <|> try parseNumber\n    <|> try (parseList parseExpr)\n    <|> try (parseVector parseExpr)\n    <|> try (parseQuote parseExpr)\n    <|> try (parseQuasiquote parseExpr)\n    <|> try (parseUnquoteSplicing parseExpr)\n    <|> try (parseUnquote parseExpr)\n    <|> try parseAtom\n\nparseExprOrMeta :: Parser LispVal\nparseExprOrMeta =\n  parseMeta\n    <|> try parseChar\n    <|> try parseString\n    <|> try parseNumber\n    <|> try (parseList parseExprOrMeta)\n    <|> try (parseVector parseExprOrMeta)\n    <|> try (parseQuote parseExprOrMeta)\n    <|> try (parseQuasiquote parseExprOrMeta)\n    <|> try (parseUnquoteSplicing parseExprOrMeta)\n    <|> try (parseUnquote parseExprOrMeta)\n    <|> try parseAtom\n\nreadOrThrow :: Parser a -> Text -> ThrowsError a\nreadOrThrow parser input = case parseOnly parser input of\n  Left  err -> throwError $ Parser err\n  Right val -> return val\n\nreadExpr :: Text -> ThrowsError LispVal\nreadExpr = readOrThrow parseExpr\n\nreadExprList :: Text -> ThrowsError [LispVal]\nreadExprList = readOrThrow (sepBy parseExpr skipSpaces)\n", "meta": {"hexsha": "4720c99aa923138e695ecac7b009b451ad2b9c3a", "size": 5650, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lang/Parser.hs", "max_stars_repo_name": "PKopel/Scheme48", "max_stars_repo_head_hexsha": "fd3578c1ba9c684a4ec76bedc425386e010e792d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lang/Parser.hs", "max_issues_repo_name": "PKopel/Scheme48", "max_issues_repo_head_hexsha": "fd3578c1ba9c684a4ec76bedc425386e010e792d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lang/Parser.hs", "max_forks_repo_name": "PKopel/Scheme48", "max_forks_repo_head_hexsha": "fd3578c1ba9c684a4ec76bedc425386e010e792d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5353535354, "max_line_length": 79, "alphanum_fraction": 0.6072566372, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934765, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.43010291001911316}}
{"text": "{-# LANGUAGE  ForeignFunctionInterface #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module     : Foreign.LAPACK.Zomplex\n-- Copyright  : Copyright (c) 2010, Patrick Perry <patperry@gmail.com>\n-- License    : BSD3\n-- Maintainer : Patrick Perry <patperry@gmail.com>\n-- Stability  : experimental\n--\n\nmodule Foreign.LAPACK.Zomplex\n    where\n\nimport Data.Complex( Complex )\nimport Foreign( Ptr )\nimport Foreign.BLAS.Types\nimport Foreign.LAPACK.Types\n\n#include \"f77_func-hsc.h\"\n\n\nforeign import ccall unsafe #f77_func zgeqrf\n    zgeqrf :: Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double)\n           -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double)\n           -> Ptr LAInt -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zgelqf\n    zgelqf :: Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double)\n           -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double)\n           -> Ptr LAInt -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zheevr\n    zheevr :: LAEigJob -> LAEigRange -> BLASUplo -> Ptr LAInt\n           -> Ptr (Complex Double) -> Ptr LAInt -> Ptr Double -> Ptr Double\n           -> Ptr LAInt -> Ptr LAInt -> Ptr Double -> Ptr LAInt -> Ptr Double\n           -> Ptr (Complex Double) -> Ptr LAInt -> Ptr LAInt\n           -> Ptr (Complex Double) -> Ptr LAInt -> Ptr Double -> Ptr LAInt\n           -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zlarfg\n    zlarfg :: Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double)\n           -> Ptr LAInt -> Ptr (Complex Double) -> IO ()\n\nforeign import ccall unsafe #f77_func zpotrf\n    zpotrf :: BLASUplo -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt\n           -> Ptr LAInt -> IO ()\n           \nforeign import ccall unsafe #f77_func zpotrs\n    zpotrs :: BLASUplo -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double)\n           -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr LAInt\n           -> IO ()\n\nforeign import ccall unsafe #f77_func zpptrf\n    zpptrf :: BLASUplo -> Ptr LAInt -> Ptr (Complex Double)\n           -> Ptr LAInt -> IO ()\n           \nforeign import ccall unsafe #f77_func zpptrs\n    zpptrs :: BLASUplo -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double)\n           -> Ptr (Complex Double) -> Ptr LAInt -> Ptr LAInt\n           -> IO ()\n\nforeign import ccall unsafe #f77_func zunmqr\n    zunmqr :: BLASSide -> BLASTrans -> Ptr LAInt -> Ptr LAInt\n           -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt\n           -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt\n           -> Ptr (Complex Double) -> Ptr LAInt -> Ptr LAInt\n           -> IO ()\n\nforeign import ccall unsafe #f77_func zunmlq\n    zunmlq :: BLASSide -> BLASTrans -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt\n           -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double)\n           -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double)\n           -> Ptr LAInt -> Ptr LAInt -> IO ()\n\n", "meta": {"hexsha": "a0826c2ef3544928ff24e18748b199942b11208a", "size": 2959, "ext": "hsc", "lang": "Haskell", "max_stars_repo_path": "lib/Foreign/LAPACK/Zomplex.hsc", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Foreign/LAPACK/Zomplex.hsc", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Foreign/LAPACK/Zomplex.hsc", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-13T07:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T07:21:09.000Z", "avg_line_length": 39.4533333333, "max_line_length": 77, "alphanum_fraction": 0.5893883069, "num_tokens": 793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4296064019894863}}
{"text": "\nmodule Shrinkage (\n    strimmerX\n  , testShrinkage\n  ) where\n\nimport Numeric.LinearAlgebra\nimport Test.Tasty\nimport Test.Tasty.HUnit\n\nimport Statistics.Covariance.Shrinkage.Strimmer\n\nstrimmerX :: Matrix Double\nstrimmerX = matrix 3 [\n    -1.1541680,  0.1229077,  0.2964592\n  , -0.4574491, -0.0106610, -0.2497785\n  ,  1.2711852,  0.2362810,  0.3653930\n  ]\n\nwithinTolVec :: Double -> Vector Double -> Vector Double -> Bool\nwithinTolVec tol x x' = abs (x - x') < scalar tol\n\nwithinTolMat :: Double -> Matrix Double -> Matrix Double -> Bool\nwithinTolMat tol x x' = withinTolVec tol (flatten x) (flatten x')\n\nstrimmerpsmallSVD :: Assertion\nstrimmerpsmallSVD = assertBool \"psmallSVD\" $ withinTolMat tol u' u\n  && withinTolVec tol s' s\n  && withinTolMat tol v' v\n  where\n    tol = 1e-6\n    (u, s, v) = psmallSVD strimmerX\n    u' = matrix 3 [\n         0.6256382, -0.7737046, -0.0997895\n      ,  0.2669970,  0.3325596, -0.9044980\n      , -0.7330003, -0.5392451, -0.4146388\n      ]\n    s' = vector [1.7850070, 0.5601167, 0.1101480]\n    v' = matrix 3 [\n        -0.99495870,  0.09886453,  0.01682235\n      , -0.05554307, -0.40358205, -0.91325599\n      , -0.08349942, -0.90958635,  0.40703871\n      ]\n\nstrimmernsmallSVD :: Assertion\nstrimmernsmallSVD = assertBool \"nsmallSVD\" $ withinTolMat tol u' u\n  && withinTolVec tol s' s\n  && withinTolMat tol v' v\n  where\n    tol = 1e-6\n    (u, s, v) = nsmallSVD strimmerX\n    u' = matrix 3 [\n        -0.6256382,  0.7737046, 0.0997895\n      , -0.2669970, -0.3325596, 0.9044980\n      ,  0.7330003,  0.5392451, 0.4146388\n      ]\n    s' = vector [1.7850070, 0.5601167, 0.1101480]\n    v' = matrix 3 [\n        0.99495870, -0.09886453, -0.01682235\n      , 0.05554307,  0.40358205,  0.91325599\n      , 0.08349942,  0.90958635, -0.40703871\n      ]\n\nstrimmerposSVD :: Assertion\nstrimmerposSVD = assertBool \"posSVD\" $ withinTolMat tol u' u\n  && withinTolVec tol s' s\n  && withinTolMat tol v' v\n  where\n    tol = 1e-6\n    (u, s, v) = posSVD strimmerX\n    u' = matrix 3 [\n        -0.6256382,  0.7737046, 0.0997895\n      , -0.2669970, -0.3325596, 0.9044980\n      ,  0.7330003,  0.5392451, 0.4146388\n      ]\n    s' = vector [1.7850070, 0.5601167, 0.1101480]\n    v' = matrix 3 [\n        0.99495870, -0.09886453, -0.01682235\n      , 0.05554307,  0.40358205,  0.91325599\n      , 0.08349942,  0.90958635, -0.40703871\n      ]\n\nstrimmerCovShrink :: Assertion\nstrimmerCovShrink = assertBool \"corpcor cor shrink is wrong\" $ withinTolMat 1e-6 cov' cov\n  where\n    cov = unSym (covShrink strimmerX)\n    cov' = matrix 3 [\n        1.13853590, 0.06889376, 0.05675350\n      , 0.06889376, 0.04389409, 0.03081658\n      , 0.05675350, 0.03081658, 0.11359393\n      ]\n\nstrimmerCorShrink :: Assertion\nstrimmerCorShrink = assertBool \"corpcor cor shrink is wrong\" $ withinTolMat 1e-6 cor' cor\n  where\n    cor = unSym (corShrink strimmerX)\n    cor' = matrix 3 [\n        1.0000000, 0.3081793, 0.1578126\n      , 0.3081793, 1.0000000, 0.4364192\n      , 0.1578126, 0.4364192, 1.0000000\n      ]\n\nstrimmerCorCoef :: Assertion\nstrimmerCorCoef = assertBool msg $ abs (lambda - coef) < 0.0000001\n  where\n    lambda = 0.5311773\n    coef = corCoef strimmerX\n    msg = \"expected: \" ++ show lambda ++ \"\\n     got: \" ++ show coef\n\nstrimmerVarCoef :: Assertion\nstrimmerVarCoef = assertBool \"corpcor var coef is wrong\" $ abs (lambda - varCoef strimmerX) < 0.0000001\n  where lambda = 0.2910548\n\nstrimmerVarShrink :: Assertion\nstrimmerVarShrink = assertBool \"corp var shrink\" $ abs (v - varShrink strimmerX) < 0.0000001\n  where v = vector [1.13853590, 0.04389409, 0.11359393]\n\ntestShrinkage :: TestTree\ntestShrinkage = testGroup \"shrinkage\" [\n    testCase \"strimmer varCoef\" strimmerVarCoef\n  , testCase \"strimmer varShrink\" strimmerVarShrink\n  , testCase \"strimmer corCoef\" strimmerCorCoef\n  , testCase \"strimmer corShrink\" strimmerCorShrink\n  , testCase \"strimmer covShrink\" strimmerCovShrink\n  , testCase \"strimmer psmallSVD\" strimmerpsmallSVD\n  , testCase \"strimmer nsmallSVD\" strimmernsmallSVD\n  , testCase \"strimmer posSVD\" strimmerposSVD\n  ]\n", "meta": {"hexsha": "1df73204a99b6a36689dd9f22828b407f0a17909", "size": 4020, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Shrinkage.hs", "max_stars_repo_name": "tsbattman/coviest", "max_stars_repo_head_hexsha": "20dd81ca77567dd146a3cb17be7b87e24d9f10b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Shrinkage.hs", "max_issues_repo_name": "tsbattman/coviest", "max_issues_repo_head_hexsha": "20dd81ca77567dd146a3cb17be7b87e24d9f10b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Shrinkage.hs", "max_forks_repo_name": "tsbattman/coviest", "max_forks_repo_head_hexsha": "20dd81ca77567dd146a3cb17be7b87e24d9f10b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1627906977, "max_line_length": 103, "alphanum_fraction": 0.660199005, "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.42960640198948624}}
{"text": "module Main where\n\n-- third party imports\nimport Criterion.Main\nimport Data.Complex\nimport Data.Tuple\nimport Graphics.Image\nimport System.Environment\n\n-- local imports\nimport CommonFunctions\nimport JuliaSet\n\nmain :: IO ()\nmain = do\n  args <- getArgs\n  if length args == 0 then do\n    usage\n  else do\n    if length args < 5 then do\n      visualizeJuliaBench\n    else do\n      let outputFilename = args !! 4\n      -- putStrLn \"visualizing julia set...\"\n      runWithCliArgs args\n      -- putStrLn (\"Done! Image output to \" ++ outputFilename)\n\nvisualizeJuliaBench = defaultMain [\n    bgroup \"visualize julia set\" [\n      -- bench \"f1 ((-0.4) :+ 0.65) VU\" $ whnf makeImageVU g,\n      -- bench \"f1 ((-0.4) :+ 0.65) VS\" $ whnf makeImageVS g,\n      bench \"f1 ((-0.4) :+ 0.65) RSU\" $ whnf makeImageRSU g,\n      bench \"f1 ((-0.4) :+ 0.65) RPU\" $ whnf makeImageRPU g,\n      bench \"f1 ((-0.4) :+ 0.65) RSS\" $ whnf makeImageRSS g,\n      bench \"f1 ((-0.4) :+ 0.65) RPS\" $ whnf makeImageRPS g\n    ]\n  ]\n  where\n    default_func = f1 ((-0.4) :+ 0.65)\n    g = pixelToJuliaSetValue default_func 1.5 width height 100\n    -- makeImageVU = makeImageR VU (width, height)\n    -- makeImageVS = makeImageR VS (width, height)\n    makeImageRSU = makeImageR RSU (width, height)\n    makeImageRPU = makeImageR RPU (width, height)\n    makeImageRSS = makeImageR RSS (width, height)\n    makeImageRPS = makeImageR RPS (width, height)\n    width = 10000\n    height = 10000\n\n-- takes string cli args and returns processed args for visualizeJuliaSet\nrunWithCliArgs :: [String] -> IO()\nrunWithCliArgs args\n  -- | (length args) < 5 = do\n  --     usage\n  --     putStrLn \"using default values \" ++ (show (\n  --       default_func, 1.5, 1000, 1000, 100, \"images/output.png\"))\n  --     (default_func, 1.5, 1000, 1000, 100, \"images/output.png\")\n  | (length args) < 6 = visualizeJuliaSet default_func r width height\n                          maxIter outputFilename \"RPU\" \n  | (length args) < 7 = visualizeJuliaSet default_func r width height\n                          maxIter outputFilename arrayType\n  | (length args) < 8 = visualizeJuliaSet (parseFunctionParams func_num [])\n                          r width height maxIter outputFilename arrayType\n  | (length args) < 9 = visualizeJuliaSet\n                          (parseFunctionParams func_num params)\n                          r width height maxIter outputFilename arrayType\n  where\n    default_func = f1 ((-0.4) :+ 0.65)\n    r = read (args !! 0) :: Double\n    width = read (args !! 1) :: Int\n    height = read (args !! 2) :: Int\n    maxIter = read (args !! 3) :: Int\n    outputFilename = args !! 4\n    arrayType = args !! 5\n    func_num = read (args!!6) :: Int\n    params = Prelude.map (read::String -> Complex Double) \n                         (slice 7 (length args) args)\n\nslice :: Int -> Int -> [a] -> [a]\nslice from to xs = take (to - from + 1) (drop from xs)\n\nparseFunctionParams :: Int\n                    -> [Complex Double]\n                    -> (Complex Double -> Complex Double)\nparseFunctionParams func_num params\n    | func_num == 1 && params == [] = f1 ((-0.4) :+ 0.65)\n    | func_num == 1 = f1 (params!!0)\n\nusage = do\n  let prog = \"stack run\"\n  -- prog <- getProgName\n  putStrLn (\"Usages: \") \n  putStrLn (\"    \" ++ prog)\n  putStrLn (\"    \" ++ prog ++ \" escape_radius width height \"\n            ++ \"max_iter output_filename [arrType]\")\n  putStrLn (\"              [func_num [constant1 [constant2] ... ]]\")\n  putStrLn (\"    \" ++ prog ++ \" -- --output benchmark.html\")\n  putStrLn \"\"\n  putStrLn \"usage 1 (no argments) displays this help\"\n  putStrLn (\"usage 2 visualizes the julia set created with the \" ++\n           \"given parameters\")\n  putStrLn \"usage 3 benchmarks the program\"\n  putStrLn \"\"\n  putStrLn \"notes on usage 2:\"\n  putStrLn (\"number of constants must correspond to the number of constants \"\n    ++ \"function func_num takes\")\n  putStrLn (\"example: \" ++ prog ++ \" 1.5 1000 1000 100 \"\n    ++ \"\\\"images/output.png\\\"\")\n  putStrLn (\"example: \" ++ prog ++ \" 1.5 1000 1000 100 \"\n    ++ \"\\\"images/output.png\\\" RPU 1 \\\"(0.285 :+ 0)\\\"\")\n", "meta": {"hexsha": "7c9f740d312dd5fc82ff4f7c7140cb7aa6036838", "size": 4062, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "rileyweber13/fraktell", "max_stars_repo_head_hexsha": "49d8fdf9e53d1daa341d653ac74406691aececbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-09T13:38:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T13:38:04.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "rileyweber13/fraktell", "max_issues_repo_head_hexsha": "49d8fdf9e53d1daa341d653ac74406691aececbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "rileyweber13/fraktell", "max_forks_repo_head_hexsha": "49d8fdf9e53d1daa341d653ac74406691aececbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5945945946, "max_line_length": 77, "alphanum_fraction": 0.6031511571, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.42953418931956067}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\nmodule Grenade.Layers.FullyConnected (\n    FullyConnected (..)\n  , FullyConnected' (..)\n  , randomFullyConnected\n  ) where\n\nimport           Control.Monad.Random hiding (fromList)\n\nimport           Data.Proxy\nimport           Data.Serialize\nimport           Data.Singletons.TypeLits\n\nimport qualified Numeric.LinearAlgebra as LA\nimport           Numeric.LinearAlgebra.Static\n\nimport           Grenade.Core\n\nimport           Grenade.Layers.Internal.Update\n\n-- | A basic fully connected (or inner product) neural network layer.\ndata FullyConnected i o = FullyConnected\n                        !(FullyConnected' i o)   -- Neuron weights\n                        !(FullyConnected' i o)   -- Neuron momentum\n\ndata FullyConnected' i o = FullyConnected'\n                         !(R o)   -- Bias\n                         !(L o i) -- Activations\n\ninstance Show (FullyConnected i o) where\n  show FullyConnected {} = \"FullyConnected\"\n\ninstance (KnownNat i, KnownNat o) => UpdateLayer (FullyConnected i o) where\n  type Gradient (FullyConnected i o) = (FullyConnected' i o)\n\n  runUpdate lp (FullyConnected (FullyConnected' oldBias oldActivations) (FullyConnected' oldBiasMomentum oldMomentum)) (FullyConnected' biasGradient activationGradient) =\n    let (newBias, newBiasMomentum)    = descendVector (learningRate lp) (learningMomentum lp) (learningRegulariser lp) oldBias biasGradient oldBiasMomentum\n        (newActivations, newMomentum) = descendMatrix (learningRate lp) (learningMomentum lp) (learningRegulariser lp) oldActivations activationGradient oldMomentum\n    in FullyConnected (FullyConnected' newBias newActivations) (FullyConnected' newBiasMomentum newMomentum)\n\n  createRandom = randomFullyConnected\n\ninstance (KnownNat i, KnownNat o) => Layer (FullyConnected i o) ('D1 i) ('D1 o) where\n  type Tape (FullyConnected i o) ('D1 i) ('D1 o) = R i\n  -- Do a matrix vector multiplication and return the result.\n  runForwards (FullyConnected (FullyConnected' wB wN) _) (S1D v) = (v, S1D (wB + wN #> v))\n\n  -- Run a backpropogation step for a full connected layer.\n  runBackwards (FullyConnected (FullyConnected' _ wN) _) x (S1D dEdy) =\n          let wB'  = dEdy\n              mm'  = dEdy `outer` x\n              -- calcluate derivatives for next step\n              dWs  = tr wN #> dEdy\n          in  (FullyConnected' wB' mm', S1D dWs)\n\ninstance (KnownNat i, KnownNat o) => Serialize (FullyConnected i o) where\n  put (FullyConnected (FullyConnected' b w) _) = do\n    putListOf put . LA.toList . extract $ b\n    putListOf put . LA.toList . LA.flatten . extract $ w\n\n  get = do\n      let f  = fromIntegral $ natVal (Proxy :: Proxy i)\n      b     <- maybe (fail \"Vector of incorrect size\") return . create . LA.fromList =<< getListOf get\n      k     <- maybe (fail \"Vector of incorrect size\") return . create . LA.reshape f . LA.fromList =<< getListOf get\n      let bm = konst 0\n      let mm = konst 0\n      return $ FullyConnected (FullyConnected' b k) (FullyConnected' bm mm)\n\nrandomFullyConnected :: (MonadRandom m, KnownNat i, KnownNat o)\n                     => m (FullyConnected i o)\nrandomFullyConnected = do\n    s1    <- getRandom\n    s2    <- getRandom\n    let wB = randomVector  s1 Uniform * 2 - 1\n        wN = uniformSample s2 (-1) 1\n        bm = konst 0\n        mm = konst 0\n    return $ FullyConnected (FullyConnected' wB wN) (FullyConnected' bm mm)\n", "meta": {"hexsha": "704165861886ebff0ecab92eb7a01ebf91dd3e0a", "size": 3548, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/FullyConnected.hs", "max_stars_repo_name": "LuisChDev/grenade", "max_stars_repo_head_hexsha": "5206c95c423d9755e620f41576470a281ba59c89", "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/FullyConnected.hs", "max_issues_repo_name": "LuisChDev/grenade", "max_issues_repo_head_hexsha": "5206c95c423d9755e620f41576470a281ba59c89", "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/FullyConnected.hs", "max_forks_repo_name": "LuisChDev/grenade", "max_forks_repo_head_hexsha": "5206c95c423d9755e620f41576470a281ba59c89", "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": 42.7469879518, "max_line_length": 170, "alphanum_fraction": 0.6578354002, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4294944041289827}}
{"text": "{-# LANGUAGE MagicHash, UnboxedTuples #-}\n\nmodule Render (render, parRender) where\n\nimport Control.Parallel.Strategies\n\nimport Numeric.Vector\nimport Numeric.Scalar (fromScalar, scalar)\nimport Types\nimport Control.Monad.State\nimport Camera (rayFrom)\nimport Raycast (raycast)\nimport Shader (reflectance, sampleBRDF, probability)\nimport Scene (makeContext)\nimport VecUtil (unpack3, vec3Of)\nimport System.Random\nimport SceneRandom\nimport Lights\n\nmap2 :: (a -> b) -> [[a]] -> [[b]]\nmap2 f = map (map f)\n\nvec23 :: Vec2d -> (Double, Double, Double)\nvec23 v = case unpackV2# v of\n            (# u, v #) -> (u, v, 1)\n\npossibly :: (a -> b) -> b -> Maybe a -> b\npossibly _ def Nothing = def\npossibly f _ (Just x) = f x\n\nshade :: Int -> State SceneContext Vec3d\nshade bounceCount = get >>= (\\ctx -> if bounceCount > s_getBounces (ss_getScene ctx) then return (vec3Of 0) else do\n  let hit = ss_getHit ctx\n  let brdf = rh_getShader $ hit\n  col <- reflectance brdf\n  let scene = ss_getScene ctx\n  let lights = s_getLights scene\n  let norm = rh_getNormal hit\n\n  mReflectRay <- sampleBRDF brdf\n  (reflectColor, reflectProbability) <- case mReflectRay of\n    Nothing -> return (0, 0)\n    Just reflectRay -> do\n      prob <- probability brdf (r_getDir reflectRay)\n      case raycast scene reflectRay of\n        Nothing -> return $ (s_getSkyColor scene, )prob\n        Just hit -> do\n          let (v, s) = runState (shade (bounceCount + 1)) $ makeContext scene (ss_getGen ctx) hit\n          put s\n          return (v, prob) -- 1 / (2 * PI)\n\n  let newRayPos = (rh_getPos hit) + (norm * (vec3Of 0.01))\n\n  lighting <- sequence $ map (sampleLight newRayPos norm) lights\n  let lighting' = filter ((>0) . fst) lighting\n  lightProbabilities <- sequence $ map (probability brdf . snd) lighting'\n  let lightColors = map fst lighting'\n\n  let probabilitySum = reflectProbability + sum lightProbabilities\n\n  let adjustedReflectColor = reflectColor * vec3Of reflectProbability\n  let adjustedIncomingLighting = sum $ zipWith (*) lightColors (map vec3Of lightProbabilities)\n  \n  let incomingLight = adjustedReflectColor + adjustedIncomingLighting\n  \n  let lit = col * incomingLight\n  \n  reflectColor <- reflectance brdf\n  return lit\n  )\n\nsamplePixel :: Scene -> (Int, Int) -> Int -> Vec3d\nsamplePixel s (x, y) sample = let w = s_getWidth s\n                                  h = s_getHeight s\n                                  cam = s_getCamera s\n                                  skyCol = s_getSkyColor s\n                                  -- Random seed is an arbitrary formula based on pixel location to form distinct results\n                                  gen = mkStdGen $ (x + y * w + x * (x + y) + (s_getSeed s)) * sample\n                              in  possibly (fst . runState (shade 0) . makeContext s gen) (skyCol / (2 * pi)) $\n                                  raycast s $\n                                  rayFrom cam $\n                                  (fromIntegral x / fromIntegral w * 2.0 - 1.0, (fromIntegral h / fromIntegral w) - fromIntegral y / fromIntegral w * 2.0)\n  \nrenderPixel :: Scene -> (Int, Int) -> Vec3d\nrenderPixel s p = let numSamples = s_getSamples s\n                      samples = map (samplePixel s p)  [1..numSamples]\n                  -- Multiply by 2pi for monte-carlo integration because the volume of the integration bounds is 2pi\n                  -- (integration bounds form a hemisphere)\n                  in  sum samples / fromIntegral numSamples * vec3Of (2 * pi)\n\nrender :: Scene -> [[(Double, Double, Double)]]\nrender s = let w = s_getWidth s\n               h = s_getHeight s\n               cam = s_getCamera s\n               skyCol = s_getSkyColor s\n               seed = 1\n               gen = mkStdGen seed\n          in  map2 unpack3 $\n              map2 (renderPixel s) $\n              [ [ (x, y) | x <- [1..w] ] | y <- [1..h] ]\n\n-- Found how to evaluate the list in parallel from\n-- https://stackoverflow.com/a/5606176\nparRender :: Scene -> [[(Double, Double, Double)]]\nparRender s = (render s) `using` parList rdeepseq\n", "meta": {"hexsha": "9aa3ada389c19850c1aba897f41e374e1ff4908a", "size": 4041, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Render.hs", "max_stars_repo_name": "craigmc08/haskell-raytracer", "max_stars_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Render.hs", "max_issues_repo_name": "craigmc08/haskell-raytracer", "max_issues_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Render.hs", "max_forks_repo_name": "craigmc08/haskell-raytracer", "max_forks_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1226415094, "max_line_length": 154, "alphanum_fraction": 0.6055431824, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4294698359451053}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n\n-- $ ghc -O2 --make wrappers.hs functions.c\n\nimport Numeric.LinearAlgebra\nimport Data.Packed.Development\nimport Foreign(Ptr,unsafePerformIO)\nimport Foreign.C.Types(CInt)\n\n-----------------------------------------------------\n\nmain = do\n    print $ myScale 3.0 (fromList [1..10])\n    print $ myDiag $ (3><5) [1..]\n\n-----------------------------------------------------\n\nforeign import ccall unsafe \"c_scale_vector\"\n    cScaleVector :: Double                -- scale\n                 -> CInt -> Ptr Double    -- argument\n                 -> CInt -> Ptr Double    -- result\n                 -> IO CInt               -- exit code\n\nmyScale s x = unsafePerformIO $ do\n    y <- createVector (dim x)\n    app2 (cScaleVector s) vec x vec y \"cScaleVector\"\n    return y\n\n-----------------------------------------------------\n-- forcing row order\n\nforeign import ccall unsafe \"c_diag\"\n    cDiag :: CInt -> CInt -> Ptr Double  -- argument\n          -> CInt -> Ptr Double          -- result1\n          -> CInt -> CInt -> Ptr Double  -- result2\n          -> IO CInt                     -- exit code\n\nmyDiag m = unsafePerformIO $ do\n    y <- createVector (min r c)\n    z <- createMatrix RowMajor r c\n    app3 cDiag mat (cmat m) vec y mat z \"cDiag\"\n    return (y,z)\n  where r = rows m\n        c = cols m\n", "meta": {"hexsha": "a88f74b055821b642fb4ecca5cf89ff521d13ff1", "size": 1329, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/devel/ej1/wrappers.hs", "max_stars_repo_name": "curiousleo/liquidhaskell", "max_stars_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 941, "max_stars_repo_stars_event_min_datetime": "2015-01-13T10:51:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:32:32.000Z", "max_issues_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/devel/ej1/wrappers.hs", "max_issues_repo_name": "curiousleo/liquidhaskell", "max_issues_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 1300, "max_issues_repo_issues_event_min_datetime": "2015-01-01T05:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:11:03.000Z", "max_forks_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/devel/ej1/wrappers.hs", "max_forks_repo_name": "curiousleo/liquidhaskell", "max_forks_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 145, "max_forks_repo_forks_event_min_datetime": "2015-01-12T08:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:29:30.000Z", "avg_line_length": 29.5333333333, "max_line_length": 54, "alphanum_fraction": 0.5026335591, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.42939825716643687}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE CPP                       #-}\n{-# LANGUAGE DataKinds                 #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE FlexibleContexts          #-}\n{-# LANGUAGE GADTs                     #-}\n{-# LANGUAGE RankNTypes                #-}\n{-# LANGUAGE ScopedTypeVariables       #-}\n{-# LANGUAGE TypeFamilies              #-}\n\nimport           Control.Applicative\nimport           Control.Concurrent\nimport           Control.Monad.Random\n\nimport           Options.Applicative\n\nimport           Graphics.Image               hiding (map, on)\n\nimport qualified Numeric.LinearAlgebra        as LA\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport           Grenade\n\n\ndata SuperResOptions = SuperResOptions FilePath         -- onnx file\n                                       FilePath         -- input image\n\npSuperRes :: Parser SuperResOptions\npSuperRes = SuperResOptions <$> argument str (metavar \"onnx\") <*> argument str (metavar \"image\")\n\nloadSuperResImage :: FilePath -> IO (Maybe (S ('D3 224 224 1), [[RealNum]], [[RealNum]]))\nloadSuperResImage path = do\n  img <- readImageRGB VU path\n  -- displayImage img\n  return $ do\n    guard $ dims img == (224, 224)\n    let imgYCbCr = toImageYCbCr img\n        imgY0    = map (\\(PixelYCbCr y _ _ )      -> doubleToRealNum y )  . concat . toLists $ imgYCbCr\n        imgCb    = map (map (\\(PixelYCbCr _ cb _) -> doubleToRealNum cb)) . toLists $ imgYCbCr\n        imgCr    = map (map (\\(PixelYCbCr _ _ cr) -> doubleToRealNum cr)) . toLists $ imgYCbCr\n\n    return (S3D (H.fromList imgY0), imgCb, imgCr)\n\ndisplayHighResImage :: S ('D3 672 672 1) -> [[RealNum]] -> [[RealNum]] -> IO ()\ndisplayHighResImage (S3D m) cbs crs = do\n  let realNumToPixel = PixelX . realNumToDouble\n      m'  = LA.toLists $ H.extract m              :: [[RealNum]]\n      m'' = map (map realNumToPixel) m'           :: [[Pixel X Double]]\n      img = fromLists m''                         :: Image VU X Double\n\n      imgBs  = fromLists $ map (map realNumToPixel) cbs :: Image VU X Double\n      imgRs  = fromLists $ map (map realNumToPixel) crs :: Image VU X Double\n\n      imgBs' = resize Bilinear Edge (672, 672) imgBs :: Image VU X Double\n      imgRs' = resize Bilinear Edge (672, 672) imgRs :: Image VU X Double\n\n      finalImg = fromImagesX [(LumaYCbCr, img), (CBlueYCbCr, imgBs'), (CRedYCbCr, imgRs')] :: Image VU YCbCr Double\n\n  displayImage finalImg\n  threadDelay 10000000\n\nmain :: IO ()\nmain = do\n    SuperResOptions netPath imgPath <- execParser (info (pSuperRes <**> helper) idm)\n    res <- loadSuperResolution netPath\n\n    inputM <- loadSuperResImage imgPath\n\n    case (res, inputM) of\n      (Right net, Just (input, cbs, crs))  -> do\n        let S3D y = runNet net input\n        displayHighResImage (S3D y) cbs crs\n\n      (Left err, _) -> print err\n      _             -> putStrLn \"Failed to load network and file\"\n", "meta": {"hexsha": "8028d1ae93aae339fd7c3866625593de41241047", "size": 2918, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/superresolution.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "examples/main/superresolution.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main/superresolution.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8961038961, "max_line_length": 115, "alphanum_fraction": 0.601439342, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4293581622522326}}
{"text": "{-# LANGUAGE BangPatterns #-}\nmodule STCFourierSeries where\n\nimport           Control.DeepSeq\nimport           Control.Monad                      as M\nimport qualified Data.Array.Accelerate              as A\nimport qualified Data.Array.Accelerate.Data.Complex as A\nimport           Data.Array.Accelerate.LLVM.PTX\nimport           Data.Array.IArray\nimport           Data.Array.Repa                    as R\nimport           Data.Binary\nimport           Data.Complex\nimport           Data.List                          as L\nimport           Data.Maybe\nimport           Data.Vector.Generic                as VG\nimport           FokkerPlanck.BrownianMotion\nimport           FokkerPlanck.FourierSeries\nimport           FokkerPlanck.GreensFunction\nimport           FokkerPlanck.Histogram\nimport           FokkerPlanck.MonteCarlo\nimport           Foreign.CUDA.Driver                as CUDA\nimport           Image.IO\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Utils.Array\nimport           Utils.Time\n\nmain = do\n  args@(gpuIDStr:numPointStr:deltaXStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:deltaLogStr:taoStr:numTrailStr:maxTrailStr:phiFreqsStr:rhoFreqsStr:thetaFreqsStr:scaleFreqsStr:initDistStr:initScaleStr:histFilePath:stdStr:stdGStr:locationStr:numThreadStr:_) <-\n    getArgs\n  let gpuID = read gpuIDStr :: [Int]\n      numPoint = read numPointStr :: Int\n      deltaX = read deltaXStr :: Double\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      phiFreq = read phiFreqsStr :: Double\n      phiFreqs = [-phiFreq .. phiFreq]\n      rhoFreq = read rhoFreqsStr :: Double\n      rhoFreqs = [-rhoFreq .. rhoFreq]\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scaleFreq = read scaleFreqsStr :: Double\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      initDist = read initDistStr :: [(Double, Double, Double, Double)]\n      initScale = read initScaleStr :: Double\n      initPoints = L.map (\\(x, y, t, s) -> Point x y t s) initDist\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/STCFourierSeries\"\n      maxScale = read maxScaleStr :: Double\n      halfLogPeriod = log maxScale\n      deltaLog = read deltaLogStr :: Double\n      std = read stdStr :: Double\n      stdG = read stdGStr :: Double\n      location = read locationStr :: (Int, Int)\n  removePathForcibly folderPath\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  -- hist <-\n  --   if flag\n  --     then do\n  --       printCurrentTime $ \"read data from \" L.++ histFilePath\n  --       decodeFile histFilePath\n  --     else runMonteCarloFourierCoefficientsGPU\n  --            gpuID\n  --            numThread\n  --            numTrail\n  --            maxTrail\n  --            thetaSigma\n  --            scaleSigma\n  --            maxScale\n  --            tao\n  --            phiFreqs\n  --            rhoFreqs\n  --            thetaFreqs\n  --            scaleFreqs\n  --            deltaLog\n  --            initScale\n  --            histFilePath\n  --            (emptyHistogram\n  --               [ L.length phiFreqs\n  --               , L.length rhoFreqs\n  --               , L.length thetaFreqs\n  --               , L.length scaleFreqs\n  --               ]\n  --               0)\n  -- hist <-\n  --   sampleLogpolar\n  --     histFilePath\n  --     (L.head gpuID)\n  --     180\n  --     180\n  --     (fromIntegral $ div numPoint 2)\n  --     initScale\n  --     thetaSigma\n  --     tao\n  --     phiFreqs\n  --     rhoFreqs\n  --     thetaFreqs\n  --     scaleFreqs\n  hist <-\n    sampleCartesian\n      folderPath\n      histFilePath\n      gpuID\n      (fromIntegral $ div numPoint 2)\n      144\n      deltaLog\n      initScale\n      thetaSigma\n      tao\n      phiFreqs\n      rhoFreqs\n      thetaFreqs\n      scaleFreqs\n  let !initSource =\n        computeInitialDistribution'\n          numPoint\n          numPoint\n          phiFreqs\n          rhoFreqs\n          -- thetaFreqs\n          halfLogPeriod\n          [L.head initPoints]\n      !initSink =\n        computeInitialDistribution'\n          numPoint\n          numPoint\n          phiFreqs\n          rhoFreqs\n          -- thetaFreqs\n          halfLogPeriod\n          [L.last initPoints]\n      !coefficients =\n        normalizeFreqArr' std phiFreqs rhoFreqs . getNormalizedHistogramArr $\n        hist\n       -- = getNormalizedHistogramArr $ hist :: R.Array U DIM4 (Complex Double)\n      !thetaRHarmonics =\n        computeThetaRHarmonics\n          numOrientation\n          numScale\n          thetaFreqs\n          scaleFreqs\n          halfLogPeriod\n  plan <-\n    makePlan\n      folderPath\n      emptyPlan\n      numPoint\n      numPoint\n      (L.length thetaFreqs)\n      (L.length scaleFreqs)\n  printCurrentTime \"harmonicsArray\"\n  -- gaussian <- gaussianFilter2D plan numPoint stdG\n  harmonicsArray <-\n    dftHarmonicsArray\n      plan\n      numPoint\n      deltaX\n      numPoint\n      deltaX\n      phiFreqs\n      rhoFreqs\n      thetaFreqs\n      scaleFreqs\n      halfLogPeriod\n      (fromIntegral numPoint * sqrt 2)\n      -- gaussian\n  -- let harmonicsArray' =\n  --       computeHarmonicsArray\n  --         numPoint\n  --         deltaX\n  --         numPoint\n  --         deltaX\n  --         phiFreqs\n  --         rhoFreqs\n  --         thetaFreqs\n  --         scaleFreqs\n  --         halfLogPeriod\n  --         maxScale\n  --         -- (fromIntegral numPoint)\n  -- harmonicsArrayGPU <-\n  --   dftHarmonicsArrayGPU\n  --     plan\n  --     numPoint\n  --     deltaX\n  --     numPoint\n  --     deltaX\n  --     phiFreqs\n  --     rhoFreqs\n  --     thetaFreqs\n  --     scaleFreqs\n  --     halfLogPeriod\n  --     maxScale\n  -- initialise []\n  -- dev <- device . L.head $ gpuID\n  -- ctx <- CUDA.create dev []\n  -- ptx <- createTargetFromContext ctx\n  -- registerPinnedAllocatorWith ptx\n  --Source\n  printCurrentTime \"Source\"\n  sourceArr <- convolve' Source plan coefficients harmonicsArray initSource\n  -- sourceArr' <- convolve'' Source plan coefficients harmonicsArray' initSource\n  -- printCurrentTime \"CPU\"\n  -- sourceArr <-\n  --   convolveGPU\n  --     ptx\n  --     Source\n  --     plan\n  --     (A.use .\n  --      A.fromList\n  --        (A.Z A.:. (L.length scaleFreqs) A.:. (L.length thetaFreqs) A.:.\n  --         (L.length rhoFreqs) A.:.\n  --         (L.length phiFreqs)) .\n  --      R.toList $\n  --      coefficients)\n  --     (A.use .\n  --      A.fromList\n  --        (A.Z A.:. (L.length scaleFreqs) A.:. (L.length thetaFreqs) A.:.\n  --         (L.length rhoFreqs) A.:.\n  --         (L.length phiFreqs)) .\n  --      R.toList $\n  --      coefficients)\n  --     harmonicsArrayGPU\n  --     initSource\n  -- printCurrentTime \"GPU\"\n  plotDFTArrayPower\n    (folderPath </> (printf \"SourcePower.png\"))\n    numPoint\n    numPoint $\n    sourceArr\n  plotDFTArrayThetaR\n    (folderPath </> \"Source.png\")\n    numPoint\n    numPoint\n    thetaRHarmonics\n    sourceArr\n  let sourceArr' =\n        fromUnboxed (Z :. numOrientation :. numPoint :. numPoint) .\n        VG.convert .\n        VG.concat .\n        computeFourierSeriesThetaR thetaRHarmonics . getDFTArrayVector $\n        sourceArr\n  plotThetaDimension folderPath \"FourierSeries_\" location . R.map magnitude $\n    sourceArr'\n  -- plotDFTArrayThetaR\n  --   (folderPath </> \"Source_test.png\")\n  --   numPoint\n  --   numPoint\n  --   thetaRHarmonics\n  --   sourceArr'\n  --Sink\n  printCurrentTime \"Sink\"\n  sinkArr <- convolve' Sink plan coefficients harmonicsArray initSink\n  plotDFTArrayPower (folderPath </> (printf \"SinkPower.png\")) numPoint numPoint $\n    sinkArr\n  plotDFTArrayThetaR\n    (folderPath </> \"Sink.png\")\n    numPoint\n    numPoint\n    thetaRHarmonics\n    sinkArr\n  printCurrentTime \"Completion\"\n  completionArr <- completionField' plan sourceArr sinkArr\n  plotDFTArrayThetaR\n    (folderPath </> \"Completion.png\")\n    numPoint\n    numPoint\n    thetaRHarmonics\n    completionArr\n  plotDFTArrayPower\n    (folderPath </> (printf \"CompletionPower.png\"))\n    numPoint\n    numPoint\n    completionArr\n  let a =\n        computeFourierSeriesThetaR thetaRHarmonics . getDFTArrayVector $\n        sourceArr\n      b =\n        computeFourierSeriesThetaR thetaRHarmonics . getDFTArrayVector $ sinkArr\n  plotImageRepa (folderPath </> \"CompletionR2S1.png\") .\n    ImageRepa 8 .\n    fromUnboxed (Z :. (1 :: Int) :. numPoint :. numPoint) .\n    VG.map (\\x -> x ^ 2) . VG.convert . L.foldl1' (VG.zipWith (+)) $\n    L.zipWith (VG.zipWith (\\x y -> magnitude x * magnitude y)) a b\n  printCurrentTime \"\"\n  -- M.mapM_\n  --   (\\s -> do\n  --      let !arr =\n  --            getNormalizedHistogramArr hist :: R.Array U DIM4 (Complex Double)\n  --          initArr =\n  --            traverse4\n  --              (fromListUnboxed (Z :. L.length phiFreqs) phiFreqs)\n  --              (fromListUnboxed (Z :. L.length rhoFreqs) rhoFreqs)\n  --              (fromListUnboxed (Z :. L.length thetaFreqs) thetaFreqs)\n  --              (fromListUnboxed (Z :. L.length scaleFreqs) scaleFreqs)\n  --              (\\_ _ _ _ -> extent arr) $ \\fPhi fRho fTheta fScale (Z :. scale :. theta :. rho :. phi) ->\n  --              cis $\n  --              (-pi * log s) * fRho (Z :. rho) / halfLogPeriod -\n  --              (fPhi (Z :. phi) * t0 * pi / 180)\n  --      printCurrentTime \"\"\n  --      source <- computeUnboxedP $ arr *^ initArr\n  --      plotImageRepaComplex (folderPath </> (printf \"Source_%.2f.png\" s)) .\n  --        ImageRepa 8 .\n  --        fromUnboxed (Z :. (1 :: Int) :. numPoint :. numPoint) .\n  --        L.foldl1' (VU.zipWith (+)) .\n  --        computeFourierSeriesThetaR\n  --          numOrientation\n  --          numScale\n  --          thetaFreqs\n  --          scaleFreqs\n  --          halfLogPeriod .\n  --        computeFourierSeriesR2\n  --          numPoint\n  --          deltaX\n  --          numPoint\n  --          deltaX\n  --          phiFreqs\n  --          rhoFreqs\n  --          thetaFreqs\n  --          scaleFreqs\n  --          halfLogPeriod\n  --          maxScale\n  --          harmonicsArray $\n  --        source)\n  --   [1,1.25 .. s0]\n", "meta": {"hexsha": "93d978289ae5a516e52c98c4fccaf44b5e07c83c", "size": 10350, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCFourierSeries/STCFourierSeries.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/STCFourierSeries/STCFourierSeries.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/STCFourierSeries/STCFourierSeries.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 30.9880239521, "max_line_length": 287, "alphanum_fraction": 0.5710144928, "num_tokens": 2870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4292528830659302}}
{"text": "-------------------------------------------------------------------------------\n-- |\n-- Module    :  Spaces.Action\n-- Copyright :  (c) Sentenai 2017\n-- License   :  BSD3\n-- Maintainer:  sam@sentenai.com\n-- Stability :  experimental\n-- Portability: non-portable\n--\n-- typeclass for a discrete action space, as well as helper functions\n-------------------------------------------------------------------------------\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Reinforce.Spaces.Action\n  ( DiscreteActionSpace(..)\n  -- , oneHot\n  , oneHot'\n  , allActions\n  , randomChoice\n  ) where\n\nimport Control.Monad.IO.Class\n-- import Numeric.LinearAlgebra.Static (R)\n-- import qualified Numeric.LinearAlgebra.Static as LA\n\nimport Control.MonadMWCRandom\nimport GHC.TypeLits\nimport Data.Proxy\nimport Data.Vector (Vector)\nimport qualified Data.Vector as V\n\n-- | Mostly tags around an Enum, but includes information about the size of\n-- an action space and is used in helper functions.\nclass (Bounded a, Enum a) => DiscreteActionSpace a where\n  type Size a :: Nat\n\n  toAction :: Int -> a\n  toAction = toEnum\n\n  fromAction :: a -> Int\n  fromAction = fromEnum\n\n\n-- | one-hot encode a bounded enumerable. Doesn't care if minBound is < or > 0\n-- oneHot :: forall a . (KnownNat (Size a), DiscreteActionSpace a) => a -> R (Size a)\n-- oneHot e = LA.vector . V.toList\n--   $ V.unsafeUpd (replicateZeros (Proxy :: Proxy a)) [(fromEnum e, 1)]\n\n\n-- | one-hot encode a bounded enumerable\noneHot' :: forall a . (DiscreteActionSpace a) => a -> Vector Double\noneHot' e = V.unsafeUpd (replicateZeros (Proxy :: Proxy a)) [(fromEnum e, 1)]\n\n\n-- | helper function to initialize a one-hot vector\nreplicateZeros :: forall a . (Enum a, Bounded a) => Proxy a -> Vector Double\nreplicateZeros _ = V.fromList $ replicate (fromEnum (maxBound :: a) + 1) 0\n\n\n-- | helper function to get all actions in a discrete action space\nallActions :: DiscreteActionSpace a => [a]\nallActions = [minBound..maxBound]\n\n-- | make a uniform-random selection of an Action in a discrete action space\nrandomChoice\n  :: forall m a . (MonadIO m , MonadMWCRandom m, DiscreteActionSpace a)\n  => m a\nrandomChoice = toEnum . fst <$> sampleFrom uniformDist\n  where\n    uniformDist :: [Double]\n    uniformDist = fmap (\\a -> convert a / total) allActions\n      where\n        convert :: a -> Double\n        convert = fromIntegral . fromEnum\n\n        total :: Double\n        total = sum (fmap convert allActions)\n\n\n\n", "meta": {"hexsha": "dafc9f0bfef1637286674864f0cef87c2ba76d2d", "size": 2526, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "reinforce/src/Reinforce/Spaces/Action.hs", "max_stars_repo_name": "juliendehos/reinforce", "max_stars_repo_head_hexsha": "f503c9b85cf20dbf7443655a5921e5aa58c94ccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-04-25T19:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T16:48:41.000Z", "max_issues_repo_path": "reinforce/src/Reinforce/Spaces/Action.hs", "max_issues_repo_name": "sentenai/reinforce", "max_issues_repo_head_hexsha": "03fdeea14c606f4fe2390863778c99ebe1f0a7ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2017-03-17T21:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-26T09:58:22.000Z", "max_forks_repo_path": "reinforce/src/Reinforce/Spaces/Action.hs", "max_forks_repo_name": "sentenai/reinforce", "max_forks_repo_head_hexsha": "03fdeea14c606f4fe2390863778c99ebe1f0a7ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-07-31T14:31:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T12:03:48.000Z", "avg_line_length": 30.4337349398, "max_line_length": 85, "alphanum_fraction": 0.6464766429, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4291760805280774}}
{"text": "{-# LANGUAGE TupleSections #-}\nmodule Geo.Computations.Trail\n       ( -- * Types         \n         AvgMethod(..)\n       , Selected(..)\n       , PointGrouping\n       , TransformGrouping\n         -- * Utility Functions\n       , isSelected\n       , isNotSelected\n       , onSelected\n       , selLength\n         -- * Trail Functions\n         -- ** Queries\n       , totalDistance\n       , totalTime\n       , avgSpeeds\n       , slidingAverageSpeed\n       , closestDistance\n       , convexHull\n         -- ** Transformations\n       , bezierCurveAt\n       , bezierCurve\n       , linearTime\n       , filterPoints\n         -- ** Grouping Methods\n       , betweenSpeeds\n       , restLocations\n       , spansTime\n       , everyNPoints\n         -- ** Group Transformations \n       , intersectionOf\n       , invertSelection\n       , firstGrouping\n       , lastGrouping\n       , unionOf\n       , refineGrouping\n       , (/\\), (\\/)\n         -- ** Composite Operations (Higher Level)\n       , smoothRests\n       , smoothTrail\n        -- * Misc\n       , bezierPoint\n         ) where\n\nimport Text.Show.Functions ()\nimport Geo.Computations.Basic\n\nimport Control.Arrow (first)\nimport Control.Monad\nimport Data.Fixed (mod')\nimport Data.Function (on)\nimport Data.List as L\nimport Data.Maybe\nimport Data.Ord\nimport Data.Time\n\n\nimport Statistics.Function as F\nimport Statistics.Sample\nimport qualified Data.Vector.Unboxed as V\n\ntakeWhileEnd :: (a -> Bool) -> [a] -> (Maybe a, [a],[a])\ntakeWhileEnd p xs = go xs Nothing\n  where\n  go [] e = (e, [], [])\n  go (a:as) e\n    | p a = let (e',xs2,zs) = go as (Just a) in (e',a:xs2,zs)\n    | otherwise = (e,[], a:as)\n\ndata AvgMethod c\n  = AvgMean              -- ^ Obtain the 'mean' of the considered points\n  | AvgHarmonicMean      -- ^ Obtain the 'harmonicMean'\n  | AvgGeometricMean     -- ^ Obtain the 'geometricMean'\n  | AvgMedian            -- ^ Obtain the median of the considered points\n  | AvgEndPoints         -- ^ Compute the speed considering only the given endpoints\n  | AvgMinOf [AvgMethod c] -- ^ Take the minimum of the speeds from the given methods\n  | AvgWith ([c] -> Speed)\n    \n-- | @avgSpeeds n points@\n-- Average speed using a window of up to @n@ seconds and averaging by taking the\n-- Median ('AvgMedian').\navgSpeeds :: NominalDiffTime -> Trail Point -> [(UTCTime, Speed)]\navgSpeeds = slidingAverageSpeed AvgHarmonicMean\n\n-- | @slidingAverageSpeed m n@ Average speed using a moving window of up to @n@ seconds\n-- and an 'AvgMethod' of @m@.\nslidingAverageSpeed :: AvgMethod Point -> NominalDiffTime -> Trail Point -> [(UTCTime, Speed)]\nslidingAverageSpeed _ _ [] = []\nslidingAverageSpeed m minTime xs =\n  let pts   = map unSelect (spansTime minTime xs)\n      spds  = map (getAvg m) pts\n      times = map getAvgTimes pts\n  in concatMap maybeToList $ zipWith (\\t s -> fmap (,s) t) times spds\n  where\n  getTimeDiff a b = on (liftM2 diffUTCTime) pntTime a b\n  \n  --  getAvg :: [] -> AvgMethod -> Speed\n  getAvg _ [] = 0\n  getAvg _ [_] = 0\n  getAvg m2 cs =\n    let ss = getSpeedsV cs\n    in case m2 of\n        AvgMean -> mean ss\n        AvgHarmonicMean  -> harmonicMean ss\n        AvgGeometricMean -> geometricMean ss\n        AvgMedian ->\n          let ss' = F.sort $ getSpeedsV cs\n              len = V.length ss'\n              mid = len `div` 2\n          in if V.length ss' < 3\n             then mean ss'\n             else if odd len then ss' V.! mid else mean (V.slice mid 2 ss')\n        AvgEndPoints -> fromMaybe 0 $ speed (head cs) (last cs)\n        AvgMinOf as -> minimum $ map (flip getAvg cs) as\n        AvgWith f -> f cs\n  getAvgTimes [] = Nothing\n  getAvgTimes [x] = pntTime x\n  getAvgTimes ps = getAvgTime (head ps) (last ps)\n  getAvgTime a b = liftM2 addUTCTime (getTimeDiff b a) (pntTime a)\n  getSpeedsV = V.fromList . getSpeeds\n  getSpeeds zs = concatMap maybeToList $ zipWith speed zs (drop 1 zs)\n\n-- | A PointGrouping is a function that selects segments of a trail.\n-- \n-- Grouping point _does not_ result in deleted points. It is always true that:\n--\n--     forall g :: PointGrouping c -->\n--     concatMap unSelect (g ts) == ts\n--\n-- The purpose of grouping is usually for later processing.  Any desire to drop\n-- points that didn't meet a particular grouping criterion can be filled with\n-- a composition with 'filter' (or directly via 'filterPoints').\ntype PointGrouping c = Trail c -> [Selected (Trail c)]\n\n-- | Given a selection of coordinates, transform the selected\n-- coordinates in some way (while leaving the non-selected\n-- coordinates unaffected).\ntype TransformGrouping c = [Selected (Trail c)] -> [Selected (Trail c)]\n\n-- | When grouping points, lists of points are either marked as 'Select' or 'NotSelect'.\ndata Selected a = Select {unSelect :: a} | NotSelect {unSelect :: a}\n  deriving (Eq, Ord, Show)\n\nisSelected :: Selected a -> Bool\nisSelected (Select _) = True\nisSelected _ = False\n\nisNotSelected :: Selected a -> Bool\nisNotSelected = not . isSelected\n\nselLength :: Selected [a] -> Int\nselLength = length . unSelect\n\nonSelected :: (a -> b) -> (a -> b) -> Selected a -> b\nonSelected f _ (Select a) = f a\nonSelected _ g (NotSelect a) = g a\n\ninstance Functor Selected where\n  fmap f (Select x) = Select $ f x\n  fmap f (NotSelect x) = NotSelect $ f x\n\ndropExact :: Int -> [Selected [a]] -> [Selected [a]]\ndropExact _ [] = []\ndropExact i (x:xs) =\n  case compare (selLength x) i of\n    EQ -> xs\n    LT -> dropExact (i - selLength x) xs\n    GT -> fmap (drop i) x : xs\n\n-- | Groups trail segments into contiguous points within the speed\n-- and all others outside of the speed.  The \"speed\" from point p(i)\n-- to p(i+1) is associated with p(i) (except for the first speed\n-- value, which is associated with both the first and second point)\nbetweenSpeeds :: Double -> Double -> PointGrouping Point\nbetweenSpeeds low hi ps =\n  let spds = concatMap maybeToList $ zipWith speed ps (drop 1 ps)\n      psSpds = [(p,s) | p <- ps, s <- maybeToList (listToMaybe spds) ++ spds]\n      inRange x = x >= low && x <= hi\n      chunk [] = []\n      chunk xs@(x:_) =\n        let op p = if inRange (snd x) then first Select . span p else first NotSelect . break p\n            (r,rest) = op (inRange . snd) xs\n        in r : chunk rest\n  in map (fmap (map fst)) $ chunk psSpds\n\n-- | A \"rest point\" means the coordinates remain within a given distance\n-- for at least a particular amount of time.\nrestLocations :: Distance -> NominalDiffTime -> PointGrouping Point\nrestLocations d s ps =\n  let consToFirst x [] = [NotSelect [x]]\n      consToFirst x (a:as) = (fmap (x:) a) : as\n      go [] [] = []\n      go [] nonRests = [NotSelect $ reverse nonRests]\n      go (a:as) nonRests =\n        case takeWhileEnd ((<=) d . distance a) as of\n          (Just l, close, far) ->\n            case (pntTime a, pntTime l) of\n              (Just t1, Just t2) ->\n                let diff = diffUTCTime t2 t1\n                in if diff >= s then NotSelect (reverse nonRests) : Select (a:close) : go far [] else go as (a:nonRests)\n              _ -> consToFirst a $ go as nonRests\n          _ -> consToFirst a $ go as nonRests\n  in go ps []\n     \n-- | Chunks points into groups spanning at most the given time\n-- interval.\nspansTime :: NominalDiffTime -> PointGrouping Point\nspansTime n ps =\n  let times  = mkTimePair ps\n      chunk [] = []\n      chunk xs@(x:_) =\n        let (good,rest) = span ((<= addUTCTime n (snd x)) . snd) xs \n        in if null good then [xs] else good : chunk rest\n  in map (Select . map fst) $ chunk times\n\n-- | Intersects the given groupings\nintersectionOf :: [PointGrouping Point] -> PointGrouping Point\nintersectionOf gs ps =\n  let groupings = map ($ ps) gs\n      -- chunk :: [[Selected [pnts]]] -> pnts -> [pnts]\n      chunk _ [] = []\n      chunk ggs xs = \n        let minLen = max 1 . minimum . concatMap (take 1) $ map (map selLength) ggs   -- FIXME this is all manner of broken\n            sel = if all isSelected (concatMap (take 1) ggs) then Select else NotSelect\n            (c,rest) = splitAt minLen xs\n        in sel c : chunk (filter (not . null) $ map (dropExact minLen) ggs) rest\n  in chunk groupings ps\n\n-- | Union all the groupings\nunionOf :: [PointGrouping Point] -> PointGrouping Point\nunionOf gs ps =\n  let groupings = map ($ ps) gs\n      chunk _ [] = []\n      chunk ggs xs =\n        let getSegs = concatMap (take 1)\n            segs = getSegs ggs\n            len =\n              if any isSelected segs\n                 then max 1 . maximum . getSegs . map (map selLength) . map (filter isSelected) $ ggs\n                 else max 1 . minimum . getSegs . map (map selLength) $ ggs\n            sel = if any isSelected segs then Select else NotSelect\n            (c,rest) = splitAt len xs\n        in sel c : chunk (filter (not . null) $ map (dropExact len) ggs) rest\n  in chunk groupings ps\n     \n-- | Intersection binary operator\n(/\\) :: [Selected (Trail a)] -> TransformGrouping a\n(/\\) _ [] = []\n(/\\) [] _ = []\n(/\\) xsL@(Select x:_) ysL@(Select y:_) =\n  let z = if length x < length y then x else y\n      xs' = selListDrop (length z) xsL\n      ys' = selListDrop (length z) ysL\n  in Select z : (xs' /\\ ys')\n(/\\) xs (NotSelect y:ys) = NotSelect y : (selListDrop (length y) xs /\\ ys)\n(/\\) (NotSelect x:xs) ys = NotSelect x : (xs /\\ selListDrop (length x) ys)\n\n-- | Union binary operator\n(\\/) :: [Selected (Trail a)] -> TransformGrouping a\n(\\/) xs [] = xs\n(\\/) [] ys = ys\n(\\/) (Select x:xs) (Select y : ys) =\n  let xLen = length x\n      yLen = length y\n  in if xLen < yLen\n       then (Select y :) (selListDrop (yLen - xLen) xs \\/ ys)\n       else (Select x :) (xs \\/ selListDrop (xLen - yLen) ys)\n(\\/) (Select x:_) ys = Select x : selListDrop (length x) ys\n(\\/) xs (Select y:_) = Select y : selListDrop (length y) xs\n(\\/) xsL@(NotSelect x:xs) ysL@(NotSelect y:ys) =\n  let xLen = length x\n      yLen = length y\n  in if xLen < yLen\n        then (NotSelect x:) (xs \\/ selListDrop xLen ysL)\n        else (NotSelect y:) (selListDrop yLen xsL \\/ ys)\n\nselListDrop :: Int -> [Selected [a]] -> [Selected [a]]\nselListDrop 0 xs = xs\nselListDrop _ [] = []\nselListDrop n (x:xs) =\n  let x' = drop n (unSelect x)\n  in fmap (const x') x : selListDrop (n - (selLength x - length x')) xs\n\n-- | Inverts the selected/nonselected segments\ninvertSelection :: TransformGrouping a\ninvertSelection = map (onSelected NotSelect Select)\n\n-- | @firstGrouping f ps@ only the first segment remains 'Select'ed, and only\n-- if it was already selected by @f@.\nfirstGrouping ::  TransformGrouping a\nfirstGrouping ps = take 1 ps ++ map (NotSelect . unSelect) (drop 1 ps)\n\n-- | Only the last segment, if any, is selected (note: the current\n-- implementation is inefficient, using 'reverse')\nlastGrouping ::  TransformGrouping a\nlastGrouping ps  = let ps' = reverse ps in reverse $ take 1 ps' ++ map (NotSelect . unSelect) (drop 1 ps')\n\n-- | Chunks the trail into groups of N points\neveryNPoints ::  Int -> PointGrouping a\neveryNPoints n ps\n  | n <= 0 = [NotSelect ps]\n  | otherwise = go ps\n    where\n      go [] = []\n      go xs = let (h,t) = splitAt n xs in Select h : go t\n  \n-- | For every selected group, refine the selection using the second\n-- grouping method.  This differs from 'IntersectionOf' by restarting\n-- the second grouping algorithm at the beginning each group selected\n-- by the first algorithm.\nrefineGrouping ::  PointGrouping a -> TransformGrouping a\nrefineGrouping b = concatMap (onSelected b (\\x -> [NotSelect x]))\n\n-- | Remove all points that remain 'NotSelect'ed by the given grouping algorithm.\nfilterPoints :: PointGrouping a -> Trail a -> Trail a\nfilterPoints g = concatMap unSelect . filter isSelected . g\n\n-- Extract the time from each coordinate.  If no time is available then\n-- the coordinate is dropped!\nmkTimePair :: Trail Point -> [(Point,UTCTime)]\nmkTimePair xs =\n  let timesM = map (\\x-> fmap (x,) $ pntTime x) xs\n  in concatMap maybeToList timesM\n\n-- | Construct a bezier curve using the provided trail.  Construct a\n-- new trail by sampling the given bezier curve at the given times.\n-- The current implementation assumes the times of the input\n-- coordinates are available and all equal (Ex: all points are 5\n-- seconds apart), the results will be poor if this is not the case!\nbezierCurveAt :: [UTCTime] -> Trail Point -> Trail Point\nbezierCurveAt _ [] = []\nbezierCurveAt selectedTimes xs = \n  let timesDef = mkTimePair xs\n      end = last timesDef\n      top = head timesDef\n      tTime  = diffUTCTime (snd end) (snd top)\n      times = if null selectedTimes then map snd timesDef else selectedTimes\n      diffTimes = [diffUTCTime t (snd top) / tTime | t <- times]\n      queryTimes = map realToFrac diffTimes\n  in if tTime <= 0 || any (\\x -> x < 0 || x > 1) queryTimes\n        then xs -- error \"bezierCurveAt has a out-of-bound time!\"\n        else\n         if null timesDef || any (\\x -> x < 0 || x > 1) queryTimes\n         then xs\n         else let curvePoints = (map (bezierPoint xs) queryTimes)\n                  newTimes = [addUTCTime t (snd top) | t <- diffTimes]\n              in zipWith (\\t p -> p { pntTime = Just t}) newTimes curvePoints\n\nbezierPoint :: [Point] -> Double -> Point\nbezierPoint pnts t   = go pnts\n  where\n  go [] = error \"GPS Package: Can not create a bezier point from an empty list\"\n  go [p] = p\n  go ps = interpolate (go (init ps)) (go (tail ps)) t\n\n-- | Interpolate selected points onto a bezier curve.  Note this gets\n-- exponentially more expensive with the length of the segment being\n-- transformed - it is not advisable to perform this operation on\n-- trail segements with more than ten points!\nbezierCurve ::  [Selected (Trail Point)] -> Trail Point\nbezierCurve = concatMap (onSelected (bezierCurveAt []) Prelude.id)\n\n-- | Filter out any points that go backward in time (thus must not be\n-- valid if this is a trail)\nlinearTime :: [Point] -> [Point]\nlinearTime [] = []\nlinearTime (p:ps) = go (pntTime p) ps\n  where\n  go _ [] = []\n  go t (x:xs) = if pntTime x < t then go t xs else x : go (pntTime x) xs\n\n-- | Return the closest distance between two trails (or Nothing if a\n-- trail is empty).  Inefficient implementation:\n-- O( (n * m) * log (n * m) )\nclosestDistance :: Trail Point -> Trail Point -> Maybe Distance\nclosestDistance as bs = listToMaybe $ L.sort [distance a b | a <- as, b <- bs]\n\n-- | Find the total distance traveled\ntotalDistance :: [Point] -> Distance\ntotalDistance as = sum $ zipWith distance as (drop 1 as)\n\ntotalTime :: Trail Point -> NominalDiffTime\ntotalTime [] = 0\ntotalTime xs@(x:_) = fromMaybe 0 $ liftM2 diffUTCTime (pntTime $ last xs) (pntTime x)\n\n-- | Uses Grahams scan to compute the convex hull of the given points.\n-- This operation requires sorting of the points, so don't try it unless\n-- you have notably more memory than the list of points will consume.\nconvexHull :: [Point] -> [Point]\nconvexHull lst =\n        let frst = southMost lst\n        in case frst of\n                Nothing -> []\n                Just f  ->\n                     let sorted = L.sortBy (comparing (eastZeroHeading f)) (filter (/= f) lst)\n                     in case sorted of\n                        (a:b:cs) -> grahamScan (b:a:f:[]) cs\n                        cs       -> f : cs\n  where\n  grahamScan [] _ = []\n  grahamScan ps [] = ps\n  grahamScan (x:[]) _ = [x]\n  grahamScan (p2:p1:ps) (x:xs) =\n        case turn p1 p2 x of\n                LeftTurn  -> grahamScan (x:p2:p1:ps) xs\n                Straight  -> grahamScan (x:p2:p1:ps) xs\n                _         -> grahamScan (p1:ps) (x:xs)\n\neastZeroHeading :: Point -> Point -> Heading\neastZeroHeading s = (`mod'` (2*pi)) . (+ pi/2) . heading s\n\ndata Turn = LeftTurn | RightTurn | Straight deriving (Eq, Ord, Show, Read, Enum)\n\nturn :: Point -> Point -> Point -> Turn\nturn a b c =\n        let h1 = eastZeroHeading a b\n            h2 = eastZeroHeading b c\n            d  = h2 - h1\n        in if d >= 0 && d < pi then LeftTurn else RightTurn\n\n-- | Find the southmost point\nsouthMost :: [Point] -> Maybe Point\nsouthMost []  = Nothing\nsouthMost cs = Just . minimumBy (comparing pntLat) $ cs\n\n---------- COMPOSIT OPERATIONS ---------------\n-- These operations are simply implemented using the previously\n-- defined functions. They can serve either for concise use for novice\n-- users or as instructional examples.\n------------------------------------------\n\n-- | Smooth points with rest areas using a bezierCurve.\n--\n-- Parameters: rest for 1 minute within 30 meters get smoothed\n-- in a bezier curve over every 8 points.\nsmoothRests :: Trail Point -> Trail Point\nsmoothRests = bezierCurve . refineGrouping (everyNPoints 8) . restLocations 30 60\n\n-- | Smooth every 7 points using a bezier curve\nsmoothTrail :: Trail Point -> Trail Point\nsmoothTrail = gSmoothSome 7\n\n-- | Smooth every n points using a bezier curve\ngSmoothSome :: Int -> Trail Point -> Trail Point\ngSmoothSome n = bezierCurve . everyNPoints n\n", "meta": {"hexsha": "30a029f8129722524748b7824ed612854da9c5ac", "size": 16766, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Geo/Computations/Trail.hs", "max_stars_repo_name": "beezee/gps", "max_stars_repo_head_hexsha": "739ff6d9112eee56950969c65493358a8efec78e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-09-01T01:00:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-03T00:58:59.000Z", "max_issues_repo_path": "Geo/Computations/Trail.hs", "max_issues_repo_name": "beezee/gps", "max_issues_repo_head_hexsha": "739ff6d9112eee56950969c65493358a8efec78e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-02-08T14:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-30T03:12:49.000Z", "max_forks_repo_path": "Geo/Computations/Trail.hs", "max_forks_repo_name": "beezee/gps", "max_forks_repo_head_hexsha": "739ff6d9112eee56950969c65493358a8efec78e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-18T12:08:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-30T02:17:38.000Z", "avg_line_length": 37.5078299776, "max_line_length": 123, "alphanum_fraction": 0.6300846952, "num_tokens": 4735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4289256662009424}}
{"text": "{-|\nModule: Numeric.Morpheus.MatrixReduce\nDescription: Matrix reduce by column/row operations.\nCopyright: (c) Alexander Ignatyev, 2017\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n-}\n\nmodule Numeric.Morpheus.MatrixReduce\n(\n  columnPredicate\n  , rowPredicate\n  , columnSum\n  , rowSum\n  , columnMaxIndex\n  , columnMinIndex\n  , rowMaxIndex\n  , rowMinIndex\n)\n\nwhere\n\nimport Numeric.Morpheus.Utils(morpheusLayout)\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Devel\nimport System.IO.Unsafe(unsafePerformIO)\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.Ptr(Ptr)\n\n\ntype Predicate = R -> R -> R\nforeign import ccall \"wrapper\" mkPredicate :: Predicate -> IO (FunPtr Predicate)\n\n\n{- morpheus_column_predicate -}\nforeign import ccall safe \"morpheus_column_predicate\"\n  c_morpheus_column_predicate :: FunPtr Predicate -> CInt -> CInt -> CInt\n                              -> Ptr R -> Ptr R -> IO ()\n\n\ncall_morpheus_column_predicate :: FunPtr Predicate\n                               -> CInt -> CInt -> CInt -> CInt -> Ptr R\n                               -> CInt -> Ptr R\n                               -> IO ()\ncall_morpheus_column_predicate f rows cols xRow xCol matPtr _ vecPtr = do\n  let layout = morpheusLayout xCol cols\n  c_morpheus_column_predicate f layout rows cols matPtr vecPtr\n\n\n-- | Scan every column of the given matrix.\n-- Predicate takes and accumulator and next value of the column, returns new accumulator.\n-- Returns accumulator values for every column.\ncolumnPredicate :: (R -> R -> R) -> Matrix R -> Vector R\ncolumnPredicate f m = unsafePerformIO $ do\n  v <- createVector (cols m)\n  fpred <- mkPredicate f\n  apply m (apply v id) (call_morpheus_column_predicate fpred)\n  return v\n\n\n{- morpheus_row_predicate -}\nforeign import ccall safe \"morpheus_row_predicate\"\n  c_morpheus_row_predicate :: FunPtr Predicate -> CInt -> CInt -> CInt\n                           -> Ptr R -> Ptr R -> IO ()\n\n\ncall_morpheus_row_predicate :: FunPtr Predicate\n                            -> CInt -> CInt -> CInt -> CInt -> Ptr R\n                            -> CInt -> Ptr R\n                            -> IO ()\ncall_morpheus_row_predicate f rows cols xRow xCol matPtr _ vecPtr = do\n  let layout = morpheusLayout xCol cols\n  c_morpheus_row_predicate f layout rows cols matPtr vecPtr\n\n\n-- | Scan every row of the given matrix.\n-- Predicate takes and accumulator and next value of the row, returns new accumulator.\n-- Returns accumulator values for every row.\nrowPredicate :: (R -> R -> R) -> Matrix R -> Vector R\nrowPredicate f m = unsafePerformIO $ do\n  v <- createVector (rows m)\n  fpred <- mkPredicate f\n  apply m (apply v id) (call_morpheus_row_predicate fpred)\n  return v\n\n\n{- morpheus_column_sum -}\nforeign import ccall unsafe \"morpheus_column_sum\"\n  c_morpheus_column_sum :: CInt -> CInt -> CInt -> Ptr Double -> Ptr Double -> IO ()\n\n\ncall_morpheus_column_sum :: CInt -> CInt -> CInt -> CInt -> Ptr Double\n                         -> CInt -> Ptr Double\n                         -> IO ()\ncall_morpheus_column_sum rows cols xRow xCol matPtr _ vecPtr = do\n  let layout = morpheusLayout xCol cols\n  c_morpheus_column_sum layout rows cols matPtr vecPtr\n\n\n-- | Calculates sums of elements of every column of the given matrix\ncolumnSum :: Matrix Double -> Vector Double\ncolumnSum m = unsafePerformIO $ do\n    v <- createVector (cols m)\n    apply m (apply v id) call_morpheus_column_sum\n    return v\n\n\n{- morpheus_row_sum -}\nforeign import ccall unsafe \"morpheus_row_sum\"\n  c_morpheus_row_sum :: CInt -> CInt -> CInt -> Ptr Double -> Ptr Double -> IO ()\n\n\ncall_morpheus_row_sum :: CInt -> CInt -> CInt -> CInt -> Ptr Double\n                      -> CInt -> Ptr Double\n                      -> IO ()\ncall_morpheus_row_sum rows cols xRow xCol matPtr _ vecPtr = do\n  let layout = morpheusLayout xCol cols\n  c_morpheus_row_sum layout rows cols matPtr vecPtr\n\n\n-- | Calculates sums of elements of every row of the given matrix\nrowSum :: Matrix Double -> Vector Double\nrowSum m = unsafePerformIO $ do\n    v <- createVector (rows m)\n    apply m (apply v id) call_morpheus_row_sum\n    return v\n\n\n{- morpheus_column_max_index -}\nforeign import ccall unsafe \"morpheus_column_max_index\"\n  c_morpheus_column_max_index :: CInt -> CInt -> CInt -> Ptr Double -> Ptr Double -> Ptr CInt -> IO ()\n\n\ncall_morpheus_column_max_index :: CInt -> CInt -> CInt -> CInt -> Ptr Double\n                                  -> CInt -> Ptr Double\n                                  -> CInt -> Ptr CInt\n                                  -> IO ()\ncall_morpheus_column_max_index rows cols xRow xCol matPtr _ vecPtr _ idxPtr = do\n  let layout = morpheusLayout xCol cols\n  c_morpheus_column_max_index layout rows cols matPtr vecPtr idxPtr\n\n\n-- | Finds maximum values and their indices of every column of the given matrix\ncolumnMaxIndex :: Matrix Double -> (Vector R, Vector I)\ncolumnMaxIndex m = unsafePerformIO $ do\n    v <- createVector (cols m)\n    i <- createVector (cols m)\n    apply m (apply v (apply i id)) call_morpheus_column_max_index\n    return (v, i)\n\n\n{- morpheus_column_min_index -}\nforeign import ccall unsafe \"morpheus_column_min_index\"\n  c_morpheus_column_min_index :: CInt -> CInt -> CInt -> Ptr Double -> Ptr Double -> Ptr CInt -> IO ()\n\n\ncall_morpheus_column_min_index :: CInt -> CInt -> CInt -> CInt -> Ptr Double\n                                  -> CInt -> Ptr Double\n                                  -> CInt -> Ptr CInt\n                                  -> IO ()\ncall_morpheus_column_min_index rows cols xRow xCol matPtr _ vecPtr _ idxPtr = do\n  let layout = morpheusLayout xCol cols\n  c_morpheus_column_min_index layout rows cols matPtr vecPtr idxPtr\n\n\n-- | Finds minimum values and their indices of every column of the given matrix\ncolumnMinIndex :: Matrix Double -> (Vector R, Vector I)\ncolumnMinIndex m = unsafePerformIO $ do\n    v <- createVector (cols m)\n    i <- createVector (cols m)\n    apply m (apply v (apply i id)) call_morpheus_column_min_index\n    return (v, i)\n\n\n{- morpheus_row_max_index -}\nforeign import ccall unsafe \"morpheus_row_max_index\"\n  c_morpheus_row_max_index :: CInt -> CInt -> CInt -> Ptr Double -> Ptr Double -> Ptr CInt -> IO ()\n\n\ncall_morpheus_row_max_index :: CInt -> CInt -> CInt -> CInt -> Ptr Double\n                               -> CInt -> Ptr Double\n                               -> CInt -> Ptr CInt\n                               -> IO ()\ncall_morpheus_row_max_index rows cols xRow xCol matPtr _ vecPtr _ idxPtr = do\n  let layout = morpheusLayout xCol cols\n  c_morpheus_row_max_index layout rows cols matPtr vecPtr idxPtr\n\n\n-- | Finds maximum values and their indices of every row of the given matrix\nrowMaxIndex :: Matrix Double -> (Vector R, Vector I)\nrowMaxIndex m = unsafePerformIO $ do\n    v <- createVector (rows m)\n    i <- createVector (rows m)\n    apply m (apply v (apply i id)) call_morpheus_row_max_index\n    return (v, i)\n\n\n{- morpheus_row_min_index -}\nforeign import ccall unsafe \"morpheus_row_min_index\"\n  c_morpheus_row_min_index :: CInt -> CInt -> CInt -> Ptr Double -> Ptr Double -> Ptr CInt -> IO ()\n\n\ncall_morpheus_row_min_index :: CInt -> CInt -> CInt -> CInt -> Ptr Double\n                               -> CInt -> Ptr Double\n                               -> CInt -> Ptr CInt\n                               -> IO ()\ncall_morpheus_row_min_index rows cols xRow xCol matPtr _ vecPtr _ idxPtr = do\n  let layout = morpheusLayout xCol cols\n  c_morpheus_row_min_index layout rows cols matPtr vecPtr idxPtr\n\n\n-- | Finds minimum values and their indices of every row of the given matrix\nrowMinIndex :: Matrix Double -> (Vector R, Vector I)\nrowMinIndex m = unsafePerformIO $ do\n    v <- createVector (rows m)\n    i <- createVector (rows m)\n    apply m (apply v (apply i id)) call_morpheus_row_min_index\n    return (v, i)\n", "meta": {"hexsha": "39105c6964b2219021e93ede9bda1fb2857dd0d7", "size": 7776, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "hmatrix-morpheus/src/Numeric/Morpheus/MatrixReduce.hs", "max_stars_repo_name": "Alexander-Ignatyev/morpheus", "max_stars_repo_head_hexsha": "ee01b67441cb2e27abff4a025bd0be4a44762108", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-08-04T19:44:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T11:30:47.000Z", "max_issues_repo_path": "hmatrix-morpheus/src/Numeric/Morpheus/MatrixReduce.hs", "max_issues_repo_name": "aligusnet/morpheus", "max_issues_repo_head_hexsha": "ee01b67441cb2e27abff4a025bd0be4a44762108", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hmatrix-morpheus/src/Numeric/Morpheus/MatrixReduce.hs", "max_forks_repo_name": "aligusnet/morpheus", "max_forks_repo_head_hexsha": "ee01b67441cb2e27abff4a025bd0be4a44762108", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.027027027, "max_line_length": 102, "alphanum_fraction": 0.660622428, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4288795672360338}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n\n-- $ ghc -O2 --make wrappers.hs functions.c\n\nimport Numeric.LinearAlgebra\nimport Data.Packed.Development\nimport Foreign(Ptr,unsafePerformIO)\nimport Foreign.C.Types(CInt)\n\n-----------------------------------------------------\n\nmain = do\n    print $ myDiag $ (3><5) [1..]\n\n-----------------------------------------------------\n-- arbitrary data order\n\nforeign import ccall unsafe \"c_diag\"\n    cDiag :: CInt                        -- matrix order\n          -> CInt -> CInt -> Ptr Double  -- argument\n          -> CInt -> Ptr Double          -- result1\n          -> CInt -> CInt -> Ptr Double  -- result2\n          -> IO CInt                     -- exit code\n\nmyDiag m = unsafePerformIO $ do\n    y <- createVector (min r c)\n    z <- createMatrix (orderOf m) r c\n    app3 (cDiag o) mat m vec y mat z \"cDiag\"\n    return (y,z)\n  where r = rows m\n        c = cols m\n        o = if orderOf m == RowMajor then 1 else 0\n", "meta": {"hexsha": "1c02a249d47059cbfacd1e16a8e9b220e2fe042b", "size": 952, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/devel/ej2/wrappers.hs", "max_stars_repo_name": "curiousleo/liquidhaskell", "max_stars_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 941, "max_stars_repo_stars_event_min_datetime": "2015-01-13T10:51:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:32:32.000Z", "max_issues_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/devel/ej2/wrappers.hs", "max_issues_repo_name": "curiousleo/liquidhaskell", "max_issues_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 1300, "max_issues_repo_issues_event_min_datetime": "2015-01-01T05:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:11:03.000Z", "max_forks_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/devel/ej2/wrappers.hs", "max_forks_repo_name": "curiousleo/liquidhaskell", "max_forks_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 145, "max_forks_repo_forks_event_min_datetime": "2015-01-12T08:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:29:30.000Z", "avg_line_length": 28.8484848485, "max_line_length": 56, "alphanum_fraction": 0.5094537815, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.428846360115051}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n{-|\nModule      : Grenade.Layers.Internal.Add\nDescription : Fast addition functions that call efficient C function\nMaintainer  : Theo Charalambous\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.Internal.Add (\n  addPerChannel\n) where\n\nimport qualified Data.Vector.Storable        as U (unsafeFromForeignPtr0,\n                                                   unsafeToForeignPtr0)\n\nimport           Foreign                     (mallocForeignPtrArray, withForeignPtr)\nimport           Foreign.Ptr                 (Ptr)\nimport           Numeric.LinearAlgebra       (Matrix, Vector, flatten)\nimport qualified Numeric.LinearAlgebra.Devel as U\nimport           System.IO.Unsafe            (unsafePerformIO)\n\nimport           Grenade.Types\n\n-- | Add the nth element to a vector to every pixel in the nth channel of a matrix.\n--   It assumes that the size of the vector and the number of channels in the matrix \n--   are both equal to channels.\naddPerChannel :: Int -> Int -> Int -> Matrix RealNum -> Vector RealNum -> Matrix RealNum\naddPerChannel channels rows cols m b\n  = let outMatSize      = rows * cols * channels\n        vec             = flatten m\n    in unsafePerformIO $ do\n      outPtr        <- mallocForeignPtrArray outMatSize\n      let (inPtr, _) = U.unsafeToForeignPtr0 vec\n          (bPtr, _)  = U.unsafeToForeignPtr0 b\n \n      withForeignPtr inPtr $ \\inPtr' ->\n        withForeignPtr bPtr $ \\bPtr' ->\n          withForeignPtr outPtr $ \\outPtr' ->\n            add_per_channel_cpu inPtr' channels rows cols bPtr' outPtr'\n \n      let matVec = U.unsafeFromForeignPtr0 outPtr outMatSize\n      return (U.matrixFromVector U.RowMajor (rows * channels) cols matVec)\n{-# INLINE addPerChannel #-}\n\nforeign import ccall unsafe\n    add_per_channel_cpu\n      :: Ptr RealNum -> Int -> Int -> Int -> Ptr RealNum -> Ptr RealNum -> IO ()\n", "meta": {"hexsha": "46afb045a125cfb9f41ba198d4e293573f2c24e9", "size": 1895, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/Add.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Internal/Add.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Internal/Add.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4791666667, "max_line_length": 88, "alphanum_fraction": 0.6485488127, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4286968293265634}}
{"text": "{-# LANGUAGE DeriveGeneric #-}\n\n-- import BDSCOD.Conditioning\nimport BDSCOD.Aggregation\nimport qualified BDSCOD.InhomogeneousBDSLlhd as InhomBDSLlhd\nimport BDSCOD.Llhd\nimport BDSCOD.Types\nimport BDSCOD.Utility\nimport Control.Monad (replicateM)\nimport Data.List (sort)\nimport Data.Maybe (fromJust, isJust)\nimport Data.Tuple (swap)\nimport qualified Data.Vector.Unboxed as Unboxed\nimport qualified Epidemic as EpiSim\nimport qualified Epidemic.BirthDeathSampling as EpiBDS\nimport qualified Epidemic.BDSCOD as EpiBDSCOD\nimport Epidemic.Types.Events\nimport Epidemic.Types.Parameter\nimport Epidemic.Types.Population\nimport qualified Epidemic.Utility as EpiUtil\nimport GHC.Generics\nimport Generic.Random (genericArbitraryU)\nimport Numeric.LinearAlgebra.HMatrix\nimport qualified System.Random.MWC as MWC\nimport Test.Hspec\nimport Test.Hspec.QuickCheck\nimport Test.QuickCheck\nimport Test.QuickCheck.Gen\nimport Test.Hspec.Core.QuickCheck (modifyMaxDiscardRatio)\nimport Data.Either.Combinators (fromRight', isLeft)\n\n-- | Check if @y@ is withing @delta@ of @x@\nwithinDeltaOf :: (Ord a, Num a)\n              => a -- ^ delta\n              -> a -- ^ y\n              -> a -- ^ x\n              -> Bool\nwithinDeltaOf delta y x = abs (y - x) < delta\n\n-- | Apply the @withinDeltaOf@ function to two lists.\nallWithinDeltaOf :: (Ord a, Num a) => a -> [a] -> [a] -> Bool\nallWithinDeltaOf _ [] [] = True\nallWithinDeltaOf delta [y] [x] = withinDeltaOf delta y x\nallWithinDeltaOf delta (y:ys) (x:xs) = withinDeltaOf delta y x && allWithinDeltaOf delta ys xs\nallWithinDeltaOf _ _ _ = False\n\n\nunsafeNBFromMAndV x = fromRight' $ nbFromMAndV x\n\n\n-- | Approximate the derivative of @f@ at @x@ with a step of size @h@.\nfiniteDifference :: Fractional a\n                 => a         -- ^ h\n                 -> (a -> a)  -- ^ f\n                 -> a         -- ^ x\n                 -> a\nfiniteDifference h f x = (f (x+h) - f (x-h)) / (2*h)\n\ntestTestingHelpers =\n  describe \"Testing the helper functions for the testing suite\" $ do\n    context \"withinDeltaOf\" $ do\n      it \"sanity\" $ do\n        withinDeltaOf 0.2 1 2 `shouldBe` False\n        withinDeltaOf 0.2 1 1.1 `shouldBe` True\n      it \"identity\" $ property $\n        \\x -> withinDeltaOf 0.2 x (x :: Double)\n      it \"range\" $ property $\n        \\x -> withinDeltaOf 1 1 (1 + (x :: Double)) || not (x < 1 && x > (-1))\n    context \"finiteDifference\" $ do\n      it \"sine\" $ property $\n        \\x -> let fFD = finiteDifference 0.01 sin\n                  f' = cos\n                in withinDeltaOf 1e-3 (fFD (x :: Double)) (f' x)\n      it \"polynomial\" $ property $\n        \\x -> let fFD = finiteDifference 0.01 (\\z -> z + 0.5 * z ** 2)\n                  f' = \\z -> 1 + z\n                in withinDeltaOf 1e-3 (fFD (x :: Double)) (f' x)\n\ntestLogSumExp =\n  describe \"Test the log-sum-exp function\" $\n    it \"equivalence to unsafe implementation\" $ property $\n      \\x -> (not $ null x) ==> withinDeltaOf 1e-6 (logSumExp x) (log (sum [exp x' | x' <- x :: [Double]]))\n\n\ntestNbPGF = do\n  describe \"Test nbPGF: 1\" $ do\n    it \"known value of PGF is correct 1\" $\n      nbPGF Zero 0.0 `shouldBe` 1\n\n    it \"known value of PGF is correct 2\" $\n      nbPGF Zero 0.5 `shouldBe` 1\n\n    it \"known value of PGF is correct 3\" $\n      nbPGF Zero 1.0 `shouldBe` 1\n\n    it \"known value of PGF is correct 4\" $\n      nbPGF (NegBinomSizeProb 1 0.5) 0.0 `shouldBe` 0.5\n\n    it \"known value of PGF is correct 5\" $\n      nbPGF (NegBinomSizeProb 1 0.5) 0.5 `shouldSatisfy` (withinDeltaOf 1e-6 (2.0 / 3.0))\n\n    it \"known value of PGF is correct 5\" $\n      nbPGF (NegBinomSizeProb 1 0.5) 1.0 `shouldBe` 1.0\n\n    it \"PGF partial derivative seems correct 1\" $\n      nbPGF' (NegBinomSizeProb 1 0.5) 1.0 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-3 (\\x -> nbPGF (NegBinomSizeProb 1 0.5) x) 1.0))\n\n    it \"PGF partial derivative seems correct 2\" $\n      nbPGF' (NegBinomSizeProb 1 0.5) 0.5 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-3 (\\x -> nbPGF (NegBinomSizeProb 1 0.5) x) 0.5))\n\n    it \"PGF partial derivative seems correct 3\" $\n      nbPGF' (NegBinomSizeProb 1 0.5) 0.0 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-3 (\\x -> nbPGF (NegBinomSizeProb 1 0.5) x) 0.0))\n\n    it \"PGF second partial derivative seems correct 1\" $\n      nbPGF'' (NegBinomSizeProb 1 0.5) 1.0 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-3 (\\x -> nbPGF' (NegBinomSizeProb 1 0.5) x) 1.0))\n\n    it \"PGF second partial derivative seems correct 2\" $\n      nbPGF'' (NegBinomSizeProb 1 0.5) 0.5 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\x -> nbPGF' (NegBinomSizeProb 1 0.5) x) 0.5))\n\n    it \"PGF second partial derivative seems correct 3\" $\n      nbPGF'' (NegBinomSizeProb 1 0.5) 0.0 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\x -> nbPGF' (NegBinomSizeProb 1 0.5) x) 0.0))\n\n  describe \"Test nbPGF: 2\" $ do\n    it \"test pochhammer and logPochhammer\" $ do\n      pochhammer 2 5 > 2 `shouldBe` True\n      let pochhammersWorking (a,b) = withinDeltaOf 1e-5 (log $ pochhammer a b) (logPochhammer a b)\n      all pochhammersWorking [(a,b) | a <- [1..10], b <- [1..10], a <= b] `shouldBe` True\n      all pochhammersWorking [(a+0.1,b) | a <- [1..10], b <- [1..10], a <= b] `shouldBe` True\n\n    it \"test nbPGFdash and logNbPGFdash\" $ do\n      let nbPGFdashWorking (j,r,p,z) = withinDeltaOf 1e-5 (log $ nbPGFdash j (NegBinomSizeProb r p) z) (logNbPGFdash j (NegBinomSizeProb r p) z)\n      all nbPGFdashWorking [(j,r,p,z) | j <- [2..50], r <- [2..50], p <- [0.1,0.3,0.5,0.7,0.9], z <- [0.1,0.3,0.5,0.7,0.9]] `shouldBe` True\n\n    it \"test nbPGF and logNbPGF\" $ do\n      let nbPGFWorking (r,p,z) = withinDeltaOf 1e-5 (log $ nbPGF (NegBinomSizeProb r p) z) (logNbPGF (NegBinomSizeProb r p) z)\n      all nbPGFWorking [(r,p,z) | r <- [2..50], p <- [0.1,0.3,0.5,0.7,0.9], z <- [0.1,0.3,0.5,0.7,0.9]] `shouldBe` True\n\n    it \"test nbPGF' and logNbPGF'\" $ do\n      let nbPGFWorking (r,p,z) = withinDeltaOf 1e-5 (log $ nbPGF' (NegBinomSizeProb r p) z) (logNbPGF' (NegBinomSizeProb r p) z)\n      all nbPGFWorking [(r,p,z) | r <- [2..50], p <- [0.1,0.3,0.5,0.7,0.9], z <- [0.1,0.3,0.5,0.7,0.9]] `shouldBe` True\n\n    it \"test nbPGF'' and logNbPGF''\" $ do\n      let nbPGFWorking (r,p,z) = withinDeltaOf 1e-5 (log $ nbPGF'' (NegBinomSizeProb r p) z) (logNbPGF'' (NegBinomSizeProb r p) z)\n      all nbPGFWorking [(r,p,z) | r <- [2..50], p <- [0.1,0.3,0.5,0.7,0.9], z <- [0.1,0.3,0.5,0.7,0.9]] `shouldBe` True\n\ntestLogPdeGF1 = do\n    describe \"test pdeGF and logPdeGF\" $ do\n      modifyMaxDiscardRatio (const 1000) $\n        it \"test pdeGF and logPdeGF\" $ property $\n        \\(z\n         , delay\n         , lam\n         , mu) -> (z > 0) &&\n                  (delay < 30) &&\n                  (delay > 0) &&\n                  (lam < 30) &&\n                  (lam > 0) &&\n                  (mu < 30) &&\n                  (mu > 0) ==>\n                  withinDeltaOf 1e-3 (log $ pdeGF (params lam mu) (TimeDelta delay) pdeSol z) (logPdeGF (params lam mu) (TimeDelta delay) pdeSol z)\n                  where params lam mu = (Parameters (lam, mu, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed []))\n                        pdeSol = (PDESol Zero 1)\n\ntestLogPdeGF2 = do\n    describe \"test pdeGF and logPdeGF again\" $ do\n      modifyMaxDiscardRatio (const 10000) $\n        it \"test pdeGF and logPdeGF again\" $ property $\n        \\(z\n         , lam\n         , delay\n         , nbMean\n         , nbVar) -> (z <= 1) && (z > 0) &&\n                     (lam < 200) &&\n                     (lam > 0) &&\n                     (delay < 200) &&\n                     (delay > 0) &&\n                     (nbMean > 0) &&\n                     (nbVar > nbMean) ==>\n                     withinDeltaOf 1e-3 (log $ pdeGF (params lam) (scaledDelay delay) (pdeSol (nbMean,nbVar)) z) (logPdeGF (params lam) (scaledDelay delay) (pdeSol (nbMean,nbVar)) z)\n                     where params lam = (Parameters (lam / 10, 0.3, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed []))\n                           pdeSol nbStats = (PDESol (unsafeNBFromMAndV nbStats) 1)\n                           scaledDelay d = TimeDelta $ d / 10\n\n\ntestLogPdeGFDash1 = do\n    describe \"test pdeGF' and logPdeGF'\" $ do\n      modifyMaxDiscardRatio (const 1000) $\n        it \"test pdeGF' and logPdeGF'\" $ property $\n        \\(z100\n         , delay\n         , lam\n         , mu) -> (z100 <= 100) &&\n                  (z100 > 0) &&\n                  (delay < 30) &&\n                  (delay > 0) &&\n                  (lam < 30) &&\n                  (lam > 0) &&\n                  (mu < 30) &&\n                  (mu > 0) ==>\n                  withinDeltaOf 1e-3 (log $ pdeGF' (params lam mu) (TimeDelta delay) pdeSol (z100 / 100)) (logPdeGF' (params lam mu) (TimeDelta delay) pdeSol (z100 / 100))\n                  where params lam mu = (Parameters (lam, mu, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed []))\n                        pdeSol = (PDESol Zero 1)\n\ntestLogPdeGFDash2 = do\n    describe \"test pdeGF' and logPdeGF' again\" $ do\n      modifyMaxDiscardRatio (const 10000) $\n        it \"test pdeGF' and logPdeGF' again\" $ property $\n        \\(z\n         , lam\n         , delay\n         , nbMean\n         , nbVar) -> (z <= 1) && (z > 0) &&\n                     (lam < 200) &&\n                     (lam > 0) &&\n                     (delay < 200) &&\n                     (delay > 0) &&\n                     (nbMean > 0) &&\n                     (nbVar > nbMean) ==>\n                     withinDeltaOf 1e-3 (log $ pdeGF' (params lam) (scaledDelay delay) (pdeSol (nbMean,nbVar)) z) (logPdeGF' (params lam) (scaledDelay delay) (pdeSol (nbMean,nbVar)) z)\n                     where params lam = (Parameters (lam / 10, 0.3, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed []))\n                           pdeSol nbStats = (PDESol (unsafeNBFromMAndV nbStats) 1)\n                           scaledDelay d = TimeDelta $ d / 50\n\ntestLogPdeGFDashDash1 = do\n    describe \"test pdeGF'' and logPdeGF''\" $ do\n      modifyMaxDiscardRatio (const 1000) $\n        it \"test pdeGF'' and logPdeGF''\" $ property $\n        \\(z100\n         , delay\n         , lam\n         , mu) -> (z100 <= 100) &&\n                  (z100 > 0) &&\n                  (delay < 30) &&\n                  (delay > 0) &&\n                  (lam < 30) &&\n                  (lam > 0) &&\n                  (mu < 30) &&\n                  (mu > 0) ==>\n                  withinDeltaOf 1e-3 (log $ pdeGF'' (params lam mu) (TimeDelta delay) pdeSol (z100 / 100)) (logPdeGF'' (params lam mu) (TimeDelta delay) pdeSol (z100 / 100))\n                  where params lam mu = (Parameters (lam, mu, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed []))\n                        pdeSol = (PDESol Zero 1)\n\ntestLogPdeGFDashDash2 = do\n    describe \"test pdeGF'' and logPdeGF'' again\" $ do\n      modifyMaxDiscardRatio (const 10000) $\n        it \"test pdeGF'' and logPdeGF'' again\" $ property $\n        \\(z\n         , lam\n         , delay\n         , nbMean\n         , nbVar) -> (z <= 1) && (z > 0) &&\n                     (lam < 200) &&\n                     (lam > 0) &&\n                     (delay < 200) &&\n                     (delay > 0) &&\n                     (nbMean > 0) &&\n                     (nbVar > nbMean) ==>\n                     withinDeltaOf 1e-3 (log $ pdeGF'' (params lam) (scaledDelay delay) (pdeSol (nbMean,nbVar)) z) (logPdeGF'' (params lam) (scaledDelay delay) (pdeSol (nbMean,nbVar)) z)\n                     where params lam = (Parameters (lam / 10, 0.3, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed []))\n                           pdeSol nbStats = (PDESol (unsafeNBFromMAndV nbStats) 1)\n                           scaledDelay d = TimeDelta $ d / 50\n\n\n\ntestLogPdeStatistics = do\n    describe \"test pdeStatistics and logPdeStatistics\" $ do\n      modifyMaxDiscardRatio (const 10000) $\n        it \"test pdeStatistics and logPdeStatistics\" $ property $\n        \\( lam\n         , delay\n         , nbMean\n         , nbVar) -> (lam < 200) &&\n                     (lam > 6) &&\n                     (delay < 200) &&\n                     (delay > 0) &&\n                     (nbMean > 1) &&\n                     (nbVar > nbMean) ==>\n                     withinDeltaOf 1e-3 (log . fst' $ fooUnlogged lam (TimeDelta delay) nbMean nbVar) (fst' $ fooLogged lam (TimeDelta delay) nbMean nbVar) &&\n                     withinDeltaOf 1e-3 (log . snd' $ fooUnlogged lam (TimeDelta delay) nbMean nbVar) (snd' $ fooLogged lam (TimeDelta delay) nbMean nbVar) &&\n                     withinDeltaOf 1e-3 (log . thd' $ fooUnlogged lam (TimeDelta delay) nbMean nbVar) (thd' $ fooLogged lam (TimeDelta delay) nbMean nbVar)\n                     where params lam = (Parameters (lam / 10, 0.3, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed []))\n                           pdeSol nbStats = (PDESol (unsafeNBFromMAndV nbStats) 1)\n                           scaledDelay d = TimeDelta $ d / 50\n                           fooUnlogged lam (TimeDelta delay) nbMean nbVar = pdeStatistics (params lam) (scaledDelay delay) (pdeSol (nbMean,nbVar))\n                           fooLogged lam (TimeDelta delay) nbMean nbVar  = (logPdeStatistics (params lam) (scaledDelay delay) (pdeSol (nbMean,nbVar)))\n                           fst' (a,_,_) = a\n                           snd' (_,a,_) = a\n                           thd' (_,_,a) = a\n\n\n\ntestp0 = do\n  describe \"Test p0\" $ do\n    it \"Initial condition 1\" $ do\n      p0 (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 0.0001) 0.2 `shouldSatisfy` (withinDeltaOf 1e-3 0.2)\n      p0 (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 0.0001) 1.0 `shouldSatisfy` (withinDeltaOf 1e-3 1.0)\n\n    it \"Evolution 1\" $\n      let a = p0 (Parameters (2.3, 0.5, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.2\n          b = p0 (Parameters (2.3, 0.5, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.1) 0.2\n       in a > b `shouldBe` True\n\n    it \"Long term condition 1\" $ do\n      p0 (Parameters (0.001, 5.9, 0.001, Timed [(AbsoluteTime 1000, 0.001)], 0.01, Timed [])) (TimeDelta 100.0) 0.2 `shouldSatisfy` (withinDeltaOf 1e-2 1.0)\n      p0 (Parameters (0.001, 5.9, 0.001, Timed [(AbsoluteTime 1000, 0.001)], 0.01, Timed [])) (TimeDelta 100.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-2 1.0)\n\n    it \"Long term condition 2\" $ do\n      p0 (Parameters (10.1, 0.1, 9.0, Timed [(AbsoluteTime 1000, 1.0)], 0.01, Timed [])) (TimeDelta 100.0) 0.2 `shouldSatisfy` (withinDeltaOf 1e-2 0.0)\n      p0 (Parameters (10.1, 0.1, 9.0, Timed [(AbsoluteTime 1000, 1.0)], 0.01, Timed [])) (TimeDelta 100.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-2 0.0)\n\n    it \"First partial derivative seems correct 1\" $ do\n      p0' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.7 `shouldSatisfy` (withinDeltaOf 1e-2 (finiteDifference 1e-5 (\\z -> p0 (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) z) 0.7))\n      p0' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> p0 (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) z) 0.9))\n      p0' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) 0.7 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> p0 (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) z) 0.7))\n      p0' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> p0 (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) z) 0.9))\n\n    it \"Second partial derivative seems correct 1\" $ do\n      p0'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.7 `shouldSatisfy` (withinDeltaOf 1e-2 (finiteDifference 1e-5 (\\z -> p0' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) z) 0.7))\n      p0'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> p0' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) z) 0.9))\n      p0'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) 0.7 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> p0' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) z) 0.7))\n      p0'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> p0' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) z) 0.9))\n\n\ntestRr = do\n  describe \"Test rr\" $ do\n    it \"Initial condition 1\" $ do\n      rr (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 0.0001) 0.2 `shouldSatisfy` (withinDeltaOf 1e-3 (0.8/0.8))\n      rr (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 0.0001) 0.9 `shouldSatisfy` (withinDeltaOf 1e-3 (0.1/0.1))\n\n    it \"Evolution 1\" $\n      let a = rr (Parameters (0.001, 0.001, 0.001, Timed [(AbsoluteTime 1000,0.9)], 0.001, Timed [])) (TimeDelta 0.01) 0.3\n          b = rr (Parameters (0.001, 0.001, 0.001, Timed [(AbsoluteTime 1000,0.9)], 0.001, Timed [])) (TimeDelta 0.01) 0.2\n       in a > b `shouldBe` True\n\n    it \"Long term condition 1\" $ do\n      rr (Parameters (3, 0.9, 0.01, Timed [(AbsoluteTime 1000,0.1)], 0.1, Timed [])) (TimeDelta 100.0) 0.2 `shouldSatisfy` (withinDeltaOf 1e-2 0.0)\n      rr (Parameters (3, 0.9, 0.01, Timed [(AbsoluteTime 1000,0.1)], 0.1, Timed [])) (TimeDelta 100.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-2 0.0)\n\n    it \"Long term condition 2\" $\n      let a = rr (Parameters (3, 0.1, 0.01, Timed [(AbsoluteTime 1000,0.1)], 0.1, Timed [])) (TimeDelta 1.1) (0.9/(1-0.9))\n          b = rr (Parameters (3, 0.1, 0.01, Timed [(AbsoluteTime 1000,0.1)], 0.1, Timed [])) (TimeDelta 1.1) (0.8/(1-0.8))\n          c = rr (Parameters (3, 0.1, 0.01, Timed [(AbsoluteTime 1000,0.1)], 0.1, Timed [])) (TimeDelta 1.1) (0.3/(1-0.3))\n       in do\n        a < b `shouldBe` True\n        b < c `shouldBe` True\n\n    it \"First partial derivative seems correct 1\" $ do\n      rr' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.7 `shouldSatisfy` (withinDeltaOf 1e-2 (finiteDifference 1e-5 (\\z -> rr (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) z) 0.7))\n      rr' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> rr (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) z) 0.9))\n      rr' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) 0.7 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> rr (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) z) 0.7))\n      rr' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> rr (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) z) 0.9))\n\n    it \"Second partial derivative seems correct 1\" $ do\n      rr'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.7 `shouldSatisfy` (withinDeltaOf 1e-2 (finiteDifference 1e-5 (\\z -> rr' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) z) 0.7))\n      rr'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> rr' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) z) 0.9))\n      rr'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) 0.7 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> rr' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) z) 0.7))\n      rr'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) 0.9 `shouldSatisfy` (withinDeltaOf 1e-5 (finiteDifference 1e-5 (\\z -> rr' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) z) 0.9))\n\n\ntestPdeGF = do\n  describe \"Test pdeGF\" $ do\n    it \"First partial derivative seems correct 1\" $ do\n      pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol Zero 1) 0.7 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 ((\\z -> pdeGF (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol Zero 1) z)) 0.7))\n      pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol Zero 1) 0.9 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol Zero 1) z) 0.9))\n      pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol Zero 1) 0.7 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol Zero 1) z) 0.7))\n      pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol Zero 1) 0.9 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol Zero 1) z) 0.9))\n      pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) 0.7 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) z) 0.7))\n      pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) 0.9 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) z) 0.9))\n      pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) 0.7 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) z) 0.7))\n      pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) 0.9 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) z) 0.9))\n\n    it \"Second partial derivative seems correct 1\" $ do\n      pdeGF'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol Zero 1) 0.7 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol Zero 1) z) 0.7))\n      pdeGF'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol Zero 1) 0.9 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol Zero 1) z) 0.9))\n      pdeGF'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol Zero 1) 0.7 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol Zero 1) z) 0.7))\n      pdeGF'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol Zero 1) 0.9 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol Zero 1) z) 0.9))\n      pdeGF'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) 0.7 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) z) 0.7))\n      pdeGF'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) 0.9 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-6 (\\z -> pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 1.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) z) 0.9))\n      pdeGF'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) 0.7 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) z) 0.7))\n      pdeGF'' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) 0.9 `shouldSatisfy` (withinDeltaOf 1e-4 (finiteDifference 1e-5 (\\z -> pdeGF' (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) (TimeDelta 2.0) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 1) z) 0.9))\n\ntestPdeStatistics = do\n  describe \"Test pdeStatistics\" $ do\n    it \"Properties 1\" $\n      let (c,m,v) = pdeStatistics (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1) (PDESol Zero 1)\n          (c',m',v') = pdeStatistics (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2) (PDESol Zero 1)\n          (c'',m'',v'') = pdeStatistics (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 20) (PDESol Zero 1)\n       in do\n        c > c' `shouldBe` True\n        c' > c'' `shouldBe` True\n        c'' `shouldSatisfy` (withinDeltaOf 1e-6 0.0)\n        m < m' `shouldBe` True\n        m' < m'' `shouldBe` True\n        v < v' `shouldBe` True\n        v' < v'' `shouldBe` True\n        m < v `shouldBe` True\n        m' < v' `shouldBe` True\n        m'' < v'' `shouldBe` True\n\n    it \"Properties 2\" $\n      let (c,m,v) = pdeStatistics (Parameters (2.3, 1.2, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 1) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 2)\n          (c',m',v') = pdeStatistics (Parameters (2.3, 1.2, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 2) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 2)\n          (c'',m'',v'') = pdeStatistics (Parameters (2.3, 1.2, 0.3, Timed [(AbsoluteTime 1000,0.5)], 0.6, Timed [])) (TimeDelta 20) (PDESol (unsafeNBFromMAndV (3.0,9.0)) 2)\n       in do\n        c > c' `shouldBe` True\n        c' > c'' `shouldBe` True\n        c'' `shouldSatisfy` (withinDeltaOf 1e-6 0.0)\n        m < m' `shouldBe` True\n        m' < m'' `shouldBe` True\n        v < v' `shouldBe` True\n        v' < v'' `shouldBe` True\n        m < v `shouldBe` True\n        m' < v' `shouldBe` True\n        m'' < v'' `shouldBe` True\n\n    it \"Properties 3\" $\n      let (c,m,v) = pdeStatistics (Parameters (2.0,1.0,0.5, Timed [(AbsoluteTime 1000,0.5)],0.4,Timed [])) (TimeDelta 2.0) (PDESol (NegBinomSizeProb 3.9 0.5) 1.0)\n       in do\n        c > 0 `shouldBe` True\n        m > 0 `shouldBe` True\n        v > m `shouldBe` True\n\n\ntestLlhd = do\n  describe \"Test llhd\" $ do\n    it \"Manceau example\" $\n      let obs = [ (TimeDelta 1.0, OBirth)\n                , (TimeDelta 1.0, OOccurrence)\n                , (TimeDelta 1.0, OBirth)\n                , (TimeDelta 1.0, OBirth)\n                , (TimeDelta 1.0, ObsUnscheduledSequenced)\n                , (TimeDelta 1.0, OOccurrence)\n                , (TimeDelta 1.0, OCatastrophe 3) ]\n          params lam = Parameters (lam,1.0,0.3, Timed [(AbsoluteTime 7.0,0.5)],0.6,Timed [])\n          (llhdVal1,_) = unsafeLlhdAndNB obs (params 1.1) initLlhdState\n          (llhdVal2,_) = unsafeLlhdAndNB obs (params 1.2) initLlhdState\n          (llhdVal3,_) = unsafeLlhdAndNB obs (params 1.3) initLlhdState\n          (llhdVal9,_) = unsafeLlhdAndNB obs (params 1.9) initLlhdState\n       in do\n        llhdVal1 `shouldSatisfy` (withinDeltaOf 1e-1 (-40.5))\n        llhdVal2 `shouldSatisfy` (withinDeltaOf 2e-1 (-41.0))\n        llhdVal3 `shouldSatisfy` (withinDeltaOf 2e-1 (-41.5))\n        llhdVal9 `shouldSatisfy` (withinDeltaOf 2e-1 (-46.0))\n\ntestInhomBDSLlhd = do\n  describe \"Test inhomogeneous BDS LLHD\" $ do\n    it \"Check for constant parameters it looks right\" $\n      let obs = [(TimeDelta 1.0,OBirth),(TimeDelta 1.0,OBirth),(TimeDelta 1.0,ObsUnscheduledSequenced),(TimeDelta 1.0,ObsUnscheduledSequenced),(TimeDelta 1.0,ObsUnscheduledSequenced)]\n          tlams = fromJust $ asTimed [(AbsoluteTime 0,1.2)]\n          tlams' = fromJust $ asTimed [(AbsoluteTime 0,1.2),(AbsoluteTime 10,5.0)]\n          tlams'' = fromJust $ asTimed [(AbsoluteTime 0,1.3),(AbsoluteTime 10,5.0)]\n          tlams''' = fromJust $ asTimed [(AbsoluteTime 0,1.3),(AbsoluteTime 0.5,1.4)]\n          tlams'''' = fromJust $ asTimed [(AbsoluteTime 0,1.3),(AbsoluteTime 1.5,1.3),(AbsoluteTime 2.5,1.3)]\n          lam = fromJust $ cadlagValue tlams (AbsoluteTime 0.1)\n          lam'' = fromJust $ cadlagValue tlams'' (AbsoluteTime 0.1)\n          (llhdValXXX1,_) = InhomBDSLlhd.inhomLlhdAndNB obs (InhomBDSLlhd.InhomParams (tlams,1.0,0.3)) InhomBDSLlhd.initLlhdState\n          (llhdValXXX2,_) = InhomBDSLlhd.inhomLlhdAndNB obs (InhomBDSLlhd.InhomParams (tlams',1.0,0.3)) InhomBDSLlhd.initLlhdState\n          (llhdValXXX3,_) = InhomBDSLlhd.inhomLlhdAndNB obs (InhomBDSLlhd.InhomParams (tlams'',1.0,0.3)) InhomBDSLlhd.initLlhdState\n          (llhdValXXX4,_) = InhomBDSLlhd.inhomLlhdAndNB obs (InhomBDSLlhd.InhomParams (tlams''',1.0,0.3)) InhomBDSLlhd.initLlhdState\n          (llhdValXXX5,_) = InhomBDSLlhd.inhomLlhdAndNB obs (InhomBDSLlhd.InhomParams (tlams'''',1.0,0.3)) InhomBDSLlhd.initLlhdState\n          (llhdValYYY1,_) = unsafeLlhdAndNB obs (Parameters (lam,1.0,0.3,Timed [],0.0,Timed [])) initLlhdState\n          (llhdValYYY2,_) = unsafeLlhdAndNB obs (Parameters (lam'',1.0,0.3,Timed [],0.0,Timed [])) initLlhdState\n          (llhdValYYY3,_) = unsafeLlhdAndNB obs (Parameters (lam'' + 0.1,1.0,0.3,Timed [],0.0,Timed [])) initLlhdState\n       in do\n        llhdValXXX1 `shouldSatisfy` (withinDeltaOf 1e-3 (llhdValYYY1))\n        llhdValXXX2 `shouldSatisfy` (withinDeltaOf 1e-3 (llhdValYYY1))\n        llhdValXXX3 `shouldSatisfy` (withinDeltaOf 1e-3 (llhdValYYY2))\n        llhdValXXX3 `shouldSatisfy` (\\l -> not $ withinDeltaOf 1e-3 llhdValYYY1 l)\n        (if llhdValYYY3 < llhdValYYY2 then llhdValXXX3 > llhdValXXX4 else llhdValXXX3 < llhdValXXX4) `shouldBe` True\n        llhdValXXX5 `shouldSatisfy` (withinDeltaOf 1e-1 (llhdValYYY2)) -- exposes limitation of approximation!!!\n    describe \"Check values are finite when sensible\" $\n      let infParams = (InhomBDSLlhd.InhomParams (fromJust $ asTimed [(AbsoluteTime 0.0,1.0),(AbsoluteTime 1.0,1.0)],0.4,0.4)) :: InhomBDSLlhd.InhomParams\n          (InhomBDSLlhd.InhomParams (tlams,_,_)) = infParams\n          obs = [(TimeDelta 0.3,OBirth),(TimeDelta 0.5,OBirth),(TimeDelta 0.19,ObsUnscheduledSequenced)]\n          llhdVal = fst $ InhomBDSLlhd.inhomLlhdAndNB obs infParams InhomBDSLlhd.initLlhdState\n          obs' = [(TimeDelta 0.3,OBirth),(TimeDelta 0.5,OBirth),(TimeDelta 0.20,ObsUnscheduledSequenced)]\n          llhdVal' = fst $ InhomBDSLlhd.inhomLlhdAndNB obs' infParams InhomBDSLlhd.initLlhdState\n          obs'' = [(TimeDelta 0.3,OBirth),(TimeDelta 0.5,OBirth),(TimeDelta 0.21,ObsUnscheduledSequenced)]\n          llhdVal'' = fst $ InhomBDSLlhd.inhomLlhdAndNB obs'' infParams InhomBDSLlhd.initLlhdState\n       in do\n        it \"Check cadlagValue\" $ do\n          cadlagValue tlams (AbsoluteTime 1.1) == Just 1.0 `shouldBe` True\n          cadlagValue tlams (AbsoluteTime 1.0) == Just 1.0 `shouldBe` True\n          cadlagValue tlams (AbsoluteTime 0.9) == Just 1.0 `shouldBe` True\n        it \"Check nextTime\" $ do\n          isJust (nextTime tlams (AbsoluteTime 1.1)) `shouldBe` True\n          isJust (nextTime tlams (AbsoluteTime 1.0)) `shouldBe` True\n          isJust (nextTime tlams (AbsoluteTime 0.9)) `shouldBe` True\n        it \"Check llhdValue\" $ do\n          isInfinite llhdVal `shouldBe` False\n          isInfinite llhdVal' `shouldBe` False\n          isInfinite llhdVal'' `shouldBe` False\n\ntestConversion = do\n  describe \"Test conversion between event types\" $ do\n    it \"Demonstration data set 1\" $\n      let p1 = Person (Identifier 1)\n          p2 = Person (Identifier 2)\n          p4 = Person (Identifier 4)\n          p5 = Person (Identifier 5)\n          p6 = Person (Identifier 6)\n          simObsEvents =\n            [ Infection (AbsoluteTime 1) p1 p2\n            , Sampling (AbsoluteTime 3) p1\n            , Infection (AbsoluteTime 4) p2 p4\n            , Sampling (AbsoluteTime 6) p4\n            , Occurrence (AbsoluteTime 8) p2\n            , Occurrence (AbsoluteTime 11) p6\n            , Sampling (AbsoluteTime 12) p5\n            ]\n          llhdObsEvents =\n            [ (TimeDelta 1.0, OBirth)\n            , (TimeDelta 2.0, ObsUnscheduledSequenced)\n            , (TimeDelta 1.0, OBirth)\n            , (TimeDelta 2.0, ObsUnscheduledSequenced)\n            , (TimeDelta 2.0, OOccurrence)\n            , (TimeDelta 3.0, OOccurrence)\n            , (TimeDelta 1.0, ObsUnscheduledSequenced)\n            ]\n       in eventsAsObservations simObsEvents `shouldSatisfy` (== llhdObsEvents)\n\n\n\n\ntestImpossibleParameters = do\n  describe \"Test correct handling of impossible parameters\" $ do\n    it \"Test negative birth rate is impossible\" $\n      let obs = [(TimeDelta 1.0,OBirth),(TimeDelta 1.0,OOccurrence),(TimeDelta 1.0,OBirth),(TimeDelta 1.0,OBirth),(TimeDelta 1.0,ObsUnscheduledSequenced),(TimeDelta 1.0,OOccurrence)]\n          llhd1 = fst $ unsafeLlhdAndNB obs (Parameters (0.0000000001,1.0,0.3,Timed [],0.6,Timed [])) initLlhdState\n          llhd2 = llhdAndNB obs (Parameters (0.0000000000,1.0,0.3,Timed [],0.6,Timed [])) initLlhdState\n          llhd3 = llhdAndNB obs (Parameters (-0.0000000001,1.0,0.3,Timed [],0.6,Timed [])) initLlhdState\n       in do\n        isNaN llhd1 `shouldBe` False\n        isInfinite llhd1 `shouldBe` False\n        llhd1 < 0 `shouldBe` True\n        isLeft llhd2 `shouldBe` True\n        isLeft llhd3 `shouldBe` True\n    it \"Test negative sampling rate is impossible\" $\n      let obs1 = [(TimeDelta 1.0,OBirth),(TimeDelta 1.0,OOccurrence),(TimeDelta 1.0,OBirth),(TimeDelta 1.0,OBirth),(TimeDelta 1.0,ObsUnscheduledSequenced),(TimeDelta 1.0,OOccurrence)]\n          obs2 = [(TimeDelta 1.0,OBirth),(TimeDelta 1.0,OOccurrence),(TimeDelta 1.0,OBirth),(TimeDelta 1.0,OBirth),(TimeDelta 1.0,OOccurrence)]\n          llhd11 = fst $ unsafeLlhdAndNB obs1 (Parameters (1.0,1.0,0.1,Timed [],0.6,Timed [])) initLlhdState\n          llhd12 = llhdAndNB obs1 (Parameters (1.0,1.0,0.0,Timed [],0.6,Timed [])) initLlhdState\n          llhd13 = llhdAndNB obs1 (Parameters (1.0,1.0,-0.1,Timed [],0.6,Timed [])) initLlhdState\n          llhd21 = fst $ unsafeLlhdAndNB obs2 (Parameters (1.0,1.0,0.1,Timed [],0.6,Timed [])) initLlhdState\n          llhd22 = fst $ unsafeLlhdAndNB obs2 (Parameters (1.0,1.0,0.0,Timed [],0.6,Timed [])) initLlhdState\n          llhd23 = llhdAndNB obs2 (Parameters (1.0,1.0,-0.1,Timed [],0.6,Timed [])) initLlhdState\n       in do\n        isNaN llhd11 `shouldBe` False\n        isLeft llhd12 `shouldBe` True\n        isLeft llhd13 `shouldBe` True\n        isNaN llhd21 `shouldBe` False\n        isNaN llhd22 `shouldBe` False\n        isLeft llhd23 `shouldBe` True\n        isInfinite llhd11 `shouldBe` False\n        isInfinite llhd21 `shouldBe` False\n        isInfinite llhd22 `shouldBe` False\n\ntmpIsSampling :: EpidemicEvent -> Bool\ntmpIsSampling e = case e of\n  Sampling{} -> True\n  _ -> False\n\ntestParameterUpdate :: SpecWith ()\ntestParameterUpdate =\n  let params1 = (Parameters (2.4, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) :: Parameters\n      params2 = (Parameters (2.3, 1, 0.3, Timed [(AbsoluteTime 1000, 0.5)], 0.6, Timed [])) :: Parameters\n      params3 = (Parameters (2.4, 1, 0.3, Timed [(AbsoluteTime 1000, 0.6)], 0.6, Timed [])) :: Parameters\n    in do describe \"Testing parameter update function\" $ do\n            it \"test lambda update\" $ do\n              (params1 /= params2) `shouldBe` True\n              (params1 == putLambda params2 2.4) `shouldBe` True\n            it \"test rhos update\" $ do\n              (params1 /= params3) `shouldBe` True\n              (params1 == putRhos params3 (Timed [(AbsoluteTime 1000, 0.5)])) `shouldBe` True\n\n-- | This test case looks at how to set the seed when using @mwc-random@. We\n-- care about this because we want to be able to generate reproducible\n-- simulations without being restricted to the fixed seed that is the default\n-- value.\ntestMWCSeeding :: SpecWith ()\ntestMWCSeeding = do\n  describe \"Testing MWC seeding\" $ do\n    it \"test create works as expected\" $ do\n      gen <- MWC.create\n      x1 <- (MWC.uniform gen :: IO Double)\n      x2 <- (MWC.uniform gen :: IO Double)\n      gen' <- MWC.create\n      x1' <- (MWC.uniform gen' :: IO Double)\n      (x1 /= x2) `shouldBe` True\n      (x1 == x1') `shouldBe` True\n    it \"test initialise works as expected\" $ do\n      xGen <- MWC.create\n      x1 <- (MWC.uniform xGen :: IO Double)\n      yGen <- MWC.initialize (Unboxed.fromList [1,2,3])\n      y1 <- (MWC.uniform yGen :: IO Double)\n      (x1 /= y1) `shouldBe` True\n      y2 <- (MWC.uniform yGen :: IO Double)\n      (y1 /= y2) `shouldBe` True\n      zGen <- MWC.initialize (Unboxed.fromList [1,2,3])\n      z1 <- (MWC.uniform zGen :: IO Double)\n      (y1 == z1) `shouldBe` True\n      wGen <- MWC.initialize (Unboxed.fromList [3,2,1])\n      w1 <- (MWC.uniform wGen :: IO Double)\n      (z1 /= w1) `shouldBe` True\n\n\n-- | Generate a random @NumLineages@\nqcRandomNumLineages :: Gen NumLineages\nqcRandomNumLineages = do\n  kDouble <- choose (1 + 1e-6, 1e2 :: Double)\n  return . fromIntegral $ round kDouble\n\n-- | Generate a random @Rate@\nqcRandomRate :: Gen Rate\nqcRandomRate = choose (1e-3, 1e1)\n\n-- | Generate a random @Probability@\nqcRandomProbability :: Gen Probability\nqcRandomProbability = choose (0, 1)\n\n-- | Generate a random @NegativeBinomial@ using @NegBinomSizeProb@ /not/ any\n-- other constructor.\nqcRandomNegBinomSizeProb :: Gen NegativeBinomial\nqcRandomNegBinomSizeProb = do\n  r <- qcRandomRate\n  p <- qcRandomProbability\n  return $ NegBinomSizeProb r p\n\n-- | Generate a random @TimeDelta@\nqcRandomTimeDelta :: Gen TimeDelta\nqcRandomTimeDelta = do\n  td <- qcRandomRate\n  return $ TimeDelta td\n\n-- | Generate a random __small__ @TimeDelta@\nqcRandomSmallTimeDelta :: Gen TimeDelta\nqcRandomSmallTimeDelta = do\n  td <- choose (1e-3,2)\n  return $ TimeDelta td\n\n-- | Generate a list of absolute times that occur after the origin within the\n-- duration.\nqcRandomOrderedAbsTimes :: AbsoluteTime -> TimeDelta -> Gen [AbsoluteTime]\nqcRandomOrderedAbsTimes (AbsoluteTime a) (TimeDelta d) = do\n  times <- listOf1 $ choose (a, a + d)\n  return [AbsoluteTime t | t <- sort times]\n\n-- | Generate a random @Timed x@ from the start time and the duration and the\n-- constant value to store at each time.\nqcRandomTimedX :: Num x => AbsoluteTime -> TimeDelta -> x -> Gen (Timed x)\nqcRandomTimedX originTime duration x = do\n  absTimes <- qcRandomOrderedAbsTimes originTime duration\n  case asTimed (zip absTimes (repeat x)) of\n    Just timedVals -> return timedVals\n    Nothing -> qcRandomTimedX originTime duration x\n\n-- | Generate a random @Parameters@\nqcRandomParameters :: AbsoluteTime -> TimeDelta -> Gen Parameters\nqcRandomParameters originTime duration = do\n  -- randLambda <- qcRandomRate\n  randMu <- qcRandomRate\n  randPsi <- qcRandomRate\n  randRho <- qcRandomProbability\n  randOmega <- qcRandomRate\n  tmp <- choose (0.5,1.0)\n  let randLambda = (randMu + randPsi + randOmega) / tmp\n  randNu <- qcRandomProbability\n  randTimedRho <- qcRandomTimedX originTime duration randRho\n  randTimedNu <- qcRandomTimedX originTime duration randNu\n  return $\n    Parameters\n      (randLambda, randMu, randPsi, randTimedRho, randOmega, randTimedNu)\n\n-- | Generate a random @ObservedEvent@\nqcRandomObservedEvent :: Gen ObservedEvent\nqcRandomObservedEvent = do\n  isUnscheduled <- chooseAny\n  if isUnscheduled\n    then elements [OBirth, ObsUnscheduledSequenced, OOccurrence]\n    else do\n      isSequenced <- chooseAny\n      numLineages <- suchThat chooseAny (> 0)\n      if isSequenced\n        then return (OCatastrophe numLineages)\n        else return (ODisaster numLineages)\n\n-- | Generate a random list of @observation@ values\nqcRandomObservations :: Gen [Observation]\nqcRandomObservations = do\n  durationDouble <- suchThat chooseAny (> 0) :: Gen Double\n  eventAbsTimesDoubles <- listOf1 (choose (0, durationDouble))\n  let duration = TimeDelta durationDouble\n      eventAbsTimes = [AbsoluteTime t | t <- eventAbsTimesDoubles]\n  let eats = sort ((AbsoluteTime 0) : eventAbsTimes)\n      timeDeltas = [timeDelta a b | (a, b) <- zip (init eats) (tail eats)]\n      numEvents = length eventAbsTimes\n  eventTypes <- vectorOf numEvents qcRandomObservedEvent\n  return $ zip timeDeltas eventTypes\n\n\n-- | A copy of the @withinDeltaOf@ function specialised to\n-- @AggregatedObservations@ to test for approximate equality of aggregated\n-- observations.\nwithinDeltaOfAggObs :: Double\n                    -> AggregatedObservations\n                    -> AggregatedObservations\n                    -> Bool\nwithinDeltaOfAggObs delta (AggregatedObservations aggTimes obs) (AggregatedObservations aggTimes' obs') =\n  withinDeltaOfAggTimes delta aggTimes aggTimes' &&  allWithinDeltaOfObs delta obs obs'\n\n\nwithinDeltaOfAbsoluteTimes :: Double -> AbsoluteTime -> AbsoluteTime -> Bool\nwithinDeltaOfAbsoluteTimes delta (AbsoluteTime a) (AbsoluteTime b) = withinDeltaOf delta a b\n\nallWithinDeltaOfAbsoluteTimes :: Double -> [AbsoluteTime] -> [AbsoluteTime] -> Bool\nallWithinDeltaOfAbsoluteTimes delta absTimes1 absTimes2 =\n  let f (a,b) = withinDeltaOfAbsoluteTimes delta a b\n      absTimePairs = zip absTimes1 absTimes2\n  in all f absTimePairs\n\n\nwithinDeltaOfTimeDeltas :: Double -> TimeDelta -> TimeDelta -> Bool\nwithinDeltaOfTimeDeltas delta (TimeDelta a) (TimeDelta b) = withinDeltaOf delta a b\n\nallWithinDeltaOfTimeDeltas :: Double -> [TimeDelta] -> [TimeDelta] -> Bool\nallWithinDeltaOfTimeDeltas delta timeDels1 timeDels2 =\n  let f (a,b) = withinDeltaOfTimeDeltas delta a b\n      timeDelPairs = zip timeDels1 timeDels2\n  in all f timeDelPairs\n\n\nwithinDeltaOfAggTimes :: Double -> AggregationTimes -> AggregationTimes -> Bool\nwithinDeltaOfAggTimes delta (AggTimes ts) (AggTimes ts') =\n  let times = map fst ts\n      obsEvents = map snd ts\n      times' = map fst ts'\n      obsEvents' = map snd ts'\n      timesWithinDelta = allWithinDeltaOfAbsoluteTimes delta times times'\n      observedEventsEqual = all (uncurry (withinDeltaOfObsEvent delta)) (zip obsEvents obsEvents')\n  in timesWithinDelta && observedEventsEqual\n\nwithinDeltaOfObsEvent :: Double -> ObservedEvent -> ObservedEvent -> Bool\nwithinDeltaOfObsEvent delta (ODisaster nl) (ODisaster nl') = withinDeltaOf delta nl nl'\nwithinDeltaOfObsEvent delta (OCatastrophe nl) (OCatastrophe nl') = withinDeltaOf delta nl nl'\nwithinDeltaOfObsEvent _ OBirth OBirth = True\nwithinDeltaOfObsEvent _ ObsUnscheduledSequenced ObsUnscheduledSequenced = True\nwithinDeltaOfObsEvent _ OOccurrence OOccurrence = True\nwithinDeltaOfObsEvent _ _ _ = False\n\nwithinDeltaOfObs :: Double -> Observation -> Observation -> Bool\nwithinDeltaOfObs delta (t,oe) (t',oe') = withinDeltaOfTimeDeltas delta t t' && withinDeltaOfObsEvent delta oe oe'\n\nallWithinDeltaOfObs :: Double -> [Observation] -> [Observation] -> Bool\nallWithinDeltaOfObs _ [] [] = True\nallWithinDeltaOfObs delta [y] [x] = withinDeltaOfObs delta y x\nallWithinDeltaOfObs delta (y:ys) (x:xs) = withinDeltaOfObs delta y x && allWithinDeltaOfObs delta ys xs\nallWithinDeltaOfObs _ _ _ = False\n\n\n\ntestAggregation :: SpecWith ()\ntestAggregation =\n  describe \"Testing Aggregation\" $ do\n    let smallDelta = 1e-4\n        tinyDelta = TimeDelta 1e-6\n        duration obs = AbsoluteTime $ sum [t | (TimeDelta t, _) <- obs]\n        multiplyAbsTime a (AbsoluteTime x) = AbsoluteTime (a * x)\n        propertyRemoveSeq obs =\n          let dur = duration obs\n              ats =\n                fromJust $\n                maybeAggregationTimes [timeAfterDelta dur tinyDelta] []\n              (AggregatedObservations _ obs') =\n                aggregateUnscheduledObservations ats obs\n           in not $ any isUnscheduledSequenced obs'\n        propertyRemoveUnseq obs =\n          let dur = duration obs\n              ats =\n                fromJust $\n                maybeAggregationTimes [] [timeAfterDelta dur tinyDelta]\n              (AggregatedObservations _ obs') =\n                aggregateUnscheduledObservations ats obs\n           in not $ any isOccurrence obs'\n        propertyRemoveUnsched1 obs =\n          let dur = duration obs\n              ats =\n                fromJust $\n                maybeAggregationTimes\n                  [timeAfterDelta dur tinyDelta]\n                  [ timeAfterDelta\n                      (timeAfterDelta dur tinyDelta)\n                      (TimeDelta 1.0)\n                  ]\n              (AggregatedObservations _ obs') =\n                aggregateUnscheduledObservations ats obs\n           in not (any isOccurrence obs') &&\n              not (any isUnscheduledSequenced obs')\n        propertyRemoveUnsched2 obs =\n          let dur = duration obs\n              ats =\n                fromJust $\n                maybeAggregationTimes\n                  [multiplyAbsTime 0.4 dur]\n                  [multiplyAbsTime 0.5 dur]\n              (AggregatedObservations _ obs') =\n                aggregateUnscheduledObservations ats obs\n           in not (any isOccurrence obs') &&\n              not (any isUnscheduledSequenced obs')\n        propertyBirthsRemain obs =\n          let dur = duration obs\n              numBs = length $ filter isBirth obs\n              ats =\n                fromJust $\n                maybeAggregationTimes\n                  [timeAfterDelta dur tinyDelta]\n                  [ timeAfterDelta\n                      (timeAfterDelta dur tinyDelta)\n                      (TimeDelta 1.0)\n                  ]\n              (AggregatedObservations _ obs') =\n                aggregateUnscheduledObservations ats obs\n              numBs' = length $ filter isBirth obs'\n           in numBs == numBs'\n        propertyLineagesConst os =\n          let dur = duration os\n              numSeq = sum $ map numSequenced os\n              numUnseq = sum $ map numUnsequenced os\n              ats =\n                fromJust $\n                maybeAggregationTimes\n                  [timeAfterDelta dur tinyDelta]\n                  [ timeAfterDelta\n                      (timeAfterDelta dur tinyDelta)\n                      (TimeDelta 1.0)\n                  ]\n              (AggregatedObservations _ os') =\n                aggregateUnscheduledObservations ats os\n              numSeq' = sum $ map numSequenced os'\n              numUnseq' = sum $ map numUnsequenced os'\n           in withinDeltaOf smallDelta numSeq numSeq' &&\n              withinDeltaOf smallDelta numUnseq numUnseq'\n    it \"sequenced aggregation removes all such unscheduled observations\" $\n      forAll qcRandomObservations propertyRemoveSeq\n    it \"unsequenced aggregation removes all such unscheduled observations\" $\n      forAll qcRandomObservations propertyRemoveUnseq\n    it \"aggregating both removes all relevent observations 1\" $\n      forAll qcRandomObservations propertyRemoveUnsched1\n    it \"aggregating both removes all relevent observations 2\" $\n      forAll qcRandomObservations propertyRemoveUnsched2\n    it \"aggregating leaves birth observations unchanged\" $\n      forAll qcRandomObservations propertyBirthsRemain\n    it \"aggregating leaves the number of observed lineages unchanged\" $\n      forAll qcRandomObservations propertyLineagesConst\n\n\n\n\ntestIntervalLlhd :: SpecWith ()\ntestIntervalLlhd =\n  describe \"Testing the intervalLlhd function\" $ do\n    let propertyNBNotNaN (params, delay, k, nb) =\n          let (_, nb') = fromRight' $ intervalLlhd params delay k nb\n              (m, _) = mAndVFromNb nb'\n           in not $ isNaN m\n        absTimeZero = AbsoluteTime 0\n        qcIntervalLlhdArgs ::\n             Gen (Parameters, TimeDelta, NumLineages, NegativeBinomial)\n        qcIntervalLlhdArgs = do\n          totalDuration <- qcRandomTimeDelta\n          params <- qcRandomParameters absTimeZero totalDuration\n          delay <- qcRandomSmallTimeDelta\n          k <- qcRandomNumLineages\n          nb <- qcRandomNegBinomSizeProb\n          return (params, delay, k, nb)\n        propertyPDEStatsNonNaN (params, delay, k, nb) =\n          let (_,logm,_) = logPdeStatistics params delay (PDESol nb k)\n          in not $ isNaN logm\n        propertyLogCNotNaN (params, delay, k, nb) =\n          let pdeSol = PDESol nb k\n              logmGF = logPdeGF params delay pdeSol\n              logC = logmGF 1\n          in not $ isNaN logC\n        propertyLogmTermNotNaN (params, delay, k, nb) =\n          let pdeSol = PDESol nb k\n              logmGF' = logPdeGF' params delay pdeSol\n              logmTerm = logmGF' 1\n          in not $ isNaN logmTerm\n        propertyOdeHelperNotNaN (params, delay, _, _) =\n          let (x1,x2,disc,expFact) = odeHelpers params delay\n              notNaN = not . isNaN\n          in notNaN x1 && notNaN x2 && 0 < disc && 1 > expFact && x2 > x1\n    it \"resulting odeHelpers are not NaN\" $ forAll qcIntervalLlhdArgs propertyOdeHelperNotNaN\n    it \"resulting logmTerm from logPdeGF' is not NAN\" $ forAll qcIntervalLlhdArgs propertyLogmTermNotNaN\n    it \"resulting logC from logPdeGF is not NAN\" $ forAll qcIntervalLlhdArgs propertyLogCNotNaN\n    it \"resulting log(mean) from logPdeStatistics is not NAN\" $ forAll qcIntervalLlhdArgs propertyPDEStatsNonNaN\n    it \"resulting NB is not NAN\" $ forAll qcIntervalLlhdArgs propertyNBNotNaN\n\ntestLogP0Dash :: SpecWith ()\ntestLogP0Dash = do\n  describe \"Testing the logP0' function\" $ do\n    let absTimeZero = AbsoluteTime 0\n        qcP0Args :: Gen (Parameters, TimeDelta, Probability)\n        qcP0Args = do\n          totalDuration <- qcRandomTimeDelta\n          params_ <- qcRandomParameters absTimeZero totalDuration\n          delay_ <- qcRandomSmallTimeDelta\n          z_ <- qcRandomProbability\n          return (params_, delay_, z_)\n        propertyLogValNotNaN (params_, delay_, z_) =\n          let logValue = logP0' params_ delay_ z_\n          in not $ isNaN logValue\n        propertyApproximateEquality (params, delay, z) =\n          let linearValue = p0' params delay z\n              logValue = logP0' params delay z\n          in withinDeltaOf 1e-10 (exp logValue) linearValue -- fails for smaller delta :)\n    it \"log version is not nan\" $ forAll qcP0Args propertyLogValNotNaN\n    it \"approximate equality to p0'\" $ forAll qcP0Args propertyApproximateEquality\n  describe \"Testing the logP0'' function\" $ do\n    let absTimeZero = AbsoluteTime 0\n        qcP0Args :: Gen (Parameters, TimeDelta, Probability)\n        qcP0Args = do\n          totalDuration <- qcRandomTimeDelta\n          params_ <- qcRandomParameters absTimeZero totalDuration\n          delay_ <- qcRandomSmallTimeDelta\n          z_ <- qcRandomProbability\n          return (params_, delay_, z_)\n        propertyLogValNotNaN (params_, delay_, z_) =\n          let logValue = logP0'' params_ delay_ z_\n          in not $ isNaN logValue\n        propertyApproximateEquality (params, delay, z) =\n          let linearValue = p0'' params delay z\n              logValue = logP0'' params delay z\n          in withinDeltaOf 1e-10 (exp logValue) linearValue -- fails for smaller delta :)\n    it \"log version is not nan\" $ forAll qcP0Args propertyLogValNotNaN\n    it \"approximate equality to p0''\" $ forAll qcP0Args propertyApproximateEquality\n\n-- | Two of the tests have been commented out because they are broken by changes\n-- to the LLHD interface rather than the underlying code that does the\n-- computation.\nmain :: IO ()\nmain = hspec $ do\n  -- ** slow tests **\n  testNbPGF\n  -- ** fast tests **\n  testTestingHelpers\n  testPdeStatistics\n  testp0\n  testRr\n  testPdeGF\n  -- testLlhd -- broken because we guard against R0 < 1 in current version.\n  testConversion\n  -- testImpossibleParameters -- broken because we use either monad instead of infinite values now.\n  -- testInhomBDSLlhd -- not relevant to the first manuscript.\n  testParameterUpdate\n  testMWCSeeding\n  testLogPdeGF1\n  testLogPdeGF2\n  testLogPdeGFDash1\n  testLogPdeGFDash2\n  testLogPdeGFDashDash1\n  testLogPdeGFDashDash2\n  testLogSumExp\n  testLogPdeStatistics\n  testAggregation\n  testIntervalLlhd\n  testLogP0Dash\n\n", "meta": {"hexsha": "05b2f0787519aac97ba770b5e09a87e1af6b34c4", "size": 53788, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Spec.hs", "max_stars_repo_name": "aezarebski/timtam", "max_stars_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-21T01:07:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T01:07:59.000Z", "max_issues_repo_path": "test/Spec.hs", "max_issues_repo_name": "aezarebski/timtam", "max_issues_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-21T01:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T01:19:37.000Z", "max_forks_repo_path": "test/Spec.hs", "max_forks_repo_name": "aezarebski/timtam", "max_forks_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.5661157025, "max_line_length": 365, "alphanum_fraction": 0.6186881832, "num_tokens": 19015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4285935144491531}}
{"text": "{-# LANGUAGE BangPatterns         #-}\n{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE MagicHash            #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE UnboxedTuples        #-}\n\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\n-- |\n-- Module      :  Internal.Vector\n-- Copyright   :  (c) Alberto Ruiz 2007-15\n-- License     :  BSD3\n-- Maintainer  :  Alberto Ruiz\n-- Stability   :  provisional\n--\n\nmodule Internal.Vector(\n    I,Z,R,C,\n    fi,ti,\n    Vector, fromList, unsafeToForeignPtr, unsafeFromForeignPtr, unsafeWith,\n    createVector, avec, inlinePerformIO,\n    toList, dim, (@>), at', (|>),\n    vjoin, subVector, takesV, idxs,\n    buildVector,\n    asReal, asComplex,\n    toByteString,fromByteString,\n    zipVector, unzipVector, zipVectorWith, unzipVectorWith,\n    foldVector, foldVectorG, foldVectorWithIndex, foldLoop,\n    mapVector, mapVectorM, mapVectorM_,\n    mapVectorWithIndex, mapVectorWithIndexM, mapVectorWithIndexM_\n) where\n\nimport           Data.Complex\nimport           Data.Int                      (Int64)\nimport           Data.Vector.Storable          (Vector, fromList, unsafeFromForeignPtr,\n                                                unsafeToForeignPtr, unsafeWith)\nimport qualified Data.Vector.Storable          as Vector\nimport           Foreign.C.Types               (CInt)\nimport           Foreign.ForeignPtr\nimport           Foreign.Marshal.Array\nimport           Foreign.Ptr\nimport           Foreign.Storable\nimport           GHC.Base                      (IO (IO), realWorld#, when)\nimport           GHC.ForeignPtr                (mallocPlainForeignPtrBytes)\nimport           System.IO.Unsafe              (unsafePerformIO)\n\nimport           Control.Monad                 (replicateM)\nimport           Data.Binary\nimport           Data.Binary.Put\nimport qualified Data.ByteString.Internal      as BS\nimport           Data.Vector.Storable.Internal (updPtr)\n\ntype I = CInt\ntype Z = Int64\ntype R = Float\ntype C = Complex Float\n\n\n-- | specialized fromIntegral\nfi :: Int -> CInt\nfi = fromIntegral\n\n-- | specialized fromIntegral\nti :: CInt -> Int\nti = fromIntegral\n\n\n-- | Number of elements\ndim :: (Storable t) => Vector t -> Int\ndim = Vector.length\n{-# INLINE dim #-}\n\n\n-- C-Haskell vector adapter\n{-# INLINE avec #-}\navec :: Storable a => Vector a -> (f -> IO r) -> ((CInt -> Ptr a -> f) -> IO r)\navec v f g = unsafeWith v $ \\ptr -> f (g (fromIntegral (Vector.length v)) ptr)\n\n-- allocates memory for a new vector\ncreateVector :: Storable a => Int -> IO (Vector a)\ncreateVector n = do\n    when (n < 0) $ error (\"trying to createVector of negative dim: \"++show n)\n    fp <- doMalloc undefined\n    return $ unsafeFromForeignPtr fp 0 n\n  where\n    --\n    -- Use the much cheaper Haskell heap allocated storage\n    -- for foreign pointer space we control\n    --\n    doMalloc :: Storable b => b -> IO (ForeignPtr b)\n    doMalloc dummy = do\n        mallocPlainForeignPtrBytes (n * sizeOf dummy)\n\n{- | creates a Vector from a list:\n\n@> fromList [2,3,5,7]\n4 |> [2.0,3.0,5.0,7.0]@\n\n-}\n\nsafeRead :: Storable a => Vector a -> (Ptr a -> IO c) -> c\nsafeRead v = inlinePerformIO . unsafeWith v\n{-# INLINE safeRead #-}\n\ninlinePerformIO :: IO a -> a\ninlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r\n{-# INLINE inlinePerformIO #-}\n\n{- extracts the Vector elements to a list\n\n>>> toList (linspace 5 (1,10))\n[1.0,3.25,5.5,7.75,10.0]\n\n-}\ntoList :: Storable a => Vector a -> [a]\ntoList v = safeRead v $ peekArray (dim v)\n\n{- | Create a vector from a list of elements and explicit dimension. The input\n     list is truncated if it is too long, so it may safely\n     be used, for instance, with infinite lists.\n\n>>> 5 |> [1..]\n[1.0,2.0,3.0,4.0,5.0]\nit :: (Enum a, Num a, Foreign.Storable.Storable a) => Vector a\n\n-}\n(|>) :: (Storable a) => Int -> [a] -> Vector a\ninfixl 9 |>\nn |> l\n    | length l' == n = fromList l'\n    | otherwise      = error \"list too short for |>\"\n  where\n    l' = take n l\n\n\n-- | Create a vector of indexes, useful for matrix extraction using '(??)'\nidxs :: [Int] -> Vector I\nidxs js = fromList (map fromIntegral js) :: Vector I\n\n{- | takes a number of consecutive elements from a Vector\n\n>>> subVector 2 3 (fromList [1..10])\n[3.0,4.0,5.0]\nit :: (Enum t, Num t, Foreign.Storable.Storable t) => Vector t\n\n-}\nsubVector :: Storable t => Int       -- ^ index of the starting element\n                        -> Int       -- ^ number of elements to extract\n                        -> Vector t  -- ^ source\n                        -> Vector t  -- ^ result\nsubVector = Vector.slice\n{-# INLINE subVector #-}\n\n\n{- | Reads a vector position:\n\n>>> fromList [0..9] @> 7\n7.0\n\n-}\n(@>) :: Storable t => Vector t -> Int -> t\ninfixl 9 @>\nv @> n\n    | n >= 0 && n < dim v = at' v n\n    | otherwise = error \"vector index out of range\"\n{-# INLINE (@>) #-}\n\n-- | access to Vector elements without range checking\nat' :: Storable a => Vector a -> Int -> a\nat' v n = safeRead v $ flip peekElemOff n\n{-# INLINE at' #-}\n\n{- | concatenate a list of vectors\n\n>>> vjoin [fromList [1..5::Float], konst 1 3]\n[1.0,2.0,3.0,4.0,5.0,1.0,1.0,1.0]\nit :: Vector Float\n\n-}\nvjoin :: Storable t => [Vector t] -> Vector t\nvjoin [] = fromList []\nvjoin [v] = v\nvjoin as = unsafePerformIO $ do\n    let tot = sum (map dim as)\n    r <- createVector tot\n    unsafeWith r $ \\ptr ->\n        joiner as tot ptr\n    return r\n  where joiner [] _ _ = return ()\n        joiner (v:cs) _ p = do\n            let n = dim v\n            unsafeWith v $ \\pb -> copyArray p pb n\n            joiner cs 0 (advancePtr p n)\n\n\n{- | Extract consecutive subvectors of the given sizes.\n\n>>> takesV [3,4] (linspace 10 (1,10::Float))\n[[1.0,2.0,3.0],[4.0,5.0,6.0,7.0]]\nit :: [Vector Float]\n\n-}\ntakesV :: Storable t => [Int] -> Vector t -> [Vector t]\ntakesV ms w | sum ms > dim w = error $ \"takesV \" ++ show ms ++ \" on dim = \" ++ (show $ dim w)\n            | otherwise = go ms w\n    where go [] _ = []\n          go (n:ns) v = subVector 0 n v\n                      : go ns (subVector n (dim v - n) v)\n\n---------------------------------------------------------------\n\n-- | transforms a complex vector into a real vector with alternating real and imaginary parts\nasReal :: (RealFloat a, Storable a) => Vector (Complex a) -> Vector a\nasReal v = unsafeFromForeignPtr (castForeignPtr fp) (2*i) (2*n)\n    where (fp,i,n) = unsafeToForeignPtr v\n\n-- | transforms a real vector into a complex vector with alternating real and imaginary parts\nasComplex :: (RealFloat a, Storable a) => Vector a -> Vector (Complex a)\nasComplex v = unsafeFromForeignPtr (castForeignPtr fp) (i `div` 2) (n `div` 2)\n    where (fp,i,n) = unsafeToForeignPtr v\n\n--------------------------------------------------------------------------------\n\n\n-- | map on Vectors\nmapVector :: (Storable a, Storable b) => (a-> b) -> Vector a -> Vector b\nmapVector f v = unsafePerformIO $ do\n    w <- createVector (dim v)\n    unsafeWith v $ \\p ->\n        unsafeWith w $ \\q -> do\n            let go (-1) = return ()\n                go !k = do x <- peekElemOff p k\n                           pokeElemOff      q k (f x)\n                           go (k-1)\n            go (dim v -1)\n    return w\n{-# INLINE mapVector #-}\n\n-- | zipWith for Vectors\nzipVectorWith :: (Storable a, Storable b, Storable c) => (a-> b -> c) -> Vector a -> Vector b -> Vector c\nzipVectorWith f u v = unsafePerformIO $ do\n    let n = min (dim u) (dim v)\n    w <- createVector n\n    unsafeWith u $ \\pu ->\n        unsafeWith v $ \\pv ->\n            unsafeWith w $ \\pw -> do\n                let go (-1) = return ()\n                    go !k = do x <- peekElemOff pu k\n                               y <- peekElemOff pv k\n                               pokeElemOff      pw k (f x y)\n                               go (k-1)\n                go (n -1)\n    return w\n{-# INLINE zipVectorWith #-}\n\n-- | unzipWith for Vectors\nunzipVectorWith :: (Storable (a,b), Storable c, Storable d)\n                   => ((a,b) -> (c,d)) -> Vector (a,b) -> (Vector c,Vector d)\nunzipVectorWith f u = unsafePerformIO $ do\n      let n = dim u\n      v <- createVector n\n      w <- createVector n\n      unsafeWith u $ \\pu ->\n          unsafeWith v $ \\pv ->\n              unsafeWith w $ \\pw -> do\n                  let go (-1) = return ()\n                      go !k   = do z <- peekElemOff pu k\n                                   let (x,y) = f z\n                                   pokeElemOff      pv k x\n                                   pokeElemOff      pw k y\n                                   go (k-1)\n                  go (n-1)\n      return (v,w)\n{-# INLINE unzipVectorWith #-}\n\nfoldVector :: Storable a => (a -> b -> b) -> b -> Vector a -> b\nfoldVector f x v = unsafePerformIO $\n    unsafeWith v $ \\p -> do\n        let go (-1) s = return s\n            go !k !s = do y <- peekElemOff p k\n                          go (k-1::Int) (f y s)\n        go (dim v -1) x\n{-# INLINE foldVector #-}\n\n-- the zero-indexed index is passed to the folding function\nfoldVectorWithIndex :: Storable a => (Int -> a -> b -> b) -> b -> Vector a -> b\nfoldVectorWithIndex f x v = unsafePerformIO $\n    unsafeWith v $ \\p -> do\n        let go (-1) s = return s\n            go !k !s = do y <- peekElemOff p k\n                          go (k-1::Int) (f k y s)\n        go (dim v -1) x\n{-# INLINE foldVectorWithIndex #-}\n\nfoldLoop :: (Int -> t -> t) -> t -> Int -> t\nfoldLoop f s0 d = go (d - 1) s0\n     where\n       go 0 s   = f (0::Int) s\n       go !j !s = go (j - 1) (f j s)\n\nfoldVectorG :: Storable t1 => (Int -> (Int -> t1) -> t -> t) -> t -> Vector t1 -> t\nfoldVectorG f s0 v = foldLoop g s0 (dim v)\n    where g !k !s = f k (safeRead v . flip peekElemOff) s\n          {-# INLINE g #-} -- Thanks to Ryan Ingram (http://permalink.gmane.org/gmane.comp.lang.haskell.cafe/46479)\n{-# INLINE foldVectorG #-}\n\n-------------------------------------------------------------------\n\n-- | monadic map over Vectors\n--    the monad @m@ must be strict\nmapVectorM :: (Storable a, Storable b, Monad m) => (a -> m b) -> Vector a -> m (Vector b)\nmapVectorM f v = do\n    w <- return $! unsafePerformIO $! createVector (dim v)\n    mapVectorM' w 0 (dim v -1)\n    return w\n    where mapVectorM' w' !k !t\n              | k == t               = do\n                                       x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                       y <- f x\n                                       return $! inlinePerformIO $! unsafeWith w' $! \\q -> pokeElemOff q k y\n              | otherwise            = do\n                                       x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                       y <- f x\n                                       _ <- return $! inlinePerformIO $! unsafeWith w' $! \\q -> pokeElemOff q k y\n                                       mapVectorM' w' (k+1) t\n{-# INLINE mapVectorM #-}\n\n-- | monadic map over Vectors\nmapVectorM_ :: (Storable a, Monad m) => (a -> m ()) -> Vector a -> m ()\nmapVectorM_ f v = do\n    mapVectorM' 0 (dim v -1)\n    where mapVectorM' !k !t\n              | k == t            = do\n                                    x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                    f x\n              | otherwise         = do\n                                    x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                    _ <- f x\n                                    mapVectorM' (k+1) t\n{-# INLINE mapVectorM_ #-}\n\n-- | monadic map over Vectors with the zero-indexed index passed to the mapping function\n--    the monad @m@ must be strict\nmapVectorWithIndexM :: (Storable a, Storable b, Monad m) => (Int -> a -> m b) -> Vector a -> m (Vector b)\nmapVectorWithIndexM f v = do\n    w <- return $! unsafePerformIO $! createVector (dim v)\n    mapVectorM' w 0 (dim v -1)\n    return w\n    where mapVectorM' w' !k !t\n              | k == t               = do\n                                       x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                       y <- f k x\n                                       return $! inlinePerformIO $! unsafeWith w' $! \\q -> pokeElemOff q k y\n              | otherwise            = do\n                                       x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                       y <- f k x\n                                       _ <- return $! inlinePerformIO $! unsafeWith w' $! \\q -> pokeElemOff q k y\n                                       mapVectorM' w' (k+1) t\n{-# INLINE mapVectorWithIndexM #-}\n\n-- | monadic map over Vectors with the zero-indexed index passed to the mapping function\nmapVectorWithIndexM_ :: (Storable a, Monad m) => (Int -> a -> m ()) -> Vector a -> m ()\nmapVectorWithIndexM_ f v = do\n    mapVectorM' 0 (dim v -1)\n    where mapVectorM' !k !t\n              | k == t            = do\n                                    x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                    f k x\n              | otherwise         = do\n                                    x <- return $! inlinePerformIO $! unsafeWith v $! \\p -> peekElemOff p k\n                                    _ <- f k x\n                                    mapVectorM' (k+1) t\n{-# INLINE mapVectorWithIndexM_ #-}\n\n\nmapVectorWithIndex :: (Storable a, Storable b) => (Int -> a -> b) -> Vector a -> Vector b\n--mapVectorWithIndex g = head . mapVectorWithIndexM (\\a b -> [g a b])\nmapVectorWithIndex f v = unsafePerformIO $ do\n    w <- createVector (dim v)\n    unsafeWith v $ \\p ->\n        unsafeWith w $ \\q -> do\n            let go (-1) = return ()\n                go !k = do x <- peekElemOff p k\n                           pokeElemOff      q k (f k x)\n                           go (k-1)\n            go (dim v -1)\n    return w\n{-# INLINE mapVectorWithIndex #-}\n\n--------------------------------------------------------------------------------\n\n\n-- a 64K cache, with a Float taking 13 bytes in Bytestring,\n-- implies a chunk size of 5041\nchunk :: Int\nchunk = 5000\n\nchunks :: Int -> [Int]\nchunks d = let c = d `div` chunk\n               m = d `mod` chunk\n           in if m /= 0 then reverse (m:(replicate c chunk)) else (replicate c chunk)\n\nputVector :: (Storable t, Binary t) => Vector t -> Data.Binary.Put.PutM ()\nputVector v = mapM_ put $! toList v\n\ngetVector :: (Storable a, Binary a) => Int -> Get (Vector a)\ngetVector d = do\n              xs <- replicateM d get\n              return $! fromList xs\n\n--------------------------------------------------------------------------------\n\ntoByteString :: Storable t => Vector t -> BS.ByteString\ntoByteString v = BS.PS (castForeignPtr fp) (sz*o) (sz * dim v)\n  where\n    (fp,o,_n) = unsafeToForeignPtr v\n    sz = sizeOf (v@>0)\n\n\nfromByteString :: Storable t => BS.ByteString -> Vector t\nfromByteString (BS.PS fp o n) = r\n  where\n    r = unsafeFromForeignPtr (castForeignPtr (updPtr (`plusPtr` o) fp)) 0 n'\n    n' = n `div` sz\n    sz = sizeOf (r@>0)\n\n--------------------------------------------------------------------------------\n\ninstance (Binary a, Storable a) => Binary (Vector a) where\n\n    put v = do\n            let d = dim v\n            put d\n            mapM_ putVector $! takesV (chunks d) v\n\n    -- put = put . v2bs\n\n    get = do\n          d <- get\n          vs <- mapM getVector $ chunks d\n          return $! vjoin vs\n\n    -- get = fmap bs2v get\n\n\n-------------------------------------------------------------------\n\n{- | creates a Vector of the specified length using the supplied function to\n     to map the index to the value at that index.\n\n@> buildVector 4 fromIntegral\n4 |> [0.0,1.0,2.0,3.0]@\n\n-}\nbuildVector :: Storable a => Int -> (Int -> a) -> Vector a\nbuildVector len f =\n    fromList $ map f [0 .. (len - 1)]\n\n\n-- | zip for Vectors\nzipVector :: (Storable a, Storable b, Storable (a,b)) => Vector a -> Vector b -> Vector (a,b)\nzipVector = zipVectorWith (,)\n\n-- | unzip for Vectors\nunzipVector :: (Storable a, Storable b, Storable (a,b)) => Vector (a,b) -> (Vector a,Vector b)\nunzipVector = unzipVectorWith id\n\n-------------------------------------------------------------------\n", "meta": {"hexsha": "700839fa20d12b346319ffe9b9652249e2fbe892", "size": 16163, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Internal/Vector.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Internal/Vector.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Internal/Vector.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 34.4626865672, "max_line_length": 115, "alphanum_fraction": 0.5109200025, "num_tokens": 4420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.4285932891628051}}
{"text": "--\n-- ConvLayer : convolution layer\n--\n\nmodule CNN.ConvLayer (\n  initFilterC\n, convolve\n, deconvolve\n, reverseConvFilter\n, updateConvFilter\n) where\n\nimport Control.Monad hiding (msum)\nimport Data.List hiding (transpose)\nimport Data.Maybe\nimport Debug.Trace\nimport Numeric.LinearAlgebra\nimport System.Random.Mersenne as MT\n\nimport CNN.Algebra\nimport CNN.Image\nimport CNN.LayerType\n\n{- |\ninitFilterC\n\n  IN : #kernel\n       #channel\n       input size (x * y)\n       kernel size (n * n)\n       pool size (m * m)\n\n  OUT: filter of convolution layer\n\n-}\n\ninitFilterC :: Int -> Int -> Int -> Int -> Int -> Int -> IO [FilterC]\ninitFilterC k c x y n m = do\n  f <- forM [1..k] $ \\i -> do\n    w <- initKernel c n\n    return (w, 0.0)\n  return f\n  where\n    ri = fromIntegral (n * n * c)   -- resolution (input)\n    ro = fromIntegral (n * n * k) / (fromIntegral (m * m))\n    a = sqrt (6.0 / (ri + ro))\n    initKernel :: Int -> Int -> IO Kernel\n    initKernel c n = do\n      let\n        sz = n * n\n      w <- forM [1..c] $ \\i -> do\n        w' <- forM [1..sz] $ \\j -> do\n          r <- MT.randomIO :: IO Double\n          return ((r * 2.0 - 1.0) * a)\n        return w'\n      return $ fromLists w\n\n--\n\n{- |\nconvolve\n\n  IN: kernel size\n      filter\n      image\n\ntest: filter k=3, c=2, s=2\n>>> let filter = [(fromLists [[1.0,2.0,3.0,4.0],[5.0,6.0,7.0,8.0]],0.25),(fromLists [[3.0,4.0,5.0,6.0],[7.0,8.0,1.0,2.0]],0.5),(fromLists [[5.0,6.0,7.0,8.0],[1.0,2.0,3.0,4.0]],0.75)] :: [FilterC]\n>>> let img1 = [fromLists [[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]], fromLists [[4.0,5.0,6.0],[7.0,8.0,9.0],[1.0,2.0,3.0]]] :: Image\n>>> let img2 = [fromLists [[1.0,2.0,3.0,4.0],[4.0,5.0,6.0,7.0],[7.0,8.0,9.0,10.0],[10.0,11.0,12.0,13.0]],fromLists [[4.0,5.0,6.0,7.0],[7.0,8.0,9.0,10.0],[1.0,2.0,3.0,4.0],[4.0,5.0,6.0,7.0]]] :: Image\n>>> convolve 2 filter img1\n[(2><2)\n [ 200.25, 236.25\n , 173.25, 209.25 ],(2><2)\n [ 152.5, 188.5\n , 233.5, 269.5 ],(2><2)\n [ 152.75, 188.75\n , 197.75, 233.75 ]]\n>>> convolve 2 filter img2\n[(3><3)\n [ 200.25, 236.25, 272.25\n , 173.25, 209.25, 245.25\n , 182.25, 218.25, 254.25 ],(3><3)\n [ 152.5, 188.5, 224.5\n , 233.5, 269.5, 305.5\n , 206.5, 242.5, 278.5 ],(3><3)\n [ 152.75, 188.75, 224.75\n , 197.75, 233.75, 269.75\n , 278.75, 314.75, 350.75 ]]\n\n-}\n\n--\n-- USE corr2 ??\n--\n\nconvolve :: Int -> [FilterC] -> Image -> Image\nconvolve s fs im = map (convolveImage x iss) fs\n  where\n    pl = head im\n    x  = cols pl - (s - 1)\n    y  = rows pl - (s - 1)\n    ps = [(i, j) | i <- [0..(x-1)], j <- [0..(y-1)]]\n    iss = map subImage im\n    subImage :: Plain -> Matrix R\n    subImage i = fromColumns $ map (\\p -> flatten $ subMatrix p (s, s) i) ps\n\nconvolveImage :: Int -> [Matrix R] -> FilterC -> Plain\nconvolveImage x iss (k, b) = reshape x $ cmap (+ b) $ vsum vs\n  where\n    vs = zipWith (<#) (toRows k) iss\n\n-- back prop\n\ndeconvolve :: Int -> [FilterC] -> Image -> Delta -> (Delta, Maybe Layer)\ndeconvolve s fs im d = (delta, Just (ConvLayer s dw))\n  where\n    delta = convolve s fs $ addBorder s d\n    sim = slideImage s im\n    dw = map (hadamard sim) d\n\n{- |\naddBorder\n\n  IN : kernel size\n       delta (Image)\n  OUT: delta (Image)\n\n>>> let s = [fromLists [[1.0, 2.0],[3.0,4.0]], fromLists [[5.0,6.0],[7.0,8.0]]]\n>>> addBorder 2 s\n[(4><4)\n [ 0.0, 0.0, 0.0, 0.0\n , 0.0, 1.0, 2.0, 0.0\n , 0.0, 3.0, 4.0, 0.0\n , 0.0, 0.0, 0.0, 0.0 ],(4><4)\n [ 0.0, 0.0, 0.0, 0.0\n , 0.0, 5.0, 6.0, 0.0\n , 0.0, 7.0, 8.0, 0.0\n , 0.0, 0.0, 0.0, 0.0 ]]\n\n-}\n\naddBorder :: Int -> Delta -> Delta\naddBorder s d = map ab d\n  where\n    s' = s - 1\n    ab :: Plain -> Plain\n    ab p = yb ||| ((xb === (p === xb)) ||| yb)\n      where\n        x = cols p\n        y = rows p\n        xb = (s'><x) $ repeat 0.0\n        yb = ((y + 2 * s')><s') $ repeat 0.0\n\n{- |\nslideImage\n\n>>> let p = [fromLists [[1.0,2.0,3.0,4.0],[5.0,6.0,7.0,8.0],[9.0,10.0,11.0,12.0],[13.0,14.0,15.0,16.0]]] :: Image\n>>> slideImage 2 p\n[[(3><3)\n [ 1.0,  2.0,  3.0\n , 5.0,  6.0,  7.0\n , 9.0, 10.0, 11.0 ],(3><3)\n [  2.0,  3.0,  4.0\n ,  6.0,  7.0,  8.0\n , 10.0, 11.0, 12.0 ],(3><3)\n [  5.0,  6.0,  7.0\n ,  9.0, 10.0, 11.0\n , 13.0, 14.0, 15.0 ],(3><3)\n [  6.0,  7.0,  8.0\n , 10.0, 11.0, 12.0\n , 14.0, 15.0, 16.0 ]]]\n\n-}\n\nslideImage :: Int -> Image -> [[Plain]]\nslideImage s im = map (slidePlain s) im\n\n{- |\nslidePlain\n\n>>> let p = fromLists [[1.0,2.0,3.0,4.0],[5.0,6.0,7.0,8.0],[9.0,10.0,11.0,12.0],[13.0,14.0,15.0,16.0]] :: Plain\n>>> slidePlain 2 p\n[(3><3)\n [ 1.0,  2.0,  3.0\n , 5.0,  6.0,  7.0\n , 9.0, 10.0, 11.0 ],(3><3)\n [  2.0,  3.0,  4.0\n ,  6.0,  7.0,  8.0\n , 10.0, 11.0, 12.0 ],(3><3)\n [  5.0,  6.0,  7.0\n ,  9.0, 10.0, 11.0\n , 13.0, 14.0, 15.0 ],(3><3)\n [  6.0,  7.0,  8.0\n , 10.0, 11.0, 12.0\n , 14.0, 15.0, 16.0 ]]\n\n>>> slidePlain 3 p\n[(2><2)\n [ 1.0, 2.0\n , 5.0, 6.0 ],(2><2)\n [ 2.0, 3.0\n , 6.0, 7.0 ],(2><2)\n [ 3.0, 4.0\n , 7.0, 8.0 ],(2><2)\n [ 5.0,  6.0\n , 9.0, 10.0 ],(2><2)\n [  6.0,  7.0\n , 10.0, 11.0 ],(2><2)\n [  7.0,  8.0\n , 11.0, 12.0 ],(2><2)\n [  9.0, 10.0\n , 13.0, 14.0 ],(2><2)\n [ 10.0, 11.0\n , 14.0, 15.0 ],(2><2)\n [ 11.0, 12.0\n , 15.0, 16.0 ]]\n\n-}\n\nslidePlain :: Int -> Plain -> [Plain]\nslidePlain s m \n  | s < 1     = []\n  | s == 1    = [m]\n  | otherwise = map (\\p -> subMatrix p (x, y) m) ps\n  where\n    x = cols m - (s - 1)\n    y = rows m - (s - 1)\n    ps = [(i, j) | i <- [0..s-1], j <- [0..s-1]]\n\n{- |\nhadamard\n\n  IN : slided images\n       delta\n  OUT: (Kernel, Bias)\n\n>>> let p = [fromLists [[1.0,2.0,3.0,4.0],[5.0,6.0,7.0,8.0],[9.0,10.0,11.0,12.0],[13.0,14.0,15.0,16.0]], fromLists [[16.0,15.0,14.0,13.0],[12.0,11.0,10.0,9.0],[8.0,7.0,6.0,5.0],[4.0,3.0,2.0,1.0]]] :: Image\n>>> let ds = fromLists [[0.1,0.2,0.3],[0.4,0.5,0.6],[0.7,0.8,0.9]]\n>>> hadamard (slideImage 2 p) ds\n((2><4)\n [ 34.800000000000004, 39.3, 52.800000000000004, 57.3\n ,               41.7, 37.2, 23.700000000000006, 19.2 ],4.5)\n\n-}\n\nhadamard :: [[Plain]] -> Plain -> FilterC\nhadamard sim ds = (w, b)\n  where\n    b = sumElements ds\n    d' = flatten ds\n    w = fromLists $ map (map ((<.>) d' . flatten)) sim\n\n{- |\nreverseConvFilter\n\n  IN : kernel size\n       original filter\n  OUT: reversed filter\n\n>>> let fs = [(fromLists [[0.1,0.2,0.3,0.4],[0.5,0.6,0.7,0.8]],1.0),(fromLists [[0.1,0.3,0.5,0.7],[0.2,0.4,0.6,0.8]],2.0),(fromLists [[0.1,0.2,0.5,0.6],[0.3,0.4,0.7,0.8]],3.0)] :: [FilterC]\n>>> let ConvLayer s fs' = reverseConvFilter 2 fs\n>>> s\n2\n>>> fs'\n[((3><4)\n [ 0.4, 0.3, 0.2, 0.1\n , 0.7, 0.5, 0.3, 0.1\n , 0.6, 0.5, 0.2, 0.1 ],0.0),((3><4)\n [ 0.8, 0.7, 0.6, 0.5\n , 0.8, 0.6, 0.4, 0.2\n , 0.8, 0.7, 0.4, 0.3 ],0.0)]\n\n-}\n\nreverseConvFilter :: Int -> [FilterC] -> Layer\nreverseConvFilter s fs = ConvLayer s (zip rv (repeat 0.0))\n  where\n    (k, _) = unzip fs\n    k'     = map (toLists . fliprl) k\n    --r      = transpose $ map (map reverse) k'\n    r      = transpose k'\n    rv     = map fromLists r\n\n-- update\n\nupdateConvFilter :: Int -> [FilterC] -> Double -> [Maybe Layer] -> Layer\nupdateConvFilter s fs lr dl\n  | dl' == [] = ConvLayer s fs\n  | otherwise = ConvLayer s $ zip ks' (toList bs')\n  where\n    dl' = catMaybes dl\n    sc = lr / fromIntegral (length dl')\n    (ks , bs ) = unzip fs\n    (kss, bss) = unzip $ map unzip $ strip dl'\n    dbs = vsum $ map fromList bss\n    dks = map (mscale sc . msum) $ transpose kss\n    bs' = (fromList bs) - (vscale sc dbs)\n    ks' = zipWith (-) ks dks\n\nstrip :: [Layer] -> [[FilterC]]\nstrip [] = []\nstrip (ConvLayer s fs:ds) = fs:strip ds\nstrip (_:ds) = strip ds  -- if not ConvLayer\n\n", "meta": {"hexsha": "4fd6318c5d9e0f421f9c61db787d365300a70e55", "size": 7341, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CNN/ConvLayer.hs", "max_stars_repo_name": "eijian/deeplearning", "max_stars_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-30T01:28:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T18:58:17.000Z", "max_issues_repo_path": "CNN/ConvLayer.hs", "max_issues_repo_name": "eijian/deeplearning", "max_issues_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CNN/ConvLayer.hs", "max_forks_repo_name": "eijian/deeplearning", "max_forks_repo_head_hexsha": "ef7ab2ef7664bdad240f11becb2f5efe7b9d2b29", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9901960784, "max_line_length": 205, "alphanum_fraction": 0.5052445171, "num_tokens": 3667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4283255521310855}}
{"text": "-- | Data structure of compiler. https://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/\n\nmodule LispVal\n       ( LispVal(..)\n       , Env\n       , unwordsList\n       ) where\n\nimport           Data.Complex\nimport           Data.IORef\nimport           Data.Ratio                 (denominator, numerator)\nimport           ErrorCheckingAndExceptions\nimport           System.IO                  (Handle)\n\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             | PrimitiveFunc ([LispVal] -> ThrowsError LispVal)\n             | Func { params :: [String], vararg :: Maybe String, body :: [LispVal], closure :: Env}\n             | IOFunc ([LispVal] -> IOThrowsError LispVal)\n             | Port Handle\n\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 ++ \")\"\nshowVal (PrimitiveFunc _) = \"<primitive>\"\nshowVal (Func {params = args, vararg = varargs, body = body, closure = env}) =\n  \"(lambda (\" ++ unwords (map show args) ++\n  (case varargs of\n     Nothing -> \"\"\n     Just arg -> \" . \" ++ arg) ++ \") ...)\"\nshowVal (Port _) = \"<IO port>\"\nshowVal (IOFunc _) = \"<IO primitive>\"\n\n\nunwordsList :: [LispVal] -> String\nunwordsList = unwords . map showVal\n\ninstance Show LispVal where\n  show = showVal\n\ntype Env = IORef [(String, IORef LispVal)]\n", "meta": {"hexsha": "28cf0cfea52bed650bbfc317049a99b645c0d274", "size": 1978, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "WriteYourselfAScheme/sec9-creating-IO-primitives/code/src/LispVal.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/sec9-creating-IO-primitives/code/src/LispVal.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/sec9-creating-IO-primitives/code/src/LispVal.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": 33.5254237288, "max_line_length": 100, "alphanum_fraction": 0.5652173913, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.42829598811766906}}
{"text": "{-# LANGUAGE ScopedTypeVariables, TypeFamilies, TupleSections, FlexibleContexts #-}\n\nmodule Fuml.Unsupervised where\n\nimport Fuml.Core\nimport qualified Fuml.Base.PCA as PCA\nimport Fuml.Base.KNN (euclideanDistance)\nimport Numeric.LinearAlgebra\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector as V\nimport Data.List (foldl1', sortBy, nub)\nimport Data.Ord (comparing)\nimport Control.Monad.Identity\n\n\ntype Unsupervisor m p a = Supervisor m () p a\n\nwith :: b -> [a] -> [(a,b)]\nwith y = map (,y)\n\ndata PCA = PCA { pcaComponents :: Int, pcaStat :: PCA.Stat }\n\npca :: Int -> Unsupervisor Identity PCA.Stat (Vector Double)\npca ncomp  = Supervisor $ \\_ theData ->\n  let stat@(m,_,v) = PCA.statVs $ map fst theData\n  in return $ Predict stat $ \\x -> takeRows ncomp v #> (x - m)\n\nfindNearestCentroidIx :: [Vector Double] -> Vector Double -> Int\nfindNearestCentroidIx ctrs x =\n  let vdixs = zip [0..] $ map (\\c -> euclideanDistance c x) ctrs\n  in fst $ head $ sortBy (comparing snd) vdixs\n\ncentroid :: [Vector Double] -> Vector Double\ncentroid vs =\n  let vadd = VS.zipWith (+)\n      n = realToFrac $ length vs\n  in VS.map (/n) $ foldl1' vadd vs\n\n{-kmeans :: Int -> Unsupervisor Identity [Vector Double] Int\nkmeans nclus\n  =  Supervisor $ \\_ theData ->\n        let clus = KM.kmeans (VU.convert) KM.euclidSq nclus (map fst theData)\n            ctrs = map (centroid . KM.elements) $ V.toList clus\n            pr v = findNearestCentroidIx ctrs v\n        in return $ Predict ctrs pr\n\ncluster :: Eq b => [a] -> (a-> Vector Double) -> Unsupervisor Identity p b -> [[a]]\ncluster xs f unsup =\n  let p = runIdentity $ runSupervisor unsup Nothing $ with () $ map (f) xs\n      withClus x = (x,predict p $ f x)\n      withCluss = map withClus xs\n      cluss = nub $ map snd withCluss\n      getElems clus = map fst $ filter ((==clus) . snd) withCluss\n  in map getElems cluss -}\n", "meta": {"hexsha": "92aa8d2de4aa3e6f59be9b04270a2bdea70666ed", "size": 1916, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "fuml/lib/Fuml/Unsupervised.hs", "max_stars_repo_name": "ekalosak/open", "max_stars_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81, "max_stars_repo_stars_event_min_datetime": "2017-05-22T22:42:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T10:41:20.000Z", "max_issues_repo_path": "fuml/lib/Fuml/Unsupervised.hs", "max_issues_repo_name": "ekalosak/open", "max_issues_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2017-05-31T09:06:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-18T12:00:27.000Z", "max_forks_repo_path": "fuml/lib/Fuml/Unsupervised.hs", "max_forks_repo_name": "ekalosak/open", "max_forks_repo_head_hexsha": "9faadba7614fc9d9448f1d3000c58cc3e93a8a36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23, "max_forks_repo_forks_event_min_datetime": "2017-05-22T15:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:26:20.000Z", "avg_line_length": 34.2142857143, "max_line_length": 83, "alphanum_fraction": 0.6753653445, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4279114429137299}}
{"text": "{-|\nModule : Mnist\n|-}\nmodule Mnist\n  ( Image(..)\n  , readTrainingData\n  , readTestData\n  , getData\n  ) where\n\nimport qualified Codec.Compression.GZip as GZip\nimport qualified Data.ByteString.Lazy as BL\nimport Data.Binary.Get\nimport Data.Word\nimport qualified Data.List.Split as S\nimport Numeric.LinearAlgebra\n\n\n-- | data representing an image\ndata Image = Image {\n      iRows :: Int -- ^ Number of rows\n    , iColumns :: Int -- ^ Number of columns\n    , iPixels :: [Word8] -- ^ Pixels\n    } deriving (Eq, Show)\n\n\n-- | Create column vector of Image pixels\ntoColVector :: Image\n         -> Matrix Double\ntoColVector image = (rc><1) p :: Matrix Double\n  where rc = iRows image * iColumns image\n        p = normalisedData image\n\n\n-- | Normalise Image pixels\nnormalisedData :: Image -> [Double]\nnormalisedData image = normalisePixel <$> iPixels image\n\n\n-- | Normalise pixel\nnormalisePixel :: Word8 -> Double\nnormalisePixel p = fromIntegral p / 255.0\n\n{-\n[offset] [type]          [value]          [description]\n0000     32 bit integer  0x00000801(2049) magic number (MSB first)\n0004     32 bit integer  60000            number of items\n0008     unsigned byte   ??               label\n0009     unsigned byte   ??               label\n ........\nxxxx     unsigned byte   ??               label\nThe labels values are 0 to 9.\n-}\n\n\n-- | Extract information from labels file\ndeserialiseLabels :: Get (Word32, Word32, [Word8])\ndeserialiseLabels = do\n  magicNumber <- getWord32be\n  count <- getWord32be\n  labelData <- getRemainingLazyByteString\n  let labels = BL.unpack labelData\n  return (magicNumber, count, labels)\n\n\n-- | Read labels from file\nreadLabels :: FilePath -> IO [Int]\nreadLabels filename = do\n  content <- GZip.decompress <$> BL.readFile filename\n  let (_, _, labels) = runGet deserialiseLabels content\n  return (fromIntegral <$> labels)\n\n{-\n[offset] [type]          [value]          [description]\n0000     32 bit integer  0x00000803(2051) magic number\n0004     32 bit integer  60000            number of images\n0008     32 bit integer  28               number of rows\n0012     32 bit integer  28               number of columns\n0016     unsigned byte   ??               pixel\n0017     unsigned byte   ??               pixel\n ........\nxxxx     unsigned byte   ??               pixel\nPixels are organized row-wise. Pixel values are 0 to 255. 0 means background (white), 255 means foreground (black).\n-}\n\n\n-- | Extract information from image file\ndeserialiseHeader :: Get (Word32, Word32, Word32, Word32, [[Word8]])\ndeserialiseHeader = do\n  magicNumber <- getWord32be\n  imageCount <- getWord32be\n  r <- getWord32be\n  c <- getWord32be\n  packedData <- getRemainingLazyByteString\n  let len = fromIntegral (r * c)\n  let unpackedData = S.chunksOf len (BL.unpack packedData)\n  return (magicNumber, imageCount, r, c, unpackedData)\n\n\n-- | Read Images form file\nreadImages :: FilePath -> IO [Image]\nreadImages filename = do\n  content <- GZip.decompress <$> BL.readFile filename\n  let (_, _, r, c, unpackedData) = runGet deserialiseHeader content\n  return (Image (fromIntegral r) (fromIntegral c) <$> unpackedData)\n\n\n-- | Create column vector of label\nvectorizedLabels :: Int -> Matrix Double\nvectorizedLabels x = (10><1) p :: Matrix Double\n  where p = [i | j <- [0 .. 9], let i = if j == x then 1.0 else 0.0]\n\n\n-- | Get training data\nreadTrainingData :: IO [(Matrix Double, Matrix Double)]\nreadTrainingData = do\n  trainingLabels <- readLabels \"train-labels-idx1-ubyte.gz\"\n  trainingImages <- readImages \"train-images-idx3-ubyte.gz\"\n  return (zip (map toColVector trainingImages) (vectorizedLabels <$> trainingLabels))\n\n\n-- | Get test data\nreadTestData :: IO [(Matrix Double, Int)]\nreadTestData = do\n  testLabels <- readLabels \"t10k-labels-idx1-ubyte.gz\"\n  testImages <- readImages \"t10k-images-idx3-ubyte.gz\"\n  return (zip (map toColVector testImages) testLabels)\n\n\n-- | Get training and test data\ngetData :: IO ([(Matrix Double, Matrix Double)], [(Matrix Double, Int)])\ngetData = do\n  trainingData <- readTrainingData\n  testData <- readTestData\n  return (trainingData, testData)", "meta": {"hexsha": "c336de77107d44c953184bb00c81abfd28fa06b4", "size": 4067, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Mnist.hs", "max_stars_repo_name": "Malenczuk/HuskNet", "max_stars_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-29T22:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-29T22:04:24.000Z", "max_issues_repo_path": "src/Mnist.hs", "max_issues_repo_name": "Malenczuk/HuskNet", "max_issues_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mnist.hs", "max_forks_repo_name": "Malenczuk/HuskNet", "max_forks_repo_head_hexsha": "ce64117b907fd79f4dfae824f16f3fe2e1db2b1b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1259259259, "max_line_length": 115, "alphanum_fraction": 0.6727317433, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.42751154778156303}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Data.AdaptiveCoordinateDescent.Internal\n  ( normalize\n  , perturb\n  , makePerturbed\n  , fromVector\n  , generate\n  , plus\n  , minus\n  , sphere\n  , rosen )\n  where\n\nimport Control.Monad\nimport Control.Monad.Primitive\nimport Control.Monad.State.Strict\nimport Control.Monad.ST\nimport Data.Foldable\nimport Data.Traversable\nimport qualified Data.Vector.Unboxed as V\nimport qualified Data.Vector.Unboxed.Mutable as VM\nimport Numeric.LinearAlgebra hiding ( toList )\nimport Pipes hiding ( for )\nimport System.Random.MWC\n\nnormalize :: Matrix Double -> Matrix Double\nnormalize mat = runST $ do\n  stds <- VM.replicate columns (0, 0)\n  for_ [0..columns-1] $ \\column -> do\n    for_ [0..rows-1] $ \\row -> do\n      (avg, std) <- VM.read stds column\n      VM.write stds column (avg + mat `atIndex` (row, column),\n                            std + (mat `atIndex` (row, column))**2)\n    (avg, std) <- VM.read stds column\n    VM.write stds column (avg / fromIntegral rows\n                         ,sqrt $ (std / fromIntegral rows) - (avg / fromIntegral rows)**2)\n\n  fstds <- V.unsafeFreeze stds\n\n  return $ (rows><columns) $ generate (rows*columns) $ \\offset ->\n             let row = offset `div` columns\n                 column = offset `mod` columns\n\n                 (avg, _var) = fstds V.! column -- variance ignored for now\n\n              in ((mat `atIndex` (row, column)) - avg)\n where\n  (rows, columns) = size mat\n\nperturb :: (PrimMonad m, Traversable f)\n        => f Double\n        -> Gen (PrimState m)\n        -> m (f Double)\nperturb thing rng = for thing $ \\val -> do\n  perturbance <- uniformR (-0.1, 0.1) rng\n  return $ val + perturbance\n\nmakePerturbed :: (PrimMonad m, Traversable f)\n              => f Double\n              -> Gen (PrimState m)\n              -> Int\n              -> Producer (f Double) m ()\nmakePerturbed params rng num_items =\n  replicateM_ num_items $ do\n    new_values <- lift $ perturb params rng\n    yield new_values\n\nfromVector :: (Container Vector a, Traversable f) => Vector a -> f void -> f a\nfromVector vec structure =\n  flip evalState 0 $ for structure $ \\_ -> do\n    idx <- get\n    put (idx+1)\n    return $ vec `atIndex` idx\n{-# INLINE fromVector #-}\n\ngenerate' :: Int -> (Int -> a) -> [a]\ngenerate' 0 _ = []\ngenerate' n fun = fun (n-1):generate' (n-1) fun\n\ngenerate :: Int -> (Int -> a) -> [a]\ngenerate x fun = reverse $ generate' x fun\n\nplus :: (Num a, Traversable f) => f a -> f a -> f a\nplus tr1 tr2 = flip evalState (toList tr2) $ for tr1 $ \\item -> do\n  (x:rest) <- get\n  put rest\n  return $ item + x\n\nminus :: (Num a, Traversable f) => f a -> f a -> f a\nminus tr1 tr2 = flip evalState (toList tr2) $ for tr1 $ \\item -> do\n  (x:rest) <- get\n  put rest\n  return $ item - x\n\nsphere :: [Double] -> Double\nsphere [x, y] = sqrt $ x*x + y*y\nsphere _ = error \"sphere takes two arguments.\"\n\nrosen :: [Double] -> Double\nrosen [x, y] = (1 - x)**2 + 100*(y - x**2)**2\nrosen _ = error \"rosen takes two arguments.\"\n\n", "meta": {"hexsha": "baf575a2c749c5f7f437a3a299ac6c1af1793e00", "size": 2973, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/AdaptiveCoordinateDescent/Internal.hs", "max_stars_repo_name": "Noeda/adaptivecoordinatedescent", "max_stars_repo_head_hexsha": "c2121a634ba6e38999f79d4763f89319ebd88c2e", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/AdaptiveCoordinateDescent/Internal.hs", "max_issues_repo_name": "Noeda/adaptivecoordinatedescent", "max_issues_repo_head_hexsha": "c2121a634ba6e38999f79d4763f89319ebd88c2e", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/AdaptiveCoordinateDescent/Internal.hs", "max_forks_repo_name": "Noeda/adaptivecoordinatedescent", "max_forks_repo_head_hexsha": "c2121a634ba6e38999f79d4763f89319ebd88c2e", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5865384615, "max_line_length": 90, "alphanum_fraction": 0.608139926, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4274707999157818}}
{"text": "-- {-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE DataKinds, GADTs, TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FunctionalDependencies #-}\n\nmodule UnitBLAS.Level2(unitTestLevel2BLAS) where \n\nimport Test.HUnit\n--import Numerical.Array.Shape as S \nimport Prelude as P\nimport Test.Tasty\nimport Test.Tasty.HUnit\n\n\nimport qualified Data.Vector.Storable as SV \nimport qualified Data.Vector.Storable.Mutable as SMV \n\nimport Data.Complex\n\nimport  Numerical.HBLAS.MatrixTypes as Matrix \nimport  Numerical.HBLAS.BLAS as BLAS \n\n\n--unitTestShape = testGroup \"Shape Unit tests\"\n--    [ testCase \"foldl on shape\" $ ( S.foldl (+) 0 (1:* 2:* 3 :* Nil )  @?=  ( P.foldl   (+) 0  [1,2,3])  )\n--    , testCase \"foldr on shape\" $ ( S.foldr (+) 0 (1:* 2:* 3 :* Nil )  @?=  ( P.foldr  (+) 0  [1,2,3])  )\n--    , testCase \"scanr1 on shape\" (S.scanr1 (+) 0 (1:* 1 :* 1:* Nil )   @?=  (3:* 2:* 1 :* Nil ) )\n--    , testCase \"scanl1 on shape\" (S.scanl1 (+) 0 (1:* 1 :* 1:* Nil )   @?=  (1:* 2:* 3:* Nil ) )\n--    ]\n\nmatmatTest1SGEMV:: IO ()\nmatmatTest1SGEMV = do \n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (\\_ -> (1.0::Float))\n    right <- Matrix.generateMutableDenseVector 2 (\\_ -> (1.0 :: Float))\n    res  <- Matrix.generateMutableDenseVector  2 (\\_ -> (0.0 :: Float))\n    BLAS.sgemv Matrix.NoTranspose  1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res \n    resList @?= [2,2]\n\nmatmatTest1DGEMV:: IO ()\nmatmatTest1DGEMV = do \n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (\\_ -> (1.0))\n    right <- Matrix.generateMutableDenseVector 2 (\\_ -> (1.0 ))\n    res  <- Matrix.generateMutableDenseVector 2  (\\_ -> (0.0 ))\n    BLAS.dgemv Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res \n    resList @?= [2.0,2.0]\n\nmatmatTest1CGEMV:: IO ()\nmatmatTest1CGEMV = do \n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (\\_ -> (1.0))\n    right <- Matrix.generateMutableDenseVector 2 (\\_ -> (1.0 ))\n    res  <- Matrix.generateMutableDenseVector  2 (\\_ -> (0.0 ))\n    BLAS.cgemv Matrix.NoTranspose  1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res \n    resList @?= [2.0,2.0]\n\nmatmatTest1ZGEMV:: IO ()\nmatmatTest1ZGEMV = do \n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (\\_ -> (1.0))\n    right <- Matrix.generateMutableDenseVector 2 (\\_ -> (1.0 ))\n    res  <- Matrix.generateMutableDenseVector 2 (\\_ -> (0.0 ))\n    BLAS.zgemv Matrix.NoTranspose  1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res \n    resList @?= [2.0,2.0]\n\n----\n----\n\nmatmatTest1SGER :: IO ()\nmatmatTest1SGER = do\n  res <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,2) (\\_ -> 1.0)\n  x <- Matrix.generateMutableDenseVector 2 (\\_ -> 2.0)\n  y <- Matrix.generateMutableDenseVector 2 (\\_ -> 3.0)\n  BLAS.sger 2.0 x y res\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n  resList @?= [13.0,13.0,13.0,13.0]\n\nmatmatTest1DGER :: IO ()\nmatmatTest1DGER = do\n  res <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,2) (\\_ -> 1.0)\n  x <- Matrix.generateMutableDenseVector 2 (\\_ -> 2.0)\n  y <- Matrix.generateMutableDenseVector 2 (\\_ -> 3.0)\n  BLAS.sger 2.0 x y res\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n  resList @?= [13.0,13.0,13.0,13.0]\n\n----\n----\n\nmatmatTest1STRSV:: IO ()\nmatmatTest1STRSV = do \n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) \n            (\\(i,j) -> if i >= j then (1.0::Float) else 0 )\n    \n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 3 else 1)\n    BLAS.strsv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res \n    resList @?= [2,1]\n\nmatmatTest1DTRSV:: IO ()\nmatmatTest1DTRSV = do \n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) \n                (\\(i,j) -> if i >= j then (1.0::Double) else 0 )\n    \n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 3 else 1)\n    BLAS.dtrsv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res \n    resList @?= [2,1]\n\nmatmatTest1CTRSV:: IO ()\nmatmatTest1CTRSV = do \n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) \n                (\\(i,j) -> if i >= j then (1.0::(Complex Float)) else 0 )\n    \n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 3 else 1)\n    BLAS.ctrsv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res \n    resList @?= [2,1]\n\nmatmatTest1ZTRSV:: IO ()\nmatmatTest1ZTRSV = do \n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) \n                (\\(i,j) -> if i >= j then (1.0::(Complex Double )) else 0 )\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 3 else 1)\n    BLAS.ztrsv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res \n    resList @?= [2,1]\n\nunitTestLevel2BLAS = testGroup \"BLAS Level 2 tests \" [\n----- gemv tests \n    testCase \"sgemv on 2x2 all 1s\"    matmatTest1SGEMV\n    ,testCase \"dgemv  on 2x2 all 1s \" matmatTest1DGEMV\n    ,testCase \"cgemv  on 2x2 all 1s\" matmatTest1CGEMV\n    ,testCase \"zgemv on 2x2 all 1s\" matmatTest1ZGEMV\n----- trsv tests\n    ,testCase \"strsv on 2x2 upper 1s\" matmatTest1STRSV\n    ,testCase \"dtrsv on 2x2 upper 1s\" matmatTest1DTRSV\n    ,testCase \"ctrsv on 2x2 upper 1s\" matmatTest1CTRSV\n    ,testCase \"ztrsv on 2x2 upper 1s\" matmatTest1ZTRSV\n---- ger tests\n    ,testCase \"sger on 2x2 all 1s\" matmatTest1SGER\n    ,testCase \"dger on 2x2 all 1s\" matmatTest1DGER\n    ]\n    \n", "meta": {"hexsha": "f0e22c5e97cc36704d06fb98960f1e79e6baf1d4", "size": 5814, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/UnitBLAS/Level2.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": "tests/UnitBLAS/Level2.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": "tests/UnitBLAS/Level2.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": 39.2837837838, "max_line_length": 108, "alphanum_fraction": 0.6554867561, "num_tokens": 2029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.42697563900267604}}
{"text": "{-# LANGUAGE BangPatterns          #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedLists       #-}\n{-# LANGUAGE ViewPatterns          #-}\n\n-- | Main module\nmodule SatOpt (main) where\n--module SatOpt (module SatOpt) where\n\nimport           SatOpt.FFT                    as SatOpt\nimport           SatOpt.Optimize               as SatOpt\nimport           SatOpt.Render                 as SatOpt\nimport           SatOpt.Utility                as SatOpt\n-- GENERATE: import New.Module as SatOpt\n\nimport           Data.Colour                   (blend)\nimport           Data.Colour.RGBSpace\nimport           Data.Colour.RGBSpace.HSL\nimport           Data.Complex\nimport           Data.List\nimport           Data.Packed.Matrix            (mapMatrix)\nimport           Debug.Trace                   (trace)\nimport           Numeric.LinearAlgebra.HMatrix hiding (disp, matrix, size)\nimport qualified Numeric.LinearAlgebra.HMatrix as HM\n\ndata Field2D a = FMat  (Matrix a)\n               | FFT   (Matrix a)\n               | FDisp (Matrix a)\n               | FFunc (\u211d -> \u211d -> a)\n\ndata HSource = HPointSources  [(\u211d, \u211d, \u2102)]\n             | HCircleSources \u211d [\u2102]\n             | HSum [HSource]\n\nhsrcToField :: HSource -> Field2D \u2102\nhsrcToField (HPointSources ps)   = FFunc $ pointSources ps\nhsrcToField (HCircleSources r p) = FFunc $ circleOfSources r p\nhsrcToField (HSum [h])           = hsrcToField h\nhsrcToField (HSum (h:hs))        = fieldSum (hsrcToField h) (hsrcToField (HSum hs))\n\nfieldSum :: Field2D \u2102 -> Field2D \u2102 -> Field2D \u2102\nfieldSum (FMat m1)  (FMat m2)  = FMat (m1 + m2)\nfieldSum (FFunc f1) (FFunc f2) = FFunc (\\x y -> f1 x y + f2 x y)\nfieldSum (FMat m1)  (FFunc f2) = fieldSum (FFunc f2) (FMat m1)\nfieldSum (FFunc f1) (FMat m2)  = fieldSum (matField (FFunc f1)) (FMat m2)\n\ndata HDisp = HConstDisp \u2102\n           | HFuncDisp (\u211d -> \u211d -> \u2102)\n\nhdspToField :: HDisp -> Field2D \u2102\nhdspToField (HConstDisp p) = constF p\nhdspToField (HFuncDisp f) = FFunc f\n\ndata HelmConf = HelmConf { helmsrc :: HSource\n                         , helmdsp :: HDisp\n                         }\n\ndata State a = State { amplitude  :: Field2D \u2102\n                     , dispersion :: Field2D \u2102\n                     , sources    :: Field2D \u2102\n                     , time       :: \u211d\n                     , freq       :: \u211d\n                     , conf       :: a\n                     , configure  :: State a -> State a\n                     , concrete   :: Bool\n                     }\n\nconstF :: Element a => a -> Field2D a\nconstF x = matField (FFunc (\\_ _ -> x))\n\ndefState :: State a\ndefState = State { amplitude  = constF (0 :+ 0)\n                 , dispersion = constF (1 :+ 0.1)\n                 , sources    = constF (0 :+ 0)\n                 , time       = 0\n                 , freq       = 1\n                 , conf       = undefined\n                 , configure  = const defState\n                 , concrete   = False\n                 }\n\nfromFieldC :: Field2D \u2102 -> Matrix \u2102\nfromFieldC (FFunc f) = sample2DM f [0, 1 .. size - 1] [0, 1 .. size - 1]\nfromFieldC (FMat m)  = m\nfromFieldC (FFT m)   = ifft2dM m\nfromFieldC (FDisp m) = sqrt $ (recip m) - (square normm)\n\nmatField :: Element a => Field2D a -> Field2D a\nmatField (FFunc f) = FMat $ sample2DM f [0, 1 .. size - 1] [0, 1 .. size - 1]\nmatField x         = x\n\nfftMat :: Field2D \u2102 -> Matrix \u2102\nfftMat (FFT m)  = m\nfftMat (FMat m) = fft2dM m\nfftMat f        = fftMat $ matField f\n\ndispMat :: Field2D \u2102 -> Matrix \u2102\ndispMat (FDisp m) = m\ndispMat (FMat m)  = recip $ square m + square normm\ndispMat f         = dispMat $ matField f\n\nmakeConcrete :: (State a) -> (State a)\nmakeConcrete st@(State { concrete = True }) = st\nmakeConcrete (st@(State { dispersion = d, sources = s, time = t, freq = f }))\n  = st { amplitude = ampl\n       , dispersion = FDisp disp\n       , sources = FFT srcs\n       , concrete = True }\n  where\n    disp = dispMat $ matField d\n    srcs = fftMat $ matField s\n    ampl = FMat $ timeShift f t $ ifft2dM $ srcs * disp\n\nphaseShift :: Matrix \u211d -> Matrix \u2102 -> Matrix \u2102\nphaseShift p m = mags * zipMatrixWith (:+) (cos angles) (sin angles)\n  where\n    angles = p + (mapMatrix realPart m `arctan2` mapMatrix imagPart m)\n    mags = m * conj m\n\ntimeShift :: \u211d -> \u211d -> Matrix \u2102 -> Matrix \u2102\ntimeShift f t m = case matField $ constF (tau * f * t) of\n                   FMat p -> phaseShift p m\n                   _      -> error \"matField output invalid\"\n\nsize :: Num a => a\nsize = 256\n\ntau :: \u211d\ntau = 2 * pi\n\nrootsOfUnity :: Int -> [\u2102]\nrootsOfUnity i = take i $ iterate (rotate (tau / fromIntegral i)) (1 :+ 0)\n\npointsOnCircle :: Int -> \u211d -> [(\u211d, \u211d)]\npointsOnCircle i r = map (fromC . scaleC r) $ rootsOfUnity i\n  where\n    fromC (a :+ b) = (a, b)\n    scaleC s c = (s :+ 0) * c\n\n-- | Take a position with respect to the center and move its origin to the top right\ncenter :: Floating a => a -> a\ncenter x = x - (size / 2)\n\npointSources :: [(\u211d, \u211d, \u2102)] -> \u211d -> \u211d -> \u2102\npointSources ps x y = sum $ map (\\(cx, cy, s) -> s * delta cx cy x y) ps\n\ncircleOfSources :: \u211d -> [\u2102] -> \u211d -> \u211d -> \u2102\ncircleOfSources rad cs = pointSources $ zipCs $ pointsOnCircle (length cs) rad\n  where\n    zipCs = map (\\(z, (x, y)) -> (x, y, z)) . zip cs\n\n\n--const $ FFunc testFunc\n\n-- testFunc :: HelmConf -> Field2D \u2102\n-- testFunc (HelmConf (HPointSources ps) _)   = FFunc $ pointSources ps\n-- testFunc (HelmConf (HCircleSources r p) _) = FFunc $ circleOfSources r p\n  -- where\n  --   pol m p = mkPolar m ((pi/180)*p)\n-- testFunc = pointSources [ (0.48, 0.48, 0.5 :+ 0)\n--                         , (0.52, 0.52, (-0.5) :+ 0)\n--                         ]\n\n-- 0.1 [ pol 1 0\n--                                , pol 1 60\n--                                , pol 1 120\n--                                , pol 1 120\n--                                , pol 1 60\n--                                , pol 1 0\n--                                ]\n\nnormm :: Matrix \u2102\n--im, jm :: Matrix \u2102\n--im = sample2DM (\\x _ -> x :+ 0) [0, 1 .. size - 1] [0, 1 .. size - 1]\n--jm = sample2DM (\\_ y -> y :+ 0) [0, 1 .. size - 1] [0, 1 .. size - 1]\nnormm = sample2DM (\\x y -> norm x y :+ 0) [0, 1 .. size - 1] [0, 1 .. size - 1]\n\neps :: \u211d\neps = 5\n\ndelta :: \u211d -> \u211d -> \u211d -> \u211d -> \u2102\ndelta ((*size) -> cx) ((*size) -> cy) ((*size) -> x) ((*size) -> y)\n  | norm (center x - cx) (center y - cy) < size * eps    = 1\n  | otherwise                                                       = 0\n\nrendCmp_ :: \u2102 -> (\u211d, \u211d, \u211d)\nrendCmp_ (polar -> (m, p)) = uncurryRGB (\\x y z -> (x, y, z)) $ hsl a 1 m\n  where\n--    a = if p < 0 then 90 else 0\n    a = (p + pi) * (180 / pi)\n\nrendCmp :: Matrix \u2102 -> (Matrix \u211d, Matrix \u211d, Matrix \u211d)\nrendCmp = matrify . unzip3 . map (unzip3 . map rendCmp_) . toLists\n  where\n    matrify (x, y, z) = (fromLists x, fromLists y, fromLists z)\n\nrotate :: \u211d -> \u2102 -> \u2102\nrotate r = uncurry mkPolar . (\\(m, p) -> (m, p + r)) . polar\n\nvisual :: (\u211d, \u211d, \u211d, \u211d) -> \u2102 -> \u2102\nvisual (xa, xb, ya, yb) (polar -> (m, p))\n  = mkPolar (((yb - ya) * (m - xa)/(xb - xa)) + ya) p\n\nvisualM :: Matrix \u2102 -> Matrix \u2102\nvisualM cs@(fromComplex -> (r, i)) = mapMatrix (visual (small, big, 0, 1)) cs\n  where\n    !mags  = flatten $ sqrt $ (r * r) + (i * i)\n    !small = minElement mags\n    !big   = maxElement mags\n\nupdateState :: State a -> State a\n--updateState = id\nupdateState s@State { time = t } = s { time = t + 0.01, concrete = False }\n\ndata RenderMode = RendAmp | RendSrc | RendDsp | RendAmpMag | RendAmpPhs\n\n\nrenderState :: RenderMode -> State a -> RGBTrips\nrenderState r = case r of\n  RendAmp    -> rend . concAmp\n  RendAmpMag -> rend . concAmpMag\n  RendAmpPhs -> rend . concAmpPhs\n  RendSrc    -> rend . concSrc\n  RendDsp    -> rend . concDsp\n  where\n  wrap f = fromFieldC . f . makeConcrete\n  rend =  rendCmp . visualM\n  concAmp    = wrap amplitude\n  concAmpMag = mag . fromComplex . concAmp\n  concAmpPhs = phs . fromComplex . concAmp\n  concSrc    = wrap sources\n  concDsp    = wrap dispersion\n  mag (x, y) = toComplex $ ((x*x) + (y*y), y - y)\n  phs (x, y) = toComplex $ ((y `arctan2` x), y - y)\n\nchangeRenderMode :: RenderMode -> Conf (State a) -> Conf (State a)\nchangeRenderMode r c = c { render = renderState r }\n\ngetConf :: Conf (State HelmConf) -> HelmConf\ngetConf (Conf { state = (State { conf = cn })}) = cn\n\nchangeConf :: (HelmConf -> HelmConf) -> Conf (State HelmConf) -> Conf (State HelmConf)\nchangeConf h c@(Conf { state = s@(State { configure = f, conf = cn })})\n  = c { state = configure s' s' }\n  where\n    s' = s { conf = h cn }\n\nrelPhase (polar -> (_, p1)) (polar -> (_, p2)) = abs $ p1 - p2\n\n--getPhase c@(HelmConf { helmsrc = HCircleSources _ [c1, c2] }) = Just $ relPhase c1 c2\n--getPhase _ = Nothing\ngetPhase c@(HelmConf { helmsrc = HPointSources [_, (x, _, _)] }) = Just x\ngetPhase _ = Nothing\n\nchangePhase :: Double -> Conf (State HelmConf) -> Conf (State HelmConf)\nchangePhase p = changeConf shift\n  where\n    shift c@(getPhase -> m) = case m of\n                               Just ph -> c { helmsrc = testSource $ ph + p }\n                               Nothing -> c\n\nkeyState :: KMState -> Conf (State HelmConf) -> IO (Conf (State HelmConf))\nkeyState \"\"  c = return c\nkeyState \"d\" c = return $ changeRenderMode RendDsp c\nkeyState \"s\" c = return $ changeRenderMode RendSrc c\nkeyState \"a\" c = return $ changeRenderMode RendAmp c\nkeyState \"m\" c = return $ changeRenderMode RendAmpMag c\nkeyState \"p\" c = return $ changeRenderMode RendAmpPhs c\nkeyState \"w\" c = do\n  let p = changePhase 0.5 c\n  putStrLn $ \"Shifted by 0.5 to \" ++ show (getPhase $ getConf c)\n  return p\nkeyState \"q\" c = do\n  let p = changePhase (-0.5) c\n  putStrLn $ \"Shifted by -0.5 to \" ++ show (getPhase $ getConf c)\n  return p\nkeyState x   c = return $ trace x c\n\npol m p = mkPolar m (p * pi / 180)\n\ntestSource :: Double -> HSource\ntestSource p = HPointSources [ (size/2, size/2, (-1) :+ 0)\n                             , (p, p, 1 :+ 0)\n                             ]\n-- testSource p = HSum [ HCircleSources 0.2  [ pol 1 0\n--                                           , pol 1 0\n--                                           , pol 1 0\n--                                           , pol 1 0\n--                                           ]\n--                     , HCircleSources 0.15 [ pol 1 0\n--                                           , pol 1 90\n--                                           , pol 1 180\n--                                           , pol 1 270\n--                                           ]\n--                     ]\n\ndspfun :: \u211d -> \u211d -> \u2102\ndspfun x y\n  | outbox (center x) (center y) = 1.2 :+ 0\n  | otherwise                    = 1 :+ 0\n  where\n    test = 1\n    outbox a b\n      | a < (-32) = True\n      | a > 32    = True\n      | b < (-32) = True\n      | b > 32    = True\n      | otherwise = False\n\ntestConf :: Double -> HelmConf\ntestConf p = HelmConf { helmsrc = testSource p\n                      , helmdsp = HFuncDisp dspfun\n                      }\n\n-- testConf = HelmConf { helmsrc = HCircleSources 0.1 [ pol 1 0\n--                                                    , pol 1 0\n--                                                    , pol 1 0\n--                                                    , pol 1 0\n--                                                    , pol 1 0\n--                                                    , pol 1 0 ]\n--                     , helmdsp = HConstDisp 0.001\n--                     }\n--   where\n--     pol m p = mkPolar m (p * pi / 180)\n\ntestConfigure st@(State { conf = HelmConf { helmdsp = d, helmsrc = s }})\n  = st { sources = hsrcToField s\n       , dispersion = hdspToField d\n       , concrete = False\n       }\n\ninitState :: State HelmConf\ninitState = defState { freq = 3\n                     , conf = testConf 0\n                     , configure = testConfigure\n                     }\n\nconfig :: Conf (State HelmConf)\nconfig = changeConf id\n         Conf { keyBinds = keyState\n              , state    = initState\n              , evolve   = updateState\n              , render   = renderState RendAmp\n              , canvas   = (size, size)\n              }\n\n-- | TODO\nmain :: IO ()\n--main = optimize\nmain = runDisp config\n", "meta": {"hexsha": "582b23bf6327f3ba3fb0d3e6993780ce7ef867d8", "size": 12060, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "library/SatOpt.hs", "max_stars_repo_name": "taktoa/SatOpt", "max_stars_repo_head_hexsha": "b3920635c179103f1f127431e91845ea92a0f64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T05:08:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:08:33.000Z", "max_issues_repo_path": "library/SatOpt.hs", "max_issues_repo_name": "taktoa/SatOpt", "max_issues_repo_head_hexsha": "b3920635c179103f1f127431e91845ea92a0f64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "library/SatOpt.hs", "max_forks_repo_name": "taktoa/SatOpt", "max_forks_repo_head_hexsha": "b3920635c179103f1f127431e91845ea92a0f64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2613636364, "max_line_length": 87, "alphanum_fraction": 0.5055555556, "num_tokens": 3788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021787, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.42665345908375846}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE AllowAmbiguousTypes   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveAnyClass        #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedLabels      #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-|\nModule      : Grenade.Layers.Transpose\nDescription : Layer that transposes its input\nMaintainer  : Theo Charalambous\nLicense     : BSD2\nStability   : experimental\n-}\n\nmodule Grenade.Layers.Transpose \n  (\n  -- * Layer Definition\n    Transpose (..)\n  \n  -- * Helper function\n  , initTranspose\n  ) where\n\nimport           Control.DeepSeq                   (NFData (..))\n\nimport           Data.Kind                         (Type)\nimport           Data.Maybe                        (fromJust)\nimport           Data.Proxy\nimport           Data.Serialize\nimport           GHC.TypeLits\n\nimport qualified Numeric.LinearAlgebra             as LA\nimport           Numeric.LinearAlgebra.Static      (R)\nimport qualified Numeric.LinearAlgebra.Static      as H\n\nimport           Grenade.Core\nimport           Grenade.Layers.Internal.Transpose\nimport           Grenade.Onnx\n\n -- todo: we can probably use a type family to represent this much better\ndata Transpose :: Nat\n               -> Shape\n               -> Shape\n               -> Type where\n  Transpose  :: ( KnownNat dimensions )\n          => !(R dimensions)\n          -> Transpose dimensions input output\n\ninstance Show (Transpose dimensions input output) where\n  show (Transpose mat) = \"Transpose \" ++ show mat\n\ninstance UpdateLayer (Transpose dimensions input output) where\n  type Gradient (Transpose dimensions input output) = ()\n  runUpdate _ x _  = x\n  reduceGradient _ = ()\n\ninstance ( KnownNat dimensions ) => RandomLayer (Transpose dimensions input output) where\n  createRandomWith _ _ = pure initTranspose\n\n-- | Initialize a tranpose layer that is equivalent to the identity function\ninitTranspose :: forall dimensions input output. ( KnownNat dimensions )\n              => Transpose dimensions input output\ninitTranspose =\n  let ds    = fromIntegral $ natVal (Proxy :: Proxy dimensions)\n      perms = H.fromList [1..ds] :: R dimensions\n  in Transpose perms\n\ninstance ( KnownNat dimensions ) => Serialize (Transpose dimensions input output) where\n  put (Transpose perms) = putListOf put . LA.toList . H.extract $ perms\n  get                   = do\n    perms <- maybe (fail \"Vector of incorrect size\") return . H.create . LA.fromList =<< getListOf get\n    return $ Transpose perms\n\ninstance ( KnownNat i, KnownNat j, KnownNat k, KnownNat l, KnownNat a, KnownNat b, KnownNat c, KnownNat d )\n  => Layer (Transpose 4 ('D4 i j k l) ('D4 a b c d)) ('D4 i j k l) ('D4 a b c d) where\n\n  type Tape (Transpose 4 ('D4 i j k l) ('D4 a b c d)) ('D4 i j k l) ('D4 a b c d) = ()\n\n  runForwards (Transpose perms) (S4D x)\n    = let n  = fromIntegral $ natVal (Proxy :: Proxy i)\n          c  = fromIntegral $ natVal (Proxy :: Proxy j)\n          h  = fromIntegral $ natVal (Proxy :: Proxy k)\n          w  = fromIntegral $ natVal (Proxy :: Proxy l)\n          x' = H.extract x\n          perms' = H.extract perms\n          r  = transpose4d [n, c, h, w] perms' x'\n      in  ((), S4D . fromJust . H.create $ r)\n\n  runBackwards = undefined\n\ninstance OnnxOperator (Transpose dimensions input output) where\n  onnxOpTypeNames _ = [\"Transpose\"]\n\ninstance OnnxLoadable (Transpose 4 input output) where\n  loadOnnxNode _ node = readIntsAttribute \"perm\" node >>= formatPerm\n    where\n      formatPerm :: [Int] -> Either OnnxLoadFailure (Transpose 4 input output)\n      formatPerm [_, _, n, c, h, w]\n        = let centered = map (\\x -> fromIntegral $ x - 2) [n, c, h, w]\n              perms :: R 4 = H.fromList centered\n          in  return $ Transpose perms\n      formatPerm _ = loadFailureReason \"Permutation shape incorrect of Transpose\"\n\ninstance NFData (Transpose dims input output) where\n  rnf (Transpose perms) = rnf perms\n", "meta": {"hexsha": "07d7eb939c1b69ddb670555dd8297447911d03e2", "size": 4297, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Transpose.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/Transpose.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/Transpose.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": 36.7264957265, "max_line_length": 107, "alphanum_fraction": 0.6292762392, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4264322825098493}}
{"text": "{-# LANGUAGE DataKinds            #-}\n{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE GADTs                #-}\n{-# LANGUAGE KindSignatures       #-}\n{-# LANGUAGE LambdaCase           #-}\n{-# LANGUAGE PolyKinds            #-}\n{-# LANGUAGE QuasiQuotes          #-}\n{-# LANGUAGE RankNTypes           #-}\n{-# LANGUAGE RecordWildCards      #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE TemplateHaskell      #-}\n{-# LANGUAGE TypeApplications     #-}\n{-# LANGUAGE TypeInType           #-}\n{-# LANGUAGE TypeOperators        #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nimport           Control.Category\nimport           Control.DeepSeq\nimport           Control.Exception\nimport           Control.Monad\nimport           Data.Foldable\nimport           Data.Kind\nimport           Data.List hiding                      ((\\\\))\nimport           Data.Maybe\nimport           Data.Singletons\nimport           Data.Monoid\nimport           Data.Singletons.TypeLits\nimport           Data.Time.Clock\nimport           Options.Applicative\nimport           Prelude hiding                        ((.), id)\nimport           Statistics.Distribution.Uniform\nimport           System.Random.MWC\nimport           TensorOps.Backend.BTensor\nimport           TensorOps.Backend.NTensor\nimport           TensorOps.Learn.NeuralNet\nimport           TensorOps.Learn.NeuralNet.FeedForward\nimport           TensorOps.NatKind\nimport           TensorOps.Types\nimport           Text.PrettyPrint.ANSI.Leijen hiding   ((<>),(<$>))\nimport           Text.Printf\nimport           Type.Class.Higher.Util\nimport qualified Data.String.Here                      as H\nimport qualified TensorOps.Tensor                      as TT\n\n\nnetTest\n    :: forall k (t :: [k] -> Type).\n     ( Tensor t\n     , ElemT t ~ Double\n     , NFData1 t\n     , NFData (t '[FromNat 1])\n     , NFData (t '[FromNat 2])\n     )\n    => Proxy t\n    -> Double\n    -> Int\n    -> [Integer]\n    -> GenIO\n    -> IO String\nnetTest _ rate n hs g = withSingI (sFromNat @k (SNat @1)) $\n                        withSingI (sFromNat @k (SNat @2)) $ do\n    ((inps,outs),tp) <- time $ do\n      inps :: [t '[FromNat 2]] <- replicateM n (genRand (uniformDistr (-1) 1) g)\n      let outs :: [t '[FromNat 1]]\n          outs = flip map inps $ \\v -> TT.konst $\n                   if v `inCircle` (TT.konst 0.33, 0.33)\n                        || v `inCircle` (TT.konst (-0.33), 0.33)\n                     then 1\n                     else 0\n      evaluate . force $ (inps, outs)\n    printf \"Generated test points (%s)\\n\" (show tp)\n    net0 :: Network t (FromNat 2) (FromNat 1)\n            <- genNet (hs `zip` repeat actLogistic) actLogistic g\n    let trained = foldl' trainEach net0 (zip inps outs)\n          where\n            trainEach :: SingI o\n                      => Network t i o\n                      -> (t '[i], t '[o])\n                      -> Network t i o\n            trainEach nt (i, o) = nt `deepseq` trainNetwork squaredError rate i o nt\n    (trained', tn) <- time $ return trained\n    printf \"Network trained (%s)\\n\" (show tn)\n    let outMat = [ [ render . TT.unScalar . join TT.dot . runNetwork trained' $\n                       fromJust (TT.fromList [x / 25 - 1,y / 10 - 1])\n                   | x <- [0..50] ]\n                 | y <- [0..20] ]\n        render r | r <= 0.2  = ' '\n                 | r <= 0.4  = '.'\n                 | r <= 0.6  = '-'\n                 | r <= 0.8  = '='\n                 | otherwise = '#'\n    return $ unlines outMat\n  where\n    inCircle\n        :: SingI n\n        => t '[n]\n        -> (t '[n], Double)\n        -> Bool\n    v `inCircle` (o, r) = let d = TT.zip (-) v o\n                          in  TT.unScalar (d `TT.dot` d) <= r**2\n\n\ndata Opts = O { oRate    :: Double\n              , oSamples :: Int\n              , oNetwork :: [Integer]\n              , oTests   :: [TestT]\n              }\n\nopts :: Parser Opts\nopts = O <$> option auto\n               ( long \"rate\" <> short 'r' <> metavar \"STEP\"\n              <> help \"Neural network learning rate\"\n              <> value 1 <> showDefault\n               )\n         <*> option auto\n               ( long \"samps\" <> short 's' <> metavar \"COUNT\"\n              <> help \"Number of samples to train the network on\"\n              <> value 50000 <> showDefault\n               )\n         <*> option auto\n               ( long \"layers\" <> short 'l' <> metavar \"LIST\"\n              <> help \"List of hidden layer sizes\"\n              <> value [12,8] <> showDefault\n               )\n         <*> (nub <$> (some (argument readBackend (metavar \"BACKEND\")))\n               <|> pure [TTBLAS TBHMat]\n             )\n\nmain :: IO ()\nmain = withSystemRandom $ \\g -> do\n    O{..} <- execParser $ info (helper <*> opts)\n        ( fullDesc\n       <> header \"tensor-ops-dots - train neural nets with tensor-ops\"\n       <> progDescDoc (Just d)\n        )\n\n    printf \"rate: %f | samps: %d | layers: %s\\n\" oRate oSamples (show oNetwork)\n\n    forM_ oTests $ \\t -> do\n      printf \"Training %s network ...\\n\" (ttLong t)\n      let tester :: Double -> Int -> [Integer] -> GenIO -> IO String\n          tester = case t of\n            TTNested TVList -> netTest (Proxy @NTensorL)\n            TTNested TVVect -> netTest (Proxy @NTensorV)\n            TTBLAS   TBHMat -> netTest (Proxy @(BTensorV (HMat Double)))\n      putStrLn =<< tester oRate oSamples oNetwork g\n  where\n    d :: Doc\n    d = string [H.here|\nTrains a feed-forward neural network on a 2D classifier using tensor-ops\nmachinery, with the given backends.  (If none provided, backend defaults to 'b')\n|]\n     <$$> mempty\n     <$$> string \"Backends:\"\n     <$$> vsep [ string $ printf \"- %s: %s\" (ttShort t) (ttLong t)\n               | t <- allTests ]\n\ntime\n    :: NFData a\n    => IO a\n    -> IO (a, NominalDiffTime)\ntime x = do\n    t1 <- getCurrentTime\n    y  <- evaluate . force =<< x\n    t2 <- getCurrentTime\n    return (y, t2 `diffUTCTime` t1)\n\n\ndata TestT = TTNested TestV\n           | TTBLAS   TestB\n           deriving (Show, Eq, Ord)\ndata TestV = TVList\n           | TVVect\n           deriving (Show, Eq, Ord)\ndata TestB = TBHMat\n           deriving (Show, Eq, Ord)\n\nallTests :: [TestT]\nallTests = ([TTNested] <*> [TVList, TVVect]) ++ [TTBLAS TBHMat]\n\nreadBackend :: ReadM TestT\nreadBackend = eitherReader $ \\s -> case s of\n    \"nl\" -> Right $ TTNested TVList\n    \"nv\" -> Right $ TTNested TVVect\n    \"b\"  -> Right $ TTBLAS   TBHMat\n    o    -> Left  $ \"Unknown backend: \" ++ o\n\nttShort\n    :: TestT\n    -> String\nttShort = \\case\n    TTNested v -> 'n' : tvShort v\n    TTBLAS   b -> 'b' : tbShort b\n  where\n    tvShort = \\case\n      TVList -> \"l\"\n      TVVect -> \"v\"\n    tbShort = \\case\n      TBHMat -> \"\"\n\nttLong\n    :: TestT\n    -> String\nttLong = \\case\n    TTNested v -> printf \"Nested (%s)\" (tvLong v)\n    TTBLAS   b -> printf \"BLAS (%s)\" (tbLong b)\n  where\n    tvLong = \\case\n      TVList -> \"List\"\n      TVVect -> \"Vector\"\n    tbLong = \\case\n      TBHMat -> \"HMatrix\"\n\n", "meta": {"hexsha": "accf541dc6897dd2e4e867a4d4dcaeec55fa242b", "size": 6908, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Dots.hs", "max_stars_repo_name": "mstksg/tensor-ops", "max_stars_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2016-08-24T06:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T00:31:35.000Z", "max_issues_repo_path": "app/Dots.hs", "max_issues_repo_name": "mstksg/tensor-ops", "max_issues_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-09-29T06:01:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T10:52:51.000Z", "max_forks_repo_path": "app/Dots.hs", "max_forks_repo_name": "mstksg/tensor-ops", "max_forks_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-09-28T05:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2017-01-30T11:01:34.000Z", "avg_line_length": 32.2803738318, "max_line_length": 84, "alphanum_fraction": 0.5046323104, "num_tokens": 1899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706733, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4262690655859436}}
{"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleInstances #-}\n\nmodule Math.Matrix\n       ( DimVector (..)\n       , DimMatrix (..)\n       , GPConstraint\n       , withMat\n       , toMatrix\n       , mulM\n       , transposeM\n       , mapMM\n       , mapDiagonalM\n       , invSM\n       , substractMeanM\n       , (+^^)\n       , (-^^)\n       , (*^^)\n       , cholM\n       , foldAllSM\n       , sumAllSM\n       , trace2SM\n       , toDimMatrix\n       , detSM\n       , toMatrixM'\n       , zipWithDim\n       , zipWithArray\n       , identM\n       , delayMatrix\n       , linearSolveM\n       , vectorLength\n       , randomMatrixD\n       , matrixRowsNum\n       , matrixColsNum\n       , pinvSM\n       , mulPM\n       , eigSHM\n       )\n       where\n\nimport Universum hiding (Vector, transpose, map, natVal,\n                         zipWith)\n\nimport           GHC.TypeLits hiding (someNatVal)\n\nimport           Data.Array.Repa\nimport           Data.Random.Normal (normals)\nimport           Data.Vector.Unboxed.Base (Unbox)\nimport           Data.Vinyl.TypeLevel (AllConstrained)\n--import           Numeric.Dimensions \nimport           Numeric.LinearAlgebra.Repa hiding (Matrix, Vector)\nimport           System.Random (Random, RandomGen)\n\nimport PCA.Types\nimport PCA.Util hiding (randomMatrixD, zipWithArray)\n\nnewtype DimVector r (n :: Nat) a\n  = DimVector { runVector :: Vector r a }\n  deriving Eq\n\nnewtype DimMatrix r (y :: Nat) (x :: Nat) a\n  = DimMatrix { getInternal :: Matrix r a}\n\ninstance Functor (DimVector D n) where\n  fmap f (DimVector vector) = DimVector (smap f vector)\n\nwithMat\n  :: Matrix D a\n  -> (forall x y. (KnownNat x, KnownNat y) => DimMatrix D x y a -> k)\n  -> k\nwithMat m f =\n  let (Z :. x :. y) = extent m\n  in\n  case someNatVal (fromIntegral x) of\n    SomeNat (Proxy :: Proxy m) -> case someNatVal (fromIntegral y) of\n      SomeNat (Proxy :: Proxy n) -> f (DimMatrix @_ @m @n m)\n\nmulM\n  :: forall y1 x1 y2 x2 a.\n  ( AllConstrained KnownNat [x1, x2, y1, y2]\n  , Numeric a\n  , x1 ~ y2\n  )\n  => DimMatrix D y1 x1 a\n  -> DimMatrix D y2 x2 a\n  -> DimMatrix D y1 x2 a\nmulM (DimMatrix m1) (DimMatrix m2) = DimMatrix $ delay $ m1 `mulS` m2\n\ntransposeM\n  :: (KnownNat y, KnownNat x)\n  => DimMatrix D y x a\n  -> DimMatrix D x y a\ntransposeM (DimMatrix m) = DimMatrix $ transpose m\n\nmapMM\n  ::\n  ( KnownNat y\n  , KnownNat x\n  , Unbox a\n  , Unbox b\n  )\n  => (a -> b)\n  -> DimMatrix D y x a\n  -> DimMatrix D y x b\nmapMM f (DimMatrix m) =  DimMatrix $ map f m\n\nmapDiagonalM\n  ::\n  ( KnownNat y\n  , KnownNat x\n  , Unbox a\n  )\n  => (a -> a)\n  -> DimMatrix D y x a\n  -> DimMatrix D y x a\nmapDiagonalM f (DimMatrix m) = DimMatrix $ mapDiagonal f m\n\ninvSM\n  ::\n  ( KnownNat y\n  , KnownNat x\n  , Field a\n  , Numeric a\n  , y ~ x\n  )\n  => DimMatrix D y x a\n  -> DimMatrix D y x a\ninvSM (DimMatrix m) = DimMatrix $ delay $ invS m\n\nsubstractMeanM\n  ::\n  ( KnownNat y\n  , KnownNat x\n  )\n  => DimMatrix D y x Double\n  -> DimMatrix D y x Double\nsubstractMeanM (DimMatrix m) = DimMatrix $ substractMean m\n\ninfixl 6 +^^, -^^\ninfixl 7 *^^\n\n(+^^)\n  :: forall y1 x1 y2 x2 a.\n  ( AllConstrained KnownNat [x1, x2, y1, y2]\n  , x1 ~ x2\n  , y1 ~ y2\n  , Num a\n  )\n  => DimMatrix D y1 x1 a\n  -> DimMatrix D y2 x2 a\n  -> DimMatrix D y2 x2 a\n(+^^) (DimMatrix m1) (DimMatrix m2) = DimMatrix $ m1 +^ m2\n\n(-^^)\n  :: forall y1 x1 y2 x2 a.\n  ( AllConstrained KnownNat [x1, x2, y1, y2]\n  , x1 ~ x2\n  , y1 ~ y2\n  , Num a\n  )\n  => DimMatrix D y1 x1 a\n  -> DimMatrix D y2 x2 a\n  -> DimMatrix D y2 x2 a\n(-^^) (DimMatrix m1) (DimMatrix m2) = DimMatrix $ m1 -^ m2\n\n(*^^)\n  :: forall y1 x1 y2 x2 a.\n  ( AllConstrained KnownNat [x1, x2, y1, y2]\n  , x1 ~ x2\n  , y1 ~ y2\n  , Num a\n  )\n  => DimMatrix D y1 x1 a\n  -> DimMatrix D y2 x2 a\n  -> DimMatrix D y2 x2 a\n(*^^) (DimMatrix m1) (DimMatrix m2) = DimMatrix $ m1 *^ m2\n\ncholM\n  ::\n  ( KnownNat y\n  , KnownNat x\n  , Field a\n  , y ~ x\n  )\n  => DimMatrix D y x a\n  -> DimMatrix D y x a\ncholM (DimMatrix m) = DimMatrix $ delay $ chol $ trustSym $ computeS m\n\nsumAllSM\n  ::\n  ( KnownNat y\n  , KnownNat x\n  , Num a)\n  => DimMatrix D y x a\n  -> a\nsumAllSM (DimMatrix m) = sumAllS m\n\nfoldAllSM\n  :: (KnownNat y, KnownNat x)\n  => (Double -> Double -> Double)\n  -> Double\n  -> DimMatrix D y x Double\n  -> Double\nfoldAllSM f initValue (DimMatrix m) = foldAllS f initValue m\n\ndetSM\n  :: (KnownNat y, KnownNat x)\n  => DimMatrix D y x Double\n  -> Double\ndetSM (DimMatrix m) = detS m\n\ntrace2SM\n  :: (KnownNat x, KnownNat y)\n  => DimMatrix D x y Double\n  -> Double\ntrace2SM (DimMatrix m) = trace2S $ computeS m\n\ntoDimMatrix\n  ::\n  ( Source r a\n  , KnownNat m\n  , KnownNat n\n  )\n  => DimVector r m a\n  -> Int\n  -> DimMatrix D m n a\ntoDimMatrix (DimVector arr) desiredSize =\n  DimMatrix (toMatrix arr desiredSize)\n\ntoMatrixM'\n  :: (Source r a, KnownNat n, KnownNat m)\n  => DimVector r n a\n  -> DimMatrix D n m a\ntoMatrixM' (DimVector arr) =\n  DimMatrix $ fromFunction (Z :. dimension :. 1) generator\n  where\n    dimension = size . extent $ arr\n    generator (Z :. rows :. _) = linearIndex arr rows\n\nzipWithDim\n  ::\n  ( Source r1 a\n  , Source r2 b\n  , KnownNat m\n  , KnownNat n\n  )\n  => (a -> b -> c)\n  -> DimMatrix r1 m n a\n  -> DimMatrix r2 m n b\n  -> DimMatrix D m n c\nzipWithDim f (DimMatrix mat1) (DimMatrix mat2) =\n  DimMatrix $ zipWith f mat1 mat2\n\nzipWithArray\n  ::\n  ( KnownNat n\n  , KnownNat m\n  )\n  => (a -> b -> c)\n  -> DimVector D n a\n  -> DimMatrix D n m b\n  -> DimMatrix D n m c\nzipWithArray f (DimVector array1) (DimMatrix array2) =\n  DimMatrix $ zipWith f (toMatrix array1 n) array2\n  where\n    (Z :. n :. _) = extent array2\n\nidentM\n  :: forall m n a.\n  ( KnownNat m\n  , KnownNat n\n  , GPConstraint a\n  , m ~ n\n  )\n  => DimMatrix D m n a\nidentM =\n  let dim = fromEnum $\n            natVal @m @Proxy Proxy in DimMatrix $\n            identD dim\n\ndelayMatrix\n  ::\n  ( KnownNat m\n  , KnownNat n\n  , Source r a\n  )\n  => DimMatrix r m n a\n  -> DimMatrix D m n a\ndelayMatrix (DimMatrix matrix) = DimMatrix (delay matrix)\n\nlinearSolveM\n  ::\n  ( Field a\n  , AllConstrained KnownNat '[m, n]\n  )\n  => DimMatrix D m m a\n  -> DimMatrix D m n a\n  -> Maybe (DimMatrix D m n a)\nlinearSolveM (DimMatrix mat1) (DimMatrix mat2) =\n  case linearSolveS mat1 mat2 of\n    Nothing  -> Nothing\n    Just sol -> Just . delayMatrix . DimMatrix $ sol\n\nvectorLength\n  :: forall r m a. KnownNat m\n  => DimVector r m a\n  -> Int\nvectorLength _ = fromEnum $ natVal (Proxy @m)\n\nmatrixRowsNum\n  :: forall r m n a. KnownNat m\n  => DimMatrix r m n a\n  -> Int\nmatrixRowsNum _ = fromEnum $ natVal (Proxy @m)\n\nmatrixColsNum\n  :: forall r m n a. KnownNat n\n  => DimMatrix r m n a\n  -> Int\nmatrixColsNum _ = fromEnum $ natVal (Proxy @n)\n\nrandomMatrixD\n  :: forall a g m n.\n  ( RandomGen g\n  , Random a\n  , Unbox a\n  , Floating a\n  , KnownNat m\n  , KnownNat n\n  )\n  => g\n  -> (Int, Int)\n  -> DimMatrix D m n a\nrandomMatrixD gen (rows, cols) =\n  let randomList = take (rows * cols) (normals gen) in\n    DimMatrix . delay $ fromListUnboxed (Z :. rows :. cols) randomList\n\ntype GPConstraint a =\n  ( Field a\n  , Random a\n  , Unbox a\n  , Floating a\n  , Eq a\n  )\n{-\nhermToMatrixM\n  :: Herm a\n  -> DimMatrix D m n a\nhermToMatrixM = undefined\n-}\npinvSM\n  ::\n  ( KnownNat y\n  , KnownNat x\n  , Field a\n  , Numeric a\n  , y ~ x\n  )\n  => DimMatrix D y x a\n  -> DimMatrix D y x a\npinvSM (DimMatrix m) = DimMatrix . delay $ pinvS m\n\nmulPM\n  :: forall y1 x1 y2 x2 a.\n  ( AllConstrained KnownNat [x1, x2, y1, y2]\n  , Numeric a\n  , x1 ~ y2\n  )\n  => DimMatrix D y1 x1 a\n  -> DimMatrix D y2 x2 a\n  -> DimMatrix D y1 x2 a\nmulPM (DimMatrix m) (DimMatrix n) =\n  DimMatrix . delay . runIdentity $ m `mulP` n\n\neigSHM\n  :: (Field a, Numeric a)\n  => Herm a\n  -> (DimVector D m Double, DimMatrix D m m a)\neigSHM hermM =\n  (DimVector $ delay $ fst out, DimMatrix $ delay $ snd out)\n  where\n    out = eigSH hermM\n", "meta": {"hexsha": "839c4ff04792c9fb49a7c3726dfb731e96c40029", "size": 7737, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Matrix.hs", "max_stars_repo_name": "serokell/PCA", "max_stars_repo_head_hexsha": "2f71ebd4b3bb06308eaf761cc710df0955a5067c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math/Matrix.hs", "max_issues_repo_name": "serokell/PCA", "max_issues_repo_head_hexsha": "2f71ebd4b3bb06308eaf761cc710df0955a5067c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Matrix.hs", "max_forks_repo_name": "serokell/PCA", "max_forks_repo_head_hexsha": "2f71ebd4b3bb06308eaf761cc710df0955a5067c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2010443864, "max_line_length": 70, "alphanum_fraction": 0.595579682, "num_tokens": 2767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.42553346039501694}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RecordWildCards  #-}\n\nmodule AI.DemoLayer\n( LayerDefinition(..)\n, Layer(..)\n\n, Weights\n, Biases\n, LayerWidth\n, Connectivity\n\n--, createLayer\n) where\n\nimport AI.DemoNeuron\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data\nimport Data.Binary\nimport Data.Binary.Put\nimport qualified Data.ByteString.Lazy as B\nimport System.Random\n\ndata LayerDefinition a = LayerDefinition { neuronType   :: a\n                                         , width        :: LayerWidth\n                                         , connectivity :: Connectivity\n                                         }\n\ndata Layer a = Layer { neuron :: a\n                     , weights :: Weights\n                     , biases :: Biases\n                     } deriving (Show)\n\ntype Weights = Matrix Double\ntype Biases = Vector Double\ntype LayerWidth = Int\ntype Connectivity = LayerWidth -> LayerWidth -> Weights\n\ninstance (Neuron a) => Binary (Layer a) where\n  put Layer{..} = do put weights; put biases\n  get = do weights <- get; biases <- get; return Layer{..}\n\n-- createLayer :: (Neuron a, RandomGen g)\n--               => RandomTransform -> g -> LayerDefinition a\n--               -> LayerDefinition a -> Layer\n-- createLayer t g li lj = Layer (neuron lj) \n", "meta": {"hexsha": "2b2368bc0d8fcaa7c77040215408896e43901ebe", "size": 1277, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AI/DemoLayer.hs", "max_stars_repo_name": "jbarrow/LambdaNet", "max_stars_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 308, "max_stars_repo_stars_event_min_datetime": "2015-01-01T01:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:03:18.000Z", "max_issues_repo_path": "AI/DemoLayer.hs", "max_issues_repo_name": "jbarrow/LambdaNet", "max_issues_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2015-05-23T20:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-29T17:04:47.000Z", "max_forks_repo_path": "AI/DemoLayer.hs", "max_forks_repo_name": "jbarrow/LambdaNet", "max_forks_repo_head_hexsha": "fbdb2b9e75aaa88ea43d2f9e7b9f94ebc849301e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2015-01-01T07:14:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:33:41.000Z", "avg_line_length": 26.6041666667, "max_line_length": 71, "alphanum_fraction": 0.591229444, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.42510898899512245}}
{"text": "-- Lib.hs\n\nmodule Lib\n    ( symbol\n    , readExp\n    , spaces\n    ) where\n\nimport Text.ParserCombinators.Parsec hiding (spaces)\nimport Numeric (readHex, readOct, readFloat)\nimport Data.Char (digitToInt)\nimport qualified Data.Complex as C\nimport Data.Ratio ((%))\n\ndata LispVal = Atom String\n             | List [LispVal]\n             | DottedList [LispVal] LispVal\n             | Complex (C.Complex Double)\n             | Integer Integer\n             | Real Double\n             | Rational Rational\n             | String String\n             | Char Char\n             | Bool Bool\n\nreadExp :: String -> String\nreadExp input =\n  case parse parseExpr \"lisp\" input of\n    Left err -> \"No match: \" ++ show err\n    Right _  -> \"Found value\"\n\nparseExpr :: Parser LispVal\nparseExpr = parseAtom\n        <|> parseString\n        <|> parseNumber\n        <|> try parseChar\n        <|> parseQuoted\n        <|> do _ <- char '('\n               x <- try parseList <|> try parseDottedList\n               _ <- char ')'\n               return x\n        <|> parseQuasiQuoted\n        <|> parseUnquote\n\nparseAtom :: Parser LispVal\nparseAtom =\n  do first <- letter <|> symbol\n     rest <- many $ letter <|> digit <|> symbol\n     let atom = first:rest\n     return $ case atom of\n                \"#t\" -> Bool True\n                \"#f\" -> Bool False\n                _    -> Atom atom\n\nparseString :: Parser LispVal\nparseString =\n  do _ <- char '\"'\n     x <- many $ escapedChars <|> noneOf \"\\\"\"\n     _ <- char '\"'\n     return $ String x\n\nparseNumber :: Parser LispVal\nparseNumber = try parseComplex\n          <|> try parseReal\n          <|> try parseRational\n          <|> try parseInteger\n\nparseInteger :: Parser LispVal\nparseInteger = parseDec\n           <|> parseDec2\n           <|> parseOct\n           <|> parseHex\n           <|> parseBin\n\nparseOct :: Parser LispVal\nparseOct = try (string \"#o\") >> many1 octDigit >>= return . Integer . octToDig\n  where octToDig = fst . head . readOct\n\nparseDec :: Parser LispVal\nparseDec = Integer . read <$> many1 digit\n\nparseDec2 :: Parser LispVal\nparseDec2 = try (string \"#d\") >> Integer . read <$> many1 digit\n\nparseHex :: Parser LispVal\nparseHex = try (string \"#x\") >> many1 hexDigit >>= return . Integer . hexToDig\n  where hexToDig = fst . head . readHex\n\nparseBin :: Parser LispVal\nparseBin =\n  try (string \"#b\") >>\n  many1 (oneOf \"10\") >>=\n  return . Integer . binToDig\n-- x0 + 2 * (x1 + 2 * (x2 + 2 * (x3 + 2 * x4)))\n  where binToDig \"\" = 0\n        binToDig s = foldr f 0 ds\n          where ds      = (toInteger . digitToInt) <$> reverse s\n                f x acc = x + 2 * acc\n\nparseChar :: Parser LispVal\nparseChar = parseChar1 <|> parseChar2\n\nparseChar1 :: Parser LispVal\nparseChar1 =\n  do _ <- try (string \"#\\\\\")\n     x <- anyChar >>= \\c -> notFollowedBy alphaNum >> return c\n     return . Char $ x\n\nparseChar2 :: Parser LispVal\nparseChar2 =\n  try (string \"#\\\\\") >>\n  try (string \"newline\" <|> string \"space\") >>= \\x ->\n  return . Char $ case x of\n                    \"newline\" -> '\\n'\n                    \"space\"   -> ' '\n\nparseReal :: Parser LispVal\nparseReal =\n  do x <- many1 digit\n     _ <- char '.'\n     y <- many1 digit\n     return . Real . fst . head . readFloat $ x ++ ['.'] ++ y\n\nparseRational :: Parser LispVal\nparseRational =\n  do n <- many1 digit\n     _ <- char '/'\n     d <- many1 digit\n     return . Rational $ read d % read n\n\nparseComplex :: Parser LispVal\nparseComplex =\n  do r <- try $ parseReal <|> parseDec\n     _ <- char '+'\n     i <- try $ parseReal <|> parseDec\n     _ <- char 'i'\n     return . Complex $ (toDouble r) C.:+ (toDouble i)\n  where toDouble (Real f)    = realToFrac f\n        toDouble (Integer f) = fromIntegral f\n\nparseList :: Parser LispVal\nparseList = List <$> sepBy parseExpr spaces\n\nparseDottedList :: Parser LispVal\nparseDottedList =\n  do h <- endBy parseExpr spaces\n     t <- char '.' >> spaces >> parseExpr\n     return $ DottedList h t\n\nparseQuoted :: Parser LispVal\nparseQuoted =\n  do _ <- char '\\''\n     x <- parseExpr\n     return $ List [Atom \"quote\", x]\n\nparseQuasiQuoted :: Parser LispVal\nparseQuasiQuoted =\n  do _ <- char '`'\n     e <- parseExpr\n     return $ List [Atom \"quasiquote\", e]\n\nparseUnquote :: Parser LispVal\nparseUnquote =\n  do _ <- char ','\n     e <- parseExpr\n     return $ List [Atom \"unquote\", e]\n\nsymbol :: Parser Char\nsymbol = oneOf \"!#$%&|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\nescapedChars :: Parser Char\nescapedChars = char '\\\\' >>\n               oneOf \"\\\\\\\"\\n\\r\\t\" >>= \\x ->\n               return $ case x of\n                          '\\\\' -> x\n                          '\"'  -> x\n                          'n'  -> '\\n'\n                          'r'  -> '\\r'\n", "meta": {"hexsha": "d64e7c3bb9dcbb9bc11ca4b54270a9e325775804", "size": 4673, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "edgarlepe/scheme", "max_stars_repo_head_hexsha": "5cf1ac8ae007f6a007fd6668d20a068b540066f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "edgarlepe/scheme", "max_issues_repo_head_hexsha": "5cf1ac8ae007f6a007fd6668d20a068b540066f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lib.hs", "max_forks_repo_name": "edgarlepe/scheme", "max_forks_repo_head_hexsha": "5cf1ac8ae007f6a007fd6668d20a068b540066f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6758241758, "max_line_length": 78, "alphanum_fraction": 0.5523218489, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4250267293941805}}
{"text": "{-# LANGUAGE BangPatterns     #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict           #-}\nmodule STC.InitialDistribution where\n\nimport           Array.UnboxedArray       as AU\nimport           Data.Array.Repa          as R\nimport           Data.Complex\nimport           Data.List                as L\nimport           Data.Vector.Generic      as VG\nimport           Data.Vector.Storable     as VS\nimport           DFT.Plan\nimport           FourierPinwheel\nimport           Pinwheel.FourierSeries2D\nimport           STC.Convolution\nimport           STC.DFTArray\nimport           STC.Point\nimport           STC.Utils\nimport           Utils.Distribution\nimport           Utils.List\nimport           Utils.Parallel\nimport Filter.Utils\n\n{-# INLINE computeInitialDistribution #-}\ncomputeInitialDistribution ::\n     Int -> Int -> [Double] -> [Double] -> Double -> [Point] -> DFTArray\ncomputeInitialDistribution rows cols phiFreqs rhoFreqs halfLogPeriod points =\n  let (!minR, !maxR) = computeRange rows\n      (!minC, !maxC) = computeRange cols\n  in if L.any (\\(Point _ _ _ s) -> s <= 0) points\n       then error $ \"computeInitialDistribution: initial scale <= 0.\"\n       else DFTArray rows cols phiFreqs rhoFreqs .\n            parMap\n              rdeepseq\n              (\\(!rFreq, !thetaFreq) ->\n                 VG.convert .\n                 toUnboxedVector .\n                 AU.accum (+) 0 ((minC, minR), (maxC, maxR)) .\n                 L.map\n                   (\\(Point x y theta scale) ->\n                      ( (round x, round y)\n                      , cis $\n                        (log scale) * (-rFreq) - (thetaFreq * theta * pi / 180))) $\n                 points) $\n            (,) <$> rhoFreqs <*> phiFreqs\n\n\n{-# INLINE computeInitialDistribution' #-}\ncomputeInitialDistribution' ::\n     Int -> Int -> [Double] -> [Double] -> Double -> [Point] -> DFTArray\ncomputeInitialDistribution' rows cols phiFreqs rhoFreqs  halfLogPeriod points =\n  let (!minR, !maxR) = computeRange rows\n      (!minC, !maxC) = computeRange cols\n  in if L.any (\\(Point _ _ _ s) -> s <= 0) points\n       then error $ \"computeInitialDistribution: initial scale <= 0.\"\n       else DFTArray rows cols phiFreqs rhoFreqs .\n            parMap\n              rdeepseq\n              (\\(!thetaFreq) ->\n                 VG.convert .\n                 toUnboxedVector .\n                 AU.accum (+) 0 ((minC, minR), (maxC, maxR)) .\n                 L.map\n                   (\\(Point x y theta _) ->\n                      ((round x, round y), cis $ -(thetaFreq * theta * pi / 180))) $\n                 points) $\n            phiFreqs\n\n\n{-# INLINE computeInitialDistributionPowerMethod #-}\ncomputeInitialDistributionPowerMethod ::\n     Int -> Int -> [Double] -> [Double] -> Double -> [Point] -> DFTArray\ncomputeInitialDistributionPowerMethod rows cols thetaFreqs rFreqs halfLogPeriod points =\n  let (!minR, !maxR) = computeRange rows\n      (!minC, !maxC) = computeRange cols\n      !zeroVec = VG.replicate (rows * cols) 0\n  in if L.any (\\(Point _ _ _ s) -> s <= 0) points\n       then error $ \"computeInitialDistributionPowerMethod: initial scale <= 0.\"\n       else DFTArray rows cols thetaFreqs rFreqs .\n            L.map\n              (\\(!rFreq, !thetaFreq) ->\n                 if rFreq == 0 && thetaFreq == 0\n                   then VG.convert .\n                        toUnboxedVector .\n                        AU.accum (+) 0 ((minC, minR), (maxC, maxR)) .\n                        L.map (\\(Point x y theta scale) -> ((round x, round y), 1)) $\n                        points\n                   else zeroVec) $\n            (,) <$> rFreqs <*> thetaFreqs\n\n{-# INLINE computeInitialDistributionPowerMethod' #-}\ncomputeInitialDistributionPowerMethod' ::\n     Int -> Int -> [Double] -> [Double] -> [Point] -> DFTArray\ncomputeInitialDistributionPowerMethod' rows cols phiFreqs rhoFreqs points =\n  let (!minR, !maxR) = computeRange rows\n      (!minC, !maxC) = computeRange cols\n      !zeroVec = VG.replicate (rows * cols) 0\n  in if L.any (\\(Point _ _ _ s) -> s <= 0) points\n       then error $ \"computeInitialDistributionPowerMethod: initial scale <= 0.\"\n       else DFTArray rows cols phiFreqs rhoFreqs .\n            L.map\n              (\\(!thetaFreq) ->\n                 if thetaFreq == 0\n                   then VG.convert .\n                        toUnboxedVector .\n                        AU.accum (+) 0 ((minC, minR), (maxC, maxR)) .\n                        L.map (\\(Point x y theta scale) -> ((round x, round y), 1)) $\n                        points\n                   else zeroVec) $\n            phiFreqs\n\n\n{-# INLINE computeInitialDistributionPowerMethodSparse #-}\ncomputeInitialDistributionPowerMethodSparse ::\n     [Double] -> [Double] -> [Point] -> [R.Array U DIM2 (Complex Double)]\ncomputeInitialDistributionPowerMethodSparse thetaFreqs rFreqs points =\n  let !numThetaFreq = L.length thetaFreqs\n      !numRFreq = L.length rFreqs\n      !thetaCenter = div numThetaFreq 2\n      !rCenter = div numRFreq 2\n      !initArr =\n        computeUnboxedS . fromFunction (Z :. numRFreq :. numThetaFreq) $ \\(Z :. i :. j) ->\n          if i == rCenter && j == thetaCenter\n            then 1\n            else 0\n  in L.replicate (L.length points) initArr\n\n\n{-# INLINE computeInitialDistributionPowerMethodSparse' #-}\ncomputeInitialDistributionPowerMethodSparse' ::\n     [Double] -> [Double] -> [Point] -> [R.Array U DIM1 (Complex Double)]\ncomputeInitialDistributionPowerMethodSparse' thetaFreqs rFreqs points =\n  let !numThetaFreq = L.length thetaFreqs\n      !thetaCenter = div numThetaFreq 2\n      !initArr =\n        computeUnboxedS . fromFunction (Z :. numThetaFreq) $ \\(Z :. j) ->\n          if j == thetaCenter\n            then 1\n            else 0\n      -- !initArr =\n      --   computeUnboxedS .\n      --   R.traverse (fromListUnboxed (Z :. numThetaFreq) thetaFreqs) id $ \\f (Z :. thetaFreq) ->\n      --     cis $ -(fromIntegral thetaFreq * 36 * pi / 180)\n  in L.replicate (L.length points) initArr\n\n\ncomputeInitialDistributionFull' ::\n     Int -> Double -> Int -> Int -> [Point] -> DFTArray\ncomputeInitialDistributionFull' numR2Freq period phiFreq rhoFreq points =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n      phiFreqs = L.map fromIntegral [-phiFreq .. phiFreq]\n      rhoFreqs = L.map fromIntegral [-rhoFreq .. rhoFreq]\n  in DFTArray\n       numR2Freq\n       numR2Freq\n       phiFreqs\n       rhoFreqs\n       [ VG.fromList\n         [ L.foldl'\n           (\\b (Point x y theta _) ->\n              b +\n              cis\n                (-(angularFreq * theta * pi / 180 +\n                   (freqX * x + freqY * y) * 2 * pi / period)))\n           0\n           points\n         | freqY <- r2Freqs\n         , freqX <- r2Freqs\n         ]\n       | angularFreq <- phiFreqs\n       ]\n\ncomputeInitialDistributionPowerMethodPinwheelBasis' ::\n     Int -> Double -> Double -> Int -> Int -> [Point] -> DFTArray\ncomputeInitialDistributionPowerMethodPinwheelBasis' numR2Freq sigma period phiFreq rhoFreq points =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n      phiFreqs = L.map fromIntegral [-phiFreq .. phiFreq]\n      rhoFreqs = L.map fromIntegral [-rhoFreq .. rhoFreq]\n      zeroVec = VG.replicate (numR2Freq ^ 2) 0\n      envelope =\n        VG.convert .\n        toUnboxed . computeS . fromFunction (Z :. numR2Freq :. numR2Freq) $ \\(Z :. i :. j) ->\n          (exp $\n           (fromIntegral $ (i - div numR2Freq 2) ^ 2 + (j - div numR2Freq 2) ^ 2) *\n           (sigma ^ 2) /\n           (-2)) *\n          (sigma ^ 2) /\n          (2 * pi) :+\n          0\n  in DFTArray\n       numR2Freq\n       numR2Freq\n       phiFreqs\n       rhoFreqs\n       [ if angularFreq == 0\n         then VG.zipWith (*) envelope . VG.fromList $\n              [ L.foldl'\n                (\\b (Point x y _ _) ->\n                   b + cis (-(freqX * x + freqY * y) * 2 * pi / period))\n                0\n                points\n              | freqY <- r2Freqs\n              , freqX <- r2Freqs\n              ]\n         else zeroVec\n       | angularFreq <- phiFreqs\n       ]\n\ncomputeInitialDistributionPowerMethodPinwheelBasis ::\n     Int -> Double -> Double -> Int -> Int -> [Point] -> DFTArray\ncomputeInitialDistributionPowerMethodPinwheelBasis numR2Freq sigma period phiFreq rhoFreq points =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n      phiFreqs = L.map fromIntegral [-phiFreq .. phiFreq]\n      rhoFreqs = L.map fromIntegral [-rhoFreq .. rhoFreq]\n      zeroVec = VG.replicate (numR2Freq ^ 2) 0\n      envelope =\n        VG.convert .\n        toUnboxed . computeS . fromFunction (Z :. numR2Freq :. numR2Freq) $ \\(Z :. i :. j) ->\n          (exp $\n           (fromIntegral $ (i - div numR2Freq 2) ^ 2 + (j - div numR2Freq 2) ^ 2) *\n           (sigma ^ 2) /\n           (-2)) *\n          (sigma ^ 2) /\n          (2 * pi) :+\n          0\n      -- envelope =\n      --   VG.convert . toUnboxed . computeUnboxedS $\n      --   analyticalFourierCoefficients2 numR2Freq 1 0 0 sigma period (period * sqrt 2)\n  in DFTArray\n       numR2Freq\n       numR2Freq\n       phiFreqs\n       rhoFreqs\n       [ if angularFreq == 0 && radialFreq == 0\n         then VG.zipWith (*) envelope .\n              VG.fromList $\n              [ L.foldl'\n                (\\b (Point x y _ _) ->\n                   b + cis (-(freqX * x + freqY * y) * 2 * pi / period))\n                0\n                points\n              | freqY <- r2Freqs\n              , freqX <- r2Freqs\n              ]\n         else zeroVec\n       | radialFreq <- rhoFreqs\n       , angularFreq <- phiFreqs\n       ]\n\n\ncomputeInitialDistributionFourierPinwheel ::\n     (VG.Vector vector (Complex Double), NFData (vector (Complex Double)))\n  => Int\n  -> Double\n  -> Double\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> [Point]\n  -> FPArray (vector (Complex Double))\ncomputeInitialDistributionFourierPinwheel numR2Freqs period periodEnv phiFreq rhoFreq thetaFreq rFreq points =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freqs\n      thetaFreqs = L.map fromIntegral [-thetaFreq .. thetaFreq]\n      rFreqs = L.map fromIntegral [-rFreq .. rFreq]\n   in FPArray\n        numR2Freqs\n        numR2Freqs\n        (2 * rFreq + 1)\n        (2 * thetaFreq + 1)\n        (2 * rhoFreq + 1)\n        (2 * phiFreq + 1) .\n      L.map\n        (\\radialFreq ->\n           VG.concat .\n           parMap\n             rdeepseq\n             (\\angularFreq ->\n                VG.convert . toUnboxed . computeS . makeFilter2D . fromListUnboxed (Z :. numR2Freqs :. numR2Freqs) $\n                   [ L.foldl'\n                     (\\b (Point x y theta scale) ->\n                        b +\n                        cis\n                          (-(angularFreq * theta * pi / 180 +\n                             (freqX * x + freqY * y) * 2 * pi / period +\n                             2 * pi / log periodEnv * log scale * radialFreq)))\n                     0\n                     points\n                   | freqY <- r2Freqs\n                   , freqX <- r2Freqs\n                   ]) $\n           thetaFreqs) $\n      rFreqs\n\n\ncomputeInitialDistributionPowerMethodFourierPinwheel ::\n     Int\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> VS.Vector (Complex Double)\n  -> FPArray (VS.Vector (Complex Double))\ncomputeInitialDistributionPowerMethodFourierPinwheel numR2Freqs phiFreq rhoFreq thetaFreq rFreq bias =\n  let thetaFreqs = L.map fromIntegral [-thetaFreq .. thetaFreq]\n      rFreqs = L.map fromIntegral [-rFreq .. rFreq]\n      numThetaFreq = 2 * thetaFreq + 1\n      zeroVec = VG.replicate (numThetaFreq * numR2Freqs ^ 2) 0\n   in FPArray\n        numR2Freqs\n        numR2Freqs\n        (2 * rFreq + 1)\n        numThetaFreq\n        (2 * rhoFreq + 1)\n        (2 * phiFreq + 1) .\n      L.map\n        (\\radialFreq ->\n           if radialFreq == 0\n             then bias\n             else zeroVec) $\n      rFreqs\n      \n\ncomputeInitialDistributionPowerMethodFourierPinwheelFull ::\n     Int\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> VS.Vector (Complex Double)\n  -> FPArray (VS.Vector (Complex Double))\ncomputeInitialDistributionPowerMethodFourierPinwheelFull numR2Freqs phiFreq rhoFreq thetaFreq rFreq bias =\n  let numThetaFreq = 2 * thetaFreq + 1\n      numRFreq = 2 * rFreq + 1\n   in FPArray\n        numR2Freqs\n        numR2Freqs\n        (2 * rFreq + 1)\n        numThetaFreq\n        (2 * rhoFreq + 1)\n        (2 * phiFreq + 1) .\n      parMap\n        rdeepseq\n        (\\radialFreq ->\n           VG.convert .\n           toUnboxed .\n           computeS .\n           R.slice\n             (fromUnboxed\n                (Z :. numRFreq :. numThetaFreq :. numR2Freqs :. numR2Freqs) .\n              VG.convert $\n              bias) $\n           (Z :. radialFreq :. All :. All :. All)) $\n      [0 .. 2 * rFreq]\n", "meta": {"hexsha": "eab2e5912633271de37a1eb6582f96afdfc6841a", "size": 12691, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/InitialDistribution.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/InitialDistribution.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/InitialDistribution.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 35.7492957746, "max_line_length": 116, "alphanum_fraction": 0.5403041525, "num_tokens": 3411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4249794896365475}}
{"text": "{-# LANGUAGE LambdaCase, DoAndIfThenElse, GeneralizedNewtypeDeriving #-} \nmodule Truthiness where\n\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as ByteString\n\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Monoid (Any(..), All(..))\nimport System.Exit (ExitCode(..)) \nimport Numeric.Natural (Natural)\nimport Data.Complex (Complex(..))\nimport Data.Ratio (Ratio)\nimport Control.Applicative (Alternative(..), Alternative(..))\nimport Control.Monad (MonadPlus(..))\nimport Data.Foldable (Foldable(..))\n\n\n{-| Pythonic truthiness/falsines. see <https://docs.python.org/2.4/lib/truth.html>.\n\nkeep around information (e.g. use @Maybe@, a custom flag type, etc.)\nto avoid <https://existentialtype.wordpress.com/2011/03/15/boolean-blindness/ Boolean Blindness>, \nthen drop that information with 'Boolean', when necessary for convenience.  \n\n\ne.g. 'when'\n\n\nwhen 'Foldable', instances should satisfy the following law: \n\n@\n'falsy' = 'null' . 'toList'\n@\n\n\nwhen a 'Monoid', instances should satisfy the following law: \n\n@\n'falsy' = ('mempty' ==) \n@\n\n\nwhen a 'Num', instances should satisfy the following law: \n\n@\n'falsy' = (0 ==) \n@\n\n\nnon-instances: \n\n* @()@ \n* @Dual@ \n\n\n-}\nclass Boolean a where\n\n falsy :: a -> Bool\n\n truthy :: a -> Bool\n truthy = not . falsy \n\n\n-- booleans \ninstance Boolean Bool         where falsy = (== False)      \ninstance Boolean Any          where falsy = falsy . getAny  \ninstance Boolean All          where falsy = falsy . getAll  \n\n-- errors   \ninstance Boolean (Maybe a)    where falsy = (\\case Nothing -> True; _ -> False) -- not (== Nothing) \ninstance Boolean (Either e a) where falsy = (\\case Left{} -> True; _ -> False)        \n-- | (includes 'String's)\ninstance Boolean [a]          where falsy = (\\case [] -> True; _ -> False) -- not (== [])  \n\n-- numbers \ninstance Boolean Int          where falsy = (== 0)  \ninstance Boolean Word         where falsy = (== 0)  \ninstance Boolean Integer      where falsy = (== 0)  \ninstance Boolean Natural      where falsy = (== 0)  \ninstance (Integral a) => Boolean (Ratio a)    where falsy = (== 0)  \ninstance (RealFloat a) => Boolean (Complex a)  where falsy = (== 0)  \n\n-- containers \ninstance Boolean (Set a)      where falsy = Set.null  \ninstance Boolean (Map k v)    where falsy = Map.null  \n\n-- strings \ninstance Boolean Char         where falsy = (== '\\NUL')       \ninstance Boolean Text         where falsy = Text.null         \ninstance Boolean ByteString   where falsy = ByteString.null   \n\n-- et cetera \ninstance Boolean ExitCode      where falsy = (\\case ExitFailure{} -> True; _ -> False)  \n\n\ninstance (Foldable t)       => Boolean (WrappedFoldable t a) where falsy = null . toList  \ninstance (Monoid a, Eq a)   => Boolean (WrappedMonoid a)     where falsy = (mempty ==)    \ninstance (Num a,    Eq a)   => Boolean (WrappedNum a)        where falsy = (0 ==)         \n\nnewtype WrappedFoldable t a = WrappedFoldable { getWrappedFoldable :: t a } deriving (Foldable)\nnewtype WrappedMonoid   a   = WrappedMonoid   { getWrappedMonoid   :: a } deriving (Monoid,Eq)\nnewtype WrappedNum      a   = WrappedNum      { getWrappedNum      :: a } deriving (Num,Eq)\n\n\n\n-- control \n\nwhenB :: (Applicative m, Boolean b) => b -> m () -> m () \nwhenB condition action = ifB condition action nothing\n{-# INLINEABLE whenB #-}\n\nwhenM :: (Monad m, Boolean b) => m b -> m () -> m () \nwhenM condition action = ifM condition action nothing \n{-# INLINEABLE whenM #-}\n\nguardB :: (Alternative m, Boolean b) => b -> m ()\nguardB condition = unlessB condition empty \n{-# INLINEABLE guardB #-}\n\nguardM :: (MonadPlus m, Boolean b) => m b -> m ()\nguardM condition = unlessM condition mzero\n{-# INLINEABLE guardM #-}\n\nunlessB :: (Applicative m, Boolean b) => b -> m () -> m () \nunlessB condition action = ifB condition nothing action \n{-# INLINEABLE unlessB #-}\n\nunlessM :: (Monad m, Boolean b) => m b -> m () -> m () \nunlessM condition action = ifM condition nothing action \n{-# INLINEABLE unlessM #-}\n\nboolB :: (Boolean b) => a -> a -> b -> a \nboolB x y c = ifB c x y \n{-# INLINEABLE boolB #-}\n\nifB :: (Boolean b) => b -> a -> a -> a \nifB c x y = \n if   truthy c \n then x \n else y \n{-# INLINEABLE ifB #-}\n\nifM :: (Monad m, Boolean b) => m b -> m a -> m a -> m a \nifM condition a b = (\\c -> ifB c a b) =<< condition \n{-# INLINEABLE ifM #-}\n\nnothing :: (Applicative m) => m () \nnothing = pure()\n\n\n{-$ alternatives\n \ntoo explicit: <https://hackage.haskell.org/package/base-4.8.2.0/docs/Control-Monad.html>\n\nfewer instances: <https://hackage.haskell.org/package/cond> \n\n-}\n", "meta": {"hexsha": "25d4bb022bcc005728952ce17c396e05a2b7e204", "size": 4660, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "library/Truthiness.hs", "max_stars_repo_name": "sboosali/truthiness", "max_stars_repo_head_hexsha": "55d85687784d4764d5a020b4fd1eada82354cf0d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-25T08:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T08:14:10.000Z", "max_issues_repo_path": "library/Truthiness.hs", "max_issues_repo_name": "sboosali/truthiness", "max_issues_repo_head_hexsha": "55d85687784d4764d5a020b4fd1eada82354cf0d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "library/Truthiness.hs", "max_forks_repo_name": "sboosali/truthiness", "max_forks_repo_head_hexsha": "55d85687784d4764d5a020b4fd1eada82354cf0d", "max_forks_repo_licenses": ["BSD-3-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.5889570552, "max_line_length": 100, "alphanum_fraction": 0.641416309, "num_tokens": 1269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4249666180119423}}
{"text": "import ImageLoader\nimport Brain\n\n--------------------------------------------------------------------------------\n\nimport Control.Exception (SomeException (..))\nimport System.Random     (mkStdGen, randomR)\nimport Numeric.LinearAlgebra\nimport Data.List\nimport qualified Numeric.LinearAlgebra.Data as V\nimport Debug.Trace\n\n\n--------------------------------------------------------------------------------\n\ntype Samples = [(V.Vector Double, V.Vector Double)]\n\n\nmain :: IO ()\nmain = loadFiles\n\n\nloadFiles :: IO ()\nloadFiles = do\n    ex    <- loadExamples\n    notEx <- loadNonExamples\n    case (ex, notEx)\n      of (Left (SomeException e), _) -> printError e\n         (_, Left (SomeException e)) -> printError e\n         (Right v1, Right v2)        -> runTraining v1 v2\n  where\n    printError e = putStrLn $ \"Exception: \" ++ (show e)\n\n\nrunTraining :: Samples -> Samples -> IO ()\nrunTraining s1 s2 = do\n    net <- constructNeuralNetwork 256 [512, 256, 128, 64] 1 all_\n    putStrLn \"----\"\n    printSamples all_ net\n    putStrLn \"----\"\n    let net' = trainN net 800\n    printSamples all_ net'\n  where all_   = s1 ++ s2\n\n\nprintSamples :: Samples -> NetworkWithSamples -> IO ()\nprintSamples [] _       = return ()\nprintSamples (x:xs) net = do\n    putStrLn $ vid ++ \" --> \" ++ output ++ \" ? \" ++ expectedOut\n    printSamples xs net\n  where in_    = fst x\n        expectedOut = show $ snd x\n        vid    = show $ (vecId in_)\n        output = show $ (activate net in_)\n\n\n-- Given a list of examples, separates into a list of\n-- test data (fst) and training data (snd)\nsepExTest :: [a] -> ([a], [a])\nsepExTest xs = go xs ([], []) (mkStdGen 10)\n  where\n        go [] a _            = a\n        go (v:vs) (a, b) gen = case randomR (0, 99) gen\n                               of (n, gen') -> if n < (20 :: Int)\n                                                  then go vs (v:a, b) gen'\n                                                  else go vs (a, v:b) gen'\n\nvecId :: V.Vector Double -> Double\nvecId v = v <.> V.fromList (replicate 256 (1 :: Double))\n", "meta": {"hexsha": "46e063765570bde5ee19e08dd0fe30c24206a280", "size": 2038, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "robmcl4/A-Neural", "max_stars_repo_head_hexsha": "7eb283de2d5602787c7919e15da4f0d77af08844", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-05-13T06:21:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-06T05:07:55.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "robmcl4/A-Neural", "max_issues_repo_head_hexsha": "7eb283de2d5602787c7919e15da4f0d77af08844", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Main.hs", "max_forks_repo_name": "robmcl4/A-Neural", "max_forks_repo_head_hexsha": "7eb283de2d5602787c7919e15da4f0d77af08844", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:56:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T14:56:23.000Z", "avg_line_length": 29.1142857143, "max_line_length": 80, "alphanum_fraction": 0.518155054, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.42439546578349147}}
{"text": "{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE RecordWildCards       #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-|\nModule      : Grenade.Layers.Convolution\nDescription : Convolution layer\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n\nThis module provides the Convolution layer, which is critical in many computer vision tasks.\n\n-}\nmodule Grenade.Layers.Convolution (\n    Convolution (..)\n  , Convolution' (..)\n  , randomConvolution\n  ) where\n\nimport           Control.Monad.Random hiding ( fromList )\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Serialize\nimport           Data.Singletons.TypeLits\n\n#if MIN_VERSION_base(4,11,0)\nimport           GHC.TypeLits hiding (natVal)\n#else\nimport           GHC.TypeLits\n#endif\n#if MIN_VERSION_base(4,9,0)\nimport           Data.Kind (Type)\n#endif\n\nimport           Numeric.LinearAlgebra hiding ( uniformSample, konst )\nimport qualified Numeric.LinearAlgebra as LA\nimport           Numeric.LinearAlgebra.Static hiding ((|||), build, toRows)\n\nimport           Grenade.Core\nimport           Grenade.Layers.Internal.Convolution\nimport           Grenade.Layers.Internal.Update\n\n-- | A convolution layer for a neural network.\n--   This uses the im2col convolution trick popularised by Caffe, which essentially turns the\n--   many, many, many, many loop convolution into a single matrix multiplication.\n--\n--   The convolution layer takes all of the kernels for the convolution, which are flattened\n--   and then put into columns in the matrix.\n--\n--   The kernel size dictates which input and output sizes will \"fit\". Fitting the equation:\n--   `out = (in - kernel) / stride + 1` for both dimensions.\n--\n--   One probably shouldn't build their own layer, but rather use the randomConvolution function.\ndata Convolution :: Nat -- Number of channels, for the first layer this could be RGB for instance.\n                 -> Nat -- Number of filters, this is the number of channels output by the layer.\n                 -> Nat -- The number of rows in the kernel filter\n                 -> Nat -- The number of column in the kernel filter\n                 -> Nat -- The row stride of the convolution filter\n                 -> Nat -- The columns stride of the convolution filter\n                 -> Type where\n  Convolution :: ( KnownNat channels\n                 , KnownNat filters\n                 , KnownNat kernelRows\n                 , KnownNat kernelColumns\n                 , KnownNat strideRows\n                 , KnownNat strideColumns\n                 , KnownNat kernelFlattened\n                 , kernelFlattened ~ (kernelRows * kernelColumns * channels))\n              => !(L kernelFlattened filters) -- The kernel filter weights\n              -> !(L kernelFlattened filters) -- The last kernel update (or momentum)\n              -> Convolution channels filters kernelRows kernelColumns strideRows strideColumns\n\ndata Convolution' :: Nat -- Number of channels, for the first layer this could be RGB for instance.\n                  -> Nat -- Number of filters, this is the number of channels output by the layer.\n                  -> Nat -- The number of rows in the kernel filter\n                  -> Nat -- The number of column in the kernel filter\n                  -> Nat -- The row stride of the convolution filter\n                  -> Nat -- The columns stride of the convolution filter\n                  -> Type where\n  Convolution' :: ( KnownNat channels\n                  , KnownNat filters\n                  , KnownNat kernelRows\n                  , KnownNat kernelColumns\n                  , KnownNat strideRows\n                  , KnownNat strideColumns\n                  , KnownNat kernelFlattened\n                  , kernelFlattened ~ (kernelRows * kernelColumns * channels))\n               => !(L kernelFlattened filters) -- The kernel filter gradient\n               -> Convolution' channels filters kernelRows kernelColumns strideRows strideColumns\n\ninstance Show (Convolution c f k k' s s') where\n  show (Convolution a _) = renderConv a\n    where\n      renderConv mm =\n        let m  = extract mm\n            ky = fromIntegral $ natVal (Proxy :: Proxy k)\n            rs = LA.toColumns m\n            ms = map (take ky) $ toLists . reshape ky <$> rs\n\n            render n'  | n' <= 0.2  = ' '\n                       | n' <= 0.4  = '.'\n                       | n' <= 0.6  = '-'\n                       | n' <= 0.8  = '='\n                       | otherwise =  '#'\n\n            px = (fmap . fmap . fmap) render ms\n        in unlines $ foldl1 (zipWith (\\a' b' -> a' ++ \"   |   \" ++ b')) $ px\n\nrandomConvolution :: ( MonadRandom m\n                     , KnownNat channels\n                     , KnownNat filters\n                     , KnownNat kernelRows\n                     , KnownNat kernelColumns\n                     , KnownNat strideRows\n                     , KnownNat strideColumns\n                     , KnownNat kernelFlattened\n                     , kernelFlattened ~ (kernelRows * kernelColumns * channels))\n                  => m (Convolution channels filters kernelRows kernelColumns strideRows strideColumns)\nrandomConvolution = do\n    s     <- getRandom\n    let wN = uniformSample s (-1) 1\n        mm = konst 0\n    return $ Convolution wN mm\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         ) => UpdateLayer (Convolution channels filters kernelRows kernelColumns strideRows strideColumns) where\n  type Gradient (Convolution channels filters kernelRows kernelColumns strideRows strideColumns) = (Convolution' channels filters kernelRows kernelColumns strideRows strideColumns)\n  runUpdate LearningParameters {..} (Convolution oldKernel oldMomentum) (Convolution' kernelGradient) =\n    let (newKernel, newMomentum) = descendMatrix learningRate learningMomentum learningRegulariser oldKernel kernelGradient oldMomentum\n    in Convolution newKernel newMomentum\n\n  createRandom = randomConvolution\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * channels)\n         ) => Serialize (Convolution channels filters kernelRows kernelColumns strideRows strideColumns) where\n  put (Convolution w _) = putListOf put . toList . flatten . extract $ w\n  get = do\n      let f  = fromIntegral $ natVal (Proxy :: Proxy filters)\n      wN    <- maybe (fail \"Vector of incorrect size\") return . create . reshape f . LA.fromList =<< getListOf get\n      let mm = konst 0\n      return $ Convolution wN mm\n\n-- | A three dimensional image (or 2d with many channels) can have\n--   an appropriately sized convolution filter run across it.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , KnownNat channels\n         , ((outputRows - 1) * strideRows) ~ (inputRows - kernelRows)\n         , ((outputCols - 1) * strideCols) ~ (inputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * channels)\n         , KnownNat (outputRows * filters)\n         ) => Layer (Convolution channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) where\n\n  type Tape (Convolution channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (Convolution kernel _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n\n        c  = vid2col kx ky sx sy ix iy ex\n        mt = c LA.<> ek\n        r  = col2vid 1 1 1 1 ox oy mt\n        rs = fromJust . create $ r\n    in  (S3D input, S3D rs)\n  runBackwards (Convolution kernel _) (S3D input) (S3D dEdy) =\n    let ex = extract input\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n\n        c  = vid2col kx ky sx sy ix iy ex\n\n        eo = extract dEdy\n        ek = extract kernel\n\n        vs = vid2col 1 1 1 1 ox oy eo\n\n        kN = fromJust . create $ tr c LA.<> vs\n\n        dW = vs LA.<> tr ek\n\n        xW = col2vid kx ky sx sy ix iy dW\n    in  (Convolution' kN, S3D . fromJust . create $ xW)\n\n\n-- | A two dimentional image may have a convolution filter applied to it\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , ((outputRows - 1) * strideRows) ~ (inputRows - kernelRows)\n         , ((outputCols - 1) * strideCols) ~ (inputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * 1)\n         , KnownNat (outputRows * filters)\n         ) => Layer (Convolution 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) where\n  type Tape (Convolution 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\n\n-- | A two dimensional image may have a convolution filter applied to it producing\n--   a two dimensional image if both channels and filters is 1.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , ((outputRows - 1) * strideRows) ~ (inputRows - kernelRows)\n         , ((outputCols - 1) * strideCols) ~ (inputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * 1)\n         , KnownNat (outputRows * 1)\n         ) => Layer (Convolution 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) where\n  type Tape (Convolution 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D back :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) -> (c', S2D back)\n\n-- | A three dimensional image can produce a 2D image from a convolution with 1 filter\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , KnownNat channels\n         , ((outputRows - 1) * strideRows) ~ (inputRows - kernelRows)\n         , ((outputCols - 1) * strideCols) ~ (inputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * channels)\n         , KnownNat (outputRows * 1)\n         ) => Layer (Convolution channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) where\n  type Tape (Convolution channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D back :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D back)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1))\n", "meta": {"hexsha": "11dc9c130562f640c3eef9137703588a94a70567", "size": 13477, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Convolution.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-21T04:14:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-21T04:14:09.000Z", "max_issues_repo_path": "src/Grenade/Layers/Convolution.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Convolution.hs", "max_forks_repo_name": "Alien-Inc/grenade", "max_forks_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5304054054, "max_line_length": 196, "alphanum_fraction": 0.6310751651, "num_tokens": 3271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8757869819218866, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.4242137721120092}}
{"text": "{-# LANGUAGE RankNTypes #-}\nmodule Patterns where\n\nimport Prelude hiding (map, zip, iterate)\nimport qualified Prelude (map, zip, iterate)\n\nimport Numeric.SpecFunctions (log2)\nimport Data.Array\n\ntype Vec = Array Int\n\n-- high-level patterns\nmap :: forall a b. (a -> b) -> [a] -> [b]\nmap = Prelude.map\n\nreduce :: forall a. (a -> a -> a) -> a -> [a] -> [a]\nreduce f z xs = [Prelude.foldl f z xs]\n\nzip :: forall a b. [a] -> [b] -> [(a,b)]\nzip = Prelude.zip\n\nsplit :: forall a. Int -> [a] -> [[a]]\nsplit n xs | len `mod` n == 0   = builder (len `div` n) xs\n           | otherwise          = error \"Length not divisible by n\"\n    where len = length xs\n          builder 1 xs = [take n xs]\n          builder i xs = take n xs : builder (i-1) (drop n xs)\n\njoin :: forall a. [[a]] -> [a]\njoin = foldl (++) []\n\niterate :: forall a. Int -> (a -> a) -> a -> a\niterate 0 f xs = xs\niterate n f xs = iterate (n-1) f (f xs)\n\nreorder :: forall a. [a] -> [a]\nreorder = id\n\n-- low-level patterns\nmapWorkgroup    = map\nmapLocal        = map\nmapGlobal       = map\nmapWarp         = map\nmapLane         = map\nmapSeq          = map\n\nreduceSeq :: forall a b. (a -> b -> a) -> a -> [b] -> [a]\nreduceSeq f z xs = [Prelude.foldl f z xs]\n\nreorderStride :: forall a. Int -> [a] -> [a]\nreorderStride s = id\n\ntoLocal :: forall a b. (a -> b) -> (a -> b)\ntoLocal = id\n\ntoGlobal :: forall a b. (a -> b) -> (a -> b)\ntoGlobal = id\n\nasVector :: forall a. Int -> [a] -> [Vec a]\nasVector n xs | len `mod` n == 0    = builder (len `div` n) xs\n              | otherwise           = error \"Length not divisible by n\"\n    where len = length xs\n          builder 1 xs = [newVector (take n xs)]\n          builder i xs = newVector (take n xs) : builder (i-1) (drop n xs)\n          newVector xs = array (1, n) (zip [1..n] xs)\n\nasScalar :: forall a. [Vec a] -> [a]\nasScalar = join . map elems\n\nvectorize :: forall a b. Int -> (a -> b) -> (Vec a -> Vec b)\nvectorize n f = \\ a -> array (bounds a) $ map (\\ (i, e) -> (i, f e)) $ assocs a\n\n-- utilities\nonPairs :: forall a b c. (a -> b -> c) -> ((a, b) -> c)\nonPairs f = \\ (a, b) -> f a b\n\n\n-- benchmarks\nscal :: forall a. Num a => a -> [a] -> [a]\nscal a = map ((*) a)\n\nasum :: forall a. (Ord a, Num a) => [a] -> [a]\nasum xs = reduce (+) 0 (map abs xs)\n\ndot :: forall a. Num a => [a] -> [a] -> [a]\ndot xs ys = reduce (+) 0 (map (onPairs (*)) (zip xs ys))\n\ngemv :: forall a. Num a => [[a]] -> [a] -> [a] -> a -> a -> [a]\ngemv mss xs ys a b = map (onPairs (+)) (zip zs (scal b ys))\n    where zs = map (head . scal a . dot xs) mss\n\n\n-- vector scale\nmult3 :: forall a. Num a => a -> a\nmult3 x = x * 3\n\nvectorScale1 :: forall a. Num a => [a] -> [a]\nvectorScale1 = map mult3\n\nvectorScale2 :: forall a. Num a => [a] -> [a]\nvectorScale2 xs = join . map (map mult3) . split (s `div` 2) $ xs\n    where s = length xs\n\nvectorScale3 :: forall a. Num a => [a] -> [a]\nvectorScale3 xs = join . map (\n        asScalar . map (vectorize 4 mult3) . asVector 4\n    ) . split (s `div` 2) $ xs\n    where s = length xs\n\nvectorScale4 :: forall a. Num a => [a] -> [a]\nvectorScale4 xs = join . mapWorkgroup (\n        asScalar . mapLocal (vectorize 4 mult3) . asVector 4\n    ) . split (s `div` 2) $ xs\n    where s = length xs\n\n\n\n\n-- reduction\nvecSum0 = reduce (+) 0\n\nvecSum1 xs = vecSum0 . join . mapWorkgroup (\n        join . toGlobal (mapLocal (mapSeq id)) . split 1 .\n        iterate (log2 wgSize) (\n            join . mapLocal (reduceSeq (+) 0) . split 2\n        ) .\n        join . toLocal (mapLocal (mapSeq id)) . split 1\n    ) . split wgSize $ xs\n    where wgSize = 128\n\nvecSum2 xs = vecSum0 . join . mapWorkgroup (\n        join . toGlobal (mapLocal (mapSeq id)) . split 1 .\n        iterate (log2 wgSize) (\n            join . mapLocal (reduceSeq (+) 0) . split 2\n        ) .\n        join . toLocal (mapLocal (reduceSeq (+) 0)) . split 2\n    ) . split (2 * wgSize) $ xs\n    where wgSize = 128\n\nvecSum3 xs = vecSum0 . join . mapWorkgroup (\n        join . toGlobal (mapLocal (mapSeq id)) . split 1 .\n        join . mapWarp (\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2\n        ) . split 64 .\n        iterate (log2 wgSize - log2 64) (\n            join . mapLocal (reduceSeq (+) 0) . split 2\n        ) .\n        join . toLocal (mapLocal (reduceSeq (+) 0)) . split 2\n    ) . split (2 * wgSize) $ xs\n    where wgSize = 128\n\nvecSum4 xs = vecSum0 . join . mapWorkgroup (\n        join . toGlobal (mapLocal (mapSeq id)) . split 1 .\n        join . mapWarp (\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2\n        ) . split 64 .\n        join . mapLocal (reduceSeq (+) 0) . split 2 .\n        join . toLocal (mapLocal (reduceSeq (+) 0)) . split 2\n    ) . split (2 * wgSize) $ xs\n    where wgSize = 128\n\nvecSum5 xs = vecSum0 . join . mapWorkgroup (\n        join . toGlobal (mapLocal (mapSeq id)) . split 1 .\n        join . mapWarp (\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2 .\n            join . mapLane (reduceSeq (+) 0) . split 2\n        ) . split 64 .\n        join . mapLocal (reduceSeq (+) 0) . split 2 .\n        join . toLocal (mapLocal (reduceSeq (+) 0)) . \n            split (blockSize `div` wgSize)\n    ) . split blockSize $ xs\n    where wgSize = 128\n          blockSize = 262144\n\n", "meta": {"hexsha": "8dbdb11c1c411ea6de4230cd8530c057f76113bc", "size": 5977, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Patterns.hs", "max_stars_repo_name": "michel-steuwer/haskell-patterns", "max_stars_repo_head_hexsha": "329ab122eed2530ce610a4aa017002e4de9b3ebb", "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/Patterns.hs", "max_issues_repo_name": "michel-steuwer/haskell-patterns", "max_issues_repo_head_hexsha": "329ab122eed2530ce610a4aa017002e4de9b3ebb", "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/Patterns.hs", "max_forks_repo_name": "michel-steuwer/haskell-patterns", "max_forks_repo_head_hexsha": "329ab122eed2530ce610a4aa017002e4de9b3ebb", "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.6243386243, "max_line_length": 79, "alphanum_fraction": 0.5290279404, "num_tokens": 1989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4241690754169794}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE ParallelListComp #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# OPTIONS_GHC -fno-warn-name-shadowing #-}\n{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}\nmodule Language.Grappa.Inference.OldVariationalInference where\n\nimport Control.Monad ( forM, replicateM )\nimport Data.List ( transpose )\n\nimport Control.Lens ( (.~) )\nimport qualified Data.Colour as G\nimport qualified Data.Colour.Names as G\nimport qualified Data.Default.Class as G\nimport qualified Data.Matrix as Dm\nimport qualified Graphics.Rendering.Chart as G\nimport qualified Graphics.Rendering.Chart.Backend.Diagrams as G\nimport qualified Numeric.AD as Ad\nimport qualified Numeric.LinearAlgebra as La\nimport Numeric.LinearAlgebra ( Matrix, Vector, (<>), (<.>), (#>) )\nimport qualified Statistics.Distribution as S\nimport qualified Statistics.Distribution.StudentT as S\nimport qualified System.Random.MWC as MWC\nimport qualified Test.QuickCheck as Qc\nimport qualified Test.QuickCheck.Monadic as Qc\nimport qualified Test.QuickCheck.Property as Qc\n\nimport Language.Grappa.Distribution\nimport Language.Grappa.Inference.GradientDescent\nimport Language.Grappa.Rand.MWCRandM\n\nimport Debug.Trace\n\n----------------------------------------------------------------\n-- * BBVI algorithms\n----------------------------------------------------------------\n--\n-- $bbviAlgorithms\n-- Here is a summary of ways @conathan@ thought of to improve\n-- BBVI. Only the first, simplest observation has been implemented, by\n-- 'iteratedBbvi'.\n--\n-- When running BBVI to learn goal values @lambda@ that\n-- are very far from the randomly chosen start values for\n-- @lambda@, simply rerunning BBVI, starting from the previous\n-- @lambda@, works well. For example, in\n--\n-- > runBbviTestUsingLazyRand 1\n-- >   2      {- singleFactorBbvi2 -}\n-- >   3      {- bbviTest3 -}\n-- >   0.01   {- epsilon -}\n-- >   100    {- num trials -}\n-- >   [ 1000 {- mu -}\n-- >   , 10 ] {- sigma -}\n--\n-- when lambda is initialized via\n--\n-- > replicateM 2 $ distSample (Normal 0 10)\n--\n-- the guesses are likely to be close to zero and far from 1000,\n-- the goal value for @mu@.\n--\n-- The goal is to learn @lambda = [1000,10]@, and starting with\n-- random lambda near zero, and then redefining @sampleLambda@ to\n-- return the result, and iterating, we get the following sequence\n-- of discovered lambda values:\n--\n-- @\n-- sampleLambda = return $\n--   -- [266.51484560478195,7.379162331856864]\n--   -- [484.67445818993525,7.68279736309357]\n--   -- [695.344938596016,8.239851183556492]\n--   -- [874.483037696744,9.262297809983037]\n--   -- [976.4159168688128,9.889695342218715]\n--   -- [999.2564614475032,10.024071543947]\n--   -- [999.9992140408281,9.999553691817553]\n--   [999.99991729097,10.000438169812853]\n-- @\n--\n-- As the result gets closer to the correct answer @[1000,10]@,\n-- the incremental BBVI calls converge much more quickly. So, the\n-- above corresponds to 8 runs of BBVI, but only take 3 or 4 times\n-- as long as the first run.\n--\n-- With this improvement via iteration in mind, an obvious idea is\n-- to simply implement a meta algorithm that does this iteration\n-- for us: run BBVI in a loop, reusing the last @lambda@ to seed\n-- the current run, until the @lambda@ computed by this meta\n-- algorithm stabilizes (or some number of iterations are reached,\n-- since for some functions, e.g. @sin@-like functions, we would\n-- never converge).\n--\n-- And why does this meta algorithm work? Because when we restart\n-- BBVI the learning rate / step size is large again, so we can\n-- make lots of early progress before the decreasing learning rate\n-- artificially slows us down.\n--\n-- This observation motivates a more general approach/goal: how\n-- can we adjust the learning rate in a more intelligent way, so\n-- that we don't slow down too early, but do slow down when we\n-- reach a local optimum? (\"Get while the gettin' is good\" and\n-- then stop.)\n--\n-- First, some ideas for detecting that we're not making progress\n-- anymore:\n--\n-- 1. the difference between two consecutive values of lambda is\n--    small. This is the approach the BBVI paper suggests. As\n--    we've seen, it's misleading in conjunction with the\n--    decreasing learning rates suggested by the paper.\n--\n-- 2. a whole group (tail of the sequence of lambdas) is\n--    \"clustered\". The work here is defining \"clustered\". For\n--    example, if the average distance (or max distance) between a\n--    bunch of lambdas was close to the min distance (or average\n--    distance), then the points are clustered.\n--\n-- 3.  the value of the objective function (ELBO) is not increasing\n--     fast enough / in proportion to the effort. The work here\n--     includes\n--\n--     - evaluating / estimating the objective function: turns out\n--       this is quite similar to estimating the gradient of the\n--       objective, and using a control variate should be similar\n--       here. Indeed, we can define a control variate by adding a\n--       multiple of the score function (as we do for estimating the\n--       gradient itself.\n--\n--     - defining \"fast enough / in proportion to the effort\". For\n--       example, we could define a \"velocity of improvement\" as the\n--       ratio of the change in the objective to the step size.\n--\n-- Second, some ideas for ensuring we do keep making progress when\n-- we can, by not decreasing the step size unnecessarily:\n--\n-- 1.  don't decrease the step size until the objective function stops\n--     improving \"fast enough\", as determined by (3) above.\n--\n-- 2.  split the AdaGrad step size into two parts, a scalar learning\n--     rate (@eta@ or @rho@ in the papers) and normalized AdaGrad\n--     learning rate vector. That is, in place of\n--\n--     > diag(G^t)^{-1/2}\n--\n--     we use\n--\n--     > eta^t (d^t / || d^t ||_2)\n--\n--     for some @d^t@ based on @diag(G^t)^{-1/2}@.\n--\n--     While this approach punts a bit, by depending on a new\n--     scalar learning rate @eta@, it simpler in that it decouples\n--     the per component learning rate / emphasis part of AdaGrad,\n--     a vector, from the scalar decrease in the step size. We can\n--     use a notion of decreasing progress as above to wind down\n--     the scalar learning rate.\n--\n--     For the @d^t@ we can simply use @diag(G^t)^{-1/2}@ itself,\n--     or perhaps a forgetful version, e.g.\n--\n--     > diag(G^{t-k,t})^{-1/2}\n--\n--     for\n--\n--     > G^{t1,t2} := g^{t1} g^{t1}^T + ... + g^{t1} g^{t1}^T\n--\n--     i.e.\n--\n--     > G^t = G^{1,t}.\n--\n-- So, there are a lot of interesting things we could try ...\n\n-- | The type of BBVI algorithms.\n--\n-- The @m@ is always monadic, but adding a @Monad m@ constraint on the\n-- RHS here causes problems with \"impredicative polymorphism\" later,\n-- when we try to make a list of @Bbvi m a@.\ntype Bbvi m a =\n  R {-^ @epsilon@  -} ->\n  Int {-^ @numSamples@ -} ->\n  (Int -> [R] -> [R]) {-^ @projectLambda@ -} ->\n  m [R] {-^ @sampleLambda@ -} ->\n  ([R] -> m a) {-^ @sampleQ@  -} ->\n  (a -> [R] -> m R) {-^ @evalLogQ@ -} ->\n  (a -> [R] -> m [R]) {-^ @evalGradLoqQ@ -} ->\n  (a -> m R) {-^ @evalLogP@ -} ->\n  m [R]\n\n-- | Black Box Variational Inference Algorithm 1.\n--\n-- From\n-- http://www.cs.columbia.edu/~blei/papers/RanganathGerrishBlei2014.pdf.\n--\n-- We assume that @evalLogP@ is already (partially) applied to the\n-- data @x@, unlike in the paper.\n--\n-- Here @epsilon@ is @0.01@ in the paper, and @numSamples@ is the\n-- unspecified @S@ in the paper.\n--\n-- The @projectLambda@ function is used to project computed @lambda@\n-- values back into the valid range of values for lambda.\n--\n-- === /Alternative approach/\n--\n-- As an alternative to defining a non-identity @projectLambda@, you\n-- can \"just\" reparameterize to make @lambda@ range over all of\n-- @R^n@. This is complicated and not suggested; see `bbviTest2` for\n-- an example of reparameterizing.\n--\n-- You may be able to use functions from our 'Continuous' class to do\n-- the transformations.\n--\n-- For example, normal distributions only support positive values for\n-- sigma; we can work around this by using @fromRealLbInfty 0@ and\n-- @toRealLbInfty 0@.\n--\n-- Alternatively, it might be possible to make the @q@-related\n-- functions signal some kind of error when some part of lambda is out\n-- of range. Not sure how to best recover here, but coming up with a\n-- good way to recover could be much simpler than reparameterizing.\nbbvi1 :: Monad m => Bbvi m a\nbbvi1 epsilon numSamples projectLambda\n  sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP = do\n  lambda <- projectLambda 1 <$> sampleLambda\n  loop lambda 1\n  where\n    loop lambda t = do\n      zs <- replicateM numSamples (sampleQ lambda)\n      elboGradTerms <- forM zs $ \\z -> do\n        glq <- evalGradLogQ z lambda\n        lq <- evalLogQ z lambda\n        lp <- evalLogP z\n        return $ (lp - lq) `scaleV` glq\n      let elboGrad = (1 / fromIntegral numSamples) `scaleV`\n                     sumV elboGradTerms\n      let lambda' = projectLambda t $ lambda `addV` (rho t `scaleV` elboGrad)\n      let delta = ell1 $ lambda `subV` lambda'\n      if delta >= epsilon\n      then loop lambda' (t + 1)\n      else trace (\"t = \"++show t) $ return lambda'\n\n    -- Paper says any sequence converging in @\\ell^2@ and diverging in\n    -- @\\ell^1@ will do for @rho@ here.\n    rho t = 1/fromIntegral t\n\n-- | Single factor Black Box Variational Inference Algorithm 2,.\n--\n-- The n-factor algorithm can be implemented in terms of the single\n-- factor algorithm, assuming the factors can be sampled\n-- independently, which seems likely since their pdfs are independent\n-- by assumption. The single factor Algorithm 2 is pretty similar to\n-- Algorithm 1, except we use control variates to reduce the\n-- variation.\n--\n-- See 'bbvi1' for more docs.\n--\n-- The use of @projectLambda@ in this implementation only corresponds\n-- to the AdaGrad paper when the domain of lambda is a closed (hyper)\n-- rectangle, but (partially) open rectangles should be close\n-- enough. For non-rectangular domains, the projection function in the\n-- AdaGrad paper takes @diagG@ into account via a \"Mahalanobis norm\"\n-- (same as the @\\ell^2@ norm for rectangular domains in this\n-- context). I expect this doesn't matter much ...\n--\n-- TODO: change this into a stream algorithm, so that epsilon does not\n-- have to be passed in, and instead the caller can just\n--\n-- > dropWhile (error > epsilon)\n--\n-- Chad suggested this approach earlier for coordinate descent.\nsingleFactorBbvi2 :: Monad m => Bbvi m a\nsingleFactorBbvi2 epsilon numSamples projectLambda\n  sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP = do\n  lambda <- projectLambda 1 <$> sampleLambda\n  let diagG = map (const 0) lambda\n  loop diagG lambda 1\n  where\n    loop diagG lambda t = do\n      zs <- replicateM numSamples (sampleQ lambda)\n      hs <- forM zs $ \\z -> do\n        evalGradLogQ z lambda\n      fs <- forM (zip zs hs) $ \\(z, h) -> do\n        lq <- evalLogQ z lambda\n        lp <- evalLogP z\n        return $ (lp - lq) `scaleV` h\n\n      -- In the paper they say that they used 1000 for @numSamples@\n      -- (called @S@ in the paper) and 100 estimates (i.e. 1/10th of\n      -- the 1000) for the approximate Cov and Var in the computation\n      -- of @\\hat{a}^*_d@. So, we're generalizing this to using 1/10th\n      -- of the samples.\n      let numSamples' = if numSamples <= 10\n                        then numSamples\n                        else numSamples `div` 10\n      let hs' = take numSamples' hs\n      let fs' = take numSamples' fs\n      let hs't = transpose hs'\n      let fs't = transpose fs'\n      let as = [ cov fCol hCol / var hCol | fCol <- fs't | hCol <- hs't ]\n\n      let elboGradTerms = [ f `subV` aH\n                          | f <- fs\n                          | aH <- map (multV as) hs ]\n      let elboGrad = (1 / fromIntegral numSamples) `scaleV` sumV elboGradTerms\n      let diagG' = diagG `addV` (elboGrad `multV` elboGrad)\n      -- Square root of pseudo inverse of @diagG'@.\n      let learningRate = eta `scaleV`\n                         [ if x == 0 then 0 else x**(-0.5) | x <- diagG' ]\n      let dLambda = learningRate `multV` elboGrad\n      let lambda' = projectLambda t $ lambda `addV` dLambda\n\n      let delta = ell1 $ lambda `subV` lambda'\n      if trace (\"delta = \"++show delta++\"\\ndiagG = \"++show diagG'++\"\\ndLambda = \"++show dLambda++\"\\nlambda = \"++show lambda') $\n         delta >= epsilon\n      then loop diagG' lambda' (t + 1)\n      else trace (\"t = \"++show t) $ return lambda'\n\n    -- I think the AdaGrad paper said this parameter doesn't matter\n    -- much (e.g. the theorem about the regret going to zero doesn't\n    -- depend on an optimal choice for eta). I think this is the value\n    -- they used though.\n    eta = 2**0.5\n\n    -- Note that @cov@ and @var@ are unnormalized -- i.e. not divided\n    -- by the length of the input vectors -- since the normalization\n    -- factors would just cancel in the calculation of @as@ as a ratio\n    -- of @cov@ to @var@.\n    var xs = cov xs xs\n    cov xs ys = sum [ (x - meanXs) * (y - meanYs) | x <- xs | y <- ys ]\n      where\n        meanXs = mean xs\n        meanYs = mean ys\n    mean xs = sum xs / fromIntegral (length xs)\n\n-- | Iterate BBVI until convergence or round limit is reached.\n--\n-- The @bbvi@ argument is expected to be a partially applied to all\n-- arguments except for @sampleLambda@.\niterateBbvi ::\n  Monad m =>\n  Int ->\n  R ->\n  m [R] ->\n  (m [R] -> m [R]) ->\n  m [R]\niterateBbvi maxRounds epsilon sampleLambda bbvi = do\n  result <- bbvi sampleLambda\n  go 2 result\n  where\n    go round result\n      | round >= maxRounds = return result\n      | otherwise = do\n          result' <- bbvi (return result)\n          if ell1 (result `subV` result') <= epsilon\n            then return result'\n            else trace (show result') $ go (round + 1) result'\n\n-- | Create an iterated version of an existing BBVI algorithm.\n--\n-- A helper to call @iterateBbvi@ for you, producing something of type\n-- @Bbvi@' (useful for tests where I want to put BBVI algs in a list).\niteratedBbvi :: Monad m => Int -> Bbvi m a -> Bbvi m a\niteratedBbvi maxRounds bbvi epsilon numSamples projectLambda\n  sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP =\n  iterateBbvi maxRounds epsilon sampleLambda\n  (\\sample -> bbvi epsilon numSamples projectLambda\n              sample sampleQ evalLogQ evalGradLogQ evalLogP)\n\n-- | A variety of BBVI algs for use in testing.\nbbvis :: Monad m => [Bbvi m a]\nbbvis =  [ bbvi1\n         , singleFactorBbvi2\n         , iteratedBbvi 100 bbvi1\n         , iteratedBbvi 100 singleFactorBbvi2 ]\n\n----------------------------------------------------------------\n-- * Variational families\n----------------------------------------------------------------\n--\n-- $variationalFamilies\n-- The code needed to use a specific variational family (the @q \\in\n-- Q@) with a BBVI algorithm is independent of the target distribution\n-- (the @p@) being approximated.\n\n----------------------------------------------------------------\n-- ** Normal\n\nsampleNormal :: SampleableIn m Normal => [R] -> m R\nsampleNormal [mu, sigma] = distSample (Normal mu sigma)\n\nevalLogNormalDensity :: Monad m => R -> [R] -> m R\nevalLogNormalDensity z [mu, sigma] = return $\n  probToLogR $ distDensity (Normal mu sigma) z\n\nevalGradLogNormalDensity :: Monad m => R -> [R] -> m [R]\nevalGradLogNormalDensity z [mu, sigma] = return\n  -- Calculated by hand from @normalDensity@ ...\n  [ (z - mu) / sigma\n  , (z - mu)**2 / sigma**3 - 1 / sigma ]\n\nprojectLambdaNormal :: Int -> [R] -> [R]\nprojectLambdaNormal = projectRectangle\n  [ (OpenBound (-1/0), OpenBound (1/0)),\n    (OpenBound 0, OpenBound (1/0)) ]\n\n----------------------------------------------------------------\n-- ** Multivariate normal\n--\n-- $mvNormal\n-- Everywhere below @k@ is the dimension of the mv normal.\n\n-- | Convert the flat list of params used by the bbvi algorithm into\n-- the vector and matrix params used by the mv normal distribution.\nparamsToDistParamsMVNormal :: Int -> [Double] -> (Vector Double, Matrix Double)\nparamsToDistParamsMVNormal k muAndC =\n  if length muAndC /= expectedLength\n  then error $\n       \"paramsToDistParamsMVNormal: \"++\n       \"the parameter list is the wrong length! Expected: \"++\n       show expectedLength++\", actual: \"++show (length muAndC)\n  else (mu, c)\n  where\n    -- An upper triangular @k x k@ matrix has @k + 1@ choose 2\n    -- potentially non-zero entries.\n    expectedLength = k + ((k * (k+1)) `div` 2)\n\n    (muList, cList) = splitAt k muAndC\n    mu = La.fromList muList\n    c = (k La.>< k) $ upperTriangular k cList\n\n-- | Build full list of entries in upper triangular matrix from list\n-- of its potentially non-zero entries.\n--\n-- Builds up the full list for the matrix by filling in zeros for\n-- undefined entries. The undefined entries are the lower tringular,\n-- i.e. where the row index is larger than the column index.\nupperTriangular :: (Num a) => Int -> [a] -> [a]\nupperTriangular k xs0 = zeroPad rcs xs0\n  where\n    rcs = [ (r, c) | r <- [0..(k-1)], c <- [0..(k-1)] ]\n    zeroPad []           []         = []\n    zeroPad ((r,c):rcs') xs@(x:xs') =\n      if r > c\n      then 0 : zeroPad rcs' xs\n      else x : zeroPad rcs' xs'\n\nsampleMVNormal :: SampleableIn m MVNormal => Int -> [R] -> m (Vector R)\nsampleMVNormal k muAndC = distSample (MVNormal mu c)\n  where\n    (mu, c) = paramsToDistParamsMVNormal k muAndC\n\n-- | The @k@ is the dimension of the mv normal.\nevalLogMVNormalDensity ::\n  Monad m => Int -> Vector R -> [R] -> m R\nevalLogMVNormalDensity k z muAndC = return $\n  probToLogR $ distDensity (MVNormal mu c) z\n  where\n    (mu, c) = paramsToDistParamsMVNormal k muAndC\n\n-- | The log pdf is\n--\n-- > lpdf = -1/2 ( ln |C^T C| + (x-mu)^T(C^T C)^{-1}(x-mu) + k ln (2 pi) ) ,\n--\n-- where @|M|@ is the absolute value of the determinant of @M@.\n--\n-- The partials with respect to @mu@'s components are easy. The\n-- product rule gives\n--\n-- > d_{mu_i} lpdf = -1/2 ( m^T(C^T C)^{-1}(x-mu) + (x-mu)^T(C^T C)^{-1}m )\n--\n-- for @m := - d_{mu_i} mu@, i.e. a vector with @m_j = - (Kronecker) delta i j@.\n--\n-- The partials with respect to @C@'s components are trickier, but\n-- simplified by the fact that the determinant of @C@ is simple.\n--\n-- Let @d@ be some partial @d/dC_{ij}@. It comes down to calculating\n--\n-- > d ln |C^T C|\n--\n-- and\n--\n-- > d (x-mu)^T(C^T C)^{-1}(x-mu) .\n--\n--\n-- For the first term we have @|C^T C|@ = @|C|^2@ and so\n--\n-- > ln |C^T C| = 2 ln |C|\n--\n-- and so\n--\n-- > d ln |C^T C| = (2/|C|) d |C| .\n--\n-- Since @C@ is upper triangular with positive diagonal, we have\n--\n-- > |C| = C_{11} .. C_{kk}\n--\n-- and so for @d = d/dC_{ij}@ we have\n--\n-- > d |C| = if i == j then |C|/C_{ij} else 0 .\n--\n-- and so\n--\n-- > d ln |C^T C| = if i == j then 2/C_{ij} else 0 .\n--\n--\n-- For the second term we have\n--\n-- > (C^T C)^{-1} = (C^{-1}) (C^{-1})^T\n--\n-- and so\n--\n-- > d (C^T C)^{-1} = (d C^{-1}) (C^{-1})^T + C^{-1} (d C^{-1})^T ,\n--\n-- and so we just need the derivative of the inverse:\n--\n-- > d C^{-1} = - C^{-1} (d C) C^{-1}\n--\n-- see http://planetmath.org/derivativeofinversematrix.\n--\n-- Putting that all back together, with @B := C^{-1}@, we have\n--\n-- > d (C^T C)^{-1} = - (B dC B B^T + B B^T dC^T B^T)\n-- >                = - B (dC B + (dC B)^T) B^T\n--\n-- and for @d = d/d(C_{ij})@ we have\n--\n-- > (dC)_{st} = delta i s * delta j t .\nevalGradLogMVNormalDensity ::\n  Monad m => Int -> Vector Double -> [R] -> m [R]\nevalGradLogMVNormalDensity k x muAndC =\n  return $ map (* (-1/2)) $ muGrads ++ cGrads\n  where\n    (mu, c) = paramsToDistParamsMVNormal k muAndC\n    delta i j = if i == j then 1 else 0\n\n    muGrads = [ d <.> cInvFun (x - mu) +\n                (x - mu) <.> cInvFun d\n              | i <- [ 0 .. k-1 ]\n              , d <- [ La.fromList $ map (((-1) *) . delta i) [ 0 .. k-1 ] ] ]\n    -- Efficient left multiplication of a vector by @(C^T C)^{-1}@.\n    cInvFun = La.flatten . La.cholSolve c . La.asColumn\n\n    cGrads = [ lnGrad i j + prodGrad i j\n             | i <- [ 0 .. k-1 ]\n             , j <- [ i .. k-1 ] ]\n    lnGrad i j = if i == j then 2 / (c `La.atIndex` (i, j)) else 0\n    prodGrad i j = (x - mu) <.> middle #> (x - mu)\n      where\n        middle = (-1) * b <> (dC i j <> b + La.tr (dC i j <> b)) <> La.tr b\n    -- The inverse of @C@ as a matrix.\n    (b, _) = La.invlndet c\n    -- The derivative of @C@ w.r.t. @C_{ij}@.\n    dC i j = La.assoc (k, k) 0 [ ((i, j), 1) ]\n\n-- | The diagonal entries of the Cholesky matrix must be positive. The\n-- other values are unconstrained.\n--\n-- The @k@ is the dimension of the mv normal.\nprojectLambdaMVNormal :: Int -> Int -> [R] -> [R]\nprojectLambdaMVNormal k = projectRectangle $ muBounds ++ cBounds\n  where\n    reals = (OpenBound (-1/0), OpenBound (1/0))\n    positiveReals = (OpenBound 0, OpenBound (1/0))\n\n    muBounds = replicate k reals\n    cBounds = flip concatMap [ k, k - 1 .. 1 ] $ \\rowLength ->\n      take rowLength $ [ positiveReals ] ++ repeat reals\n\n----------------------------------------------------------------\n-- *** Test mv normal implementation.\n--\n-- $testMvNormal\n--\n-- The gradient we calculated by hand was quite complicated, so\n-- compare it with the gradient we get from automatic differentiation\n-- (would have been much faster in human time to just use automatic\n-- differentiation in the first place, but now we have very high\n-- confidence the gradient is correct).\n\n-- | An overloaded (i.e. @Floating@) implementation of the log pdf.\n--\n-- This allows us to use automatic differentiation and compare the\n-- result with the manual, by hand gradient\n-- 'evalGradLogMVNormalDensity' above.\nlogMVNormalDensityOverloaded ::\n  (Floating a, Eq a) => Int -> [a] -> [a] -> a\nlogMVNormalDensityOverloaded k xList muAndC =\n  ((- 0.5) *) $\n  2 * log detC +\n  fromIntegral k * log (2 * pi) +\n  -- The @Dm@ library uses 1-based indexing.\n  prod Dm.! (1,1)\n  where\n    (muList, cList) = splitAt k muAndC\n    x = Dm.fromList k 1 xList\n    mu = Dm.fromList k 1 muList\n    c = Dm.fromList k k $ upperTriangular k cList\n    detC = foldr (*) 1 $ Dm.getDiag c\n    sigma = Dm.transpose c * c\n    Right sigmaInv = Dm.inverse sigma\n    prod = (Dm.transpose $ x - mu) * sigmaInv * (x - mu)\n\n-- | Use automatic differentiation to check the manually computed mv\n-- normal gradient.\ncompareGrads :: Monad m => Int -> [R] -> [R] -> m [R]\ncompareGrads k x muAndC = do\n  manual <- evalGradLogMVNormalDensity k (La.fromList x) muAndC\n  -- AD needs the function to differentiate to overloaded / take\n  -- @Floating@ arguments.\n  let x' :: Floating a => [a]\n      x' = map (fromRational . toRational) x\n  let auto = Ad.grad (logMVNormalDensityOverloaded k x') muAndC\n  -- The rescaling of errors is essential here: without it, for very\n  -- large gradient entries (e.g. size 10^10), there can be large\n  -- absolute differences between gradient entries. We care about\n  -- large relative differences, which can't be explained away by\n  -- rounding error. Dividing by 1 here avoids division by zero, and\n  -- means we avoid spurious differences detected when we divide by\n  -- very small numbers.\n  return $ [ abs (m - a) / (abs m + abs a + 1) | m <- manual | a <- auto ]\n\n-- | QuickCheck property asserting 'compareGrads' for given mv normal\n-- dimension @k@.\nprop_evalGradLogMVNormalDensity_correct :: Int -> Qc.Property\nprop_evalGradLogMVNormalDensity_correct k =\n  -- forAll' \"k\" Qc.arbitrary $ \\(Qc.Positive (k :: Int)) ->\n  forAll' \"xList\" (Qc.vector k) $ \\xList ->\n  forAll' \"muList\" (Qc.vector k) $ \\muList ->\n  forAll' \"cList\" (genCList k) $ \\cList ->\n  Qc.monadicIO $ do\n    deltas <- Qc.run $ compareGrads k (i xList) (i $ muList ++ cList)\n    Qc.monitor (Qc.counterexample $ \"(Index, Delta): \" ++ show (argMax deltas))\n    Qc.assert $ all isSmall deltas\n  where\n    -- Return index of max entry, and max entry.\n    argMax :: Ord a => [a] -> (Int, a)\n    argMax (x:xs) = go 1 (0,x) xs\n      where\n        go _ p [] = p\n        go j (i,x) (x':xs) = go (j+1) (if x < x' then (j, x') else (i, x)) xs\n\n    i :: [Integer] -> [R]\n    i = map fromInteger\n    -- Generate a list representation of a Cholesky factor. The\n    -- strategy is to recursively generate row tails from the diagonal\n    -- entry onwards, with non-zero diagonal entries and arbitrary\n    -- other entries.\n    genCList :: Int -> Qc.Gen [Integer]\n    genCList k = do\n      rows <- forM [k,k-1..1] $ \\len -> do\n        Qc.Positive diagEntry <- Qc.arbitrary\n        rest <- Qc.vectorOf (len-1) Qc.arbitrary\n        return $ diagEntry : rest\n      return $ concat rows\n\n    isSmall delta = abs delta <= 0.001\n\n    -- A version of @Qc.forAll@ with named quantifiers. This makes the\n    -- counterexamples much easier to read.\n    forAll' name gen pf =\n      -- The library provided @Qc.forAll@ that I adapted to create\n      -- this @forAll'@ has a @Qc.again@ here. But I don't understand\n      -- why I need it, and more importantly, I get an import error,\n      -- so leaving it out ...\n      --\n      -- Qc.again $\n      Qc.MkProperty $\n      gen >>= \\x ->\n        Qc.unProperty $\n        Qc.counterexample (name++\": \"++show x) (pf x)\n\n-- | Check the QuickCheck props @numTrials@ many times.\n--\n-- For larger @k@ this fails, but I think it's due to numerical\n-- instability. For small @k@, e.g. less than or equal to 5, we can\n-- pass hundreds of thousands of tests. For large @k@, e.g. @k = 30@,\n-- we fail pretty fast.\ncheckProps :: Int -> Int -> IO ()\ncheckProps k numTrials = do\n  qc $ prop_evalGradLogMVNormalDensity_correct k\n  where\n    qc = Qc.quickCheckWith (Qc.stdArgs { Qc.maxSuccess = numTrials })\n\n----------------------------------------------------------------\n-- * Tests\n----------------------------------------------------------------\n\n-- | Even simpler version of the 'bbv1Test2' below.\n--\n-- Here we approximate a normal by a normal. The standard deviation is\n-- fixed, and we fit the mean. The input @mu@ and @sigma@ are the\n-- parameters of the normal that we are trying to approximate; our\n-- goal is to discover @mu@.\n--\n-- We make @mu@ the parameter to discover, because it ranges over all\n-- reals and so no transformations are needed.\n--\n-- Returns the error in the discovered @mu@, and the discovered @mu@.\nbbviTest1 ::\n  (SampleableIn m Normal) =>\n  Int -> R -> Int -> [R] -> m (R, [R])\nbbviTest1 algNum epsilon numSamples [mu, sigma] = do\n  [mu'] <- (bbvis !! (algNum - 1)) epsilon numSamples projectLambda\n           sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP\n  let error' = ell1 $ [mu'] `subV` [mu]\n  return (error', [mu'])\n  where\n    -- We can see that bbvi1 at least kind of works by seeding @lambda@\n    -- with a value very close to the right answer.\n    --\n    -- sampleLambda = replicateM 1 $ distSample (Normal mu 0.1)\n    sampleLambda = defaultSampleLambda 1\n    sampleQ [mu'] = distSample (Normal mu' sigma)\n    evalLogQ z [mu'] = return $\n      probToLogR $ distDensity (Normal mu' sigma) z\n    evalGradLogQ z [mu'] = return [ (z - mu') / sigma ]\n    evalLogP z = return $\n      probToLogR $ distDensity (Normal mu sigma) z\n    projectLambda _ lambda = lambda\n\n-- | Test 'bbv1' by approximating a linear combination of normals by a\n-- normal ... except it turns out that a linear combination of normals\n-- *is* a normal, and the only way to analytically weight its samples\n-- is to know this, so I'm really just going to approximate a normal\n-- by a normal. At least we can expect this to succeed :D\n--\n-- Formulas for linear combination of normals are here:\n-- https://www.statlect.com/probability-distributions/normal-distribution-linear-combinations.\n--\n-- Note that we have to transform the standard deviation param sigma,\n-- per the comments above in 'bbvi1'.\nbbviTest2 ::\n  (SampleableIn m Normal) =>\n  Int -> R -> Int -> [R] -> m (R, [R])\nbbviTest2 algNum epsilon numSamples [mu, sigma] = do\n  [mu', sigma'] <- fRLambda <$>\n    (bbvis !! (algNum - 1)) epsilon numSamples projectLambda\n    sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP\n  -- In general, it might only make sense to compute the error in the\n  -- real domain.\n  let error' = ell1 $ [mu', sigma'] `subV` [mu, sigma]\n  return (error', [mu', sigma'])\n  where\n    projectLambda _ lambda = lambda\n    -- Since lambda is always a vector of reals, it's not clear why it\n    -- should be a param to 'bbvi1'.\n    --\n    -- !!!: THE @fromRealLbInfty 0@ UNDERFLOWS TO ZERO FOR LARGE VALUES.\n    --\n    -- ???: does the delta in the output change when we increase\n    -- numSampls???\n    sampleLambda = defaultSampleLambda 2\n\n    sampleQOrig = sampleNormal\n    sampleQ = sampleQOrig . fRLambda\n\n    evalLogQOrig = evalLogNormalDensity\n    evalLogQ z = evalLogQOrig z . fRLambda\n\n    -- Calculated by hand from @normalDensity@ ...\n    evalGradLogQOrig = evalGradLogNormalDensity\n    evalGradLogQ z lambda =\n      -- Chain rule specialized to vars transformed independently\n      -- (i.e. the derivative matrix of the transformation @fRLambda@\n      -- is diagonal).\n      zipWith (*) (fRLambda' lambda) <$>\n      evalGradLogQOrig z (fRLambda lambda)\n\n    evalLogP z = evalLogNormalDensity z [mu, sigma]\n\n    -- Transformations from and to reals for sigma param of\n    -- normal. Note: the 'Continuous' class transforms the support /\n    -- output, not the params / input of a distribution.\n    fRSigma = fromRealLbInfty 0\n    fRSigma' = probToR . fromRealLbInfty' 0\n    -- tRSigma = toRealLbInfty 0\n\n    fRLambda [mu', sigma'R] = [mu', fRSigma sigma'R]\n    -- Here @1@ is the derivative of the identity.\n    fRLambda' [_mu', sigma'R] = [1, fRSigma' sigma'R]\n    -- tRLambda [mu', sigma'] = [mu', tRSigma sigma']\n\n-- | Like `bbviTest2`, but use a non-trivial `projectLambda`, instead\n-- of a reparameterization.\nbbviTest3 ::\n  (SampleableIn m Normal) =>\n  Int -> R -> Int -> [R] -> m (R, [R])\nbbviTest3 algNum epsilon numSamples [mu, sigma] = do\n  [mu', sigma'] <-\n    (bbvis !! (algNum - 1)) epsilon numSamples projectLambda\n    sampleLambda sampleQOrig evalLogQOrig evalGradLogQOrig evalLogP\n  -- In general, it might only make sense to compute the error in the\n  -- real domain.\n  let error' = ell1 $ [mu', sigma'] `subV` [mu, sigma]\n  return (error', [mu', sigma'])\n  where\n    -- Since lambda is always a vector of reals, it's not clear why it\n    -- should be a param to 'bbvi1'.\n    --\n    -- !!!: THE @fromRealLbInfty 0@ UNDERFLOWS TO ZERO FOR LARGE VALUES.\n    sampleLambda = defaultSampleLambda 2\n    sampleQOrig = sampleNormal\n    evalLogQOrig = evalLogNormalDensity\n    evalGradLogQOrig = evalGradLogNormalDensity\n    projectLambda = projectLambdaNormal\n\n    evalLogP z = evalLogNormalDensity z [mu, sigma]\n\n-- | Learn a normal that approximates a Student's t-distribution.\n--\n-- The parameters are @mu@ real and @nu@ positive real.\n--\n-- We want the mean of the learned normal to be the mean of the\n-- t-distribution. I don't know what to expect for the std deviation\n-- of the learned normal tho. The variance of the t-distribution is\n-- @nu / (nu - 2)@ for @nu > 2@ and infinite or undefined otherwise.\n--\n-- See https://en.wikipedia.org/wiki/Student's_t-distribution.\nbbviTest4 ::\n  SampleableIn m Normal =>\n  Int -> R -> Int -> [R] -> m (R, [R])\nbbviTest4 algNum epsilon numSamples [mu, nu] = do\n  [mu', sigma'] <-\n    (bbvis !! (algNum - 1)) epsilon numSamples projectLambda\n    sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP\n  -- In general, it might only make sense to compute the error in the\n  -- real domain.\n  let error' = ell1 $ [mu'] `subV` [mu]\n  return (error', [mu', sigma'])\n  where\n    sampleQ = sampleNormal\n    evalLogQ = evalLogNormalDensity\n    evalGradLogQ = evalGradLogNormalDensity\n    sampleLambda = defaultSampleLambda 2\n    projectLambda = projectLambdaNormal\n\n    evalLogP z = return $\n      S.logDensity (S.studentT nu) (z - mu)\n\n----------------------------------------------------------------\n\n-- | Learn a multivariate normal that approximates a linear\n-- regression.\n--\n-- The linear regression has parameters slope @m@, @y@-intercept @b@,\n-- and error standard deviation @sigma@. The generative model\n-- comprises a arbitrary distribution of the parameters @m@, @b@, and\n-- @sigma@, say\n--\n-- > m ~ Uniform 0 10\n-- > b ~ Uniform 0 10\n-- > sigma ~ Uniform 0 10 ,\n--\n-- and a noisy linear distribution on the dependent variable @y@ given\n-- the independent variable @x@, i.e.\n--\n-- > e ~ Normal 0 sigma\n-- > y := m*x + b + e ,\n--\n-- or equivalently\n--\n-- > y ~ Normal (m*x + b) e .\n--\n-- So, the joint distribution given data\n--\n-- > xys = [(x1,y1),...,(xn,yn)]\n--\n-- is\n--\n-- > P[xys,m,b,sigma] = P[xys|m,b,sigma] * P[m,b,sigma] ,\n--\n-- where\n--\n-- > P[m,b,sigma] = 1\n--\n-- and\n--\n-- > P[xys|m,b,sigma] = p(x1,y1) * ... * p(xn,yn) ,\n--\n-- for\n--\n-- > p(x,y) =\n-- > Pr[y = m*x + b + e] =\n-- > Pr[e = y - m*x - b] =\n-- > distDensity (Normal (m*x + b) sigma) y .\n--\n-- The @xysFlat@ argument is\n--\n-- > [x1,y1,x2,y2,...,xn,yn] .\nbbviTest5 ::\n  (SampleableIn m Normal, SampleableIn m MVNormal) =>\n  Int -> R -> Int -> [R] -> m (R, [R])\nbbviTest5 algNum epsilon numSamples (m:b:sigma:xysFlat) = do\n  muAndC'@(m':b':sigma':_cList') <-\n    (bbvis !! (algNum - 1)) epsilon numSamples projectLambda\n    sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP\n  let error' = ell1 $ [m',b',sigma'] `subV` [m,b,sigma]\n  return (error', muAndC')\n  where\n    -- Three dimensions, for @m@, @b@, and @sigma@.\n    k = 3\n    muSize = k\n    cSize = (k * (k+1)) `div` 2\n\n    sampleQ = sampleMVNormal k\n    evalLogQ = evalLogMVNormalDensity k\n    evalGradLogQ = evalGradLogMVNormalDensity k\n    sampleLambda = defaultSampleLambda (muSize + cSize)\n    projectLambda = projectLambdaMVNormal k\n\n    xys = go xysFlat\n      where\n        go [] = []\n        go (x:y:xysFlat') = (x,y) : go xysFlat'\n\n    evalLogP mBSigma = return $ linRegLogDensity xys m' b' sigma'\n      where\n        [m', b', sigma'] = La.toList mBSigma\n\n-- | A version of 'bbviTest5' that fixes the noise deviation sigma, so\n-- that the mv normal only needs two params. The sigma passed in will\n-- be used, and should correspond to the supplied data in @xysFlat@.\nbbviTest7 ::\n  (SampleableIn m Normal, SampleableIn m MVNormal) =>\n  Int -> R -> Int -> [R] -> m (R, [R])\nbbviTest7 algNum epsilon numSamples (m:b:sigma:xysFlat) = do\n  muAndC'@(m':b':_cList') <-\n    (bbvis !! (algNum - 1)) epsilon numSamples projectLambda\n    sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP\n  let error' = ell1 $ [m',b'] `subV` [m,b]\n  return (error', muAndC')\n  where\n    -- Two dimensions, for @m@, @b@.\n    k = 2\n    muSize = k\n    cSize = (k * (k+1)) `div` 2\n\n    sampleQ = sampleMVNormal k\n    evalLogQ = evalLogMVNormalDensity k\n    evalGradLogQ = evalGradLogMVNormalDensity k\n    sampleLambda = defaultSampleLambda (muSize + cSize)\n    projectLambda = projectLambdaMVNormal k\n\n    xys = go xysFlat\n      where\n        go [] = []\n        go (x:y:xysFlat') = (x,y) : go xysFlat'\n\n    evalLogP mB = return $ linRegLogDensity xys m' b' sigma\n      where\n        [m', b'] = La.toList mB\n\nlinRegLogDensity ::\n  [(R, R)] -> R -> R -> R -> R\nlinRegLogDensity xys m b sigma =\n  -- An alternative approach:\n  --\n  -- The @abs sigma'@ is here to avoid using negative sigma\n  -- values. Not sure what the right approach is here: we could\n  -- use a different @projectLambda@ implementation that restricts\n  -- to positive third component (i.e. the mean of the sigma\n  -- values), but that won't stop them from being\n  -- negative.\n  {-\n  sum [ logFromLogFloat (distDensity (Normal (m'*x + b') (abs sigma')) y)\n      | (x, y) <- xys ]\n  -}\n  -- We penalize negative sigmas, by returning a very small value\n  -- here.\n  if sigma > 0\n  then\n    (if logProb < logVerySmallValue\n     then trace (\"XXX: logProb is very small: \"++show logProb)\n     else id)\n    logProb\n  else\n    -- Is this value is really small enough? Could try @-1/0@.\n    --\n    -- Update: using negative infinity, or more generally very large\n    -- negative values here, causes various crashes (for finite values\n    -- an underflow in @LogFloat@, and for negative infinity a\n    -- malformed Cholesky factor).\n    logVerySmallValue\n    where\n      logVerySmallValue = -10e10\n      logProb = sum [ probToLogR $ distDensity (Normal (m*x + b) sigma) y\n                    | (x, y) <- xys ]\n\nsimpleLinRegData :: Int -> R -> R -> [(R, R)]\nsimpleLinRegData numPoints m b =\n  [ (x, m*x+b) | x <- [ 1 .. fromIntegral numPoints ] ]\n\ngenLinRegDataIO :: Int -> R -> R -> R -> IO [(R, R)]\ngenLinRegDataIO numSamples m b sigma = do\n  g <- MWC.create\n  runRand g $ genLinRegData numSamples m b sigma\n\ngenLinRegData ::\n  ( SampleableIn m Normal, SampleableIn m Uniform ) =>\n  Int -> R -> R -> R -> m [(R, R)]\ngenLinRegData numSamples m b sigma = do\n  replicateM numSamples $ do\n    -- Use integral @x@s to make the output a little easier to inspect\n    -- visually.\n    x <- fromInteger . round <$> distSample (Uniform (-1000) 1000)\n    y <- distSample (Normal (m*x + b) sigma)\n    return (x,y)\n\n-- scatterPlot :: [(R, R)] -> ???\n-- | Based on http://indiana.edu/~ppaml/HakaruTutorial.html and\n-- https://github.com/timbod7/haskell-chart/wiki/example%202.\n--\n-- Writes output to an SVG file, regardless of supplied file extension\n-- :P The examples I referred to use the Cairo backend, but I'm using\n-- the Diagrams backend, so that might be the issue. So, I changed\n-- this function to supply the extension, to avoid confusion.\nscatterPlot :: String -> String -> [(R, R)] -> IO (G.PickFn ())\nscatterPlot title file xys =\n  G.renderableToFile G.def (file++\".svg\") $ G.toRenderable layout\n  where\n    plot = G.plot_points_style .~ G.filledCircles 2 (G.opaque G.purple)\n           $ G.plot_points_values .~ xys\n           $ G.def\n\n    layout = G.layout_title .~ title\n             $ G.layout_plots .~ [G.toPlot plot]\n             $ G.layout_x_axis . G.laxis_generate .~ G.scaledAxis G.def (-4, 4)\n             $ G.layout_y_axis . G.laxis_generate .~ G.scaledAxis G.def (-4, 4)\n             $ G.def\n\n-- | https://en.wikipedia.org/wiki/File:MultivariateNormal.png\n--\n-- I can't figure out how to set the aspect ratio :P\nwikipediaExample :: IO ()\nwikipediaExample = do\n  g <- MWC.create\n  xyVectors <- runRand g $ replicateM numSamples (distSample (MVNormal mu c))\n  let xys = [ (x, y) | v <- xyVectors, [x,y] <- [ La.toList v ] ]\n  _ <- scatterPlot (\"Wikipedia Test (\"++show numSamples++\" samples)\") \"/tmp/out\" xys\n  return ()\n  where\n    mu = La.fromList [0, 0]\n    c = La.chol (La.trustSym $ (2 La.>< 2) [1, 0.6, 0.6, 2])\n    numSamples = 10000\n\n----------------------------------------------------------------\n\n-- | Sanity test: match an mv normal to an mv normal.\n--\n-- This works pretty well with iterated bbvi 2, e.g. with\n--\n-- > runBbviTestUsingLazyRand 1 4 6 1 1000 [1,2,3,1,0,0,2,0,3]\n--\n-- Of course, this doesn't prove much.\nbbviTest6 ::\n  (SampleableIn m Normal, SampleableIn m MVNormal) =>\n  Int -> R -> Int -> [R] -> m (R, [R])\nbbviTest6 algNum epsilon numSamples muAndC = do\n  muAndC' <-\n    (bbvis !! (algNum - 1)) epsilon numSamples projectLambda\n    sampleLambda sampleQ evalLogQ evalGradLogQ evalLogP\n  let error' = ell1 $ muAndC' `subV` muAndC\n  return (error', muAndC')\n  where\n    k = 3\n    muSize = k\n    cSize = (k * (k+1)) `div` 2\n\n    sampleQ = sampleMVNormal k\n    evalLogQ = evalLogMVNormalDensity k\n    evalGradLogQ = evalGradLogMVNormalDensity k\n    sampleLambda = defaultSampleLambda (muSize + cSize)\n    projectLambda = projectLambdaMVNormal k\n\n    evalLogP z = evalLogMVNormalDensity k z muAndC\n\n----------------------------------------------------------------\n\nrunBbviTestUsingLazyRand ::\n  Int -> Int -> Int -> R -> Int -> [R] -> IO [(R, [R])]\nrunBbviTestUsingLazyRand numTrials algNum testNum epsilon numSamples testParams = do\n  g <- MWC.create\n  runRand g $ replicateM numTrials $ test algNum epsilon numSamples testParams\n  where\n    test = [ bbviTest1\n           , bbviTest2\n           , bbviTest3\n           , bbviTest4\n           , bbviTest5 -- Mv normal for linear regression: learn m, b, sigma.\n           , bbviTest6 -- Mv normal for mv normal.\n           , bbviTest7 -- Mv normal for linear regression: learn m, b.\n           ] !! (testNum - 1)\n\ntest5 :: IO [(R, [R])]\ntest5 = runBbviTestUsingLazyRand 1 3 5 0.1 1000\n  ([m,b,sigma] ++ concat [ [x, y] | (x, y) <- simpleLinRegData 1000 m b ])\n  where\n    m = 1\n    b = 2\n    sigma = 0.001\n", "meta": {"hexsha": "68ebc7ae7b4ecbb3489bd05d6dd59ed81d057d3e", "size": 40278, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Language/Grappa/Inference/OldVariationalInference.hs", "max_stars_repo_name": "kquick/grappa", "max_stars_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T06:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T06:40:58.000Z", "max_issues_repo_path": "src/Language/Grappa/Inference/OldVariationalInference.hs", "max_issues_repo_name": "kquick/grappa", "max_issues_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-09-05T16:06:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-26T01:24:32.000Z", "max_forks_repo_path": "src/Language/Grappa/Inference/OldVariationalInference.hs", "max_forks_repo_name": "kquick/grappa", "max_forks_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-19T17:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T17:29:10.000Z", "avg_line_length": 36.450678733, "max_line_length": 127, "alphanum_fraction": 0.6297482497, "num_tokens": 12007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.423603965276478}}
{"text": "{-# LANGUAGE FlexibleContexts, NamedFieldPuns #-}\n\nmodule School.Unit.CostFunction\n( SetupCost\n, CostFunction(..)\n, defSetupCost\n) where\n\nimport Conduit ((.|), ConduitM, ZipSource(..), getZipSource, mapC, mapMC)\nimport Numeric.LinearAlgebra (Container, Matrix, Vector, add, cols, rows)\nimport School.Types.Slinky (Slinky(..), slinkyConcat)\nimport School.Unit.CostParams (CostParams)\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitForward (ForwardStack)\nimport School.Unit.UnitGradient (UnitGradient(..))\nimport School.Utils.LinearAlgebra (zeroMatrix)\n\ntype SetupCost a m = ConduitM () (Matrix a) m ()\n                  -> ConduitM () (ForwardStack a) m ()\n\ndefSetupCost :: (Monad m) => SetupCost a m\ndefSetupCost source =\n  source .| mapMC (\\matrix -> return ([BatchActivation matrix], SNil))\n\ntype CompupteCost a = UnitActivation a\n                   -> Slinky CostParams\n                   -> Either String a\n\ntype DerivCost a = UnitActivation a\n                -> Slinky CostParams\n                -> Either String (UnitGradient a)\n\ntype PrepareCost m a =\n  ConduitM (ForwardStack a) (ForwardStack a) m ()\n\ndata CostFunction a m =\n  CostFunction { computeCost :: CompupteCost a\n               , derivCost :: DerivCost a\n               , prepareCost :: PrepareCost m a\n               , setupCost :: SetupCost a m\n               }\n\nmappendCompute :: (Num a)\n               => CompupteCost a\n               -> CompupteCost a\n               -> CompupteCost a\nmappendCompute c1 c2 activations params1@(SNode _ params2) = do\n  res1 <- c1 activations params1\n  res2 <- c2 activations params2\n  return $ res1 + res2\nmappendCompute _ _ _ _ = Left \"mappend costfunctions needs two cost params\"\n\nmappendDeriv :: (Container Vector a, Num a)\n             => DerivCost a\n             -> DerivCost a\n             -> DerivCost a\nmappendDeriv d1 d2 activations params1@(SNode _ params2) = do\n  (BatchGradient res1) <- d1 activations params1\n  (BatchGradient res2) <- d2 activations params2\n  return $ BatchGradient $ add res1 res2\nmappendDeriv _ _ _ _ = Left \"mappend costfunctions needs two cost params\"\n\ncombinator :: ForwardStack a -> ForwardStack a -> ForwardStack a\ncombinator (_, cParams1) (activations, cParams2) =\n  (activations, slinkyConcat cParams1 cParams2)\n\nmappendSetup :: (Monad m)\n             => SetupCost a m\n             -> SetupCost a m\n             -> SetupCost a m\nmappendSetup s1 s2 source = getZipSource $ combinator\n                                       <$> (ZipSource $ s1 source)\n                                       <*> (ZipSource $ s2 source)\n\ninstance (Container Vector a, Num a, Monad m) => Monoid (CostFunction a m) where\n  mappend CostFunction { computeCost = c1\n                       , derivCost = d1\n                       , prepareCost = p1\n                       , setupCost = s1\n                       }\n          CostFunction { computeCost = c2\n                       , derivCost = d2\n                       , prepareCost = p2\n                       , setupCost = s2\n                       } =\n   CostFunction { computeCost = mappendCompute c1 c2\n                , derivCost = mappendDeriv d1 d2\n                , prepareCost = p1 .| p2\n                , setupCost = mappendSetup s1 s2\n                }\n  mempty = CostFunction { computeCost\n                        , derivCost\n                        , prepareCost = mapC id\n                        , setupCost = defSetupCost\n                        } where\n    computeCost _ _ = Right 0\n    derivCost (BatchActivation g) _ =\n      Right . BatchGradient $ zeroMatrix r c\n      where r = rows g\n            c = cols g\n    derivCost _ _ = Left \"mempty deriv cost expects batch activation\"\n", "meta": {"hexsha": "ac94c9c9e14da05b916f3aeef9374cb998191dac", "size": 3698, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/Unit/CostFunction.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/School/Unit/CostFunction.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/School/Unit/CostFunction.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2549019608, "max_line_length": 80, "alphanum_fraction": 0.5884261763, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4235268139644897}}
{"text": "{-# LANGUAGE RankNTypes #-}\nmodule Main where\n\nimport Codec.Picture (PixelRGBA8 (..), writePng)\nimport Control.Monad\nimport Data.Array.Accelerate\n  ( Acc,\n    All (..),\n    Any (..),\n    Array,\n    DIM2,\n    Elt,\n    Exp,\n    Generic,\n    Lift (..),\n    Matrix,\n    Plain,\n    Unlift,\n    Vector,\n    Z (..),\n    (:.) (..),\n  )\nimport qualified Data.Array.Accelerate as A\nimport Data.Array.Accelerate.Data.Complex\nimport Data.Array.Accelerate.LLVM.PTX\nimport Data.Array.Accelerate.Representation.Type\nimport Data.Array.Accelerate.Smart\nimport Data.Array.Accelerate.Sugar.Elt\nimport qualified Data.Complex as C\n-- import Graphics.Amusing\nimport Graphics.Rasterific hiding (Vector)\nimport Graphics.Rasterific.Texture\nimport Prelude.Unicode\nimport Text.Printf\n\ntype Pendulum a b = (a, b)\n\nzs :: Pendulum a b -> a\nzs (zs,  _) = zs\n\nps :: Pendulum a b -> b\nps (_, ps) = ps\n\ntype Pair a = (a, a)\n\ng :: (RealFrac a, A.RealFloat a, Elt a) => Exp a\ng = 9.81\n\norigin ::\n  (RealFrac a, A.RealFloat a, Elt a) =>\n  Exp (Pair (Complex a))\norigin = A.constant (0 :+ 0, 0 :+ 0)\n\nzero ::\n  (RealFrac a, A.RealFloat a, Elt a) =>\n  Exp (Pair a)\nzero = A.constant (0, 0)\n\none ::\n  (RealFrac a, A.RealFloat a, Elt a) =>\n  Exp (Pair (Complex a))\none = A.constant (1 :+ 0, 1 :+ 0)\n\ncalc ::\n  forall a.\n  (RealFrac a, A.RealFloat a, Elt a) =>\n  Exp a ->\n  Exp a ->\n  Exp a ->\n  Exp (Pendulum (Pair (Complex a)) (Pair a)) ->\n  Exp (Pendulum (Pair (Complex a)) (Pair a))\ncalc m1 m2 dt pendulum =\n  let (zs, ps) = A.unlift pendulum\n      zs :: Exp (Pair (Complex a))\n      ps :: Exp (Pair a)\n      (z1 :: Exp (Complex a), z3 :: Exp (Complex a)) = A.unlift zs\n      (p1 :: Exp a, p3 :: Exp a) = A.unlift ps\n      i1 = inertia z1 m1\n      i3 = inertia z3 m2\n      angleDiff = phase z1 - phase z3\n      commonFactor = (magnitude z3 / i1)/(18 * i3 * cos angleDiff**2 -\n                        8 * absSquared z3 * (3 * m2 + m1))\n      \u03c91 = commonFactor * m1 *\n             (3 * magnitude z1 * p3 * cos angleDiff - 2 * magnitude z3 * p1)\n      \u03c93 = commonFactor/i3 *\n             (3 * m1 * magnitude z1 * i3 * p1 * cos angleDiff - 2 * i1 * magnitude z3 * p3 * (3 * m2 + m1))\n      v1 = cis(\u03c91 * dt)\n      v3 = cis(\u03c93 * dt)\n      pCommonFactor = 6 * magnitude (z1 / z3) * i3 * \u03c91 * \u03c93 * sin angleDiff\n      p1' = (-pCommonFactor) - g * (m1/2 + m2) * magnitude z1 * cos(phase z1)\n      p3' = pCommonFactor - g * m2 * magnitude z3 / 2 * cos(phase z3)\n   in A.lift\n        ( (z1 * v1, z3 * v3),\n          (p1 + p1' * dt, p3 + p3' * dt)\n        )\n  where\n    absSquared z = real (z * conjugate z)\n    inertia z m = m * absSquared z / 12\n\ninited ::\n  (RealFrac a, A.RealFloat a, Elt a) =>\n  Int ->\n  Exp (Pair (Complex a)) ->\n  Acc (Vector (Pendulum (Pair (Complex a)) (Pair a)))\ninited frames zs = A.fill (A.constant $ Z :. 1) $ A.lift (zs, zero)\n\ncompute ::\n  (RealFrac a, A.RealFloat a, Elt a) =>\n  ( Exp (Pendulum (Pair (Complex a)) (Pair a)) ->\n    Exp (Pendulum (Pair (Complex a)) (Pair a))\n  ) ->\n  Acc (Vector (Pendulum (Pair (Complex a)) (Pair a))) ->\n  Acc (Vector (Pendulum (Pair (Complex a)) (Pair a)))\ncompute calc mat =\n  let n = indexHead $ A.shape mat\n      last = A.replicate (A.constant $ Z :. 1 :: Exp (Z :. Int)) $ A.slice mat (A.lift $ Z :. n - 1)\n      new = A.map calc last\n   in mat A.++ new\n\ncomputation ::\n  forall a.\n  (RealFrac a, A.RealFloat a, Elt a) =>\n  Int ->\n  Acc (Vector (Pendulum (Pair (Complex a)) (Pair a))) ->\n  ( Acc (Vector (Pendulum (Pair (Complex a)) (Pair a))) ->\n    Acc (Vector (Pendulum (Pair (Complex a)) (Pair a)))\n  ) ->\n  Exp (Pair (Complex a)) ->\n  Acc (Vector (Pair (Complex a)))\ncomputation frames inited compute zs =\n  A.map mapper ran\n  where\n    pred mat =\n      let (A.unlift -> Z :. i :: Z :. Exp Int) = A.shape mat\n          in A.unit $ i A.< A.constant frames\n\n    mapper :: Exp (Pendulum (Pair (Complex a)) (Pair a)) -> Exp (Pair (Complex a))\n    mapper (A.unlift -> pendulum :: Pendulum (Exp (Pair (Complex a))) (Exp (Pair a))) =\n      let (z, _) = pendulum\n       in z\n\n    ran :: Acc (Vector (Pendulum (Pair (Complex a)) (Pair a)))\n    ran = A.awhile pred compute inited\n\nsimulatePendulums ::\n  (RealFrac a, A.RealFloat a, Elt a) =>\n  (C.Complex a, a) ->\n  (C.Complex a, a) ->\n  a ->\n  a ->\n  [Pair (C.Complex a)]\nsimulatePendulums (z1, m1) (z2, m2) t dt = A.toList $ run computation'\n  where\n    frames = ceiling $ t / dt\n    zs = A.constant (z1, z2)\n    calc' = calc (A.constant m1) (A.constant m2) (A.constant dt)\n    inited' = inited frames zs\n    compute' = compute calc'\n    computation' = computation frames inited' compute' zs\n\nskip :: Int\nskip = 2\n\npaint :: Double -> (Int, Pair (Complex Double)) -> IO ()\npaint m (i, (z1@(x1 C.:+ y1), z2@(x2 C.:+ y2))) =\n  when (mod i skip == 0) $ do\n    putStrLn $ \"z1 = \" ++ show z1\n    putStrLn $ \"z2 = \" ++ show z2\n    let side = 2000 :: Int\n        width = 15\n        x1' = realToFrac $ (fromIntegral side / 2) * (1 + x1 / m)\n        y1' = realToFrac $ (fromIntegral side / 2) * (1 - y1 / m)\n        x2' = realToFrac $ (fromIntegral side / 2) * (1 + (x2 + x1) / m)\n        y2' = realToFrac $ (fromIntegral side / 2) * (1 - (y2 + y1) / m)\n        bg = PixelRGBA8 0x0c 0x0a 0x20 255\n        lineColor = PixelRGBA8 0xdf 0x85 0xff 255\n        img = renderDrawing side side bg $\n          withTexture (uniformTexture lineColor) $ do\n            stroke width JoinRound (CapRound, CapRound) $\n              line\n                (V2 (fromIntegral side / 2) (fromIntegral side / 2))\n                (V2 x1' y1')\n                ++ line (V2 x1' y1') (V2 x2' y2')\n    writePng (printf \"results/double-pendulum-%05v.png\" $ div i skip) img\n\nmain :: IO ()\nmain = do\n  let z1 = C.cis (pi/4) :: Complex Double\n      z2 = C.cis (pi/4) :: Complex Double\n      list = zip [0 ..] $ simulatePendulums\n                            (z1, 1) (z2, 1)\n                            (50 * fromIntegral skip) (1 / (60 * fromIntegral skip))\n  forM_ list $ paint $ C.magnitude z1 + C.magnitude z2\n", "meta": {"hexsha": "2c48fb653439eefaad613b63ee707b6652093f83", "size": 5939, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Main.hs", "max_stars_repo_name": "LuigiPiucco/mnc-ifsc", "max_stars_repo_head_hexsha": "325e0f3a805d8405c2eb030ed338917c6c55cb25", "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": "Main.hs", "max_issues_repo_name": "LuigiPiucco/mnc-ifsc", "max_issues_repo_head_hexsha": "325e0f3a805d8405c2eb030ed338917c6c55cb25", "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": "Main.hs", "max_forks_repo_name": "LuigiPiucco/mnc-ifsc", "max_forks_repo_head_hexsha": "325e0f3a805d8405c2eb030ed338917c6c55cb25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6134020619, "max_line_length": 107, "alphanum_fraction": 0.5628893753, "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4234295066831888}}
{"text": "{-# LANGUAGE MultiParamTypeClasses #-}\nmodule ChaosBox.Geometry.Class\n  ( Boundary(..)\n  , HasP2(..)\n  , Intersects(..)\n  , getP2\n  , setP2\n  , modifyP2\n  )\nwhere\n\nimport           ChaosBox.Geometry.P2\nimport           Control.Lens         (Lens', lens, (%~), (&), (.~), (^.))\nimport           Data.Complex\nimport           Linear.V2\n\n-- | Class of objects that can be queried for points\nclass Boundary a where\n  containsPoint :: a -> P2 -> Bool\n\nclass HasP2 a where\n  _V2 :: Lens' a P2\n\ninstance HasP2 P2 where\n  _V2 = _xy\n\ninstance HasP2 (Complex Double) where\n  _V2 = lens (\\(a :+ b) -> V2 a b) (\\_ (V2 x y) -> x :+ y)\n\ngetP2 :: HasP2 a => a -> P2\ngetP2 = (^. _V2)\n\nsetP2 :: HasP2 a => a -> P2 -> a\nsetP2 x p2 = x & _V2 .~ p2\n\nmodifyP2 :: HasP2 a => a -> (P2 -> P2) -> a\nmodifyP2 x f = x & _V2 %~ f\n\nclass Intersects a b where\n  intersectionPoints :: a -> b -> [P2]\n  intersects :: a -> b -> Bool\n  intersects a b = null (intersectionPoints a b)\n", "meta": {"hexsha": "5f39a34630faecbbcbeb272c0ba5be25af158480", "size": 949, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ChaosBox/Geometry/Class.hs", "max_stars_repo_name": "akrmn/chaosbox", "max_stars_repo_head_hexsha": "5dbb20bfdfc61e05da1c1890718ef542a2f61be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 59, "max_stars_repo_stars_event_min_datetime": "2018-09-16T00:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T21:02:36.000Z", "max_issues_repo_path": "src/ChaosBox/Geometry/Class.hs", "max_issues_repo_name": "akrmn/chaosbox", "max_issues_repo_head_hexsha": "5dbb20bfdfc61e05da1c1890718ef542a2f61be0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2020-03-18T23:22:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-14T09:43:11.000Z", "max_forks_repo_path": "src/ChaosBox/Geometry/Class.hs", "max_forks_repo_name": "akrmn/chaosbox", "max_forks_repo_head_hexsha": "5dbb20bfdfc61e05da1c1890718ef542a2f61be0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-09-16T00:52:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:05:47.000Z", "avg_line_length": 22.0697674419, "max_line_length": 74, "alphanum_fraction": 0.574288725, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.42317243431359514}}
{"text": "{-# LANGUAGE ForeignFunctionInterface #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module     : Foreign.BLAS.Zomplex\n-- Copyright  : Copyright (c) 2010, Patrick Perry <patperry@gmail.com>\n-- License    : BSD3\n-- Maintainer : Patrick Perry <patperry@gmail.com>\n-- Stability  : experimental\n--\n\nmodule Foreign.BLAS.Zomplex \n    where\n\nimport Data.Complex( Complex )\nimport Foreign\nimport Foreign.BLAS.Types\nimport Foreign.C.Types\n\n#include \"config.h\"\n#include \"f77_func-hsc.h\"\n#define la_int int\n\n---------------------------- Level 1 Routines -------------------------------\n\nforeign import ccall unsafe #f77_func zdotu\n    zdotu :: Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zdotc\n    zdotc :: Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\n\nforeign import ccall unsafe #f77_func dznrm2\n    znrm2  :: Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO Double\n\nforeign import ccall unsafe #f77_func dzasum\n    zasum  :: Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO Double\n\nforeign import ccall unsafe #f77_func izamax\n    izamax_hidden :: Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO CInt \nizamax :: Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO LAInt    \nizamax a b c = do \n                res <- izamax_hidden a b c \n                return $! LAInt res \n\n\nforeign import ccall unsafe #f77_func zscal\n    zscal  :: Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zswap\n    zswap  :: Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zcopy\n    zcopy  :: Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zaxpy\n    zaxpy  :: Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zrotg\n    zrotg  :: Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr (Complex Double) -> IO ()\n\nforeign import ccall unsafe #f77_func zdrot\n    zdrot :: Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr Double -> Ptr Double -> IO ()\n\n\n---------------------------- Level 2 Routines -------------------------------\n\nforeign import ccall unsafe #f77_func zgemv\n    zgemv :: BLASTrans -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zgbmv\n    zgbmv ::  BLASTrans -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func ztrmv\n    ztrmv ::  BLASUplo -> BLASTrans -> BLASDiag -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func ztpmv\n    ztpmv ::  BLASUplo -> BLASTrans -> BLASDiag -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func ztpsv\n    ztpsv ::  BLASUplo -> BLASTrans -> BLASDiag -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func ztbmv\n    ztbmv ::  BLASUplo -> BLASTrans -> BLASDiag -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n                 \nforeign import ccall unsafe #f77_func ztrsv\n    ztrsv ::  BLASUplo -> BLASTrans -> BLASDiag -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func ztbsv\n    ztbsv ::  BLASUplo -> BLASTrans -> BLASDiag -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n    \nforeign import ccall unsafe #f77_func zhemv\n    zhemv ::  BLASUplo -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zhbmv\n    zhbmv ::  BLASUplo -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n    \nforeign import ccall unsafe #f77_func zgeru\n    zgeru  ::  Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zgerc\n    zgerc  ::  Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n        \nforeign import ccall unsafe #f77_func zher\n    zher  ::  BLASUplo -> Ptr LAInt -> Ptr Double -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zher2\n    zher2 ::  BLASUplo -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zhpmv\n    zhpmv ::  BLASUplo -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zhpr\n    zhpr  ::  BLASUplo -> Ptr LAInt -> Ptr Double -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> IO ()\n\nforeign import ccall unsafe #f77_func zhpr2\n    zhpr2 ::  BLASUplo -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> IO ()\n\n\n---------------------------- Level 3 Routines -------------------------------\n\nforeign import ccall unsafe #f77_func zgemm\n    zgemm  ::  BLASTrans -> BLASTrans -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zsymm\n    zsymm  ::  BLASSide -> BLASUplo -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zhemm\n    zhemm  ::  BLASSide -> BLASUplo -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func ztrmm\n    ztrmm  ::  BLASSide -> BLASUplo -> BLASTrans -> BLASDiag -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func ztrsm\n    ztrsm  ::  BLASSide -> BLASUplo -> BLASTrans -> BLASDiag -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zsyrk\n    zsyrk  ::  BLASUplo -> BLASTrans -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n           \nforeign import ccall unsafe #f77_func zsyr2k           \n    zsyr2k ::  BLASUplo -> BLASTrans -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n\nforeign import ccall unsafe #f77_func zherk\n    zherk  ::  BLASUplo -> BLASTrans -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n           \nforeign import ccall unsafe #f77_func zher2k           \n    zher2k ::  BLASUplo -> BLASTrans -> Ptr LAInt -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr LAInt -> Ptr (Complex Double) -> Ptr (Complex Double) -> Ptr LAInt -> IO ()\n", "meta": {"hexsha": "c9be38aef8d7a860bd419b0ace3ba727580e42b4", "size": 8719, "ext": "hsc", "lang": "Haskell", "max_stars_repo_path": "lib/Foreign/BLAS/Zomplex.hsc", "max_stars_repo_name": "cartazio/hs-cblas", "max_stars_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-01-19T00:43:25.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-14T16:18:59.000Z", "max_issues_repo_path": "lib/Foreign/BLAS/Zomplex.hsc", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Foreign/BLAS/Zomplex.hsc", "max_forks_repo_name": "cartazio/hs-cblas", "max_forks_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.3129251701, "max_line_length": 244, "alphanum_fraction": 0.6351645831, "num_tokens": 2469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.42218294760581426}}
{"text": "{-# LANGUAGE DataKinds, FlexibleContexts, FlexibleInstances, GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses, TypeFamilies                   #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n-- | This Library provides some *dangerous* instances for @Double@s and @Complex@.\nmodule Algebra.Instances () where\nimport Algebra.Scalar\n\nimport           AlgebraicPrelude\nimport           Control.DeepSeq       (NFData (..))\nimport           Control.Monad.Random  (Random (..), getRandom)\nimport           Control.Monad.Random  (getRandomR, runRand)\nimport           Data.Complex          (Complex (..))\nimport           Data.Convertible.Base (Convertible (..))\nimport qualified Data.Ratio            as P\nimport qualified Data.Vector           as DV\nimport           Data.Vector.Instances ()\nimport qualified Numeric.Algebra       as NA\nimport qualified Prelude               as P\n\ninstance Additive r => Additive (DV.Vector r) where\n  (+) = DV.zipWith (+)\n\n-- | These Instances are not algebraically right, but for the sake of convenience.\ninstance DecidableZero r => DecidableZero (Complex r) where\n  isZero (a :+ b) = isZero a && isZero b\n\ninstance (NFData a) => NFData (Fraction a) where\n  rnf a = rnf (numerator a) `seq` rnf (denominator a) `seq` ()\n\ninstance Additive r => Additive (Complex r) where\n  (a :+ b) + (c :+ d) = (a + c) :+ (b + d)\ninstance Abelian r => Abelian (Complex r) where\ninstance (Group r, Semiring r) => Semiring (Complex r) where\ninstance (Group r, Rig r) => Rig (Complex r) where\n  fromNatural = (:+ zero) . fromNatural\ninstance (Group r, Commutative r) => Commutative (Complex r) where\ninstance Ring r => Ring (Complex r) where\n  fromInteger = (:+ zero) . fromInteger'\ninstance Group r => Group (Complex r) where\n  (a :+ b) - (c :+ d) = (a - c) :+ (b - d)\n  negate (a :+ b) = negate a :+ negate b\n  times n (a :+ b) = times n a :+ times n b\ninstance LeftModule a r => LeftModule a (Complex r) where\n  r .* (a :+ b) = (r .* a) :+ (r .* b)\ninstance RightModule a r => RightModule a (Complex r) where\n  (a :+ b) *. r = (a *. r) :+ (b *. r)\ninstance Monoidal r => Monoidal (Complex r) where\n  zero = zero :+ zero\ninstance (Group r, Monoidal r, Unital r) => Unital (Complex r) where\n  one = one :+ zero\ninstance Additive Double where\n  (+) = (P.+)\ninstance (Group r, Multiplicative r) => Multiplicative (Complex r) where\n  (a :+ b) * (c :+ d) = (a*c - b*d) :+ (a*d + b*c)\ninstance LeftModule Natural Double where\n  n .* d = fromIntegral n P.* d\ninstance RightModule Natural Double where\n  d *. n = d P.* fromIntegral n\ninstance Monoidal Double where\n  zero = 0\ninstance Unital Double where\n  one = 1\ninstance Multiplicative Double where\n  (*) = (P.*)\ninstance Commutative Double where\ninstance Group Double where\n  (-) = (P.-)\n  negate = P.negate\n  subtract = P.subtract\n  times n r = P.fromIntegral n P.* r\ninstance LeftModule Integer Double where\n  n .* r = P.fromInteger n * r\ninstance RightModule Integer Double where\n  r *. n = r * P.fromInteger n\ninstance Rig Double where\n  fromNatural = P.fromInteger . fromNatural\ninstance Semiring Double where\ninstance Abelian Double where\ninstance Ring Double where\n  fromInteger = P.fromInteger\ninstance DecidableZero Double where\n  isZero 0 = True\n  isZero _ = False\n\ninstance Division Double where\n  recip = P.recip\n  (/)   = (P./)\n\ninstance P.Integral r => Additive (P.Ratio r) where\n  (+) = (P.+)\n\ninstance P.Integral r => Abelian (P.Ratio r)\n\ninstance P.Integral r => LeftModule Natural (P.Ratio r) where\n  n .* r = fromIntegral n P.* r\n\ninstance P.Integral r => RightModule Natural (P.Ratio r) where\n  r *. n = r P.* fromIntegral n\n\ninstance P.Integral r => LeftModule Integer (P.Ratio r) where\n  n .* r = P.fromInteger n P.* r\n\ninstance P.Integral r => RightModule Integer (P.Ratio r) where\n  r *. n = r P.* P.fromInteger n\n\ninstance P.Integral r => Group (P.Ratio r) where\n  (-)    = (P.-)\n  negate = P.negate\n  subtract = P.subtract\n  times n r = P.fromIntegral n P.* r\n\ninstance P.Integral r => Commutative (P.Ratio r)\n\ninstance (Semiring r, P.Integral r) => LeftModule (Scalar r) (P.Ratio r) where\n  Scalar n .* r = (n P.% 1) * r\n\ninstance (Semiring r, P.Integral r) => RightModule (Scalar r) (P.Ratio r) where\n  r *. Scalar n = r * (n P.% 1)\n\ninstance P.Integral r => Multiplicative (P.Ratio r) where\n  (*) = (P.*)\n\ninstance P.Integral r => Unital (P.Ratio r) where\n  one = 1\n\ninstance P.Integral r => Division (P.Ratio r) where\n  (/) = (P./)\n  recip = P.recip\n\ninstance P.Integral r => Monoidal (P.Ratio r) where\n  zero = 0\n\ninstance P.Integral r => Semiring (P.Ratio r)\n\ninstance P.Integral r => Rig (P.Ratio r) where\n  fromNatural = P.fromIntegral\n\ninstance P.Integral r => Ring (P.Ratio r) where\n  fromInteger = P.fromInteger\n\ninstance P.Integral r => DecidableZero (P.Ratio r) where\n  isZero 0 = True\n  isZero _ = False\n\ninstance P.Integral r => DecidableUnits (P.Ratio r) where\n  isUnit 0 = False\n  isUnit _ = True\n  recipUnit 0 = Nothing\n  recipUnit n = Just (P.recip n)\n  r ^? n\n    | r == 0 = Just 1\n    | r /= 0 = Just (r P.^^ n)\n    | r == 0 && n P.> 0 = Just 0\n    | otherwise = Nothing\n\ninstance Convertible (Fraction Integer) Double where\n  safeConvert a = Right $ P.fromInteger (numerator a) P./ P.fromInteger (denominator a)\n\ninstance Convertible (Fraction Integer) (Complex Double) where\n  safeConvert a = Right $ P.fromInteger (numerator a) P./ P.fromInteger (denominator a) :+ 0\n\ninstance (Random (Fraction Integer)) where\n  random = runRand $ do\n    i <- getRandom\n    j <- getRandom\n    return $ i % (P.abs j + 1)\n  randomR (a, b) = runRand $ do\n    j <- succ . P.abs <$> getRandom\n    let g = foldl1 P.lcm  [denominator a, denominator b, j]\n        lb = g * numerator a `quot` denominator a\n        ub = g * numerator b `quot` denominator b\n    i <- getRandomR (lb, ub)\n    return $ i % g\n", "meta": {"hexsha": "36cc3667c6f55eb4e2b5b0ad7e9e872d8a6bc795", "size": 5777, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "halg-core/src/Algebra/Instances.hs", "max_stars_repo_name": "hangingman/computational-algebra", "max_stars_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-02-09T01:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:37:09.000Z", "max_issues_repo_path": "halg-core/src/Algebra/Instances.hs", "max_issues_repo_name": "hangingman/computational-algebra", "max_issues_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2017-09-18T16:31:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T08:28:37.000Z", "max_forks_repo_path": "halg-core/src/Algebra/Instances.hs", "max_forks_repo_name": "hangingman/computational-algebra", "max_forks_repo_head_hexsha": "1c5b5b2ca4f3e0e54391206b95bb2d474f5834a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-12-22T16:04:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T19:35:53.000Z", "avg_line_length": 33.2011494253, "max_line_length": 92, "alphanum_fraction": 0.6498182448, "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.42166545924257326}}
{"text": "{-# LANGUAGE FlexibleContexts           #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE RecordWildCards            #-}\n{-# LANGUAGE ScopedTypeVariables        #-}\n{-# LANGUAGE StandaloneDeriving         #-}\n\nmodule Main (main)\nwhere\n\nimport           Phase\nimport           Random\n\nimport           Control.Monad                     as CM\nimport qualified Control.Monad.Log                 as ML\nimport           Control.Monad.Random\nimport qualified Control.Monad.State.Strict        as MS\nimport           Data.Complex\nimport qualified Data.List                         as L\nimport qualified Data.Massiv.Array                 as A\nimport qualified Data.Massiv.Array.Manifest.Vector as AMV\nimport qualified Data.MultiSet                     as M\nimport qualified Data.Vector.Unboxed               as V\nimport           Numeric\nimport           Prelude                           as P\nimport           System.Console.ANSI\nimport           System.Environment\nimport           System.TimeIt\n\n-- | a vector of multiplication phases; should be kept sorted\ntype PhaseVector = A.Array A.U A.Ix1 Phase\n\n-- | the massiv computation strategy to use throughout\nstrat :: A.Comp\nstrat = A.Par\n\nfromVector :: Vector Phase -> PhaseVector\nfromVector vec = AMV.fromVector' strat (A.Sz1 (V.length vec)) vec\n\n-- | a tuple of phase vectors to be collimated\ntype PVTuple = (PhaseVector, PhaseVector)\n\n-- what LoggingT couldn't\nderiving instance (MonadRandom m) => MonadRandom (ML.LoggingT message m)\n\n-- | the base-2 logarithm\nlog2 :: Integral a => a -> Double\nlog2 = logBase (2 :: Double) . fromIntegral\n\n-- | for convenience\nlog2rnd :: Integral a => a -> Int\nlog2rnd  = round . log2\n\ndot :: Num a => [a] -> [a] -> a\ndot [] _          = 0\ndot _ []          = 0\ndot (x:xs) (y:ys) = x*y + dot xs ys\n\n---------- COLLIMATION ----------\n\ndata CollimateInfo = SI { s     :: !Phase, lReq :: !Int,\n                          lReal :: !Int,   kept :: !Bool }\n\ninstance Show CollimateInfo where\n  show SI{..} =\n    let lRatio = fromIntegral lReal / fromIntegral lReq :: Double\n    in \"(~2^\" P.++ show (log2rnd s) P.++\n       \",\" P.++ show lReq P.++\n       \",\" P.++ show lReal P.++\n       \",\" P.++ showFFloat (Just 2) lRatio\n       (if not kept then \" DISCARDED\" else \"\") P.++ \")\"\n\ncollimateInfoHandler :: MonadIO m\n                     => Int     -- | number of bottom sieve layers to suppress\n                     -> [Phase] -- | list of intervals sizes for sieve\n                     -> CollimateInfo\n                     -> m ()\ncollimateInfoHandler skip ss =\n  let len = P.length ss in \\si@SI{..} ->\n    let i' = L.elemIndex s ss\n    in maybe (return ())\n       (\\i -> when (i < len - skip) $ liftIO $ do\n           setSGR [SetColor Foreground (if i < 7 then Vivid else Dull)\n                   (toEnum (i `mod` 7 + 1))]\n           putStrLn $ P.concat (P.replicate i \"  \") P.++ show si\n           setSGR [Reset]) i'\n\n-- | all the mod-@n@ subset-sums of a vector. Results are not\n-- necessarily sorted!\nsubsetSums :: Vector Phase -> Vector Phase\nsubsetSums v =\n  V.generate (2^V.length v) (go 0 0) where\n  go i acc s\n    | i >= V.length v = acc\n    | otherwise = go (i+1) (acc + if odd s then v V.! i else 0) (s `div` 2)\n\n-- | choose a random phase multiplier from the given phase vector\nrandomElt :: MonadRandom m => PhaseVector -> m Phase\nrandomElt v =  (v A.!) <$> getRandomR (0, A.elemsCount v - 1)\n\n-- | the first index (in a sorted vector) of an element that is /at\n-- least/ @a@, or 'length v' if none exists\nfindAtLeast :: PhaseVector -> Phase -> Int\nfindAtLeast v a = go 0 (A.elemsCount v) where\n  go i j | i == j         = i\n         | (v A.! i) >= a = i\n         -- don't use i+j `div` 2, to avoid overflow on big arrays\n         | otherwise      = let k = i + ((j - i) `div` 2)\n                            in if (v A.! k) >= a then go i k else go (k+1) j\n\n-- | collimate phase vectors\ncollimate :: (MonadRandom m)\n          => Phase              -- | desired interval size S (upper bound)\n          -> PVTuple            -- | phase vectors to collimate\n          -> m PhaseVector\ncollimate s (v1,v2) = do\n  b1 <- randomElt v1\n  b2 <- randomElt v2\n  let q = (b1 + b2) `div` s\n      qs = q*s\n      start i1 = (i1, findAtLeast v2 (qs - (v1 A.! i1)))\n      gen (i1,i2)\n        | i1 >= A.elemsCount v1 = Nothing\n        | i2 >= A.elemsCount v2 = gen $ start (i1+1)\n        | v < qs + s            = Just (v `mod` s, (i1, i2+1))\n        | otherwise             = gen $ start (i1+1)\n        where v = (v1 A.! i1) + (v2 A.! i2)\n      -- Create a Vector because massiv doesn't supported\n      -- unknown-length unfoldr.\n  return $ A.quicksort $ fromVector $ V.unfoldr gen (start 0)\n\n---------- SIEVE ----------\n\ndata SieveState = SS { numQueries :: !Int, maxLength    :: !Int,\n                       numNodes   :: !Int, numDiscarded :: !Int}\n  deriving (Show, Eq)\n\nnewSieveState :: SieveState\nnewSieveState = SS 0 0 0 0\n\naddQueries :: Int -> SieveState -> SieveState\naddQueries i ss@SS{..} = ss { numQueries = numQueries + i }\n\nupdateLength :: Int -> SieveState -> SieveState\nupdateLength l ss@SS{..} = ss { maxLength = max l maxLength }\n\nincrementNodes :: SieveState -> SieveState\nincrementNodes ss@SS{..} = ss { numNodes = succ numNodes }\n\nincrementDiscarded :: SieveState -> SieveState\nincrementDiscarded ss@SS{..} = ss { numDiscarded = succ numDiscarded }\n\n-- | Collimation sieve.\nsieve :: (MonadRandom m, ML.MonadLog CollimateInfo m,\n          MS.MonadState SieveState m)\n      => Phase   -- | group order N\n      -> Double  -- | threshold factor for long-enough phase vectors\n      -> [Phase] -- | increasing interval sizes S_i for the i'th level\n                 -- of the sieve; the final one should equal N\n      -> Int     -- | desired phase vector length L\n      -> m PhaseVector\nsieve = sieve' True where       -- don't discard final output\n  sieve' _ _ _ [] _ = error \"sieve: empty list of interval sizes\"\n  sieve' alwaysKeep n threshold ss@(s:ss') l\n    | s >= n = do\n        let logl = log2rnd l\n        v <- (A.quicksort . fromVector . V.map (`mod` n)) . subsetSums <$>\n          -- create a Vector because massiv doesn't support monadic replicate\n             V.replicateM logl (getRandomR (0,n-1))\n        ML.logMessage (SI s l (A.elemsCount v) True)\n        MS.modify'   incrementNodes\n        MS.modify' $ addQueries logl\n        MS.modify' $ updateLength (A.elemsCount v)\n        return v\n    | otherwise =\n        let s' = P.head ss'\n            z  = 1.5 * fromIntegral l * fromIntegral s' / fromIntegral s :: Double\n            l' = ceiling $ sqrt z\n        in do v1   <- sieve' False n threshold ss' l'\n              v2   <- sieve' False n threshold ss' $\n                      ceiling (z / fromIntegral (A.elemsCount v1))\n              v    <- collimate s (v1,v2)\n              let vlen = A.elemsCount v\n                  -- check if vector is long enough to be useful\n                  keep = alwaysKeep ||\n                         fromIntegral vlen / fromIntegral l >= threshold\n              ML.logMessage (SI s l vlen keep)\n              MS.modify' incrementNodes\n              if keep\n                then MS.modify' (updateLength vlen) >> return v\n                else MS.modify' incrementDiscarded >> sieve' False n threshold ss l\n\n-- | histogram of (n, # multipliers appearing n times) in a phase\n-- vector for a (final, small) interval [S]\nhistogram :: Int -> Vector Int -> [(Int,Int)]\nhistogram s v =\n  let occurs = fmap snd $ M.toOccurList $ M.fromList $ V.toList v\n      num    = P.length occurs\n      hist   = L.sortOn fst $ M.toOccurList $ M.fromList occurs\n  in if s == num then hist else (0, s - num) : hist\n\nchi :: Double -> Complex Double\nchi = cis . (2.0 * pi *)\n\nsquare :: Num a => a -> a\nsquare x = x*x\n\n-- | partition a phase vector into one consisting of its unique phase\n-- multipliers, and one containing all the leftovers.\npuncture :: PhaseVector -> (PhaseVector, PhaseVector)\npuncture v =\n  let v' = AMV.toVector v\n      u' = V.uniq v'\n      gen i\n        | i >= V.length v' = Nothing\n        | v' V.! (i-1) == v' V.! i = Just (v' V.! i, i+1)\n        | otherwise = gen $ i+1\n  in (fromVector u', fromVector $ V.unfoldr gen 1)\n\nunfold :: (b -> (a,b)) -> b -> [a]\nunfold f b = let (a,b') = f b in a : unfold f b'\n\n-- | probability assigned to \\( w \\), given by \\( \\theta = s/N - w/T\n-- \\), by the \\( T \\)-dimensional inverse-QFT of the given punctured\n-- phase vector on \\( [T] \\).\nprobTheta :: Int                -- | range \\( [T] \\) of phase vector\n          -> PhaseVector        -- | uniquified phase vector\n          -> Double             -- | \\( \\theta \\)\n          -> Double\nprobTheta t v theta =\n  square (magnitude $ A.sum $ A.map (chi . (* theta) . fromIntegral) v) /\n  (fromIntegral t * fromIntegral (A.elemsCount v))\n\n-- | probability that the \\( T \\)-dimensional inverse-QFT on the given\n-- punctured phase vector on \\( [T] \\) will output some \\( w \\in\n-- \\lfloor sT/N \\rceil - \\{ - \\lfloor z/2 \\rfloor, \\ldots, \\lfloor\n-- (z-1)/2 \\rfloor \\} \\), given the (essentially uniform) shift \\(\n-- sT/N \\bmod 1 \\in [-1/2,1/2) \\).  Assumes that (\\ z \\) is positive\n-- and small enough not to double-count probabilities.\nprobClosest :: Int               -- | \\( T \\)\n            -> Double            -- | \\( sT/N \\bmod 1 \\in [-1/2,1/2) \\)\n            -> PhaseVector       -- | uniquified phase vector\n            -> Int               -- | number \\( z \\) of closest to count\n            -> Double\nprobClosest t shift v z =\n  let thetas = A.makeArrayR A.D strat (A.Sz1 z)\n               (\\(A.Ix1 i) -> (shift + fromIntegral (i - z `div` 2))\n                              / fromIntegral t)\n  in A.sum $ A.map (probTheta t v) thetas\n\nmain :: IO ()\nmain = do\n  args <- getArgs\n  let (params,rest) = splitAt 3 args\n      [logn :: Int, logl, logs] = read <$> params\n      threshold = if null rest then 0.25 :: Double else read (head rest)\n      n     = if logn > 0\n              then 2^logn\n                   -- from https://eprint.iacr.org/2019/498.pdf\n              else 3 * 37 * 1407181 * 51593604295295867744293584889 *\n                   31599414504681995853008278745587832204909\n      l     = 2^logl\n      s     = 2^logs\n      ss    = P.takeWhile (< n)\n              (iterate (\\t -> (2 * t * fromIntegral l) `div` 3) $ fromIntegral s)\n              P.++ [n]\n\n  -- print schedule of log interval sizes\n  putStrLn $ \"log S's = \" P.++ show (log2rnd <$> ss)\n\n  -- run the sieve\n  (time, (v, sieveState@SS{..})) <- timeItT $\n    evalCryptoRandIO\n    (flip ML.runLoggingT (collimateInfoHandler (min 5 (P.length ss - 1)) ss)\n     (flip MS.runStateT newSieveState (sieve n threshold ss l)))\n\n  -- print results\n\n  -- parameters again, for convenience\n  putStrLn $ \"\\n[log N, log L, log S_0] = \" P.++\n    show [logn, logl, logs]\n\n  putStrLn $ \"threshold = \" P.++ showFFloat (Just 2) threshold \"\"\n\n  -- log interval sizes again, for convenience\n  putStrLn $ \"\\nlog S's = \" P.++ show (log2rnd <$> ss)\n\n  putStrLn $ \"\\nSieve summary = \" P.++ show sieveState\n\n  -- compute number of queries according to model\n  let delta = fromIntegral numDiscarded / fromIntegral numNodes :: Double\n      depth = P.length ss - 1\n      l' = sqrt $ 1.5 * fromIntegral l * fromIntegral n /\n           fromIntegral (ss P.!! (P.length ss - 2)) :: Double\n      modelQueries = (2.0 / (1-delta))^depth * logBase 2 l'\n\n  putStrLn $ \"\\nProbability of discarding = \" P.++ showFFloat (Just 4) delta \"\"\n\n  putStrLn $ (P.++) \"\\nNumber of queries actual/modeled = \" $ (P.++)\n    (show numQueries)                $ (P.++) \"/\" $\n    showFFloat (Just 1) modelQueries $ (P.++) \" ~= \" $\n    showFFloat (Just 2) (fromIntegral numQueries / modelQueries) \"\"\n\n  -- compute probability of obtaining a regular state\n  let hist = histogram s $ V.map fromIntegral $ AMV.toVector v\n      num  = s * fst (P.head hist)\n      den  = A.elemsCount v\n      probRegular = fromIntegral num / fromIntegral den :: Double\n\n  putStrLn $ \"\\nProbability of obtaining a regular state = \" P.++\n    show num P.++ \"/\" P.++ show den P.++ \" ~= \" P.++\n    showFFloat (Just 3) probRegular \"\"\n\n  -- compute probabilities of getting punctured regular states, and close\n  shift :: Double <- getRandomR (-0.5, 0.5)\n  let punctureds = takeWhile ((> 2^(logs - 6)) . A.elemsCount) $\n                   unfold puncture v\n      puncturedProbs :: [Double] =\n        (/ fromIntegral den) . fromIntegral . A.elemsCount <$> punctureds\n      closest = [1,2,4,8]       -- how many of the closest w to check\n      closestProbs = map (<$> closest) (probClosest s shift <$> punctureds)\n      totalClosestProbs = dot puncturedProbs <$> L.transpose closestProbs\n\n  putStrLn $ (P.++) \"\\nProbability of obtaining each punctured state (1st, 2nd, ... attempt) =\\n\" $\n    L.intercalate \", \" $ mapM (showFFloat (Just 3)) puncturedProbs \"\"\n\n  putStrLn $ (P.++) \"\\nProbability bounds for each punctured state for \" $\n    (P.++) (show closest) $ (P.++) \" closest w = \\n\" $\n    L.intercalate \"\\n\" $ L.intercalate \", \" <$>\n    (mapM . mapM) (showFFloat (Just 3)) closestProbs \"\"\n\n  putStrLn $ (P.++) \"\\nTotal probability bounds for \" $\n    (P.++) (show closest) $ (P.++) \" closest w = \\n\" $\n    L.intercalate \", \" $ mapM (showFFloat (Just 3)) totalClosestProbs \"\"\n\n  putStrLn $ (P.++) \"\\nLaTeX table row:\\n\" $\n    showFFloat (Just 1) (log2 n)                          $ (P.++) \" & \" $\n    showFFloat (Just 1) (log2 numQueries)                 $ (P.++) \" & \" $\n    showFFloat (Just 1) (logBase 2 modelQueries)          $ (P.++) \" & \" $\n    showFFloat (Just 1) (log2 maxLength)                  $ (P.++) \" & \" $\n    (P.++) (show logl)                                    $ (P.++) \" & \" $\n    (P.++) (show logs)                                    $ (P.++) \" & \" $\n    showFFloat (Just 0) (probRegular * 100)               $ (P.++) \" & \" $\n    showFFloat (Just 1) (fromIntegral logs * probRegular) $ (P.++) \" & \" $\n    showFFloat (Just 2) threshold                         $ (P.++) \" & \" $\n    showFFloat (Just 1) (delta * 100)                     $ (P.++) \" & \" $\n    (P.++) (show depth)                                   $ (P.++) \" & \" $\n    showFFloat (Just 1) (time / 3600) \" \\\\\\\\\"\n\n", "meta": {"hexsha": "2854fc0ab55a5db7c2bcc63833e12dd036cdadf3", "size": 14113, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "cpeikert/CollimationSieve", "max_stars_repo_head_hexsha": "6f9188e4eb5611bcfdf29a3e1ec3cd69a29a50e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-06-18T21:57:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T21:55:16.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "cpeikert/CollimationSieve", "max_issues_repo_head_hexsha": "6f9188e4eb5611bcfdf29a3e1ec3cd69a29a50e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "cpeikert/CollimationSieve", "max_forks_repo_head_hexsha": "6f9188e4eb5611bcfdf29a3e1ec3cd69a29a50e9", "max_forks_repo_licenses": ["BSD-3-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.4383954155, "max_line_length": 99, "alphanum_fraction": 0.5557996174, "num_tokens": 4107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4216207393249934}}
{"text": "{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE BangPatterns #-}\nmodule Polestar.Type where\nimport Data.Complex\nimport Data.Monoid\nimport Data.Ord\n\n-- variable name (for debugging)\nnewtype Id = Id String deriving (Show)\n\n-- ordering: s <: t implies s < t\ndata PrimType\n  -- numeric types\n  = PTyZero\n  | PTyNat\n  | PTyInt\n  | PTyNNReal -- non-negative real number\n  | PTyReal\n  | PTyImaginary\n  | PTyComplex\n  -- boolean\n  | PTyTrue\n  | PTyFalse\n  | PTyBool\n  -- other\n  | PTyUnit\n  deriving (Eq,Ord,Show,Enum,Bounded)\n\ndata Type = TyPrim !PrimType\n          | TyArr Type Type\n          | TyAll Id !(Maybe Type) Type\n          | TyRef !Int\n          | TyTuple [Type] -- must have 2 or more elements\n          | TyInter [Type] -- must have 2 or more elements\n          deriving (Eq,Show)\n\npattern TyZero = TyPrim PTyZero\npattern TyNat = TyPrim PTyNat\npattern TyInt = TyPrim PTyInt\npattern TyNNReal = TyPrim PTyNNReal\npattern TyReal = TyPrim PTyReal\npattern TyImaginary = TyPrim PTyImaginary\npattern TyComplex = TyPrim PTyComplex\npattern TyTrue = TyPrim PTyTrue\npattern TyFalse = TyPrim PTyFalse\npattern TyBool = TyPrim PTyBool\npattern TyUnit = TyPrim PTyUnit\npattern TyPair a b = TyTuple [a,b]\n\n-- compound canonical type\n-- no pair of the components have subtyping relation\ntype CanonicalType = [ICanonicalType]\n\n-- individual canonical type\ndata ICanonicalType = CTyPrim !PrimType\n                    | CTyArr CanonicalType ICanonicalType\n                    | CTyAll Id CanonicalType ICanonicalType\n                    | CTyRef !Int\n                    | CTyTuple [ICanonicalType]\n                    deriving (Eq,Show)\n\npattern CTyTrue = CTyPrim PTyTrue\npattern CTyFalse = CTyPrim PTyFalse\npattern CTyBool = CTyPrim PTyBool\n\ndata Builtin\n  -- unary\n  = BNegate\n  | BLogicalNot\n  | BNatToInt\n  | BNatToNNReal\n  | BIntToNat -- max(n,0)\n  | BIntToReal\n  | BNNRealToReal\n  | BRealToComplex\n  | BMkImaginary\n  | BImaginaryToComplex\n  | BRealPart\n  | BImagPart\n  | BAbs\n  | BSqrt\n  | BExp\n  | BExpm1\n  | BLog\n  | BLog1p\n  | BSin\n  | BCos\n  | BTan\n  | BSinh\n  | BCosh\n  | BTanh\n  | BAsin\n  | BAcos\n  | BAtan\n  | BAsinh\n  | BAcosh\n  | BAtanh\n  -- TODO: factorial\n  -- TODO: exp, log, expm1, log1p\n  -- TODO: trigonometric functions and hyperbolic functions\n  -- binary\n  | BAdd\n  | BSub\n  | BMul\n  | BDiv\n  | BPow\n  | BTSubNat -- truncated subtraction\n  | BLt\n  | BLe\n  | BEqual\n  | BMax\n  | BMin\n  | BIntDiv\n  | BIntMod\n  | BGcd\n  | BLcm\n  | BLogicalAnd\n  | BLogicalOr\n  -- TODO: binomial coefficients\n  -- other primitives\n  | BIterate\n  -- | BUnsafeGlue\n  deriving (Eq,Show,Enum,Bounded)\n\ndata PrimValue = PVZero\n               | PVInt !Integer\n               | PVReal !Double\n               | PVImaginary !Double\n               | PVComplex !(Complex Double)\n               | PVBool !Bool\n               | PVUnit\n               | PVBuiltin !Builtin\n               deriving (Eq,Show)\n\ndata Term = TmPrim !PrimValue             -- primitive value\n          | TmAbs Id Type Term            -- lambda abstraction\n          | TmTyAbs Id !(Maybe Type) Term -- bounded type abstraction\n          | TmRef !Int                    -- variable (de Bruijn index)\n          | TmApp Term Term               -- function application\n          | TmTyApp Term Type             -- type application\n          | TmLet Id Term Term            -- let-in\n          | TmAlt Id [Type] Term          -- type alternation\n          | TmIf Term Term Term           -- if-then-else\n          | TmTuple [Term]                -- tuple\n          | TmProj Term !Int              -- projection\n          | TmCoerce Term Type            -- coercion\n          | TmCoherentTuple [Term]        -- coherent tuple\n          deriving (Eq,Show)\n\ndata Binding = VarBind Id CanonicalType\n             | TyVarBind Id CanonicalType\n             | AnonymousBind\n             deriving (Eq,Show)\n\nisUnary :: Builtin -> Bool\nisUnary f = case f of\n  BNegate -> True\n  BLogicalNot -> True\n  BNatToInt -> True\n  BNatToNNReal -> True\n  BIntToNat -> True\n  BIntToReal -> True\n  BNNRealToReal -> True\n  BRealToComplex -> True\n  BMkImaginary -> True\n  BImaginaryToComplex -> True\n  BRealPart -> True\n  BImagPart -> True\n  BAbs -> True\n  BSqrt -> True\n  BExp -> True\n  BExpm1 -> True\n  BLog -> True\n  BLog1p -> True\n  BSin -> True\n  BCos -> True\n  BTan -> True\n  BSinh -> True\n  BCosh -> True\n  BTanh -> True\n  BAsin -> True\n  BAcos -> True\n  BAtan -> True\n  BAsinh -> True\n  BAcosh -> True\n  BAtanh -> True\n  _ -> False\n\nisBinary :: Builtin -> Bool\nisBinary f = case f of\n  BAdd -> True\n  BSub -> True\n  BMul -> True\n  BDiv -> True\n  BPow -> True\n  BTSubNat -> True\n  BLt -> True\n  BLe -> True\n  BEqual -> True\n  BMax -> True\n  BMin -> True\n  BIntDiv -> True\n  BIntMod -> True\n  BGcd -> True\n  BLcm -> True\n  BLogicalAnd -> True\n  BLogicalOr -> True\n  _ -> False\n\nisValue :: Term -> Bool\nisValue t = case t of\n  TmPrim _ -> True\n  TmAbs _ _ _ -> True\n  TmTyAbs _ _ _ -> True\n  TmApp (TmPrim (PVBuiltin f)) x | isBinary f -> isValue x -- partial application\n  TmTyApp (TmPrim (PVBuiltin BIterate)) ty -> True\n  TmApp (TmTyApp (TmPrim (PVBuiltin BIterate)) ty) x -> isValue x\n  TmApp (TmApp (TmTyApp (TmPrim (PVBuiltin BIterate)) ty) x) y -> isValue x && isValue y\n  TmTuple xs -> all isValue xs\n  TmCoherentTuple xs -> all isValue xs\n  _ -> False\n\ngetCTypeFromContext :: [Binding] -> Int -> CanonicalType\ngetCTypeFromContext ctx i\n  | 0 <= i && i < length ctx = case ctx !! i of\n      VarBind _ ty -> ty\n      b -> error (\"TmRef: expected a variable binding, found \" ++ show b)\n  | otherwise = error \"TmRef: index out of bounds\"\n\ngetTypeFromContext :: [Binding] -> Int -> Type\ngetTypeFromContext ctx i = canonicalToOrdinary $ getCTypeFromContext ctx i\n\ngetCBoundFromContext :: [Binding] -> Int -> CanonicalType\ngetCBoundFromContext ctx i\n  | i < length ctx = case ctx !! i of\n                       TyVarBind _ b -> b\n                       b -> error (\"TyRef: expected a type variable binding, found \" ++ show b)\n  | otherwise = error \"TyRef: index out of bounds\"\n\ngetBoundFromContext :: [Binding] -> Int -> Maybe Type\ngetBoundFromContext ctx i = canonicalToOrdinaryM $ getCBoundFromContext ctx i\n\ntypeShift :: Int -> Int -> Type -> Type\n-- typeShift 0 _ ty = ty\ntypeShift !delta = go\n  where\n    go !i ty = case ty of\n      TyPrim _ -> ty\n      TyArr u v -> TyArr (go i u) (go (i + 1) v)\n      TyAll name b t -> TyAll name (typeShift delta i <$> b) (typeShift delta (i + 1) t)\n      TyRef j | j >= i, j + delta >= 0 -> TyRef (j + delta)\n              | j >= i, j + delta < 0 -> error \"typeShift: negative index\"\n              | otherwise -> ty\n      TyTuple tys -> TyTuple $ map (go i) tys\n      TyInter tys -> TyInter $ map (go i) tys\n\ntypeShiftC :: Int -> Int -> CanonicalType -> CanonicalType\n-- typeShiftC 0 _ = id\ntypeShiftC !delta !i = map (typeShiftI delta i)\n\ntypeShiftI :: Int -> Int -> ICanonicalType -> ICanonicalType\ntypeShiftI !delta = go\n  where\n    go :: Int -> ICanonicalType -> ICanonicalType\n    go !i ty = case ty of\n      CTyPrim _ -> ty\n      CTyArr u v -> CTyArr (map (go i) u) (go (i + 1) v)\n      CTyAll name b t -> CTyAll name (map (go i) b) (go (i + 1) t)\n      CTyRef j | j >= i, j + delta >= 0 -> CTyRef (j + delta)\n               | j >= i, j + delta < 0 -> error \"typeShift: negative index\"\n               | otherwise -> ty\n      CTyTuple tys -> CTyTuple $ map (go i) tys\n\ntypeSubstD :: Int -> Type -> Int -> Type -> Type\ntypeSubstD !depth s !i ty = case ty of\n  TyPrim _ -> ty\n  TyArr u v -> TyArr (typeSubstD depth s i u) (typeSubstD (depth + 1) s (i + 1) v)\n  TyAll name b t -> TyAll name (typeSubstD depth s i <$> b) (typeSubstD (depth + 1) s (i + 1) t)\n  TyRef j | j == i -> typeShift depth 0 s\n          | j > i -> TyRef (j - 1)\n          | otherwise -> ty\n  TyTuple tys -> TyTuple $ map (typeSubstD depth s i) tys\n  TyInter tys -> TyInter $ map (typeSubstD depth s i) tys\n\ntypeSubst = typeSubstD 0\n\ntypeSubstCD :: Int -> CanonicalType -> Int -> ICanonicalType -> CanonicalType\ntypeSubstCD !depth s !i ty = case ty of\n  CTyPrim _ -> return ty\n  CTyArr u v -> CTyArr (u >>= typeSubstCD depth s i) <$> typeSubstCD (depth + 1) s (i + 1) v\n  CTyAll name b t -> CTyAll name (b >>= typeSubstCD depth s i) <$> typeSubstCD (depth + 1) s (i + 1) t\n  CTyRef j | j == i -> typeShiftC depth 0 s\n           | j > i -> return $ CTyRef (j - 1)\n           | otherwise -> return ty\n  CTyTuple tys -> CTyTuple <$> mapM (typeSubstCD depth s i) tys\n\ntypeSubstC = typeSubstCD 0\n\ncanonicalToOrdinary :: CanonicalType -> Type\ncanonicalToOrdinary [] = error \"canonicalToOrdinary: Top type\"\ncanonicalToOrdinary [t] = iCanonicalToOrdinary t\ncanonicalToOrdinary tys = TyInter $ map iCanonicalToOrdinary tys\n\ncanonicalToOrdinaryM :: CanonicalType -> Maybe Type\ncanonicalToOrdinaryM [] = Nothing\ncanonicalToOrdinaryM [t] = Just $ iCanonicalToOrdinary t\ncanonicalToOrdinaryM tys = Just $ TyInter $ map iCanonicalToOrdinary tys\n\niCanonicalToOrdinary :: ICanonicalType -> Type\niCanonicalToOrdinary (CTyPrim p) = TyPrim p\niCanonicalToOrdinary (CTyArr u v) = TyArr (canonicalToOrdinary u) (iCanonicalToOrdinary v)\niCanonicalToOrdinary (CTyAll name b t) = TyAll name (canonicalToOrdinaryM b) (iCanonicalToOrdinary t)\niCanonicalToOrdinary (CTyRef i) = TyRef i\niCanonicalToOrdinary (CTyTuple tys) = TyTuple $ map iCanonicalToOrdinary tys\n\n\ninstance Eq Id where\n  _ == _ = True\n\n{-\ninstance Ord ICanonicalType where\n  compare (CTyPrim p) (CTyPrim p') = compare p p'\n  compare (CTyArr s t) (CTyArr s' t') = compare (Down s) (Down s') <> compare t t'\n  compare (CTyAll _ s t) (CTyAll _ s' t') = compare (Down s) (Down s') <> compare t t'\n  compare (CTyRef i) (CTyRef i') = compare i i'\n  compare (CTyTuple tys) (CTyTuple tys') = compare tys tys'\n  compare (CTyPrim _) _ = LT\n  compare _ (CTyPrim _) = GT\n  compare (CTyArr _ _) _ = LT\n  compare _ (CTyArr _ _) = GT\n  compare (CTyAll _ _ _) _ = LT\n  compare _ (CTyAll _ _ _) = GT\n  compare (CTyRef _) _ = LT\n  compare _ (CTyRef _) = GT\n  -- compare (CTyTuple _) _ = LT\n  -- compare _ (CTyTuple _) = GT\n-}\n", "meta": {"hexsha": "3e0287906de3dc5d35b15e5f065a10a02ce0ff29", "size": 9986, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Polestar/Type.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/Type.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/Type.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": 29.5443786982, "max_line_length": 102, "alphanum_fraction": 0.6215701983, "num_tokens": 3248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.42130531534750904}}
{"text": "module Numeric.LinearAlgebra.Matrix\n( module C\n, module M44\n, module M33\n, Mat44\n, Mat33\n) where\n\nimport Numeric.LinearAlgebra.Matrix.Class as C\nimport Numeric.LinearAlgebra.Matrix.Mat44 as M44 hiding (Mat44(..))\nimport Numeric.LinearAlgebra.Matrix.Mat44 (Mat44)\nimport Numeric.LinearAlgebra.Matrix.Mat33 as M33 hiding (Mat33(..))\nimport Numeric.LinearAlgebra.Matrix.Mat33 (Mat33)\n\n", "meta": {"hexsha": "f50ada14f207ae1c345f35168d94d3ba1a478b8d", "size": 382, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/Matrix.hs", "max_stars_repo_name": "dagit/lin-alg", "max_stars_repo_head_hexsha": "b7c189573015871953c41f0b1fed4c8a73c081aa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T07:25:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:25:33.000Z", "max_issues_repo_path": "src/Numeric/LinearAlgebra/Matrix.hs", "max_issues_repo_name": "dagit/lin-alg", "max_issues_repo_head_hexsha": "b7c189573015871953c41f0b1fed4c8a73c081aa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearAlgebra/Matrix.hs", "max_forks_repo_name": "dagit/lin-alg", "max_forks_repo_head_hexsha": "b7c189573015871953c41f0b1fed4c8a73c081aa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4666666667, "max_line_length": 67, "alphanum_fraction": 0.7905759162, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.42114852107188677}}
{"text": "module QIO.Circuit.Compile where\n\nimport qualified QIO.Circuit.Circuit as C\n\nimport Data.Complex\nimport QIO.QioSyn\nimport QIO.Qio\n\ncompileCircuit :: C.Circuit -> QIO [Bool]\ncompileCircuit circuit = do\n  qs <- mkQbits (length $ C.qubits circuit) False\n  applyU (gatesToU (C.gates circuit) qs)\n  measQbits qs\n\ngatesToU :: [C.Gate] -> [Qbit] -> U\ngatesToU [] _      = mempty\ngatesToU (g:gs) qs = (gateToU g qs) <> (gatesToU gs qs)\n\ngateToU :: C.Gate -> [Qbit] -> U\ngateToU (C.Had _ qis) qs         = condU uhad $ map (\\i -> qs !! i) qis\ngateToU (C.PX _ qis) qs          = condU unot $ map (\\i -> qs !! i) qis\ngateToU (C.PY _ qis) qs          = condU (\\q -> rot q yRot) $ map (\\i -> qs !! i) qis\n                                   where\n                                     yRot (False, True) = 0 :+ 1\n                                     yRot (True, False) = 0 :+ (-1)\n                                     yRot _             = 0\ngateToU (C.PZ _ qis) qs          = condU (\\q -> uphase q pi) $ map (\\i -> qs !! i) qis\ngateToU (C.Swap _ (q1:q2:[])) qs = swap (qs !! q1) (qs !! q2)\ngateToU _ _                      = mempty\n\nmkQbits :: Int -> Bool -> QIO [Qbit]\nmkQbits n b = mkQbits' n b []\n  where\n    mkQbits' 0 _ qs = return qs\n    mkQbits' n b qs = do\n      q <- mkQbit b\n      mkQbits' (n-1) b (qs ++ [q])\n\nmeasQbits :: [Qbit] -> QIO [Bool]\nmeasQbits qs = measQbits' qs []\n  where\n    measQbits' [] bs = return bs\n    measQbits' (q:qs) bs = do\n      b <- measQbit q\n      measQbits' qs (bs ++ [b])\n\ncondU :: (Qbit -> U) -> [Qbit] -> U\ncondU u (ql:[]) = u ql\ncondU u (q:qs)  = cond q (\\x -> if x then (condU u qs) else mempty)\n", "meta": {"hexsha": "8f5efafb30f562ad03ee17b613d1528c8511de30", "size": 1625, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "QIO/Circuit/Compile.hs", "max_stars_repo_name": "psycjw/qio", "max_stars_repo_head_hexsha": "b00584c9bda732fb8454e1520618decee968819d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-10-01T11:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T19:27:22.000Z", "max_issues_repo_path": "QIO/Circuit/Compile.hs", "max_issues_repo_name": "psycjw/qio", "max_issues_repo_head_hexsha": "b00584c9bda732fb8454e1520618decee968819d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QIO/Circuit/Compile.hs", "max_forks_repo_name": "psycjw/qio", "max_forks_repo_head_hexsha": "b00584c9bda732fb8454e1520618decee968819d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-22T17:11:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T17:11:13.000Z", "avg_line_length": 32.5, "max_line_length": 86, "alphanum_fraction": 0.5083076923, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4211192346252086}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\nimport Numeric.LinearAlgebra\nimport Control.DeepSeq\nimport Control.Concurrent\nimport Control.Monad\nimport Control.Exception\nimport System.Mem\nimport Control.Concurrent.Async\nimport System.Environment\n\nmain :: IO ()\nmain = do\n  [matSizeS] <- getArgs\n  let matSize = read matSizeS\n  let gcs = do\n        performMinorGC\n        performMajorGC\n        threadDelay 1000\n  caps <- getNumCapabilities\n  void $ concurrently gcs $ flip mapConcurrently [1..caps] $ \\i0 -> do\n    let matrices :: Int -> [Matrix Double]\n        matrices i = if i == 10000\n          then matrices (-10000)\n          else let\n            a :: Matrix Double = (matSize >< matSize) (take (matSize * matSize) [fromIntegral i..])\n            in a : matrices (i+1)\n    forM_ (matrices i0) $ \\a -> do\n      let (l, m, r) = svd a\n      evaluate (force (l <> diagRect 0 m matSize matSize <> tr r))\n", "meta": {"hexsha": "b7c70b07505bfbd27869b3d0ac972a574a49b8af", "size": 915, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "bitonic/hmatrix-nasal-demons", "max_stars_repo_head_hexsha": "8c3892c9d8a7e0dddf9839f11b0740135e6c0882", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "bitonic/hmatrix-nasal-demons", "max_issues_repo_head_hexsha": "8c3892c9d8a7e0dddf9839f11b0740135e6c0882", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "bitonic/hmatrix-nasal-demons", "max_forks_repo_head_hexsha": "8c3892c9d8a7e0dddf9839f11b0740135e6c0882", "max_forks_repo_licenses": ["BSD-3-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.59375, "max_line_length": 99, "alphanum_fraction": 0.6480874317, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.420897071582223}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE NoStarIsType          #-}\n{-# LANGUAGE OverloadedLabels      #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE PolyKinds             #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n\nimport           Control.Monad\nimport           System.Random.MWC\n\nimport           Data.Constraint              (Dict (..))\nimport           Data.List                    (zipWith5)\nimport           Data.Proxy\nimport           Data.Reflection\nimport           Data.Singletons\nimport           Data.Singletons.TypeLits     hiding (natVal)\nimport           GHC.TypeLits\nimport           Unsafe.Coerce                (unsafeCoerce)\n\nimport           Numeric.LinearAlgebra.Static (L, R)\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport           Criterion.Main\n\nimport           Grenade\nimport           Grenade.Utils.LinearAlgebra\nimport           Grenade.Utils.ListStore\n\nmain :: IO ()\nmain = do\n  defaultMain\n    [ bgroup\n        \"batchnorm forward (CxHxW)\"\n        [ benchBatchNorm \"1x1x64\" 1 1 64\n        , benchBatchNorm \"1x64x64\" 1 64 64\n        , benchBatchNorm \"64x64x64\" 64 64 64\n        ]\n    , bgroup\n        \"convolutions with bias (CxHxW)\"\n        [ benchBiasConvolution \"1024x64x64, 125 kernels\" 1024 64 64 125 1 1 64 64\n        , benchBiasConvolution \"3x416x416, 64 kernels\" 3 416 416 64 2 1 208 208\n        ]\n    , bgroup\n        \"leaky relu (CxHxW)\"\n        [ benchLeakyRelu \"3x416x416\" 3 416 416\n        , benchLeakyRelu \"1024x16x16\" 1024 16 16\n        ]\n    ]\n\n-- BENCHMARK GENERATION FUNCTIONS\n\nbenchBiasConvolution :: String -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Benchmark\nbenchBiasConvolution name channels width height filters strides kernels outWidth outHeight\n  | strides * (outHeight - 1) <= (height - kernels + 1) - 1 && (height - kernels + 1) <= (outHeight * strides) && strides * (outWidth - 1) <= (width - kernels + 1) - 1 && (width - kernels + 1) <= (outWidth * strides)\n      = case (someNatVal (fromIntegral channels), someNatVal (fromIntegral width), someNatVal (fromIntegral height), someNatVal (fromIntegral filters), someNatVal (fromIntegral strides), someNatVal (fromIntegral kernels), someNatVal (fromIntegral outWidth), someNatVal (fromIntegral outHeight)) of\n          (Just (SomeNat (Proxy :: Proxy channels)), Just (SomeNat (Proxy :: Proxy width)), Just (SomeNat (Proxy :: Proxy height)), Just (SomeNat (Proxy :: Proxy filters)), Just (SomeNat (Proxy :: Proxy strides)), Just (SomeNat (Proxy :: Proxy kernels)), Just (SomeNat (Proxy :: Proxy outWidth)), Just (SomeNat (Proxy :: Proxy outHeight))) ->\n            case (channels, width, height\n                 , (unsafeCoerce (Dict :: Dict ()) :: Dict ( strides * (outHeight - 1) <= (height - kernels) ) )\n                 , (unsafeCoerce (Dict :: Dict ()) :: Dict ( (height - kernels) <= (outHeight * strides) - 1 ) )\n                 , (unsafeCoerce (Dict :: Dict ()) :: Dict ( strides * (outWidth - 1) <= (width - kernels ) ) )\n                 , (unsafeCoerce (Dict :: Dict ()) :: Dict ( (width - kernels) <= (outWidth * strides) - 1 ) ) ) of\n              (1, 1, _, _, _, _, _)\n                -> error \"1D convolutions are not allowed\"\n              (1, _, _, Dict, Dict, Dict, Dict)\n                -> env (generateBiasConvEnv :: IO (Convolution 'WithBias 'NoPadding 1 filters kernels kernels strides strides, S ('D2 height width))) $ \\ ~(layer, x) -> bench name $ nf (snd . runForwards layer :: S ('D2 height width) -> S ('D3 outHeight outWidth filters )) x\n              (_, _, _, Dict, Dict, Dict, Dict)\n                -> env (generateBiasConvEnv :: IO (Convolution 'WithBias 'NoPadding channels filters kernels kernels strides strides, S ('D3 height width channels))) $ \\ ~(layer, x) -> bench name $ nf (snd . runForwards layer :: S ('D3 height width channels) -> S ('D3 outHeight outWidth filters)) x\n  where\n    generateBiasConvEnv :: forall channels filters kernel1 kernel2 strides1 strides2 s.\n                            ( SingI s, KnownNat channels, KnownNat filters, KnownNat kernel1, KnownNat kernel2,\n                              KnownNat strides1, KnownNat strides2 )\n                            => IO (Convolution 'WithBias 'NoPadding channels filters kernel1 kernel2 strides1 strides2, S s)\n    generateBiasConvEnv = do\n      x     <- randomOfShape\n      gen   <- createSystemRandom\n      layer <- createRandomWith UniformInit gen\n      return (layer, x)\n\nbenchBatchNorm :: String -> Int -> Int -> Int -> Benchmark\nbenchBatchNorm name channels width height\n  = case (someNatVal (fromIntegral channels), someNatVal (fromIntegral width), someNatVal (fromIntegral height)) of\n          (Just (SomeNat (Proxy :: Proxy channels)), Just (SomeNat (Proxy :: Proxy width)), Just (SomeNat (Proxy :: Proxy height))) ->\n            case (channels, width, height) of\n              (1, 1, _) -> env (generateBatchNormEnv False :: IO (BatchNorm 1 1 width 90, S ('D1 width))) $ \\ ~(layer, x) -> bench name $ nf (snd . runForwards layer :: S ('D1 width) -> S ('D1 width)) x\n              (1, _, _) -> env (generateBatchNormEnv False :: IO (BatchNorm 1 width height 90, S ('D2 width height))) $ \\ ~(layer, x) -> bench name $ nf (snd . runForwards layer :: S ('D2 width height) -> S ('D2 width height)) x\n              (_, _, _) -> env (generateBatchNormEnv False :: IO (BatchNorm channels width height 90, S ('D3 width height channels))) $ \\ ~(layer, x) -> bench name $ nf (snd . runForwards layer :: S ('D3 width height channels) -> S ('D3 width height channels)) x\n  where\n    generateBatchNormEnv :: forall c h w s. (KnownNat c, KnownNat h, KnownNat w, SingI s)\n                         => Bool -> IO (BatchNorm c h w 90, S s)\n    generateBatchNormEnv training = do\n      x     <- randomOfShape\n      gens  <- replicateM 4 createSystemRandom\n      seeds <- mapM uniform gens :: IO [Int]\n      let [gamma, beta, running_mean, running_var] = map (\\s -> H.randomVector s H.Uniform) seeds :: [R c]\n          \u03b5            = 0.00001\n      return (BatchNorm training (BatchNormParams gamma beta) running_mean running_var \u03b5 mkListStore, x)\n\nbenchLeakyRelu :: String -> Int -> Int -> Int -> Benchmark\nbenchLeakyRelu name channels width height\n  = case (someNatVal (fromIntegral channels), someNatVal (fromIntegral width), someNatVal (fromIntegral height)) of\n          (Just (SomeNat (Proxy :: Proxy channels)), Just (SomeNat (Proxy :: Proxy width)), Just (SomeNat (Proxy :: Proxy height))) ->\n            case (channels, width, height) of\n              (1, 1, _) -> env (generateLeakyReluEnv :: IO (LeakyRelu, S ('D1 width))) $ \\ ~(layer, x) -> bench name $ nf (snd . runForwards layer :: S ('D1 width) -> S ('D1 width)) x\n              (1, _, _) -> env (generateLeakyReluEnv :: IO (LeakyRelu, S ('D2 width height))) $ \\ ~(layer, x) -> bench name $ nf (snd . runForwards layer :: S ('D2 width height) -> S ('D2 width height)) x\n              (_, _, _) -> env (generateLeakyReluEnv :: IO (LeakyRelu, S ('D3 width height channels))) $ \\ ~(layer, x) -> bench name $ nf (snd . runForwards layer :: S ('D3 width height channels) -> S ('D3 width height channels)) x\n  where\n    generateLeakyReluEnv :: forall s. (SingI s) => IO (LeakyRelu, S s)\n    generateLeakyReluEnv = do\n      x     <- randomOfShape\n      gen   <- createSystemRandom\n      alpha <- uniformR (-1, 1) gen :: IO RealNum\n      return (LeakyRelu alpha, x)", "meta": {"hexsha": "f0f248e9abf029eb3739631b8948f5d2f2071444", "size": 7782, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/bench-layers.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": "bench/bench-layers.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": "bench/bench-layers.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": 63.2682926829, "max_line_length": 342, "alphanum_fraction": 0.6081984066, "num_tokens": 2078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.420485513331455}}
{"text": "{-|\nType aliases for activation functions and their derivative.\n-}\nmodule ML.NN.ActivationFunction (ActivationFunction, ActivationFunctionDerivative) where\n\nimport Numeric.LinearAlgebra (R)\n\n-- | An activation function for a neuron.\ntype ActivationFunction = R -> R\n\n-- | The derivative of a neuron activation function.\ntype ActivationFunctionDerivative = R -> R\n", "meta": {"hexsha": "44efe8b53cdf05abfa299e06ad0fc9c9c20da3b8", "size": 363, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ML/NN/ActivationFunction.hs", "max_stars_repo_name": "m-renaud/ML", "max_stars_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-15T16:13:43.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-15T16:13:43.000Z", "max_issues_repo_path": "src/ML/NN/ActivationFunction.hs", "max_issues_repo_name": "m-renaud/ML", "max_issues_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ML/NN/ActivationFunction.hs", "max_forks_repo_name": "m-renaud/ML", "max_forks_repo_head_hexsha": "7fb9fdac687cd76528d6b3d9080030a0723b01ca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9230769231, "max_line_length": 88, "alphanum_fraction": 0.7851239669, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4204504014449288}}
{"text": "{-# LANGUAGE TypeApplications #-}\nmodule Main where\n\nimport Config\nimport File\n\nimport Statistics.Distribution\nimport Statistics.Distribution.Empirical\nimport Statistics.Distribution.Normal\n\nimport Data.List\nimport Data.Yaml\n\nimport Text.Printf\n\nimport Debug.Trace\n\n\nmain :: IO ()\nmain = do\n  -- YAML setup\n  yml <- decodeFileEither \"splits.yaml\"\n\n  f <- case yml of\n         Right (Config _ levels) -> load levels\n         Left  _ -> load'\n\n  let l = 1\n      (Just distrs) = lookup l $ levelEmpiricalDistribution f\n      (Just level) = fmap (sort . map realToFrac) . lookup l $ onlyValidSplits $ levelData f\n      elems = [0, 0.01..0.99]\n      dens = 1 / (fromIntegral $ length level)\n      domain = reverse [1.0, 1.0 - dens..dens]\n\n      vec = zipWith Vector2 level domain\n\n      vecs = zip4 vec (drop 1 vec) (drop 2 vec) (drop 3 vec)\n\n      vals = concat $ [ [ let (Vector2 x y) = centripetalInterpolate v m in (x, y) | m <- elems ] | v <- vecs ]\n\n      (xs, ys) = unzip vals\n\n      test = zipWith (\\(x1, y1) (x2, y2) -> (abs $ 1 / (y2 - y1)) * (x2 - x1)) vals $ tail vals\n      (dx, dy) = unzip $ zipWith (\\(x1, y1) (x2, y2) -> (,) (x2 - x1) (y2 - y1)) vals $ tail vals\n\n  mapM_ putStrLn $ zipWith5 (printf \"%f %f %f %f %f\") xs ys dx dy test\n\n\nlinearInterpolate :: (Double, Double) -> Double -> Double\nlinearInterpolate (lRange, uRange) m =\n  let notM = 1 - m\n  in lRange * notM + uRange * m\n\nhermiteInterpolate :: (Double, Double, Double, Double) -> Double -> Double\nhermiteInterpolate (y0, y1, y2, y3) mu =\n  let mu2 = mu * mu\n      a0 = (-0.5) * y0 + 1.5 * y1 - 1.5 * y2 + 0.5 * y3\n      a1 = y0 - 2.5 * y1 + 2 * y2 - 0.5 * y3\n      a2 = (-0.5) * y0 + 0.5 * y2\n      a3 = y1\n  in a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3\n\ncentripetalInterpolate (p0, p1, p2, p3) mu =\n  let t0 = 0\n      t1 = getT t0 p0 p1\n      t2 = getT t1 p1 p2\n      t3 = getT t2 p2 p3\n\n      t = linearInterpolate (t1, t2) mu\n\n      a1 = vscale ((t1 - t) / (t1 - t0)) p0 + vscale ((t - t0) / (t1 - t0)) p1\n      a2 = vscale ((t2 - t) / (t2 - t1)) p1 + vscale ((t - t1) / (t2 - t1)) p2\n      a3 = vscale ((t3 - t) / (t3 - t2)) p2 + vscale ((t - t2) / (t3 - t2)) p3\n\n      b1 = vscale ((t2 - t) / (t2 - t0)) a1 + vscale ((t - t0) / (t2 - t0)) a2\n      b2 = vscale ((t3 - t) / (t3 - t1)) a2 + vscale ((t - t1) / (t3 - t1)) a3\n  in vscale ((t2 - t) / (t2 - t1)) b1 + vscale ((t - t1) / (t2 - t1)) b2\n  where getT tn (Vector2 x1 y1) (Vector2 x2 y2) = tn + ((sqrt $ (x2 - x1) ^ 2 + (y2 - y1) ^ 2) ** alpha)\n        alpha = 0.5\n\n\ntype Scalar = Double\n\nclass Vector v where\n  vmap  :: (Scalar -> Scalar) -> v -> v\n  vzip  :: (Scalar -> Scalar -> Scalar) -> v -> v -> v\n  vfold :: (x -> Scalar -> x) -> x -> v -> x\n\nvdot :: Vector v => v -> v -> Scalar\nvdot v0 v1 = vfold (+) 0 $ vzip (*) v0 v1\n\nvmag_sqr :: Vector v => v -> Scalar\nvmag_sqr v = v `vdot` v\n\nvmag :: Vector v => v -> Scalar\nvmag = sqrt . vmag_sqr\n\nvscale :: Vector v => Scalar -> v -> v\nvscale s = vmap (s*)\n\nvunit :: Vector v => v -> v\nvunit v =\n  if vmag v == 0\n    then v\n    else vscale (1 / vmag v) v\n\n\ndata Vector2 = Vector2 {v2x, v2y :: Scalar} deriving (Eq)\n\ninstance Show Vector2 where\n  show (Vector2 x y) = \"<\" ++ (show x) ++ \", \" ++ (show y) ++ \">\"\n\ninstance Vector Vector2 where\n  vmap  f   (Vector2 x y) = Vector2 (f x) (f y)\n  vfold f i (Vector2 x y) = (i `f` x) `f` y\n  vzip  f   (Vector2 x0 y0) (Vector2 x1 y1) = Vector2 (f x0 x1) (f y0 y1)\n\ninstance Num Vector2 where\n  (+) = vzip (+)\n  (-) = vzip (-)\n  (*) = vzip (*)\n  negate = vmap negate\n  fromInteger s = Vector2 (fromInteger s) (fromInteger s)\n\ninstance Fractional Vector2 where\n  (/) = vzip (/)\n  fromRational s = let r = realToFrac s in Vector2 r r\n", "meta": {"hexsha": "89574a0f136da8bbe92257fd3a29525aff548874", "size": 3657, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "distr-test/Main.hs", "max_stars_repo_name": "argiopetech/timer", "max_stars_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distr-test/Main.hs", "max_issues_repo_name": "argiopetech/timer", "max_issues_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-29T16:51:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-29T16:51:58.000Z", "max_forks_repo_path": "distr-test/Main.hs", "max_forks_repo_name": "argiopetech/timer", "max_forks_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "max_forks_repo_licenses": ["BSD-3-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.5703125, "max_line_length": 111, "alphanum_fraction": 0.554279464, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4203797896058491}}
{"text": "{-# LANGUAGE BangPatterns #-}\n\nimport Gauge.Main (defaultMain, bench, whnf)\n\nimport Data.Int (Int64)\nimport Data.List (unfoldr)\nimport Data.Maybe (fromJust)\nimport Data.Primitive.Contiguous (PrimArray, fromListN)\nimport Statistics.Array.Types (AscList)\nimport System.Random (random, mkStdGen)\n\nimport qualified Data.Primitive as PM\nimport qualified Statistics.Array as Stats\nimport qualified Statistics.Array.Types as Asc\n\nmain :: IO ()\nmain = defaultMain\n  [ bench \"sort-16\" $ whnf fromAscInt input16\n  , bench \"sort-128\" $ whnf fromAscInt input128\n  , bench \"sort-1024\" $ whnf fromAscInt input1024\n  , bench \"sort-65536\" $ whnf fromAscInt input65536\n  , bench \"list-derivative\" $ whnf performListDerivativeInt asc1024\n  , bench \"median-of-absolute-deviations\" $ whnf Stats.mad asc1024\n  ]\n  where\n  input16, input128, input1024, input65536 :: PrimArray Int64\n  !input16 = fromListN 16 $ take 16 . drop 0 $ inputInf\n  !input128 = fromListN 128 $ take 128 . drop 16 $ inputInf\n  !input1024 = fromListN 1024 $ take 1024 . drop (16+128) $ inputInf\n  !input65536 = fromListN 65536 $ take 65536 . drop (16+128+1024) $ inputInf\n  asc1024 :: AscList Int64\n  asc1024 = fromJust $ Asc.fromArray input1024\n\nfromAscInt :: PrimArray Int64 -> Int64\n{-# noinline fromAscInt #-}\nfromAscInt !x = case Asc.fromArray x of\n  Nothing -> 0\n  Just (Asc.AscList y) -> fromIntegral (PM.sizeofPrimArray y)\n\n-- This is here to make it easy to inspect Core to confirm that specialization\n-- works correctly. \nperformListDerivativeInt :: AscList Int64 -> PrimArray Int64\n{-# noinline performListDerivativeInt #-}\nperformListDerivativeInt !x = Stats.listDerivative x\n\ninputInf :: [Int64]\ninputInf = unfoldr (Just . random) seed\n  where\n  seed = mkStdGen 1234567\n", "meta": {"hexsha": "5ecdff7e279b1698bdabf7cec70f3564f748234b", "size": 1734, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/Main.hs", "max_stars_repo_name": "Zankoku-Okuno/array-statistics", "max_stars_repo_head_hexsha": "25b520ff7fa7a463ee0708fb50772d54253a0767", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/Main.hs", "max_issues_repo_name": "Zankoku-Okuno/array-statistics", "max_issues_repo_head_hexsha": "25b520ff7fa7a463ee0708fb50772d54253a0767", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/Main.hs", "max_forks_repo_name": "Zankoku-Okuno/array-statistics", "max_forks_repo_head_hexsha": "25b520ff7fa7a463ee0708fb50772d54253a0767", "max_forks_repo_licenses": ["BSD-3-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.68, "max_line_length": 78, "alphanum_fraction": 0.7433679354, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.420311379817292}}
{"text": "module GApprox\n  (\n    GApprox (..)\n  , createGApprox\n  , predictG\n  , updateG\n  ) where\n\n-- Wrapper for HNN's Neural network module\n-- Using it for function approximation while in simulation -> wrapper supports creation,\n-- prediction, and update.\n-- Usecase: Predict 1 -> update 1 -> predict 1 -> update 1\n\n-- Goal -> understand library enough to support a CCEA approach (ie, be able to mutate the\n-- weights). It seems like there is a load from weight matrix function, so should involve just\n-- creating a Network -> Weight matrix function.\n\nimport AI.HNN.FF.Network\nimport Numeric.LinearAlgebra\nimport Policy\n\ndata GApprox = GApprox (IO (Network Double))\ninstance Eq GApprox where\n  (==) _ _ = True\n\npredictG :: GApprox     -- Neural Network Approximating G\n         -> [Double]    -- Input (will be state action pair)\n         -> IO [Double] -- predicted value of G\npredictG (GApprox network) input = do\n  net <- network\n  return $ toList $ output net sigmoid $ fromList input\n\nupdateG :: GApprox -- Neural Network Approximating G\n        -> Double   -- Learning Rate\n        -> [Double] -- Input to G\n        -> [Double] -- Actual value of G\n        -> GApprox -- Updated Neural Network\nupdateG (GApprox network) rate input target = GApprox newNet\n  where newNet = do\n          net <- network\n          let sample = [ fromList input --> fromList target ] :: Samples Double\n          return $ trainNTimes 1 rate sigmoid sigmoid' net sample\n\ncreateGApprox :: GApprox\ncreateGApprox = GApprox $ createNetwork 8 [14] 1\n", "meta": {"hexsha": "aaf463c213a3eaff1fa5eef0a0077247f57ba6cd", "size": 1520, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "local-dpp/src/GApprox.hs", "max_stars_repo_name": "eklinkhammer/local-dpp", "max_stars_repo_head_hexsha": "d2ab7c6b4827d92d6a38bc3ab23069dab858e94f", "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": "local-dpp/src/GApprox.hs", "max_issues_repo_name": "eklinkhammer/local-dpp", "max_issues_repo_head_hexsha": "d2ab7c6b4827d92d6a38bc3ab23069dab858e94f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-10-06T02:09:26.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-10T05:26:27.000Z", "max_forks_repo_path": "local-dpp/src/GApprox.hs", "max_forks_repo_name": "eklinkhammer/local-dpp", "max_forks_repo_head_hexsha": "d2ab7c6b4827d92d6a38bc3ab23069dab858e94f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0434782609, "max_line_length": 94, "alphanum_fraction": 0.6782894737, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.420311379817292}}
{"text": "{- |\nModule          : $Header$\nDescription     : This is the parser file for the Scheme compiler.\nCopyright       : (c) Michael Buchel\nLicense         : BSD3\n\nMaintainer      : abuchel2@uwo.ca\nStability       : experimental\nPortability     : portable\n\nThis is the parser, where I am using Parsec for simplicity.\n| -}\nmodule Parser where\n\nimport Abstract\nimport Control.Monad\nimport Control.Monad.Except\nimport Data.Array\nimport Data.Complex\nimport Data.Ratio\nimport Error\nimport Evaluator\nimport Numbers\nimport Text.ParserCombinators.Parsec\n\n-- | Symbol function which identifies all the symbols allowed in Scheme.\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\n-- | Escaped character parser.\nescapedChars :: Parser Char\nescapedChars = do\n\tchar '\\\\'\n\tx <- oneOf \"\\\\\\\"nrt\"\n\treturn $ case x of\n\t\t      '\\\\' -> x\n\t\t      '\"' -> x\n\t\t      'n' -> '\\n'\n\t\t      'r' -> '\\r'\n\t\t      't' -> '\\t'\n\n-- | Parses a string.\nparseString :: Parser LispVal\nparseString = do\n\tchar '\"'\n\tx <- many $ escapedChars <|> noneOf \"\\\"\\\\\"\n\tchar '\"'\n\treturn $ String x\n\n-- | Parses an atom.\nparseAtom :: Parser LispVal\nparseAtom = do\n\tfirst <- letter <|> symbol\n\trest <- many (letter <|> digit <|> symbol)\n\tlet atom = first:rest\n\treturn $ Atom atom\n\n-- | Parses a boolean value.\nparseBool :: Parser LispVal\nparseBool = do\n\tchar '#'\n\t(char 't' >> return (Bool True)) <|> (char 'f' >> return (Bool False))\n\n-- | Parses decimals without the identifier string.\nparseDecimal1 :: Parser LispVal\nparseDecimal1 = many1 digit >>= (return . Number . read)\n\n-- | Parses decimals with the identifier string.\nparseDecimal2 :: Parser LispVal\nparseDecimal2 = do\n\ttry $ string \"#d\"\n\tmany1 digit >>= (return . Number . read)\n\n-- | Parses hexadecimals.\nparseHex :: Parser LispVal\nparseHex = do\n\ttry $ string \"#x\"\n\tmany1 hexDigit >>= (return . Number . hex2dig)\n\n-- | Parses octal numbers.\nparseOct :: Parser LispVal\nparseOct = do\n\ttry $ string \"#o\"\n\tmany1 octDigit >>= (return . Number . oct2dig)\n\n-- | Parses binary numbers.\nparseBin :: Parser LispVal\nparseBin = do\n\ttry $ string \"#b\"\n\tmany1 (oneOf \"10\") >>= (return . Number . bin2dig)\n\n-- | Parses a number.\nparseNumber :: Parser LispVal\nparseNumber = parseDecimal1 <|> parseDecimal2 <|> parseHex <|> parseOct <|> parseBin\n\n-- | Parses a floating point number.\nparseFloat :: Parser LispVal\nparseFloat = do\n\tx <- many1 digit\n\tchar '.'\n\ty <- many1 digit\n\treturn $ Float $ getFloat x y\n\n-- | Parses a ratio value.\nparseRatio :: Parser LispVal\nparseRatio = do\n\tx <- many1 digit\n\tspaces >> char '/' >> spaces\n\ty <- many1 digit\n\treturn $ Ratio ((read x) % (read y))\n\n-- | Parses a complex number.\nparseComplex :: Parser LispVal\nparseComplex = do\n\tx <- (try parseFloat <|> parseDecimal1)\n\tspaces >> char '+' >> spaces\n\ty <- (try parseFloat <|> parseDecimal1)\n\toneOf \"ij\"\n\treturn $ Complex (toDouble x :+ toDouble y)\n\n-- | Helper list parser.\nparseListHelp :: Parser LispVal\nparseListHelp = do\n\tchar '.' >> (skipMany1 space)\n\tx <- parseExpr\n\tspaces >> char ')'\n\treturn x\n\n-- | Parses an individual list.\nparseList :: Parser LispVal\nparseList = do\n\tchar '(' >> spaces\n\theadList <- parseExpr `sepEndBy` (skipMany1 space)\n\t(parseListHelp >>= return . (DottedList headList)) <|> (spaces >> char ')' >> return (List headList))\n\n-- | For Scheme syntax sugar.\nparseQuoted :: Parser LispVal\nparseQuoted = do\n\tchar '\\''\n\tx <- parseExpr\n\treturn $ List [Atom \"quote\", x]\n\n-- | For Scheme syntax sugar.\nparseQuasiQuoted :: Parser LispVal\nparseQuasiQuoted = do\n\tchar '`'\n\tx <- parseExpr\n\treturn $ List [Atom \"quasiquote\", x]\n\n-- | For Scheme syntax sugar.\nparseUnQuoted :: Parser LispVal\nparseUnQuoted = do\n\tchar ','\n\tx <- parseExpr\n\treturn $ List [Atom \"unquote\", x]\n\n-- | Parses a character value.\nparseChar :: Parser LispVal\nparseChar = do\n\ttry $ string \"#\\\\\"\n\tvalue <- try (string \"newline\" <|> string \"space\") <|> do {x <- anyChar; notFollowedBy alphaNum; return [x]}\n\treturn $ Character $ case value of\n\t\t\t\t  \"space\" -> ' '\n\t\t\t\t  \"newline\" -> '\\n'\n\t\t\t\t  otherwise -> (value !! 0)\n\n-- | Parses a vector.\nparseVector :: Parser LispVal\nparseVector = do\n\tarrayVals <- sepBy parseExpr spaces\n\treturn $ Vector (listArray (0, (length arrayVals - 1)) arrayVals)\n\n-- | Helper function for parsing vectors.\nparseVectors :: Parser LispVal\nparseVectors = do\n\tstring \"#(\" >> spaces\n\tx <- parseVector\n\tspaces >> char ')'\n\treturn x\n\n-- | Helper parsing function which tries to parse the expression given to it.\nparseExpr :: Parser LispVal\nparseExpr = parseAtom\n\t<|> parseString\n\t<|> parseQuoted\n\t<|> parseQuasiQuoted\n\t<|> parseUnQuoted\n\t<|> try parseComplex\n\t<|> try parseFloat\n\t<|> try parseRatio\n\t<|> try parseNumber\n\t<|> try parseBool\n\t<|> try parseChar\n\t<|> try parseVectors\n\t<|> parseList\n\n-- | A function to read the expression from a string.\nreadExpr :: String -- ^ Input string\n\t-> ThrowsError LispVal\nreadExpr input = case parse (spaces >> parseExpr) \"parser\" input of\n\t\t      Left err -> throwError $ Parser err\n\t\t      Right val -> return val\n\n-- | Find the end of an expression.\nfindExpr :: String -- ^ Input string.\n\t-> Integer -- ^ Previous integer.\n\t-> Integer -- ^ Nesting of expression.\n\t-> Integer\nfindExpr [] x _ = x\nfindExpr (x : xs) n y = case x of\n\t\t\t     '(' -> findExpr xs (n + 1) (y + 1)\n\t\t\t     ')' -> if (y - 1) == 0 then (n + 1) else findExpr xs (n + 1) (y - 1)\n\t\t\t     otherwise -> findExpr xs (n + 1) y\n", "meta": {"hexsha": "247511cbb533374e70770251884fd8cdffc42d0b", "size": 5322, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Parser.hs", "max_stars_repo_name": "mbuchel/compiler", "max_stars_repo_head_hexsha": "4a021bae14b851cedfec5e86f0afb627a987cd94", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Parser.hs", "max_issues_repo_name": "mbuchel/compiler", "max_issues_repo_head_hexsha": "4a021bae14b851cedfec5e86f0afb627a987cd94", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Parser.hs", "max_forks_repo_name": "mbuchel/compiler", "max_forks_repo_head_hexsha": "4a021bae14b851cedfec5e86f0afb627a987cd94", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8691588785, "max_line_length": 109, "alphanum_fraction": 0.6529500188, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.41984282247472904}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\nmodule Lisp.EvalSpec (spec) where\n\nimport           Test.Hspec\nimport           Test.QuickCheck\n\nimport           Data.Complex\nimport           Data.Ratio\nimport           Data.Text\n\nimport           Lisp\nimport           Lisp.LispVal    (h2l)\n\nspec :: Spec\n\nspec = do\n  describe \"Basic primitives self-eval\" $ do\n    it \"Ints self-eval\" $\n      property $ \\i -> let l = Int i in eval l == l\n\n    it \"Reals self-eval\" $\n      property $ \\r -> let l = Real r in eval l == l\n\n    it \"Rationals self-eval\" $\n      property $ \\q -> let l = Rational q in eval l == l\n\n    it \"Complex numbers self-eval\" $\n      property $ \\c -> let l = Complex c in eval l == l\n\n    it \"Strings self-eval\" $\n      property $ \\s -> let l = String (pack s) in eval l == l\n\n    it \"Bools self-eval\" $\n      property $ \\b -> let l = Bool b in eval l == l\n\n  describe \"quoted forms return their contents\" $ do\n    let quoted v = Pair (Symbol \"quote\") (Pair v Nil)\n    let foo = Symbol \"foo\"\n    let bar = Symbol \"bar\"\n    let foobar = Pair foo bar\n    it \"'foo evaluates to foo\" $\n      eval (quoted foo) `shouldBe` foo\n    it \"'(foo . bar) evaluates to (foo . bar)\" $\n      eval (quoted foobar) `shouldBe` foobar\n\n\n  describe \"basic primitives\" $ do\n    it \"Can add two Ints\" $\n      eval (h2l [Symbol \"+\", Int 5, Int 5]) `shouldBe` Int 10\n    it \"Can add two Reals\" $\n      eval (h2l [Symbol \"+\", Real 5.0, Real 5.0]) `shouldBe` Real 10.0\n    it \"Can add Ints and Reals\" $\n      eval (h2l [Symbol \"+\", Int 5, Real 5.0]) `shouldBe` Real 10.0\n    it \"Can add Rationals and Complex\" $\n      eval (h2l [Symbol \"+\", Rational (5%2), Complex (2.4:+3.1)]) `shouldBe` Complex (4.9:+3.1)\n\n\n", "meta": {"hexsha": "2ba9431847837338baa42394732281b2c757b422", "size": 1690, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Lisp/EvalSpec.hs", "max_stars_repo_name": "blaisepascal/Haskell-LiSP", "max_stars_repo_head_hexsha": "a9478b521f6488b0c557bbcee88cf0d3b38aef6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-15T09:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:43:08.000Z", "max_issues_repo_path": "tests/Lisp/EvalSpec.hs", "max_issues_repo_name": "blaisepascal/Haskell-LiSP", "max_issues_repo_head_hexsha": "a9478b521f6488b0c557bbcee88cf0d3b38aef6a", "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": "tests/Lisp/EvalSpec.hs", "max_forks_repo_name": "blaisepascal/Haskell-LiSP", "max_forks_repo_head_hexsha": "a9478b521f6488b0c557bbcee88cf0d3b38aef6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1379310345, "max_line_length": 95, "alphanum_fraction": 0.573964497, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.6150878555160664, "lm_q1q2_score": 0.4198428065878099}}
{"text": "\n-- https://drive.google.com/open?id=0BxJP-hCBgo5OcU9td2Fhc2xHek0\n\nmodule Numeric.Combinations\n  ( combIndex\n  , combIndexSorted\n  )\n  where\n\nimport Control.Monad.ST (runST)\n\nimport Data.Vector.Unboxed ((!))\nimport qualified Data.Vector.Unboxed as UV\nimport Data.Vector.Algorithms.Merge (sort)\n\nimport Numeric.SpecFunctions (choose)\n\nimport Debug.Trace\n\n-- | Calculates the combination index. Assumes that neither alpha nor x\n--   contain any duplicate elements.\ncombIndex :: (UV.Unbox a, Ord a)\n          => UV.Vector a -- Alphabet of length N\n          -> UV.Vector a -- element of length K\n          -> Maybe Int -- Index in C_K^A\ncombIndex alpha x | UV.length x > UV.length alpha = Nothing -- Require that the alphabet is bigger than the element!\ncombIndex alpha x = combIndexSorted alpha_sorted x_sorted where\n  alpha_sorted = runST $ do\n    m_alpha <- UV.thaw alpha\n    sort m_alpha\n    UV.unsafeFreeze m_alpha\n  x_sorted = runST $ do\n    m_x <- UV.thaw x\n    sort m_x\n    UV.unsafeFreeze m_x\n\n-- | Calculates the combination index assuming both alpha and x are pre-sorted.\n--   This will give incorrect answers if the inputs are not sorted!\ncombIndexSorted :: (UV.Unbox a, Ord a)\n                => UV.Vector a -- Alphabet of length N\n                -> UV.Vector a -- element of length K\n                -> Maybe Int -- Index in C_K^A\ncombIndexSorted alpha x | UV.length x > UV.length alpha = Nothing\ncombIndexSorted alpha x = do\n    x_idx <- m_x_idx\n    return $ UV.sum\n           . UV.map (flip inner_sum x_idx)\n           $ UV.enumFromN 0 cap_k\n  where\n    m_x_idx = UV.mapM (flip UV.elemIndex alpha) x\n    cap_k = UV.length x\n    cap_n = UV.length alpha\n    i_k (-1) _ = -1\n    i_k k x_idx = x_idx ! k\n    inner_sum k x_idx =\n          UV.sum\n        . UV.map (\\q -> floor\n                      $ choose (cap_n - (i1 + 1) - q) (cap_k - k - 1))\n        $ UV.enumFromN 1 (i0 - (i1 + 1))\n      where\n        i0 = i_k k x_idx\n        i1 = i_k (k-1) x_idx\n", "meta": {"hexsha": "033535c3f915cc16e29063cae47790697e84b4d8", "size": 1963, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Combinations.hs", "max_stars_repo_name": "nc6/tooth", "max_stars_repo_head_hexsha": "f8e8ac6b9bb6bddfd7ff1e2c9b8e8c1361a8b59a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T10:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T10:48:13.000Z", "max_issues_repo_path": "src/Numeric/Combinations.hs", "max_issues_repo_name": "nc6/tooth", "max_issues_repo_head_hexsha": "f8e8ac6b9bb6bddfd7ff1e2c9b8e8c1361a8b59a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Combinations.hs", "max_forks_repo_name": "nc6/tooth", "max_forks_repo_head_hexsha": "f8e8ac6b9bb6bddfd7ff1e2c9b8e8c1361a8b59a", "max_forks_repo_licenses": ["BSD-3-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.1587301587, "max_line_length": 116, "alphanum_fraction": 0.633723892, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4198428065878099}}
{"text": "{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE EmptyCase #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule Models.Integrals.Approximate2  where\n\nimport Algebra.Classes\nimport qualified Algebra.Morphism.Affine as A\nimport Prelude hiding (Num(..), Fractional(..), (^), product, sum, pi, sqrt\n                      , exp)\nimport qualified Models.Field\nimport qualified Algebra.Linear.Chebyshev as Chebyshev\nimport Data.Complex\nimport qualified Algebra.Morphism.Polynomial.Multi as Multi\nimport Algebra.Morphism.Polynomial.Multi hiding (constPoly)\nimport qualified Algebra.Morphism.LinComb as LC\nimport Control.Applicative\n\nimport Models.Integrals.Types\n\ntype family Env \u03b3 where\n  Env 'Unit = ()\n  Env (a ':\u00d7 b) = (Env a, Env b)\n  Env 'R = Double\n\ntype RR = Double\n\nnewtype PointWise x a = PW (x -> a) deriving Functor\ninstance Applicative (PointWise x) where\n  pure x = PW $  \\_ -> x\n  PW f <*> PW a = PW (\\x -> (f x) (a x))\n\nfromPointWise :: PointWise x a -> x -> a\nfromPointWise (PW x) = x\n\ninstance Additive a => Additive (PointWise x a) where\n  zero = pure zero\n  (+) = liftA2 (+)\n\ninstance Group a => Group (PointWise x a) where\n  negate = fmap negate\n  (-) = liftA2 (-)\n\ninstance AbelianAdditive a => AbelianAdditive (PointWise x a)\n\ninstance Multiplicative a => Multiplicative (PointWise x a) where\n  one  = pure one\n  (*) = liftA2 (*)\n\ninstance Division a => Division (PointWise x a) where\n  recip  = fmap recip\n  (/) = liftA2 (/)\n\n\ninstance Roots a => Roots (PointWise x a) where\n  root n  = fmap (root n)\n\ninstance Transcendental a => Transcendental (PointWise x a) where\n  pi = pure pi\n  -- log = fmap log\n  -- sin = fmap sin\n  -- cos = fmap cos\n  -- asin = fmap asin\n  -- acos = fmap acos\n  -- atan = fmap atan\n  -- sinh = fmap sinh\n  -- cosh = fmap cosh\n  -- asinh = fmap asinh\n  -- acosh = fmap acosh\n  -- atanh = fmap atanh\n  exp = fmap exp\n\ninstance Multiplicative a => Scalable (PointWise x a) (PointWise x a) where\n  (*^) = (*)\n\ninstance Ring a => Ring (PointWise x a) where\n  fromInteger = PW . const . fromInteger\n\ninstance Field a => Field (PointWise x a) where\n  fromRational = PW . const . fromRational\n\ntype S \u03b3 = PointWise (Env \u03b3) RR\n\nlk :: Var \u03b3 -> Env \u03b3 -> RR\nlk Get (_,x) = x\nlk (Weaken x) (\u03c1,_) = lk x \u03c1\n\nlk' :: Var \u03b3 -> S \u03b3\nlk' v = PW $ lk v\n\nevalC :: forall \u03b3. Coef \u03b3 -> S \u03b3\nevalC (Coef c) = LC.eval (\\x -> PW @(Env \u03b3) $ \\_\u03c1 -> Models.Field.eval @RR x)\n                         (exp . evalP) c\n\nevalP :: forall \u03b3. Poly \u03b3 -> S \u03b3\nevalP = Multi.eval evalC evalE \n\nevalE :: forall \u03b3. Elem \u03b3 -> S \u03b3\nevalE = \\case\n  Supremum dir es -> case dir of\n    Min ->  foldr (liftA2 min) (pure ( 1/0)) (evalP <$> es)\n    Max ->  foldr (liftA2 max) (pure (-1/0)) (evalP <$> es)\n  Vari x -> lk' x\n  CharFun x -> fmap (\\y -> if y >= 0 then 1 else 0) (evalP x)\n\n\napproxIntegrals :: Int -> Env \u03b3 -> P \u03b3 -> RR\napproxIntegrals n \u03c1 =\n  let evP x = fromPointWise (evalP x) \u03c1\n  in \\case\n      Add a b -> approxIntegrals n \u03c1 a + approxIntegrals n \u03c1 b\n      Div a b -> approxIntegrals n \u03c1 a / approxIntegrals n \u03c1 b\n      Integrate (mkSuprema -> (lo,hi)) e ->\n        realPart (Chebyshev.integral @Double @C n (evP lo) (evP hi) $\n                  \\x -> approxIntegrals n (\u03c1,x) e :+ 0)\n      Ret x -> evP x\n      Cond (IsNegative c) e -> if A.eval Models.Field.eval (flip lk \u03c1) c <= 0 then approxIntegrals n \u03c1 e else 0\n      Cond (IsZero _) _ -> error \"approxIntegrals: equality not eliminated?\"\n", "meta": {"hexsha": "7511ad1d128b505519d3e021562385c6735bad58", "size": 3673, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Models/Integrals/Approximate2.hs", "max_stars_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_stars_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Models/Integrals/Approximate2.hs", "max_issues_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_issues_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Models/Integrals/Approximate2.hs", "max_forks_repo_name": "juliangrove/grove-bernardy-bayesian-semantics-tlc", "max_forks_repo_head_hexsha": "70efc3f8fcdf28a4560c77a9a4c089f3e978ff74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6953125, "max_line_length": 111, "alphanum_fraction": 0.6365368908, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.41976996109811887}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes        #-}\n{-# LANGUAGE DeriveGeneric              #-}\n{-# LANGUAGE FlexibleContexts           #-}\n{-# LANGUAGE GADTs                      #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE InstanceSigs               #-}\n{-# LANGUAGE LambdaCase                 #-}\n{-# LANGUAGE ScopedTypeVariables        #-}\n{-# LANGUAGE StandaloneDeriving         #-}\n{-# LANGUAGE TypeApplications           #-}\n{-# LANGUAGE TypeFamilies               #-}\n{-# LANGUAGE TypeFamilyDependencies     #-}\n{-# LANGUAGE TypeInType                 #-}\n{-# LANGUAGE TypeOperators              #-}\n{-# LANGUAGE UndecidableInstances       #-}\n{-# LANGUAGE ViewPatterns               #-}\n\nmodule Numeric.BLAS.HMatrix (\n    HM(..)\n  , HM'\n  , flatten\n  , unflatten\n  ) where\n\nimport           Control.Applicative\nimport           Control.DeepSeq\nimport           Control.Monad\nimport           Control.Monad.Trans.State\nimport           Data.Finite.Internal\nimport           Data.Foldable\nimport           Data.Function\nimport           Data.Kind\nimport           Data.Maybe\nimport           Data.MonoTraversable\nimport           Data.Monoid                  (Endo(..))\nimport           Data.Singletons\nimport           Data.Singletons.Prelude\nimport           Data.Singletons.TypeLits\nimport           Data.Type.Product\nimport           GHC.Generics                 (Generic)\nimport           GHC.TypeLits\nimport           Numeric.BLAS hiding          (outer)\nimport           Numeric.LinearAlgebra.Static\nimport           Type.Family.List hiding      (Reverse)\nimport qualified Data.Vector                  as UV\nimport qualified Data.Vector.Generic.Sized    as VG\nimport qualified Data.Vector.Sized            as V\nimport qualified Data.Vector.Storable         as UVS\nimport qualified Data.Vector.Storable.Sized   as VS\nimport qualified Numeric.LinearAlgebra        as LA\n\ntype family HM' (s :: [Nat]) = (h :: Type) | h -> s where\n    HM' '[]            = Double\n    HM' '[n]           = R n\n    HM' '[m,n]         = L m n\n    HM' (n ': m ': ms) = V.Vector n (HM' (m ': ms))\n\nnewtype HM :: [Nat] -> Type where\n    HM  :: { getHM :: HM' b }\n        -> HM b\n  deriving (Generic)\n\ntype instance Element (HM s) = Double\n\ninstance BLAS HM where\n\n    transp (HM x) = HM (tr x)\n\n    scal \u03b1 (HM x)        = HM (konst \u03b1 * x)\n    axpy \u03b1 (HM x) (HM y) = HM (konst \u03b1 * x + y)\n    dot    (HM x) (HM y) = x <.> y\n    norm2  (HM x)        = norm_2 x\n    asum   (HM x)        = norm_1 x\n\n    iamax\n        :: forall n. KnownNat n\n        => HM '[n + 1]\n        -> Finite (n + 1)\n    iamax  (HM x)        = withKnownNat (SNat @n %:+ SNat @1) $\n        Finite . fromIntegral\n      . LA.maxIndex . extract\n      $ abs x\n\n    gemv \u03b1 (HM a) (HM x) = \\case\n        Just (\u03b2, HM y) -> HM (konst \u03b1 * (a #> x) + konst \u03b2 * y)\n        Nothing        -> HM (konst \u03b1 * (a #> x))\n    ger  \u03b1 (HM x) (HM y) = \\case\n        Just (HM a) -> HM (konst \u03b1 * outer x y + a)\n        Nothing     -> HM (konst \u03b1 * outer x y)\n    gemm \u03b1 (HM a) (HM b) = \\case\n        Just (\u03b2, HM c) -> HM (konst \u03b1 * (a <> b) + konst \u03b2 * c)\n        Nothing        -> HM (konst \u03b1 * (a <> b))\n\ninstance Tensor HM where\n    type Scalar  HM = Double\n\n    gen = \\case\n      SNil -> \\f -> HM $ f \u00d8\n      n@SNat `SCons` SNil -> \\f -> HM . fromJust . create $\n        LA.build (fromIntegral (fromSing n))\n          (f . only . Finite . round)\n      m@SNat `SCons` (n@SNat `SCons` SNil) -> \\f -> HM . fromJust . create $\n        LA.build (fromIntegral (fromSing m), fromIntegral (fromSing n))\n          (\\i j -> f (Finite (round i) :< Finite (round j) :< \u00d8))\n      SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) -> \\f -> HM $\n        V.generate_ $ \\i -> getHM $ gen ns (\\js -> f (i :< js))\n\n    genA = \\case\n      SNil -> \\f -> HM <$> f \u00d8\n      n@SNat `SCons` SNil -> \\f ->\n        fmap (HM . vector) . traverse (f . only . Finite) $\n          [0 .. fromSing n - 1]\n      m@SNat `SCons` (n@SNat `SCons` SNil) -> \\f ->\n        fmap (HM . matrix) . traverse f $\n          [ Finite i :< Finite j :< \u00d8 | j <- [0 .. fromSing m - 1]\n                                      , i <- [0 .. fromSing n - 1]\n          ]\n      SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) -> \\f -> fmap HM $\n        sequenceA . V.generate_ $ \\i -> getHM <$> genA ns (\\js -> f (i :< js))\n\n    tkonst s = HM . hkonst s\n\n    tsum :: forall s. SingI s => HM s -> Double\n    tsum = go sing . getHM\n      where\n        go :: Sing ns -> HM' ns -> Double\n        go = \\case\n          SNil                                      -> id\n          SNat `SCons` SNil                         -> LA.sumElements . extract\n          SNat `SCons` (SNat `SCons` SNil)          -> LA.sumElements . extract\n          SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) -> sum . fmap (go ns)\n\n    tmap :: forall s. SingI s => (Double -> Double) -> HM s -> HM s\n    tmap = omap\n\n    tzip\n        :: forall s. SingI s\n        => (Double -> Double -> Double)\n        -> HM s -> HM s -> HM s\n    tzip f (HM x0) (HM y0) = HM $ hzip f sing x0 y0\n\n    tindex\n        :: forall s. SingI s\n        => Prod Finite s\n        -> HM s\n        -> Double\n    tindex ix0 = go sing ix0 . getHM\n      where\n        go :: Sing ns -> Prod Finite ns -> HM' ns -> Double\n        go = \\case\n          SNil -> \\case\n            \u00d8 -> id\n          SNat `SCons` SNil -> \\case\n            i :< \u00d8 -> (`LA.atIndex` fromIntegral i) . extract\n          SNat `SCons` (SNat `SCons` SNil) -> \\case\n            i :< j :< \u00d8 -> (`LA.atIndex` (fromIntegral i, fromIntegral j)) . extract\n          SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) -> \\case\n            i :< js -> go ns js . (`V.index` i)\n\n    tslice\n        :: forall n m. ()\n        => ProdMap Slice n m\n        -> HM n\n        -> HM m\n    tslice sl0 (HM x0) = HM $ go sl0 x0\n      where\n        go  :: forall ns ms. ()\n            => ProdMap Slice ns ms\n            -> HM' ns\n            -> HM' ms\n        go = \\case\n          PMZ -> \\x -> x\n          PMS (Slice sL sC@SNat sR) PMZ -> \\xs -> fromJust . create $\n            let l = fromIntegral $ fromSing sL\n                c = fromIntegral $ fromSing sC\n            in  withKnownNat (sL %:+ sC %:+ sR) $\n                  LA.subVector l c (extract xs)\n          PMS (Slice sLy sCy@SNat sRy) (PMS (Slice sLx sCx@SNat sRx) PMZ) ->\n              \\xs -> fromJust . create $\n            let lx = fromIntegral $ fromSing sLx\n                ly = fromIntegral $ fromSing sLy\n                cx = fromIntegral $ fromSing sCx\n                cy = fromIntegral $ fromSing sCy\n            in  withKnownNat (sLy %:+ sCy %:+ sRy) $\n                withKnownNat (sLx %:+ sCx %:+ sRx) $\n                  LA.subMatrix (ly, lx) (cy, cx) (extract xs)\n          PMS (Slice sL sC@SNat _) pm@(PMS _ (PMS _ _)) -> \\xs ->\n            let l = fromIntegral $ fromSing sL\n                c = fromIntegral $ fromSing sC\n            in  fmap (go pm)\n                  . fromJust . V.toSized\n                  . UV.take c\n                  . UV.drop l\n                  . V.fromSized\n                  $ xs\n\n    tconv\n        :: forall n m s. ()\n        => Sing n\n        -> ProdMap Conv m s\n        -> HM (m >: n)      -- ^ mask\n        -> HM s\n        -> HM (s >: n)\n    tconv sn@SNat pm0 (HM m0) (HM x0) = HM $ go pm0 m0 x0\n      where\n        go  :: forall ms ss. ()\n            => ProdMap Conv ms ss\n            -> HM' (ms >: n)\n            -> HM' ss\n            -> HM' (ss >: n)\n        go = \\case\n          PMZ -> \\m x -> konst x * m\n          PMS (Conv sM sS str off) PMZ -> \\m x ->\n            undefined\n\n    treshape\n        :: (SingI s1, Product s1 ~ Product s2)\n        => Sing s2\n        -> HM s1\n        -> HM s2\n    treshape s = unflatten s . flatten\n\n    tload\n        :: Sing s\n        -> V.Vector (Product s) Double\n        -> HM s\n    tload s = unflatten s . VG.convert\n\n    textract\n        :: SingI s\n        => HM s\n        -> V.Vector (Product s) Double\n    textract = VG.convert . flatten\n\n-- hconv\n--     :: forall o ms ns. (KnownNat o)\n--     => DoubleProd Sing ms ns\n--     -> HM' (o ': ms)\n--     -> HM' ns\n--     -> HM' (o ': ns)\n-- hconv = \\case\n--     DPZ -> \\ms x -> konst x * ms\n--     DPS SNat sn@SNat DPZ -> \\m x -> fromJust . create $\n--       let c = LA.conv2 (extract m) (LA.asRow (extract x))\n--           o = fromInteger (natVal (Proxy @o))\n--           left = o `div` 2\n--       in  LA.subMatrix (0,left) (o, fromInteger (fromSing sn)) c\n--     DPS smx@SNat snx@SNat (DPS smy@SNat sny@SNat DPZ) -> \\m x ->\n--       -- todo: vectorize with im2colV\n--       flip fmap m $ \\msk -> fromJust . create $\n--         let c = LA.conv2 (extract msk) (extract x)\n--             left = fromInteger (fromSing smx) `div` 2\n--             top  = fromInteger (fromSing smy) `div` 2\n--         in  LA.subMatrix (left, top) (fromInteger (fromSing snx), fromInteger (fromSing sny)) c\n--     dp0@(DPS (SNat :: Sing m0) (SNat :: Sing n0) (DPS _ _ (DPS _ _ _) :: DoubleProd Sing ms0 ns0)) ->\n--               \\(ms :: V.Vector o (V.Vector m0 (HM' ms0))) (xs :: V.Vector n0 (HM' ns0)) ->\n--       flip fmap ms $ \\(msk :: V.Vector m0 (HM' ms0)) -> hconv1 dp0 msk xs\n\n-- hconv1\n--     :: forall m s. ()\n--     => DoubleProd Sing m s\n--     -> HM' m\n--     -> HM' s\n--     -> HM' s\n-- hconv1 = \\case\n--     DPZ -> (*)\n--     DPS sm@SNat sn@SNat DPZ -> \\m x -> fromJust . create $\n--       let c = LA.conv (extract m) (extract x)\n--           left = fromInteger (fromSing sm) `div` 2\n--       in  UVS.slice left (fromInteger (fromSing sn)) c\n--     DPS smx@SNat snx@SNat (DPS smy@SNat sny@SNat DPZ) -> \\m x -> fromJust . create $\n--       let c = LA.conv2 (extract m) (extract x)\n--           left = fromInteger (fromSing smx) `div` 2\n--           top  = fromInteger (fromSing smy) `div` 2\n--       in  LA.subMatrix (left, top) (fromInteger (fromSing snx), fromInteger (fromSing sny)) c\n--     DPS (SNat :: Sing m0) (SNat :: Sing n0) dps@(DPS _ _ (DPS _ _ _) :: DoubleProd Sing ms0 ns0) ->\n--               \\(ms :: V.Vector m0 (HM' ms0)) (xs :: V.Vector n0 (HM' ns0)) ->\n--       let s   :: Sing ns0\n--           s   = prodSing $ secondDP dps\n--           cl :: V.Vector n0 (V.Vector m0 (HM' ns0))\n--           cl = im2colV (hkonst s 0) xs\n--       in  fmap (hsum s . V.zipWith (hconv1 dps) ms) cl\n\nflatten :: SingI s => HM s -> VS.Vector (Product s) Double\nflatten = hflatten sing . getHM\n\nunflatten :: Sing s -> VS.Vector (Product s) Double -> HM s\nunflatten s = HM . hunflatten s\n\nhflatten\n    :: Sing s\n    -> HM' s\n    -> VS.Vector (Product s) Double\nhflatten = \\case\n    SNil -> VS.singleton\n    SNat `SCons` SNil -> fromJust . VS.toSized . extract\n    sn@SNat `SCons` (sm@SNat `SCons` SNil) -> case sn %:* sm of\n      SNat -> fromJust . VS.toSized . LA.flatten . extract\n    SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) ->\n      VG.convert . V.concatMap (VG.convert . hflatten ns)\n\nhunflatten\n    :: Sing s\n    -> VS.Vector (Product s) Double\n    -> HM' s\nhunflatten = \\case\n    SNil -> VS.head\n    SNat `SCons` SNil -> fromJust . create . VS.fromSized\n    SNat `SCons` (sm@SNat `SCons` SNil) -> fromJust . create . LA.reshape (fromInteger (fromSing sm)) . VS.fromSized\n    sn@SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) -> case sProduct ns of\n      sp@SNat -> fromJust\n            . V.fromList\n            . evalState (replicateM (fromInteger (fromSing sn)) $\n                           hunflatten ns . fromJust . VS.toSized <$> state (UVS.splitAt (fromInteger (fromSing sp)))\n                        )\n            . VS.fromSized\n\nim2col\n    :: forall m n o. (KnownNat m, KnownNat n, KnownNat o)\n    => L n m\n    -> L n o\nim2col = undefined\n\nim2colV\n    :: forall m n a. (KnownNat m, KnownNat n)\n    => a\n    -> V.Vector n a\n    -> V.Vector n (V.Vector m a)\nim2colV pad (V.fromSized->v) = V.generate $ \\i ->\n      fromJust . V.toSized $ UV.slice i m padded\n  where\n    padded = UV.concat [UV.replicate left pad, v, UV.replicate right pad]\n    m :: Int\n    m  = fromIntegral $ natVal (Proxy @m)\n    left  = m `div` 2\n    right = m - left\n\nhadd :: Sing s -> HM' s -> HM' s -> HM' s\nhadd = \\case\n    SNil                                     -> (+)\n    SNat `SCons` SNil                        -> (+)\n    SNat `SCons` (SNat `SCons` SNil)         -> (+)\n    SNat `SCons` s@(_ `SCons` (_ `SCons` _)) -> liftA2 (hadd s)\n\nhsum :: Foldable f => Sing s -> f (HM' s) -> HM' s\nhsum s = foldl' (hadd s) (hkonst s 0)\n\nhkonst :: Sing s -> Double -> HM' s\nhkonst = \\case\n    SNil                                     -> id\n    SNat `SCons` SNil                        -> konst\n    SNat `SCons` (SNat `SCons` SNil)         -> konst\n    SNat `SCons` s@(_ `SCons` (_ `SCons` _)) -> pure . hkonst s\n\nhzip\n    :: (Double -> Double -> Double)\n    -> Sing s\n    -> HM' s\n    -> HM' s\n    -> HM' s\nhzip f = go\n  where\n    go :: Sing t -> HM' t -> HM' t -> HM' t\n    go = \\case\n      SNil                             -> f\n      SNat `SCons` SNil                -> zipWithVector f\n      SNat `SCons` (SNat `SCons` SNil) ->\n        (\\xs ys -> matrix (zipWith f xs ys))\n           `on` (concat . LA.toLists . extract)\n      SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) ->\n         V.zipWith (go ns)\n\n-- firstDP\n--     :: DoubleProd f as bs\n--     -> Prod f as\n-- firstDP = \\case\n--     DPZ        -> \u00d8\n--     DPS x _ xs -> x :< firstDP xs\n\n-- secondDP\n--     :: DoubleProd f as bs\n--     -> Prod f bs\n-- secondDP = \\case\n--     DPZ        -> \u00d8\n--     DPS _ x xs -> x :< secondDP xs\n\nprodSing\n    :: Prod Sing as\n    -> Sing as\nprodSing = \\case\n    \u00d8       -> SNil\n    x :< xs -> x `SCons` prodSing xs\n\ninstance SingI s => MonoFunctor (HM s) where\n    omap f = HM . go sing . getHM\n      where\n        go :: Sing ns -> HM' ns -> HM' ns\n        go = \\case\n          SNil                                      -> f\n          SNat `SCons` SNil                         -> dvmap f\n          SNat `SCons` (SNat `SCons` SNil)          -> dmmap f\n          SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) -> fmap (go ns)\n\nhelems :: forall s. SingI s => HM s -> [Double]\nhelems = flip appEndo [] . go sing . getHM\n  where\n    go :: Sing ns -> HM' ns -> Endo [Double]\n    go = \\case\n      SNil                                      -> \\x -> Endo (x:)\n      SNat `SCons` SNil                         -> Endo . (++) . LA.toList . extract\n      SNat `SCons` (SNat `SCons` SNil)          -> foldMap (Endo . (++)) . LA.toLists . extract\n      SNat `SCons` ns@(_ `SCons` (_ `SCons` _)) -> foldMap (go ns)\n\ninstance SingI s => MonoFoldable (HM s) where\n    ofoldMap f     = foldMap f . helems\n    ofoldr f z     = foldr f z . helems\n    ofoldl' f z    = foldl' f z . helems\n    otoList        = helems\n    oall f         = all f . helems\n    oany f         = any f . helems\n    onull          = (== 0) . olength\n    olength _      = fromIntegral (product (fromSing (sing @_ @s)))\n    olength64      = fromIntegral . olength\n    ocompareLength = ocompareLength . helems\n    otraverse_ f   = traverse_ f . helems\n    ofor_ x        = for_ (helems x)\n    omapM_ f       = traverse_ f . helems\n    oforM_ x       = for_ (helems x)\n    ofoldlM f x    = foldlM f x . helems\n    ofoldMap1Ex f  = ofoldMap1Ex f . helems\n    ofoldr1Ex f    = ofoldr1Ex f . helems\n    ofoldl1Ex' f   = ofoldl1Ex' f . helems\n    headEx         = headEx . helems\n    lastEx         = lastEx . helems\n    maximumByEx f  = maximumByEx f . helems\n    minimumByEx f  = minimumByEx f . helems\n\nderiving instance NFData (HM' s)     => NFData (HM s)\nderiving instance Show (HM' s)       => Show (HM s)\nderiving instance Num (HM' s)        => Num (HM s)\nderiving instance Fractional (HM' s) => Fractional (HM s)\nderiving instance Floating (HM' s)   => Floating (HM s)\n\n", "meta": {"hexsha": "c1088d09b3b4be82c6ec336e01ed52b51e690026", "size": 15608, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old/src/Numeric/BLAS/HMatrix.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old/src/Numeric/BLAS/HMatrix.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old/src/Numeric/BLAS/HMatrix.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 35.1531531532, "max_line_length": 116, "alphanum_fraction": 0.4906458227, "num_tokens": 4958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.4195530340732464}}
{"text": "{-# language BangPatterns #-}\n{-# language GeneralizedNewtypeDeriving #-}\n{-# language MultiParamTypeClasses #-}\n{-# language RankNTypes #-}\n{-# language RebindableSyntax #-}\n{-# language TypeFamilies #-}\nmodule W40K.Core.Prob\n  ( QQ\n  , Event(..)\n  , Prob\n  , events\n  , traceLength\n  , traceEvents\n  , traceNumEvents\n  , fmapProb\n  , fmapProbMonotone\n  , fmapProbMonotone'\n  , (|>>=|), (|=<<|)\n  , uniformly\n  , probTrue\n  , probFalse\n  , probOf\n  , given\n  , bernoulli\n  , binomial\n  , foldlProbs'\n  , foldrProbs\n  , foldProbs\n  , sumProbs\n  , foldAssocIID\n  , foldIID\n  , sumIID\n  , addImpossibleEvents\n  , cdf\n  , ccdf\n  , summary\n  , summaryInt\n  , mean\n  , variance\n  , stDev\n  , maxEvent\n  ) where\n\nimport Prelude hiding (Functor(..), Applicative(..), Monad(..))\n\nimport Control.DeepSeq (NFData(..))\n\nimport Data.List (foldl', sort)\nimport Data.MemoTrie (memo)\n\nimport Numeric.SpecFunctions (choose)\n\nimport Debug.Trace (trace)\n\nimport W40K.Core.SortedList (SortedList, SortedListItem(..))\nimport qualified W40K.Core.SortedList as SortedList\n\nimport W40K.Core.ConstrMonad as ConstrMonad\nimport W40K.Core.Util\n\n\ntype QQ = Double\n\ndata Event a = Event !a {-# unpack #-} !QQ\n    deriving (Eq, Ord)\n\nmapEvent :: (a -> b) -> Event a -> Event b\nmapEvent f (Event a p) = Event (f a) p\n{-# inline mapEvent #-}\n\ninstance NFData a => NFData (Event a) where\n    rnf (Event a _) = rnf a\n\ninstance Ord a => SortedListItem (Event a) where\n    type ItemKey (Event a) = a\n    itemKey (Event a _) = a\n    combineItems (Event _ p) (Event a p') = Event a (p + p')\n\ninstance Show a => Show (Event a) where\n    show (Event a p) = show a ++ \": \" ++ show (realToFrac p :: Float)\n\n\nnewtype Prob a = Prob { density :: SortedList (Event a) }\n    deriving (Eq, Ord, Show, NFData)\n\nevents :: Prob a -> [Event a]\nevents (Prob es) = SortedList.toAscList es\n{-# inline events #-}\n\ntraceLength :: [a] -> [a]\ntraceLength as = trace (show (length as)) as\n\ntraceEvents :: Show a => Prob a -> Prob a\ntraceEvents df@(Prob _) =\n    trace (show (events df)) df\n\ntraceNumEvents :: Prob a -> Prob a\ntraceNumEvents df@(Prob _) =\n    trace (show (length (events df))) df\n\nfmapProb :: Ord b => (a -> b) -> Prob a -> Prob b\nfmapProb f (Prob evts) = Prob (SortedList.map (mapEvent f) evts)\n{-# inline fmapProb #-}\n\n{-# rules \"fmap/fmapProb\" fmap = fmapProb #-}\n{-# specialize fmapProb :: (a -> Int) -> Prob a -> Prob Int #-}\n\n-- only for monotone f\nfmapProbMonotone :: Ord b => (a -> b) -> Prob a -> Prob b\nfmapProbMonotone f (Prob evts) = Prob (SortedList.mapMonotone (mapEvent f) evts)\n{-# inline fmapProbMonotone #-}\n\n-- only for *strictly* monotone f\nfmapProbMonotone' :: (a -> b) -> Prob a -> Prob b\nfmapProbMonotone' f (Prob evts) = Prob (SortedList.mapMonotone' (mapEvent f) evts)\n{-# inline fmapProbMonotone' #-}\n\nbindProbWithStrat :: Ord b => (forall c. [c] -> [c]) -> Prob a -> (a -> Prob b) -> Prob b\nbindProbWithStrat evalList (Prob evts) f =\n    case SortedList.toAscList evts of\n      [Event a _] -> f a\n      evtList     -> Prob $ SortedList.concat $ evalList $ totalProb [Event (f a) p | Event a p <- evtList]\n  where\n    totalProb :: [Event (Prob a)] -> [SortedList (Event a)]\n    totalProb ess = [SortedList.fromAscList [Event b (p*p') | Event b p' <- events y] | Event y p <- ess]\n\n{-# inlinable bindProbWithStrat #-}\n\n\ninstance ConstrMonad Ord Prob where\n    return a = Prob (SortedList.singleton (Event a 1))\n    {-# inline return #-}\n    (>>=) = bindProbWithStrat seqItems\n    {-# inline (>>=) #-}\n    {-# specialize (>>=) :: Prob a -> (a -> Prob Int) -> Prob Int #-}\n\n(|>>=|) :: (Ord a, Ord b) => Prob a -> (a -> Prob b) -> Prob b\n(|>>=|) = bindProbWithStrat parItems\n{-# inline (|>>=|) #-}\n\n(|=<<|) :: (Ord a, Ord b) => (a -> Prob b) -> Prob a -> Prob b\nf |=<<| ma = ma |>>=| f\n{-# inline (|=<<|) #-}\n\n\nuniformly :: Ord a => [a] -> Prob a\nuniformly as = Prob $ SortedList.fromAscList [Event a (1/n) | a <- sort as]\n  where\n    n = fromIntegral (length as)\n\nprobTrue :: Prob Bool -> QQ\nprobTrue prob =\n    case events prob of\n        [Event False _, Event True p] -> p\n        [Event True p]                -> p\n        [Event False q]               -> 1 - q\n        []                            -> error \"empty Prob!\"\n        _                             -> error (\"unnormalized Prob!\" ++ show prob)\n\nprobFalse :: Prob Bool -> QQ\nprobFalse df = 1 - probTrue df\n\nprobOf :: (a -> Bool) -> Prob a -> QQ\nprobOf test df = sum [p | Event a p <- events df, test a]\n\ngiven :: (a -> Bool) -> Prob a -> Prob a\ngiven hyp prob =\n    Prob (SortedList.fromAscList [Event a (p / probHyp) | Event a p <- events prob, hyp a])\n  where\n    probHyp = probOf hyp prob\n\nbernoulli :: QQ -> Prob Bool\nbernoulli p = Prob $ SortedList.fromAscList [Event False (1-p), Event True p]\n\nbinomial :: Int -> QQ -> Prob Int\nbinomial 0 _ = return 0\nbinomial n p = binomialFlip p n\n\nbinomialFlip :: QQ -> Int -> Prob Int\nbinomialFlip p\n  | p == 1/2  = binomial12\n  | p == 1/3  = binomial13\n  | p == 1/6  = binomial16\n  | p == 2/3  = binomial23\n  | otherwise = binomialMemo p\n\nbinomialMemo :: QQ -> Int -> Prob Int\nbinomialMemo p = memo $ \\n ->\n    case p of\n      0 -> return 0\n      1 -> return n\n      _ -> Prob $ SortedList.fromAscList [Event k (binomProbOf n p k) | k <- [0..n]]\n  where\n    binomProbOf :: Int -> QQ -> Int -> QQ\n    binomProbOf n p k\n      | k < 0 || k > n = 0\n      | n == 0         = 1\n      | otherwise      = realToFrac (choose n k) * p^k * (1-p)^(n-k)\n\nbinomial23 :: Int -> Prob Int\nbinomial23 = binomialMemo (2/3)\n\nbinomial12 :: Int -> Prob Int\nbinomial12 = binomialMemo (1/2)\n\nbinomial13 :: Int -> Prob Int\nbinomial13 = binomialMemo (1/3)\n\nbinomial16 :: Int -> Prob Int\nbinomial16 = binomialMemo (1/6)\n\nfoldlProbs' :: (Ord a, Ord b) => (b -> a -> b) -> Prob b -> [Prob a] -> Prob b\nfoldlProbs' = foldl' . liftA2\n\nfoldrProbs :: (Ord a, Ord b) => (a -> b -> b) -> Prob b -> [Prob a] -> Prob b\nfoldrProbs = foldr . liftA2\n\nfoldProbs :: (Ord m, Monoid m) => [Prob m] -> Prob m\nfoldProbs = foldlProbs' mappend (return mempty)\n\nsumProbs :: (Ord a, Num a) => [Prob a] -> Prob a\nsumProbs []     = return 0\nsumProbs [p]    = p\nsumProbs (p:ps) = foldlProbs' (+) p ps\n{-# specialize sumProbs :: [Prob Int] -> Prob Int #-}\n\nfoldAssocIID :: (Ord a) => (a -> a -> a) -> a -> Int -> Prob a -> Prob a\nfoldAssocIID _ z 0 _ = return z\nfoldAssocIID f z n p\n  | n < 0     = error \"foldAssocIID: n must be >= 0\"\n  | otherwise = noCheck f z n p\n  where\n    noCheck _ _ 1 p = p\n    noCheck f z n p\n      | n `mod` 2 == 0 = twiceHalf\n      | otherwise      = liftA2 f p twiceHalf\n      where\n        !twiceHalf = liftA2 f recHalf recHalf\n        !recHalf   = foldAssocIID f z (n`div`2) p\n\nfoldIID :: (Ord a, Monoid a) => Int -> Prob a -> Prob a\nfoldIID = foldAssocIID mappend mempty\n\n-- TODO: Option to use Central Limit Theorem for sufficiently large n\nsumIID :: (Ord a, Num a) => Int -> Prob a -> Prob a\nsumIID = foldAssocIID (+) 0\n\naddImpossibleEvents :: (Ord a, Enum a) => Prob a -> Prob a\naddImpossibleEvents prob =\n    let es = events prob\n        as = [a | Event a _ <- es]\n    in\n        Prob $ SortedList.fromAscList $ merge es (zipWith Event [minimum as .. maximum as] (repeat 0))\n  where\n    merge es []  = es\n    merge [] es' = es'\n    merge ees@(e@(Event a _):es)\n          ees'@(e'@(Event a' _):es')\n      | a == a' = e : merge es es'\n      | a <  a' = e : merge es ees'\n      | a >  a' = e' : merge ees es'\n\ncdf :: Ord a => Prob a -> [Event a]\ncdf = scanl1 sumEvents . events\n  where\n    sumEvents (Event _ p) (Event a p') = Event a (p + p')\n\nccdf :: Ord a => Prob a -> [Event a]\nccdf = scanr1 sumEvents . events\n  where\n    sumEvents (Event a p) (Event _ p') = Event a (p + p')\n\nsummary :: Prob QQ -> IO ()\nsummary p =\n  let mu    = \"\u00b5=\" ++ show (realToFrac (mean p) :: Double)\n      sigma = \"\u03c3=\" ++ show (sqrt $ realToFrac (variance p) :: Double)\n  in\n      putStrLn $ mu ++ \", \" ++ sigma\n\nsummaryInt :: Prob Int -> IO ()\nsummaryInt = summary . fmap fromIntegral\n\nmean :: Prob QQ -> QQ\nmean df = sum [k * p | Event k p <- events df]\n\nvariance :: Prob QQ -> QQ\nvariance df = sum [squared k * p | Event k p <- events df] - squared (mean df)\n  where\n    squared x = x*x\n\nstDev :: Prob QQ -> QQ\nstDev df = sqrt (variance df)\n\nmaxEvent :: Ord a => Prob a -> a\nmaxEvent df = maximum [a | Event a _ <- events df]\n", "meta": {"hexsha": "5ac3448e62c487ebaa7617b1f8809f48e0ce1ad6", "size": 8279, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/W40K/Core/Prob.hs", "max_stars_repo_name": "xcv-/w40k", "max_stars_repo_head_hexsha": "7c15ecbfe798ae555684b4e413e316ed863d424b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-13T08:20:55.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-13T08:20:55.000Z", "max_issues_repo_path": "src/W40K/Core/Prob.hs", "max_issues_repo_name": "xcv-/w40k", "max_issues_repo_head_hexsha": "7c15ecbfe798ae555684b4e413e316ed863d424b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/W40K/Core/Prob.hs", "max_forks_repo_name": "xcv-/w40k", "max_forks_repo_head_hexsha": "7c15ecbfe798ae555684b4e413e316ed863d424b", "max_forks_repo_licenses": ["BSD-3-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.9695945946, "max_line_length": 107, "alphanum_fraction": 0.5907718323, "num_tokens": 2712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.41955155647232995}}
{"text": "{-# LANGUAGE DataKinds #-}\n\nmodule SCG.Graph () where\n{--\nimport GHC.TypeLits\nimport Algebra.Graph\nimport Backprop\nimport Numeric.LinearAlgebra.Static\n\n{--\nOptimizing loss functions over random variables is often intractable\ndue to the loss functions and their gradients being either a sum over\nan exponential number of latent variable configurations or non-analytic,\nhigh-dimensional integrals.\n\nUsually this is resolved by using problem-specific MC Grad Estimators.\n\nThere is a general technique for this!\n\nStochastic Computation Graphs:\n- Allows derivation of unbiased gradient estimators for general expected losses.\n- Estimator can be computed as the grad of a differentiable \"surrogate loss\" through backprop\n- Variance reduction techniques can be applied to this problem formulation\n- Hessian-free methods and majorization-minimization algorithms can be generalized to the SCG framework\n\n\n!! The main modification to backprop is to introduce extra gradient signals at the stochastic nodes.\n--}\n\n\n-- Gradient Estimators for a Single Random Variable\n\ntype RV = Vector Double\n\ntype Theta = Matrix\n\nparameterizedProbDist :: Theta -> RV\n\ncostfn :: RV -> Double\ncostfn rv = 2.0\n\n-- scoreFunctionEstimator: By Log-Derivative Trick (valid if p_x_theta is continuous function of theta, though not necessarily for x)\n-- also known as REINFORCE or likelihood ratio estimator\nddTheta_expect_over_x_f_x x f p theta = expectation $ x $ f x $ ddTheta $ log $ p x theta \n\n\n-- if x is deterministic differentiable (perhaps representable as a type constraint? find one)\n-- function of theta and another rv z, (i.e, x(z, theta)) we can use\n-- !!Pathwise Derivative\n-- only valid if f(x(z, theta)) is continous function of theta for all z (another type constraint?)\nddTheta_expect_over_x_f_ztheta f x z theta = expectation $ z $ ddTheta $ f (x z theta)\n\n\n-- Theta might appear inside the expectation and the prob dist!\n-- ddtheta Expectation_z~p(., theta)[ f( x(z, theta) ) ]\n-- then two terms in the gradient estimator:\n\n\nddtheta_expect_over_z_from_pOfTheta_f_of_x_of_z_theta p f x z theta =\n  expectation map (\\z -> pointwiseEstimate) sample (p z theta)\n  where pointwiseEstimate = ddTheta $ f (x z theta) + (ddTheta $ log (p z theta)) * (f $ x z theta)\n\n\n\n{--\n1. SF can be used even if f is discontinuous or x is a discrete rv\n2. SF only requires trajectories, PD requires f'(x)\n3. SF has higher variance than PD, unless f is rough as in time-series problems with exploding gradients\n4. PD has a deterministic limit, SF doesn't.\n--}\n\n{--\n  STOCHASTIC COMPUTATION GRAPHS:\n    Directed, Acyclic Graph with Three Kinds of nodes:\n    - Input Nodes, set externally including the parameters we differentiate with respect to\n    - Deterministic Nodes: pure functions of their parents\n    - Stochastic Nodes: Distributed Conditionally on their parents.\n\n    Each parent v of a non-input node w is connected to it by a directed edge (v, w)\n\n  THE STRUCTURE OF THE GRAPH FULLY SPECIFIES:\n    - What estimator we will use, SF or PD or a combination thereof\n    - Nodes arranged in series are multiplicative terms only\n    - Nodes arranged in parallel lead to sums over mulplicative terms\n    - \n--}\n{--\ndata Node a = InputNode a | DeterministicNode a | StochasticNode a\n\nnewtype InputNode a = IO a\n\nnewtype DeterministicNode v e = ([v] -> e -> b)\n\nnewtype StochasticNode v e = ConditionalDistribution [v] e\n\ndata DirectedEdge a = DirectedEdge\n  { _v :: Node,\n    _w :: DeterministicNode | StochasticNode\n  }\n--}\n\n\n-- TODO: Create a directed acyclic graph DS using alga\n-- TODO: Define Node types which typecheck (initially for a scalar parameterization of the relevant types)\n-- TODO: Add backprop for folds over the deterministic nodes? derive an instance of Backprop for edges?\n-- TODO: Add the right gradient estimation procedure for combinations of deterministic and stochastic nodes\n-- TODO: Figure out how to do dataflow programming over the Graph\n--}\n", "meta": {"hexsha": "49e1a202c460ae3a8eb49d8262ed39ec8e53c2cc", "size": 3937, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SCG/Graph.hs", "max_stars_repo_name": "faezs/opt-expect", "max_stars_repo_head_hexsha": "8f232abf68b480807bc6dcb9fc70d2049974b822", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-13T12:24:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T11:05:50.000Z", "max_issues_repo_path": "src/SCG/Graph.hs", "max_issues_repo_name": "faezs/opt-expect", "max_issues_repo_head_hexsha": "8f232abf68b480807bc6dcb9fc70d2049974b822", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SCG/Graph.hs", "max_forks_repo_name": "faezs/opt-expect", "max_forks_repo_head_hexsha": "8f232abf68b480807bc6dcb9fc70d2049974b822", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-14T14:58:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-14T14:58:24.000Z", "avg_line_length": 36.119266055, "max_line_length": 133, "alphanum_fraction": 0.7574295149, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4194618146234809}}
{"text": "-- Graphical and Network Models in Haskell. \n-- Nicolas Kim\n-- Department of Statistics, Carnegie Mellon University \n-- Distributed under the MIT License. \n\nimport System.IO\nimport System.Random\n\nimport Adjacency\nimport Core\nimport Local\n\nimport Control.Monad\nimport Control.Monad.Random\nimport Control.Parallel (par, pseq)\n-- import Control.Lens\n\nimport qualified Data.Map.Lazy as M\nimport qualified Data.List as L\n\nimport Numeric.LinearAlgebra (dispf)\n\n-- import qualified Numeric.LinearAlgebra as LA\n\n-- Some examples of graphs. \ngr1 = Graph [1..3] [(1,2), (1,3), (2,3)] :: Graph Int\ngr2 = Graph [1..2] [(1,2), (1,3), (2,3)] :: Graph Int\ngr3 = completeGraph [1..10] :: Graph Int\ngr4 = Graph [1..4] [(1,2), (3,4), (1,4)] :: Graph Int\n\nkite = Graph [1..4] [(1,2), (1,3), (2,3), (2,4), (3,4)] :: Graph Int\nwiki = Graph [1..6] [(1,2), (1,5), (2,5), (2,3), (3,4), (4,5), (4,6)] ::\n  Graph Int\ngr5 = Graph [1..3] [(1,2)] :: Graph Int\ndisconnected = Graph [1..4] [(1,2), (3,4)] :: Graph Int\n\n-- Data structure for network models. \n-- data Model = ERG { parameters :: [Double] } deriving (Show, Eq)\n\n-- Makes an empty graph. \nemptyGraph :: Graph a\nemptyGraph = Graph [] []\n\n-- Makes a complete simple graph from a list of nodes. \ncompleteGraph :: (Ord a, Eq a) => [a] -> Graph a\ncompleteGraph ns = Graph sns es\n  where\n    sns = L.sort ns\n    es = completeEdges sns\n\n-- List of all possible graphs on n nodes. \n-- allGraphs :: (Ord a, Eq a) => [a] -> [Graph a] -> M.Map [Int] [Graph a]\n-- allGraphs ns = L.foldl' () mapInit [1..n]\n--   where\n--     mapInit = M.fromList [(0, emptyGraph)]\n--     n = (\\x -> x*(x-1) `div` 2) $ length ns\n\n-- Makes a valid graph object from a list of edges. \ntoGraph :: (Ord a, Eq a) => [(a, a)] -> Graph a\ntoGraph es = Graph (extractNodes es) es\n\n-- Checks if the edges contain defined nodes. \nvalidGraph :: (Eq a) => Graph a -> Bool\nvalidGraph (Graph ns es) = subset (L.union (map fst es) (map snd es)) ns\n  where\n    subset xs ys = all (`elem` ys) xs\n\n-- Removes redundant edges (e.g. (1,2) = (2,1)). \nredundant :: (Ord a, Eq a) => [(a, a)] -> [(a, a)]\nredundant es = L.intersect es (map f es)\n  where\n    f (x, y) = (min x y, max x y)\n\n-- Makes a graph valid (see the `validGraph` function). \nmakeValid :: (Eq a) => Graph a -> Graph a\nmakeValid gr@(Graph ns es)\n  | validGraph gr = gr\n  | otherwise = Graph (L.union ens ns) es\n    where\n      ens = L.nub $ L.union (map fst es) (map snd es)\n\n-- From a list of edges, give the sorted and pruned list of nodes\nextractNodes :: (Ord a, Eq a) => [(a, a)] -> [a]\nextractNodes es = L.nub $ L.sort allnodes\n  where\n    allnodes = (map fst es) ++ (map snd es)\n\n-- The complete set of edges between nodes in a list. Nodes don't need to\n-- be orderable. 22s\ncompleteEdges' :: [a] -> [(a, a)]\ncompleteEdges' ns = [ (fst x, fst y) | x <- zs, y <- zs, snd x < snd y ]\n  where\n    zs = zip ns [1..]\n\n-- Add a set of nodes to a graph using their labels. \naddNodes :: (Ord a) => Graph a -> [a] -> Graph a\naddNodes (Graph ns es) nns = Graph (L.union ns nns) es\n\n-- Add a set of edges to a graph. \naddEdges :: (Ord a) => Graph a -> [(a, a)] -> Graph a\naddEdges (Graph ns es) ees = Graph ns (L.union es ees)\n\n\n-- -- Various graph statistics. \n-- Computes the number of nodes. \nnNode :: Graph a -> Int\nnNode gr = length $ nodes gr\n\n-- Computes the number of edges. \nnEdge :: Graph a -> Int\nnEdge gr = length $ edges gr\n\n\n-- -- Monad-based generation of random nodes and edges, i.e. random graphs.\n-- Erdos-Renyi Model\n-- Include or don't include an edge? \npBool :: (RandomGen g) => Double -> Rand g Bool\npBool p = liftM (< p) $ getRandomR ((0, 1) :: (Double, Double))\n\n-- Decide over a list of edges. \npBools :: (RandomGen g) => [Double] -> Rand g [Bool]\npBools ps = sequence $ map pBool ps\n\n-- Given a list of Bools and any other list, return the list subsetted by\n-- the list of Bools. \nbyBool :: [Bool] -> [a] -> [a]\nbyBool bs xs = [ snd zs | zs <- (zip bs xs), fst zs ]\n\n-- Select elements from a list independently and with probabilities ps. \nsetEdges :: (RandomGen g) => [a] -> [Double] -> Rand g [a]\nsetEdges xs ps = liftM (flip byBool xs) $ pBools ps\n\n-- Generate an Erdos-Renyi random graph; nodes ns, and edge probabilities\n-- ps. \nerdosGen :: (Ord a, RandomGen g) => [a] -> [Double] -> Rand g (Graph a)\nerdosGen ns ps = liftM (Graph ns) $ setEdges (completeEdges ns) ps\n\n-- Graphon Model: generates a w-random graph. \ngraphonGen :: (Ord a, RandomGen g) => [a] -> (Double -> Double -> Double)\n  -> Rand g (Graph a)\ngraphonGen ns w = liftM (Graph ns) es\n  where\n    us = liftM (take (length ns)) $ getRandomRs ((0, 1) :: (Double, Double))\n    es = (liftM (applyUpper w) us) >>= (setEdges (completeEdges ns))\n\n-- Graphon Model: generates a w-random graph. Parallel. \ngraphonGen' :: (Ord a, RandomGen g) => [a] -> (Double -> Double -> Double)\n  -> Rand g (Graph a)\ngraphonGen' ns w = liftM2 pseq (liftM2 par (liftM force es) (liftM force\n                               es')) (liftM (Graph ns) (liftM2 (++) es\n                               es'))\n  where\n    us = liftM (take (length ns)) $ getRandomRs ((0, 1) :: (Double, Double))\n    cs = completeEdges ns\n    n = length ns\n    cshalf = splitAt (((n * (n-1))+2) `div` 4) cs\n    es = (liftM (applyUpper w) us) >>= (setEdges (fst cshalf))\n    es' = (liftM (applyUpper w) us) >>= (setEdges (snd cshalf))\n\n-- From \"Real World Haskell\". Used in the parallel version of the code for\n-- generating w-random graphs, `graphonGen'`. \nforce :: [a] -> ()\nforce xs = go xs `pseq` ()\n  where go (_:xs) = go xs\n        go [] = 1\n\n-- Apply a function to the upper triangle of an array. \napplyUpper :: (a -> a -> b) -> [a] -> [b]\napplyUpper f xs = [ f (fst x) (fst y) | x <- zl, y <- zl, snd x < snd y ]\n  where\n    zl = zip xs ([1..] :: [Int])\n\nsblock :: Double -> Double -> Double\nsblock x y\n  | x < 0.5 && y < 0.5 = 0.8\n  | x < 0.5 || y < 0.5 = 0.2\n  | otherwise          = 0.8\n\n-- Need to create a show instance for this (or rewrite it). \nround' :: (RealFrac a, RealFrac b, Integral b) => Int -> a -> b\nround' x = (/ 10^x) . round . (* 10^x)\n\nmain :: IO ()\nmain = do\n    -- values <- evalRandIO $ graphonGen [1..10] (\\x y -> (x+y)/2)\n    let n = 100 :: Int\n    gr <- evalRandIO $ graphonGen [1..n] sblock\n    putStrLn . show . length $ community (toMap gr) 1\n    -- let spannum = spanTreeCount values\n    -- putStrLn . (\\x -> \"Number of spanning trees: \" ++ x) $ show spannum\n    -- putStrLn . show $ spectralCluster' values\n    -- putStrLn . (\\x -> \"Guess for optimal lambda: \" ++ x) . show\n    --  $ lambdaSelect values\n    -- putStrLn . (\\x -> \"This is \" ++ x ++ \"% of the true value.\" ) . show\n    --   . round' 4 . ((/) $ fromIntegral n^(n-2)) $ fromIntegral spannum\n", "meta": {"hexsha": "aea8d9fe8ee2ded62d99186bdac494d99468dca2", "size": 6675, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Graph.hs", "max_stars_repo_name": "kimolas/causal-haskell", "max_stars_repo_head_hexsha": "cadfa26fef2a53b943c1ac2de46913bd90a9abcd", "max_stars_repo_licenses": ["BSD-3-Clause", "MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-03-27T03:08:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-03T18:28:29.000Z", "max_issues_repo_path": "app/Graph.hs", "max_issues_repo_name": "kimolas/causal-haskell", "max_issues_repo_head_hexsha": "cadfa26fef2a53b943c1ac2de46913bd90a9abcd", "max_issues_repo_licenses": ["BSD-3-Clause", "MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-06-30T07:59:49.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-30T08:01:33.000Z", "max_forks_repo_path": "app/Graph.hs", "max_forks_repo_name": "kimolas/causal-haskell", "max_forks_repo_head_hexsha": "cadfa26fef2a53b943c1ac2de46913bd90a9abcd", "max_forks_repo_licenses": ["BSD-3-Clause", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.056122449, "max_line_length": 76, "alphanum_fraction": 0.6004494382, "num_tokens": 2204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4190122124776902}}
{"text": "-- |\n-- Module      : Occlusion.Vector\n-- Description :\n-- Copyright   : (c) Jonatan H Sundqvist, 2015\n-- License     : MIT\n-- Maintainer  : Jonatan H Sundqvist\n-- Stability   : experimental|stable\n-- Portability : POSIX (not sure)\n--\n\n-- Created Jonatan H Sundqvist 2015\n\n-- TODO | - Most of these functions should be moved to a utility library (eg. Cartesian)\n--        -\n\n-- SPEC | -\n--        -\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC Pragmas\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule Occlusion.Vector where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\nimport Data.Complex\nimport Data.Functor ((<$>))\nimport Data.List    (sort, sortBy)\nimport Control.Applicative\nimport Control.Lens\nimport Control.Monad\n\nimport Southpaw.Math.Constants\n\nimport Occlusion.Types\nimport Occlusion.Lenses\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- |\nvectorise :: (a -> a -> b) -> Complex a -> b\nvectorise f (x:+y) = f x y\n\n-- Plumbing --------------------------------------------------------------------------------------------------------------------------------\n\n-- |\ndotwise :: (a -> a -> a) -> Complex a -> Complex a -> Complex a\ndotwise f (x:+y) (x':+y') = f x x':+f y y'\n\n\n-- |\ndotmap :: (a -> a) -> Complex a -> Complex a\ndotmap f (x:+y) = f x:+f y\n\n-- Linear functions ------------------------------------------------------------------------------------------------------------------------\n\n-- |\n-- TODO: Refactor\n-- TODO: Invariants, check corner cases\n-- TODO: Deal with vertical lines\n-- TODO: Factor out infinite-line logic\n-- TODO: Decide how to deal with identical lines\n-- TODO: Factor out domain logic (eg. write restrict or domain function)\n-- TODO: Visual debugging functions\nintersect :: RealFloat f => Line f -> Line f -> Maybe (Complex f)\n-- intersect f@(Line a b) g@(Line a' b')\nintersect f' g' = mp >>= \\p -> indomain f' p >> indomain g' p\n  where\n    indomain h' = restrict (h'^.linebegin) (h'^.linestop)\n    mp = case [linear f', linear g'] of\n      [Just f, Nothing] -> let x = g'^.linebegin.real in Just $ (x):+(plotpoint f x)\n      [Nothing, Just g] -> let x = f'^.linebegin.real in Just $ (x):+(plotpoint g x)\n      [Just f,  Just g] -> linearIntersect f g\n      _                 -> Nothing\n\n\n-- | Gives the linear function overlapping the given segment\nlinear :: RealFloat f => Line f -> Maybe (Linear f)\nlinear line = (,) <$> slope line <*> intercept line\n\n\n-- | Applies a linear function to the given value\n-- TODO: Rename (?)\nplotpoint :: RealFloat f => Linear f -> f -> f\nplotpoint (slope', intercept') x = slope'*x + intercept'\n\n\n-- | Finds the intersection (if any) of two linear functions\nlinearIntersect :: RealFloat f => Linear f -> Linear f -> Maybe (Complex f)\nlinearIntersect (kf, mf) (kg, mg)\n  | kf == kg  = Nothing\n  | otherwise = let x = (mg-mf)/(kg-kg)\n                    y = (mf*x + kf)\n                in Just $ x:+y\n\n\n-- |\nslope :: RealFloat f => Line f -> Maybe f\nslope (Line fr to)\n  | dx == 0   = Nothing\n  | otherwise = Just $ dy/dx\n  where\n    (dx:+dy) = to - fr\n\n\n-- |\nintercept :: Line f -> Maybe f\nintercept (Line a b) = error \"\"\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n-- |\nbetween :: Ord a => a -> a -> a -> Bool\nbetween mini maxi a = mini <= a && a <= maxi\n\n\n-- | Ensures that a given point lies within the domain and codomain\n-- TODO: Let thus function work on scalars, write another function for domain and codomain (?)\n-- restrict domain codomain p = _\nrestrict :: Ord f => Complex f -> Complex f -> Complex f -> Maybe (Complex f)\nrestrict a b p@(x:+y)\n  | indomain && incodomain = Just p\n  | otherwise              = Nothing\n  where\n    (lowx:+lowy)   = dotwise min a b\n    (highx:+highy) = dotwise max a b\n    indomain       = between lowx highx x\n    incodomain     = between lowy highy y\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n-- |\npass :: Monad m => m ()\npass = return ()\n\n\n-- |\nunit :: Monad m => a -> m a\nunit = return\n\n\n-- | Like maybe, except the function comes at the end\nperhaps :: b -> Maybe a -> (a -> b) -> b\nperhaps d m f = maybe d f m\n", "meta": {"hexsha": "f48ef30c5defbed4d46b5bf73b9f323eac542950", "size": 5235, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Occlusion/Vector.hs", "max_stars_repo_name": "SwiftsNamesake/Occlusion", "max_stars_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Occlusion/Vector.hs", "max_issues_repo_name": "SwiftsNamesake/Occlusion", "max_issues_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Occlusion/Vector.hs", "max_forks_repo_name": "SwiftsNamesake/Occlusion", "max_forks_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.71875, "max_line_length": 140, "alphanum_fraction": 0.4150907354, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4190054896341362}}
{"text": "-- {-# LANGUAGE NoImplicitPrelude #-}\n{-# LANGUAGE DataKinds, GADTs, TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FunctionalDependencies #-}\n\nmodule HBLAS.BLAS.Level2Spec(main, spec) where\n\nimport Data.Complex\n\nimport Test.Hspec\n\nimport Numerical.HBLAS.MatrixTypes as Matrix\nimport Numerical.HBLAS.BLAS.Level2 as BLAS\nimport qualified Data.Vector.Storable as S\nimport qualified Data.Vector.Storable.Mutable as SM\n\nmain :: IO ()\nmain = hspec spec\n\nspec :: Spec\nspec = do\n  gbmvSpec\n  gemvSpec\n  gerSpec\n  gercSpec\n  geruSpec\n  hbmvSpec\n  hemvSpec\n  herSpec\n  her2Spec\n  hpmvSpec\n  hprSpec\n  hpr2Spec\n  sbmvSpec\n  spmvSpec\n  sprSpec\n  spr2Spec\n  symvSpec\n  syrSpec\n  syr2Spec\n  tbmvSpec\n  tbsvSpec\n  tpmvSpec\n  tpsvSpec\n  trmvSpec\n  trsvSpec\n  gemvBugJune2017\n\ngemvBugJune2017 :: Spec\ngemvBugJune2017  =\n  --context \"?gemv bug\"\n\n {-\n\n\n\n -}\n    describe \"dgemv abstraction\" $ do\n      it \"3*2 matrix vector product sadness\" $\n             let m = S.fromList [1,2,3, 4,5,6]\n                 x = S.fromList [10,20,30]\n             in\n             do\n\n              m' <- S.unsafeThaw m\n              x' <- S.unsafeThaw x\n              y' <- SM.new 2\n\n              let mat   = MutableDenseMatrix SRow 3 2 3 m'\n                  xvec  = MutableDenseVector SDirect 3 1 x'\n                  yvec  = MutableDenseVector SDirect 2 1 y'\n\n              dgemv NoTranspose 1 0 mat xvec yvec\n              resList <-mutableVectorToList $ _bufferMutDenseVector yvec\n              resList `shouldBe` [140, 320]\n\n\n\ngbmvSpec :: Spec\ngbmvSpec =\n  context \"?GBMV\" $ do\n    describe \"SGBMV\" $ do\n      it \"3x5 a(5x5 matrix) all 1's\" $ do\n        matvecTest1SGBMV\n    describe \"DBGMV\" $ do\n      it \"3x5 a(10x5 matrix) all 1's with beta 1.0\" $ do\n        matvecTest1DGBMV\n    describe \"CGBMV\" $ do\n      it \"2x4 a(4x4 matrix) all 1+i's\" $ do\n        matvecTest1CGBMV\n     -- it \"gbmv on 2x4 a(4x4 matrix) all 1+i s with conjnotranspose\" $ do\n     --   matvecTest2CGBMV -- conjnotranspose is invalid\n    describe \"ZGBMV\" $ do\n      it \"2x10 a(5x10 matrix) all 1+i s with transpose and alpha 1.0\" $ do\n        matvecTest1ZGBMV\n      it \"2x10 a(5x10 matrix) all 1+i s with conjtranspose and alpha 1.0\" $ do\n        matvecTest2ZGBMV\n\n\nmatvecTest1SGBMV :: IO ()\nmatvecTest1SGBMV = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 5) (\\_ -> (1.0))\n    x <- Matrix.generateMutableDenseVector 5 (\\_ -> (1.0))\n    res <- Matrix.generateMutableDenseVector 5 (\\_ -> (1.0))\n    BLAS.sgbmv Matrix.NoTranspose 5 5 1 1 1.0 a x 0.0 res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2, 3, 3, 3, 2]\n\nmatvecTest1DGBMV :: IO ()\nmatvecTest1DGBMV = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 5) (\\_ -> (1.0))\n    x <- Matrix.generateMutableDenseVector 5 (\\_ -> (1.0))\n    res <- Matrix.generateMutableDenseVector 10 (\\_ -> (1.0))\n    BLAS.dgbmv Matrix.NoTranspose 10 5 1 1 1.0 a x 1.0 res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [3, 4, 4, 4, 3, 1, 1, 1, 1, 1]\n    -- not [3, 4, 4, 4, 3, 2, 1, 1, 1, 1]\n\nmatvecTest1CGBMV :: IO ()\nmatvecTest1CGBMV = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2, 4) (\\(x, y) -> [1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 0] !! (x * 4 + y))\n    x <- Matrix.generateMutableDenseVector 4 (\\_ -> (1.0:+1.0))\n    res <- Matrix.generateMutableDenseVector 4 (\\_ -> (1.0:+1.0))\n    BLAS.cgbmv Matrix.NoTranspose 4 4 0 1 1.0 a x 0.0 res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [0:+4.0, 0:+4.0, 0:+4.0, 0:+2.0]\n\nmatvecTest2CGBMV :: IO ()\nmatvecTest2CGBMV = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2, 4) (\\(x, y) -> [1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 0] !! (x * 4 + y))\n    x <- Matrix.generateMutableDenseVector 4 (\\_ -> (1.0:+1.0))\n    res <- Matrix.generateMutableDenseVector 4 (\\_ -> (1.0:+1.0))\n    BLAS.cgbmv Matrix.ConjNoTranspose 4 4 0 1 1.0 a x 0.0 res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [4.0:+0, 4.0:+0, 4.0:+0, 2.0:+0]\n\nmatvecTest1ZGBMV :: IO ()\nmatvecTest1ZGBMV = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2, 10) (\\_ -> (1.0:+1.0))\n    x <- Matrix.generateMutableDenseVector 10 (\\_ -> (1.0:+1.0))\n    res <- Matrix.generateMutableDenseVector 5 (\\_ -> (1.0:+1.0))\n    BLAS.cgbmv Matrix.Transpose 10 5 1 0 2.0 a x 0.0 res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [0:+8.0, 0:+8.0, 0:+8.0, 0:+8.0, 0:+8.0]\n    -- not [0:+8.0, 0:+8.0, 0:+8.0, 0:+8.0, 0:+4.0]\n\nmatvecTest2ZGBMV :: IO ()\nmatvecTest2ZGBMV = do\n    a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2, 10) (\\_ -> (1.0:+1.0))\n    x <- Matrix.generateMutableDenseVector 10 (\\_ -> (1.0:+1.0))\n    res <- Matrix.generateMutableDenseVector 5 (\\_ -> (1.0:+1.0))\n    BLAS.cgbmv Matrix.ConjTranspose 10 5 1 0 2.0 a x 0.0 res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [8.0:+0, 8.0:+0, 8.0:+0, 8.0:+0, 8.0:+0]\n    -- not [0:+8.0, 0:+8.0, 0:+8.0, 0:+8.0, 0:+4.0]\n\n-- notes for gbmv\n-- column > rows: the tail of the supper diagonals is considered.\n-- rows > column: the tail of the sub diagonals is not considered.\n\n\ngemvSpec :: Spec\ngemvSpec =\n  context \"?GEMV\" $ do\n    describe \"SGEMV\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1SGEMV\n    describe \"DGEMV\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1DGEMV\n    describe \"CGEMV\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1CGEMV\n    describe \"ZGEMV\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1ZGEMV\n\nmatmatTest1SGEMV :: IO ()\nmatmatTest1SGEMV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (\\_ -> (1.0::Float))\n    right <- Matrix.generateMutableDenseVector 2 (\\_ -> (1.0 :: Float))\n    res  <- Matrix.generateMutableDenseVector  2 (\\_ -> (0.0 :: Float))\n    BLAS.sgemv Matrix.NoTranspose  1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2,2]\n\nmatmatTest1DGEMV :: IO ()\nmatmatTest1DGEMV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (\\_ -> (1.0))\n    right <- Matrix.generateMutableDenseVector 2 (\\_ -> (1.0 ))\n    res  <- Matrix.generateMutableDenseVector 2  (\\_ -> (0.0 ))\n    BLAS.dgemv Matrix.NoTranspose 1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2.0,2.0]\n\nmatmatTest1CGEMV :: IO ()\nmatmatTest1CGEMV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (\\_ -> (1.0))\n    right <- Matrix.generateMutableDenseVector 2 (\\_ -> (1.0 ))\n    res  <- Matrix.generateMutableDenseVector  2 (\\_ -> (0.0 ))\n    BLAS.cgemv Matrix.NoTranspose  1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2.0,2.0]\n\nmatmatTest1ZGEMV :: IO ()\nmatmatTest1ZGEMV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2) (\\_ -> (1.0))\n    right <- Matrix.generateMutableDenseVector 2 (\\_ -> (1.0 ))\n    res  <- Matrix.generateMutableDenseVector 2 (\\_ -> (0.0 ))\n    BLAS.zgemv Matrix.NoTranspose  1.0 1.0 left right res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2.0,2.0]\n\n----\n----\ngerSpec :: Spec\ngerSpec =\n  context \"?GER\" $ do\n    describe \"SGER\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1SGER\n    describe \"DGER\" $ do\n      it \"2x2 all 1's\" $ do\n        matmatTest1DGER\n\nmatmatTest1SGER :: IO ()\nmatmatTest1SGER = do\n  res <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,2) (\\_ -> 1.0)\n  x <- Matrix.generateMutableDenseVector 2 (\\_ -> 2.0)\n  y <- Matrix.generateMutableDenseVector 2 (\\_ -> 3.0)\n  BLAS.sger 2.0 x y res\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n  resList `shouldBe` [13.0,13.0,13.0,13.0]\n\nmatmatTest1DGER :: IO ()\nmatmatTest1DGER = do\n  res <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (2,2) (\\_ -> 1.0)\n  x <- Matrix.generateMutableDenseVector 2 (\\_ -> 2.0)\n  y <- Matrix.generateMutableDenseVector 2 (\\_ -> 3.0)\n  BLAS.sger 2.0 x y res\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n  resList `shouldBe` [13.0,13.0,13.0,13.0]\n\ngercSpec :: Spec\ngercSpec =\n  context \"?GERC\" $ do\n    describe \"CGERC\" $ do\n      it \"2x3 all 1+i's\" $ do\n        matmatTest1CGERC\n    describe \"ZGERC\" $ do\n      it \"2x3 all 1+i's\" $ do\n        matmatTest1ZGERC\n\nmatmatTest1CGERC :: IO ()\nmatmatTest1CGERC = do\n  res <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,2) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 2.0:+3.0)\n  y <- Matrix.generateMutableDenseVector 2 (\\_ -> 3.0:+2.0)\n  BLAS.cgerc 2.0 x y res\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n  resList `shouldBe` [25.0:+11.0, 25.0:+11.0, 1.0:+1.0, 25.0:+11.0, 25.0:+11.0, 1.0:+1.0]\n  -- why the following is not correct...\n  -- resList `shouldBe` [25.0:+11.0, 25.0:+11.0, 25.0:+11.0, 25.0:+11.0, 25.0:+11.0, 25.0:+11.0]\n\nmatmatTest1ZGERC :: IO ()\nmatmatTest1ZGERC = do\n  res <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,2) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 2.0:+3.0)\n  y <- Matrix.generateMutableDenseVector 2 (\\_ -> 3.0:+2.0)\n  BLAS.zgerc 2.0 x y res\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n  resList `shouldBe` [25.0:+11.0, 25.0:+11.0, 1.0:+1.0, 25.0:+11.0, 25.0:+11.0, 1.0:+1.0]\n  -- why the following is not correct...\n  -- resList `shouldBe` [25.0:+11.0, 25.0:+11.0, 25.0:+11.0, 25.0:+11.0, 25.0:+11.0, 25.0:+11.0]\n\ngeruSpec :: Spec\ngeruSpec =\n  context \"?GERU\" $ do\n    describe \"CGERU\" $ do\n      it \"2x3 all 1+i's\" $ do\n        matmatTest1CGERU\n    describe \"ZGERU\" $ do\n      it \"2x3 all 1+i's\" $ do\n        matmatTest1ZGERU\n\n\nmatmatTest1CGERU :: IO ()\nmatmatTest1CGERU = do\n  res <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,2) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 2.0:+(-3.0))\n  y <- Matrix.generateMutableDenseVector 2 (\\_ -> 3.0:+(-2.0))\n  BLAS.cgeru 2.0 x y res\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n  resList `shouldBe` [1.0:+(-25.0), 1.0:+(-25.0), 1.0:+1.0, 1.0:+(-25.0), 1.0:+(-25.0), 1.0:+1.0]\n  -- why the following is not correct...\n  -- resList `shouldBe` [1.0:+(-25.0), 1.0:+(-25.0), 1.0:+(-25.0), 1.0:+(-25.0), 1.0:+(-25.0), 1.0:+(-25.0)]\n\nmatmatTest1ZGERU :: IO ()\nmatmatTest1ZGERU = do\n  res <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3,2) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 2.0:+(-3.0))\n  y <- Matrix.generateMutableDenseVector 2 (\\_ -> 3.0:+(-2.0))\n  BLAS.zgeru 2.0 x y res\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat res\n  resList `shouldBe` [1.0:+(-25.0), 1.0:+(-25.0), 1.0:+1.0, 1.0:+(-25.0), 1.0:+(-25.0), 1.0:+1.0]\n  -- why the following is not correct...\n  -- resList `shouldBe` [1.0:+(-25.0), 1.0:+(-25.0), 1.0:+(-25.0), 1.0:+(-25.0), 1.0:+(-25.0), 1.0:+(-25.0)]\n\n-- [1:+0    1:+1    1:+1    0:+0]\n-- [1:+(-1) 1:+0    1:+1    1:+1]\n-- [1:+(-1) 1:+(-1) 1:+0    1:+1]\n-- [0:+0    1:+(-1) 1:+(-1) 1:+0]\n--\n-- [1:+1]\n-- [1:+1]\n-- [1:+1]\n-- [1:+1]\n\nhbmvSpec :: Spec\nhbmvSpec =\n  context \"?HBMV\" $ do\n    describe \"CHBMV\" $ do\n      it \"4*3 a(4x4 matrix) upper all 1+i's\" $ do\n        matvecTest1CHBMV\n      it \"4*3 a(4x4 matrix) upper all 1+i's (column oriented)\" $ do\n        matvecTest2CHBMV\n    describe \"ZHBMV\" $ do\n      it \"4*3 a(4x4 matrix) lower all 1+i's\" $ do\n        matvecTest1ZHBMV\n\n\nmatvecTest1CHBMV :: IO ()\nmatvecTest1CHBMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 3) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\_ -> 1.0:+1.0)\n  y <- Matrix.generateMutableDenseVector 4 (\\_ -> 0.0:+0.0)\n  BLAS.chbmv Matrix.MatUpper 2 1.0 a x 0.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [1.0:+5.0, 3.0:+5.0, 5.0:+3.0, 5.0:+1.0]\n\nmatvecTest2CHBMV :: IO ()\nmatvecTest2CHBMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (4, 3) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\_ -> 1.0:+1.0)\n  y <- Matrix.generateMutableDenseVector 4 (\\_ -> 0.0:+0.0)\n  BLAS.chbmv Matrix.MatUpper 2 1.0 a x 0.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [1.0:+5.0, 3.0:+5.0, 5.0:+3.0, 5.0:+1.0]\n\n-- [1:+0    1:+1    1:+1    0:+0]\n-- [1:+(-1) 1:+0    1:+1    1:+1]\n-- [1:+(-1) 1:+(-1) 1:+0    1:+1]\n-- [0:+0    1:+(-1) 1:+(-1) 1:+0]\n--\n-- [1:+1]\n-- [1:+1]\n-- [1:+1]\n-- [1:+1]\nmatvecTest1ZHBMV :: IO ()\nmatvecTest1ZHBMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 3) (\\_ -> 1.0:+(-1.0))\n  x <- Matrix.generateMutableDenseVector 4 (\\_ -> 1.0:+1.0)\n  y <- Matrix.generateMutableDenseVector 4 (\\_ -> 0.0:+0.0)\n  BLAS.zhbmv Matrix.MatLower 2 1.0 a x 0.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [1.0:+5.0, 3.0:+5.0, 5.0:+3.0, 5.0:+1.0]\n\n-- [1:+0    1:+1    1:+1    1:+1]\n-- [1:+(-1) 1:+0    1:+1    1:+1]\n-- [1:+(-1) 1:+(-1) 1:+0    1:+1]\n-- [1:+(-1) 1:+(-1) 1:+(-1) 1:+0]\n--\n-- [1:+1]\n-- [1:+1]\n-- [1:+1]\n-- [1:+1]\n--\nhemvSpec :: Spec\nhemvSpec =\n  context \"?HEMV\" $ do\n    describe \"CHEMV\" $ do\n      it \"4*3 a(4x4 matrix) upper all 1+i's\" $ do\n        matvecTest1CHEMV\n      it \"4*3 a(4x4 matrix) upper all 1+i s (column oriented)\" $ do\n        matvecTest2CHEMV\n    describe \"ZHEMV\" $ do\n      it \"4*3 a(4x4 matrix) lower all 1+i's\" $ do\n        matvecTest1ZHEMV\n\nmatvecTest1CHEMV :: IO ()\nmatvecTest1CHEMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 4) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\_ -> 1.0:+1.0)\n  y <- Matrix.generateMutableDenseVector 4 (\\_ -> 0.0:+0.0)\n  BLAS.chemv Matrix.MatUpper 1.0 a x 0.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [1.0:+7.0, 3.0:+5.0, 5.0:+3.0, 7.0:+1.0]\n\nmatvecTest2CHEMV :: IO ()\nmatvecTest2CHEMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (4, 4) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\_ -> 1.0:+1.0)\n  y <- Matrix.generateMutableDenseVector 4 (\\_ -> 0.0:+0.0)\n  BLAS.chemv Matrix.MatUpper 1.0 a x 0.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [1.0:+7.0, 3.0:+5.0, 5.0:+3.0, 7.0:+1.0]\n\nmatvecTest1ZHEMV :: IO ()\nmatvecTest1ZHEMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 4) (\\_ -> 1.0:+(-1.0))\n  x <- Matrix.generateMutableDenseVector 4 (\\_ -> 1.0:+1.0)\n  y <- Matrix.generateMutableDenseVector 4 (\\_ -> 0.0:+0.0)\n  BLAS.zhemv Matrix.MatLower 1.0 a x 0.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [1.0:+7.0, 3.0:+5.0, 5.0:+3.0, 7.0:+1.0]\n\nherSpec :: Spec\nherSpec =\n  context \"?HER\" $ do\n    describe \"CHER\" $ do\n      it \"4*4 a upper all 1+i's\" $ do\n        matvecTest1CHER\n    describe \"ZHER\" $ do\n      it \"4*4 a upper all 1+i's\" $ do\n        matvecTest1ZHER\n\nmatvecTest1CHER :: IO ()\nmatvecTest1CHER = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 4) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0] !! idx)\n  BLAS.cher Matrix.MatUpper 1.0 x a\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat a\n  resList `shouldBe` [3.0:+0.0, 5.0:+1.0,  7.0:+1.0,  9.0:+1.0,\n               1.0:+1.0, 9.0:+0.0, 13.0:+1.0, 17.0:+1.0,\n               1.0:+1.0, 1.0:+1.0, 19.0:+0.0, 25.0:+1.0,\n               1.0:+1.0, 1.0:+1.0,  1.0:+1.0, 33.0:+0.0]\n\nmatvecTest1ZHER :: IO ()\nmatvecTest1ZHER = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 4) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0] !! idx)\n  BLAS.zher Matrix.MatLower 1.0 x a\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat a\n  resList `shouldBe` [3.0:+0.0,  1.0:+1.0,  1.0:+1.0,  1.0:+1.0,\n               5.0:+1.0,  9.0:+0.0,  1.0:+1.0,  1.0:+1.0,\n               7.0:+1.0, 13.0:+1.0, 19.0:+0.0,  1.0:+1.0,\n               9.0:+1.0, 17.0:+1.0, 25.0:+1.0, 33.0:+0.0]\n\nher2Spec :: Spec\nher2Spec =\n  context \"?HER2\" $ do\n    describe \"CHER2\" $ do\n      it \"4*4 a upper all 1+i's\" $ do\n        matvecTest1CHER2\n    describe \"ZHER2\" $ do\n      it \"4*4 a upper all 1+i's\" $ do\n        matvecTest1ZHER2\n\nmatvecTest1CHER2 :: IO ()\nmatvecTest1CHER2 = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 4) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0] !! idx)\n  y <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0] !! idx)\n  BLAS.cher2 Matrix.MatUpper 1.0 x y a\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat a\n  resList `shouldBe` [5.0:+0.0,  9.0:+1.0, 13.0:+1.0, 17.0:+1.0,\n               1.0:+1.0, 17.0:+0.0, 25.0:+1.0, 33.0:+1.0,\n               1.0:+1.0,  1.0:+1.0, 37.0:+0.0, 49.0:+1.0,\n               1.0:+1.0,  1.0:+1.0,  1.0:+1.0, 65.0:+0.0]\n\nmatvecTest1ZHER2 :: IO ()\nmatvecTest1ZHER2 = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 4) (\\_ -> 1.0:+1.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0] !! idx)\n  y <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0] !! idx)\n  BLAS.zher2 Matrix.MatLower 1.0 x y a\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat a\n  resList `shouldBe` [ 5.0:+0.0,  1.0:+1.0,  1.0:+1.0,  1.0:+1.0,\n                9.0:+1.0, 17.0:+0.0,  1.0:+1.0,  1.0:+1.0,\n               13.0:+1.0, 25.0:+1.0, 37.0:+0.0,  1.0:+1.0,\n               17.0:+1.0, 33.0:+1.0, 49.0:+1.0, 65.0:+0.0]\n\n\nhpmvSpec :: Spec\nhpmvSpec =\n  context \"?HPMV\" $ do\n    describe \"CHPMV\" $ do\n      it \"4*4 a upper (row oriented)\" $ do\n        matvecTest1CHPMV\n    describe \"ZHPMV\" $ do\n      it \"4*4 a upper (column oriented)\" $ do\n        matvecTest1ZHPMV\n\n-- [0:+0    1:+1    2:+2    3:+3]\n-- [1:+(-1) 4:+0    5:+5    6:+6]\n-- [2:+(-2) 5:+(-5) 7:+0    8:+8]\n-- [3:+(-3) 6:+(-6) 8:+(-8) 9:+0]\n--\n-- [2:+2]\n-- [2:+2]\n-- [2:+2]\n-- [2:+2]\n--\n-- [ 3:+27]\n-- [15:+55]\n-- [45:+49]\n-- [89:+21]\nmatvecTest1CHPMV :: IO ()\nmatvecTest1CHPMV = do\n  a <- Matrix.generateMutableDenseVector 10 (\\idx -> [0.0:+0.0, 1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0, 5.0:+5.0, 6.0:+6.0, 7.0:+7.0, 8.0:+8.0, 9.0:+9.0] !! idx)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [2.0:+2.0, 2.0:+2.0, 2.0:+2.0, 2.0:+2.0] !! idx)\n  y <- Matrix.generateMutableDenseVector 4 (\\idx -> [3.0:+3.0, 3.0:+3.0, 3.0:+3.0, 3.0:+3.0] !! idx)\n  BLAS.chpmv Matrix.SRow Matrix.MatUpper 4 1.0 a x 1.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [ 3.0:+27.0, 15.0:+55.0, 45.0:+49.0, 89.0:+21.0]\n\n-- [0:+0    1:+1    3:+3    6:+6]\n-- [1:+(-1) 2:+0    4:+4    7:+7]\n-- [3:+(-3) 4:+(-4) 5:+0    8:+8]\n-- [6:+(-6) 7:+(-7) 8:+(-8) 9:+0]\n--\n-- [2:+2]\n-- [2:+2]\n-- [2:+2]\n-- [2:+2]\n--\n-- [  6:+46]\n-- [ 14:+54]\n-- [ 44:+48]\n-- [108:+24]\nmatvecTest1ZHPMV :: IO ()\nmatvecTest1ZHPMV = do\n  a <- Matrix.generateMutableDenseVector 10 (\\idx -> [0.0:+0.0, 1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0, 5.0:+5.0, 6.0:+6.0, 7.0:+7.0, 8.0:+8.0, 9.0:+9.0] !! idx)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [2.0:+2.0, 2.0:+2.0, 2.0:+2.0, 2.0:+2.0] !! idx)\n  y <- Matrix.generateMutableDenseVector 4 (\\idx -> [3.0:+3.0, 3.0:+3.0, 3.0:+3.0, 3.0:+3.0] !! idx)\n  BLAS.zhpmv Matrix.SColumn Matrix.MatUpper 4 1.0 a x 2.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [ 6.0:+46.0, 14.0:+54.0, 44.0:+48.0, 108.0:+24.0]\n\n-- [1:+1]\n-- [2:+2]\n-- [3:+3]\n-- [4:+4]\n--\n-- [2:+0    4:+0    6:+0    8:+0 ]\n-- [4:+0    8:+0    12:+0   16:+0]\n-- [6:+0    12:+0   18:+0   24:+0]\n-- [8:+0    16:+0   24:+0   32:+0]\n--\n-- [0:+0    1:+1    3:+3    6:+6]\n-- [1:+(-1) 2:+0    4:+4    7:+7]\n-- [3:+(-3) 4:+(-4) 5:+0    8:+8]\n-- [6:+(-6) 7:+(-7) 8:+(-8) 9:+0]\n--\n-- [2:+0     5:+1     9:+3     14:+6]\n-- [5:+(-1)  10:+0    16:+4    23:+7]\n-- [9:+(-3)  16:+(-4) 23:+0    32:+8]\n-- [14:+(-6) 23:+(-7) 32:+(-8) 41:+0]\n\nhprSpec :: Spec\nhprSpec =\n  context \"?HPR\" $ do\n    describe \"CHPR\" $ do\n      it \"4*4 a upper (column oriented)\" $ do\n        matvecTest1CHPR\n    describe \"ZHPR\" $ do\n      it \"4*4 a lower (row oriented)\" $ do\n        matvecTest1ZHPR\n\nmatvecTest1CHPR :: IO ()\nmatvecTest1CHPR = do\n  a <- Matrix.generateMutableDenseVector 10 (\\idx -> [0.0:+0.0, 1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0, 5.0:+5.0, 6.0:+6.0, 7.0:+7.0, 8.0:+8.0, 9.0:+9.0] !! idx)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0] !! idx)\n  BLAS.chpr Matrix.SColumn Matrix.MatUpper 4 1.0 x a\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector a\n  resList `shouldBe` [2.0:+0.0, 5.0:+1.0, 10.0:+0.0, 9.0:+3.0, 16.0:+4.0, 23.0:+0.0, 14.0:+6.0, 23.0:+7.0,  32.0:+8.0, 41.0:+0.0]\n\n-- [1:+1]\n-- [2:+2]\n-- [3:+3]\n-- [4:+4]\n--\n-- [2:+0    4:+0    6:+0    8:+0 ]\n-- [4:+0    8:+0    12:+0   16:+0]\n-- [6:+0    12:+0   18:+0   24:+0]\n-- [8:+0    16:+0   24:+0   32:+0]\n--\n-- [0:+0    1:+1    3:+3    6:+6]\n-- [1:+(-1) 2:+0    4:+4    7:+7]\n-- [3:+(-3) 4:+(-4) 5:+0    8:+8]\n-- [6:+(-6) 7:+(-7) 8:+(-8) 9:+0]\n--\n-- [2:+0     5:+1     9:+3     14:+6]\n-- [5:+(-1)  10:+0    16:+4    23:+7]\n-- [9:+(-3)  16:+(-4) 23:+0    32:+8]\n-- [14:+(-6) 23:+(-7) 32:+(-8) 41:+0]\nmatvecTest1ZHPR :: IO ()\nmatvecTest1ZHPR = do\n  a <- Matrix.generateMutableDenseVector 10 (\\idx -> [0.0:+(-0.0), 1.0:+(-1.0), 2.0:+(-2.0), 3.0:+(-3.0), 4.0:+(-4.0), 5.0:+(-5.0), 6.0:+(-6.0), 7.0:+(-7.0), 8.0:+(-8.0), 9.0:+(-9.0)] !! idx)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 2.0:+2.0, 3.0:+3.0, 4.0:+4.0] !! idx)\n  BLAS.zhpr Matrix.SRow Matrix.MatLower 4 1.0 x a\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector a\n  resList `shouldBe` [2.0:+0.0, 5.0:+(-1.0), 10.0:+0.0, 9.0:+(-3.0), 16.0:+(-4.0), 23.0:+0.0, 14.0:+(-6.0), 23.0:+(-7.0), 32.0:+(-8.0), 41.0:+0.0]\n\n\nhpr2Spec :: Spec\nhpr2Spec =\n  context \"?HPR2\" $ do\n    describe \"CHRP2\" $ do\n      it \"4*4 a upper (column oriented)\" $ do\n        matvecTest1CHPR2\n    describe \"ZHRP2\" $ do\n      it \"4*4 a upper (row oriented)\" $ do\n        matvecTest1ZHPR2\n\n-- [12:+0 ...]\n-- [.       ...]\n-- [.       ...]\n-- [.       ...]\n--\nmatvecTest1CHPR2 :: IO ()\nmatvecTest1CHPR2 = do\n  a <- Matrix.generateMutableDenseVector 10 (\\_ -> 0.0:+0.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0] !! idx)\n  y <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+2.0, 1.0:+2.0, 1.0:+2.0, 1.0:+2.0] !! idx)\n  BLAS.chpr2 Matrix.SColumn Matrix.MatUpper 4 2.0 x y a\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector a\n  resList `shouldBe` [12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0]\n\nmatvecTest1ZHPR2 :: IO ()\nmatvecTest1ZHPR2 = do\n  a <- Matrix.generateMutableDenseVector 10 (\\_ -> 0.0:+0.0)\n  x <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+1.0, 1.0:+1.0, 1.0:+1.0, 1.0:+1.0] !! idx)\n  y <- Matrix.generateMutableDenseVector 4 (\\idx -> [1.0:+2.0, 1.0:+2.0, 1.0:+2.0, 1.0:+2.0] !! idx)\n  BLAS.zhpr2 Matrix.SColumn Matrix.MatUpper 4 2.0 x y a\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector a\n  resList `shouldBe` [12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0, 12.0:+0.0]\n\n-- [1 2 0 0]\n-- [2 3 4 0]\n-- [0 4 5 6]\n-- [0 0 6 7]\n--\n-- [1 2]\n-- [3 4]\n-- [5 6]\n-- [7 0]\n--\n-- [5]\n-- [11]\n-- [17]\n-- [15]\n\nsbmvSpec :: Spec\nsbmvSpec =\n  context \"?SBMV\" $ do\n    describe \"SSBMV\" $ do\n      it \"4*4 a upper (row oriented)\" $ do\n        matvecTest1SSBMV\n    describe \"DSBMV\" $ do\n      it \"4*4 a lower (column oriented)\" $ do\n        matvecTest1DSBMV\n\nmatvecTest1SSBMV :: IO ()\nmatvecTest1SSBMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (4, 2) (\\(x, y) -> [1, 2, 3, 4, 5, 6, 7, 0] !! (y * 4 + x))\n  x <- Matrix.generateMutableDenseVector 4 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 4 (\\_ -> 2)\n  BLAS.ssbmv Matrix.MatUpper 1 1.0 a x 1.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [5, 11, 17, 15]\n\n-- [1 3 5 7]\n-- [2 4 6 0]\n\nmatvecTest1DSBMV :: IO ()\nmatvecTest1DSBMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (4, 2) (\\(x, y) -> [1, 3, 5, 7, 2, 4, 6, 0] !! (y * 4 + x))\n  x <- Matrix.generateMutableDenseVector 4 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 4 (\\_ -> 2)\n  BLAS.dsbmv Matrix.MatLower 1 1.0 a x 1.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [5, 11, 17, 15]\n\nspmvSpec :: Spec\nspmvSpec =\n  context \"?SPMV\" $ do\n    describe \"SSPMV\" $ do\n      it \"3*3 a upper (row oriented)\" $ do\n        matvecTest1SSPMV\n    describe \"DSPMV\" $ do\n      it \"3*3 a lower (column oriented)\" $ do\n        matvecTest1DSPMV\n\nmatvecTest1SSPMV :: IO ()\nmatvecTest1SSPMV = do\n  a <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 2, 3, 4, 5, 6] !! idx)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 3 (\\_ -> 2)\n  BLAS.sspmv Matrix.SRow Matrix.MatUpper 3 1.0 a x 1.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [8, 13, 16]\n\nmatvecTest1DSPMV :: IO ()\nmatvecTest1DSPMV = do\n  a <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 2, 3, 4, 5, 6] !! idx)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 3 (\\_ -> 2)\n  BLAS.dspmv Matrix.SColumn Matrix.MatLower 3 1.0 a x 1.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [8, 13, 16]\n\nsprSpec :: Spec\nsprSpec =\n  context \"?SPR\" $ do\n    describe \"SSPR\" $ do\n      it \"3*3 a upper (row oriented)\" $ do\n        matvecTest1SSPR\n    describe \"DSPR\" $ do\n      it \"3*3 a upper (column oriented)\" $ do\n        matvecTest1DSPR\n\nmatvecTest1SSPR :: IO ()\nmatvecTest1SSPR = do\n  a <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 2, 3, 4, 5, 6] !! idx)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  BLAS.sspr Matrix.SRow Matrix.MatUpper 3 1.0 x a\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector a\n  resList `shouldBe` [2, 3, 4, 5, 6, 7]\n\nmatvecTest1DSPR :: IO ()\nmatvecTest1DSPR = do\n  a <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 2, 3, 4, 5, 6] !! idx)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  BLAS.dspr Matrix.SRow Matrix.MatUpper 3 1.0 x a\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector a\n  resList `shouldBe` [2, 3, 4, 5, 6, 7]\n\nspr2Spec :: Spec\nspr2Spec =\n  context \"?SPR2\" $ do\n    describe \"SSPR2\" $ do\n      it \"3*3 a upper (row oriented)\" $ do\n        matvecTest1SSPR2\n    describe \"DSPR2\" $ do\n      it \"3*3 a upper (column oriented)\" $ do\n        matvecTest1DSPR2\n\n\nmatvecTest1SSPR2 :: IO ()\nmatvecTest1SSPR2 = do\n  a <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 2, 3, 4, 5, 6] !! idx)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 3 (\\idx -> [1, 2, 3] !! idx)\n  BLAS.sspr2 Matrix.SRow Matrix.MatUpper 3 1.0 x y a\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector a\n  resList `shouldBe` [3, 5, 7, 8, 10, 12]\n\nmatvecTest1DSPR2 :: IO ()\nmatvecTest1DSPR2 = do\n  a <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 2, 3, 4, 5, 6] !! idx)\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 3 (\\idx -> [1, 2, 3] !! idx)\n  BLAS.dspr2 Matrix.SRow Matrix.MatUpper 3 1.0 x y a\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector a\n  resList `shouldBe` [3, 5, 7, 8, 10, 12]\n\n\nsymvSpec :: Spec\nsymvSpec =\n  context \"?SYMV\" $ do\n    describe \"SSYMV\" $ do\n      it \"3*3 a upper (row oriented)\" $ do\n        matvecTest1SSYMV\n    describe \"DSYMV\" $ do\n      it \"3*3 a lower (column oriented)\" $ do\n        matvecTest1DSYMV\n\n-- [1 2 3]\n-- [0 5 6]\n-- [0 0 7]\nmatvecTest1SSYMV :: IO ()\nmatvecTest1SSYMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 3) (\\(x, y) -> [1, 2, 3, 0, 5, 6, 0, 0, 7] !! (y * 3 + x))\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 3 (\\_ -> 2)\n  BLAS.ssymv Matrix.MatUpper 1.0 a x 1.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [8, 15, 18]\n\nmatvecTest1DSYMV :: IO ()\nmatvecTest1DSYMV = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 3) (\\(x, y) -> [1, 0, 0, 2, 5, 0, 3, 6, 7] !! (y * 3 + x))\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 3 (\\_ -> 2)\n  BLAS.dsymv Matrix.MatLower 1.0 a x 1.0 y\n  resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector y\n  resList `shouldBe` [8, 15, 18]\n\n\nsyrSpec :: Spec\nsyrSpec =\n  context \"?SYR\" $ do\n    describe \"SSYR\" $ do\n      it \"3*3 a upper (row oriented)\" $ do\n        matvecTest1SSYR\n    describe \"DSYR\" $ do\n      it \"3*3 a upper (column oriented)\"$ do\n        matvecTest1DSYR\n-- [1 2 3]\n-- [0 5 6]\n-- [0 0 7]\nmatvecTest1SSYR :: IO ()\nmatvecTest1SSYR = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 3) (\\(x, y) -> [1, 2, 3, 0, 5, 6, 0, 0, 7] !! (y * 3 + x))\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  BLAS.ssyr Matrix.MatUpper 1.0 x a\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat a\n  resList `shouldBe` [2, 3, 4, 0, 6, 7, 0, 0, 8]\n\nmatvecTest1DSYR :: IO ()\nmatvecTest1DSYR = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 3) (\\(x, y) -> [1, 0, 0, 2, 5, 0, 3, 6, 7] !! (y * 3 + x))\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  BLAS.dsyr Matrix.MatLower 1.0 x a\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat a\n  resList `shouldBe` [2, 3, 4, 0, 6, 7, 0, 0, 8]\n\nsyr2Spec :: Spec\nsyr2Spec =\n  context \"?SYR2\" $ do\n    describe \"SSYR2\" $ do\n      it \"3*3 a upper (row oriented)\" $ do\n        matvecTest1SSYR2\n    describe \"DSYR2\" $ do\n      it \"3*3 a upper (column oriented)\" $ do\n        matvecTest1DSYR2\n\nmatvecTest1SSYR2 :: IO ()\nmatvecTest1SSYR2 = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SRow) (3, 3) (\\(x, y) -> [1, 2, 3, 0, 5, 6, 0, 0, 7] !! (y * 3 + x))\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 3 (\\idx -> [1, 2, 3] !! idx)\n  BLAS.ssyr2 Matrix.MatUpper 1.0 x y a\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat a\n  resList `shouldBe` [3, 5, 7, 0, 9, 11, 0, 0, 13]\n\nmatvecTest1DSYR2 :: IO ()\nmatvecTest1DSYR2 = do\n  a <- Matrix.generateMutableDenseMatrix (Matrix.SColumn) (3, 3) (\\(x, y) -> [1, 0, 0, 2, 5, 0, 3, 6, 7] !! (y * 3 + x))\n  x <- Matrix.generateMutableDenseVector 3 (\\_ -> 1)\n  y <- Matrix.generateMutableDenseVector 3 (\\idx -> [1, 2, 3] !! idx)\n  BLAS.dsyr2 Matrix.MatLower 1.0 x y a\n  resList <- Matrix.mutableVectorToList $ _bufferDenMutMat a\n  resList `shouldBe` [3, 5, 7, 0, 9, 11, 0, 0, 13]\n\n\ntbmvSpec :: Spec\ntbmvSpec =\n  context \"?TBMV\" $ do\n    describe \"STBMV\" $ do\n      it \"3x3 upper no trans (row oriented)\" $ do\n        matmatTest1STBMV\n    describe \"DTBMV\" $ do\n      it \"3x3 lower trans (column oriented)\" $ do\n        matmatTest1DTBMV\n    describe \"CTBMV\" $ do\n      it \"3x3 upper conj trans (row oriented)\" $ do\n        matmatTest1CTBMV\n    describe \"ZTBMV\" $ do\n      it \"3x3 lower no trans (row oriented)\" $ do\n        matmatTest1ZTBMV\n\n-- [ 1 2 0]   [-2]   [4]\n-- [ 0 1 1] * [ 3] = [5]\n-- [ 0 0 1]   [ 2]   [2]\nmatmatTest1STBMV:: IO ()\nmatmatTest1STBMV = do\n    a  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (3, 2) (\\(x, y) -> [0, 2, 1, 1, 1, 1] !! (y * 3 + x))\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [-2, 3, 2] !! idx)\n    BLAS.stbmv MatUpper NoTranspose MatUnit 1 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [4, 5, 2]\n\n-- [1 1 0]   [-2]   [1]\n-- [0 1 1] * [ 3] = [5]\n-- [0 0 1]   [ 2]   [2]\nmatmatTest1DTBMV:: IO ()\nmatmatTest1DTBMV = do\n    a  <- Matrix.generateMutableDenseMatrix (Matrix.SColumn)  (3, 2) (\\(x, y) -> [0, 1, 1, 1, 1, 1] !! (y * 3 + x))\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [-2, 3, 2] !! idx)\n    BLAS.dtbmv MatLower Transpose MatUnit 1 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [1, 5, 2]\n\n-- [ 1:+0    0:+0    0:+0]   [-2]   [-2:+0   ]\n-- [ 2:+(-2) 1:+0    0:+0] * [ 3] = [-1:+4   ]\n-- [ 0:+0    1:+(-1) 1:+0]   [ 2]   [ 5:+(-3)]\nmatmatTest1CTBMV:: IO ()\nmatmatTest1CTBMV = do\n    a  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (3, 2) (\\(x, y) -> [0:+0, 2:+2, 1:+1, 1:+1, 1:+1, 1:+1] !! (y * 3 + x))\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [-2, 3, 2] !! idx)\n    BLAS.ctbmv MatUpper Matrix.ConjTranspose MatUnit 1 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [(-2):+0, (-1):+4, 5:+(-3)]\n\n-- [1 1 0]   [2]   [5]\n-- [0 1 1] * [3] = [5]\n-- [0 0 1]   [2]   [2]\nmatmatTest1ZTBMV:: IO ()\nmatmatTest1ZTBMV = do\n    a  <- Matrix.generateMutableDenseMatrix (Matrix.SColumn)  (3, 2) (\\(x, y) -> [0:+0, 1:+0, 1:+0, 1:+0, 1:+0, 1:+0] !! (y * 3 + x))\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [2, 3, 2] !! idx)\n    BLAS.ztbmv MatUpper NoTranspose MatNonUnit 1 a x -- TODO: NAN error when using Lower Transpose\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [5, 5, 2]\n\n\ntbsvSpec :: Spec\ntbsvSpec =\n  context \"?TBSV\" $ do\n    describe \"STBSV\" $ do\n      it \"3x3 upper no trans (row oriented)\" $ do\n        matmatTest1STBSV\n    describe \"DTBSV\" $ do\n      it \"3x3 lower trans (column oriented)\" $ do\n        matmatTest1DTBSV\n    describe \"CTBSV\" $ do\n      it \"3x3 upper conj trans (row oriented)\" $ do\n        matmatTest1CTBSV\n    describe \"ZTBSV\" $ do\n      it \"3x3 lower no trans (row oriented)\" $ do\n        matmatTest1ZTBSV\n\n\n-- [ 1 2 0]   [-2]   [4]\n-- [ 0 1 1] * [ 3] = [5]\n-- [ 0 0 1]   [ 2]   [2]\nmatmatTest1STBSV:: IO ()\nmatmatTest1STBSV = do\n    a  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (3, 2) (\\(x, y) -> [0, 2, 1, 1, 1, 1] !! (y * 3 + x))\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [4, 5, 2] !! idx)\n    BLAS.stbsv MatUpper NoTranspose MatUnit 1 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [-2, 3, 2]\n\n-- [1 1 0]   [-2]   [1]\n-- [0 1 1] * [ 3] = [5]\n-- [0 0 1]   [ 2]   [2]\nmatmatTest1DTBSV:: IO ()\nmatmatTest1DTBSV = do\n    a  <- Matrix.generateMutableDenseMatrix (Matrix.SColumn)  (3, 2) (\\(x, y) -> [0, 1, 1, 1, 1, 1] !! (y * 3 + x))\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [1, 5, 2] !! idx)\n    BLAS.dtbsv MatLower Transpose MatUnit 1 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [-2, 3, 2]\n\n-- [ 1:+0    0:+0    0:+0]   [-2]   [-2:+0   ]\n-- [ 2:+(-2) 1:+0    0:+0] * [ 3] = [-1:+4   ]\n-- [ 0:+0    1:+(-1) 1:+0]   [ 2]   [ 5:+(-3)]\nmatmatTest1CTBSV:: IO ()\nmatmatTest1CTBSV = do\n    a  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (3, 2) (\\(x, y) -> [0:+0, 2:+2, 1:+1, 1:+1, 1:+1, 1:+1] !! (y * 3 + x))\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [(-2):+0, (-1):+4, 5:+(-3)] !! idx)\n    BLAS.ctbsv MatUpper Matrix.ConjTranspose MatUnit 1 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [-2, 3, 2]\n\n-- [1 1 0]   [2]   [5]\n-- [0 1 1] * [3] = [5]\n-- [0 0 1]   [2]   [2]\nmatmatTest1ZTBSV:: IO ()\nmatmatTest1ZTBSV = do\n    a  <- Matrix.generateMutableDenseMatrix (Matrix.SColumn)  (3, 2) (\\(x, y) -> [0:+0, 1:+0, 1:+0, 1:+0, 1:+0, 1:+0] !! (y * 3 + x))\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [5, 5, 2] !! idx)\n    BLAS.ztbsv MatUpper NoTranspose MatNonUnit 1 a x -- TODO: NAN error when using Lower Transpose\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [2, 3, 2]\n\n\ntpmvSpec :: Spec\ntpmvSpec =\n  context \"?TPMV\" $ do\n    describe \"STPMV\" $ do\n      it \"3x3 upper no trans (row oriented)\" $ do\n        matmatTest1STPMV\n    describe \"DTPMV\" $ do\n      it \"3x3 lower trans (column oriented)\" $ do\n        matmatTest1DTPMV\n    describe \"CTPMV\" $ do\n      it \"3x3 upper conj trans (row oriented)\" $ do\n        matmatTest1CTPMV\n    describe \"ZTPMV\" $ do\n      it \"3x3 lower no trans (row oriented)\" $ do\n        matmatTest1ZTPMV\n\n-- [ 1 2 0]   [-2]   [4]\n-- [ 0 1 1] * [ 3] = [5]\n-- [ 0 0 1]   [ 2]   [2]\nmatmatTest1STPMV:: IO ()\nmatmatTest1STPMV = do\n    a  <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 2, 0, 1, 1, 1] !! idx)\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [-2, 3, 2] !! idx)\n    BLAS.stpmv Matrix.SRow MatUpper NoTranspose MatUnit 3 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [4, 5, 2]\n\n-- [1 1 0]   [-2]   [1]\n-- [0 1 1] * [ 3] = [5]\n-- [0 0 1]   [ 2]   [2]\nmatmatTest1DTPMV:: IO ()\nmatmatTest1DTPMV = do\n    a  <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 1, 0, 1, 1, 1] !! idx)\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [-2, 3, 2] !! idx)\n    BLAS.dtpmv Matrix.SColumn MatLower Transpose MatUnit 3 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [1, 5, 2]\n\n-- [ 1:+0    0:+0    0:+0]   [-2]   [-2:+0   ]\n-- [ 2:+(-2) 1:+0    0:+0] * [ 3] = [-1:+4   ]\n-- [ 0:+0    1:+(-1) 1:+0]   [ 2]   [ 5:+(-3)]\nmatmatTest1CTPMV:: IO ()\nmatmatTest1CTPMV = do\n    a  <- Matrix.generateMutableDenseVector 6 (\\idx -> [1:+0, 2:+2, 0:+0, 1:+0, 1:+1, 1:+0] !! idx)\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [-2, 3, 2] !! idx)\n    BLAS.ctpmv Matrix.SRow MatUpper Matrix.ConjTranspose MatUnit 3 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [(-2):+0, (-1):+4, 5:+(-3)]\n\n-- [1 1 0]   [2]   [5]\n-- [0 1 1] * [3] = [5]\n-- [0 0 1]   [2]   [2]\nmatmatTest1ZTPMV:: IO ()\nmatmatTest1ZTPMV = do\n    a  <- Matrix.generateMutableDenseVector 6 (\\idx -> [1:+0, 1:+0, 1:+0, 0:+0, 1:+0, 1:+0] !! idx)\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [2, 3, 2] !! idx)\n    BLAS.ztpmv Matrix.SColumn MatUpper NoTranspose MatNonUnit 3 a x -- TODO: NAN error when using Lower Transpose\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [5, 5, 2]\n\ntpsvSpec :: Spec\ntpsvSpec =\n  context \"?TPSV\" $ do\n    describe \"STPSV\" $ do\n      it \"3x3 upper no trans (row oriented)\" $ do\n        matmatTest1STPSV\n    describe \"DTPSV\" $ do\n      it \"3x3 lower trans (column oriented)\" $ do\n        matmatTest1DTPSV\n    describe \"CTPSV\" $ do\n      it \"3x3 upper conj trans (row oriented)\" $ do\n        matmatTest1CTPSV\n    describe \"ZTPSV\" $ do\n      it \"3x3 lower no trans (row oriented)\" $ do\n        matmatTest1ZTPSV\n\n-- [ 1 2 0]   [-2]   [4]\n-- [ 0 1 1] * [ 3] = [5]\n-- [ 0 0 1]   [ 2]   [2]\nmatmatTest1STPSV:: IO ()\nmatmatTest1STPSV = do\n    a  <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 2, 0, 1, 1, 1] !! idx)\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [4, 5, 2] !! idx)\n    BLAS.stpsv Matrix.SRow MatUpper NoTranspose MatUnit 3 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [-2, 3, 2]\n\n-- [1 1 0]   [-2]   [1]\n-- [0 1 1] * [ 3] = [5]\n-- [0 0 1]   [ 2]   [2]\nmatmatTest1DTPSV:: IO ()\nmatmatTest1DTPSV = do\n    a  <- Matrix.generateMutableDenseVector 6 (\\idx -> [1, 1, 0, 1, 1, 1] !! idx)\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [1, 5, 2] !! idx)\n    BLAS.dtpsv Matrix.SColumn MatLower Transpose MatUnit 3 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [-2, 3, 2]\n\n-- [ 1:+0    0:+0    0:+0]   [-2]   [-2:+0   ]\n-- [ 2:+(-2) 1:+0    0:+0] * [ 3] = [-1:+4   ]\n-- [ 0:+0    1:+(-1) 1:+0]   [ 2]   [ 5:+(-3)]\nmatmatTest1CTPSV:: IO ()\nmatmatTest1CTPSV = do\n    a  <- Matrix.generateMutableDenseVector 6 (\\idx -> [1:+0, 2:+2, 0:+0, 1:+0, 1:+1, 1:+0] !! idx)\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [(-2):+0, (-1):+4, 5:+(-3)]!! idx)\n    BLAS.ctpsv Matrix.SRow MatUpper Matrix.ConjTranspose MatUnit 3 a x\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [-2, 3, 2]\n\n-- [1 1 0]   [2]   [5]\n-- [0 1 1] * [3] = [5]\n-- [0 0 1]   [2]   [2]\nmatmatTest1ZTPSV:: IO ()\nmatmatTest1ZTPSV = do\n    a  <- Matrix.generateMutableDenseVector 6 (\\idx -> [1:+0, 1:+0, 1:+0, 0:+0, 1:+0, 1:+0] !! idx)\n    x  <- Matrix.generateMutableDenseVector 3 (\\idx -> [5, 5, 2] !! idx)\n    BLAS.ztpsv Matrix.SColumn MatUpper NoTranspose MatNonUnit 3 a x -- TODO: NAN error when using Lower Transpose\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector x\n    resList `shouldBe` [2, 3, 2]\n\ntrmvSpec :: Spec\ntrmvSpec =\n  context \"?TRMV\" $ do\n    describe \"STRMV\" $ do\n      it \"2x2 upper 1's\" $ do\n        matmatTest1STRMV\n    describe \"DTRMV\" $ do\n      it \"2x2 upper 1's\" $ do\n        matmatTest1DTRMV\n    describe \"CTRMV\" $ do\n      it \"2x2 upper 1's\" $ do\n        matmatTest1CTRMV\n    describe \"ZTRMV\" $ do\n      it \"2x2 upper 1's\" $ do\n        matmatTest1ZTRMV\n\nmatmatTest1STRMV:: IO ()\nmatmatTest1STRMV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2)\n            (\\(i,j) -> if i >= j then (1.0::Float) else 0 )\n\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 2 else 1)\n    BLAS.strmv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [3,1]\n\nmatmatTest1DTRMV:: IO ()\nmatmatTest1DTRMV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2)\n                (\\(i,j) -> if i >= j then (1.0::Double) else 0 )\n\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 2 else 1)\n    BLAS.dtrmv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [3,1]\n\nmatmatTest1CTRMV:: IO ()\nmatmatTest1CTRMV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2)\n                (\\(i,j) -> if i >= j then (1.0::(Complex Float)) else 0 )\n\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 2 else 1)\n    BLAS.ctrmv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [3,1]\n\nmatmatTest1ZTRMV:: IO ()\nmatmatTest1ZTRMV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2)\n                (\\(i,j) -> if i >= j then (1.0::(Complex Double )) else 0 )\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 2 else 1)\n    BLAS.ztrmv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [3,1]\n\ntrsvSpec :: Spec\ntrsvSpec =\n  context \"?TRSV\" $ do\n    describe \"STRSV\" $ do\n      it \"2x2 upper 1's\" $ do\n        matmatTest1STRSV\n    describe \"DTRSV\" $ do\n      it \"2x2 upper 1's\" $ do\n        matmatTest1DTRSV\n    describe \"CTRSV\" $ do\n      it \"2x2 upper 1's\" $ do\n        matmatTest1CTRSV\n    describe \"ZTRSV\" $ do\n      it \"2x2 upper 1's\" $ do\n        matmatTest1ZTRSV\n\nmatmatTest1STRSV:: IO ()\nmatmatTest1STRSV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2)\n            (\\(i,j) -> if i >= j then (1.0::Float) else 0 )\n\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 3 else 1)\n    BLAS.strsv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2,1]\n\nmatmatTest1DTRSV:: IO ()\nmatmatTest1DTRSV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2)\n                (\\(i,j) -> if i >= j then (1.0::Double) else 0 )\n\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 3 else 1)\n    BLAS.dtrsv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2,1]\n\nmatmatTest1CTRSV:: IO ()\nmatmatTest1CTRSV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2)\n                (\\(i,j) -> if i >= j then (1.0::(Complex Float)) else 0 )\n\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 3 else 1)\n    BLAS.ctrsv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2,1]\n\nmatmatTest1ZTRSV:: IO ()\nmatmatTest1ZTRSV = do\n    left  <- Matrix.generateMutableDenseMatrix (Matrix.SRow)  (2,2)\n                (\\(i,j) -> if i >= j then (1.0::(Complex Double )) else 0 )\n    res  <- Matrix.generateMutableDenseVector  2 (\\i -> if i == 0 then 3 else 1)\n    BLAS.ztrsv MatUpper NoTranspose MatUnit left res\n    resList <- Matrix.mutableVectorToList $ _bufferMutDenseVector res\n    resList `shouldBe` [2,1]\n", "meta": {"hexsha": "da4c95fe35b06262ec65ab08479a83d7651b6d4b", "size": 44887, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/HBLAS/BLAS/Level2Spec.hs", "max_stars_repo_name": "schnecki/hblas", "max_stars_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T22:58:54.000Z", "max_issues_repo_path": "tests/HBLAS/BLAS/Level2Spec.hs", "max_issues_repo_name": "schnecki/hblas", "max_issues_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-01-24T13:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T22:15:09.000Z", "max_forks_repo_path": "tests/HBLAS/BLAS/Level2Spec.hs", "max_forks_repo_name": "schnecki/hblas", "max_forks_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:37:37.000Z", "avg_line_length": 37.0354785479, "max_line_length": 191, "alphanum_fraction": 0.592532359, "num_tokens": 19097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4189524081910329}}
{"text": "{-# LANGUAGE FlexibleContexts,\n             MultiParamTypeClasses #-}\nmodule Network.Trainer.BackpropTrainer\n( BackpropTrainer(..)\n\n, backprop\n, inputs\n, outputs\n, deltas\n, hiddenDeltas\n, calculateNablas\n, fit\n, evaluate\n) where\n\nimport Network.Network\nimport Network.Network.FeedForwardNetwork\nimport Network.Neuron\nimport Network.Layer\nimport Network.Trainer\n\nimport Numeric.LinearAlgebra\n\n-- | A BackpropTrainer performs simple backpropagation on a neural network.\n--   It can be used as the basis for more complex trainers.\ndata BackpropTrainer = BackpropTrainer { eta :: Double\n                                       , cost :: CostFunction\n                                       , cost' :: CostFunction'\n                                       }\n\n-- | Declare the BackpropTrainer to be an instance of Trainer.\ninstance Trainer BackpropTrainer FeedForwardNetwork where\n  fit s t n examples = foldl (backprop t) n $ s examples\n  -- | Use the cost function to determine the error of a network\n  evaluate t n example = (cost t) (snd example) (predict (fst example) n)\n\n-- | Perform backpropagation on a single training data instance.\nbackprop :: BackpropTrainer -> FeedForwardNetwork -> [TrainingData] -> FeedForwardNetwork\nbackprop t n es =\n  updateNetwork (length es) t (foldl (calculateNablas t n) emptyFeedForwardNetwork es) n\n\n-- | Given the size of the minibatch, the trainer, the nablas for each layer, given\n--   as a network, and the network itself, return a network with updated wieghts.\nupdateNetwork :: Int -> BackpropTrainer -> FeedForwardNetwork -> FeedForwardNetwork -> FeedForwardNetwork\nupdateNetwork mag t nablas n = addFeedForwardNetworks n\n  (FeedForwardNetwork $ map (scaleLayer $ -1 * (eta t) / (fromIntegral mag)) (layers nablas))\n\n-- | Calculate the nablas for a minibatch and return them as a network (so each\n--   weight and bias gets its own nabla).\ncalculateNablas :: BackpropTrainer -> FeedForwardNetwork -> FeedForwardNetwork -> TrainingData -> FeedForwardNetwork\ncalculateNablas t n nablas e = FeedForwardNetwork $ map (updateLayer t) (zip3 (layers n) ds os)\n  where ds = deltas t n e\n        os = outputs (fst e) n\n\n-- | The mapped function to update the weight and biases in a single layer\nupdateLayer :: BackpropTrainer -> (Layer, Vector Double, Vector Double) -> Layer\nupdateLayer t (l, delta, output) = Layer newWeight newBias n\n  where n = neuron l\n        newWeight = ((reshape 1 delta) <> (reshape (dim output) output))\n        newBias = delta\n\n-- | The outputs function scans over each layer of the network and stores the\n--   activated results\noutputs :: Vector Double -> FeedForwardNetwork -> [Vector Double]\noutputs input network = scanl apply input (layers network)\n\n-- | The inputs function performs a similar task to outputs, but returns a list\n--   of vectors of unactivated inputs\ninputs :: Vector Double -> FeedForwardNetwork -> [Vector Double]\ninputs input network = if null (layers network) then []\n  else unactivated : inputs activated (FeedForwardNetwork (tail $ layers network))\n  where unactivated = weightMatrix layer <> input + biasVector layer\n        layer = head $ layers network\n        activated = mapVector (activation (neuron layer)) unactivated\n\n-- | The deltas function returns a list of layer deltas.\ndeltas :: BackpropTrainer -> FeedForwardNetwork -> TrainingData -> [Vector Double]\ndeltas t n example = hiddenDeltas\n  (FeedForwardNetwork (reverse (layers n))) outputDelta (tail $ reverse is)\n    ++ [outputDelta]\n  where outputDelta = costd (snd example) output *\n          mapVector activationd lastInput\n        costd = cost' t\n        activationd = activation' (neuron (last (layers n)))\n        output = last os\n        lastInput = last is\n        is = inputs (fst example) n\n        os = outputs (fst example) n\n\n-- | Compute the hidden layer deltas\nhiddenDeltas :: FeedForwardNetwork -> Vector Double -> [Vector Double] -> [Vector Double]\nhiddenDeltas n prevDelta is = if length (layers n) <= 1 then []\n  else delta : hiddenDeltas rest delta (tail is)\n  where rest = FeedForwardNetwork (tail $ layers n)\n        delta = (trans w) <> prevDelta * spv\n        w = weightMatrix (head $ layers n)\n        spv = mapVector (activation' (neuron (head $ layers n))) (head is)\n", "meta": {"hexsha": "ac179357827ce0b70139e14c4cc2be4ad5203a23", "size": 4242, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Network/Trainer/BackpropTrainer.hs", "max_stars_repo_name": "AkatsukiSirius/LambdaNet", "max_stars_repo_head_hexsha": "24386af14e3e7855a80664f1ee6b48b938aa3811", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-06T12:58:43.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-06T12:58:43.000Z", "max_issues_repo_path": "Network/Trainer/BackpropTrainer.hs", "max_issues_repo_name": "world-admin/LambdaNet", "max_issues_repo_head_hexsha": "24386af14e3e7855a80664f1ee6b48b938aa3811", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Network/Trainer/BackpropTrainer.hs", "max_forks_repo_name": "world-admin/LambdaNet", "max_forks_repo_head_hexsha": "24386af14e3e7855a80664f1ee6b48b938aa3811", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:39:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:39:55.000Z", "avg_line_length": 43.2857142857, "max_line_length": 116, "alphanum_fraction": 0.7032060349, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.5, "lm_q1q2_score": 0.4188099857201406}}
{"text": "{-# LANGUAGE ApplicativeDo                            #-}\n{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE EmptyCase                                #-}\n{-# LANGUAGE FlexibleContexts                         #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE KindSignatures                           #-}\n{-# LANGUAGE LambdaCase                               #-}\n{-# LANGUAGE PartialTypeSignatures                    #-}\n{-# LANGUAGE QuantifiedConstraints                    #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE RecordWildCards                          #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE TupleSections                            #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeInType                               #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE ViewPatterns                             #-}\n{-# OPTIONS_GHC -fno-warn-partial-type-signatures     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Extra.Solver    #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\nimport           Backprop.Learn\nimport           Control.Applicative\nimport           Control.DeepSeq\nimport           Control.Exception\nimport           Control.Monad\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Primitive\nimport           Control.Monad.Trans.Class\nimport           Control.Monad.Trans.State\nimport           Data.Char\nimport           Data.Conduit\nimport           Data.Default\nimport           Data.Kind\nimport           Data.Proxy\nimport           Data.Singletons\nimport           Data.Singletons.TypeLits\nimport           Data.Time\nimport           Data.Type.Equality\nimport           Data.Type.Tuple\nimport           GHC.TypeLits.Compare\nimport           GHC.TypeNats\nimport           Numeric.LinearAlgebra.Static.Backprop hiding ((<>))\nimport           Numeric.Natural\nimport           Numeric.Opto\nimport           Options.Applicative\nimport           Statistics.Distribution\nimport           Statistics.Distribution.Normal\nimport           Text.Printf\nimport qualified Data.Conduit.Combinators                     as C\nimport qualified Data.Vector.Sized                            as SV\nimport qualified System.Random.MWC                            as MWC\n\ndata Mode = CSimulate (Maybe Int)\n          | forall s p. ( Floating s\n                        , Floating p\n                        , NFData s\n                        , NFData p\n                        , Metric Double s\n                        , Metric Double p\n                        , Show s\n                        , Show p\n                        , Initialize p\n                        , Initialize s\n                        , Backprop p\n                        , Backprop s\n                        , forall m. PrimMonad m => LinearInPlace m Double p\n                        , forall m. PrimMonad m => LinearInPlace m Double s\n                        )\n                        => CLearn (ModelPick p s)\n\ndata ModelPick :: Type -> Type -> Type where\n    MARIMA :: Sing p -> Sing d -> Sing q\n           -> ModelPick (ARIMAp p q) (ARIMAs p d q)\n    MFCRNN :: Sing h\n           -> ModelPick (LRp h 1 :# LRp (1 + h) h) (R h)\n    MLSTM  :: Sing h\n           -> ModelPick (LRp h 1 :# LSTMp 1 h)     (R h :# R h)\n    MGRU   :: Sing h\n           -> ModelPick (LRp h 1 :# GRUp 1 h)      (R h)\n\ndata Process = PSin\n\nmodelLearn :: ModelPick p s -> Model ('Just p) ('Just s) Double Double\nmodelLearn = \\case\n    MARIMA (SNat :: Sing pp) (SNat :: Sing d) (SNat :: Sing q) ->\n              arima @pp @d @q\n    MFCRNN (SNat :: Sing h) ->\n              funcD sumElements\n           <~ fc\n           <~ fcra logistic logistic\n           <~ funcD konst\n    MLSTM  (SNat :: Sing h) ->\n              funcD sumElements\n           <~ fc\n           <~ lstm\n           <~ funcD konst\n    MGRU   (SNat :: Sing h) ->\n              funcD sumElements\n           <~ fc\n           <~ gru\n           <~ funcD konst\n\ndata Options = O { oMode     :: Mode\n                 , oProcess  :: Process\n                 , oNoise    :: Double\n                 , oInterval :: Int\n                 , oLookback :: Natural\n                 }\n\nprocessConduit\n    :: PrimMonad m\n    => Process\n    -> MWC.Gen (PrimState m)\n    -> ConduitT i Double m ()\nprocessConduit = \\case\n    PSin -> \\g -> void . flip (foldr (>=>) pure) (0, 1) . repeat $ \\(t, v) -> do\n      dv <- genContVar (normalDistr 0 0.025) g\n      let v' = min 2 . max 0.5 $ v + dv\n          t' = t + v'\n      yield (sin (2 * pi * (1/25) * t))\n      return (t', v')\n\nnoisyConduit\n    :: PrimMonad m\n    => Double\n    -> MWC.Gen (PrimState m)\n    -> ConduitT Double Double m ()\nnoisyConduit \u03c3 g = C.mapM $ \\x ->\n    (x + ) <$> genContVar (normalDistr 0 \u03c3) g\n\n-- type Context = ConduitT (Vector)\n\nmain :: IO ()\nmain = MWC.withSystemRandom @IO $ \\g -> do\n    O{..} <- execParser $ info (parseOpt <**> helper)\n                            ( fullDesc\n                           <> progDesc \"Learning ARIMA\"\n                           <> header \"backprop-learn-arima - backprop-learn demo\"\n                            )\n\n    SomeNat (Proxy :: Proxy n) <- pure $ someNatVal oLookback\n    Just Refl <- pure $ Proxy @1 `isLE` Proxy @n\n    let generator = processConduit oProcess g\n                 .| noisyConduit oNoise g\n\n    case oMode of\n      CSimulate lim ->\n        runConduit $ generator\n                  .| maybe (C.map id) C.take lim\n                  .| C.mapM_ print\n                  .| C.sinkNull\n\n      CLearn (modelLearn->model) -> do\n        let unrolled = trainState . unrollFinal @(SV.Vector n) $ model\n        p0 <- initParamNormal unrolled 0.2 g\n\n        let report n b = do\n              liftIO $ printf \"(Batch %d)\\n\" (b :: Int)\n              t0 <- liftIO getCurrentTime\n              C.drop (n - 1)\n              mp <- mapM (liftIO . evaluate . force) =<< await\n              t1 <- liftIO getCurrentTime\n              case mp of\n                Nothing -> liftIO $ putStrLn \"Done!\"\n                Just p -> do\n                  chnk <- lift . state $ (,[])\n                  liftIO $ do\n                    printf \"Trained on %d points in %s.\\n\"\n                      (length chnk)\n                      (show (t1 `diffUTCTime` t0))\n                    let trainScore = testModelAll absErrorTest unrolled (TJust p) chnk\n                    printf \"Training error:   %.8f\\n\" trainScore\n                  report n (b + 1)\n\n        flip evalStateT []\n            . runConduit\n            $ transPipe lift generator\n           .| leadings\n           .| skipSampling 0.05 g\n           .| C.iterM (modify . (:))\n           .| optoConduit def p0\n                (adam def (modelGrad squaredError noReg unrolled))\n           .| report oInterval 0\n           .| C.sinkNull\n\nparseOpt :: Parser Options\nparseOpt = O <$> subparser ( command \"simulate\" (info (parseSim   <**> helper) (progDesc \"Simulate ARIMA only\"))\n                          <> command \"learn\"    (info (parseLearn <**> helper) (progDesc \"Simulate and learn model\"))\n                           )\n             <*> option (maybeReader parseProcess)\n                   ( long \"process\"\n                  <> help \"Process to learn\"\n                  <> showDefaultWith showProcess\n                  <> value PSin\n                  <> metavar \"PROCESS\"\n                   )\n             <*> option auto\n                   ( short 'e'\n                  <> help \"Standard deviation of noise term\"\n                  <> showDefault\n                  <> value 0.05\n                  <> metavar \"DOUBLE\"\n                   )\n             <*> option auto\n                   ( long \"interval\"\n                  <> short 'i'\n                  <> help \"Report interval\"\n                  <> showDefault\n                  <> value 5000\n                  <> metavar \"INT\"\n                   )\n             <*> option auto\n                   ( long \"lookback\"\n                  <> short 'l'\n                  <> help \"Learn lookback\"\n                  <> showDefault\n                  <> value 10\n                  <> metavar \"INT\"\n                   )\n  where\n    parseSim :: Parser Mode\n    parseSim = CSimulate <$> optional (option auto\n                                          ( short 'n'\n                                         <> help \"Number of items to generate (infinite, if none given)\"\n                                         <> metavar \"INT\"\n                                          )\n                                      )\n    parseLearn :: Parser Mode\n    parseLearn = subparser\n        ( command \"arima\" (info parseARIMA (progDesc \"Learn ARIMA(p,d,q) model\"))\n       <> command \"fcrnn\" (info parseFCRNN (progDesc \"Learn Fully Connected RNN model\"))\n       <> command \"lstm\"  (info parseLSTM  (progDesc \"Learn LSTM model\"))\n       <> command \"gru\"   (info parseGRU   (progDesc \"Learn GRU model\"))\n        )\n    parseARIMA :: Parser Mode\n    parseARIMA = do\n        p <- argument auto ( help \"AR(p): Autoregressive lookback\"\n                          <> metavar \"INT\"\n                           )\n        d <- argument auto ( help \"I(d): Differencing degree\"\n                          <> metavar \"INT\"\n                           )\n        q <- argument auto ( help \"MA(q): Moving average lookback\"\n                          <> metavar \"INT\"\n                           )\n        pure $ withSomeSing @Nat p $ \\sp@SNat ->\n          withSomeSing @Nat d $ \\sd@SNat ->\n          withSomeSing @Nat q $ \\sq@SNat ->\n            CLearn (MARIMA sp sd sq)\n    parseFCRNN :: Parser Mode\n    parseFCRNN = do\n        h <- argument auto ( help \"Hidden layer size\"\n                          <> metavar \"INT\"\n                          <> showDefault\n                          <> value 10\n                           )\n        pure $ withSomeSing @Nat h $ \\sh@SNat ->\n          CLearn (MFCRNN sh)\n    parseLSTM :: Parser Mode\n    parseLSTM = do\n        h <- argument auto ( help \"Hidden layer size\"\n                          <> metavar \"INT\"\n                          <> showDefault\n                          <> value 10\n                           )\n        pure $ withSomeSing @Nat h $ \\sh@SNat ->\n          CLearn (MLSTM sh)\n    parseGRU :: Parser Mode\n    parseGRU = do\n        h <- argument auto ( help \"Hidden layer size\"\n                          <> metavar \"INT\"\n                          <> showDefault\n                          <> value 10\n                           )\n        pure $ withSomeSing @Nat h $ \\sh@SNat ->\n          CLearn (MGRU sh)\n\nshowProcess :: Process -> String\nshowProcess PSin = \"sin\"\n\nparseProcess :: String -> Maybe Process\nparseProcess s = case map toLower s of\n    \"sin\" -> Just PSin\n    _     -> Nothing\n\n", "meta": {"hexsha": "92b54cf8cca473d1a5e2a513f61ad971197ce644", "size": 10777, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/series.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "app/series.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "app/series.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 37.5505226481, "max_line_length": 117, "alphanum_fraction": 0.4500324766, "num_tokens": 2412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.41836643050152844}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\nmodule Bio.ChromVAR.Background (getBackgroundPeaks) where\n\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as S\nimport qualified Data.Vector as V\nimport qualified Data.Matrix.Unboxed as MU\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport Control.Monad\nimport Data.Ord\nimport Data.List\nimport Control.Arrow\nimport qualified Data.Matrix.Static.Dense as D\nimport qualified Data.Matrix.Static.Generic as D\nimport Data.Matrix.Dynamic (Dynamic(..), matrix)\n\nimport Statistics.Sample\nimport System.Random.MWC\nimport System.Random.MWC.Distributions (categorical)\n\nimport Bio.ChromVAR.Utils\n\ntype PeakGroup = ( MU.Matrix Double   -- ^ Group to group distance\n                 , V.Vector (U.Vector Int)  -- ^ Peaks in each group\n                 , U.Vector Int       -- ^ Peak-group membership\n                 )\n\ngetBackgroundPeaks :: Int -> U.Vector (Double, Double) -> GenIO -> IO [U.Vector Int]\ngetBackgroundPeaks n xs gen =\n    let pg = mkPeakGroup xs\n    in replicateM n $ getBackgroundPeak gen pg\n\ngetBackgroundPeak :: GenIO -> PeakGroup -> IO (U.Vector Int)\ngetBackgroundPeak gen (weightMat, bins, membership) = U.generateM n $ \\i -> do\n    let ws = weightMat `MU.takeRow` (membership U.! i)\n    grp <- categorical ws gen\n    let peaks = bins V.! grp\n    idx <- uniformR (0, U.length peaks - 1) gen\n    return $ peaks U.! idx\n  where\n    n = U.length membership\n{-# INLINE getBackgroundPeak #-}\n\n-- | Make peak groups.\nmkPeakGroup :: U.Vector (Double, Double) -> PeakGroup\nmkPeakGroup raw = (weights, V.fromList groups, membership)\n  where\n    transformed = case matrix (map (\\(x,y) -> [x,y]) $ U.toList raw) of\n        Dynamic mat@(D.Matrix _) -> U.fromList $\n           map ((\\[x,y] -> (x,y)) . S.toList) $ D.toRows $ whiten Cholesky mat\n    weights = MU.generate (U.length points, U.length points) $ \\(i,j) ->\n        weight (points U.! i) (points U.! j)\n      where\n        points = U.fromList $ flip map groups $ \\is -> mean *** mean $\n            U.unzip $ U.map (transformed U.!) is\n    membership = U.create $ do\n        v <- UM.new $ U.length transformed\n        forM_ (zip [0..] groups) $ \\(x, is) -> U.forM_ is $ \\i ->\n            UM.unsafeWrite v i x\n        return v\n    groups = go [] 0 0 $ sortBy (comparing fst) $ zip (U.toList transformed) [0..]\n      where\n        go acc i j (((x,y), idx) : rest)\n            | null acc || i' == i || j' == j = go (idx : acc) i' j' rest\n            | i' > i || j' > j = U.fromList acc : go [idx] i' j' rest\n            | otherwise = error \"Impossible\"\n          where\n            i' = truncate $ (x - x_min) / x_step :: Int\n            j' = truncate $ (y - y_min) / y_step :: Int\n        go _ _ _ _ = []\n    (xs, ys) = U.unzip transformed\n    x_min = U.minimum xs\n    x_max = U.maximum xs\n    x_step = (x_max - x_min) / n\n    y_min = U.minimum ys\n    y_max = U.maximum ys\n    y_step = (y_max - y_min) / n\n    n = 50\n{-# INLINE mkPeakGroup #-}", "meta": {"hexsha": "f6d8c095c7f7ff7f7c48cfaa95eaf529dd0a8fca", "size": 3030, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Bio/ChromVAR/Background.hs", "max_stars_repo_name": "kaizhang/ChromVAR", "max_stars_repo_head_hexsha": "d64dd55579c8db9625028065b4cb3314e8f0c4a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Bio/ChromVAR/Background.hs", "max_issues_repo_name": "kaizhang/ChromVAR", "max_issues_repo_head_hexsha": "d64dd55579c8db9625028065b4cb3314e8f0c4a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Bio/ChromVAR/Background.hs", "max_forks_repo_name": "kaizhang/ChromVAR", "max_forks_repo_head_hexsha": "d64dd55579c8db9625028065b4cb3314e8f0c4a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4074074074, "max_line_length": 84, "alphanum_fraction": 0.6141914191, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.41834572836331463}}
{"text": "module Numeric.FFT.Special.Miscellaneous\n       ( special6, special9, special10, special12, special14\n       , special15, special20, special25\n       ) where\n\nimport           Control.Monad.ST\nimport           Data.Complex\nimport qualified Data.Vector.Unboxed.Mutable as MV\n\nimport           Numeric.FFT.Types\n\n\n-- | Length 6 hard-coded FFT.\nkp866025403, kp500000000 :: Double\nkp866025403 = 0.866025403784438646763723170752936183471402627\nkp500000000 = 0.500000000000000000000000000000000000000000000\nspecial6 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial6 sign xsin xsout = do\n  xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n  xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n  xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n  let tb = xr0 + xr3 ; t3 = xr0 - xr3 ; tx = xi0 + xi3 ; tp = xi0 - xi3\n      tc = xr2 + xr5 ; t6 = xr2 - xr5 ; td = xr4 + xr1 ; t9 = xr4 - xr1\n      te = tc + td ; tA = td - tc ; ts = t9 - t6 ; ta = t6 + t9\n      tu = xi2 + xi5 ; ti = xi2 - xi5 ; tf = t3 - kp500000000 * ta\n      tv = xi4 + xi1 ; tl = xi4 - xi1 ; tt = tb - kp500000000 * te\n      ty = tu + tv ; tw = tu - tv ; tq = ti + tl ; tm = ti - tl\n      tr = tp - kp500000000 * tq ; tz = tx - kp500000000 * ty\n      r5 = (tf + kp866025403 * tm) :+ (tr + kp866025403 * ts)\n      r4 = (tt - kp866025403 * tw) :+ (tz - kp866025403 * tA)\n      r3 = (t3 + ta) :+ (tp + tq)\n      r2 = (tt + kp866025403 * tw) :+ (tz + kp866025403 * tA)\n      r1 = (tf - kp866025403 * tm) :+ (tr - kp866025403 * ts)\n  MV.unsafeWrite xsout 0 $ (tb + te) :+ (tx + ty)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r5\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r4\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r3\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r2\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r1\n\n-- | Length 9 hard-coded FFT.\nkp954188894, kp363970234, kp852868531, kp984807753 :: Double\nkp492403876, kp777861913, kp839099631, kp176326980 :: Double\n--kp866025403, kp500000000 :: Double\nkp954188894 = 0.954188894138671133499268364187245676532219158\nkp363970234 = 0.363970234266202361351047882776834043890471784\nkp852868531 = 0.852868531952443209628250963940074071936020296\nkp984807753 = 0.984807753012208059366743024589523013670643252\nkp492403876 = 0.492403876506104029683371512294761506835321626\nkp777861913 = 0.777861913430206160028177977318626690410586096\nkp839099631 = 0.839099631177280011763127298123181364687434283\nkp176326980 = 0.176326980708464973471090386868618986121633062\n--kp866025403 = 0.866025403784438646763723170752936183471402627\n--kp500000000 = 0.500000000000000000000000000000000000000000000\nspecial9 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial9 sign xsin xsout = do\n  xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n  xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n  xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n  xr6 :+ xi6 <- MV.unsafeRead xsin 6 ; xr7 :+ xi7 <- MV.unsafeRead xsin 7\n  xr8 :+ xi8 <- MV.unsafeRead xsin 8\n  let t4 = xr3 + xr6 ; tm = xr6 - xr3 ; tM = xi3 - xi6 ; tk = xi3 + xi6\n      tL = xr0 - kp500000000 * t4 ; t5 = xr0 + t4\n      tl = xi0 - kp500000000 * tk ; t1f = xi0 + tk\n      tE = xr4 - xr7 ; t9 = xr4 + xr7 ; tH = xi7 - xi4 ; tC = xi4 + xi7\n      ta = xr1 + t9 ; tG = xr1 - kp500000000 * t9\n      t1c = xi1 + tC ; tD = xi1 - kp500000000 * tC\n      tI = tG - kp866025403 * tH ; tX = tG + kp866025403 * tH\n      tF = tD - kp866025403 * tE ; tW = tD + kp866025403 * tE\n      t17 = tl - kp866025403 * tm ; tn = tl + kp866025403 * tm\n      tw = xr8 - xr5 ; te = xr5 + xr8 ; tu = xi5 + xi8 ; tr = xi5 - xi8\n      tN = tL + kp866025403 * tM ; tV = tL - kp866025403 * tM\n      tf = xr2 + te ; to = xr2 - kp500000000 * te\n      t1d = xi2 + tu ; tv = xi2 - kp500000000 * tu\n      ts = to + kp866025403 * tr ; tZ = to - kp866025403 * tr\n      tg = ta + tf ; t1i = tf - ta\n      tx = tv + kp866025403 * tw ; t10 = tv - kp866025403 * tw\n      t1e = t1c - t1d ; t1g = t1c + t1d\n      t1b = t5 - kp500000000 * tg ; t1h = t1f - kp500000000 * t1g\n      tO = tx + kp176326980 * ts ; ty = ts - kp176326980 * tx\n      tJ = tF - kp839099631 * tI ; tP = tI + kp839099631 * tF\n      tS = ty + kp777861913 * tJ ; tK = ty - kp777861913 * tJ\n      tU = tO - kp777861913 * tP ; tQ = tO + kp777861913 * tP\n      tT = tn + kp492403876 * tK ; tR = tN - kp492403876 * tQ\n      t14 = tX - kp176326980 * tW ; tY = tW + kp176326980 * tX\n      t11 = tZ - kp363970234 * t10 ; t15 = t10 + kp363970234 * tZ\n      t12 = tY - kp954188894 * t11 ; t1a = tY + kp954188894 * t11\n      t16 = t14 - kp954188894 * t15 ; t18 = t14 + kp954188894 * t15\n      t13 = tV - kp492403876 * t12 ; t19 = t17 + kp492403876 * t18\n      r8 = (tN + kp984807753 * tQ) :+ (tn - kp984807753 * tK)\n      r7 = (tV + kp984807753 * t12) :+ (t17 - kp984807753 * t18)\n      r6 = (t1b + kp866025403 * t1e) :+ (t1h + kp866025403 * t1i)\n      r5 = (tR + kp852868531 * tS) :+ (tT + kp852868531 * tU)\n      r4 = (t13 - kp852868531 * t16) :+ (t19 - kp852868531 * t1a)\n      r3 = (t1b - kp866025403 * t1e) :+ (t1h - kp866025403 * t1i)\n      r2 = (tR - kp852868531 * tS) :+ (tT - kp852868531 * tU)\n      r1 = (t13 + kp852868531 * t16) :+ (t19 + kp852868531 * t1a)\n  MV.unsafeWrite xsout 0 $ (t5 + tg) :+ (t1f + t1g)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r8\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r7\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r6\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r5\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r4\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r3\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r2\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r1\n\n-- | Length 10 hard-coded FFT.\nkp951056516, kp559016994, kp250000000, kp618033988 :: Double\nkp951056516 = 0.951056516295153572116439333379382143405698634\nkp559016994 = 0.559016994374947424102293417182819058860154590\nkp250000000 = 0.250000000000000000000000000000000000000000000\nkp618033988 = 0.618033988749894848204586834365638117720309180\nspecial10 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial10 sign xsin xsout = do\n  xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n  xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n  xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n  xr6 :+ xi6 <- MV.unsafeRead xsin 6 ; xr7 :+ xi7 <- MV.unsafeRead xsin 7\n  xr8 :+ xi8 <- MV.unsafeRead xsin 8 ; xr9 :+ xi9 <- MV.unsafeRead xsin 9\n  let tj = xr0 + xr5 ; t3 = xr0 - xr5 ; t1b = xi0 + xi5 ; tN = xi0 - xi5\n      tk = xr2 + xr7 ; t6 = xr2 - xr7 ; to = xr6 + xr1 ; tg = xr6 - xr1\n      tl = xr8 + xr3 ; t9 = xr8 - xr3 ; tn = xr4 + xr9 ; td = xr4 - xr9\n      tm = tk + tl ; t1j = tk - tl ; ta = t6 + t9 ; tU = t6 - t9\n      tp = tn + to ; t1i = tn - to ; th = td + tg ; tV = td - tg\n      tq = tm + tp ; t10 = tm - tp ; ti = ta + th ; ts = ta - th\n      tw = xi2 - xi7 ; t15 = xi2 + xi7 ; t13 = xi6 + xi1 ; tG = xi6 - xi1\n      t16 = xi8 + xi3 ; tz = xi8 - xi3 ; t12 = xi4 + xi9 ; tD = xi4 - xi9\n      t1c = t15 + t16 ; t17 = t15 - t16 ; tO = tw + tz ; tA = tw - tz\n      t1d = t12 + t13 ; t14 = t12 - t13 ; tP = tD + tG ; tH = tD - tG\n      t1e = t1c + t1d ; t1g = t1c - t1d ; tQ = tO + tP ; tS = tO - tP\n      tK = tH - kp618033988 * tA ; tI = tA + kp618033988 * tH\n      tr = t3 - kp250000000 * ti ; tY = tV - kp618033988 * tU\n      tW = tU + kp618033988 * tV ; tR = tN - kp250000000 * tQ\n      tJ = tr - kp559016994 * ts ; tt = tr + kp559016994 * ts\n      t1a = t17 + kp618033988 * t14 ; t18 = t14 - kp618033988 * t17\n      tX = tR - kp559016994 * tS ; tT = tR + kp559016994 * tS\n      tZ = tj - kp250000000 * tq ; t1m = t1j + kp618033988 * t1i\n      t1k = t1i - kp618033988 * t1j ; t1f = t1b - kp250000000 * t1e\n      t19 = tZ + kp559016994 * t10 ; t11 = tZ - kp559016994 * t10\n      t1h = t1f - kp559016994 * t1g ; t1l = t1f + kp559016994 * t1g\n      r9 = (tt + kp951056516 * tI) :+ (tT - kp951056516 * tW)\n      r8 = (t11 - kp951056516 * t18) :+ (t1h + kp951056516 * t1k)\n      r7 = (tJ + kp951056516 * tK) :+ (tX - kp951056516 * tY)\n      r6 = (t19 - kp951056516 * t1a) :+ (t1l + kp951056516 * t1m)\n      r5 = (t3 + ti) :+ (tN + tQ)\n      r4 = (t19 + kp951056516 * t1a) :+ (t1l - kp951056516 * t1m)\n      r3 = (tJ - kp951056516 * tK) :+ (tX + kp951056516 * tY)\n      r2 = (t11 + kp951056516 * t18) :+ (t1h - kp951056516 * t1k)\n      r1 = (tt - kp951056516 * tI) :+ (tT + kp951056516 * tW)\n  MV.unsafeWrite xsout 0 $ (tj + tq) :+ (t1b + t1e)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r9\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r8\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r7\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r6\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r5\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r4\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r3\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r2\n  MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r1\n\n-- | Length 12 hard-coded FFT.\n--kp866025403, kp500000000 :: Double\n--kp866025403 = 0.866025403784438646763723170752936183471402627\n--kp500000000 = 0.500000000000000000000000000000000000000000000\nspecial12 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial12 sign xsin xsout = do\n  xr0  :+ xi0  <- MV.unsafeRead xsin 0  ; xr1  :+ xi1  <- MV.unsafeRead xsin 1\n  xr2  :+ xi2  <- MV.unsafeRead xsin 2  ; xr3  :+ xi3  <- MV.unsafeRead xsin 3\n  xr4  :+ xi4  <- MV.unsafeRead xsin 4  ; xr5  :+ xi5  <- MV.unsafeRead xsin 5\n  xr6  :+ xi6  <- MV.unsafeRead xsin 6  ; xr7  :+ xi7  <- MV.unsafeRead xsin 7\n  xr8  :+ xi8  <- MV.unsafeRead xsin 8  ; xr9  :+ xi9  <- MV.unsafeRead xsin 9\n  xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n  let t4 = xr4 + xr8 ; tA = xr8 - xr4 ; tS = xi4 - xi8 ; tr = xi4 + xi8\n      tR = xr0 - kp500000000 * t4 ; t5 = xr0 + t4 ; ts = xi0 + tr\n      tz = xi0 - kp500000000 * tr ; t9 = xr10 + xr2 ; tD = xr2 - xr10\n      tV = xi10 - xi2 ; tw = xi10 + xi2 ; tU = xr6 - kp500000000 * t9\n      ta = xr6 + t9 ; tx = xi6 + tw ; tC = xi6 - kp500000000 * tw\n      tf = xr7 + xr11 ; t1d = xr11 - xr7 ; tJ = xi7 - xi11 ; t1b = xi7 + xi11\n      tG = xr3 - kp500000000 * tf ; tg = xr3 + tf ; t1u = xi3 + t1b\n      t1c = xi3 - kp500000000 * t1b ; tk = xr1 + xr5 ; t1i = xr5 - xr1\n      t1t = t5 - ta ; tb = t5 + ta ; tO = xi1 - xi5 ; t1g = xi1 + xi5\n      tL = xr9 - kp500000000 * tk ; tl = xr9 + tk ; t1x = ts + tx\n      ty = ts - tx ; t1v = xi9 + t1g ; t1h = xi9 - kp500000000 * t1g\n      tn = tg - tl ; tm = tg + tl ; t1y = t1u + t1v ; t1w = t1u - t1v\n      tB = tz - kp866025403 * tA ; tZ = tz + kp866025403 * tA\n      t10 = tC + kp866025403 * tD ; tE = tC - kp866025403 * tD\n      t1o = t1c - kp866025403 * t1d ; t1e = t1c + kp866025403 * t1d\n      t1l = tZ + t10 ; t11 = tZ - t10 ; t1j = t1h + kp866025403 * t1i\n      t1p = t1h - kp866025403 * t1i ; tK = tG - kp866025403 * tJ\n      t12 = tG + kp866025403 * tJ ; t13 = tL + kp866025403 * tO\n      tP = tL - kp866025403 * tO ; tT = tR - kp866025403 * tS\n      t15 = tR + kp866025403 * tS ; t1m = t1e + t1j ; t1k = t1e - t1j\n      t18 = t12 + t13 ; t14 = t12 - t13 ; t16 = tU + kp866025403 * tV\n      tW = tU - kp866025403 * tV ; t17 = t15 + t16 ; t19 = t15 - t16\n      t1r = tB + tE ; tF = tB - tE ; t1s = t1o + t1p ; t1q = t1o - t1p\n      tY = tK + tP ; tQ = tK - tP ; tX = tT + tW ; t1n = tT - tW\n      r11 = (t19 + t1k) :+ (t11 - t14)\n      r10 = (tX - tY) :+ (t1r - t1s)\n      r9 = (t1t - t1w) :+ (tn + ty)\n      r8 = (t17 + t18) :+ (t1l + t1m)\n      r7 = (t1n + t1q) :+ (tF - tQ)\n      r6 = (tb - tm) :+ (t1x - t1y)\n      r5 = (t19 - t1k) :+ (t11 + t14)\n      r4 = (tX + tY) :+ (t1r + t1s)\n      r3 = (t1t + t1w) :+ (ty - tn)\n      r2 = (t17 - t18) :+ (t1l - t1m)\n      r1 = (t1n - t1q) :+ (tF + tQ)\n  MV.unsafeWrite xsout 0 $ (tb + tm) :+ (t1x + t1y)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r11\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r10\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r9\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r8\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r7\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r6\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r5\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r4\n  MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r3\n  MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r2\n  MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r1\n\n-- | Length 14 hard-coded FFT.\nkp974927912, kp801937735, kp900968867 :: Double\nkp554958132, kp692021471, kp356895867 :: Double\nkp974927912 = 0.974927912181823607018131682993931217232785801\nkp801937735 = 0.801937735804838252472204639014890102331838324\nkp900968867 = 0.900968867902419126236102319507445051165919162\nkp554958132 = 0.554958132087371191422194871006410481067288862\nkp692021471 = 0.692021471630095869627814897002069140197260599\nkp356895867 = 0.356895867892209443894399510021300583399127187\nspecial14 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial14 sign xsin xsout = do\n  xr0  :+ xi0  <- MV.unsafeRead xsin 0  ; xr1  :+ xi1  <- MV.unsafeRead xsin 1\n  xr2  :+ xi2  <- MV.unsafeRead xsin 2  ; xr3  :+ xi3  <- MV.unsafeRead xsin 3\n  xr4  :+ xi4  <- MV.unsafeRead xsin 4  ; xr5  :+ xi5  <- MV.unsafeRead xsin 5\n  xr6  :+ xi6  <- MV.unsafeRead xsin 6  ; xr7  :+ xi7  <- MV.unsafeRead xsin 7\n  xr8  :+ xi8  <- MV.unsafeRead xsin 8  ; xr9  :+ xi9  <- MV.unsafeRead xsin 9\n  xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n  xr12 :+ xi12 <- MV.unsafeRead xsin 12 ; xr13 :+ xi13 <- MV.unsafeRead xsin 13\n  let tp = xr0 + xr7 ; t3 = xr0 - xr7 ; t1x = xi0 + xi7 ; t1b = xi0 - xi7\n      tq = xr2 + xr9 ; t6 = xr2 - xr9 ; tr = xr12 + xr5 ; t9 = xr12 - xr5\n      tx = xr8 + xr1 ; tn = xr8 - xr1 ; tw = xr6 + xr13 ; tk = xr6 - xr13\n      to = tk + tn ; t1i = tn - tk ; tu = xr10 + xr3 ; tg = xr10 - xr3\n      tt = xr4 + xr11 ; td = xr4 - xr11 ; t1M = tr - tq ; ts = tq + tr\n      ta = t6 + t9 ; t1k = t9 - t6 ; t1L = tt - tu ; tv = tt + tu\n      th = td + tg ; t1j = tg - td ; t1K = tw - tx ; ty = tw + tx\n      tZ = to - kp356895867 * ta ; t14 = th - kp356895867 * to\n      tz = ta - kp356895867 * th ; t1Z = ty - kp356895867 * ts\n      t27 = ts - kp356895867 * tv ; t2c = tv - kp356895867 * ty\n      t1B = xi4 + xi11 ; tE = xi4 - xi11 ; t1C = xi10 + xi3 ; tH = xi10 - xi3\n      t1F = xi8 + xi1 ; tV = xi8 - xi1 ; t1E = xi6 + xi13 ; tS = xi6 - xi13\n      t1z = xi12 + xi5 ; tO = xi12 - xi5 ; t1d = tE + tH ; tI = tE - tH\n      t23 = t1F - t1E ; t1G = t1E + t1F ; t1D = t1B + t1C ; t24 = t1C - t1B\n      t1y = xi2 + xi9 ; tL = xi2 - xi9 ; tW = tS - tV ; t1e = tS + tV\n      t22 = t1y - t1z ; t1A = t1y + t1z ; tP = tL - tO ; t1c = tL + tO\n      t1n = t1e - kp356895867 * t1c ; t1s = t1c - kp356895867 * t1d\n      t1f = t1d - kp356895867 * t1e ; t1P = t1G - kp356895867 * t1A\n      t1U = t1A - kp356895867 * t1D ; t1H = t1D - kp356895867 * t1G\n      tA = to - kp692021471 * tz ; tX = tP + kp554958132 * tW\n      t1t = t1e - kp692021471 * t1s ; t1v = t1k + kp554958132 * t1i\n      tB = t3 - kp900968867 * tA ; tY = tI + kp801937735 * tX\n      t1u = t1b - kp900968867 * t1t ; t1w = t1j + kp801937735 * t1v\n      t10 = th - kp692021471 * tZ ; t11 = t3 - kp900968867 * t10\n      t12 = tW + kp554958132 * tI ; t1o = t1d - kp692021471 * t1n\n      t1q = t1i + kp554958132 * t1j ; t15 = ta - kp692021471 * t14\n      t13 = tP - kp801937735 * t12 ; t1p = t1b - kp900968867 * t1o\n      t1r = t1k - kp801937735 * t1q ; t16 = t3 - kp900968867 * t15\n      t17 = tI - kp554958132 * tP ; t1g = t1c - kp692021471 * t1f\n      t1l = t1j - kp554958132 * t1k ; t1I = t1A - kp692021471 * t1H\n      t18 = tW - kp801937735 * t17 ; t1h = t1b - kp900968867 * t1g\n      t1m = t1i - kp801937735 * t1l ; t1J = t1x - kp900968867 * t1I\n      t1N = t1L + kp554958132 * t1M ; t2d = ts - kp692021471 * t2c\n      t2f = t24 + kp554958132 * t22 ; t1Q = t1D - kp692021471 * t1P\n      t1O = t1K - kp801937735 * t1N ; t2e = tp - kp900968867 * t2d\n      t2g = t23 - kp801937735 * t2f ; t1R = t1x - kp900968867 * t1Q\n      t1S = t1K + kp554958132 * t1L ; t20 = tv - kp692021471 * t1Z\n      t25 = t23 + kp554958132 * t24 ; t1V = t1G - kp692021471 * t1U\n      t1T = t1M + kp801937735 * t1S ; t21 = tp - kp900968867 * t20\n      t26 = t22 + kp801937735 * t25 ; t1W = t1x - kp900968867 * t1V\n      t1X = t1M - kp554958132 * t1K ; t28 = ty - kp692021471 * t27\n      t2a = t22 - kp554958132 * t23 ; t1Y = t1L - kp801937735 * t1X\n      t29 = tp - kp900968867 * t28 ; t2b = t24 - kp801937735 * t2a\n      r13 = (tB + kp974927912 * tY) :+ (t1u + kp974927912 * t1w)\n      r12 = (t21 + kp974927912 * t26) :+ (t1R + kp974927912 * t1T)\n      r11 = (t16 + kp974927912 * t18) :+ (t1h + kp974927912 * t1m)\n      r10 = (t2e + kp974927912 * t2g) :+ (t1J + kp974927912 * t1O)\n      r9 = (t11 - kp974927912 * t13) :+ (t1p - kp974927912 * t1r)\n      r8 = (t29 + kp974927912 * t2b) :+ (t1W + kp974927912 * t1Y)\n      r7 = (t3 + ta + th + to) :+ (t1b + t1c + t1d + t1e)\n      r6 = (t29 - kp974927912 * t2b) :+ (t1W - kp974927912 * t1Y)\n      r5 = (t11 + kp974927912 * t13) :+ (t1p + kp974927912 * t1r)\n      r4 = (t2e - kp974927912 * t2g) :+ (t1J - kp974927912 * t1O)\n      r3 = (t16 - kp974927912 * t18) :+ (t1h - kp974927912 * t1m)\n      r2 = (t21 - kp974927912 * t26) :+ (t1R - kp974927912 * t1T)\n      r1 = (tB - kp974927912 * tY) :+ (t1u - kp974927912 * t1w)\n  MV.unsafeWrite xsout 0 $ (tp + ts + tv + ty) :+ (t1x + t1A + t1D + t1G)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r13\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r12\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r11\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r10\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r9\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r8\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r7\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r6\n  MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r5\n  MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r4\n  MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r3\n  MV.unsafeWrite xsout 12 $ if sign == 1 then r12 else r2\n  MV.unsafeWrite xsout 13 $ if sign == 1 then r13 else r1\n\n-- | Length 15 hard-coded FFT.\n--kp951056516, kp559016994, kp618033988 :: Double\n--kp250000000, kp866025403, kp500000000 :: Double\n--kp951056516 = 0.951056516295153572116439333379382143405698634\n--kp559016994 = 0.559016994374947424102293417182819058860154590\n--kp618033988 = 0.618033988749894848204586834365638117720309180\n--kp250000000 = 0.250000000000000000000000000000000000000000000\n--kp866025403 = 0.866025403784438646763723170752936183471402627\n--kp500000000 = 0.500000000000000000000000000000000000000000000\nspecial15 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial15 sign xsin xsout = do\n  xr0  :+ xi0  <- MV.unsafeRead xsin 0  ; xr1  :+ xi1  <- MV.unsafeRead xsin 1\n  xr2  :+ xi2  <- MV.unsafeRead xsin 2  ; xr3  :+ xi3  <- MV.unsafeRead xsin 3\n  xr4  :+ xi4  <- MV.unsafeRead xsin 4  ; xr5  :+ xi5  <- MV.unsafeRead xsin 5\n  xr6  :+ xi6  <- MV.unsafeRead xsin 6  ; xr7  :+ xi7  <- MV.unsafeRead xsin 7\n  xr8  :+ xi8  <- MV.unsafeRead xsin 8  ; xr9  :+ xi9  <- MV.unsafeRead xsin 9\n  xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n  xr12 :+ xi12 <- MV.unsafeRead xsin 12 ; xr13 :+ xi13 <- MV.unsafeRead xsin 13\n  xr14 :+ xi14 <- MV.unsafeRead xsin 14\n  let t1y = xr10 - xr5 ; t4 = xr5 + xr10 ; t1w = xi5 + xi10 ; tw = xi5 - xi10\n      t5 = xr0 + t4 ; tt = xr0 - kp500000000 * t4\n      t2l = xi0 + t1w ; t1x = xi0 - kp500000000 * t1w\n      tx = tt - kp866025403 * tw ; tV = tt + kp866025403 * tw\n      t1z = t1x + kp866025403 * t1y ; t1X = t1x - kp866025403 * t1y\n      tk = xr11 + xr1 ; t1k = xr1 - xr11 ; tM = xi11 - xi1 ; t1i = xi11 + xi1\n      tJ = xr6 - kp500000000 * tk ; tl = xr6 + tk ; t2c = xi6 + t1i\n      t1j = xi6 - kp500000000 * t1i ; t1p = xr4 - xr14 ; tp = xr14 + xr4\n      tN = tJ - kp866025403 * tM ; tZ = tJ + kp866025403 * tM\n      tO = xr9 - kp500000000 * tp ; tq = xr9 + tp ; t1n = xi14 + xi4\n      tR = xi14 - xi4 ; t2s = tl - tq ; tr = tl + tq\n      t10 = tO + kp866025403 * tR ; tS = tO - kp866025403 * tR\n      t1o = xi9 - kp500000000 * t1n ; t2d = xi9 + t1n\n      t1O = t1j - kp866025403 * t1k ; t1l = t1j + kp866025403 * t1k\n      t24 = tN - tS ; tT = tN + tS ; t1P = t1o - kp866025403 * t1p\n      t1q = t1o + kp866025403 * t1p ; t2e = t2c - t2d ; t2n = t2c + t2d\n      t1Z = t1O + t1P ; t1Q = t1O - t1P ; t1r = t1l - t1q ; t1B = t1l + t1q\n      t11 = tZ + t10 ; t1H = tZ - t10 ; t9 = xr8 + xr13 ; t19 = xr13 - xr8\n      tB = xi8 - xi13 ; t17 = xi8 + xi13 ; ty = xr3 - kp500000000 * t9\n      ta = xr3 + t9 ; t2f = xi3 + t17 ; t18 = xi3 - kp500000000 * t17\n      t1e = xr7 - xr2 ; te = xr2 + xr7 ; tC = ty - kp866025403 * tB\n      tW = ty + kp866025403 * tB ; tD = xr12 - kp500000000 * te\n      tf = xr12 + te ; t1c = xi2 + xi7 ; tG = xi2 - xi7 ; t2t = ta - tf\n      tg = ta + tf ; tX = tD + kp866025403 * tG\n      tH = tD - kp866025403 * tG ; t1d = xi12 - kp500000000 * t1c\n      t2g = xi12 + t1c ; t1R = t18 - kp866025403 * t19\n      t1a = t18 + kp866025403 * t19 ; t25 = tC - tH ; tI = tC + tH\n      t1S = t1d - kp866025403 * t1e ; t1f = t1d + kp866025403 * t1e\n      t2h = t2f - t2g ; t2m = t2f + t2g ; t1Y = t1R + t1S ; t1T = t1R - t1S\n      t1g = t1a - t1f ; t1A = t1a + t1f ; t2a = tg - tr ; ts = tg + tr\n      tY = tW + tX ; t1G = tW - tX ; t29 = t5 - kp250000000 * ts\n      t2o = t2m + t2n ; t2q = t2m - t2n ; t2k = t2h + kp618033988 * t2e\n      t2i = t2e - kp618033988 * t2h ; t2b = t29 - kp559016994 * t2a\n      t2j = t29 + kp559016994 * t2a ; t2p = t2l - kp250000000 * t2o\n      tU = tI + tT ; t1M = tI - tT ; t2r = t2p - kp559016994 * t2q\n      t2v = t2p + kp559016994 * t2q ; t2w = t2t + kp618033988 * t2s\n      t2u = t2s - kp618033988 * t2t ; t1L = tx - kp250000000 * tU\n      t20 = t1Y + t1Z ; t22 = t1Y - t1Z ; t1N = t1L - kp559016994 * t1M\n      t1V = t1L + kp559016994 * t1M ; t1W = t1T + kp618033988 * t1Q\n      t1U = t1Q - kp618033988 * t1T ; t21 = t1X - kp250000000 * t20\n      t1C = t1A + t1B ; t1E = t1A - t1B ; t23 = t21 - kp559016994 * t22\n      t27 = t21 + kp559016994 * t22 ; t28 = t25 + kp618033988 * t24\n      t26 = t24 - kp618033988 * t25 ; t1D = t1z - kp250000000 * t1C\n      t12 = tY + t11 ; t14 = tY - t11 ; t1F = t1D + kp559016994 * t1E\n      t1J = t1D - kp559016994 * t1E ; t1K = t1H - kp618033988 * t1G\n      t1I = t1G + kp618033988 * t1H ; t13 = tV - kp250000000 * t12\n      t1t = t13 - kp559016994 * t14 ; t15 = t13 + kp559016994 * t14\n      t1s = t1g + kp618033988 * t1r ; t1u = t1r - kp618033988 * t1g\n      r14 = (t15 + kp951056516 * t1s) :+ (t1F - kp951056516 * t1I)\n      r13 = (t1N - kp951056516 * t1U) :+ (t23 + kp951056516 * t26)\n      r12 = (t2b + kp951056516 * t2i) :+ (t2r - kp951056516 * t2u)\n      r11 = (t15 - kp951056516 * t1s) :+ (t1F + kp951056516 * t1I)\n      r10 = (tx + tU) :+ (t1X + t20)\n      r9 = (t2j + kp951056516 * t2k) :+ (t2v - kp951056516 * t2w)\n      r8 = (t1t - kp951056516 * t1u) :+ (t1J + kp951056516 * t1K)\n      r7 = (t1N + kp951056516 * t1U) :+ (t23 - kp951056516 * t26)\n      r6 = (t2j - kp951056516 * t2k) :+ (t2v + kp951056516 * t2w)\n      r5 = (tV + t12) :+ (t1z + t1C)\n      r4 = (t1V + kp951056516 * t1W) :+ (t27 - kp951056516 * t28)\n      r3 = (t2b - kp951056516 * t2i) :+ (t2r + kp951056516 * t2u)\n      r2 = (t1t + kp951056516 * t1u) :+ (t1J - kp951056516 * t1K)\n      r1 = (t1V - kp951056516 * t1W) :+ (t27 + kp951056516 * t28)\n  MV.unsafeWrite xsout 0 $ (t5 + ts) :+ (t2l + t2o)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r14\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r13\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r12\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r11\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r10\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r9\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r8\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r7\n  MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r6\n  MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r5\n  MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r4\n  MV.unsafeWrite xsout 12 $ if sign == 1 then r12 else r3\n  MV.unsafeWrite xsout 13 $ if sign == 1 then r13 else r2\n  MV.unsafeWrite xsout 14 $ if sign == 1 then r14 else r1\n\n-- | Length 20 hard-coded FFT.\n--kp951056516, kp559016994, kp618033988, kp250000000 :: Double\n--kp951056516 = 0.951056516295153572116439333379382143405698634\n--kp559016994 = 0.559016994374947424102293417182819058860154590\n--kp618033988 = 0.618033988749894848204586834365638117720309180\n--kp250000000 = 0.250000000000000000000000000000000000000000000\nspecial20 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial20 sign xsin xsout = do\n  xr0  :+ xi0  <- MV.unsafeRead xsin 0  ; xr1  :+ xi1  <- MV.unsafeRead xsin 1\n  xr2  :+ xi2  <- MV.unsafeRead xsin 2  ; xr3  :+ xi3  <- MV.unsafeRead xsin 3\n  xr4  :+ xi4  <- MV.unsafeRead xsin 4  ; xr5  :+ xi5  <- MV.unsafeRead xsin 5\n  xr6  :+ xi6  <- MV.unsafeRead xsin 6  ; xr7  :+ xi7  <- MV.unsafeRead xsin 7\n  xr8  :+ xi8  <- MV.unsafeRead xsin 8  ; xr9  :+ xi9  <- MV.unsafeRead xsin 9\n  xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n  xr12 :+ xi12 <- MV.unsafeRead xsin 12 ; xr13 :+ xi13 <- MV.unsafeRead xsin 13\n  xr14 :+ xi14 <- MV.unsafeRead xsin 14 ; xr15 :+ xi15 <- MV.unsafeRead xsin 15\n  xr16 :+ xi16 <- MV.unsafeRead xsin 16 ; xr17 :+ xi17 <- MV.unsafeRead xsin 17\n  xr18 :+ xi18 <- MV.unsafeRead xsin 18 ; xr19 :+ xi19 <- MV.unsafeRead xsin 19\n  let t1N = xr0 - xr10 ; t3 = xr0 + xr10 ; t2L = xi0 + xi10 ; tN = xi0 - xi10\n      tO = xr5 - xr15 ; t6 = xr5 + xr15 ; t2M = xi5 + xi15 ; t1Q = xi5 - xi15\n      t1d = tO + tN ; tP = tN - tO ; tD = t3 + t6 ; t7 = t3 - t6\n      t3b = t2L + t2M ; t2N = t2L - t2M ; t2f = t1N + t1Q ; t1R = t1N - t1Q\n      t1o = xr8 - xr18 ; tp = xr8 + xr18 ; t2u = xi8 + xi18 ; t13 = xi8 - xi18\n      t14 = xr13 - xr3 ; ts = xr13 + xr3 ; t2v = xi13 + xi3 ; t1r = xi13 - xi3\n      t1t = xr12 - xr2 ; tw = xr12 + xr2 ; t2x = xi12 + xi2 ; t18 = xi12 - xi2\n      tH = tp + ts ; tt = tp - ts ; t19 = xr17 - xr7 ; tz = xr17 + xr7\n      t2y = xi17 + xi7 ; t1w = xi17 - xi7 ; t2w = t2u - t2v ; t35 = t2u + t2v\n      tI = tw + tz ; tA = tw - tz ; t2z = t2x - t2y ; t36 = t2x + t2y\n      t2U = tt - tA ; tB = tt + tA ; t2P = t2w + t2z ; t2A = t2w - t2z\n      t3d = t35 + t36 ; t37 = t35 - t36 ; t15 = t13 - t14 ; t1h = t14 + t13\n      t1i = t19 + t18 ; t1a = t18 - t19 ; t1s = t1o - t1r ; t29 = t1o + t1r\n      t3j = tH - tI ; tJ = tH + tI ; t1x = t1t - t1w ; t2a = t1t + t1w\n      t2n = t15 - t1a ; t1b = t15 + t1a ; t1T = t1s + t1x ; t1y = t1s - t1x\n      t2b = t29 - t2a ; t2h = t29 + t2a ; t1j = t1h + t1i ; t1Y = t1h - t1i\n      ta = xr4 + xr14 ; t1z = xr4 - xr14 ; t2B = xi4 + xi14 ; tS = xi4 - xi14\n      tT = xr9 - xr19 ; td = xr9 + xr19 ; t2C = xi9 + xi19 ; t1C = xi9 - xi19\n      t1E = xr16 - xr6 ; th = xr16 + xr6 ; t2E = xi16 + xi6 ; tX = xi16 - xi6\n      tE = ta + td ; te = ta - td ; tY = xr1 - xr11 ; tk = xr1 + xr11\n      t2F = xi1 + xi11 ; t1H = xi1 - xi11 ; t2D = t2B - t2C ; t32 = t2B + t2C\n      tF = th + tk ; tl = th - tk ; t2G = t2E - t2F ; t33 = t2E + t2F\n      t2V = te - tl ; tm = te + tl ; t2O = t2D + t2G ; t2H = t2D - t2G\n      t3c = t32 + t33 ; t34 = t32 - t33 ; tU = tS - tT ; t1e = tT + tS\n      t1f = tY + tX ; tZ = tX - tY ; t1D = t1z - t1C ; t26 = t1z + t1C\n      t3i = tE - tF ; tG = tE + tF ; t1I = t1E - t1H ; t27 = t1E + t1H\n      t2m = tU - tZ ; t10 = tU + tZ ; t1S = t1D + t1I ; t1J = t1D - t1I\n      t28 = t26 - t27 ; t2g = t26 + t27 ; t2s = tm - tB ; tC = tm + tB\n      t1g = t1e + t1f ; t1Z = t1e - t1f ; t2r = t7 - kp250000000 * tC\n      t2Q = t2O + t2P ; t2S = t2O - t2P ; t2K = t2H + kp618033988 * t2A\n      t2I = t2A - kp618033988 * t2H ; t2t = t2r - kp559016994 * t2s\n      t2J = t2r + kp559016994 * t2s ; t2R = t2N - kp250000000 * t2Q\n      tK = tG + tJ ; t30 = tG - tJ ; t2T = t2R - kp559016994 * t2S\n      t2X = t2R + kp559016994 * t2S ; t2Y = t2V + kp618033988 * t2U\n      t2W = t2U - kp618033988 * t2V ; t2Z = tD - kp250000000 * tK\n      t3e = t3c + t3d ; t3g = t3c - t3d ; t31 = t2Z + kp559016994 * t30\n      t39 = t2Z - kp559016994 * t30 ; t3a = t37 - kp618033988 * t34\n      t38 = t34 + kp618033988 * t37 ; t3f = t3b - kp250000000 * t3e\n      t1c = t10 + t1b ; t24 = t10 - t1b ; t3h = t3f + kp559016994 * t3g\n      t3l = t3f - kp559016994 * t3g ; t3m = t3j - kp618033988 * t3i\n      t3k = t3i + kp618033988 * t3j ; t23 = tP - kp250000000 * t1c\n      t2i = t2g + t2h ; t2k = t2g - t2h ; t25 = t23 + kp559016994 * t24\n      t2d = t23 - kp559016994 * t24 ; t2e = t2b - kp618033988 * t28\n      t2c = t28 + kp618033988 * t2b ; t2j = t2f - kp250000000 * t2i\n      t1k = t1g + t1j ; t1m = t1g - t1j ; t2l = t2j + kp559016994 * t2k\n      t2p = t2j - kp559016994 * t2k ; t2q = t2n - kp618033988 * t2m\n      t2o = t2m + kp618033988 * t2n ; t1l = t1d - kp250000000 * t1k\n      t1U = t1S + t1T ; t1W = t1S - t1T ; t1n = t1l - kp559016994 * t1m\n      t1L = t1l + kp559016994 * t1m ; t1M = t1J + kp618033988 * t1y\n      t1K = t1y - kp618033988 * t1J ; t1V = t1R - kp250000000 * t1U\n      t21 = t1V + kp559016994 * t1W ; t1X = t1V - kp559016994 * t1W\n      t20 = t1Y - kp618033988 * t1Z ; t22 = t1Z + kp618033988 * t1Y\n      r19 = (t2l + kp951056516 * t2o) :+ (t25 - kp951056516 * t2c)\n      r18 = (t2t - kp951056516 * t2I) :+ (t2T + kp951056516 * t2W)\n      r17 = (t1X + kp951056516 * t20) :+ (t1n - kp951056516 * t1K)\n      r16 = (t31 - kp951056516 * t38) :+ (t3h + kp951056516 * t3k)\n      r15 = (t2f + t2i) :+ (tP + t1c)\n      r14 = (t2J + kp951056516 * t2K) :+ (t2X - kp951056516 * t2Y)\n      r13 = (t1X - kp951056516 * t20) :+ (t1n + kp951056516 * t1K)\n      r12 = (t39 + kp951056516 * t3a) :+ (t3l - kp951056516 * t3m)\n      r11 = (t2l - kp951056516 * t2o) :+ (t25 + kp951056516 * t2c)\n      r10 = (t7 + tC) :+ (t2N + t2Q)\n      r9 = (t21 + kp951056516 * t22) :+ (t1L - kp951056516 * t1M)\n      r8 = (t39 - kp951056516 * t3a) :+ (t3l + kp951056516 * t3m)\n      r7 = (t2p + kp951056516 * t2q) :+ (t2d - kp951056516 * t2e)\n      r6 = (t2J - kp951056516 * t2K) :+ (t2X + kp951056516 * t2Y)\n      r5 = (t1R + t1U) :+ (t1d + t1k)\n      r4 = (t31 + kp951056516 * t38) :+ (t3h - kp951056516 * t3k)\n      r3 = (t2p - kp951056516 * t2q) :+ (t2d + kp951056516 * t2e)\n      r2 = (t2t + kp951056516 * t2I) :+ (t2T - kp951056516 * t2W)\n      r1 = (t21 - kp951056516 * t22) :+ (t1L + kp951056516 * t1M)\n  MV.unsafeWrite xsout 0 $ (tD + tK) :+ (t3b + t3e)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r19\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r18\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r17\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r16\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r15\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r14\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r13\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r12\n  MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r11\n  MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r10\n  MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r9\n  MV.unsafeWrite xsout 12 $ if sign == 1 then r12 else r8\n  MV.unsafeWrite xsout 13 $ if sign == 1 then r13 else r7\n  MV.unsafeWrite xsout 14 $ if sign == 1 then r14 else r6\n  MV.unsafeWrite xsout 15 $ if sign == 1 then r15 else r5\n  MV.unsafeWrite xsout 16 $ if sign == 1 then r16 else r4\n  MV.unsafeWrite xsout 17 $ if sign == 1 then r17 else r3\n  MV.unsafeWrite xsout 18 $ if sign == 1 then r18 else r2\n  MV.unsafeWrite xsout 19 $ if sign == 1 then r19 else r1\n\n-- | Length 25 hard-coded FFT.\nkp803003575, kp554608978, kp248028675, kp726211448 :: Double\nkp525970792, kp992114701, kp851038619, kp912575812 :: Double\nkp912018591, kp943557151, kp614372930, kp621716863 :: Double\nkp994076283, kp734762448, kp772036680, kp126329378 :: Double\nkp827271945, kp949179823, kp860541664, kp557913902 :: Double\nkp249506682, kp681693190, kp560319534, kp998026728 :: Double\nkp906616052, kp968479752, kp845997307, kp470564281 :: Double\nkp062914667, kp921177326, kp833417178, kp541454447 :: Double\nkp242145790, kp683113946, kp559154169, kp968583161 :: Double\nkp904730450, kp831864738, kp871714437, kp939062505 :: Double\nkp549754652, kp634619297, kp256756360 :: Double\n--kp951056516, kp559016994, kp250000000, kp618033988 :: Double\nkp803003575 = 0.803003575438660414833440593570376004635464850\nkp554608978 = 0.554608978404018097464974850792216217022558774\nkp248028675 = 0.248028675328619457762448260696444630363259177\nkp726211448 = 0.726211448929902658173535992263577167607493062\nkp525970792 = 0.525970792408939708442463226536226366643874659\nkp992114701 = 0.992114701314477831049793042785778521453036709\nkp851038619 = 0.851038619207379630836264138867114231259902550\nkp912575812 = 0.912575812670962425556968549836277086778922727\nkp912018591 = 0.912018591466481957908415381764119056233607330\nkp943557151 = 0.943557151597354104399655195398983005179443399\nkp614372930 = 0.614372930789563808870829930444362096004872855\nkp621716863 = 0.621716863012209892444754556304102309693593202\nkp994076283 = 0.994076283785401014123185814696322018529298887\nkp734762448 = 0.734762448793050413546343770063151342619912334\nkp772036680 = 0.772036680810363904029489473607579825330539880\nkp126329378 = 0.126329378446108174786050455341811215027378105\nkp827271945 = 0.827271945972475634034355757144307982555673741\nkp949179823 = 0.949179823508441261575555465843363271711583843\nkp860541664 = 0.860541664367944677098261680920518816412804187\nkp557913902 = 0.557913902031834264187699648465567037992437152\nkp249506682 = 0.249506682107067890488084201715862638334226305\nkp681693190 = 0.681693190061530575150324149145440022633095390\nkp560319534 = 0.560319534973832390111614715371676131169633784\nkp998026728 = 0.998026728428271561952336806863450553336905220\nkp906616052 = 0.906616052148196230441134447086066874408359177\nkp968479752 = 0.968479752739016373193524836781420152702090879\nkp845997307 = 0.845997307939530944175097360758058292389769300\nkp470564281 = 0.470564281212251493087595091036643380879947982\nkp062914667 = 0.062914667253649757225485955897349402364686947\nkp921177326 = 0.921177326965143320250447435415066029359282231\nkp833417178 = 0.833417178328688677408962550243238843138996060\nkp541454447 = 0.541454447536312777046285590082819509052033189\nkp242145790 = 0.242145790282157779872542093866183953459003101\nkp683113946 = 0.683113946453479238701949862233725244439656928\nkp559154169 = 0.559154169276087864842202529084232643714075927\nkp968583161 = 0.968583161128631119490168375464735813836012403\nkp904730450 = 0.904730450839922351881287709692877908104763647\nkp831864738 = 0.831864738706457140726048799369896829771167132\nkp871714437 = 0.871714437527667770979999223229522602943903653\nkp939062505 = 0.939062505817492352556001843133229685779824606\nkp549754652 = 0.549754652192770074288023275540779861653779767\nkp634619297 = 0.634619297544148100711287640319130485732531031\nkp256756360 = 0.256756360367726783319498520922669048172391148\n--kp951056516 = 0.951056516295153572116439333379382143405698634\n--kp559016994 = 0.559016994374947424102293417182819058860154590\n--kp250000000 = 0.250000000000000000000000000000000000000000000\n--kp618033988 = 0.618033988749894848204586834365638117720309180\nspecial25 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial25 sign xsin xsout = do\n  xr0  :+ xi0  <- MV.unsafeRead xsin 0  ; xr1  :+ xi1  <- MV.unsafeRead xsin 1\n  xr2  :+ xi2  <- MV.unsafeRead xsin 2  ; xr3  :+ xi3  <- MV.unsafeRead xsin 3\n  xr4  :+ xi4  <- MV.unsafeRead xsin 4  ; xr5  :+ xi5  <- MV.unsafeRead xsin 5\n  xr6  :+ xi6  <- MV.unsafeRead xsin 6  ; xr7  :+ xi7  <- MV.unsafeRead xsin 7\n  xr8  :+ xi8  <- MV.unsafeRead xsin 8  ; xr9  :+ xi9  <- MV.unsafeRead xsin 9\n  xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n  xr12 :+ xi12 <- MV.unsafeRead xsin 12 ; xr13 :+ xi13 <- MV.unsafeRead xsin 13\n  xr14 :+ xi14 <- MV.unsafeRead xsin 14 ; xr15 :+ xi15 <- MV.unsafeRead xsin 15\n  xr16 :+ xi16 <- MV.unsafeRead xsin 16 ; xr17 :+ xi17 <- MV.unsafeRead xsin 17\n  xr18 :+ xi18 <- MV.unsafeRead xsin 18 ; xr19 :+ xi19 <- MV.unsafeRead xsin 19\n  xr20 :+ xi20 <- MV.unsafeRead xsin 20 ; xr21 :+ xi21 <- MV.unsafeRead xsin 21\n  xr22 :+ xi22 <- MV.unsafeRead xsin 22 ; xr23 :+ xi23 <- MV.unsafeRead xsin 23\n  xr24 :+ xi24 <- MV.unsafeRead xsin 24\n  let t4 = xr5+xr20 ; t1S = xr5-xr20 ; t7 = xr10+xr15 ; t1T = xr10-xr15\n      t4Q = t1T-kp618033988*t1S ; t1U = t1S+kp618033988*t1T\n      t8 = t4+t7 ; t3a = t4-t7 ; t3c = xi5-xi20 ; t1y = xi5+xi20\n      t39 = xr0-kp250000000*t8 ; t9 = xr0+t8\n      t1B = xi10+xi15 ; t3d = xi10-xi15\n      t3b = t39+kp559016994*t3a ; t45 = t39-kp559016994*t3a\n      t3e = t3c+kp618033988*t3d ; t46 = t3d-kp618033988*t3c\n      t1C = t1y+t1B ; t1Q = t1y-t1B ; t1P = xi0-kp250000000*t1C\n      t1D = xi0+t1C ; t4P = t1P-kp559016994*t1Q\n      t1R = t1P+kp559016994*t1Q ; t1Z = xr21-xr6 ; td = xr6+xr21\n      t20 = xr16-xr11 ; tg = xr11+xr16 ; th = td+tg ; t24 = td-tg\n      t26 = xi6-xi21 ; tT = xi6+xi21 ; tW = xi11+xi16 ; t27 = xi16-xi11\n      t1X = tT-tW ; tX = tT+tW ; t2l = xr24-xr9 ; tm = xr9+xr24\n      t2m = xr19-xr14 ; tp = xr14+xr19 ; tq = tm+tp ; t2c = tm-tp\n      t2e = xi24-xi9 ; t12 = xi9+xi24 ; t15 = xi14+xi19 ; t2f = xi19-xi14\n      t23 = xr1-kp250000000*th ; ti = xr1+th ; t2j = t15-t12\n      t16 = t12+t15 ; tr = xr4+tq ; t2b = kp250000000 * tq - xr4\n      t1W = xi1-kp250000000*tX ; tY = xi1+tX\n      t21 = t1Z+kp618033988*t20 ; t4y = t20-kp618033988*t1Z\n      t2i = xi4-kp250000000*t16 ; t17 = xi4+t16 ; ts = ti+tr\n      t1K = ti-tr ; t18 = tY-t17 ; t1E = tY+t17\n      t2n = t2l+kp618033988*t2m ; t4r = t2m-kp618033988*t2l\n      t4x = t1W-kp559016994*t1X ; t1Y = t1W+kp559016994*t1X\n      t4o = t2f-kp618033988*t2e ; t2g = t2e+kp618033988*t2f\n      t4z = t4x+kp951056516*t4y ; t5f = t4x-kp951056516*t4y\n      t3z = t1Y-kp951056516*t21 ; t22 = t1Y+kp951056516*t21\n      t4q = t2i+kp559016994*t2j ; t2k = t2i-kp559016994*t2j\n      t4s = t4q+kp951056516*t4r ; t5b = t4q-kp951056516*t4r\n      t3C = t2k-kp951056516*t2n ; t2o = t2k+kp951056516*t2n\n      t2d = t2b-kp559016994*t2c ; t4n = t2b+kp559016994*t2c\n      t28 = t26-kp618033988*t27 ; t4v = t27+kp618033988*t26\n      t3D = t2d-kp951056516*t2g ; t2h = t2d+kp951056516*t2g\n      t4p = t4n+kp951056516*t4o ; t5c = t4n-kp951056516*t4o\n      t4u = t23-kp559016994*t24 ; t25 = t23+kp559016994*t24\n      t4w = t4u-kp951056516*t4v ; t5e = t4u+kp951056516*t4v\n      t3A = t25-kp951056516*t28 ; t29 = t25+kp951056516*t28\n      t2u = xr22-xr7 ; tw = xr7+xr22 ; t2v = xr17-xr12 ; tz = xr12+xr17\n      tA = tw+tz ; t2z = tz-tw ; t2B = xi22-xi7 ; t1c = xi7+xi22\n      t1f = xi12+xi17 ; t2C = xi12-xi17 ; t2s = t1f-t1c ; t1g = t1c+t1f\n      t2J = xr8-xr23 ; tF = xr8+xr23 ; t2K = xr13-xr18 ; tI = xr13+xr18\n      tJ = tF+tI ; t2O = tI-tF ; t2Q = xi23-xi8 ; t1l = xi8+xi23\n      t1o = xi13+xi18 ; t2R = xi18-xi13 ; t2y = xr2-kp250000000*tA\n      tB = xr2+tA ; t2H = t1o-t1l ; t1p = t1l+t1o ; tK = xr3+tJ\n      t2N = xr3-kp250000000*tJ ; t2r = xi2-kp250000000*t1g\n      t1h = xi2+t1g ; t2w = t2u+kp618033988*t2v\n      t49 = t2v-kp618033988*t2u ; t2G = xi3-kp250000000*t1p\n      t1q = xi3+t1p ; tL = tB+tK ; t1L = tB-tK ; t1r = t1h-t1q\n      t1F = t1h+t1q ; t2S = t2Q+kp618033988*t2R\n      t4j = t2R-kp618033988*t2Q ; t48 = t2r+kp559016994*t2s\n      t2t = t2r-kp559016994*t2s ; t4g = t2K-kp618033988*t2J\n      t2L = t2J+kp618033988*t2K ; t4a = t48+kp951056516*t49\n      t57 = t48-kp951056516*t49 ; t3v = t2t-kp951056516*t2w\n      t2x = t2t+kp951056516*t2w ; t4i = t2N+kp559016994*t2O\n      t2P = t2N-kp559016994*t2O ; t4k = t4i-kp951056516*t4j\n      t55 = t4i+kp951056516*t4j ; t3s = t2P+kp951056516*t2S\n      t2T = t2P-kp951056516*t2S ; t2I = t2G-kp559016994*t2H\n      t4f = t2G+kp559016994*t2H ; t2D = t2B-kp618033988*t2C\n      t4c = t2C+kp618033988*t2B ; t3t = t2I+kp951056516*t2L\n      t2M = t2I-kp951056516*t2L ; t4h = t4f-kp951056516*t4g\n      t54 = t4f+kp951056516*t4g ; tM = ts+tL ; tO = ts-tL\n      t4b = t2y+kp559016994*t2z ; t2A = t2y-kp559016994*t2z\n      tN = t9-kp250000000*tM ; t4d = t4b+kp951056516*t4c\n      t58 = t4b-kp951056516*t4c ; t3w = t2A+kp951056516*t2D\n      t2E = t2A-kp951056516*t2D ; t1s = t18+kp618033988*t1r\n      t1u = t1r-kp618033988*t18 ; tP = tN+kp559016994*tO\n      t1t = tN-kp559016994*tO ; t1G = t1E+t1F ; t1I = t1E-t1F\n      t1H = t1D-kp250000000*t1G ; t1J = t1H+kp559016994*t1I\n      t1N = t1H-kp559016994*t1I ; t1M = t1K+kp618033988*t1L\n      t1O = t1L-kp618033988*t1K ; t3H = t1R+kp951056516*t1U\n      t1V = t1R-kp951056516*t1U ; t3f = t3b+kp951056516*t3e\n      t3r = t3b-kp951056516*t3e ; t30 = t29+kp256756360*t22\n      t2a = t22-kp256756360*t29 ; t2p = t2h+kp634619297*t2o\n      t31 = t2o-kp634619297*t2h ; t33 = t2E+kp549754652*t2x\n      t2F = t2x-kp549754652*t2E ; t2U = t2M-kp939062505*t2T\n      t34 = t2T+kp939062505*t2M ; t3m = t2a-kp871714437*t2p\n      t2q = t2a+kp871714437*t2p ; t3n = t2F-kp831864738*t2U\n      t2V = t2F+kp831864738*t2U ; t2W = t2q+kp904730450*t2V\n      t2Y = t2q-kp904730450*t2V ; t32 = t30-kp871714437*t31\n      t3g = t30+kp871714437*t31 ; t3h = t33+kp831864738*t34\n      t35 = t33-kp831864738*t34 ; t3i = t3g+kp904730450*t3h\n      t3k = t3g-kp904730450*t3h ; t36 = t32+kp559154169*t35\n      t38 = t35-kp683113946*t32 ; t2X = t1V-kp242145790*t2W\n      t3o = t3m+kp559154169*t3n ; t3q = t3n-kp683113946*t3m\n      t3j = t3f-kp242145790*t3i ; t2Z = t2X+kp541454447*t2Y\n      t37 = t2X-kp541454447*t2Y ; t47 = t45+kp951056516*t46\n      t53 = t45-kp951056516*t46 ; t3p = t3j-kp541454447*t3k\n      t3l = t3j+kp541454447*t3k ; t5j = t4P+kp951056516*t4Q\n      t4R = t4P-kp951056516*t4Q ; t5k = t55-kp062914667*t54\n      t56 = t54+kp062914667*t55 ; t59 = t57+kp634619297*t58\n      t5l = t58-kp634619297*t57 ; t5n = t5c-kp470564281*t5b\n      t5d = t5b+kp470564281*t5c ; t5g = t5e+kp549754652*t5f\n      t5o = t5f-kp549754652*t5e ; t5u = t56-kp845997307*t59\n      t5a = t56+kp845997307*t59 ; t5v = t5d-kp968479752*t5g\n      t5h = t5d+kp968479752*t5g ; t5i = t5a+kp906616052*t5h\n      t5A = t5a-kp906616052*t5h ; t5D = t5k-kp845997307*t5l\n      t5m = t5k+kp845997307*t5l ; t5p = t5n+kp968479752*t5o\n      t5C = t5n-kp968479752*t5o ; t5s = t5m+kp906616052*t5p\n      t5q = t5m-kp906616052*t5p ; t5w = t5u-kp560319534*t5v\n      t5y = t5v+kp681693190*t5u ; t5E = t5C-kp681693190*t5D\n      t5G = t5D+kp560319534*t5C ; t5r = t5j+kp249506682*t5q\n      t5z = t53-kp249506682*t5i ; t5t = t5r-kp557913902*t5s\n      t5x = t5r+kp557913902*t5s ; t5F = t5z+kp557913902*t5A\n      t5B = t5z-kp557913902*t5A ; t4J = t4d-kp062914667*t4a\n      t4e = t4a+kp062914667*t4d ; t4l = t4h-kp827271945*t4k\n      t4K = t4k+kp827271945*t4h ; t4G = t4s-kp126329378*t4p\n      t4t = t4p+kp126329378*t4s ; t4A = t4w+kp939062505*t4z\n      t4H = t4z-kp939062505*t4w ; t4Y = t4e-kp772036680*t4l\n      t4m = t4e+kp772036680*t4l ; t4Z = t4t-kp734762448*t4A\n      t4B = t4t+kp734762448*t4A ; t4C = t4m+kp994076283*t4B\n      t4E = t4m-kp994076283*t4B ; t4I = t4G+kp734762448*t4H\n      t4T = t4G-kp734762448*t4H ; t4S = t4J+kp772036680*t4K\n      t4L = t4J-kp772036680*t4K ; t4U = t4S+kp994076283*t4T\n      t4W = t4S-kp994076283*t4T ; t4M = t4I-kp621716863*t4L\n      t4O = t4L+kp614372930*t4I ; t4D = t47-kp249506682*t4C\n      t50 = t4Y+kp614372930*t4Z ; t52 = t4Z-kp621716863*t4Y\n      t4V = t4R+kp249506682*t4U ; t4F = t4D-kp557913902*t4E\n      t4N = t4D+kp557913902*t4E ; t51 = t4V+kp557913902*t4W\n      t4X = t4V-kp557913902*t4W ; t3I = t3t+kp126329378*t3s\n      t3u = t3s-kp126329378*t3t ; t3x = t3v-kp470564281*t3w\n      t3J = t3w+kp470564281*t3v ; t3L = t3A-kp634619297*t3z\n      t3B = t3z+kp634619297*t3A ; t3E = t3C-kp827271945*t3D\n      t3M = t3D+kp827271945*t3C ; t3S = t3u+kp912018591*t3x\n      t3y = t3u-kp912018591*t3x ; t3T = t3B+kp912575812*t3E\n      t3F = t3B-kp912575812*t3E ; t3G = t3y-kp851038619*t3F\n      t3Y = t3y+kp851038619*t3F ; t41 = t3I-kp912018591*t3J\n      t3K = t3I+kp912018591*t3J ; t3N = t3L+kp912575812*t3M\n      t40 = t3L-kp912575812*t3M ; t3Q = t3K-kp851038619*t3N\n      t3O = t3K+kp851038619*t3N ; t3U = t3S-kp525970792*t3T\n      t3W = t3T+kp726211448*t3S ; t42 = t40-kp726211448*t41\n      t44 = t41+kp525970792*t40 ; t3P = t3H+kp248028675*t3O\n      t3X = t3r+kp248028675*t3G ; t3R = t3P-kp554608978*t3Q\n      t3V = t3P+kp554608978*t3Q ; t3Z = t3X+kp554608978*t3Y\n      t43 = t3X-kp554608978*t3Y\n      r24 = (t3f+kp968583161*t3i) :+ (t1V+kp968583161*t2W)\n      r23 = (t53+kp998026728*t5i) :+ (t5j-kp998026728*t5q)\n      r22 = (t47+kp998026728*t4C) :+ (t4R-kp998026728*t4U)\n      r21 = (t3r-kp992114701*t3G) :+ (t3H-kp992114701*t3O)\n      r20 = (tP+kp951056516*t1s) :+ (t1J-kp951056516*t1M)\n      r19 = (t3l+kp921177326*t3o) :+ (t2Z-kp921177326*t36)\n      r18 = (t5B-kp860541664*t5E) :+ (t5x+kp860541664*t5y)\n      r17 = (t4F+kp943557151*t4M) :+ (t51+kp943557151*t52)\n      r16 = (t3Z-kp803003575*t42) :+ (t3V-kp803003575*t3W)\n      r15 = (t1t-kp951056516*t1u) :+ (t1N+kp951056516*t1O)\n      r14 = (t3p-kp833417178*t3q) :+ (t37+kp833417178*t38)\n      r13 = (t5F-kp949179823*t5G) :+ (t5t-kp949179823*t5w)\n      r12 = (t4N+kp949179823*t4O) :+ (t4X+kp949179823*t50)\n      r11 = (t43-kp943557151*t44) :+ (t3R+kp943557151*t3U)\n      r10 = (t1t+kp951056516*t1u) :+ (t1N-kp951056516*t1O)\n      r9 = (t3p+kp833417178*t3q) :+ (t37-kp833417178*t38)\n      r8 = (t5F+kp949179823*t5G) :+ (t5t+kp949179823*t5w)\n      r7 = (t4N-kp949179823*t4O) :+ (t4X-kp949179823*t50)\n      r6 = (t43+kp943557151*t44) :+ (t3R-kp943557151*t3U)\n      r5 = (tP-kp951056516*t1s) :+ (t1J+kp951056516*t1M)\n      r4 = (t3l-kp921177326*t3o) :+ (t2Z+kp921177326*t36)\n      r3 = (t5B+kp860541664*t5E) :+ (t5x-kp860541664*t5y)\n      r2 = (t4F-kp943557151*t4M) :+ (t51-kp943557151*t52)\n      r1 = (t3Z+kp803003575*t42) :+ (t3V+kp803003575*t3W)\n  MV.unsafeWrite xsout 0 $ (t9+tM) :+ (t1D+t1G)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r24\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r23\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r22\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r21\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r20\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r19\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r18\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r17\n  MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r16\n  MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r15\n  MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r14\n  MV.unsafeWrite xsout 12 $ if sign == 1 then r12 else r13\n  MV.unsafeWrite xsout 13 $ if sign == 1 then r13 else r12\n  MV.unsafeWrite xsout 14 $ if sign == 1 then r14 else r11\n  MV.unsafeWrite xsout 15 $ if sign == 1 then r15 else r10\n  MV.unsafeWrite xsout 16 $ if sign == 1 then r16 else r9\n  MV.unsafeWrite xsout 17 $ if sign == 1 then r17 else r8\n  MV.unsafeWrite xsout 18 $ if sign == 1 then r18 else r7\n  MV.unsafeWrite xsout 19 $ if sign == 1 then r19 else r6\n  MV.unsafeWrite xsout 20 $ if sign == 1 then r20 else r5\n  MV.unsafeWrite xsout 21 $ if sign == 1 then r21 else r4\n  MV.unsafeWrite xsout 22 $ if sign == 1 then r22 else r3\n  MV.unsafeWrite xsout 23 $ if sign == 1 then r23 else r2\n  MV.unsafeWrite xsout 24 $ if sign == 1 then r24 else r1\n\n", "meta": {"hexsha": "1bceb419850e0e33ce26e2187fa5c5fd6be81ec3", "size": 47282, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/FFT/Special/Miscellaneous.hs", "max_stars_repo_name": "ian-ross/arb-fft", "max_stars_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-15T09:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-08T13:14:27.000Z", "max_issues_repo_path": "Numeric/FFT/Special/Miscellaneous.hs", "max_issues_repo_name": "ian-ross/arb-fft", "max_issues_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-03-08T20:31:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T20:32:09.000Z", "max_forks_repo_path": "Numeric/FFT/Special/Miscellaneous.hs", "max_forks_repo_name": "ian-ross/arb-fft", "max_forks_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-11-25T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-06T22:54:26.000Z", "avg_line_length": 60.9304123711, "max_line_length": 79, "alphanum_fraction": 0.6240641259, "num_tokens": 22038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.418303427863344}}
{"text": "{-# LANGUAGE RankNTypes   #-}\n{-# LANGUAGE Strict       #-}\n{-# LANGUAGE StrictData   #-}\nmodule Pinwheel.BlockCudaMatrix where\n\nimport           Control.Concurrent.Async\nimport           Control.DeepSeq\nimport           Control.Monad            as M\nimport           Data.Array.Repa          as R\nimport           Data.Complex\nimport           Data.List                as L\nimport           Data.Vector.Storable     as VS\nimport           Data.Vector.Unboxed      as VU\nimport           Foreign.CUDA.BLAS        as BLAS\nimport           Foreign.CUDA.Driver      as CUDA\nimport           Text.Printf\nimport           Utils.BLAS\nimport           Utils.Parallel\n\ndata CuVec a\n  = CuVecHost (VS.Vector a)\n  | CuVecDevice (DevicePtr a)\n\ndata CuMat a =\n  CuMat Int\n        Int\n        (CuVec a)\n\ninstance (Storable a) => Show (CuVec a) where\n  show (CuVecHost vec) = printf \"CuVecHost length %d\" (VS.length vec)\n  show (CuVecDevice _) = \"CuVecDevice\"\n\ninstance NFData (CuVec a) where\n  rnf (CuVecHost vec) = seq vec ()\n  rnf (CuVecDevice ptr) = seq ptr ()\n\ninstance (Storable a) => Show (CuMat a) where\n  show (CuMat rows cols vec) =\n    printf \"CuMat rows = %d cols = %d %s\" rows cols (show vec)\n\ninstance NFData (CuMat a) where\n  rnf (CuMat rows cols vec) = rows `seq` cols `seq` vec `seq` ()\n\n{-# INLINE getHostCuVec #-}\ngetHostCuVec :: (Storable a) => CuVec a -> VS.Vector a\ngetHostCuVec (CuVecHost vec) = vec\ngetHostCuVec (CuVecDevice _) = error \"Error in getHostCuVec: no host vector.\"\n\n{-# INLINE getHostCuMat #-}\ngetHostCuMat :: (Storable a) => CuMat a -> VS.Vector a\ngetHostCuMat (CuMat _ _ vec) = getHostCuVec vec\n\n{-# INLINE getRowsCuMat #-}\ngetRowsCuMat :: CuMat a -> Int\ngetRowsCuMat (CuMat rows _ _) = rows\n\n{-# INLINE getColsCuMat #-}\ngetColsCuMat :: CuMat a -> Int\ngetColsCuMat (CuMat _ cols _) = cols\n\n{-# INLINE concatCuMat #-}\nconcatCuMat :: (Storable a) => [CuMat a] -> CuMat a\nconcatCuMat xs =\n  let rows = L.foldl' (\\s mat -> s + getRowsCuMat mat) 0 xs\n      cols = getColsCuMat . L.head $ xs\n  in if L.any (/= cols) . L.map getColsCuMat $ xs\n       then error\n              \"concatCuMat: concat matries with different numbers of columns.\"\n       else CuMat rows cols . CuVecHost . VS.concat . L.map getHostCuMat $ xs\n\n{-# INLINE unsafeWithCuMat #-}\nunsafeWithCuMat :: (Storable e) => CuMat e -> (DevicePtr e -> IO a) -> IO a\nunsafeWithCuMat (CuMat _ _ (CuVecHost vec)) f = unsafeWithGPU vec f\nunsafeWithCuMat (CuMat _ _ (CuVecDevice vec)) f = f vec\n\n{-# INLINE freeCuMat #-}\nfreeCuMat :: CuMat e -> IO ()\nfreeCuMat (CuMat _ _ (CuVecHost _)) = return ()\nfreeCuMat (CuMat _ _ (CuVecDevice ptr)) = CUDA.free ptr\n\n{-# INLINE subMatMul #-}\nsubMatMul ::\n     (Storable e, Floating e, CUBLAS e)\n  => Handle\n  -> Int\n  -> [CuMat e]\n  -> CuMat e\n  -> IO (CuMat e)\nsubMatMul handle rows matA@((CuMat rowsA colsA _):_) b@(CuMat _ colsB _) =\n  fmap (CuMat rows colsB . CuVecHost . VS.concat) . unsafeWithCuMat b $ \\bPtr ->\n    M.mapM\n      (\\harmonic ->\n         unsafeWithCuMat harmonic $ \\harmonicPtr ->\n           gemmCuBLAS handle rowsA colsB colsA harmonicPtr bPtr)\n      matA\n\n-- Given row-major Mat1: rows1xcols1 and Mat2: rows2xcols2, this function outputs Mat1 X Mat2\nmatMul ::\n     (Storable e, Floating e, CUBLAS e, Unbox e)\n  => Bool\n  -> Int\n  -> Int\n  -> [CuMat e]\n  -> [CuMat e]\n  -> IO (CuMat e)\nmatMul doesTranspose deviceID rows matA' matB = do\n  dev <- device deviceID\n  ctx <- CUDA.create dev []\n  handle <- BLAS.create\n  matA <-\n    if L.length matA' == 1\n      then do\n        let (CuMat rowsA colsA (CuVecHost vec)) = L.head matA'\n            len = rowsA * colsA\n        devPtr <- CUDA.mallocArray len\n        unsafeWith vec $ \\ptr -> CUDA.pokeArray len ptr devPtr\n        return [CuMat rowsA colsA (CuVecDevice devPtr)]\n      else return matA'\n  coefs <- M.mapM (subMatMul handle rows matA) matB\n  let transposedCoefs = concatCuMat . parMap rdeepseq transposeCuMat $ coefs\n      output =\n        if doesTranspose\n          then transposedCoefs\n          else transposeCuMat transposedCoefs\n  when (L.length matA' == 1) (freeCuMat . L.head $ matA)\n  BLAS.destroy handle\n  CUDA.destroy ctx\n  return output\n\n-- matA is divided into [rowsA1 x colsA .. rowsAN x colsA]\n-- matB is divided into [colsA x colsB1 .. colsA x colsBM]\n-- each colsA x colsBm is further divided into [colsA x colsBmk]\n-- M is the number of GPUs\n{-# INLINE blockMatrixMultiply #-}\nblockMatrixMultiply ::\n     (Storable e, Floating e, CUBLAS e, Unbox e)\n  => Bool\n  -> [Int]\n  -> [CuMat e]\n  -> [[CuMat e]]\n  -> IO (CuMat e)\nblockMatrixMultiply doesTranspose deviceIDs matAs matBss = do\n  unless\n    (L.length deviceIDs == L.length matBss)\n    (error $\n     printf\n       \"Error in blockMatrixMultiply: matrix B is not divided according to the number of GPUs.\\n%d GPUs vs %d blocks\"\n       (L.length deviceIDs)\n       (L.length matBss))\n  let rows = L.sum . L.map getRowsCuMat $ matAs\n  print matAs\n  print matBss\n  initialise []\n  output <-\n    fmap concatCuMat .\n    mapConcurrently\n      (\\(deviceID, matBs) -> matMul True deviceID rows matAs matBs) .\n    L.zip deviceIDs $\n    matBss\n  return $!\n    if doesTranspose\n      then output\n      else transposeCuMat output\n\n\n-- Utilities\n{-# INLINE transposeCuMat #-}\ntransposeCuMat :: (Storable e, Unbox e) => CuMat e -> CuMat e\ntransposeCuMat (CuMat rows cols (CuVecHost vec)) =\n  CuMat cols rows .\n  CuVecHost .\n  VS.convert .\n  toUnboxed .\n  computeS .\n  R.backpermute (Z :. cols :. rows) (\\(Z :. r :. c) -> (Z :. c :. r)) .\n  fromUnboxed (Z :. rows :. cols) . VS.convert $\n  vec\ntransposeCuMat _ = error \"transposeCuMat: Cannot transpose matrices on a device.\"\n\n{-# INLINE createCuMat #-}\ncreateCuMat :: (Storable e) => [VS.Vector e] -> CuMat e\ncreateCuMat xs =\n  CuMat (L.length xs) (VS.length . L.head $ xs) . CuVecHost . VS.concat $ xs\n", "meta": {"hexsha": "a6c428c9debd38e7d8c1a2eb72d4e4a7fc5695b9", "size": 5791, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Pinwheel/BlockCudaMatrix.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Pinwheel/BlockCudaMatrix.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/Pinwheel/BlockCudaMatrix.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.472826087, "max_line_length": 117, "alphanum_fraction": 0.6397858746, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41823561219340794}}
{"text": "{-# LANGUAGE CPP, NoImplicitPrelude #-}\nmodule Data.Complex.Compat (\n  module Base\n#if MIN_VERSION_base(4,4,0) && !(MIN_VERSION_base(4,8,0))\n, realPart\n, imagPart\n, mkPolar\n, cis\n, conjugate\n#endif\n) where\n\n#if !(MIN_VERSION_base(4,4,0)) || MIN_VERSION_base(4,8,0)\nimport Data.Complex as Base\n#else\nimport Data.Complex as Base hiding (\n    realPart\n  , imagPart\n  , mkPolar\n  , cis\n  , conjugate\n  )\nimport Prelude\n#endif\n\n#if MIN_VERSION_base(4,4,0) && !(MIN_VERSION_base(4,8,0))\n-- | Extracts the real part of a complex number.\nrealPart :: Complex a -> a\nrealPart (x :+ _) =  x\n\n-- | Extracts the imaginary part of a complex number.\nimagPart :: Complex a -> a\nimagPart (_ :+ y) =  y\n\n-- | The conjugate of a complex number.\n{-# SPECIALISE conjugate :: Complex Double -> Complex Double #-}\nconjugate        :: Num a => Complex a -> Complex a\nconjugate (x:+y) =  x :+ (-y)\n\n-- | Form a complex number from polar components of magnitude and phase.\n{-# SPECIALISE mkPolar :: Double -> Double -> Complex Double #-}\nmkPolar          :: Floating a => a -> a -> Complex a\nmkPolar r theta  =  r * cos theta :+ r * sin theta\n\n-- | @'cis' t@ is a complex value with magnitude @1@\n-- and phase @t@ (modulo @2*'pi'@).\n{-# SPECIALISE cis :: Double -> Complex Double #-}\ncis              :: Floating a => a -> Complex a\ncis theta        =  cos theta :+ sin theta\n#endif\n", "meta": {"hexsha": "974001fb02b143406f382bfbeef00ee8bfca1c96", "size": 1357, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "base-compat/src/Data/Complex/Compat.hs", "max_stars_repo_name": "kozross/base-compat", "max_stars_repo_head_hexsha": "f6c18fd558e56d9365c37a3053d6c8b833963042", "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": "base-compat/src/Data/Complex/Compat.hs", "max_issues_repo_name": "kozross/base-compat", "max_issues_repo_head_hexsha": "f6c18fd558e56d9365c37a3053d6c8b833963042", "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": "base-compat/src/Data/Complex/Compat.hs", "max_forks_repo_name": "kozross/base-compat", "max_forks_repo_head_hexsha": "f6c18fd558e56d9365c37a3053d6c8b833963042", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6078431373, "max_line_length": 72, "alphanum_fraction": 0.6403831982, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4182356121934078}}
{"text": "{-# LANGUAGE\n  DataKinds,\n  DeriveDataTypeable,\n  FlexibleInstances,\n  GADTs,\n  MultiParamTypeClasses,\n  TemplateHaskell,\n  TypeFamilies #-}\n\n{- |\nModule      :  Data.Real.Constructible\nDescription :  Constructible real numbers\nCopyright   :  \u00a9 Anders Kaseorg, 2013\nLicense     :  BSD-style\n\nMaintainer  :  Anders Kaseorg <andersk@mit.edu>\nStability   :  experimental\nPortability :  Non-portable (GHC extensions)\n\nThe constructible reals, 'Construct', are the subset of the real\nnumbers that can be represented exactly using field operations\n(addition, subtraction, multiplication, division) and positive square\nroots.  They support exact computations, equality comparisons, and\nordering.\n\n>>> [((1 + sqrt 5)/2)^n - ((1 - sqrt 5)/2)^n :: Construct | n <- [1..10]]\n[sqrt 5,sqrt 5,2*sqrt 5,3*sqrt 5,5*sqrt 5,8*sqrt 5,13*sqrt 5,21*sqrt 5,34*sqrt 5,55*sqrt 5]\n\n>>> let f (a, b, t, p) = ((a + b)/2, sqrt (a*b), t - p*((a - b)/2)^2, 2*p)\n>>> let (a, b, t, p) = f . f . f . f $ (1, 1/sqrt 2, 1/4, 1 :: Construct)\n>>> floor $ ((a + b)^2/(4*t))*10**40\n31415926535897932384626433832795028841971\n\n>>> let qf (p, q) = ((p + sqrt (p^2 - 4*q))/2, (p - sqrt (p^2 - 4*q))/2 :: Construct)\n>>> let [(v, w), (x, _), (y, _), (z, _)] = map qf [(-1, -4), (v, -1), (w, -1), (x, y)]\n>>> z/2\n-1/16 + 1/16*sqrt 17 + 1/8*sqrt (17/2 - 1/2*sqrt 17) + 1/4*sqrt (17/4 + 3/4*sqrt 17 - (3/4 + 1/4*sqrt 17)*sqrt (17/2 - 1/2*sqrt 17))\n\nConstructible complex numbers may be built from constructible reals\nusing 'Complex' from the complex-generic library.\n\n>>> (z/2 :+ sqrt (1 - (z/2)^2))^17\n1 :+ 0\n-}\n\nmodule Data.Real.Constructible (\n  Construct,\n  deconstruct,\n  fromConstruct,\n  ConstructException (..)) where\n\nimport Control.Applicative ((<$>), (<*>), (<|>), empty)\nimport Control.Exception (Exception, ArithException (..), throw)\nimport Data.Complex.Generic (Complex (..))\nimport Data.Complex.Generic.TH (deriveComplexF)\nimport Data.Ratio ((%), numerator, denominator)\nimport Data.Typeable (Typeable)\nimport Math.NumberTheory.Roots (exactSquareRoot)\nimport Numeric.Search.Integer (search)\nimport Text.Read (Lexeme (..), Read (..), lexP, parens, prec, readListPrecDefault, step)\nimport Text.Read.Lex (numberToInteger)\n\ndata FieldShape = QShape | SqrtShape !FieldShape deriving Show\n\ndata Field k where\n  Q :: Field 'QShape\n  Sqrt :: !(Field k) -> !(Elt k) -> Field ('SqrtShape k)\n\ninstance Show (Field k) where\n  showsPrec _ Q = showString \"Q\"\n  showsPrec d (Sqrt k r) =\n    showParen (d > 9) $ showsPrec 9 k . showString \"[sqrt \" . showsPrecK k 10 r . showString \"]\"\n\ntype family Elt (k :: FieldShape)\ntype instance Elt 'QShape = Rational\ndata SqrtElt k = SqrtZero | SqrtElt !(Elt k) !(Elt k)\ntype instance Elt ('SqrtShape k) = SqrtElt k\n\nsqrtElt :: Field k -> Elt k -> Elt k -> SqrtElt k\nsqrtElt k a b | isZeroK k a && isZeroK k b = SqrtZero\n              | otherwise = SqrtElt a b\n\nsqrtLift :: Field k -> Elt k -> SqrtElt k\nsqrtLift k a = sqrtElt k a (zeroK k)\n\naddK :: Field k -> Elt k -> Elt k -> Elt k\naddK Q a b = a + b\naddK Sqrt{} SqrtZero a = a\naddK Sqrt{} a SqrtZero = a\naddK (Sqrt k _) (SqrtElt a b) (SqrtElt c d) = sqrtElt k (addK k a c) (addK k b d)\n\nmulK :: Field k -> Elt k -> Elt k -> Elt k\nmulK Q a b = a * b\nmulK Sqrt{} SqrtZero _ = SqrtZero\nmulK Sqrt{} _ SqrtZero = SqrtZero\nmulK (Sqrt k r) (SqrtElt a b) (SqrtElt c d) =\n  SqrtElt (addK k (mulK k a c) (mulK k r (mulK k b d))) (addK k (mulK k a d) (mulK k b c))\n\nsqK :: Field k -> Elt k -> Elt k\nsqK Q a = a*a\nsqK Sqrt{} SqrtZero = SqrtZero\nsqK (Sqrt k r) (SqrtElt a b) =\n  let c = mulK k a b\n  in SqrtElt (addK k (sqK k a) (mulK k r (sqK k b))) (addK k c c)\n\nsubK :: Field k -> Elt k -> Elt k -> Elt k\nsubK Q a b = a - b\nsubK k@Sqrt{} SqrtZero a = negateK k a\nsubK Sqrt{} a SqrtZero = a\nsubK (Sqrt k _) (SqrtElt a b) (SqrtElt c d) = sqrtElt k (subK k a c) (subK k b d)\n\nnegateK :: Field k -> Elt k -> Elt k\nnegateK Q a = negate a\nnegateK Sqrt{} SqrtZero = SqrtZero\nnegateK (Sqrt k _) (SqrtElt a b) = SqrtElt (negateK k a) (negateK k b)\n\nabsK :: Field k -> Elt k -> Elt k\nabsK Q a = abs a\nabsK k a = if sgnK k a == LT then negateK k a else a\n\nsignumK :: Field k -> Elt k -> Rational\nsignumK Q a = signum a\nsignumK k a = case sgnK k a of LT -> -1; EQ -> 0; GT -> 1\n\ndivK :: Field k -> Elt k -> Elt k -> Elt k\ndivK Q a b = a / b\ndivK k a b = mulK k a (recipK k b)\n\nrecipK :: Field k -> Elt k -> Elt k\nrecipK Q a = recip a\nrecipK Sqrt{} SqrtZero = throw DivideByZero\nrecipK (Sqrt k r) (SqrtElt a b) =\n  let c = recipK k (subK k (sqK k a) (mulK k r (sqK k b)))\n  in SqrtElt (mulK k a c) (mulK k (negateK k b) c)\n\neqK :: Field k -> Elt k -> Elt k -> Bool\neqK Q a b = a == b\neqK Sqrt{} SqrtZero SqrtZero = True\neqK (Sqrt k _) (SqrtElt a b) (SqrtElt c d) = eqK k a c && eqK k b d\neqK Sqrt{} SqrtZero SqrtElt{} = False\neqK Sqrt{} SqrtElt{} SqrtZero = False\n\nisZeroK :: Field k -> Elt k -> Bool\nisZeroK Q a = a == 0\nisZeroK Sqrt{} SqrtZero = True\nisZeroK Sqrt{} SqrtElt{} = False\n\ncompareK :: Field k -> Elt k -> Elt k -> Ordering\ncompareK Q a b = compare a b\ncompareK k a b = sgnK k (subK k a b)\n\nsgnK :: Field k -> Elt k -> Ordering\nsgnK Q a = compare a 0\nsgnK Sqrt{} SqrtZero = EQ\nsgnK (Sqrt k r) (SqrtElt a b) = case (sgnK k a, sgnK k b) of\n  (o, EQ) -> o\n  (EQ, o) -> o\n  (GT, GT) -> GT\n  (LT, LT) -> LT\n  (GT, LT) -> sgnK k (subK k (sqK k a) (mulK k r (sqK k b)))\n  (LT, GT) -> sgnK k (subK k (mulK k r (sqK k b)) (sqK k a))\n\nzeroK :: Field k -> Elt k\nzeroK Q = 0\nzeroK Sqrt{} = SqrtZero\n\nfromRationalK :: Field k -> Rational -> Elt k\nfromRationalK Q a = a\nfromRationalK (Sqrt k _) a = sqrtLift k (fromRationalK k a)\n\nsqrtK :: Field k -> Elt k -> Maybe (Elt k)\nsqrtK Q a = (%) <$> exactSquareRoot (numerator a) <*> exactSquareRoot (denominator a)\nsqrtK Sqrt{} SqrtZero = return SqrtZero\nsqrtK (Sqrt k r) (SqrtElt a b)\n  | isZeroK k b = sqrtLift k <$> sqrtK k a <|> SqrtElt (zeroK k) <$> sqrtK k (divK k a r)\n  | otherwise = do\n    n <- sqrtK k $ subK k (sqK k a) (mulK k r (sqK k b))\n    let half = fromRationalK k (1 % 2)\n        p = mulK k half (addK k a n)\n        q = mulK k half b\n        y1 = do\n          c <- sqrtK k p\n          return (SqrtElt c (divK k q c))\n        y2 = do\n          d <- sqrtK k $ divK k p r\n          return (SqrtElt (divK k q d) d)\n    y1 <|> y2\n\nnegateS, sqrtS :: (Int -> ShowS) -> Int -> ShowS\n(-!), (+!), (*!), (/!) :: (Int -> ShowS) -> (Int -> ShowS) -> Int -> ShowS\ninfixl 6 +!, -!\ninfixl 7 *!, /!\nnegateS s d = showParen (d > 6) $ showChar '-' . s 7\n(+!) s1 s2 d = showParen (d > 6) $ s1 6 . showString \" + \" . s2 7\n(-!) s1 s2 d = showParen (d > 6) $ s1 6 . showString \" - \" . s2 7\n(*!) s1 s2 d = showParen (d > 7) $ s1 7 . showChar '*' . s2 8\n(/!) s1 s2 d = showParen (d > 7) $ s1 7 . showChar '/' . s2 8\nsqrtS s d = showParen (d > 9) $ showString \"sqrt \" . s 10\n\nmulSqrtS :: Field k -> Elt k -> Elt k -> Int -> ShowS\nmulSqrtS k b r\n  | eqK k b (fromRationalK k 1) = sqrtS (flip (showsPrecK k) r)\n  | otherwise = flip (showsPrecK k) b *! sqrtS (flip (showsPrecK k) r)\n\nshowsPrecK :: Field k -> Int -> Elt k -> ShowS\nshowsPrecK Q d x\n  | q == 1 = showsPrec d p\n  | p < 0 = negateS (flip showsPrec (-p) /! flip showsPrec q) d\n  | otherwise = (flip showsPrec p /! flip showsPrec q) d\n  where\n    p = numerator x\n    q = denominator x\nshowsPrecK Sqrt{} _ SqrtZero = showChar '0'\nshowsPrecK (Sqrt k r) d (SqrtElt a b) = case sgnK k b of\n  EQ -> showsPrecK k d a\n  GT | isZeroK k a -> mulSqrtS k b r d\n     | otherwise -> (flip (showsPrecK k) a +! mulSqrtS k b r) d\n  LT | isZeroK k a -> negateS (mulSqrtS k (negateK k b) r) d\n     | otherwise -> (flip (showsPrecK k) a -! mulSqrtS k (negateK k b) r) d\n\nfromRatioK :: Floating a => Field k -> Elt k -> Elt k -> a\nfromRatioK Q = \\a b -> fromRational (a/b)\nfromRatioK (Sqrt k r) = er where\n  e = fromRatioK k\n  s = sqrt (e r (fromRationalK k 1))\n  er SqrtZero _ = 0\n  er _ SqrtZero = throw DivideByZero\n  er (SqrtElt a0 b0) (SqrtElt a1 b1) = case (sgnK k a, sgnK k b) of\n    (_, EQ) -> e a n1\n    (EQ, _) -> e b n1*s\n    (GT, GT) -> x1\n    (LT, LT) -> x1\n    (GT, LT) -> x2\n    (LT, GT) -> x2\n    where\n      a = subK k (mulK k a0 a1) (mulK k r (mulK k b0 b1))\n      b = subK k (mulK k b0 a1) (mulK k a0 b1)\n      n0 = subK k (sqK k a0) (mulK k r (sqK k b0))\n      n1 = subK k (sqK k a1) (mulK k r (sqK k b1))\n      x1 = e a n1 + e b n1*s\n      x2 = recip $ e a n0 - e b n0*s\n\nfromConstructK :: Floating a => Field k -> Elt k -> a\nfromConstructK k a = fromRatioK k a (fromRationalK k 1)\n\n-- |The type of constructible real numbers.\ndata Construct where\n  C :: !(Field k) -> !(Elt k) -> Construct\n\ndeconstructK :: Field k -> Elt k -> Either Rational (Construct, Construct, Construct)\ndeconstructK Q a = Left a\ndeconstructK Sqrt{} SqrtZero = Left 0\ndeconstructK (Sqrt k r) (SqrtElt a b)\n  | isZeroK k b = deconstructK k a\n  | otherwise = Right (C k a, C k b, C k r)\n\n{- |\nDeconstruct a rational constructible number as a 'Rational', or an\nirrational constructible number as a triple @(a, b, r)@ of simpler\nconstructible numbers representing @a + b*sqrt r@ (with @b /= 0@ and\n@r > 0@).  Recursively calling 'deconstruct' on all triples will yield\na finite tree that terminates in 'Rational' leaves.\n\nNote that two irrational constructible numbers that compare as equal\nmay deconstruct in different ways.\n-}\ndeconstruct :: Construct -> Either Rational (Construct, Construct, Construct)\ndeconstruct (C k a) = deconstructK k a\n\ndata JoinK k1 k2 where\n  JoinK :: !(Field k) -> (Elt k1 -> Elt k) -> (Elt k2 -> Elt k) -> JoinK k1 k2\n\njoinK :: Field k1 -> Field k2 -> JoinK k1 k2\njoinK Q k = JoinK k (fromRationalK k) id\njoinK k Q = JoinK k id (fromRationalK k)\njoinK k1 (Sqrt k2 r) = case joinK k1 k2 of\n  JoinK k f1 f2 -> let r' = f2 r in case sqrtK k r' of\n    Nothing ->\n      let f2' SqrtZero = SqrtZero\n          f2' (SqrtElt a b) = SqrtElt (f2 a) (f2 b)\n      in JoinK (Sqrt k r') (sqrtLift k . f1) f2'\n    Just s ->\n      let f2' SqrtZero = zeroK k\n          f2' (SqrtElt a b) = addK k (f2 a) (mulK k (f2 b) s)\n      in JoinK k f1 f2'\n\ninstance Show Construct where\n  showsPrec d (C k a) = showsPrecK k d a\n\ninstance Read Construct where\n  readPrec =\n    parens $\n    pNum <|>\n    prec 6 (pNegate <|> (step readPrec >>= pAddSub)) <|>\n    prec 7 (step readPrec >>= pMulDiv) <|>\n    prec 10 pSqrt\n    where\n      pNum = do {Number n <- lexP; maybe empty (return . fromInteger) (numberToInteger n)}\n      pNegate = do {Symbol \"-\" <- lexP; a <- negate <$> step readPrec; return a <|> pAddSub a}\n      pAddSub a = do {Symbol \"+\" <- lexP; b <- (a +) <$> step readPrec; return b <|> pAddSub b} <|>\n                  do {Symbol \"-\" <- lexP; b <- (a -) <$> step readPrec; return b <|> pAddSub b}\n      pMulDiv a = do {Symbol \"*\" <- lexP; b <- (a *) <$> step readPrec; return b <|> pMulDiv b} <|>\n                  do {Symbol \"/\" <- lexP; b <- (a /) <$> step readPrec; return b <|> pMulDiv b}\n      pSqrt = do {Ident \"sqrt\" <- lexP; a <- step readPrec; return (sqrt a)}\n  readListPrec = readListPrecDefault\n\ninstance Eq Construct where\n  C k1 a1 == C k2 a2 = case joinK k1 k2 of JoinK k f1 f2 -> eqK k (f1 a1) (f2 a2)\n\ninstance Ord Construct where\n  compare (C k1 a1) (C k2 a2) = case joinK k1 k2 of JoinK k f1 f2 -> compareK k (f1 a1) (f2 a2)\n\ninstance Num Construct where\n  C k1 a1 + C k2 a2 = case joinK k1 k2 of JoinK k f1 f2 -> C k (addK k (f1 a1) (f2 a2))\n  C k1 a1 * C k2 a2 = case joinK k1 k2 of JoinK k f1 f2 -> C k (mulK k (f1 a1) (f2 a2))\n  C k1 a1 - C k2 a2 = case joinK k1 k2 of JoinK k f1 f2 -> C k (subK k (f1 a1) (f2 a2))\n  negate (C k x) = C k (negateK k x)\n  abs (C k x) = C k (absK k x)\n  signum (C k x) = C Q (signumK k x)\n  fromInteger = C Q . fromInteger\n\ninstance Fractional Construct where\n  C k1 a1 / C k2 a2 = case joinK k1 k2 of JoinK k f1 f2 -> C k (divK k (f1 a1) (f2 a2))\n  recip (C k a) = C k (recipK k a)\n  fromRational = C Q\n\n-- |The type of exceptions thrown by impossible 'Construct' operations.\ndata ConstructException =\n  -- |'toRational' was given an irrational constructible number.\n  ConstructIrrational |\n  -- |'sqrt' was given a negative constructible number.\n  ConstructSqrtNegative |\n  -- |'**' was given an exponent that is not a dyadic rational, or a transcendental function was called.\n  Unconstructible String\n  deriving (Eq, Ord, Typeable)\n\ninstance Show ConstructException where\n  showsPrec _ ConstructIrrational = showString \"cannot convert irrational Construct to rational\"\n  showsPrec _ ConstructSqrtNegative = showString \"Construct sqrt: negative argument\"\n  showsPrec _ (Unconstructible s) = showString s . showString \" is not constructible\"\n\ninstance Exception ConstructException\n\n{- |\nThis partial 'Floating' instance only supports 'sqrt' and '**' where\nthe exponent is a dyadic rational.  Passing a negative number to\n'sqrt' will throw the 'ConstructSqrtNegative' exception.  All other\noperations will throw the 'Unconstructible' exception.\n-}\ninstance Floating Construct where\n  sqrt (C k a)\n    | sgnK k a == LT = throw ConstructSqrtNegative\n    | otherwise = case sqrtK k a of\n        Nothing -> C (Sqrt k a) (SqrtElt (zeroK k) (fromRationalK k 1))\n        Just b -> C k b\n  pi = throw (Unconstructible \"pi\")\n  exp = throw (Unconstructible \"exp\")\n  log = throw (Unconstructible \"log\")\n  a ** b = go (numerator b') (denominator b') where\n    b' = toRational b\n    go p q = let (n, p') = divMod p q in a^^n*go' p' q\n    go' 0 _ = 1\n    go' p q = case divMod q 2 of\n      (q', 0) -> sqrt (go p q')\n      _ -> throw (Unconstructible \"(** non-dyadic-rational)\")\n  logBase = throw (Unconstructible \"logBase\")\n  sin = throw (Unconstructible \"sin\")\n  tan = throw (Unconstructible \"tan\")\n  cos = throw (Unconstructible \"cos\")\n  asin = throw (Unconstructible \"asin\")\n  atan = throw (Unconstructible \"atan\")\n  acos = throw (Unconstructible \"acos\")\n  sinh = throw (Unconstructible \"sinh\")\n  tanh = throw (Unconstructible \"tanh\")\n  cosh = throw (Unconstructible \"cosh\")\n  asinh = throw (Unconstructible \"asinh\")\n  atanh = throw (Unconstructible \"atanh\")\n  acosh = throw (Unconstructible \"acosh\")\n\n{- |\nThis 'Real' instance only supports 'toRational' on numbers that are in\nfact rational.  'toRational' on an irrational number will throw the\n'ConstructIrrational' exception.\n-}\ninstance Real Construct where\n  toRational = either id (\\_ -> throw ConstructIrrational) . deconstruct\n\ninstance RealFrac Construct where\n  properFraction (C Q x) = (m, C Q y) where (m, y) = properFraction x\n  properFraction x = (fromInteger m, x - fromInteger m)\n    where m = search ((> x) . fromInteger) - 1\n\ninstance Enum Construct where\n  succ = (+ 1)\n  pred = subtract 1\n  toEnum = fromIntegral\n  fromEnum = fromInteger . truncate\n  enumFrom n = n `seq` (n : enumFrom (n + 1))\n  enumFromThen n m = n `seq` m `seq` (n : enumFromThen m (m + m - n))\n  enumFromTo n m = takeWhile (<= m) (enumFrom n)\n  enumFromThenTo e1 e2 e3 = takeWhile predicate (enumFromThen e1 e2) where\n    predicate | e2 >= e1 = (<= e3)\n              | otherwise = (>= e3)\n\nmk :: a -> a -> Complex a\nmk = (:+)\n\ntoPair :: Complex a -> (a, a)\ntoPair (x :+ y) = (x, y)\n\nderiveComplexF ''Complex ''Construct 'mk 'toPair\n\n{- |\nEvaluate a floating-point approximation for a constructible number.\n\nTo improve numerical stability, addition of numbers with different\nsigns is avoided using quadratic conjugation.\n\n>>> fromConstruct $ sum (map sqrt [7, 14, 39, 70, 72, 76, 85]) - sum (map sqrt [13, 16, 46, 55, 67, 73, 79])\n1.8837969820815017e-19\n-}\nfromConstruct :: Floating a => Construct -> a\nfromConstruct (C k a) = fromConstructK k a\n", "meta": {"hexsha": "e2069c49860ef48719641dafa0c4556a996f5755", "size": 15431, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Real/Constructible.hs", "max_stars_repo_name": "andersk/haskell-constructible", "max_stars_repo_head_hexsha": "46d760cbd2d21f955ec96c8fe2c13fdf3b2dd9d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-03-31T10:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-02T02:48:59.000Z", "max_issues_repo_path": "Data/Real/Constructible.hs", "max_issues_repo_name": "andersk/haskell-constructible", "max_issues_repo_head_hexsha": "46d760cbd2d21f955ec96c8fe2c13fdf3b2dd9d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-10-09T20:21:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-09T19:00:49.000Z", "max_forks_repo_path": "Data/Real/Constructible.hs", "max_forks_repo_name": "andersk/haskell-constructible", "max_forks_repo_head_hexsha": "46d760cbd2d21f955ec96c8fe2c13fdf3b2dd9d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-09T11:57:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T21:45:00.000Z", "avg_line_length": 36.3938679245, "max_line_length": 132, "alphanum_fraction": 0.6271790551, "num_tokens": 5706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.418217867692652}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Main where\n\nimport Foreign (Ptr, alloca, poke, peek, Storable)\nimport Foreign.C.Types (CInt(..), CDouble(..))\nimport Foreign.Ptr (Ptr)\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Devel\nimport System.IO.Unsafe (unsafePerformIO)\nimport Text.Printf (printf)\n\n\n--------------------------------------------------\n-- * 0) Simple.\n--\n-- Import straight from C's stdio (IE not any custom C file).\n\nforeign import ccall \"exp\" myExp :: Double -> Double\n\n\n--------------------------------------------------\n-- * 1) Hello.\n--\n-- Demonstrates IO from Fortran with no parameter passing.\n\nforeign import ccall \"hello_\" hello :: IO ()\n\n\n--------------------------------------------------\n-- * 2) FPow.\n--\n-- Demonstrates Fortran parameter passing.\n\n-- this is a pure function that wraps the Fortran function. The Fortran function\n-- expects pointers, and this C wrapper takes values, and handles passing on the\n-- references to the Fortran function.\nforeign import ccall \"fpow\" fpow :: Double -> Double -> Double\n\n-- This function is the unwrapped Fortran function, FFI'd into C, and it expects\n-- pointers, not values.\nforeign import ccall \"fpow_\" fpow_ :: Ptr Double -> Ptr Double -> IO Double\n\nfpowViaRefs :: Double -> Double -> IO Double\nfpowViaRefs b e =\n  alloca $ \\base -> -- get a pointer\n  alloca $ \\exponent -> do\n    poke base b -- set its value\n    poke exponent e\n    fpow_ base exponent -- note: pointers don't escape, just the final value\n\n\n--------------------------------------------------\n-- * 3) Transpose.\n--\n-- Demonstrates interfacing between C and HMatrix. C and HMatrix both use\n-- row-major arrays.\n\nforeign import ccall \"transpose\"\n  transpose_ :: Double ::> Double ::> IO CInt\n\ntranspose :: Matrix Double -> Matrix Double\ntranspose m = let\n  nrow = rows m\n  ncol = cols m\n  in unsafePerformIO $ do\n  -- allocate some memory for the output matrix\n  m' <- createMatrix RowMajor ncol nrow\n  -- apply function to memory locations\n  () <- (m #! m') transpose_ #| \"transpose_\"\n  pure m'\n\n\n--------------------------------------------------\n-- * 4) Mat * Scalar multiplication.\n--\n-- Demonstrates interfacing between Fortran and HMatrix. Fortran uses\n-- colum-major arrays, so, HMatrix can correct that with `fmat`.\n\nforeign import ccall \"scalarmul\"\n  scalarmul :: Double ::> (Double -> IO CInt)\n\nscalarMul :: Matrix Double -> Double -> Matrix Double\nscalarMul m x = unsafePerformIO $ do\n  let m' = fmat m -- copy array into Fortran's col-major ordering\n  () <- (m' #! x) scalarmul #| \"scalarMul\"\n  -- TODO: m' mutated. this is ugly, is there a better way?\n  pure  m'\n\n\n--------------------------------------------------\n-- * Main.\n\nmain :: IO ()\nmain = do\n  putStrLn \"0_simple: `exp` comes from C's stdio:\"\n  putStrLn $ printf \"myExp: e^3=%3.3f\" (myExp 3)\n\n  putStrLn \"\\n1_hello: Fortran can print to stdout on its own:\"\n  hello\n\n  putStrLn \"\\n2_fpow: Passing data into Fortran:\"\n  putStrLn $ printf \"pure fpow: %3.3f\" (fpow 2 12)\n\n  putStrLn \"\\n2_fpow: Passing pointers into Fortran:\"\n  putStrLn . printf \"impure fpow: %3.3f\" =<< fpowViaRefs 2 13\n\n  putStrLn \"\\n3_transpose: Connecting C and HMatrix:\"\n  let m = (10><10) [0 :: Double ..]\n      -- testing slices to make the problem more interesting, since HMatrix may\n      -- still retain the larger array, but records the dimensions of the sliced\n      -- array separately.\n      sliceM = subMatrix (3, 3) (5, 7) m\n  print sliceM\n  print $ transpose sliceM\n\n  putStrLn \"\\n4_scalarmul: Connecting Fortran and HMatrix:\"\n  let m2 = (10><10) [0 :: Double ..]\n      sliceM2 = subMatrix (3, 3) (5, 7) m2\n  print $ scalarMul sliceM2 1000\n\n\n--------------------------------------------------\n-- * HMatrix.Devel helpers\n\ninfixr 1 #\n(#) :: TransArray c => c -> (b -> IO r) -> Trans c b -> IO r\na # b = apply a b\n{-# INLINE (#) #-}\n\n-- | Apply vectors and matrices to a c function\n--\n-- Usage Ex1:\n--   (param1 # param2 # param3 #! param4) c_function #| \"c_function\"\n(#!) :: (TransArray c, TransArray c1) => c1 -> c -> Trans c1 (Trans c (IO r)) -> IO r\na #! b = a # b # id\n{-# INLINE (#!) #-}\n\n-- This idea taken from the HMatrix library. TransArray instances, together with\n-- `apply`, will set multiple parameters to pass into C.\ninfixr 5 :>, ::>\n\n-- | Type for vector params passed to C\ntype (:>)  t r = CInt -- size of vector\n              -> Ptr t -- pointer to vector\n              -> r -- a continuation, allowing composition of params\n\n-- | Type for matrix params passed to C\ntype (::>) t r =  CInt -- slice height (nrows)\n               -> CInt -- slice width (ncols)\n               -> CInt -- matrix height\n               -> CInt -- matrix width\n               -> Ptr t -- array pointer\n               -> r -- a continuation, allowing composition of params\n\ninstance TransArray Double where\n  type TransRaw Double b = Double -> b\n  type Trans Double b = Double -> b\n  apply x f g = f (g x)\n  applyRaw x f g = f (g x)\n\ninstance TransArray Int where\n  type TransRaw Int b = Int -> b\n  type Trans Int b = Int -> b\n  apply x f g = f (g x)\n  applyRaw x f g = f (g x)\n", "meta": {"hexsha": "db39454e852e43d28b0ca6bb95738ecf5404f84b", "size": 5178, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "freckletonj/haskell-fortran", "max_stars_repo_head_hexsha": "1c4e07c2e6788a14899ccb40fbcf89fc72c8990c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-08T15:55:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T20:00:17.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "freckletonj/haskell-fortran", "max_issues_repo_head_hexsha": "1c4e07c2e6788a14899ccb40fbcf89fc72c8990c", "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/Main.hs", "max_forks_repo_name": "freckletonj/haskell-fortran", "max_forks_repo_head_hexsha": "1c4e07c2e6788a14899ccb40fbcf89fc72c8990c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4588235294, "max_line_length": 85, "alphanum_fraction": 0.6089223638, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.41814990342591263}}
{"text": "{-# LANGUAGE BangPatterns #-}\nmodule NLP.Albemarle.GloVe (\n  ContextVector,\n  TrainingApproach,\n  adagrad,\n  deemph,\n  gradient,\n  randomModel,\n  train\n) where\nimport Numeric.LinearAlgebra (Matrix, Vector, dot)\nimport qualified Data.Vector.Storable as SVec\nimport qualified Numeric.LinearAlgebra as HMatrix\nimport qualified Numeric.LinearAlgebra.Data as HMatrix\nimport qualified Data.IntMap as IntMap\nimport Lens.Micro\nimport Lens.Micro.TH\n\n-- Constants: these are known probably not worth parameterizing because their\n-- current settings seem to work the best in all situations.\ndeemph_alpha = 0.75 -- Cooccurance frequencies are raised to this power\ndeemph_cap = 100 -- Cooccurance frequencies are clamped to [1..deemph_cap]\nlearning_rate = 0.05 -- Adagrad learning rate: it's not super sensitive\n\n-- | One input or output context vector, as well as the sum of squared gradients\n--   for each dimension, as needed for adagrad\ndata ContextVector = ContextVector {\n  _bias :: !Double, -- ^ Bias associated with the vector\n  _embedding :: !Vector Double, -- ^ The input or output vector\n  _biasHist :: !Double, -- ^ The bias's SSE (calling it history) - for adagrad\n  _embeddingHist :: !Vector Double -- ^ All other SSE's - for adagrad\n}\n-- | A function computing a training step. This is merely a synonym for clarity.\ntype TrainingApproach = ContextVector -> ContextVector -> Double\n  -> (ContextVector, ContextVector)\nmakeLenses ''ContextVector\n\n-- | Measure the gradient of error between two vectors. It's used as part of a\n--   numerical optimization. (e.g. Adagrad)\ngradient :: ContextVector -- ^ The source context vector\n  -> ContextVector -- ^ The target context vector\n  -> Double -- ^ Cooccurance count of the two vectors\n  -> Double -- ^ The gradient of error between vectors\ngradient source target edgefrequency = let\n  commonness = dot (source^.embedding) (target^.embedding) -- context vector\n  logfreq_error = (source^.bias) * (target^.bias) - log edgefrequency -- bias\n  in commonness + logfreq_error -- both sources\n\n-- | Deemphasize high frequencies, to avoid overweighting stopwords\ndeemph :: Double -> Double\ndeemph f = min 1 ((f/deemph_cap) ** deemph_alpha)\n\n-- | An adaptation of Adagrad to GloVe. The difference from a typical optimizer\n--   is that it is intended to operate on large streaming sources of vector\n--   pairs.\nadagrad :: ContextVector -- ^ Source vector\n  -> ContextVector -- ^ Target vector\n  -> Double -- ^ Cooccurance frequency\n  -> (ContextVector, ContextVector) -- ^ Modified source and target vectors\nadagrad source target edgefrequency history = let\n  grad = learning_rate * gradient source target edgefrequency\n  source_grad = grad * (source^.embedding)\n  target_grad = grad * (target^.embedding)\n  repair s t sgrad tgrad = ContextVector {\n    _embedding = (s^.embedding) - (tgrad / sqrt (s^.embeddingHist))\n    _bias = (s^.bias) - (grad / sqrt (s^.biasHist))\n    _embeddingHist = (s^.embeddingHist) + (sgrad * sgrad)\n    _biasHist = (s^.biasHist) + (grad * grad)\n  }\n  in (repair source target source_grad target_grad,\n      repair target source target_grad source_grad)\n\n-- | Train a model using a specific training approach, an existing model, and\n--   some training cooccurances.\ntrain :: IntMap ContextVector -- ^ The initial parameters\n  -> TrainingApproach -- ^ The approach to training (like adagrad)\n  -> [(Int, Int, Double)] -- ^ (Probably lazy) list of cooccurances\n  -> IntMap ContextVector -- ^ Trained model\ntrain trainer params [] = params\ntrain trainer !params (s,t,v):insts = let\n  get = (IntMap.!)\n  (reps, rept) = trainer (get s) (get t) v\n  in train trainer (IntMap.insert s reps $ IntMap.insert t rept params) insts\n\n-- | Make a model out of random vectors (for bootstrapping)\nrandomModel :: Int -- | Number of words\n  -> Int -- | Vector length\n  -> IO (IntMap ContextVector) -- | Resulting map\nrandomModel height width = do\n  mat <- HMatrix.rand height width\n  return $! IntMap.fromList $ zip [0..] $ HMatrix.toRows mat\n", "meta": {"hexsha": "9d6888a01b25090c7430d2a54554d0fafef18ba3", "size": 3987, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NLP/Albemarle/GloVe.hs", "max_stars_repo_name": "SeanTater/albemarle", "max_stars_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-07-16T15:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-19T00:51:45.000Z", "max_issues_repo_path": "src/NLP/Albemarle/GloVe.hs", "max_issues_repo_name": "SeanTater/albemarle", "max_issues_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-04T14:04:54.000Z", "max_forks_repo_path": "src/NLP/Albemarle/GloVe.hs", "max_forks_repo_name": "SeanTater/albemarle", "max_forks_repo_head_hexsha": "dc5eecbb4b25f3d0f8f3b2f82625b0b0a18199d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3369565217, "max_line_length": 80, "alphanum_fraction": 0.7258590419, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4178990665838733}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\nmodule Turtle2 (main) where\nimport Prelude hiding (dropWhile)\nimport Control.Applicative\nimport Control.Arrow\nimport Data.Complex\nimport AngleNum\nimport Ros.Node\nimport Ros.Topic (repeatM, force, dropWhile, metamorphM, yieldM)\nimport Ros.TopicUtil (everyNew, interruptible)\nimport Ros.Turtlesim.Pose\nimport Ros.Turtlesim.Velocity\nimport Ros.Logging\nimport System.IO (hFlush, stdout)\n\n-- A type synonym for a 2D point.\ntype Point = Complex Float\n\n-- A Topic of user-supplied waypoint trajectories.\ngetTraj :: Topic IO [Point]\ngetTraj = repeatM (do putStr \"Enter waypoints: \" >> hFlush stdout\n                      $(logInfo \"Waiting for new traj\")\n                      map (uncurry (:+)) . read <$> getLine)\n\n-- Produce a new goal 'Point' every time a goal is reached.\ndestinations :: (Functor m, Monad m) => \n                Topic m Point -> Topic m Pose -> Topic m Point\ndestinations goals poses = metamorphM (start (p2v <$> poses)) goals\n  where start t g = yieldM g (go g t)\n        go g t g' = force (dropWhile (keepGoing g) t) >>= yieldM g' . go g'\n        keepGoing goal pose = magnitude (goal - pose) > 1.5\n        p2v (Pose x y _ _ _) = x :+ y\n\n-- Compute linear distance to goal and bearing to goal\ntoGoal :: (Pose,Point) -> (Float, Angle Float)\ntoGoal (pos,goal) = (magnitude v, angle $ phase v)\n  where v = goal - (x pos :+ y pos)\n\n-- Steer based on a current pose estimate and distance from goal\nsteering :: Pose -> (Float, Angle Float) -> Velocity\nsteering pos (dpos, thetaDesired) = Velocity (min 2 dpos) angVel\n  where thetaErr = toDegrees $ thetaDesired - angle (theta pos)\n        angVel = signum thetaErr * min 2 (abs thetaErr)\n\nnavigate :: (Pose, Point) -> Velocity\nnavigate = uncurry ($) . (steering . fst &&& toGoal)\n\nmain = runNode \"HaskellBTurtle\" $\n       do enableLogging (Just Warn)\n          poses <- subscribe \"/turtle1/pose\"\n          let goals = destinations (interruptible getTraj) poses\n          advertise \"/turtle1/command_velocity\" \n                    (navigate <$> everyNew poses goals)\n", "meta": {"hexsha": "4610a1262355665e50935ffb2e4f036299688c7d", "size": 2058, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Examples/Turtle/src/Turtle2.hs", "max_stars_repo_name": "rgleichman/roshask", "max_stars_repo_head_hexsha": "65c20fe8fdab58bc44af7510c01b6085ae69192a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/Turtle/src/Turtle2.hs", "max_issues_repo_name": "rgleichman/roshask", "max_issues_repo_head_hexsha": "65c20fe8fdab58bc44af7510c01b6085ae69192a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/Turtle/src/Turtle2.hs", "max_forks_repo_name": "rgleichman/roshask", "max_forks_repo_head_hexsha": "65c20fe8fdab58bc44af7510c01b6085ae69192a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1111111111, "max_line_length": 75, "alphanum_fraction": 0.667638484, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4177915842563189}}
{"text": "{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n-- |\n-- Module     : Numeric.BLAS\n-- Copyright  : Copyright (c) 2012 Aleksey Khudyakov <alexey.skladnoy@gmail.com>\n-- License    : BSD3\n-- Maintainer : Aleksey Khudyakov <alexey.skladnoy@gmail.com>\n-- Stability  : experimental\n--\n-- BLAS operations for immutable vectors and matrices. Current\n-- implementation tries hard to evaluate expression built using\n-- functions from this module with minimal number of BLAS calls.\nmodule Numeric.BLAS (\n    -- * Type class based API\n    LinSpace(..)\n  , Mul(..)\n  , trans\n  , conj\n    -- * Vector operations\n  , dotProduct\n  , hermitianProd\n  , vectorNorm\n  , absSum\n  , absIndex\n  ) where\n\nimport Control.Monad.ST\n\n-- import Data.Complex\nimport Data.Vector.Generic (Mutable)\n\nimport Numeric.BLAS.Bindings (BLAS1,BLAS2,BLAS3,RealType,\n                              Trans(..))\nimport Numeric.BLAS.Expression\n\n-- Vector type classes\nimport           Data.Vector.Generic         (Vector)\nimport qualified Data.Vector.Generic         as G\n-- Matrix type classes\nimport           Data.Matrix.Generic           (Transposed(..),Conjugated(..))\nimport qualified Data.Matrix.Generic         as Mat\n-- Concrete vectors\nimport qualified Data.Vector.Storable         as S\nimport qualified Data.Vector.Storable.Strided as V\n-- Concrete matrices\nimport           Data.Matrix.Dense     (Matrix)\nimport           Data.Matrix.Symmetric\n  (SymmetricRaw,IsSymmetric,IsHermitian,Conjugate(..),NumberType,IsReal)\n\nimport qualified Numeric.BLAS.Mutable as M\n\nimport Numeric.BLAS.Mutable (MVectorBLAS)\n\n\n\n----------------------------------------------------------------\n-- Type class for addition and multiplication\n----------------------------------------------------------------\n\n-- | Addition and multiplication by scalar for vectors and matrices.\nclass LinSpace m a where\n  (.+.) :: m a -> m a -> m a\n  (.-.) :: m a -> m a -> m a\n  ( *.) ::   a -> m a -> m a\n\ninstance (LinSpaceM (Mutable m) a, Freeze m a, Num a) => LinSpace m a where\n   x .+. y = eval $ Add () (Lit x) (Lit y)\n   {-# INLINE (.+.) #-}\n   x .-. y = eval $ Sub () (Lit x) (Lit y)\n   {-# INLINE (.-.) #-}\n   \u03b1  *. x = eval $ Scale () \u03b1 (Lit x)\n   {-# INLINE (*.) #-}\n\n-- | Very overloaded operator for matrix and vector multiplication.\nclass Mul v u where\n  -- | Result of multiplication,\n  type MulRes v u :: *\n  (.*.) :: v -> u -> MulRes v u\n\n-- | Transpose vector or matrix.\ntrans :: mat a -> Transposed mat a\n{-# INLINE trans #-}\ntrans = Transposed\n\n-- | Conjugate transpose vector or matrix.\nconj :: mat a -> Conjugated mat a\n{-# INLINE conj #-}\nconj  = Conjugated\n\ninfixl 6 .+.\ninfixl 7 .*., *.\n\n\n\n----------------------------------------------------------------\n-- BLAS 1\n----------------------------------------------------------------\n\n-- | Scalar product of vectors\ndotProduct :: (BLAS1 a, Vector v a, MVectorBLAS (Mutable v))\n           => v a -> v a -> a\n{-# INLINE dotProduct #-}\ndotProduct v u = runST $ do\n  mv <- G.unsafeThaw v\n  mu <- G.unsafeThaw u\n  M.dotProduct mv mu\n\n\n-- | Hermitian product of vectors. For real-valued vectors is same\n--   as 'dotProduct'.\nhermitianProd :: (BLAS1 a, Vector v a, MVectorBLAS (Mutable v))\n              => v a -> v a -> a\n{-# INLINE hermitianProd #-}\nhermitianProd v u = runST $ do\n  mv <- G.unsafeThaw v\n  mu <- G.unsafeThaw u\n  M.hermitianProd mv mu\n\n\n-- | Euclidean norm of vector\nvectorNorm :: (BLAS1 a, Vector v a, MVectorBLAS (Mutable v))\n           => v a -> RealType a\n{-# INLINE vectorNorm #-}\nvectorNorm v\n  = runST $ M.vectorNorm =<< G.unsafeThaw v\n\n\n-- | Sum of absolute values of vector\nabsSum :: (BLAS1 a, Vector v a, MVectorBLAS (Mutable v))\n       => v a -> RealType a\n{-# INLINE absSum #-}\nabsSum v\n  = runST $ M.absSum =<< G.unsafeThaw v\n\n\n-- | Index of element with maximal absolute value\nabsIndex :: (BLAS1 a, Vector v a, MVectorBLAS (Mutable v))\n         => v a -> Int\n{-# INLINE absIndex #-}\nabsIndex v\n  = runST $ M.absIndex =<< G.unsafeThaw v\n\n\n\n\n----------------------------------------------------------------\n-- Dot product\n----------------------------------------------------------------\n\ninstance (BLAS1 a, a ~ a') => Mul (Transposed S.Vector a) (S.Vector a') where\n  type MulRes (Transposed S.Vector a )\n              (           S.Vector a')\n             = a\n  Transposed v .*. u = dotProduct v u\n  {-# INLINE (.*.) #-}\ninstance (BLAS1 a, a ~ a') => Mul (Transposed V.Vector a) (V.Vector a') where\n  type MulRes (Transposed V.Vector a )\n              (           V.Vector a')\n             = a\n  Transposed v .*. u = dotProduct v u\n  {-# INLINE (.*.) #-}\n\n\n\n----------------------------------------------------------------\n--  Vector x Vector => Matrix\n----------------------------------------------------------------\n\ninstance (BLAS2 a, a ~ a') => Mul (S.Vector a) (Transposed S.Vector a') where\n  type MulRes (           S.Vector a )\n              (Transposed S.Vector a')\n             = Matrix a\n  v .*. Transposed u = eval $ VecT () (Lit v) (Lit u)\n  {-# INLINE (.*.) #-}\ninstance (BLAS2 a, a ~ a') => Mul (S.Vector a) (Conjugated S.Vector a') where\n  type MulRes (           S.Vector a )\n              (Conjugated S.Vector a')\n             = Matrix a\n  v .*. Conjugated u = eval $ VecH () (Lit v) (Lit u)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS2 a, a ~ a') => Mul (V.Vector a) (Transposed V.Vector a') where\n  type MulRes (           V.Vector a )\n              (Transposed V.Vector a')\n             = Matrix a\n  v .*. Transposed u = eval $ VecT () (Lit v) (Lit u)\n  {-# INLINE (.*.) #-}\ninstance (BLAS2 a, a ~ a') => Mul (V.Vector a) (Conjugated V.Vector a') where\n  type MulRes (           V.Vector a )\n              (Conjugated V.Vector a')\n             = Matrix a\n  v .*. Conjugated u = eval $ VecH () (Lit v) (Lit u)\n  {-# INLINE (.*.) #-}\n\n\n\n\n----------------------------------------------------------------\n-- Dense matrix x Vector\n----------------------------------------------------------------\n\n-- Strided\ninstance (BLAS2 a, a ~ a') => Mul (Matrix a) (V.Vector a') where\n  type MulRes (Matrix   a )\n              (V.Vector a')\n             = V.Vector a\n  m .*. v = eval $ MulMV () (Lit m) (Lit v)\n  {-# INLINE (.*.) #-}\ninstance (BLAS2 a, a ~ a') => Mul (Transposed Matrix a) (V.Vector a') where\n  type MulRes (Transposed Matrix a)\n              (V.Vector a')\n             = V.Vector a\n  Transposed m .*. v = eval $ MulTMV () Trans (Lit m) (Lit v)\n  {-# INLINE (.*.) #-}\ninstance (BLAS2 a, a ~ a') => Mul (Conjugated Matrix a) (V.Vector a') where\n  type MulRes (Conjugated Matrix a)\n              (V.Vector a')\n             = V.Vector a\n  Conjugated m .*. v = eval $ MulTMV () ConjTrans (Lit m) (Lit v)\n  {-# INLINE (.*.) #-}\n\n-- Storable\ninstance (BLAS2 a, a ~ a') => Mul (Matrix a) (S.Vector a') where\n  type MulRes (Matrix   a )\n              (S.Vector a')\n             = S.Vector a\n  m .*. v = eval $ MulMV () (Lit m) (Lit v)\n  {-# INLINE (.*.) #-}\ninstance (BLAS2 a, a ~ a') => Mul (Transposed Matrix a) (S.Vector a') where\n  type MulRes (Transposed Matrix a)\n              (S.Vector a')\n             = S.Vector a\n  Transposed m .*. v = eval $ MulTMV () Trans (Lit m) (Lit v)\n  {-# INLINE (.*.) #-}\ninstance (BLAS2 a, a ~ a') => Mul (Conjugated Matrix a) (S.Vector a') where\n  type MulRes (Conjugated Matrix a)\n              (S.Vector a')\n             = S.Vector a\n  Conjugated m .*. v = eval $ MulTMV () ConjTrans (Lit m) (Lit v)\n  {-# INLINE (.*.) #-}\n\n\n\n----------------------------------------------------------------\n-- Symmetric matrix x Vector\n----------------------------------------------------------------\n\ninstance (BLAS2 a, Conjugate a, a ~ a') => Mul (SymmetricRaw IsHermitian a) (S.Vector a') where\n  type MulRes (SymmetricRaw IsHermitian a)\n              (S.Vector a')\n             = S.Vector a\n  m .*. v = eval $ MulMV () (Lit m) (Lit v)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS2 a, NumberType a ~ IsReal, a ~ a') => Mul (SymmetricRaw IsSymmetric a) (S.Vector a') where\n  type MulRes (SymmetricRaw IsSymmetric a)\n              (S.Vector a')\n             = S.Vector a\n  m .*. v = eval $ MulMV () (Lit m) (Lit v)\n  {-# INLINE (.*.) #-}\n\n\n\n----------------------------------------------------------------\n-- Matrix x Matrix for dense matrices\n----------------------------------------------------------------\n\ninstance (BLAS3 a, a ~ a') => Mul (Matrix a) (Matrix a') where\n  type MulRes (Matrix a )\n              (Matrix a')\n             = Matrix a\n  m .*. n = eval $ MulMM () NoTrans (Lit m) NoTrans (Lit n)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS3 a, a ~ a') => Mul (Matrix a) (Transposed Matrix a') where\n  type MulRes (           Matrix a )\n              (Transposed Matrix a')\n             = Matrix a\n  m .*. Transposed n = eval $ MulMM () NoTrans (Lit m) Trans (Lit n)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS3 a, a ~ a') => Mul (Matrix a) (Conjugated Matrix a') where\n  type MulRes (           Matrix a )\n              (Conjugated Matrix a')\n             = Matrix a\n  m .*. Conjugated n = eval $ MulMM () NoTrans (Lit m) ConjTrans (Lit n)\n  {-# INLINE (.*.) #-}\n\n\n\ninstance (BLAS3 a, a ~ a') => Mul (Transposed Matrix a) (Matrix a') where\n  type MulRes (Transposed Matrix a )\n              (           Matrix a')\n             = Matrix a\n  Transposed m .*. n = eval $ MulMM () Trans (Lit m) NoTrans (Lit n)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS3 a, a ~ a') => Mul (Transposed Matrix a) (Transposed Matrix a') where\n  type MulRes (Transposed Matrix a )\n              (Transposed Matrix a')\n             = Matrix a\n  Transposed m .*. Transposed n = eval $ MulMM () Trans (Lit m) Trans (Lit n)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS3 a, a ~ a') => Mul (Transposed Matrix a) (Conjugated Matrix a') where\n  type MulRes (Transposed Matrix a )\n              (Conjugated Matrix a')\n             = Matrix a\n  Transposed m .*. Conjugated n = eval $ MulMM () Trans (Lit m) ConjTrans (Lit n)\n  {-# INLINE (.*.) #-}\n\n\n\ninstance (BLAS3 a, a ~ a') => Mul (Conjugated Matrix a) (Matrix a') where\n  type MulRes (Conjugated Matrix a )\n              (           Matrix a')\n             = Matrix a\n  Conjugated m .*. n = eval $ MulMM () ConjTrans (Lit m) NoTrans (Lit n)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS3 a, a ~ a') => Mul (Conjugated Matrix a) (Transposed Matrix a') where\n  type MulRes (Conjugated Matrix a )\n              (Transposed Matrix a')\n             = Matrix a\n  Conjugated m .*. Transposed n = eval $ MulMM () ConjTrans (Lit m) Trans (Lit n)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS3 a, a ~ a') => Mul (Conjugated Matrix a) (Conjugated Matrix a') where\n  type MulRes (Conjugated Matrix a )\n              (Conjugated Matrix a')\n             = Matrix a\n  Conjugated m .*. Conjugated n = eval $ MulMM () ConjTrans (Lit m) ConjTrans (Lit n)\n  {-# INLINE (.*.) #-}\n\n\n\n\n----------------------------------------------------------------\n-- Symmetric matrix x Dense matrix\n----------------------------------------------------------------\n\ninstance (BLAS3 a, a ~ a') => Mul (Matrix a) (SymmetricRaw IsSymmetric a') where\n  type MulRes (Matrix a)\n              (SymmetricRaw IsSymmetric a')\n             = Matrix a\n  m .*. sym = eval $ MulSymMM () M.RightSide (Lit sym) (Lit m)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS3 a, a ~ a') => Mul (SymmetricRaw IsSymmetric a') (Matrix a) where\n  type MulRes (SymmetricRaw IsSymmetric a')\n              (Matrix a)\n             = Matrix a\n  sym .*. m = eval $ MulSymMM () M.LeftSide (Lit sym) (Lit m)\n  {-# INLINE (.*.) #-}\n\n\n\n----------------------------------------------------------------\n-- Symmetric matrix x Dense matrix\n----------------------------------------------------------------\n\ninstance (BLAS3 a, Conjugate a, a ~ a') => Mul (Matrix a) (SymmetricRaw IsHermitian a') where\n  type MulRes (Matrix a)\n              (SymmetricRaw IsHermitian a')\n             = Matrix a\n  m .*. sym = eval $ MulHerMM () M.RightSide (Lit sym) (Lit m)\n  {-# INLINE (.*.) #-}\n\ninstance (BLAS3 a, Conjugate a, a ~ a') => Mul (SymmetricRaw IsHermitian a') (Matrix a) where\n  type MulRes (SymmetricRaw IsHermitian a')\n              (Matrix a)\n             = Matrix a\n  sym .*. m = eval $ MulHerMM () M.LeftSide (Lit sym) (Lit m)\n  {-# INLINE (.*.) #-}\n", "meta": {"hexsha": "70bf1de2e340d474de24757ad9a0658898c02d68", "size": 12240, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/BLAS.hs", "max_stars_repo_name": "Shimuuar/blas-lapack", "max_stars_repo_head_hexsha": "1b1bd3d1a61c4068a295a92ca369bb807f5868fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-31T04:52:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T04:52:43.000Z", "max_issues_repo_path": "Numeric/BLAS.hs", "max_issues_repo_name": "Shimuuar/blas-lapack", "max_issues_repo_head_hexsha": "1b1bd3d1a61c4068a295a92ca369bb807f5868fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numeric/BLAS.hs", "max_forks_repo_name": "Shimuuar/blas-lapack", "max_forks_repo_head_hexsha": "1b1bd3d1a61c4068a295a92ca369bb807f5868fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.380952381, "max_line_length": 105, "alphanum_fraction": 0.5149509804, "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.41742570195593176}}
{"text": "{-# LANGUAGE DeriveGeneric #-}\n\n{-|\nModule      : ODMatrix.SmithDecomposition.SparseMat\nDescription : Sparse representation of a matrix.\n\n-}\nmodule ODMatrix.SmithDecomposition.SparseMat (\n      SparseMat(..)\n    , denseSparseMat\n    , sparseDenseMat\n    , fixIndexes\n    , makeAssoc\n  ) where\n\n    import GHC.Generics (Generic)\n    --import Data.Aeson (ToJSON, FromJSON)\n    \n    import Numeric.LinearAlgebra as L hiding (rows, cols)\n    import Numeric.LinearAlgebra.Data as LD (toList)\n\n    \n    -- | Sparse representation of a matrix.\n    data SparseMat = SparseMat {\n        rows :: Int\n      , cols :: Int\n      , cells :: AssocMatrix\n      } deriving (Generic, Show)\n\n    --instance ToJSON SparseMat\n    --instance FromJSON SparseMat\n\n    -- | Transform a sparse matrix in a regular one.\n    denseSparseMat :: SparseMat -> Matrix Double\n    denseSparseMat m = assoc (rows m, cols m) 0 (fixIndexes $ cells m)\n\n\n    -- | Transform a regular matrix to an sparse one.\n    sparseDenseMat :: Matrix Double-> SparseMat\n    sparseDenseMat m = SparseMat r c cs\n      where (r, c) = size m\n            vals = toList . flatten $ m\n            ids = [(i,j) | i <- [0..r-1], j <- [0..c-1]]\n            cs = filter (\\(_,v) -> v /= 0) $ zip ids vals\n\n\n    \n    -- * Support functions\n\n    -- | Adjust the indexes of the association matrix from 1-starting to 0-starting.\n    -- This is needed by the Linear Algebra library.\n    fixIndexes :: (Num a) => [((a,a),b)] -> [((a,a),b)]\n    fixIndexes = map (\\((a,b),v) -> ((a-1,b-1),v))\n\n    -- | Given a constant value and a list of indexes, construct a association matrix only containing that value.\n    makeAssoc :: Double -> [(Int,Int)] -> AssocMatrix\n    makeAssoc v = fixIndexes . map (flip (,) v)\n\n\n    --------------------------------------------------------------------------------\n    --------------------------------------------------------------------------------\n    --------------------------------------------------------------------------------\n\n    ", "meta": {"hexsha": "47b8b45d490faeb527906902fd84926e9565d0b5", "size": 1999, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ODMatrix/SmithDecomposition/SparseMat.hs", "max_stars_repo_name": "renecura/odmatrix", "max_stars_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ODMatrix/SmithDecomposition/SparseMat.hs", "max_issues_repo_name": "renecura/odmatrix", "max_issues_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ODMatrix/SmithDecomposition/SparseMat.hs", "max_forks_repo_name": "renecura/odmatrix", "max_forks_repo_head_hexsha": "6c4978dc4feb1d62d84f5cd813665a75f40df4c5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.234375, "max_line_length": 113, "alphanum_fraction": 0.5357678839, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.4172812848651976}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module    : Statistics.Types\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License   : BSD3\n--\n-- Maintainer  : bos@serpentine.com\n-- Stability   : experimental\n-- Portability : portable\n--\n-- Data types common used in statistics\nmodule Statistics.Types\n    ( -- * Confidence level\n      CL\n      -- ** Accessors\n    , confidenceLevel\n    , significanceLevel\n      -- ** Constructors\n    , mkCL\n      -- ** Constants and conversion to n\u03c3\n    , cl95\n      -- * Estimates and upper/lower limits\n    , Estimate(..)\n    -- , NormalErr(..)\n    , ConfInt(..)\n      -- ** Constructors\n    -- , estimateNormErr\n    , estimateFromInterval\n    , estimateFromErr\n      -- ** Accessors\n    , confidenceInterval\n    , Scale(..)\n      -- * Other\n    , Sample\n    ) where\n\nimport Control.DeepSeq              (NFData(..))\nimport Data.Data                    (Data,Typeable)\nimport Data.Maybe                   (fromMaybe)\nimport GHC.Generics                 (Generic)\n\n#if __GLASGOW_HASKELL__ == 704\nimport qualified Data.Vector.Generic\nimport qualified Data.Vector.Generic.Mutable\n#endif\n\nimport Statistics.Internal\nimport Statistics.Types.Internal\n\n\n----------------------------------------------------------------\n-- Data type for confidence level\n----------------------------------------------------------------\n\n-- |\n-- Confidence level. In context of confidence intervals it's\n-- probability of said interval covering true value of measured\n-- value. In context of statistical tests it's @1-\u03b1@ where \u03b1 is\n-- significance of test.\n--\n-- Since confidence level are usually close to 1 they are stored as\n-- @1-CL@ internally. There are two smart constructors for @CL@:\n-- 'mkCL' and 'mkCLFromSignificance' (and corresponding variant\n-- returning @Maybe@). First creates @CL@ from confidence level and\n-- second from @1 - CL@ or significance level.\n--\n-- >>> cl95\n-- mkCLFromSignificance 0.05\n--\n-- Prior to 0.14 confidence levels were passed to function as plain\n-- @Doubles@. Use 'mkCL' to convert them to @CL@.\nnewtype CL a = CL a\n               deriving (Eq, Typeable, Data, Generic)\n\ninstance Show a => Show (CL a) where\n  showsPrec n (CL p) = defaultShow1 \"mkCLFromSignificance\" p n\ninstance (Num a, Ord a, Read a) => Read (CL a) where\n  readPrec = defaultReadPrecM1 \"mkCLFromSignificance\" mkCLFromSignificanceE\n\ninstance NFData   a => NFData   (CL a) where\n  rnf (CL a) = rnf a\n\n-- |\n-- >>> cl95 > cl90\n-- True\ninstance Ord a => Ord (CL a) where\n  CL a <  CL b = a >  b\n  CL a <= CL b = a >= b\n  CL a >  CL b = a <  b\n  CL a >= CL b = a <= b\n  max (CL a) (CL b) = CL (min a b)\n  min (CL a) (CL b) = CL (max a b)\n\n\n-- | Create confidence level from probability \u03b2 or probability\n--   confidence interval contain true value of estimate. Will throw\n--   exception if parameter is out of [0,1] range\n--\n-- >>> mkCL 0.95    -- same as cl95\n-- mkCLFromSignificance 0.05\nmkCL :: (Ord a, Num a) => a -> CL a\nmkCL\n  = fromMaybe (error \"Statistics.Types.mkCL: probability is out if [0,1] range\")\n  . mkCLE\n\n-- | Same as 'mkCL' but returns @Nothing@ instead of error if\n--   parameter is out of [0,1] range\n--\n-- >>> mkCLE 0.95    -- same as cl95\n-- Just (mkCLFromSignificance 0.05)\nmkCLE :: (Ord a, Num a) => a -> Maybe (CL a)\nmkCLE p\n  | p >= 0 && p <= 1 = Just $ CL (1 - p)\n  | otherwise        = Nothing\n\n-- | Same as 'mkCLFromSignificance' but returns @Nothing@ instead of error if\n--   parameter is out of [0,1] range\n--\n-- >>> mkCLFromSignificanceE 0.05    -- same as cl95\n-- Just (mkCLFromSignificance 0.05)\nmkCLFromSignificanceE :: (Ord a, Num a) => a -> Maybe (CL a)\nmkCLFromSignificanceE p\n  | p >= 0 && p <= 1 = Just $ CL p\n  | otherwise        = Nothing\n\n-- | Get confidence level. This function is subject to rounding\n--   errors. If @1 - CL@ is needed use 'significanceLevel' instead\nconfidenceLevel :: (Num a) => CL a -> a\nconfidenceLevel (CL p) = 1 - p\n\n-- | Get significance level.\nsignificanceLevel :: CL a -> a\nsignificanceLevel (CL p) = p\n\n\n\n-- | 95% confidence level\ncl95 :: Fractional a => CL a\ncl95 = CL 0.05\n\n----------------------------------------------------------------\n-- Data type for p-value\n----------------------------------------------------------------\n\n-- | Newtype wrapper for p-value.\nnewtype PValue a = PValue a\n               deriving (Eq,Ord, Typeable, Data, Generic)\n\ninstance Show a => Show (PValue a) where\n  showsPrec n (PValue p) = defaultShow1 \"mkPValue\" p n\ninstance (Num a, Ord a, Read a) => Read (PValue a) where\n  readPrec = defaultReadPrecM1 \"mkPValue\" mkPValueE\n\ninstance NFData a => NFData (PValue a) where\n  rnf (PValue a) = rnf a\n\n\n-- | Construct PValue. Returns @Nothing@ if argument is out of [0,1] range.\nmkPValueE :: (Ord a, Num a) => a -> Maybe (PValue a)\nmkPValueE p\n  | p >= 0 && p <= 1 = Just $ PValue p\n  | otherwise        = Nothing\n\n----------------------------------------------------------------\n-- Point estimates\n----------------------------------------------------------------\n\n-- |\n-- A point estimate and its confidence interval. It's parametrized by\n-- both error type @e@ and value type @a@. This module provides two\n-- types of error: 'NormalErr' for normally distributed errors and\n-- 'ConfInt' for error with normal distribution. See their\n-- documentation for more details.\n--\n-- For example @144 \u00b1 5@ (assuming normality) could be expressed as\n--\n-- > Estimate { estPoint = 144\n-- >          , estError = NormalErr 5\n-- >          }\n--\n-- Or if we want to express @144 + 6 - 4@ at CL95 we could write:\n--\n-- > Estimate { estPoint = 144\n-- >          , estError = ConfInt\n-- >                       { confIntLDX = 4\n-- >                       , confIntUDX = 6\n-- >                       , confIntCL  = cl95\n-- >                       }\n--\n-- Prior to statistics 0.14 @Estimate@ data type used following definition:\n--\n-- > data Estimate = Estimate {\n-- >      estPoint           :: {-# UNPACK #-} !Double\n-- >    , estLowerBound      :: {-# UNPACK #-} !Double\n-- >    , estUpperBound      :: {-# UNPACK #-} !Double\n-- >    , estConfidenceLevel :: {-# UNPACK #-} !Double\n-- >    }\n--\n-- Now type @Estimate ConfInt Double@ should be used instead. Function\n-- 'estimateFromInterval' allow to easily construct estimate from same inputs.\ndata Estimate e a = Estimate\n    { estPoint           :: !a\n      -- ^ Point estimate.\n    , estError           :: !(e a)\n      -- ^ Confidence interval for estimate.\n    } deriving (Eq, Read, Show, Generic\n#if __GLASGOW_HASKELL__ >= 708\n               , Typeable, Data\n#endif\n               )\n\ninstance (NFData   (e a), NFData   a) => NFData   (Estimate e a) where\n    rnf (Estimate x dx) = rnf x `seq` rnf dx\n\n\n-- | Confidence interval. It assumes that confidence interval forms\n--   single interval and isn't set of disjoint intervals.\ndata ConfInt a = ConfInt\n  { confIntLDX :: !a\n    -- ^ Lower error estimate, or distance between point estimate and\n    --   lower bound of confidence interval.\n  , confIntUDX :: !a\n    -- ^ Upper error estimate, or distance between point estimate and\n    --   upper bound of confidence interval.\n  , confIntCL  :: !(CL Double)\n    -- ^ Confidence level corresponding to given confidence interval.\n  }\n  deriving (Read,Show,Eq,Typeable,Data,Generic)\n\ninstance NFData   a => NFData   (ConfInt a) where\n    rnf (ConfInt x y _) = rnf x `seq` rnf y\n\n\n\n----------------------------------------\n-- Constructors\n\n-- | Create estimate with asymmetric error.\nestimateFromErr\n  :: a                     -- ^ Central estimate\n  -> (a,a)                 -- ^ Lower and upper errors. Both should be\n                           --   positive but it's not checked.\n  -> CL Double             -- ^ Confidence level for interval\n  -> Estimate ConfInt a\nestimateFromErr x (ldx,udx) cl = Estimate x (ConfInt ldx udx cl)\n\n-- | Create estimate with asymmetric error.\nestimateFromInterval\n  :: Num a\n  => a                     -- ^ Point estimate. Should lie within\n                           --   interval but it's not checked.\n  -> (a,a)                 -- ^ Lower and upper bounds of interval\n  -> CL Double             -- ^ Confidence level for interval\n  -> Estimate ConfInt a\nestimateFromInterval x (lx,ux) cl\n  = Estimate x (ConfInt (x-lx) (ux-x) cl)\n\n\n----------------------------------------\n-- Accessors\n\n-- | Get confidence interval\nconfidenceInterval :: Num a => Estimate ConfInt a -> (a,a)\nconfidenceInterval (Estimate x (ConfInt ldx udx _))\n  = (x - ldx, x + udx)\n\n\n-- | Data types which could be multiplied by constant.\nclass Scale e where\n  scale :: (Ord a, Num a) => a -> e a -> e a\n\ninstance Scale ConfInt where\n  scale a (ConfInt l u cl) | a >= 0    = ConfInt  (a*l)  (a*u) cl\n                           | otherwise = ConfInt (-a*u) (-a*l) cl\n\ninstance Scale e => Scale (Estimate e) where\n  scale a (Estimate x dx) = Estimate (a*x) (scale a dx)\n\n", "meta": {"hexsha": "49f69d2308071e21453f6f932245878afbfd872d", "size": 8995, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "statistics/Statistics/Types.hs", "max_stars_repo_name": "runeksvendsen/hs-gauge", "max_stars_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 94, "max_stars_repo_stars_event_min_datetime": "2017-10-29T16:51:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T08:36:20.000Z", "max_issues_repo_path": "statistics/Statistics/Types.hs", "max_issues_repo_name": "runeksvendsen/hs-gauge", "max_issues_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 77, "max_issues_repo_issues_event_min_datetime": "2017-09-30T15:11:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T09:34:12.000Z", "max_forks_repo_path": "statistics/Statistics/Types.hs", "max_forks_repo_name": "runeksvendsen/hs-gauge", "max_forks_repo_head_hexsha": "496a8b99e7fee3039fd89ecef7305d31eb5d5a6d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-11-04T13:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T05:44:23.000Z", "avg_line_length": 31.6725352113, "max_line_length": 80, "alphanum_fraction": 0.5864369094, "num_tokens": 2425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.41728128026286126}}
{"text": "{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport           Numeric.LinearAlgebra\n\nimport           Grenade\nimport           Grenade.Layers.Internal.Convolution\nimport           Grenade.Layers.Internal.Pooling\n\nimport           Criterion.Main\n\nmain :: IO ()\nmain = do\n  putStrLn $ \"Benchmarking with type: \" ++ nameF\n  x :: S ('D2 60 60) <- randomOfShape\n  y :: S ('D3 60 60 1) <- randomOfShape\n  defaultMain\n    [ bgroup\n        \"im2col\"\n        [ bench \"im2col 28x28\"     $ whnf (im2col 5 5 1 1) ((28 >< 28) [1 ..])\n        , bench \"im2col 100x100\"   $ whnf (im2col 10 10 1 1) ((100 >< 100) [1 ..])\n        , bench \"im2col 3x416x416\" $ whnf (vid2col 3 3 1 1 416 416) (((3 * 416) >< 416) [1 ..])\n        ]\n    , bgroup\n        \"col2im\"\n        [ bench \"col2im 28x28\"     $ whnf (col2im 5 5 1 1 28 28) ((576 >< 25) [1 ..])\n        , bench \"col2im 100x100\"   $ whnf (col2im 10 10 1 1 100 100) ((8281 >< 100) [1 ..])\n        , bench \"col2im 3x416x416\" $ whnf (col2vid 1 1 1 1 414 414) (((414 * 414) >< 27) [1 ..])\n        ]\n    , bgroup\n        \"poolfw\"\n        [ bench \"poolforwards 3x4\" $ whnf (poolForward 1 3 4 2 2 1 1) ((3 >< 4) [1 ..])\n        , bench \"poolforwards 28x28\" $ whnf (poolForward 1 28 28 5 5 1 1) ((28 >< 28) [1 ..])\n        , bench \"poolforwards 100x100\" $ whnf (poolForward 1 100 100 10 10 1 1) ((100 >< 100) [1 ..])\n        ]\n    , bgroup\n        \"poolbw\"\n        [ bench \"poolbackwards 3x4\" $ whnf (poolBackward 1 3 4 2 2 1 1 ((3 >< 4) [1 ..])) ((2 >< 3) [1 ..])\n        , bench \"poolbackwards 28x28\" $ whnf (poolBackward 1 28 28 5 5 1 1 ((28 >< 28) [1 ..])) ((24 >< 24) [1 ..])\n        , bench \"poolbackwards 100x100\" $ whnf (poolBackward 1 100 100 10 10 1 1 ((100 >< 100) [1 ..])) ((91 >< 91) [1 ..])\n        ]\n    , bgroup\n        \"padcrop\"\n        [ bench \"pad 2D 60x60\" $ nf (testRun2D Pad) x\n        , bench \"pad 3D 60x60\" $ nf (testRun3D Pad) y\n        , bench \"crop 2D 60x60\" $ nf (testRun2D' Crop) x\n        , bench \"crop 3D 60x60\" $ nf (testRun3D' Crop) y\n        ]\n    ]\n  putStrLn $ \"Benchmarked with type: \" ++ nameF\n\ntestRun2D :: Pad 1 1 1 1 -> S ('D2 60 60) -> S ('D2 62 62)\ntestRun2D = snd ... runForwards\n\ntestRun3D :: Pad 1 1 1 1 -> S ('D3 60 60 1) -> S ('D3 62 62 1)\ntestRun3D = snd ... runForwards\n\ntestRun2D' :: Crop 1 1 1 1 -> S ('D2 60 60) -> S ('D2 58 58)\ntestRun2D' = snd ... runForwards\n\ntestRun3D' :: Crop 1 1 1 1 -> S ('D3 60 60 1) -> S ('D3 58 58 1)\ntestRun3D' = snd ... runForwards\n\n(...) :: (a -> b) -> (c -> d -> a) -> c -> d -> b\n(...) = (.) . (.)\n", "meta": {"hexsha": "a52be8344adbadb35681b055bceffce78d0b593e", "size": 2608, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/bench.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": "bench/bench.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": "bench/bench.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3529411765, "max_line_length": 123, "alphanum_fraction": 0.5157208589, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.41726591244061856}}
{"text": "{-# OPTIONS_GHC  -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}\n{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}\n\n\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n-- | \n-- | Module : First attempt at approximate counting\n-- | Creator: Xiao Ling\n-- | Created: 12/08/2015\n-- | TODO   : test standard deviation of alpha, beta, and final version\n-- |\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n\nmodule Morris (\n    morris\n  , morris'\n  , count\n  , count'\n  ) where\n\nimport Data.Random\nimport Data.Conduit\nimport Data.List.Split\nimport qualified Data.Conduit.List as Cl\nimport Control.Monad.Identity\nimport System.Environment\n\n\nimport Core\nimport Statistics\n\n\n{-----------------------------------------------------------------------------\n    I. Morris Algorithm list of counter\n------------------------------------------------------------------------------}\n\n-- * Count the number of items in `as` to within `eps` of actual\n-- * with confidence `delta`\nmorris :: Eps -> Delta -> [a] -> IO Counter\nmorris e d as = runRVar (goMorris e d as) StdRandom\n\ngoMorris :: Eps -> Delta -> [a] -> RVar Counter\ngoMorris e d as = medianOfMeans $ Cl.sourceList as $$ count $ cs\n  where cs = replicate (t*m) 0\n        t  = round $ 1/(e^2*d)  :: Int          \n        m  = round . log $ 1/d  \n        medianOfMeans = fmap median' . (fmap . fmap) mean' . fmap (chunksOf t) \n\n\ncount :: [Counter] -> Sink a RVar [Counter]\ncount cs = (\\c -> 2^(round c) - 1) `ffmap` Cl.foldM (\\cs _ -> traverse incr cs) cs\n  where ffmap = fmap . fmap\n\n\n{-----------------------------------------------------------------------------\n    II. Morris Algorithm list of list of counter\n------------------------------------------------------------------------------}\n\n-- * Count the number of items in `as` to within `eps` of actual\n-- * with confidence `delta`\nmorris' :: Eps -> Delta -> [a] -> IO Counter\nmorris' e d as = runRVar (goMorris' e d as) StdRandom\n\n-- * 160000\n-- * Run on stream inputs `as` for t independent trials for `t = 1/eps^2 * d`, \n-- * and `m` times in parallel, for `m = log(1/d)` and take the median\ngoMorris' :: Eps -> Delta -> [a] -> RVar Counter\ngoMorris' e d as = medianOfMeans $ Cl.sourceList as $$ count' $ ccs\n      where\n        medianOfMeans = fmap median' . (fmap . fmap) mean' \n        ccs           = replicate m $ replicate t 0\n        t             = round $ 1/(e^2*d)            \n        m             = round . log $ 1/d  \n\n\n-- * Given an m-long list `ccs` of lists (each of which is t-lengthd) of counters,\n-- * consume the stream and output result\ncount' :: [[Counter]] -> Sink a RVar [[Counter]]\ncount' ccs = (\\x -> 2^(round x) - 1) `fffmap` Cl.foldM (\\xs _ -> incrs' xs) ccs\n  where fffmap = fmap . fmap . fmap\n\n-- * given a list of list of counters toss a coin for each counter and incr\n-- * this can be flattened\nincrs' :: [[Counter]] -> RVar [[Counter]]\nincrs' = sequence . fmap (sequence . fmap incr)\n\n\n\n{-----------------------------------------------------------------------------\n    III. Utils\n------------------------------------------------------------------------------}\n\n\n-- * Increment a counter `x` with probability 1/2^x\nincr :: Counter -> RVar Counter\nincr x = do\n  h <- toss . coin $ 0.5^(round x)\n  return $ if isHead h then (seq () succ x) else seq () x\n\n\nmean', median' :: (Floating a, Ord a, RealFrac a) => [a] -> Float\nmean'   = fromIntegral . round . mean\nmedian' = fromIntegral . round . median\n\n\n\n{-----------------------------------------------------------------------------\n    IV. Naive Implementation\n------------------------------------------------------------------------------}\n\n-- * 2x slower than morris'\n-- * Run on stream inputs `xs` for t independent trials for `t = 1/eps`, \n-- * and `m` times in parralell where `m = 1/(e^2 * d)`, take the median\nmorrisNaive :: Eps -> Delta -> [a] -> IO Counter\nmorrisNaive e d = fmap median' . replicateM m . morrisB t \n  where (t,m) = (round $ 1/(e^2*d), round $ 1/d)\n\n\n-- * Run Morris beta on stream inputs `xs` for `t` independent trials and average\nmorrisB :: Int -> [a] -> IO Counter\nmorrisB t =  fmap mean' . replicateM t . morrisA\n\n-- * Run Morris alpha on stream inputs `xs`\nmorrisA :: [a] -> IO Counter\nmorrisA xs = flip runRVar StdRandom $ Cl.sourceList xs $$ alpha\n\n\n-- * A step in morris Algorithm alpha\nalpha :: Sink a RVar Counter\nalpha = (\\x -> 2^(round x) - 1) <$> Cl.foldM (\\x _ -> incr x) 0\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0383bd7b099377fff38c6b8bc65efc538f17f176", "size": 4833, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "depricated/MorrisDep.hs", "max_stars_repo_name": "lingxiao/CIS700", "max_stars_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "depricated/MorrisDep.hs", "max_issues_repo_name": "lingxiao/CIS700", "max_issues_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "depricated/MorrisDep.hs", "max_forks_repo_name": "lingxiao/CIS700", "max_forks_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8775510204, "max_line_length": 122, "alphanum_fraction": 0.4938961308, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4171881005170027}}
{"text": "\ufeff{-# LANGUAGE BangPatterns,RecordWildCards,FlexibleContexts,TypeFamilies #-}\n{-# OPTIONS_GHC -Wno-deferred-type-errors #-}\n\nmodule Neuro where\n\n{-@ LIQUID \"--no-termination\" @-}\n{-@ LIQUID \"--reflection\" @-}\n{-@ LIQUID \"--no-total\" @-}\n\nimport Codec.Compression.Zlib     (compress, decompress)\n\nimport Data.Binary                (Binary(..), encode, decode)\nimport Data.List                  (foldl')\nimport Foreign.Storable           (Storable)\n\nimport qualified Data.ByteString.Lazy  as BS\nimport qualified Data.Vector           as DV\n      (Vector,\n      toList,\n      fromList,\n      snoc,empty,\n      foldl',\n      scanl,scanr,\n      zipWith,\n      tail,init,last,zip,map, head)\nimport Numeric.LinearAlgebra\n    ( (#>),\n      reshape,\n      vector,\n      cmap,\n      (<.>),\n      (><),\n      outer,\n      vjoin,\n      Element,\n      Matrix,\n      Container,\n      Linear(scale),\n      Numeric,\n      RealOf,\n      Transposable(tr),\n      Normed(norm_2),\n      Vector)\nimport System.Random.MWC as MWC\n    ( Variate, asGenST, uniformVector, withSystemRandom )\n\nnewtype Network a = Network\n                 { matrices   :: DV.Vector (Matrix a)\n                 } deriving Show\n\ninstance (Element a, Binary a) => Binary (Network a) where\n  put (Network ms) = put . DV.toList $ ms\n  get = (Network . DV.fromList) `fmap` get                 \n\ntype ActivationFunction a = a -> a\n\ntype ActivationFunctionDerivative a = a -> a\n\ntrainNTimes :: (Floating (Vector a), Floating a, Numeric a, Num (Vector a), Container Vector a) => Int -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a\ntrainNTimes n = trainUntil (\\k _ _ -> k > n)\n\ntrainUntil :: (Floating (Vector a), Floating a, Numeric a, Num (Vector a), Container Vector a) => (Int -> Network a -> Samples a -> Bool) -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a\ntrainUntil pr learningRate act act' net samples = go net 0\n  where go n !k | pr k n samples = n\n                | otherwise      = case backpropOnce learningRate act act' n samples of\n                                    n' -> go n' (k+1)\n\ncreateNetwork :: (Variate a, Storable a) => Int -> [Int] -> Int -> IO (Network a)\ncreateNetwork nInputs hiddens nOutputs =\n  fmap Network $ withSystemRandom . asGenST $ \\gen -> go gen dimensions DV.empty\n  where\n        go _ [] !ms         = return ms\n        go gen ((!n,!m):ds) ms = do\n          !mat <- randomMat n m gen\n          go gen ds (ms `DV.snoc` mat)\n        randomMat n m g = reshape m `fmap` uniformVector g (n*m)\n        dimensions      = zip (hiddens ++ [nOutputs]) $\n                              (nInputs+1 : hiddens)\n\nfromWeightMatrices :: Storable a => DV.Vector (Matrix a) -> Network a\nfromWeightMatrices ws = Network ws\n\noutput :: (Floating (Vector a), Numeric a, Storable a, Num (Vector a)) => Network a -> ActivationFunction a -> Vector a -> Vector a\noutput (Network{..}) act input = DV.foldl' f (vjoin [input, 1]) matrices\n  where f !inp m = cmap act $ m #> inp\n\noutputs :: (Floating (Vector a), Numeric a, Storable a, Num (Vector a)) => Network a -> ActivationFunction a -> Vector a -> DV.Vector (Vector a)\noutputs (Network{..}) act input = DV.scanl f (vjoin [input, 1]) matrices\n  where f !inp m = cmap act $ m #> inp\n\ndeltas :: (Floating (Vector a), Floating a, Numeric a, Container Vector a, Num (Vector a)) => Network a -> ActivationFunctionDerivative a -> DV.Vector (Vector a) -> Vector a -> DV.Vector (Matrix a)\ndeltas (Network{..}) act' os expected = DV.zipWith outer (DV.tail ds) (DV.init os)\n  where !dl = (DV.last os - expected) * (deriv $ DV.last os)\n        !ds = DV.scanr f dl (DV.zip os matrices)\n        f (!o, m) !del = deriv o * (tr m #> del)\n        deriv = cmap act'\n\nupdateNetwork :: (Floating (Vector a), Floating a, Numeric a, Storable a, Num (Vector a), Container Vector a) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Sample a -> Network a\nupdateNetwork alpha act act' n@(Network{..}) (input, expectedOutput) = Network $ DV.zipWith (+) matrices corr\n    where !xs = outputs n act input\n          !ds = deltas n act' xs expectedOutput\n          !corr = DV.map (scale (-alpha)) ds\n          \ntype Sample a = (Vector a, Vector a)\n\ntype Samples a = [Sample a]\n\n\nbackpropOnce :: (Floating (Vector a), Floating a, Numeric a, Num (Vector a), Container Vector a) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a\nbackpropOnce rate act act' n samples = foldl' (updateNetwork rate act act') n samples\n\n\nquadError :: (Floating (Vector a), Floating a, Fractional (RealOf a), Normed (Vector a), Numeric a) => ActivationFunction a -> Network a -> Samples a -> RealOf a\nquadError act net samples = realToFrac $ foldl' (\\err (inp, out) -> err + (norm_2 $ output net act inp - out)) 0 samples\n\n\ntanh' :: Floating a => a -> a\ntanh' x = let s = tanh x\n           in 1 - s**2\n\nloadNetwork :: (Storable a, Element a, Binary a) => FilePath -> IO (Network a)\nloadNetwork fp = return . decode . decompress =<< BS.readFile fp\n\nsaveNetwork :: (Storable a, Element a, Binary a) => FilePath -> Network a -> IO ()\nsaveNetwork fp net = BS.writeFile fp . compress $ encode net", "meta": {"hexsha": "1b3db7745f3054a5151191b5f68bc09e02cdde49", "size": 5235, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Neuro.hs", "max_stars_repo_name": "Alexander671/neuroLiquid", "max_stars_repo_head_hexsha": "48e816930b6b62b3fd4418190efaf2e71739cc4d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Neuro.hs", "max_issues_repo_name": "Alexander671/neuroLiquid", "max_issues_repo_head_hexsha": "48e816930b6b62b3fd4418190efaf2e71739cc4d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Neuro.hs", "max_forks_repo_name": "Alexander671/neuroLiquid", "max_forks_repo_head_hexsha": "48e816930b6b62b3fd4418190efaf2e71739cc4d", "max_forks_repo_licenses": ["BSD-3-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.88, "max_line_length": 239, "alphanum_fraction": 0.623495702, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085758631158, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.4171632764892826}}
{"text": "{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}\n\nmodule Wyas.Parser.Primitives where\n\nimport Wyas.Types\n\nimport Text.ParserCombinators.Parsec hiding (spaces)\nimport Numeric (readOct, readHex)\nimport Data.Ratio ((%))\nimport Data.Complex (Complex (..))\nimport Control.Monad (liftM)\n\nparseBool :: Parser LispVal\nparseBool = do char '#'\n               b <- parseTrue <|> parseFalse\n               return $ Bool b\n               where parseTrue  = char 't' >> return True\n                     parseFalse = char 'f' >> return False\n\nparseAtom :: Parser LispVal\nparseAtom = do first <- letter <|> symbol\n               rest <- many (letter <|> digit <|> symbol)\n               return $ Atom (first:rest)\n\n--\n-- Char & String\n--\n\nparseChar :: Parser LispVal\nparseChar = liftM Character (string \"#\\\\\" >> parseChar')\n          where parseWS = (string \" \" <|> string \"space\") >> return ' '\n                parseNewline = string \"newline\" >> return '\\n'\n                parseChar' = parseWS <|> parseNewline <|> anyChar\n\nparseString :: Parser LispVal\nparseString = do char '\"'\n                 x <- many (escapedChars <|> noneOf \"\\\\\\\"\")\n                 char '\"'\n                 (return . String) x\n\n--\n-- Parsing Integers\n--\n\nparseNumber :: Parser LispVal\nparseNumber = parsePlainNumber <|> parseRadixNumber\n\nparsePlainNumber :: Parser LispVal\nparsePlainNumber = liftM (Number . read) (many1 digit)\n\n--\n-- Radix Numbers\n--\n\nparseRadixNumber :: Parser LispVal\nparseRadixNumber = char '#' >>\n                   (\n                        parseDecimal\n                        <|> parseBinary\n                        <|> parseOct\n                        <|> parseHex\n                   )\n\nparseDecimal :: Parser LispVal\nparseDecimal = do char 'd'\n                  n <- many1 digit\n                  (return . Number . read) n\n\nparseBinary :: Parser LispVal\nparseBinary = do char 'b'\n                 n <- many $ oneOf \"01\"\n                 (return . Number . bin2int) n\n\nparseHex :: Parser LispVal\nparseHex = do char 'x'\n              n <- many $ oneOf \"0123456789abcdefABCDEF\"\n              return . Number . readWith readHex $ n\n              where readWith f s = fst $ head (f s)\n\nparseOct :: Parser LispVal\nparseOct = do char 'o'\n              n <- many $ oneOf \"01234567\"\n              return . Number . readWith readOct $ n\n              where readWith f s = fst $ head (f s)\n\n--\n-- Numeric Tower\n--\n\nparseFloat :: Parser LispVal\nparseFloat = do x <- many1 digit\n                char '.'\n                y <- many1 digit\n                return $ Float (read (x ++ \".\" ++y))\n\nparseRational :: Parser LispVal\nparseRational = do n <- many1 digit\n                   char '/'\n                   d <- many1 digit\n                   return $ Ratio $ read n % read d\n\nparseComplex :: Parser LispVal\nparseComplex = do x <- try parseFloat <|> parsePlainNumber\n                  char '+'\n                  y <- try parseFloat <|> parsePlainNumber\n                  char 'i'\n                  return $ Complex (toDouble x :+ toDouble y)\n\n--\n-- Helpers\n--\n\nescapedChars :: Parser Char\nescapedChars = char '\\\\' >>\n               (\n                    char '\\\\' <|> char '\"' <|>\n                    parseNewline <|>\n                    parseReturn <|>\n                    parseTab\n               )\n               where parseNewline = char 'n' >> return '\\n'\n                     parseReturn  = char 'r' >> return '\\r'\n                     parseTab     = char 't' >> return '\\t'\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%|*+-/:<=>?@^_~\"\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\nbin2int :: String -> Integer\nbin2int = bin2int' 0\n        where bin2int' digint \"\" = digint\n              bin2int' digint (x:xs) = let old = 2 * digint + (if x == '0' then 0 else 1)\n                                       in bin2int' old xs\n\n-- TODO clean up\ntoDouble :: LispVal -> Double\ntoDouble (Float f) = f\ntoDouble (Number n) = fromIntegral n\ntoDouble _ = error \"ERROR: not a double\"\n", "meta": {"hexsha": "e5ef27d6fafc117bebfe451cc28961ba2e83de1b", "size": 3946, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Wyas/Parser/Primitives.hs", "max_stars_repo_name": "grtlr/wyas", "max_stars_repo_head_hexsha": "2182f1ff2f98fa5f07cead8349c829ec31f06b49", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Wyas/Parser/Primitives.hs", "max_issues_repo_name": "grtlr/wyas", "max_issues_repo_head_hexsha": "2182f1ff2f98fa5f07cead8349c829ec31f06b49", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Wyas/Parser/Primitives.hs", "max_forks_repo_name": "grtlr/wyas", "max_forks_repo_head_hexsha": "2182f1ff2f98fa5f07cead8349c829ec31f06b49", "max_forks_repo_licenses": ["BSD-3-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.7887323944, "max_line_length": 89, "alphanum_fraction": 0.5212873796, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4170585218676458}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE Strict           #-}\nmodule STC.Plan\n  ( module DFT.Plan\n  , module STC.Plan\n  ) where\n\nimport           Control.Monad        as M\nimport           Data.Array.Repa      as R\nimport           Data.Complex\nimport           Data.List            as L\nimport           Data.Vector.Storable as VS\nimport           DFT.Plan\nimport           System.FilePath\nimport           System.Random\nimport           Control.Concurrent.Async\n\n{-# INLINE generateRadomVector #-}\ngenerateRadomVector ::\n     (Storable e, Num e, Random e)\n  => Int\n  -> IO (VS.Vector (Complex e))\ngenerateRadomVector len =\n  newStdGen >>= return . VS.map (:+ 0) . VS.fromList . L.take len . randoms\n\nmakePlanDiscrete :: FilePath -> DFTPlan -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> IO DFTPlan\nmakePlanDiscrete folderPath initPlan nx ny numR2Freq numThetaFreq numRFreq numPhiFreq numRhoFreq = do\n  importFFTWWisdom (folderPath </> \"fftwwisdom.dat\")\n  let lens =\n        [ numThetaFreq * numR2Freq ^ 2\n        , nx * ny * numThetaFreq * numRFreq\n        , numR2Freq ^ 2\n        , numThetaFreq * numRFreq * numPhiFreq * numRhoFreq\n        , numRhoFreq * numRFreq\n        , numThetaFreq * numR2Freq ^ 2\n        , numRFreq\n        ]\n  (initVec1:initVec2:initVec3:initVec4:initVec5:initVec6:initVec7:_) <-\n   mapConcurrently generateRadomVector lens\n  lock <- getFFTWLock\n  plan <-\n    fst <$>\n    (dft1dGPlan\n       lock\n       initPlan\n       [numThetaFreq, numR2Freq, numR2Freq]\n       [1, 2]\n       initVec1 >>= \\(plan, vec) ->\n       idft1dGPlan\n         lock\n         plan\n         [numThetaFreq, numR2Freq, numR2Freq]\n         [1, 2]\n         vec >>= \\(plan, _) ->\n         dft1dGPlan lock plan [numRFreq, numThetaFreq, nx, ny] [0, 1] initVec2 >>= \\(plan, vec) ->\n           idft1dGPlan lock plan [numRFreq, numThetaFreq, nx, ny] [0, 1] vec >>= \\(plan, vec) ->\n             dft1dGPlan\n               lock\n               plan\n               [numRFreq, numThetaFreq, numR2Freq, numR2Freq]\n               [0]\n               vec >>= \\(plan, vec) ->\n               idft1dGPlan\n                 lock\n                 plan\n                 [numRFreq, numThetaFreq, numR2Freq, numR2Freq]\n                 [0]\n                 vec\n            >>= \\(plan, _) ->\n             dft1dGPlan lock plan [numR2Freq, numR2Freq] [0, 1] initVec3 >>= \\(plan, vec) ->\n               idft1dGPlan lock plan [numR2Freq, numR2Freq] [0, 1] vec >>= \\(plan, _) ->\n                 dft1dGPlan\n                   lock\n                   plan\n                   [numRFreq, numRhoFreq, numThetaFreq, numPhiFreq]\n                   [0, 1]\n                   initVec4 >>= \\(plan, vec) ->\n                   idft1dGPlan\n                     lock\n                     plan\n                     [numRFreq, numRhoFreq, numThetaFreq, numPhiFreq]\n                     [0, 1]\n                     vec >>= \\(plan, _) ->\n                     dft1dGPlan lock plan [numRFreq, numRhoFreq] [0, 1] initVec5 >>= \\(plan, vec) ->\n                       idft1dGPlan lock plan [numRFreq, numRhoFreq] [0, 1] vec >>= \\(plan, _) ->\n                         idft1dGPlan\n                           lock\n                           plan\n                           [numThetaFreq, numR2Freq, numR2Freq]\n                           [1, 2]\n                           initVec6 >>= \\(plan, _) ->\n                             dft1dGPlan lock plan [numRFreq] [0] initVec7 )\n  exportFFTWWisdom (folderPath </> \"fftwwisdom.dat\")\n  return plan\n  \n\nmakePlan :: FilePath -> DFTPlan -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> IO DFTPlan\nmakePlan folderPath initPlan nx ny numR2Freq numThetaFreq numRFreq numPhiFreq numRhoFreq = do\n  importFFTWWisdom (folderPath </> \"fftwwisdom.dat\")\n  let lens =\n        [ numRFreq * numThetaFreq * numR2Freq ^ 2\n        , nx * ny * numThetaFreq * numRFreq\n        , numR2Freq ^ 2\n        , numThetaFreq * numRFreq * numPhiFreq * numRhoFreq\n        , numRhoFreq * numRFreq\n        , numThetaFreq * numR2Freq ^ 2\n        ]\n  (initVec1:initVec2:initVec3:initVec4:initVec5:initVec6:_) <-\n   mapConcurrently generateRadomVector lens\n  lock <- getFFTWLock\n  plan <-\n    fst <$>\n    (dft1dGPlan\n       lock\n       initPlan\n       [numRFreq, numThetaFreq, numR2Freq, numR2Freq]\n       [0, 1, 2, 3]\n       initVec1 >>= \\(plan, vec) ->\n       idft1dGPlan\n         lock\n         plan\n         [numRFreq, numThetaFreq, numR2Freq, numR2Freq]\n         [0, 1, 2, 3]\n         vec >>= \\(plan, _) ->\n         dft1dGPlan lock plan [numRFreq, numThetaFreq, nx, ny] [0, 1] initVec2 >>= \\(plan, vec) ->\n           idft1dGPlan lock plan [numRFreq, numThetaFreq, nx, ny] [0, 1] vec -- >>= \\(plan, vec) ->\n             -- dft1dGPlan\n             --   lock\n             --   plan\n             --   [numRFreq, numThetaFreq, numR2Freq, numR2Freq]\n             --   [0]\n             --   vec >>= \\(plan, vec) ->\n             --   idft1dGPlan\n             --     lock\n             --     plan\n             --     [numRFreq, numThetaFreq, numR2Freq, numR2Freq]\n             --     [0]\n             --     vec\n            >>= \\(plan, _) ->\n             dft1dGPlan lock plan [numR2Freq, numR2Freq] [0, 1] initVec3 >>= \\(plan, vec) ->\n               idft1dGPlan lock plan [numR2Freq, numR2Freq] [0, 1] vec >>= \\(plan, _) ->\n                 dft1dGPlan\n                   lock\n                   plan\n                   [numRFreq, numRhoFreq, numThetaFreq, numPhiFreq]\n                   [0, 1]\n                   initVec4 >>= \\(plan, vec) ->\n                   idft1dGPlan\n                     lock\n                     plan\n                     [numRFreq, numRhoFreq, numThetaFreq, numPhiFreq]\n                     [0, 1]\n                     vec >>= \\(plan, _) ->\n                     dft1dGPlan lock plan [numRFreq, numRhoFreq] [0, 1] initVec5 >>= \\(plan, vec) ->\n                       idft1dGPlan lock plan [numRFreq, numRhoFreq] [0, 1] vec >>= \\(plan, _) ->\n                         idft1dGPlan\n                           lock\n                           plan\n                           [numThetaFreq, numR2Freq, numR2Freq]\n                           [1, 2]\n                           initVec6)\n  exportFFTWWisdom (folderPath </> \"fftwwisdom.dat\")\n  return plan\n\n{-# INLINE makePlanFromArray #-}\nmakePlanFromArray ::\n     (R.Source r (Complex Double))\n  => DFTPlan\n  -> R.Array r DIM4 (Complex Double)\n  -> IO DFTPlan\nmakePlanFromArray initPlan arr = do\n  let (Z :. (numRFreq) :. (numThetaFreq) :. (nx) :. (ny)) = extent arr\n      initVec = VS.fromList . R.toList $ arr\n  lock <- getFFTWLock\n  fst <$>\n    (dft1dGPlan lock initPlan [nx, ny] [0, 1] initVec >>= \\(plan, vec) ->\n       idft1dGPlan lock plan [nx, ny] [0, 1] vec >>= \\(plan, vec) ->\n         dft1dGPlan lock plan [numRFreq, numThetaFreq, nx, ny] [0, 1] vec >>= \\(plan, vec) ->\n           idft1dGPlan lock plan [numRFreq, numThetaFreq, nx, ny] [0, 1] vec)\n\n\n-- {-# INLINE makePlan #-}\n-- makePlan :: FilePath -> DFTPlan -> Int -> Int -> Int -> Int -> Int -> IO DFTPlan\n-- makePlan folderPath initPlan nx ny numR2Freq numThetaFreq numRFreq = do\n--   importFFTWWisdom (folderPath </> \"fftwwisdom.dat\")\n--   initVec1 <-\n--     VS.fromList . L.map (:+ 0) <$> M.replicateM (numR2Freq ^ 2) randomIO\n--   initVec2 <-\n--     VS.fromList . L.map (:+ 0) <$>\n--     M.replicateM (nx * ny * numThetaFreq * numRFreq) randomIO\n--   initVec3 <- VS.fromList . L.map (:+ 0) <$> M.replicateM (nx * ny) randomIO\n--   lock <- getFFTWLock\n--   plan <-\n--     fst <$>\n--     (dft1dGPlan lock initPlan [numR2Freq, numR2Freq] [0, 1] initVec1 >>= \\(plan, vec) ->\n--        idft1dGPlan lock plan [numR2Freq, numR2Freq] [0, 1] vec >>= \\(plan, _) ->\n--          dft1dGPlan lock plan [numRFreq, numThetaFreq, nx, ny] [0, 1] initVec2 >>= \\(plan, vec) ->\n--            idft1dGPlan lock plan [numRFreq, numThetaFreq, nx, ny] [0, 1] vec >>= \\(plan, _) ->\n--              dft1dGPlan lock plan [nx, ny] [0, 1] initVec3 >>= \\(plan, vec) ->\n--                idft1dGPlan lock plan [nx, ny] [0, 1] vec)\n--   exportFFTWWisdom (folderPath </> \"fftwwisdom.dat\")\n--   return plan\n", "meta": {"hexsha": "6f0e4be1d8e4222c10576546e9b89b1d57ee8ab2", "size": 8056, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/Plan.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/Plan.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/Plan.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.684729064, "max_line_length": 102, "alphanum_fraction": 0.5081926514, "num_tokens": 2473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4168596992670342}}
{"text": "-- |\n-- Copyright: (c) 2020-2021 Tom Westerhout\n-- SPDX-License-Identifier: BSD-3-Clause\n-- Maintainer: Tom Westerhout <14264576+twesterhout@users.noreply.github.com>\nmodule Numeric.PRIMME.Dense\n  ( -- * Treat dense matrices as linear operators\n    primmeFromDense,\n  )\nwhere\n\nimport Control.Monad.ST (RealWorld)\nimport Data.Complex\nimport Data.Proxy\nimport Data.Vector.Storable (MVector, Vector)\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Storable.Mutable as MV\nimport Foreign.C.Types (CChar, CInt)\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr (Ptr)\nimport Numeric.PRIMME.Types\n\ntype BlasInt = CInt\n\ntype BlasHemmType a =\n  -- | SIDE\n  Ptr CChar ->\n  -- | UPLO\n  Ptr CChar ->\n  -- | M\n  Ptr BlasInt ->\n  -- | N\n  Ptr BlasInt ->\n  -- | ALPHA\n  Ptr a ->\n  -- | A\n  Ptr a ->\n  -- | LDA\n  Ptr BlasInt ->\n  -- | B\n  Ptr a ->\n  -- | LDB\n  Ptr BlasInt ->\n  -- | BETA\n  Ptr a ->\n  -- | C\n  Ptr a ->\n  -- | LDC\n  Ptr BlasInt ->\n  IO ()\n\nforeign import ccall unsafe \"ssymm_\" ssymm_ :: BlasHemmType Float\n\nforeign import ccall unsafe \"dsymm_\" dsymm_ :: BlasHemmType Double\n\nforeign import ccall unsafe \"chemm_\" chemm_ :: BlasHemmType (Complex Float)\n\nforeign import ccall unsafe \"zhemm_\" zhemm_ :: BlasHemmType (Complex Double)\n\nhemm :: BlasDatatype a => Int -> Int -> a -> Vector a -> Int -> Vector a -> Int -> a -> MVector RealWorld a -> Int -> IO ()\nhemm m n \u03b1 a aStride b bStride \u03b2 c cStride = do\n  with (fromIntegral (fromEnum 'L') :: CChar) $ \\side' ->\n    with (fromIntegral (fromEnum 'U') :: CChar) $ \\uplo' -> do\n      with (fromIntegral m) $ \\m' ->\n        with (fromIntegral n) $ \\n' ->\n          with (fromIntegral aStride) $ \\aStride' ->\n            with (fromIntegral bStride) $ \\bStride' ->\n              with (fromIntegral cStride) $ \\cStride' ->\n                with \u03b1 $ \\\u03b1' ->\n                  with \u03b2 $ \\\u03b2' ->\n                    V.unsafeWith a $ \\aPtr ->\n                      V.unsafeWith b $ \\bPtr ->\n                        MV.unsafeWith c $ \\cPtr ->\n                          hemm' side' uplo' m' n' \u03b1' aPtr aStride' bPtr bStride' \u03b2' cPtr cStride'\n  where\n    hemm' :: forall b. BlasDatatype b => BlasHemmType b\n    hemm' = case blasTag (Proxy :: Proxy b) of\n      FloatTag -> ssymm_\n      DoubleTag -> dsymm_\n      ComplexFloatTag -> chemm_\n      ComplexDoubleTag -> zhemm_\n\nblockHemm :: BlasDatatype a => a -> Block a -> Block a -> a -> MBlock RealWorld a -> IO ()\nblockHemm \u03b1 (Block (m, n) aStride a) (Block (n', k) bStride b) \u03b2 (MBlock (m', k') cStride c)\n  | m /= n || m /= m' || n /= n' || k /= k' =\n    error $\n      \"dimension mismatch: \" <> show (m, n) <> \" x \" <> show (n', k) <> \" = \" <> show (m', k')\n  | otherwise = hemm m' k' \u03b1 a aStride b bStride \u03b2 c cStride\n\n-- | Treat a dense symmetric or Hermitian matrix as a operator. Internally we\n-- call\n-- [@?symm@](https://www.netlib.org/lapack/explore-html/db/dc9/group__single__blas__level3_ga8e8391a9873114d97e2b63e39fe83b2e.html#ga8e8391a9873114d97e2b63e39fe83b2e)\n-- or\n-- [@?hemm@](https://www.netlib.org/lapack/explore-html/db/def/group__complex__blas__level3_gad2d1853a142397404eae974b6574ece3.html#gad2d1853a142397404eae974b6574ece3)\n-- BLAS functions so it is really important that the matrix is indeed Hermitian.\nprimmeFromDense ::\n  BlasDatatype a =>\n  -- | Matrix in column-major order\n  Block a ->\n  -- | Hermitian linear operator\n  PrimmeOperator a\nprimmeFromDense a\n  | isHermitian a = \\b c -> blockHemm 1 a b 0 c\n  | otherwise = error \"expected a Hermitian matrix\"\n\n-- | Determine whether a matrix is Hermitian (or symmetric when @a@ is real).\n--\n-- /Note:/ this function returns 'False' for non-square matrices. No exceptions\n-- are thrown.\nisHermitian :: forall a. BlasDatatype a => Block a -> Bool\nisHermitian (Block (n, n') stride v)\n  | n == n' =\n    -- Iterate in column-major order here and over the lower part of the matrix\n    loop 0 (n - 1) $ \\j ->\n      loop (j + 1) n $ \\i ->\n        check i j\n  | otherwise = False\n  where\n    access !i !j = v V.! (i + stride * j)\n    check !i !j = access i j `unsafeEq` conj (access j i)\n    loop !i !high f\n      | i < high =\n        if f i\n          then loop (i + 1) high f\n          else False\n      | otherwise = True\n    -- Yes, we really want exact binary comparison of floating point types\n    unsafeEq :: a -> a -> Bool\n    unsafeEq = case blasTag (Proxy :: Proxy a) of\n      FloatTag -> (==)\n      DoubleTag -> (==)\n      ComplexFloatTag -> (==)\n      ComplexDoubleTag -> (==)\n    -- Return complex conjugate of a number.\n    !conj = case blasTag (Proxy :: Proxy a) of\n      FloatTag -> id\n      DoubleTag -> id\n      ComplexFloatTag -> Data.Complex.conjugate\n      ComplexDoubleTag -> Data.Complex.conjugate\n", "meta": {"hexsha": "019e4134e2c3b0cd3fd365f0bad1a7a20336c506", "size": 4689, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/PRIMME/Dense.hs", "max_stars_repo_name": "twesterhout/primme-hs", "max_stars_repo_head_hexsha": "c5e7ad4fd650cf88324861fcad2c591f84f8ea5f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-30T12:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T12:18:33.000Z", "max_issues_repo_path": "src/Numeric/PRIMME/Dense.hs", "max_issues_repo_name": "twesterhout/primme-hs", "max_issues_repo_head_hexsha": "c5e7ad4fd650cf88324861fcad2c591f84f8ea5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/PRIMME/Dense.hs", "max_forks_repo_name": "twesterhout/primme-hs", "max_forks_repo_head_hexsha": "c5e7ad4fd650cf88324861fcad2c591f84f8ea5f", "max_forks_repo_licenses": ["BSD-3-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.7338129496, "max_line_length": 167, "alphanum_fraction": 0.6197483472, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4166296562077361}}
{"text": "module Other (\n    parseCsvToMatrixR,\n    printCsvFromMatrixR,\n    iterateM\n  ) where\n\nimport Numeric.LinearAlgebra\nimport Data.List\nimport Data.List.Split\n\nparseCsvToMatrixR :: FilePath -> IO (Matrix R)\nparseCsvToMatrixR fp = do\n  csv <- readFile fp\n  return . fromLists . fmap (fmap (read :: String -> R) . splitOn \",\") $ lines csv\n\nprintCsvFromMatrixR :: FilePath -> Matrix R -> IO ()\nprintCsvFromMatrixR fp m = do\n  let csv = unlines . fmap (intercalate \", \") $ fmap show <$> toLists m\n  writeFile fp csv\n\n-- TODO: check monad rule\niterateM :: Monad m => (a -> m a) -> a -> [m a]\niterateM f x = iterate (f =<<) (return x)\n", "meta": {"hexsha": "fb3f9c010110c3ba51f8661f499294e2b9cdb65f", "size": 626, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Other.hs", "max_stars_repo_name": "pupuu/deep-neuralnet", "max_stars_repo_head_hexsha": "c32a517194e11a40a686c07ade27517a4d728f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Other.hs", "max_issues_repo_name": "pupuu/deep-neuralnet", "max_issues_repo_head_hexsha": "c32a517194e11a40a686c07ade27517a4d728f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Other.hs", "max_forks_repo_name": "pupuu/deep-neuralnet", "max_forks_repo_head_hexsha": "c32a517194e11a40a686c07ade27517a4d728f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0833333333, "max_line_length": 82, "alphanum_fraction": 0.6661341853, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.4166296515654955}}
{"text": "module Main where\n\nimport Criterion.Main\nimport Statistics.Sample.Histogram.Magnitude\nimport Data.Functor.Identity\n\nmain = defaultMain\n  [ bgroup \"resolution\" [ bench \"1\"  . nf (foldHist 1) $ Identity (1 :: Double)\n                        , bench \"2\"  . nf (foldHist 2) $ Identity (1 :: Double)\n                        , bench \"3\"  . nf (foldHist 3) $ Identity (1 :: Double)\n                        ]\n  , bgroup \"size\"       [ bench \"0\"      $ nf (foldHist 2) ([] :: [Double])\n                        , bench \"0..9\"   $ nf (foldHist 2) [0..9 :: Double]\n                        , bench \"0..99\"  $ nf (foldHist 2) [0..99 :: Double]\n                        ]\n  ]\n", "meta": {"hexsha": "c369aeb74dd1b08da4b34ce8eb91fc0b2482224e", "size": 660, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmark/Bench.hs", "max_stars_repo_name": "skedgeme/histogram-magnitude", "max_stars_repo_head_hexsha": "a8417dfdb002f99dba8740925f2eaa58de8509ea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark/Bench.hs", "max_issues_repo_name": "skedgeme/histogram-magnitude", "max_issues_repo_head_hexsha": "a8417dfdb002f99dba8740925f2eaa58de8509ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/Bench.hs", "max_forks_repo_name": "skedgeme/histogram-magnitude", "max_forks_repo_head_hexsha": "a8417dfdb002f99dba8740925f2eaa58de8509ea", "max_forks_repo_licenses": ["BSD-3-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.8235294118, "max_line_length": 79, "alphanum_fraction": 0.4742424242, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.41636609309953704}}
{"text": "module Day10 where\n\nimport Data.Function ((&))\nimport Data.List.Split\nimport qualified Data.List as L\nimport Data.Array\nimport qualified Data.Set as Set\nimport qualified Data.Map.Strict as Map\nimport Data.Char\nimport Data.Maybe (catMaybes, isJust, fromJust)\nimport Text.ParserCombinators.ReadP as P\n\nimport Data.Complex\nimport qualified Data.Matrix as M\n\nimport Lib\n\n{-\n--- Day 10: Adapter Array ---\n\nPatched into the aircraft's data port, you discover weather forecasts of a massive tropical storm. Before you can figure out whether it will impact your vacation plans, however, your device suddenly turns off!\n\nIts battery is dead.\n\nYou'll need to plug it in. There's only one problem: the charging outlet near your seat produces the wrong number of jolts. Always prepared, you make a list of all of the joltage adapters in your bag.\n\nEach of your joltage adapters is rated for a specific output joltage (your puzzle input). Any given adapter can take an input 1, 2, or 3 jolts lower than its rating and still produce its rated output joltage.\n\nIn addition, your device has a built-in joltage adapter rated for 3 jolts higher than the highest-rated adapter in your bag. (If your adapter list were 3, 9, and 6, your device's built-in adapter would be rated for 12 jolts.)\n\nTreat the charging outlet near your seat as having an effective joltage rating of 0.\n\nSince you have some time to kill, you might as well test all of your adapters. Wouldn't want to get to your resort and realize you can't even charge your device!\n\nIf you use every adapter in your bag at once, what is the distribution of joltage differences between the charging outlet, the adapters, and your device?\n\nFor example, suppose that in your bag, you have adapters with the following joltage ratings:\n\n16\n10\n15\n5\n1\n11\n7\n19\n6\n12\n4\n\nWith these adapters, your device's built-in joltage adapter would be rated for 19 + 3 = 22 jolts, 3 higher than the highest-rated adapter.\n\nBecause adapters can only connect to a source 1-3 jolts lower than its rating, in order to use every adapter, you'd need to choose them like this:\n\n    The charging outlet has an effective rating of 0 jolts, so the only adapters that could connect to it directly would need to have a joltage rating of 1, 2, or 3 jolts. Of these, only one you have is an adapter rated 1 jolt (difference of 1).\n    From your 1-jolt rated adapter, the only choice is your 4-jolt rated adapter (difference of 3).\n    From the 4-jolt rated adapter, the adapters rated 5, 6, or 7 are valid choices. However, in order to not skip any adapters, you have to pick the adapter rated 5 jolts (difference of 1).\n    Similarly, the next choices would need to be the adapter rated 6 and then the adapter rated 7 (with difference of 1 and 1).\n    The only adapter that works with the 7-jolt rated adapter is the one rated 10 jolts (difference of 3).\n    From 10, the choices are 11 or 12; choose 11 (difference of 1) and then 12 (difference of 1).\n    After 12, only valid adapter has a rating of 15 (difference of 3), then 16 (difference of 1), then 19 (difference of 3).\n    Finally, your device's built-in adapter is always 3 higher than the highest adapter, so its rating is 22 jolts (always a difference of 3).\n\nIn this example, when using every adapter, there are 7 differences of 1 jolt and 5 differences of 3 jolts.\n\nHere is a larger example:\n\n28\n33\n18\n42\n31\n14\n46\n20\n48\n47\n24\n23\n49\n45\n19\n38\n39\n11\n1\n32\n25\n35\n8\n17\n7\n9\n4\n2\n34\n10\n3\n\nIn this larger example, in a chain that uses all of the adapters, there are 22 differences of 1 jolt and 10 differences of 3 jolts.\n\nFind a chain that uses all of your adapters to connect the charging outlet to your device's built-in adapter and count the joltage differences between the charging outlet, the adapters, and your device. What is the number of 1-jolt differences multiplied by the number of 3-jolt differences?\n\nTo begin, get your puzzle input.\n-}\n\nparse :: [String] -> [Integer]\nparse ls = ls\n         & map read\n\npartA ns =\n  let adapters = L.sort ns\n      diffs = zipWith (-) adapters (0:adapters)\n      ones = diffs & filter (==1) & length\n      threes = diffs & filter (==3) & length\n  in ones * (threes + 1)\n\n\nday10 ls =\n  let adapters = parse ls\n  in partA adapters\n\n{-\n--- Part Two ---\n\nTo completely determine whether you have enough adapters, you'll need to figure out how many different ways they can be arranged. Every arrangement needs to connect the charging outlet to your device. The previous rules about when adapters can successfully connect still apply.\n\nThe first example above (the one that starts with 16, 10, 15) supports the following arrangements:\n\n(0), 1, 4, 5, 6, 7, 10, 11, 12, 15, 16, 19, (22)\n(0), 1, 4, 5, 6, 7, 10, 12, 15, 16, 19, (22)\n(0), 1, 4, 5, 7, 10, 11, 12, 15, 16, 19, (22)\n(0), 1, 4, 5, 7, 10, 12, 15, 16, 19, (22)\n(0), 1, 4, 6, 7, 10, 11, 12, 15, 16, 19, (22)\n(0), 1, 4, 6, 7, 10, 12, 15, 16, 19, (22)\n(0), 1, 4, 7, 10, 11, 12, 15, 16, 19, (22)\n(0), 1, 4, 7, 10, 12, 15, 16, 19, (22)\n\n(The charging outlet and your device's built-in adapter are shown in parentheses.) Given the adapters from the first example, the total number of arrangements that connect the charging outlet to your device is 8.\n\nThe second example above (the one that starts with 28, 33, 18) has many arrangements. Here are a few:\n\n(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,\n32, 33, 34, 35, 38, 39, 42, 45, 46, 47, 48, 49, (52)\n\n(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,\n32, 33, 34, 35, 38, 39, 42, 45, 46, 47, 49, (52)\n\n(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,\n32, 33, 34, 35, 38, 39, 42, 45, 46, 48, 49, (52)\n\n(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,\n32, 33, 34, 35, 38, 39, 42, 45, 46, 49, (52)\n\n(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,\n32, 33, 34, 35, 38, 39, 42, 45, 47, 48, 49, (52)\n\n(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,\n46, 48, 49, (52)\n\n(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,\n46, 49, (52)\n\n(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,\n47, 48, 49, (52)\n\n(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,\n47, 49, (52)\n\n(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,\n48, 49, (52)\n\nIn total, this set of adapters can connect the charging outlet to your device in 19208 distinct arrangements.\n\nYou glance back down at your bag and try to remember why you brought so many adapters; there must be more than a trillion valid ways to arrange them! Surely, there must be an efficient way to count the arrangements.\n\nWhat is the total number of distinct ways you can arrange the adapters to connect the charging outlet to your device?\n-}\n\npartB ns =\n  let upper = maximum ns + 3\n      as = L.sort (0:upper:ns)\n      diffs = zipWith (-) (tail as) as\n      oneSeqs = splitOn [3] diffs\n      ways = map cnt oneSeqs\n  in product ways\n\ncnt [] = 1\ncnt (1:1:1:rest) = cnt (1:1:rest)    -- do 1:1:1:rest\n                 + cnt (1:rest)      -- 2:1:rest\n                 + cnt rest          -- 3:rest\ncnt (1:1:rest)   = cnt (1:rest)      -- 1:1:rest\n                 + cnt rest          -- 2:rest\ncnt (1:rest)     = cnt rest          -- 1:rest\n\n\ncnt' 0 = 1\ncnt' 1 = cnt' 0\ncnt' 2 = cnt' 1 + cnt' 0\ncnt' n = cnt' (n-1) + cnt' (n-2) + cnt' (n-3)\n\n\nday10b ls =\n  let as = parse ls\n  in partB as\n\n\n\n{-\nMatrix-wise:\n  let the counts for n-3, n-2, n-1 be in a 3x1 matrix\n  Then\n\n  (n-2|   = ( 0 1 0 |  ( n-3 |\n  |n-1|     | 0 0 1 |  | n-2 |\n  |n  )     | 1 1 1 )  | n-1 )\n\nBase case: (n=0, n=1, n=2) = (1 1 2)\nSo for n >= 3 we want\n\n  (n-2|  = ( 0 1 0 | ^ (n-2)  ( 1 |\n  |n-1|    | 0 0 1 |          | 1 |\n  | n )    | 1 1 1 )          | 2 )\n\nWe have\n\n\u03bb_1 = 1/3 (1 + (19 - 3 sqrt(33))^(1/3) + (19 + 3 sqrt(33))^(1/3))\n\u03bb_2 = 1/3 - 1/6 (1 + i sqrt(3)) (19 - 3 sqrt(33))^(1/3) - 1/6 (1 - i sqrt(3)) (19 + 3 sqrt(33))^(1/3)\n\u03bb_3 = 1/3 - 1/6 (1 - i sqrt(3)) (19 - 3 sqrt(33))^(1/3) - 1/6 (1 + i sqrt(3)) (19 + 3 sqrt(33))^(1/3)\n\nand eigenvectors\nv_1 = (1/3 (-1 - (4 2^(2/3))/(13 + 3 sqrt(33))^(1/3) + (2 (13 + 3 sqrt(33)))^(1/3)), 1/3 (-1 - 2/(17 + 3 sqrt(33))^(1/3) + (17 + 3 sqrt(33))^(1/3)), 1)\nv_2 = (-1/3 + (2 2^(2/3) (1 + i sqrt(3)))/(3 (13 + 3 sqrt(33))^(1/3)) - ((1 - i sqrt(3)) (13 + 3 sqrt(33))^(1/3))/(3 2^(2/3)), -1/3 + (1 - i sqrt(3))/(3 (17 + 3 sqrt(33))^(1/3)) - 1/6 (1 + i sqrt(3)) (17 + 3 sqrt(33))^(1/3), 1)\nv_3 = (-1/3 + (2 2^(2/3) (1 - i sqrt(3)))/(3 (13 + 3 sqrt(33))^(1/3)) - ((1 + i sqrt(3)) (13 + 3 sqrt(33))^(1/3))/(3 2^(2/3)), -1/3 + (1 + i sqrt(3))/(3 (17 + 3 sqrt(33))^(1/3)) - 1/6 (1 - i sqrt(3)) (17 + 3 sqrt(33))^(1/3), 1)\n-}\n\n-- M = S.J.S^(-1)\ntype C = Complex Double\ntype Mat = M.Matrix C\ns :: Mat\ns = M.fromList 3 3 [0.295598, (-0.647799) :+ (-1.72143), (-0.647799) :+ (1.72143),\n                    0.543689, (-0.771845) :+ (1.11514),  (-0.771845) :+ (-1.11514),\n                    1, 1, 1]\nj :: [C]\nj = [1.83929,\n              (-0.419643) :+ (-0.606291),\n                                          (-0.419643) :+ (0.606291)]\ns' :: Mat\ns' = M.fromList 3 3 [(0.336228) :+ (-2.81377e-18), (0.519032) :+ (-4.34358e-18), (0.61842) - (5.17532e-18),\n                     (-0.168114) :+ (0.198324), (-0.259516) :+ (-0.142222), (0.19079) :+ (0.0187006),\n                     (-0.168114) :+ (-0.198324), (-0.259516) :+ (0.142222), (0.19079) :+ (-0.0187006)]\n\npow n =\n  s `M.multStd2` j'' `M.multStd2` s'\n  where\n    j' :: [C]\n    j' = map (**n) j\n    j'' :: Mat\n    j'' = M.diagonalList 3 0 j'\n\ncnt'' 0 = 1\ncnt'' 1 = 1\ncnt'' 2 = 2\ncnt'' n =\n  let m = pow (n-2)\n      v = M.fromList 3 1 [1, 1, 2]\n      v' = m `M.multStd2` v\n  in  v' M.! (3, 1)\n\napprox :: Double -> C -> C -> Bool\napprox err a b = (realPart $ abs (a - b)) < err", "meta": {"hexsha": "8859cca3738f5ae885abf94d2838735da0270595", "size": 9816, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Day10.hs", "max_stars_repo_name": "jan-g/advent2020", "max_stars_repo_head_hexsha": "23951374cfd6cc2d658269cb1d4cdf9693ce51f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Day10.hs", "max_issues_repo_name": "jan-g/advent2020", "max_issues_repo_head_hexsha": "23951374cfd6cc2d658269cb1d4cdf9693ce51f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Day10.hs", "max_forks_repo_name": "jan-g/advent2020", "max_forks_repo_head_hexsha": "23951374cfd6cc2d658269cb1d4cdf9693ce51f9", "max_forks_repo_licenses": ["BSD-3-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.221402214, "max_line_length": 291, "alphanum_fraction": 0.6111450693, "num_tokens": 3906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.41635075426405155}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Math.Probably.NelderMead where\n\nimport Math.Probably.FoldingStats\n\nimport Data.Ord\nimport Data.List\nimport Data.Maybe\n\nimport Debug.Trace\n\nimport Foreign.Storable\n\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as L\n\n{-mean, m2 :: V.Vector Double\nmean = fromList [45.1,10.3]\n\ncov :: Matrix Double\ncov = (2><2) $ [5.0, 1,\n                1, 1.5]\n\ninvCov = inv cov\n\nlndet = log $ det cov\n\npdf = multiNormalByInv lndet invCov mean\n\nm2 = fromList [55.1,20.3]\n\nmain = runRIO $ do\n  io $ print $ pdf mean\n  ap <- nmAdaMet (defaultAM {nsam =1000000}) pdf (fromList [3.0,0.8])\n  {-iniampar <- sample $ initialAdaMet 500 5e-3 (pdf) $ fromList [30.0,8.0]\n  io $ print iniampar\n  froampar <- runAndDiscard 5000 (show . ampPar) iniampar $ adaMet False (pdf)\n  io $ print froampar\n  io $ print $ realToFrac (count_accept froampar) / (realToFrac $ count froampar) -}\n  let iniSim = genInitial (negate . pdf) 0.1 $ fromList [3.0,0.5]\n  io $ mapM_ print iniSim\n  let finalSim =  goNm (negate . pdf) 1 iniSim\n  io $ print $ finalSim\n  io $ print $ hessianFromSimplex (negate . pdf) finalSim -}\n\ntype Simplex = [(V.Vector Double, Double)]\n\n{-instance (Storable a, Num a) => Num (V.Vector a) where\n   (+) = V.zipWith (+)\n   (-) = V.zipWith (-)\n   (*) = V.zipWith (*) -}\n\nscale x = V.map (*x)\n\ncentroid :: Simplex -> V.Vector Double\ncentroid points = scale (recip l) $ sum $ map fst points\n    where l = fromIntegral $ length points\n\nnmAlpha = 1\nnmGamma = 2\nnmRho = 0.5\nnmSigma = 0.5\n\nsecondLast (x:y:[]) = x\nsecondLast (_:xs) = secondLast xs\n\nreplaceLast xs x = init xs ++ [x]\n\n{-hessianFromSimplex :: (V.Vector Double -> Double) -> [Int] -> [((Int, Int), Double)] -> Simplex -> (V.Vector Double, Matrix Double)\nhessianFromSimplex f isInt fixed sim = \n  let mat :: [V.Vector Double]\n      mat = toRows $ fromColumns $ map fst sim\n      fsw ((y0, ymin),ymax) = (y0, max (ymax-y0) (y0-ymin))\n      swings = flip map mat $ runStat (fmap fsw $ meanF `both` minFrom 1e80 `both` maxFrom (-1e80)) . toList \n      n = length swings\n      xv = fromList $ map fst swings\n      fxv = f  xv\n      fixedpts = map fst fixed\n      iswings i | i `elem` isInt = atLeastOne $snd $ swings!!i\n                | otherwise = snd $ swings!!i\n      funits d i | d/=i = 0\n                 | i `elem` isInt = atLeastOne $ snd $ swings!!i\n                 | otherwise = snd $ swings!!i \n      units = flip map [0..n-1] $ \\d -> V.generate n $ funits d\n      --http://www.caspur.it/risorse/softappl/doc/sas_docs/ormp/chap5/sect28.htm\n      fhess ij@ (i,j) | ij `elem` fixedpts = fromJust $ lookup ij fixed \n                      | i>=j = \n                         ((f $ xv + units!!i + units!!j)\n                          - (f $ xv + units!!i - units!!j)\n                          - (f $ xv - units!!i + units!!j)\n                          + (f $ xv - units!!i - units!!j) ) \n                          / (4*(iswings i) * (iswings j))\n                      | otherwise = 0.0    \n      hess1= buildMatrix n n fhess \n      hess2 = buildMatrix n n $ \\(i,j) ->if i>=j then hess1@@>(i,j) \n                                                 else hess1@@>(j,i) \n\n  -- we probably  ought to make pos-definite\n  -- http://www.mathworks.com/matlabcentral/newsreader/view_thread/103174\n  -- posdefify in R etc  \n  in (fromList (map (fst) swings), hess2) -}\n\natLeastOne :: Double -> Double\natLeastOne x | isNaN x || isInfinite x = 1.0\n             | x < -1.0 || x > 1.0 = realToFrac $ round x\n             | x < 0 = -1.0\n             | otherwise = 1.0\n\ngenInitial :: (V.Vector Double -> Double) -> [Int] -> (Int -> Double) -> V.Vector Double -> Simplex\ngenInitial f isInt h x0 = sim where\n  n = length $ V.toList x0\n  unit d = V.generate n $ \\j -> if j /=d then 0.0 else if d `elem` isInt then atLeastOne $ h j*(x0!d)\n                                                                          else h j*(x0!d)  \n  mkv d = with f $ x0 + unit d\n  sim = (x0, f x0) : map mkv [0..n-1] \n  (!) = (V.!)\n\ngoNm :: (V.Vector Double -> Double) -> [Int] -> Double -> Int -> Int -> Simplex -> Simplex\ngoNm f' isInt tol nmin nmax sim' = go f' 0 $ sortBy (comparing snd) sim'  where\n  go f i sim = let nsim = sortBy (comparing snd) $ (nmStep f isInt sim)\n                   fdiff = abs $ snd (last nsim) - snd (head nsim) \n               in case () of\n                      _ |  (fdiff < tol && i>nmin) || i>nmax -> nsim\n                        |  all (<0) (map snd sim) && any (>0) (map snd nsim) -> sim\n                        |  any (isNaN) (map snd nsim) -> sim\n                        |  otherwise   -> go f (i+1) nsim \n\ngoNmVerbose :: (V.Vector Double -> Double) -> [Int] -> Double -> Int -> Int -> Simplex -> Simplex\ngoNmVerbose f' isInt tol nmin nmax sim' = go f' 0 $ sortBy (comparing snd) sim' where\n  go f i sim = let nsim = sortBy (comparing snd) $ (nmStep f isInt sim)\n                   fdiff = trace (\"1: \"++ show (fst (head nsim)) ++ \"\\nlast: \"++ \n                                show (fst (last nsim)) ++ \"\\n#\"++show i++\": \"++\n                                show (map snd nsim)) \n                            abs $ snd (last nsim) - snd (head nsim) \n               in case () of\n                    _ |  (fdiff < tol && i>nmin) || i>nmax -> nsim\n                      |  all (<0) (map snd sim) && any (>0) (map snd nsim) -> sim\n                      |  any (isNaN) (map snd nsim) -> sim\n                      |  otherwise   -> go f (i+1) nsim\n  \n\nnmStep :: (V.Vector Double -> Double) -> [Int] -> Simplex -> Simplex\nnmStep f isInt s0 = snext where\n   x0 = centroid $ init s0\n   xnp1 = fst (last s0)\n   fxnp1 = snd (last s0)\n   xr = x0 + nmAlpha * (x0 - xnp1)\n   fxr = f xr\n   fx1 = snd $ head s0\n   snext = if fx1 <= fxr && fxr <= (snd $ secondLast s0)\n              then replaceLast s0 (xr,fxr)\n              else sexpand\n   xe = x0 + nmGamma * (x0-xnp1)\n   fxe = f xe\n   sexpand = if fxr > fx1\n                then scontract\n                else if fxe < fxr\n                        then replaceLast s0 (xe,fxe)\n                        else replaceLast s0 (xr,fxr)\n   xc = xnp1 + scale nmRho  (x0-xnp1)\n   fxc = f xc\n   scontract = if fxc < fxnp1\n                  then replaceLast s0 (xc,fxc)\n                  else sreduce\n   sreduce = case s0 of \n              p0@(x1,_):rest -> p0 : (flip map rest $ \\(xi,_) -> with f $ x1+ scale nmRho (xi-x1))\n\n   \nwith f x = (x, f x)\n", "meta": {"hexsha": "1bae42353c5b25d9b20b1a43ffe7cb405315afcf", "size": 6393, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/Probably/NelderMead.hs", "max_stars_repo_name": "glutamate/probably-base", "max_stars_repo_head_hexsha": "21f93c7391c6ec60795a0d920c1ea16d94a64d2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:20:01.000Z", "max_issues_repo_path": "Math/Probably/NelderMead.hs", "max_issues_repo_name": "glutamate/probably-base", "max_issues_repo_head_hexsha": "21f93c7391c6ec60795a0d920c1ea16d94a64d2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math/Probably/NelderMead.hs", "max_forks_repo_name": "glutamate/probably-base", "max_forks_repo_head_hexsha": "21f93c7391c6ec60795a0d920c1ea16d94a64d2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3859649123, "max_line_length": 133, "alphanum_fraction": 0.5257312686, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4161086264522747}}
{"text": "{-# LANGUAGE DataKinds                  #-}\n{-# LANGUAGE FlexibleContexts           #-}\n{-# LANGUAGE FlexibleInstances          #-}\n{-# LANGUAGE GADTs                      #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE PolyKinds                  #-}\n{-# LANGUAGE RankNTypes                 #-}\n{-# LANGUAGE ScopedTypeVariables        #-}\n{-# LANGUAGE StandaloneDeriving         #-}\n{-# LANGUAGE TypeApplications           #-}\n{-# LANGUAGE TypeFamilies               #-}\n{-# LANGUAGE TypeOperators              #-}\n{-# LANGUAGE TypeSynonymInstances       #-}\n{-# LANGUAGE UndecidableInstances       #-}\n\n{-\nA lot of error handling needs to be added to the code. For example\n0 < hopsize < windowsize < fftsize needs to be reinforced.\n-}\n\nmodule Lib.STFT where\n\nimport qualified Data.Complex                  as C\nimport           Data.Proxy\nimport           Data.Type.Equality\nimport qualified Data.Vector                   as V\nimport           GHC.TypeNats\nimport           Numeric.FFT.Vector.Invertible\n\n-- A small number\nepsilon :: Double\nepsilon = 2.2204460492503131e-16\n\n-- |The magnitude spectrum of a signal\nnewtype MagnitudeSpectrum = MkMag (V.Vector Double) deriving Show\n\n-- |The phase spectrum of a signal\nnewtype PhaseSpectrum = MkPhase (V.Vector Double) deriving Show\n\n-- |Tuple of magnitude and phase Spectrum\nnewtype Spectrums = MkSpect (MagnitudeSpectrum, PhaseSpectrum) deriving Show\n\n-- |A complex signal\nnewtype Signal = MkSignal (V.Vector (C.Complex Double))\n\n-- |A Window\nnewtype WindowFn n = Window { runWindow :: Winsz n -> V.Vector (C.Complex Double) }\n\ntype family IsPo2 (m :: Nat) :: Bool where\n  IsPo2 n = 2 ^ Log2 n == n\n\ndata FFTsz n where\n  MkFFTsz :: (KnownNat n, IsPo2 n ~ 'True) => Proxy n -> FFTsz n\n\ndata Winsz n where\n  MkWinsz :: KnownNat n => Proxy n -> Winsz n\n\ndata Hopsz n where\n  MkHopsz :: KnownNat n => Proxy n -> Hopsz n\n\ndata Config h w f where\n  MkConfig :: forall h w f. (KnownNat f, KnownNat w, KnownNat h, h <= w, w <= f) => Hopsz h -> Winsz w -> FFTsz f -> Config h w f\n\nconfig :: Config 256 2048 2048\nconfig = MkConfig hop win fft where\n  hop = (MkHopsz (Proxy @256))\n  win = (MkWinsz (Proxy @2048))\n  fft = (MkFFTsz (Proxy @2048))\n\n\nhamming :: forall n. KnownNat n => WindowFn n\nhamming = Window $ \\(MkWinsz _) -> V.generate size goHamm\n  where\n    size = fromIntegral $ natVal (Proxy @n) :: Int\n    goHamm :: Int -> C.Complex Double\n    goHamm i = (C.:+ 0) $ 0.54 - 0.46 * cos (2 * pi * fromIntegral i / (fromIntegral size - 1))\n\n-- |Phase unwrapping algorithm. Converting to and from list for pattern matching is a little cumbersome.\nunwrapPhase :: PhaseSpectrum -> PhaseSpectrum\nunwrapPhase (MkPhase xs) = MkPhase $ V.fromList $ (diff (V.toList xs) 0)\n  where\n    diff (x:y:ys) accm\n      | (y+accm) - x > pi    = x: diff (y + accm - (2 * pi):ys) (accm-(2*pi))\n      | (y+accm) - x < (-pi) = x: diff (y+accm+(2*pi):ys) (accm+(2*pi))\n      | otherwise             = x: diff (y+accm:ys) accm\n    diff [x] _     = [x]\n    diff []  _     = []\n\nhalfInt, halfIntPlus :: Int -> Int\nhalfIntPlus win = (win + 1) `div` 2\nhalfInt win = win `div` 2\n\n-- |Takes a complex signal and fftsz performs the zero phase windowing\n-- https://ccrma.stanford.edu/~jos/sasp/Zero_Phase_Zero_Padding.html\nzeroPhaseZeroPad :: forall n. KnownNat n => FFTsz n -> Signal -> Signal\nzeroPhaseZeroPad _ (MkSignal sig) = MkSignal $ positive V.++ zeros V.++ negative\n  where\n    fftsz = fromIntegral $ natVal (Proxy @n)\n    win = V.length sig\n    halfSig = halfInt win\n    halfSigPlus = halfIntPlus win\n    positive = V.slice halfSig halfSigPlus sig\n    negative = V.slice 0 halfSig sig\n    zeros = V.replicate (fftsz - halfSig - halfSigPlus) (0 C.:+ 0)\n\nnearZero :: Double -> Bool\nnearZero a = abs a <= 1e-12\n\n-- |Calculates the magnitude spectrum in Db\nmagSpect :: Signal -> MagnitudeSpectrum\nmagSpect (MkSignal sig) = MkMag $ V.map (dB. near0 . C.magnitude) sig\n  where\n    dB x = 20 * logBase 10 x\n    near0 x = if nearZero x then epsilon else x\n\n\n-- |Calculates the phase spectrum\nphaseSpect :: Signal -> PhaseSpectrum\nphaseSpect (MkSignal vec) = unwrapPhase $ MkPhase $ V.map (C.phase . to0) vec\n  where\n    to0 x = go (C.realPart x) (C.imagPart x)\n    go x y | nearZero x && nearZero y = 0 C.:+ 0\n           | nearZero x               = 0 C.:+ y\n           | nearZero y               = x C.:+ 0\n           | otherwise                = x C.:+ y\n\n-- | Takes a windowed signal and FFT size returns a the\n-- magnitude and phase spectrums. Magnitude in Db, phase unwrapped,\n-- both positive halfs of the spectrums\ndftAnal :: forall n. KnownNat n => FFTsz n -> Signal -> Spectrums\ndftAnal fftsz sig = MkSpect (magSpect trsf, phaseSpect trsf)\n  where\n      (MkSignal inputVec) = zeroPhaseZeroPad fftsz sig\n      -- ^Positive spectrum includes sample 0\n      positiveSpect = ((fromIntegral $ natVal (Proxy @n)) `div` 2) + 1\n      trsf = MkSignal $ V.slice 0 positiveSpect (run dft inputVec)\n\n-- | Splits the vector into chunks of size n that are\n-- m distance apart. Static check that chunksize is larger than hop sz.\ndivvy :: forall n m a. (KnownNat n, KnownNat m) => Winsz n\n      -> Hopsz m -> V.Vector a -> [V.Vector a]\ndivvy _ _ = go n' m'\n  where\n    n' = fromIntegral $ natVal (Proxy :: Proxy n)\n    m' = fromIntegral $ natVal (Proxy :: Proxy m)\n\n    go :: Int -> Int -> V.Vector a -> [V.Vector a]\n    go x y vec\n      | V.length vec <= x = []\n      | otherwise = V.take x vec : go x y (V.drop y vec)\n\nnormalize :: Fractional a => V.Vector a -> V.Vector a\nnormalize win = fmap (/ V.foldl1' (+) win) win\n\n-- | Takes an input signal, a window, an fftsize and a hop size and\n-- computes the short time Fourier transform, returning a list of\n-- magnitude and phase spectrums.\nstft :: forall h w f. (KnownNat h, KnownNat w, KnownNat f) => Config h w f -> Signal\n     -> [Spectrums]\nstft (MkConfig hopsz winsz fftsz) (MkSignal sig) = fmap winDFT splitSig\n  where\n    win = runWindow hamming winsz\n    halfWindow = floor (fromIntegral (natVal (Proxy @w)) / 2 :: Double)\n    zs = V.replicate halfWindow (0 C.:+ 0)\n    sigzs = zs V.++ sig V.++ zs\n    splitSig = divvy winsz hopsz sigzs\n\n    winDFT :: V.Vector (C.Complex Double) -> Spectrums\n    winDFT vec = dftAnal fftsz (MkSignal $ V.zipWith (*) vec (normalize win))\n\n\n-- Takes a tuple of vectors (Magnitude, Phase) and a window size\n-- and returns the original signal\ndftSynth :: forall n. KnownNat n => Winsz n\n         -> Spectrums -> V.Vector (C.Complex Double)\ndftSynth _ (MkSpect (MkMag magVec, MkPhase phaseVec)) =\n  let win = fromIntegral $ natVal (Proxy @n)\n      hwin = halfInt win\n      hwinp = halfIntPlus win\n      vec = V.zipWith (\\x y -> (x, y)) magVec phaseVec\n      posFreqs = fmap f vec where\n        f (mag, phase) = (10**(mag/20) C.:+ 0) *\n                         exp ((phase C.:+ 0) *\n                         (0 C.:+ 1))\n      negFreqs = (fmap f . V.reverse) (g vec) where\n        g = (V.init . V.tail)\n        f (mag, phase) = (10**(mag/20) C.:+ 0) *\n                         exp ((phase C.:+ 0) *\n                         (0 C.:+ (-1)))\n      resultidft = run idft (posFreqs V.++ negFreqs)\n  in V.slice (V.length resultidft - hwin)\n                    hwin resultidft V.++ V.take hwinp resultidft\n\n\nstftSynth :: forall h w. (KnownNat h, KnownNat w) => [Spectrums]\n          -> Hopsz h -> Winsz w -> Signal\nstftSynth magphase _ winsz =\n  let hwinp = halfIntPlus $ fromIntegral $ natVal (Proxy @w)\n      signalFrames = fmap (fmap (fromIntegral (natVal (Proxy @h)) * ) . dftSynth winsz ) magphase\n      signalTuples = fmap (V.splitAt hwinp) signalFrames\n      overlapAdd (x1, x2) (y1, y2) = (x1 V.++ V.zipWith (+) x2 y1, y2)\n   in MkSignal $ V.drop hwinp $ fst (foldl overlapAdd (Prelude.head signalTuples) (Prelude.tail signalTuples))\n\n\n", "meta": {"hexsha": "e978d64ea07defb64479007aa3a6a169537d2ebd", "size": 7743, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/lib/STFT.hs", "max_stars_repo_name": "davlum/haskell-twm", "max_stars_repo_head_hexsha": "2e407d6f8b28aafa889ea3c1b134c8cb41803f1c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-19T08:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T07:13:22.000Z", "max_issues_repo_path": "src/lib/STFT.hs", "max_issues_repo_name": "davlum/haskell-twm", "max_issues_repo_head_hexsha": "2e407d6f8b28aafa889ea3c1b134c8cb41803f1c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/STFT.hs", "max_forks_repo_name": "davlum/haskell-twm", "max_forks_repo_head_hexsha": "2e407d6f8b28aafa889ea3c1b134c8cb41803f1c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7707317073, "max_line_length": 129, "alphanum_fraction": 0.6200439106, "num_tokens": 2363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4159765674053582}}
{"text": "import Control.Monad (liftM)\nimport Control.Parallel\nimport Data.Binary.Get (runGet)\nimport Graphics.Rendering.Cairo hiding (Matrix)\nimport Numeric.LinearAlgebra\nimport System.Random (mkStdGen, randoms)\nimport qualified Data.ByteString.Lazy as BS\nimport Gradient\nimport BinaryExtras\nimport RandomExtras\nimport Types\nimport Unsafe.Coerce\nimport GHC.Float\nimport Data.Binary.Get\nimport Data.Int\nimport Data.Word\n\nopts = morrowind\n\nmain = do\n  contents <- BS.readFile $ inputFile opts\n  let arr0 = runGet (getManyF (rawFunction opts) $ imageWidth opts*imageHeight opts) contents\n  let landscape = (imageHeight opts><imageWidth opts) $ arr0\n--  landscape <- liftM ((imageHeight opts><imageWidth opts) . runGet (getAll $ imageWidth opts*imageHeight opts)) $ BS.readFile $ inputFile opts\n  let jitter = randoms $ mkStdGen 53\n  let [miny, maxy, minx, maxx] = map fromIntegral [1, imageHeight opts-2, 1, imageWidth opts-2]\n  let (numpointsy, numpointsx) = (floor $ (maxy-miny)/(gridWidth opts), floor $ (maxx-minx)/(gridWidth opts))\n  let regulargrid = [(y,x) | y <- [0..numpointsy-1], x<-[0..numpointsx-1]]\n  let jitteredgrid = zipWith (\\(y,x) (jy,jx) -> \n        ( miny + (gridWidth opts)* (fromIntegral y + jy)\n        , minx + (gridWidth opts) * (fromIntegral x + jx)\n        )) regulargrid jitter\n  let ascents = map (gradientStepper Ascent (ascentDelta opts) landscape) jitteredgrid\n  s <- createImageSurface FormatARGB32 \n    (floor $ multiplier opts * (fromIntegral $ imageWidth opts)) \n    (floor $ multiplier opts * (fromIntegral $ imageHeight opts))\n  renderWith s $ do\n    setSourceRGBA 1 1 1 0.0\n    paint\n  mapM_ (drawLine (lineWidth opts) (cellWidth opts) (multiplier opts) s) ascents\n  surfaceWriteToPNG s $ outputFile opts\n\ndrawLine line cell mult s lista = do\n  renderWith s $ do\n    setLineWidth line\n    setLineCap LineCapRound\n    go lista\n  where\n  go ((x1,y1,z1):loput@((x2,y2,z2):_)) = do\n    let c = 1.0 - ((atan2 (abs(z1-z2)) cell)/(pi/2)) in setSourceRGB c c c\n    moveTo (x1*mult) (y1*mult)\n    lineTo (x2*mult) (y2*mult)\n    stroke\n    go loput\n  go _ = return ()\n\n-- Example usage\n\nmorrowind = Options\n  { inputFile = \"tesannwyn.raw\"\n  , imageWidth = 2688\n  , imageHeight = 2816\n  , gridWidth = 2.5\n  , multiplier = 1.0\n  , ascentDelta = 1.0\n  , outputFile = \"vv.png\"\n  , lineWidth = 0.35\n  , cellWidth = 8.0\n  , rawFunction = liftM ((fromIntegral :: Int16 -> Double) . (fromIntegral :: Word16 -> Int16)) getWord16le\n  }\n\noblivion = Options\n  { inputFile = \"oblivion.raw\"\n  , imageWidth = 4288\n  , imageHeight = 4128\n  , gridWidth = 5\n  , multiplier = 1.0\n  , ascentDelta = 2.0\n  , outputFile = \"obl.png\"\n  , lineWidth = 0.5\n  , cellWidth = 8.0\n  , rawFunction = liftM ((fromIntegral :: Int16 -> Double) . (fromIntegral :: Word16 -> Int16)) getWord16le\n  }\n\nseworld = Options\n  { inputFile = \"seworld.raw\"\n  , imageWidth = 2048\n  , imageHeight = 2048\n  , gridWidth = 2.5\n  , multiplier = 1.0\n  , ascentDelta = 1.0\n  , outputFile = \"se.png\"\n  , lineWidth = 0.3\n  , cellWidth = 8.0\n  , rawFunction = liftM ((fromIntegral :: Int16 -> Double) . (fromIntegral :: Word16 -> Int16)) getWord16le\n  }\n\nmokki = Options\n  { inputFile = \"2mdem.flt\"\n  , imageWidth = 1857\n  , imageHeight = 2136\n  , gridWidth = 12.5\n  , multiplier = 1.5\n  , ascentDelta = 2.0\n  , outputFile = \"mok.png\"\n  , lineWidth = 0.5\n  , cellWidth = 0.125\n  , rawFunction = liftM (float2Double . unsafeCoerce) getWord32le\n  }\n\nturku = Options\n  { inputFile = \"pohja\"\n  , imageWidth = 513\n  , imageHeight = 513\n  , gridWidth = 1.25\n  , multiplier = 2\n  , ascentDelta = 1.0\n  , outputFile = \"turku.png\"\n  , lineWidth = 0.5\n  , cellWidth = 8\n  , rawFunction = liftM ((fromIntegral :: Int16 -> Double) . (fromIntegral :: Word16 -> Int16)) getWord16le\n  }\n\n", "meta": {"hexsha": "463eae3bde5fc5d8abac32c1b2afdb2c99820552", "size": 3733, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "hachuremap.hs", "max_stars_repo_name": "angs/Hachure-map", "max_stars_repo_head_hexsha": "1d06afe230e9321271c9d12a257bc9254b3d68f8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hachuremap.hs", "max_issues_repo_name": "angs/Hachure-map", "max_issues_repo_head_hexsha": "1d06afe230e9321271c9d12a257bc9254b3d68f8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hachuremap.hs", "max_forks_repo_name": "angs/Hachure-map", "max_forks_repo_head_hexsha": "1d06afe230e9321271c9d12a257bc9254b3d68f8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1048387097, "max_line_length": 144, "alphanum_fraction": 0.6702384141, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4157576503936006}}
{"text": "module Parser where\n\nimport Data.Ratio\nimport Data.Complex\n\nimport Number\nimport LispData\nimport Text.ParserCombinators.Parsec hiding (spaces)\nimport Text.Parsec.Number\n\n\nimport LispData\n--TODO Learn monads again and check what mapM is doing\n\n-- Recognizes if a character is a valid scheme symbol\nsymbol :: Parser Char\nsymbol = oneOf \"-.!#$%&|*+/:<=>?@^_~\"\n-- Skips one or more spaces\nspaces1 :: Parser ()\nspaces1 = skipMany1 space\n\nescapedChars :: Parser Char\nescapedChars = do\n  _ <- char '\\\\'\n  x <- oneOf \"\\\"tn\\\\\"\n  case x of\n    't' -> return '\\t'\n    'n' -> return '\\n'\n    'r' -> return '\\r'\n    '\\\\' -> return '\\\\'\n    _ -> return x\n\n-- Parses a string which starts with a \" and ends with a\"\n-- TODO \\\\t \\\\n \\\\r \\\\ \\\"\nparseString :: Parser LispVal\nparseString = do\n  _ <- char '\"' --Starts with a \"\n  -- Stops at \"\n  x <- many $ escapedChars <|> noneOf \"\\\"\"\n  _ <- char '\"' --ends with a \"\n  return $ String x\n\n-- Parses a symbol\nparseAtom :: Parser LispVal\nparseAtom = do\n  first <- (letter <|> symbol) <?> \"I HATE PARSEC\"\n  --first <- choice symlpars\n  --the following chars must be one of letter, digit or symbol\n  rest <-  many (letter <|> digit <|> symbol)\n  let atom = first :rest\n  --catch special atoms\n  case atom of \"#t\" -> return $ Bool True\n               \"#f\" -> return $ Bool False\n               ('-':x:_)   -> case x of\n                   ' ' -> return $ Atom atom\n                   _   -> parseNumber\n                             --return $ (LispNumber . Integer . read) atom --TODO THIS IS NOT GOOD, try to parse -3o\n               _    -> {-trace (\"attom\"++ show atom)-} (return $ Atom atom)\n\nparseComplex :: Parser LispVal\nparseComplex = do\n  f <- parseNumber\n  s <- char '+'\n  n <- parseNumber\n  i <- char 'i' \n  let x = case f of\n        ((LispNumber (Integer n))) -> (fromIntegral n :: Double)\n        ((LispNumber (Rational n))) -> (realToFrac n)\n        ((LispNumber (Real n))) -> n\n        _ -> 0\n\n  let y = case n of\n        ((LispNumber (Integer p))) -> (fromIntegral p :: Double)\n        ((LispNumber (Rational p))) -> (realToFrac p)\n        ((LispNumber (Real p))) -> p\n        _ -> 0\n  return $ (LispNumber . Complex) (x :+ y)\n\nparseNegFloat :: Parser LispVal\nparseNegFloat = do\n  s <-  sign\n  beforeDot <- int\n  _ <- char '.' <?> \"Floating Point Parse Error: expecting .\"\n  afterDot <- int\n  let d = s (read (show beforeDot ++ \".\" ++ (show afterDot)))\n  return $ (LispNumber . Real) d\n\nparseNegRational :: Parser LispVal\nparseNegRational = do\n  top <- int\n  _ <- char '/'\n  bottom <- int\n  return $ (LispNumber . Rational) (top % bottom)\n\nparseInteger :: Parser LispVal\nparseInteger =  do\n  int' <- many1 digit\n  return $ (LispNumber . Integer . read) int'\n\nparseNegInteger :: Parser LispVal\nparseNegInteger =  do\n  _ <-  char '-'\n  int' <- many1 digit\n  return $ (LispNumber . Integer . negate . read) int'\n\nparseVector :: Parser LispVal\nparseVector = do\n  _ <- char '('\n  vec <- sepBy parseExpr spaces1\n  _ <- char ')'\n  return $ Vector vec\n\nparseList :: Parser LispVal\n-- Parse lispExpr which hare seperated by one or more whitespace\nparseList = List <$> sepBy parseExpr spaces1\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n    -- what?\n    head' <- endBy parseExpr spaces1\n    -- parses a dot then exactly one space and saves the expression after the space\n    tail' <- char '.' >> spaces1 >> parseExpr\n    return $ DottedList head' tail'\n\n-- TODO READ r5rs\nparseQuoted :: Parser LispVal\nparseQuoted = do\n    _ <- char '\\''\n    x <- parseExpr\n    return $ List [Atom \"quote\", x]\n\nparseNumber = try parseNegFloat\n              <|> try parseNegRational\n              <|> try parseNegInteger --TODO WENN MIR WAS UM DIE OHREN FLIEGT LIEGTS HIER DRAN\n              <|> parseInteger -- etc\n\nparseExpr :: Parser LispVal\nparseExpr = try parseAtom --first try to parse a atom\n         <|> try parseComplex\n         <|> parseNumber\n         <|> parseString -- if this fails try to parse a string\n         <|> parseQuoted\n         <|> do _ <- char '('\n                -- parses a normal list until it encounter a dot, at which point it will go back and sstart to parse\n                -- a dotted list\n                x <- try parseList <|> parseDottedList\n                _ <- char ')'\n                return x\n", "meta": {"hexsha": "0d4dd54c0e8c1941af27e0f42dd8108cfd54cdbb", "size": 4257, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Parser.hs", "max_stars_repo_name": "Unaimend/schemehs", "max_stars_repo_head_hexsha": "f4b38bc81f2ff8b0d62818b660577a5eee7d11ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Parser.hs", "max_issues_repo_name": "Unaimend/schemehs", "max_issues_repo_head_hexsha": "f4b38bc81f2ff8b0d62818b660577a5eee7d11ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2020-02-06T13:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-14T09:50:19.000Z", "max_forks_repo_path": "src/Parser.hs", "max_forks_repo_name": "Unaimend/schemehs", "max_forks_repo_head_hexsha": "f4b38bc81f2ff8b0d62818b660577a5eee7d11ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5704697987, "max_line_length": 116, "alphanum_fraction": 0.5954897815, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.41552525927489664}}
{"text": "{-# OPTIONS_GHC  -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}\n{-# LANGUAGE FlexibleInstances, ConstraintKinds, ExistentialQuantification, GADTs, RankNTypes, MultiParamTypeClasses   #-}\n{-# LANGUAGE ImpredicativeTypes, RankNTypes, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}\n\n\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n-- | \n-- | Module : Count-Min Sketch\n-- | Creator: Xiao Ling\n-- | Created: 12/17/2015\n-- |\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n\nmodule CountMinSketch where\n\nimport Control.Monad.Random.Class\nimport Control.Monad.Random\nimport Control.Monad.State\nimport Control.Monad.Reader\nimport Control.Monad.Identity\n\nimport Data.Matrix\nimport Data.Conduit\nimport qualified Data.Conduit.List as Cl\nimport qualified Data.Matrix as M\n\nimport Core\nimport Utils\nimport Statistics\n\n\n{-----------------------------------------------------------------------------\n  Types \n------------------------------------------------------------------------------}\n\ntype W        = Int              -- * num cols\ntype D        = Int              -- * num rows\ntype P        = Int              -- * some prime   --> change this to Integer\ntype A        = Int              -- * coefficient a_j\ntype B        = Int              -- * coeeficient b_j\ntype Event    = Int              -- * some input event from\n                                 -- * universe: {1, .., i, .. n}\n\n\ntype Sketch   = Matrix Int       -- * W x D matrix  of counters\ntype ABs      = Matrix Int       -- * 2 x D matrix  of a_j and b_j for j = 1..d\ntype Events   = Matrix Event     -- * 2 x D matrix of event i \ntype Hash     = Event -> ColIdx  -- * Maps event to d x 1 list of index to incr\ntype ColIdx   = [Int]            -- * indices of counters to increment\n\ntype Some m   = (MonadRandom m, MonadState (Sketch, Hash) m, MonadReader (D,W,P) m)\n\n{-----------------------------------------------------------------------------\n    Count Min Sketch\n------------------------------------------------------------------------------}\n\n\n\n{-----------------------------------------------------------------------------\n    Helpers\n------------------------------------------------------------------------------}\n\n-- * initalize the sketch\nsketch' :: D -> W -> Sketch\nsketch' = zeros\n\n-- * intialize random cofficients a_j, b_j, for d x 2 matrix: \n-- * [ a_1 ... a_j ... a_d ]\n-- * [ b_1 ... b_j ... b_d ]\nab' :: MonadRandom m => P -> D -> m ABs\nab' p d = (M.fromList 2 d . take (2*d)) <$> getRandomRs (1,p)\n\n-- * h_j (i) = (a_j x i + b_j mod p) mod w\n-- * sumRow-wise  [ a_1 ... a_j ... a_d ]  .*.  [ i_1 ...  i_d ]     mod p  mod w\n-- *              [ b_1 ... b_j ... b_d ]       [ 1   ...  1   ]\n-- * result:      [ idx_1, ..., idx_d   ]\n-- *               where the indices start at 1\nhash' :: P -> W -> D -> ABs -> Hash\nhash' p w d ab = \\i ->  go $ sumR (ab .*. is) ... (\\v -> v `mod` p `mod` w)\n    where go = fmap (+1) . toList\n          is = is' d i\n\n-- * map `i` <- event univese onto d x 2 matrix of form\n-- * [ i_1 ... i_2 ]\n-- * [ 1   ...  1  ]\nis' :: D -> Event -> Events\nis' d i = (i .+ (zeros 1 d)) <-> ones 1 d\n\n\n-- * given hash function, construct a binary mask of size `w` x `d`\n-- * to increment sketch\nmask' :: W -> ColIdx -> Sketch\nmask' w ks = let vec c w = zeros 1 (c-1) <|> single 1 <|> zeros 1 (w - c) in\n    case ks of\n        c:[] -> vec c w\n        c:cs -> vec c w <-> mask' w cs\n\n\n-- * given input i and some hash function `h`, and sketch `ms`, \n-- * update `ms`\nupdate' :: W -> D -> Hash -> Sketch -> Event -> Sketch\nupdate' w d h ms i = mask' w (h i) .+. ms\n\n\n\nmaxi  = 30            :: Event\np     = 2^maxi - 1    :: P \n(d,w) = (4,3)         :: (D,W)\ni     = 12            :: Event\n\n\nmab    = evalRandIO $ ab' p d\nsketch = sketch' d w\nmhashs = (hash' p w d)  <$> mab\n\nupdate h i = update' w d h sketch i\n\nmhash  = head <$> mhashs\n\n\n\n--hs = hashF p w xs ys\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "4dcc0dd14ed5b1fc6f38bcc10a72f87dd5250589", "size": 4252, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "depricated/CountMinSketch2.hs", "max_stars_repo_name": "lingxiao/CIS700", "max_stars_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "depricated/CountMinSketch2.hs", "max_issues_repo_name": "lingxiao/CIS700", "max_issues_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "depricated/CountMinSketch2.hs", "max_forks_repo_name": "lingxiao/CIS700", "max_forks_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9436619718, "max_line_length": 122, "alphanum_fraction": 0.4346190028, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.41548913349681527}}
{"text": "{-# OPTIONS_GHC -Wno-incomplete-patterns #-}\nmodule Simulation where\n\nimport AmpOp\n    ( SignalState(..),\n      State(TwoNodes),\n      Output,\n      Value,\n      dc100,\n      dc12,\n      sen,\n      ground,\n      getSignalOutput,\n      lm741,\n      r1,\n      r2,\n      r3,\n      r4,\n      -- ampOpSpecial,\n      ampOpBuffer,\n      ampOpInverting,\n      ampOpInvertingTest,\n      ampOpInverting' )\nimport Circuit\nimport Signal\nimport Control.Monad.Fix\nimport Data.Complex\n\nexecuteTimeSimulation :: SignalState -> (SignalState -> Either String (Circuit a SignalState)) -> Signal a -> [Metric] -> Either String [(Time, Value)]\nexecuteTimeSimulation _ _ _ [] = Right []\nexecuteTimeSimulation initialState buildCircuit input (t:ts) = buildCircuit initialState >>= \\circuit -> do let result = circuit `simulate` input `at` t\n                                                                                                            rest <- executeTimeSimulation result buildCircuit input ts\n                                                                                                            Right $ (realPart t, realPart (getSignalOutput result `at` t)) : rest\n\nexecuteTimeSimulation2 :: SignalState -> (SignalState -> Circuit a SignalState) -> Signal a -> [Metric] -> [(Metric, Output)]\nexecuteTimeSimulation2 initialState buildCircuit input samples = fix calculate (initialState, [], samples)\n    where calculate f (state, l, t:ts) = if null ts then next else f (newState, next, ts)\n            where newState = buildCircuit state `simulate` input `at` t\n                  next = l ++ [result]\n                  result = (t, getSignalOutput newState `at` t)\n\niSignalState = SignalTwoNodes (dc100, ground)\niSignalState3 = SignalThreeNodes (dc100, dc100, dc100)\niSignalBuffer = SignalOneNode dc100\nc0 = ampOpBuffer lm741\nc1 = ampOpInverting lm741 r1 r2\nc3 = ampOpInvertingTest lm741 r1 r2\n-- cS = ampOpSpecial lm741 r1 r2 r3 r4\n\nsimulationSignal = executeTimeSimulation iSignalState c1 sen (map (:+ 0) [1..5])\nsimulationSignalTest = executeTimeSimulation2 iSignalState c3 sen (map (:+ 0) [1..5])\n-- simulationSpecial = executeTimeSimulation iSignalState3 cS dc12 (map (:+ 0) [1])\n\niState = TwoNodes (100, 0)\nc2 = ampOpInverting' lm741 r1 r2 12\n\nsimulation = c2 iState\n", "meta": {"hexsha": "da96c5c10a4916b66280ddb0e7ad4fffd7b9730c", "size": 2270, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Simulation.hs", "max_stars_repo_name": "FP-Modeling/fixingAnalog", "max_stars_repo_head_hexsha": "d86d80210d3c759f6e4041eb1f3b5b75c4589880", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Simulation.hs", "max_issues_repo_name": "FP-Modeling/fixingAnalog", "max_issues_repo_head_hexsha": "d86d80210d3c759f6e4041eb1f3b5b75c4589880", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Simulation.hs", "max_forks_repo_name": "FP-Modeling/fixingAnalog", "max_forks_repo_head_hexsha": "d86d80210d3c759f6e4041eb1f3b5b75c4589880", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1379310345, "max_line_length": 177, "alphanum_fraction": 0.6251101322, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4148479135298332}}
{"text": "module Numeric.FFT.Special.Primes\n       ( special3, special5, special7, special11, special13 ) where\n\nimport           Control.Monad.ST\nimport           Data.Complex\nimport qualified Data.Vector.Unboxed.Mutable as MV\n\nimport           Numeric.FFT.Types\n\n\n-- | Length 3 hard-coded FFT.\nkp500000000, kp866025403 :: Double\nkp866025403 = 0.866025403784438646763723170752936183471402627\nkp500000000 = 0.500000000000000000000000000000000000000000000\nspecial3 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial3 sign xsin xsout = do\n  xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n  xr2 :+ xi2 <- MV.unsafeRead xsin 2\n  let rp = xr1 + xr2 ; rm = xr1 - xr2\n      ip = xi1 + xi2 ; im = xi1 - xi2\n      tr = xr0 - kp500000000 * rp\n      ti = xi0 - kp500000000 * ip\n      r1 = (tr - kp866025403 * im) :+ (ti + kp866025403 * rm)\n      r2 = (tr + kp866025403 * im) :+ (ti - kp866025403 * rm)\n  MV.unsafeWrite xsout 0 $ (xr0 + rp) :+ (xi0 + ip)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r2\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r1\n\n-- | Length 5 hard-coded FFT.\nkp951056516, kp559016994, kp250000000, kp618033988 :: Double\nkp951056516 = 0.951056516295153572116439333379382143405698634\nkp559016994 = 0.559016994374947424102293417182819058860154590\nkp250000000 = 0.250000000000000000000000000000000000000000000\nkp618033988 = 0.618033988749894848204586834365638117720309180\nspecial5 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial5 sign xsin xsout = do\n  xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n  xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n  xr4 :+ xi4 <- MV.unsafeRead xsin 4\n  let ts = xr1 - xr4 ; t4 = xr1 + xr4 ; tt = xr2 - xr3 ; t7 = xr2 + xr3\n      t8 = t4 + t7 ; ta = t4 - t7 ; te = xi1 - xi4 ; tm = xi1 + xi4\n      tn = xi2 + xi3 ; th = xi2 - xi3 ; to = tm + tn ; tq = tm - tn\n      ti = te + kp618033988 * th ; tk = th - kp618033988 * te\n      t9 = xr0 - kp250000000 * t8 ; tu = ts + kp618033988 * tt\n      tw = tt - kp618033988 * ts ; tp = xi0 - kp250000000 * to\n      tb = t9 + kp559016994 * ta ; tj = t9 - kp559016994 * ta\n      tr = tp + kp559016994 * tq ; tv = tp - kp559016994 * tq\n      r4 = (tb + kp951056516 * ti) :+ (tr - kp951056516 * tu)\n      r3 = (tj - kp951056516 * tk) :+ (tv + kp951056516 * tw)\n      r2 = (tj + kp951056516 * tk) :+ (tv - kp951056516 * tw)\n      r1 = (tb - kp951056516 * ti) :+ (tr + kp951056516 * tu)\n  MV.unsafeWrite xsout 0 $ (xr0 + t8) :+ (xi0 + to)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r4\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r3\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r2\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r1\n\n-- | Length 7 hard-coded FFT.\nkp974927912, kp900968867, kp801937735 :: Double\nkp692021471, kp356895867, kp554958132 :: Double\nkp974927912 = 0.974927912181823607018131682993931217232785801\nkp900968867 = 0.900968867902419126236102319507445051165919162\nkp801937735 = 0.801937735804838252472204639014890102331838324\nkp692021471 = 0.692021471630095869627814897002069140197260599\nkp356895867 = 0.356895867892209443894399510021300583399127187\nkp554958132 = 0.554958132087371191422194871006410481067288862\nspecial7 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial7 sign xsin xsout = do\n  xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n  xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n  xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n  xr6 :+ xi6 <- MV.unsafeRead xsin 6\n  let tI = xr6 - xr1 ; t4 = xr1 + xr6 ; tG = xr4 - xr3 ; ta = xr3 + xr4\n      tT = tI + kp554958132 * tG ; tp = ta - kp356895867 * t4\n      tH = xr5 - xr2 ; t7 = xr2 + xr5\n      tJ = tH - kp554958132 * tI ; tO = tG + kp554958132 * tH\n      tu = t7 - kp356895867 * ta ; tb = t4 - kp356895867 * t7\n      tB = xi2 + xi5 ; tg = xi2 - xi5\n      tC = xi3 + xi4 ; tm = xi3 - xi4 ; tA = xi1 + xi6 ; tj = xi1 - xi6\n      tD = tB - kp356895867 * tC ; ts = tm + kp554958132 * tg\n      tL = tC - kp356895867 * tA ; tQ = tA - kp356895867 * tB\n      tx = tg - kp554958132 * tj ; tn = tj + kp554958132 * tm\n      tc = ta - kp692021471 * tb ; tU = tH + kp801937735 * tT\n      to = tg + kp801937735 * tn ; tR = tC - kp692021471 * tQ\n      td = xr0 - kp900968867 * tc ; tt = tj - kp801937735 * ts\n      tq = t7 - kp692021471 * tp ; tS = xi0 - kp900968867 * tR\n      tr = xr0 - kp900968867 * tq ; tP = tI - kp801937735 * tO\n      tM = tB - kp692021471 * tL ; ty = tm - kp801937735 * tx\n      tv = t4 - kp692021471 * tu ; tK = tG - kp801937735 * tJ\n      tN = xi0 - kp900968867 * tM ; tE = tA - kp692021471 * tD\n      tw = xr0 - kp900968867 * tv ; tF = xi0 - kp900968867 * tE\n      r6 = (td + kp974927912 * to) :+ (tS + kp974927912 * tU)\n      r5 = (tr + kp974927912 * tt) :+ (tN + kp974927912 * tP)\n      r4 = (tw + kp974927912 * ty) :+ (tF + kp974927912 * tK)\n      r3 = (tw - kp974927912 * ty) :+ (tF - kp974927912 * tK)\n      r2 = (tr - kp974927912 * tt) :+ (tN - kp974927912 * tP)\n      r1 = (td - kp974927912 * to) :+ (tS - kp974927912 * tU)\n  MV.unsafeWrite xsout 0 $ (xr0 + t4 + t7 + ta) :+ (xi0 + tA + tB + tC)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r6\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r5\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r4\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r3\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r2\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r1\n\n-- | Length 11 hard-coded FFT.\nkp989821441, kp959492973, kp918985947, kp876768831, kp830830026 :: Double\nkp778434453, kp715370323, kp634356270, kp342584725, kp521108558 :: Double\nkp989821441 = 0.989821441880932732376092037776718787376519372\nkp959492973 = 0.959492973614497389890368057066327699062454848\nkp918985947 = 0.918985947228994779780736114132655398124909697\nkp876768831 = 0.876768831002589333891339807079336796764054852\nkp830830026 = 0.830830026003772851058548298459246407048009821\nkp778434453 = 0.778434453334651800608337670740821884709317477\nkp715370323 = 0.715370323453429719112414662767260662417897278\nkp634356270 = 0.634356270682424498893150776899916060542806975\nkp342584725 = 0.342584725681637509502641509861112333758894680\nkp521108558 = 0.521108558113202722944698153526659300680427422\nspecial11 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial11 sign xsin xsout = do\n  xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n  xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n  xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n  xr6 :+ xi6 <- MV.unsafeRead xsin 6 ; xr7 :+ xi7 <- MV.unsafeRead xsin 7\n  xr8 :+ xi8 <- MV.unsafeRead xsin 8 ; xr9 :+ xi9 <- MV.unsafeRead xsin 9\n  xr10 :+ xi10 <- MV.unsafeRead xsin 10\n  let t1u = xr10 - xr1 ; t4 = xr1 + xr10 ; t1q = xr6 - xr5 ; tg = xr5 + xr6;\n      t1t = xr9 - xr2 ; t7 = xr2 + xr9 ; t1s = xr8 - xr3 ; ta = xr3 + xr8;\n      t25 = t1u + kp521108558 * t1q ; t1W = t1q + kp521108558 * t1s\n      tO = ta - kp342584725 * t4 ; th = t7 - kp342584725 * ta\n      td = xr4 + xr7 ; t1r = xr7 - xr4\n      tP = tg - kp634356270 * tO ; t1X = t1t - kp715370323 * t1W\n      t26 = t1r + kp715370323 * t25 ; tF = t4 - kp342584725 * td\n      ti = td - kp634356270 * th ; t1N = t1r - kp521108558 * t1t\n      t1v = t1t - kp521108558 * t1u ; tG = t7 - kp634356270 * tF\n      tX = tg - kp342584725 * t7 ; t1O = t1q + kp715370323 * t1N\n      t1w = t1s - kp715370323 * t1v ; t1E = t1s + kp521108558 * t1r\n      tY = t4 - kp634356270 * tX ; t16 = td - kp342584725 * tg\n      t1F = t1u + kp715370323 * t1E ; t17 = ta - kp634356270 * t16\n      to = xi3 - xi8 ; t1i = xi3 + xi8 ; t1k = xi5 + xi6 ; tA = xi5 - xi6\n      t1h = xi2 + xi9 ; tr = xi2 - xi9 ; t1j = xi4 + xi7 ; tu = xi4 - xi7\n      t20 = t1h - kp342584725 * t1i ; tK = tA + kp521108558 * to\n      tT = tu - kp521108558 * tr ; t1g = xi1 + xi10 ; tx = xi1 - xi10\n      t21 = t1j - kp634356270 * t20 ; tU = tA + kp715370323 * tT\n      tL = tr - kp715370323 * tK ; tB = tx + kp521108558 * tA\n      t1R = t1g - kp342584725 * t1j ; t1I = t1i - kp342584725 * t1g\n      t1l = t1j - kp342584725 * t1k ; tC = tu + kp715370323 * tB\n      t1S = t1h - kp634356270 * t1R ; t1J = t1k - kp634356270 * t1I\n      t1m = t1i - kp634356270 * t1l ; t12 = to + kp521108558 * tu\n      t1z = t1k - kp342584725 * t1h ; t1b = tr - kp521108558 * tx\n      t13 = tx + kp715370323 * t12 ; t1A = t1g - kp634356270 * t1z\n      t1c = to - kp715370323 * t1b ; tj = t4 - kp778434453 * ti\n      tD = tr + kp830830026 * tC ; t22 = t1g - kp778434453 * t21\n      t27 = t1t + kp830830026 * t26 ; tk = tg - kp876768831 * tj\n      tE = to + kp918985947 * tD ; t23 = t1k - kp876768831 * t22\n      t28 = t1s + kp918985947 * t27 ; tl = xr0 - kp959492973 * tk\n      t1T = t1k - kp778434453 * t1S ; t24 = xi0 - kp959492973 * t23\n      t1Y = t1u + kp830830026 * t1X ; t1U = t1i - kp876768831 * t1T\n      t1Z = t1r - kp918985947 * t1Y ; t1V = xi0 - kp959492973 * t1U\n      tH = tg - kp778434453 * tG ; tM = tx + kp830830026 * tL\n      tQ = td - kp778434453 * tP ; tI = ta - kp876768831 * tH\n      tN = tu - kp918985947 * tM ; tR = t7 - kp876768831 * tQ\n      tV = to - kp830830026 * tU ; tJ = xr0 - kp959492973 * tI\n      t1K = t1j - kp778434453 * t1J ; tS = xr0 - kp959492973 * tR\n      tW = tx - kp918985947 * tV ; t1L = t1h - kp876768831 * t1K\n      t1P = t1s - kp830830026 * t1O ; t1M = xi0 - kp959492973 * t1L\n      tZ = ta - kp778434453 * tY ; t14 = tA - kp830830026 * t13\n      t1Q = t1u - kp918985947 * t1P ; t1B = t1i - kp778434453 * t1A\n      t10 = td - kp876768831 * tZ ; t15 = tr + kp918985947 * t14\n      t11 = xr0 - kp959492973 * t10 ; t1C = t1j - kp876768831 * t1B\n      t1G = t1q - kp830830026 * t1F ; t1n = t1h - kp778434453 * t1m\n      t1D = xi0 - kp959492973 * t1C ; t1H = t1t + kp918985947 * t1G\n      t1o = t1g - kp876768831 * t1n ; t1x = t1r - kp830830026 * t1w\n      t18 = t7 - kp778434453 * t17 ; t1p = xi0 - kp959492973 * t1o\n      t1y = t1q - kp918985947 * t1x ; t19 = t4 - kp876768831 * t18\n      t1d = tu - kp830830026 * t1c ; t1a = xr0 - kp959492973 * t19\n      t1e = tA - kp918985947 * t1d\n      r10 = (tl + kp989821441 * tE) :+ (t24 + kp989821441 * t28)\n      r9 = (tJ - kp989821441 * tN) :+ (t1V - kp989821441 * t1Z)\n      r8 = (tS + kp989821441 * tW) :+ (t1M + kp989821441 * t1Q)\n      r7 = (t11 - kp989821441 * t15) :+ (t1D - kp989821441 * t1H)\n      r6 = (t1a + kp989821441 * t1e) :+ (t1p + kp989821441 * t1y)\n      r5 = (t1a - kp989821441 * t1e) :+ (t1p - kp989821441 * t1y)\n      r4 = (t11 + kp989821441 * t15) :+ (t1D + kp989821441 * t1H)\n      r3 = (tS - kp989821441 * tW) :+ (t1M - kp989821441 * t1Q)\n      r2 = (tJ + kp989821441 * tN) :+ (t1V + kp989821441 * t1Z)\n      r1 = (tl - kp989821441 * tE) :+ (t24 - kp989821441 * t28)\n  MV.unsafeWrite xsout 0 $ (xr0+t4+t7+ta+td+tg) :+ (xi0+t1g+t1h+t1i+t1j+t1k)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r10\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r9\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r8\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r7\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r6\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r5\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r4\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r3\n  MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r2\n  MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r1\n\n-- | Length 13 hard-coded FFT.\nkp875502302, kp520028571, kp575140729 :: Double\nkp600477271, kp300462606, kp516520780 :: Double\nkp968287244, kp503537032, kp251768516 :: Double\nkp581704778, kp859542535, kp083333333 :: Double\nkp957805992, kp522026385, kp853480001 :: Double\nkp769338817, kp612264650, kp038632954 :: Double\nkp302775637, kp514918778, kp686558370 :: Double\nkp226109445, kp301479260 :: Double\n--kp866025403, kp500000000 :: Double\nkp875502302 = 0.875502302409147941146295545768755143177842006\nkp520028571 = 0.520028571888864619117130500499232802493238139\nkp575140729 = 0.575140729474003121368385547455453388461001608\nkp600477271 = 0.600477271932665282925769253334763009352012849\nkp300462606 = 0.300462606288665774426601772289207995520941381\nkp516520780 = 0.516520780623489722840901288569017135705033622\nkp968287244 = 0.968287244361984016049539446938120421179794516\nkp503537032 = 0.503537032863766627246873853868466977093348562\nkp251768516 = 0.251768516431883313623436926934233488546674281\nkp581704778 = 0.581704778510515730456870384989698884939833902\nkp859542535 = 0.859542535098774820163672132761689612766401925\nkp083333333 = 0.083333333333333333333333333333333333333333333\nkp957805992 = 0.957805992594665126462521754605754580515587217\nkp522026385 = 0.522026385161275033714027226654165028300441940\nkp853480001 = 0.853480001859823990758994934970528322872359049\nkp769338817 = 0.769338817572980603471413688209101117038278899\nkp612264650 = 0.612264650376756543746494474777125408779395514\nkp038632954 = 0.038632954644348171955506895830342264440241080\nkp302775637 = 0.302775637731994646559610633735247973125648287\nkp514918778 = 0.514918778086315755491789696138117261566051239\nkp686558370 = 0.686558370781754340655719594850823015421401653\nkp226109445 = 0.226109445035782405468510155372505010481906348\nkp301479260 = 0.301479260047709873958013540496673347309208464\n--kp866025403 = 0.866025403784438646763723170752936183471402627\n--kp500000000 = 0.500000000000000000000000000000000000000000000\nspecial13 :: Int -> MVCD s -> MVCD s -> ST s ()\nspecial13 sign xsin xsout = do\n  xr0 :+ xi0 <- MV.unsafeRead xsin 0 ; xr1 :+ xi1 <- MV.unsafeRead xsin 1\n  xr2 :+ xi2 <- MV.unsafeRead xsin 2 ; xr3 :+ xi3 <- MV.unsafeRead xsin 3\n  xr4 :+ xi4 <- MV.unsafeRead xsin 4 ; xr5 :+ xi5 <- MV.unsafeRead xsin 5\n  xr6 :+ xi6 <- MV.unsafeRead xsin 6 ; xr7 :+ xi7 <- MV.unsafeRead xsin 7\n  xr8 :+ xi8 <- MV.unsafeRead xsin 8 ; xr9 :+ xi9 <- MV.unsafeRead xsin 9\n  xr10 :+ xi10 <- MV.unsafeRead xsin 10 ; xr11 :+ xi11 <- MV.unsafeRead xsin 11\n  xr12 :+ xi12 <- MV.unsafeRead xsin 12\n  let t2d = xr8 - xr5 ; tf = xr8 + xr5 ; ta = xr10 + xr4 ; tq = xr10 - xr4\n      ty = kp500000000 * ta - xr12\n      tb = xr12 + ta ; tr = xr9 - xr3 ; t5 = xr3 + xr9 ; t6 = xr1 + t5\n      tx = xr1 - kp500000000 * t5\n      ti = xr11 + xr6 ; tt = xr11 - xr6 ; tu = xr7 - xr2 ; tl = xr7 + xr2\n      tc = t6 + tb ; t2n = t6 - tb ; t2b = ti - tl ; tm = ti + tl\n      t2e = tt + tu ; tv = tt - tu ; ts = tq - tr ; t2g = tr + tq\n      tz = tx - ty ; t2a = tx + ty\n      tA = tf - kp500000000 * tm\n      tn = tf + tm\n      t2f = t2d - kp500000000 * t2e\n      t2o = t2d + t2e ; to = tc + tn ; tH = tc - tn\n      t2h = t2f + kp866025403 * t2g ; t2k = t2f - kp866025403 * t2g\n      tE = tz - tA ; tB = tz + tA ; tF = ts - tv ; tw = ts + tv\n      t2j = t2a - kp866025403 * t2b ; t2c = t2a + kp866025403 * t2b\n      t1R = xi8 + xi5 ; tM = xi8 - xi5 ; t17 = xi10 + xi4 ; t10 = xi10 - xi4\n      t18 = kp500000000 * t17 - xi12\n      t1l = xi12 + t17 ; tX = xi9 - xi3 ; t14 = xi3 + xi9 ; t1k = xi1 + t14\n      t15 = xi1 - kp500000000 * t14\n      tP = xi11 - xi6 ; t1a = xi11 + xi6 ; t1b = xi7 + xi2 ; tS = xi7 - xi2\n      t1Q = t1k + t1l ; t1m = t1k - t1l ; t11 = tX + t10 ; t1W = t10 - tX\n      t1X = tP - tS ; tT = tP + tS ; t1S = t1a + t1b ; t1c = t1a - t1b\n      t19 = t15 + t18 ; t1Z = t15 - t18 ; t1j = tM + tT\n      tU = tM - kp500000000 * tT\n      t1T = t1R + t1S\n      t20 = t1R - kp500000000 * t1S ; t12 = tU + kp866025403 * t11\n      t1f = tU - kp866025403 * t11\n      t21 = t1Z + t20 ; t24 = t1Z - t20 ; t27 = t1Q - t1T ; t1U = t1Q + t1T\n      t1g = t19 - kp866025403 * t1c ; t1d = t19 + kp866025403 * t1c\n      t25 = t1W - t1X ; t1Y = t1W + t1X\n      tC = tw + kp301479260 * tB ; t1x = tB - kp226109445 * tw\n      t1y = tF + kp686558370 * tE ; tG = tE - kp514918778 * tF\n      t1n = t1j - kp302775637 * t1m ; t1G = t1m + kp302775637 * t1j\n      t1u = t1d - kp038632954 * t12 ; t1e = t12 + kp038632954 * t1d\n      t1h = t1f + kp612264650 * t1g ; t1v = t1g - kp612264650 * t1f\n      t1J = t1x + kp769338817 * t1y ; t1z = t1x - kp769338817 * t1y\n      t1H = t1u - kp853480001 * t1v ; t1w = t1u + kp853480001 * t1v\n      t1I = t1G - kp522026385 * t1H ; t1O = t1H + kp957805992 * t1G\n      tp = xr0 - kp083333333 * to ; t1E = t1e + kp853480001 * t1h\n      t1i = t1e - kp853480001 * t1h ; t1q = tH - kp859542535 * tG\n      tI = tG + kp581704778 * tH ; t1o = t1i + kp957805992 * t1n\n      t1s = t1n - kp522026385 * t1i ; t1p = tp - kp251768516 * tC\n      tD = tp + kp503537032 * tC ; t1C = t1w - kp968287244 * t1z\n      t1A = t1w + kp968287244 * t1z ; tJ = tD + kp516520780 * tI\n      t1N = tD - kp516520780 * tI ; t1D = t1p - kp300462606 * t1q\n      t1r = t1p + kp300462606 * t1q ; t1t = t1r - kp575140729 * t1s\n      t1B = t1r + kp575140729 * t1s ; t1L = t1D - kp520028571 * t1E\n      t1F = t1D + kp520028571 * t1E ; t1K = t1I + kp875502302 * t1J\n      t1M = t1I - kp875502302 * t1J ; t2D = t21 - kp226109445 * t1Y\n      t22 = t1Y + kp301479260 * t21 ; t26 = t24 - kp514918778 * t25\n      t2E = t25 + kp686558370 * t24 ; t2v = t2o - kp302775637 * t2n\n      t2p = t2n + kp302775637 * t2o ; t2i = t2c - kp038632954 * t2h\n      t2s = t2h + kp038632954 * t2c ; t2t = t2k + kp612264650 * t2j\n      t2l = t2j - kp612264650 * t2k ; t2F = t2D - kp769338817 * t2E\n      t2N = t2D + kp769338817 * t2E ; t2K = t2s + kp853480001 * t2t\n      t2u = t2s - kp853480001 * t2t ; t2w = t2u + kp957805992 * t2v\n      t2A = t2v - kp522026385 * t2u ; t1V = xi0 - kp083333333 * t1U\n      t2m = t2i - kp853480001 * t2l ; t2C = t2i + kp853480001 * t2l\n      t28 = t26 + kp581704778 * t27 ; t2y = t27 - kp859542535 * t26\n      t2M = t2p - kp522026385 * t2m ; t2q = t2m + kp957805992 * t2p\n      t23 = t1V + kp503537032 * t22 ; t2x = t1V - kp251768516 * t22\n      t2O = t2M - kp875502302 * t2N ; t2Q = t2M + kp875502302 * t2N\n      t2r = t23 + kp516520780 * t28 ; t29 = t23 - kp516520780 * t28\n      t2z = t2x + kp300462606 * t2y ; t2J = t2x - kp300462606 * t2y\n      t2P = t2J + kp520028571 * t2K ; t2L = t2J - kp520028571 * t2K\n      t2B = t2z + kp575140729 * t2A ; t2H = t2z - kp575140729 * t2A\n      t2I = t2C + kp968287244 * t2F ; t2G = t2C - kp968287244 * t2F\n      r12 = (tJ - kp600477271 * t1o) :+ (t2r + kp600477271 * t2w)\n      r11 =  (t1F + kp575140729 * t1K) :+ (t2L - kp575140729 * t2O)\n      r10 = (t1t + kp520028571 * t1A) :+ (t2B - kp520028571 * t2G)\n      r9 = (t1B + kp520028571 * t1C) :+ (t2H - kp520028571 * t2I)\n      r8 = (t1N + kp600477271 * t1O) :+ (t29 - kp600477271 * t2q)\n      r7 = (t1L + kp575140729 * t1M) :+ (t2P - kp575140729 * t2Q)\n      r6 = (t1F - kp575140729 * t1K) :+ (t2L + kp575140729 * t2O)\n      r5 = (t1N - kp600477271 * t1O) :+ (t29 + kp600477271 * t2q)\n      r4 = (t1t - kp520028571 * t1A) :+ (t2B + kp520028571 * t2G)\n      r3 = (t1B - kp520028571 * t1C) :+ (t2H + kp520028571 * t2I)\n      r2 = (t1L - kp575140729 * t1M) :+ (t2P + kp575140729 * t2Q)\n      r1 = (tJ + kp600477271 * t1o) :+ (t2r - kp600477271 * t2w)\n  MV.unsafeWrite xsout 0 $ (xr0 + to) :+ (xi0 + t1U)\n  MV.unsafeWrite xsout 1 $ if sign == 1 then r1 else r12\n  MV.unsafeWrite xsout 2 $ if sign == 1 then r2 else r11\n  MV.unsafeWrite xsout 3 $ if sign == 1 then r3 else r10\n  MV.unsafeWrite xsout 4 $ if sign == 1 then r4 else r9\n  MV.unsafeWrite xsout 5 $ if sign == 1 then r5 else r8\n  MV.unsafeWrite xsout 6 $ if sign == 1 then r6 else r7\n  MV.unsafeWrite xsout 7 $ if sign == 1 then r7 else r6\n  MV.unsafeWrite xsout 8 $ if sign == 1 then r8 else r5\n  MV.unsafeWrite xsout 9 $ if sign == 1 then r9 else r4\n  MV.unsafeWrite xsout 10 $ if sign == 1 then r10 else r3\n  MV.unsafeWrite xsout 11 $ if sign == 1 then r11 else r2\n  MV.unsafeWrite xsout 12 $ if sign == 1 then r12 else r1\n", "meta": {"hexsha": "afd4fab1c71dfa33d26a01ae8e95523a1620cc9b", "size": 19616, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/FFT/Special/Primes.hs", "max_stars_repo_name": "ian-ross/arb-fft", "max_stars_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-15T09:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-08T13:14:27.000Z", "max_issues_repo_path": "Numeric/FFT/Special/Primes.hs", "max_issues_repo_name": "ian-ross/arb-fft", "max_issues_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-03-08T20:31:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T20:32:09.000Z", "max_forks_repo_path": "Numeric/FFT/Special/Primes.hs", "max_forks_repo_name": "ian-ross/arb-fft", "max_forks_repo_head_hexsha": "4a5e78e8197218e8f56c56f409b0f4daabb9c437", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-11-25T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-06T22:54:26.000Z", "avg_line_length": 58.380952381, "max_line_length": 79, "alphanum_fraction": 0.6331056281, "num_tokens": 8635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.41484125433109204}}
{"text": "{-# LANGUAGE FlexibleInstances   #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Polynomials where\n\nimport           Numeric.LinearAlgebra\nimport           System.Random hiding (rand)\nimport           Control.Monad.IO.Class\nimport           Control.Monad\nimport           Control.Exception\nimport           Data.Maybe\nimport qualified Data.Vector as V\nimport qualified Data.Array.Accelerate as A\nimport           Genetic\nimport           Formulas\n\nimport Debug.Trace\n\ndata Article = Article\n            { _articlePowers  :: Powers\n            , _articleInputs  :: Inplist\n            , _articleOutputs :: Y\n            } deriving (Eq, Ord)\n\ninstance Show Article where\n      show = show . _articlePowers\n\ninstance Individual Article where\n   -- fitness :: a -> IO (Maybe Double)\n      fitness (Article ps is os) = do\n            let x' = calcX is ps\n                rows = length $ toLists x'\n                cols = length . head $ toLists x'\n                y = os\n            noise_ <- rand rows cols\n            let   noise = noise_ * 100.0\n                  x = if det (tr x' <> x') == 0\n                      then x' + noise\n                      else x'\n            -- bug fix for BLAS matrix rank on big numbers\n            return $ if det (tr x <> x) == 0\n                     then Nothing\n                     else Just $ cost (normEq x y) x y\n\n   -- mutateIndividual :: a -> IO a\n      mutateIndividual (Article pows _a _b) = do\n            r <- randomIO\n            if mutationProbability < r\n            then inner pows\n            else return $ Article pows _a _b\n            where\n                  mutationProbability :: Double\n                  mutationProbability = 0.1\n\n                  inner :: Powers -> IO Article\n                  inner x = do\n                        blockIndex <- randomRIO (0, V.length x - 1)\n                        powerIndex <- randomRIO (0, V.length (x V.! 0) - 1)\n                        newPower   <- randomRIO (-4, 4)\n\n                        let updated = updateVV x ( blockIndex, powerIndex) newPower\n                        return $ Article updated _a _b\n\n\n   -- crossover :: (a, a) -> IO a\n      crossover ( Article pows1 _a _b\n                , Article pows2 _ _\n                ) = do\n            index <- randomRIO (0, V.length pows1)\n            let leftPart  = V.take index pows1\n            let rightPart = V.drop index pows2\n            return $ Article (V.concat [leftPart, rightPart]) _a _b\n\n\nupdateVV :: V.Vector (V.Vector a) -- what to update\n         -> (Int, Int)            -- where\n         -> a                     -- what to put there\n         -> V.Vector (V.Vector a) -- result\nupdateVV vvs (xIdx, yIdx) value =\n      vvs V.// [(xIdx, updatedV)]\n      where\n            updatedV  = originalV V.// [(yIdx, value)]\n            originalV = vvs V.! xIdx", "meta": {"hexsha": "36198d5906e9ef1d4eaa5ed30dc790fb9e02e783", "size": 2821, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Polynomials.hs", "max_stars_repo_name": "orenm13/Genetic-Algorithm-in-Haskell", "max_stars_repo_head_hexsha": "70fc1c618e2a3ccab077785794f8b05c3855b602", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Polynomials.hs", "max_issues_repo_name": "orenm13/Genetic-Algorithm-in-Haskell", "max_issues_repo_head_hexsha": "70fc1c618e2a3ccab077785794f8b05c3855b602", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Polynomials.hs", "max_forks_repo_name": "orenm13/Genetic-Algorithm-in-Haskell", "max_forks_repo_head_hexsha": "70fc1c618e2a3ccab077785794f8b05c3855b602", "max_forks_repo_licenses": ["BSD-3-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.9879518072, "max_line_length": 83, "alphanum_fraction": 0.5044310528, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.41483874644964736}}
{"text": "-------------------------------------------------------------------------------\n-- |\n-- Module    :  Environments.Bandits\n-- Copyright :  (c) Sentenai 2017\n-- License   :  BSD3\n-- Maintainer:  sam@sentenai.com\n-- Stability :  experimental\n-- Portability: non-portable\n--\n-- Implementation of an n-armed bandit environment.\n--\n-- FIXME: currently this is only for a 10-armed bandit. This needs to be tied\n-- to a config.\n-------------------------------------------------------------------------------\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# OPTIONS_GHC -Wno-unused-top-binds #-}\nmodule Environments.Bandits\n  ( Environment(..)\n  , runEnvironment\n  , Event.Event(..)\n  , Config\n  , Action\n  , mkBandits\n  , defaultBandits\n  , mkAction\n  ) where\n\nimport Control.MonadEnv\nimport Control.MonadMWCRandom\nimport qualified Data.Vector as V\nimport Data.Vector ((!), Vector)\nimport Data.Hashable\nimport qualified Data.Event as Event\nimport Control.Exception.Safe (assert, MonadThrow)\nimport qualified Statistics.Distribution as Dist\nimport Statistics.Distribution.Normal\nimport Data.DList\nimport Control.Monad.Reader.Class\nimport Control.Monad.RWS.Class\nimport Control.Monad.IO.Class\nimport Control.Monad.Writer.Class\nimport Control.Monad.State.Class\nimport Control.Monad.Trans.RWS (RWST, evalRWST)\nimport GHC.Generics\n\n\n-- | FIXME: only 10 arms for the time being. This is where a \"discrete space\"\n-- would be nice\ndata Config = Config\n  { nBandits :: Int\n  , offset   :: Int\n  , stdDev   :: Float\n  , bandits  :: Vector NormalDistribution\n  , gen      :: GenIO\n  }\n\ninstance Show Config where\n  show c = \"Config\" ++\n    \"{nBandits=\"++ show (nBandits c)++\n    \"{offset=\"++ show (offset c)++\n    \"{bandit_stdDevs=\"++ show (stdDev c)++\n    \"{bandit_means=\"++ show (fmap Dist.mean . V.toList $ bandits c)++\n    \"}\"\n\ntype Event = Event.Event Reward () Action\n\n-- | The slot machine index whose arm will be pulled\nnewtype Action = Action { unAction :: Int }\n  deriving (Eq, Ord, Show, Enum, Generic)\n\ninstance Bounded Action where\n  minBound = Action 0\n  maxBound = Action 9\n\ninstance Hashable Action where\n\n-- | Convert an Int to an Action  in the bandit environment. Throw if the Int\n-- falls out of bounds.\nmkAction :: Int -> Environment Action\nmkAction i = Environment $ do\n  n <- nBandits <$> ask\n  assert (i > n || i < 0) (pure $ Action i)\n\n-- | Monad for an n-armed bandit environment\nnewtype Environment a = Environment\n  { getEnvironment :: RWST Config (DList Event) () IO a }\n  deriving\n    ( Functor\n    , Applicative\n    , Monad\n    , MonadIO\n    , MonadThrow\n    , MonadReader Config\n    , MonadWriter (DList Event)\n    , MonadState ()\n    , MonadRWS Config (DList Event) ()\n    )\n\n-- | run an n-armed bandit environment\nrunEnvironment :: Config -> Environment () -> IO (DList Event)\nrunEnvironment c (Environment m) = snd <$> evalRWST m c ()\n\n-- | Give the default config of a 10-armed bandit\ndefaultBandits :: GenIO -> Config\ndefaultBandits = mkBandits 10 2 0.1\n\n-- | helper function to build a bandits config with normally-distributed\n-- reward functions\nmkBandits :: Int -> Int -> Float -> GenIO -> Config\nmkBandits n offset' std = Config n offset' std $\n  V.fromList $ fmap (`rewardDist` std) [offset' .. offset' + n - 1]\n  where\n    rewardDist :: Int -> Float -> NormalDistribution\n    rewardDist m s = normalDistr (fromIntegral m) (realToFrac s)\n\ninstance MonadMWCRandom Environment where\n  getGen = Environment $ fmap gen ask\n\ninstance MonadEnv Environment () Action Reward where\n  -- this isn't an episodic environment... we'll have to split this out later\n  reset :: Environment (Initial ())\n  reset = return $ Initial ()\n\n  step :: Action -> Environment (Obs Reward ())\n  step (Action a) = do\n    rwd <- genContVar =<< (! a) . bandits <$> ask\n    tell . pure $ Event.Event 0 rwd () (Action a)\n    return $ Next rwd ()\n", "meta": {"hexsha": "6786be9c836ad0e5df97bd3077f38582fc8d0cc1", "size": 3935, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "reinforce-environments/src/Environments/Bandits.hs", "max_stars_repo_name": "juliendehos/reinforce", "max_stars_repo_head_hexsha": "f503c9b85cf20dbf7443655a5921e5aa58c94ccb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-04-25T19:47:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T16:48:41.000Z", "max_issues_repo_path": "reinforce-environments/src/Environments/Bandits.hs", "max_issues_repo_name": "sentenai/reinforce", "max_issues_repo_head_hexsha": "03fdeea14c606f4fe2390863778c99ebe1f0a7ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2017-03-17T21:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-26T09:58:22.000Z", "max_forks_repo_path": "reinforce-environments/src/Environments/Bandits.hs", "max_forks_repo_name": "sentenai/reinforce", "max_forks_repo_head_hexsha": "03fdeea14c606f4fe2390863778c99ebe1f0a7ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2017-07-31T14:31:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T12:03:48.000Z", "avg_line_length": 29.8106060606, "max_line_length": 79, "alphanum_fraction": 0.6622617535, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4143395397799629}}
{"text": "module Augmentation.DGA\n    (DGA_Map (DGA_Map)\n    ,Augmentation (Aug)\n    ,applyDGAMap\n    ,compose_maps\n    ,Algebra\n    ,fromDGAMap\n    ) where\n\nimport Algebra\nimport Braid\nimport Data.Maybe\nimport Numeric.LinearAlgebra as N\nimport Data.List\nimport Debug.Trace\n\ndefault (Int,Double)\n\ndata DGA_Map = DGA_Map [(Char,Algebra)] deriving Eq\ninstance Show DGA_Map where\n    show (DGA_Map l) = \"[\" ++ (foldr (\\(c,e) xs -> [c] ++ \"\u2192\" ++ show e ++ (if xs /= \"]\" then \",\" else \"\") ++ xs) \"]\" l)\n\ndata Augmentation = Aug StdBraid [(Char,[Vector Z])]\ninstance Show Augmentation where\n    show (Aug b m) = (show b) ++ \"\\n\" ++ (concat $ map (\\(c,vs) -> [c] ++ \"\u2192\" ++ (foldr (\\x xs -> show x ++ if xs == \"\" then \"\" else \"+\"++xs) \"\" vs) ++ \" \") m)\ninstance Eq Augmentation where\n    (Aug b1 m1) == (Aug b2 m2) = b1 == b2 && inZ2 m1 == inZ2 m2 && (m1 == m2 || eqh m1 m2)\n\ninZ2 :: [(Char,[Vector Z])] -> [(Char,Z2)]\ninZ2 = map (\\(c,vs) -> (c,sum $ map (\\_ -> fromInteger 1) vs))\n\nisUpperTri :: Matrix Z -> Bool\nisUpperTri mat = uptrih mat 0\n\nuptrih :: Matrix Z -> Int -> Bool\nuptrih mat i = let (l,w) = size mat\n                   cond = and $ map (\\j -> (==0) $ mat `atIndex` (j,i)) [i+1..l-1] \n                in if i == w then True else cond && (uptrih mat $ i+1)\n\neqh :: [(Char,[Vector Z])] -> [(Char,[Vector Z])] -> Bool\neqh l1 l2 = maybe False id $ do\n            { l1' <- mapM (\\c -> lookup c l1) $ map fst l2\n            ; l2' <- mapM (\\(l,l') -> if length l == length l' then Just l' else Nothing) $ zip l1' $ map snd l2\n            ; return True\n            ; let dims1 = nub $ map size $ concat l1'\n            ; let dims2 = nub $ map size $ concat l2'\n            ; dim <- if length dims1 == 1 && length dims2 == 1 && dims1 == dims2 then Just $ head dims1 else Nothing\n            ; let m2 = fromRows $ map (fromZ :: Vector Z -> Vector R) $ concat l2'\n            ; let n0s = map (\\l -> (0,(length $ permutations l)-1)) l1'\n            ; let suc mns = if mns == [] then [] else if (fst $ head mns) == (snd $ head mns) then (0,snd $ head mns):(suc $ tail mns) else (1 + (fst $ head mns), snd $ head mns):(tail mns)\n            ; let bound (acc,mns) = if mns == [] then acc else bound (((snd $ head mns)+1)*acc,tail mns)\n            ; let ubound = bound (1,n0s)\n            ; let mat mns = fromRows $ map (fromZ :: Vector Z -> Vector R) $ concat $ zipWith (\\l (m,_) -> (permutations l) !! m) l1' mns\n            ; let check m = maybe False id $ do \n                            { let (l,u,p,s) = lu m\n                            ; let (lR,lC) = size l\n                            ; let sq = abs $ lR - lC\n                            ; let l' = if lC == lR then l else if lC < lR then l ||| (konst 0 (lC,sq) === ident sq) else l === (konst 0 (sq,lR) ||| ident sq)\n                            ; linv <- if det l' == 0 then Nothing else Just $ inv l' \n                            ; pinv <- if s == 0 then Nothing else Just $ inv p\n                            ; let mat' = linv N.<> pinv N.<> m2\n                            ; let matz = fromColumns $ map (toZ . roundVector) $ toColumns mat'\n                            ; let cond = isUpperTri matz\n                            ; let cond' = and $ map (\\x -> (x - (fromIntegral $ floor x) < cutoff) || (((fromIntegral $ ceiling x) - x) < cutoff)) $ toList $ flatten mat'\n                            ; return $ cond && cond'\n                            }\n            ; let checkAll k mns = if size (mat mns) /= size m2 then trace \"Dim mismatch\" False else if check $ mat mns then trace \"Found one!\" True else if k > ubound then trace (\"Tried: \"++show k) False else checkAll (k+1) (suc mns)\n            ; return $ checkAll 0 n0s\n            }\n\nfromDGAMap :: StdBraid -> DGA_Map -> [Char] -> Maybe Augmentation\nfromDGAMap b (DGA_Map l) chars = do\n                                { l' <- mapM (\\(c,a) -> (represent chars a) >>= (\\vs -> return (c,vs))) l\n                                ; return $ Aug b l'\n                                }\n\ncompose_maps :: DGA_Map -> DGA_Map -> DGA_Map\ncompose_maps (DGA_Map map1) (DGA_Map map2) = DGA_Map $ (map (\\(c,exp) -> (c,applyDGAMap (DGA_Map map2) exp)) map1) ++ (filter (\\(c,_) -> not $ elem c $ map fst map1) map2)\n\napplyDGAMap :: DGA_Map -> Algebra -> Algebra\napplyDGAMap (DGA_Map alist) a = appmaph alist a\n\nappmaph::[(Char,Algebra)] -> Algebra -> Algebra\nappmaph [] = id\nappmaph cs = plugIn (\\c -> case (lookup c cs) of Just e -> e\n                                                 Nothing -> G $ E c)\n", "meta": {"hexsha": "c268ad79dd2765408351e68ebd9cec4fdae04b69", "size": 4483, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Augmentation/DGA.hs", "max_stars_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_stars_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "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/Augmentation/DGA.hs", "max_issues_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_issues_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-07-08T23:05:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-18T19:21:55.000Z", "max_forks_repo_path": "src/Augmentation/DGA.hs", "max_forks_repo_name": "Creatorri/Legendrian-Knots-UROP", "max_forks_repo_head_hexsha": "9a2926b5c02280a74f1fde360881861ef935097a", "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": 51.5287356322, "max_line_length": 234, "alphanum_fraction": 0.5021191167, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4143150941350393}}
{"text": "{-# LANGUAGE ViewPatterns #-}\n\nmodule Main where\n\nimport Codec.Image.DevIL\nimport Data.Array.Unboxed\nimport Math.Probably.MCMC\nimport Math.Probably.RandIO\nimport Math.Probably.Sampler\nimport Math.Probably.FoldingStats\nimport Control.Monad.State.Strict \nimport System.Cmd\nimport System.Environment\nimport Data.Array.IO\nimport System.IO\n\nimport Data.Array.Unboxed\nimport Numeric.LinearAlgebra hiding (find)\nimport qualified Math.Probably.PDF as PDF\nimport Data.List\nimport Data.Maybe\nimport Control.Applicative\nimport Data.Ord\n \nimport Data.IORef\nimport System.IO.Unsafe\n\nimport CVUtils\nimport Edge\n\n\nposteriorV :: Image -> Image -> (Int, Int) -> Vector R -> R\nposteriorV bgim im (cx,cy) v = \n   uniformLogPdf 0 100.0 len1 +\n   uniformLogPdf 0 1.0 ecc +\n   uniformLogPdf 0 10000.0 noise +\n   uniformLogPdf 0 1500.0 px +\n   uniformLogPdf 0 1500.0 py +\n   sum [ f x y chan | \n                   x <- [ (cx::Int) -20.. cx +20],\n                   y <- [ cy -20.. cy +20], \n                   chan <- [0..2]]\n\n  where px = v @> 0\n        py = v @> 1\n        noise = v @> 2\n        len1 = v@> 3\n        rot = v@> 4\n        ecc = v@> 5\n        red = v@> 6\n        green = v@> 7\n        blue = v@> 8\n        noiseInside = v@> 9\n        len2 = v@> 10\n        f1x = px+(len1*ecc)*cos rot\n        f1y = py+(len1*ecc)*sin rot\n        f2x = px-(len1*ecc)*cos rot\n        f2y = py-(len1*ecc)*sin rot\n        f1x2 = px+(len2*ecc)*cos rot\n        f1y2 = py+(len2*ecc)*sin rot\n        f2x2 = px-(len2*ecc)*cos rot\n        f2y2 = py-(len2*ecc)*sin rot\n        colVec = fromList [red,green,blue]\n        f :: Int -> Int -> Int -> R\n        f x y ch \n         = if dist  f1x f1y   x  y  + dist  f2x f2y   x  y  < 2 * len1\n              then gaussR noiseInside (colVec@>ch) $ im!(y,x,ch)\n              else if dist  f1x2 f1y2   x  y  + dist  f2x2 f2y2   x  y  < 2 * len2\n                      then gaussW8 noise ((bgim!(y,x,ch))`div` 2) $ im!(y,x,ch)\n                      else gaussW8 noise (bgim!(y,x,ch)) $ im!(y,x,ch)\n\n\nmain = do\n     ilInit\n     bgnm : fvid :_ <- getArgs\n     bgIm <-readImage bgnm\n     system $ \"~/cvutils/extract \"++fvid++\" 3200\"\n     frame0 <-readImage \"extract.png\"\n     let x = 1092\n         y = 518\n         rot = -5.12\n         posterior = posteriorV bgIm frame0 (round x,round y)\n         postAndV v = (posteriorV bgIm frame0 (round x,round y) $ fromList v, v)\n         \n         initialsV = fromList [x,y,218, 4.5, rot, 0.9, 0.1,0.1,0.1, 218, 6]\n     print [frame0!(round y,round x,c) | c <- [0..2]]\n     print [frame0!(round y+1,round x,c) | c <- [0..2]]\n     print [frame0!(round y,round x+1,c) | c <- [0..2]]\n     runRIO $ do\n         iniampar <- sample $ initialAdaMet 300 1.5e-4 posterior initialsV\n         AMPar v _ _ _ _ _ _ <- runAndDiscard 50000 (show . ampPar) iniampar $ adaMet False posterior\n         lift $ print initialsV\n         lift $ print v", "meta": {"hexsha": "137e8c63f98ac9af86ccab642c8576b1b78d3a38", "size": 2870, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Locate.hs", "max_stars_repo_name": "glutamate/cvutils", "max_stars_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:20:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:20:21.000Z", "max_issues_repo_path": "Locate.hs", "max_issues_repo_name": "glutamate/cvutils", "max_issues_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Locate.hs", "max_forks_repo_name": "glutamate/cvutils", "max_forks_repo_head_hexsha": "4211023dade7b755eceb2f16b127fdcd7ad16473", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8602150538, "max_line_length": 101, "alphanum_fraction": 0.5620209059, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4141324003299797}}
{"text": "import Control.Applicative\nimport Data.Generics.Random.Boltzmann.GeneratingFunctions\nimport Numeric.LinearAlgebra\nimport Test.HUnit\n\nmain = runTestTT $ TestList\n  [ test_solve\n  ]\n\ntest_solve = \"F(x) = 1 + x F(x)^2\" ~: do\n    print xs\n    print (evalDeltas <$> xs <*> pure es)\n  where\n    x : fx : f'x : _ = fmap X [0 ..]\n    expectedSize x n = (n * fx, x * f'x)\n    es =\n      [ expectedSize x 10000\n      , (fx, 1 + x * fx * fx)\n      , (f'x, fx * fx + 2 * x * f'x * fx)\n      ]\n    xs = solveEquations defSolveArgs es (vector [0, 1, 1])\n", "meta": {"hexsha": "ea608087eeb3629156751ce3878dd0f5931d279d", "size": 540, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Spec.hs", "max_stars_repo_name": "blackheaven/generic-random", "max_stars_repo_head_hexsha": "d148a66b003db776099c20e6d5df1a83f1d8e37c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 83, "max_stars_repo_stars_event_min_datetime": "2016-04-09T00:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T07:08:38.000Z", "max_issues_repo_path": "test/Spec.hs", "max_issues_repo_name": "blackheaven/generic-random", "max_issues_repo_head_hexsha": "d148a66b003db776099c20e6d5df1a83f1d8e37c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2016-08-22T10:56:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T01:26:15.000Z", "max_forks_repo_path": "test/Spec.hs", "max_forks_repo_name": "blackheaven/generic-random", "max_forks_repo_head_hexsha": "d148a66b003db776099c20e6d5df1a83f1d8e37c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-04-09T12:08:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T21:48:47.000Z", "avg_line_length": 24.5454545455, "max_line_length": 58, "alphanum_fraction": 0.5796296296, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4141061906538742}}
{"text": "-- | Example originally inspired by\n-- <https://ro-che.info/articles/2015-12-05-testing-fft Roman Cheplyaka>.\n\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Main where\n\nimport Data.Complex\nimport qualified Language.R as R\nimport Language.R (R)\nimport Language.R.QQ\n\n-- Call R's FFT\nr_fft :: [Complex Double] -> R s [Complex Double]\nr_fft nums = do\n    R.dynSEXP <$> [r| fft(nums_hs) |]\n\nmain :: IO ()\nmain = R.withEmbeddedR R.defaultConfig $ do\n    result <- R.runRegion $ r_fft [1,2,1]\n    print result\n", "meta": {"hexsha": "4c3c29449652751469aacce83c5c120cc793985a", "size": 585, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/fft/Main.hs", "max_stars_repo_name": "reactormonk/HaskellR", "max_stars_repo_head_hexsha": "b164e7cbf9145bbb8fd2877593c03ba58002f33c", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 591, "max_stars_repo_stars_event_min_datetime": "2015-07-28T22:32:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T21:32:10.000Z", "max_issues_repo_path": "examples/fft/Main.hs", "max_issues_repo_name": "reactormonk/HaskellR", "max_issues_repo_head_hexsha": "b164e7cbf9145bbb8fd2877593c03ba58002f33c", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": 150, "max_issues_repo_issues_event_min_datetime": "2015-07-27T08:03:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T12:28:30.000Z", "max_forks_repo_path": "examples/fft/Main.hs", "max_forks_repo_name": "reactormonk/HaskellR", "max_forks_repo_head_hexsha": "b164e7cbf9145bbb8fd2877593c03ba58002f33c", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 50, "max_forks_repo_forks_event_min_datetime": "2015-09-06T00:07:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T02:14:30.000Z", "avg_line_length": 23.4, "max_line_length": 73, "alphanum_fraction": 0.6820512821, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.41406366208725753}}
{"text": "{-\n   Copyright 2016, Dominic Orchard, Andrew Rice, Mistral Contrastin, Matthew Danish\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n-}\n\n{-\n  Units of measure extension to Fortran: backend\n-}\n\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Camfort.Specification.Units.InferenceBackend\n  ( chooseImplicitNames\n  , criticalVariables\n  , inconsistentConstraints\n  , inferVariables\n  -- mainly for debugging and testing:\n  , shiftTerms\n  , flattenConstraints\n  , flattenUnits\n  , constraintsToMatrix\n  , constraintsToMatrices\n  , rref\n  , genUnitAssignments\n  , genUnitAssignments'\n  , provenance\n  , splitNormHNF\n  ) where\n\nimport           Camfort.Specification.Units.Environment\nimport qualified Camfort.Specification.Units.InferenceBackendFlint as Flint\nimport           Control.Arrow (first, second, (***))\nimport           Control.Monad\nimport           Control.Monad.ST\nimport           Control.Parallel.Strategies\nimport qualified Data.Array as A\nimport           Data.Generics.Uniplate.Operations\n  (transformBi, universeBi)\nimport           Data.Graph.Inductive hiding ((><))\nimport qualified Data.IntMap as IM\nimport qualified Data.IntSet as IS\nimport           Data.List\n  ((\\\\), findIndex, inits, nub, partition, sort, sortBy, group, tails, foldl')\nimport qualified Data.Map.Strict as M\nimport           Data.Maybe (fromMaybe, mapMaybe)\nimport           Data.Ord\nimport           Data.Tuple (swap)\nimport           Numeric.LinearAlgebra\n  ( atIndex, (<>)\n  , rank, (?), (\u00bf)\n  , rows, cols\n  , subMatrix, diag\n  , fromBlocks, ident\n  )\nimport qualified Numeric.LinearAlgebra as H\nimport           Numeric.LinearAlgebra.Devel\n  ( newMatrix, readMatrix\n  , writeMatrix, runSTMatrix\n  , freezeMatrix, STMatrix\n  )\nimport           Prelude hiding ((<>))\n\n\n-- | Returns list of formerly-undetermined variables and their units.\ninferVariables :: Constraints -> [(VV, UnitInfo)]\ninferVariables cons = unitVarAssignments\n  where\n    unitAssignments = genUnitAssignments cons\n    -- Find the rows corresponding to the distilled \"unit :: var\"\n    -- information for ordinary (non-polymorphic) variables.\n    unitVarAssignments            =\n      [ (var, units) | ([UnitPow (UnitVar var)                 k], units) <- unitAssignments, k `approxEq` 1 ] ++\n      [ (var, units) | ([UnitPow (UnitParamVarAbs (_, var)) k], units)    <- unitAssignments, k `approxEq` 1 ]\n\n-- Detect inconsistency if concrete units are assigned an implicit\n-- abstract unit variable with coefficients not equal, or there are\n-- monomorphic literals being given parametric polymorphic units.\ndetectInconsistency :: [([UnitInfo], UnitInfo)] -> Constraints\ndetectInconsistency unitAssignments = inconsist\n  where\n    ua' = map (shiftTerms . fmap flattenUnits) unitAssignments\n    badImplicits = [ fmap foldUnits a | a@([UnitPow (UnitParamImpAbs _) k1], rhs) <- ua'\n                                      , UnitPow _ k2 <- rhs\n                                      , k1 /= k2 ]\n    inconsist = unitAssignmentsToConstraints badImplicits ++ mustBeUnitless unitAssignments\n\n-- Must be unitless: any assignments of parametric abstract units to\n-- monomorphic literals.\nmustBeUnitless :: [([UnitInfo], UnitInfo)] -> Constraints\nmustBeUnitless unitAssignments = mbu\n  where\n    mbu = [ ConEq UnitlessLit (UnitPow (UnitLiteral l) k)\n          | (UnitPow (UnitLiteral l) k:_, rhs) <- ua''\n          , any isParametric (universeBi rhs :: [UnitInfo]) ]\n    -- ua' = map (shiftTerms . fmap flattenUnits) unitAssignments\n    ua'' = map (shiftTermsBy isLiteral . fmap flattenUnits) unitAssignments\n\n    isLiteral UnitLiteral{} = True\n    isLiteral (UnitPow UnitLiteral{} _) = True\n    isLiteral _ = False\n\n    isParametric UnitParamVarAbs{} = True\n    isParametric UnitParamPosAbs{} = True\n    isParametric UnitParamEAPAbs{} = True\n    isParametric UnitParamLitAbs{} = True\n    isParametric UnitParamImpAbs{} = True\n    isParametric (UnitPow u _)     = isParametric u\n    isParametric _                 = False\n\n\n-- convert the assignment format back into constraints\nunitAssignmentsToConstraints :: [([UnitInfo], UnitInfo)] -> Constraints\nunitAssignmentsToConstraints = map (uncurry ConEq . first foldUnits)\n\n-- | Raw units-assignment pairs.\ngenUnitAssignments :: Constraints -> [([UnitInfo], UnitInfo)]\ngenUnitAssignments cons\n  -- if the results include any mappings that must be forced to be unitless...\n  | mbu <- mustBeUnitless ua, not (null mbu) = genUnitAssignments (mbu ++ unitAssignmentsToConstraints ua)\n  | null (detectInconsistency ua)            = ua\n  | otherwise                                = []\n  where\n    ua = genUnitAssignments' colSort cons\n\n-- | Break up the problem of solving normHNF on each group of related\n-- columns, then bring it all back together.\nsplitNormHNF :: H.Matrix Double -> (H.Matrix Double, [Int])\nsplitNormHNF unsolvedM = (combinedMat, allNewColIndices)\n  where\n    combinedMat      = joinMat (map (first fst) solvedMs)\n    allNewColIndices = concatMap (snd . fst) solvedMs\n\n    inParallel = (`using` parTuple2 (parList rseq) rseq)\n    (solvedMs, _) = inParallel . foldl' eachResult ([], cols unsolvedM) $ map (first Flint.normHNF) (splitMat unsolvedM)\n\n    -- for each result re-number the generated columns & add mappings for each.\n    eachResult (ms, startI) ((m, newColIndices), origCols) = (((m, newColIndices'), origCols'):ms, endI)\n      where\n        -- produce (length newColIndices) number of mappings\n        endI           = startI + length newColIndices\n        -- re-number the newColIndices according to the lookup list\n        newColIndices' = map (origCols !!) newColIndices\n        -- add columns in the (combined) matrix for the newly\n        -- generated columns from running normHNF on m.\n        origCols'      = origCols ++ [startI .. endI-1]\n\ngenUnitAssignments' :: SortFn -> Constraints -> [([UnitInfo], UnitInfo)]\ngenUnitAssignments' _ [] = []\ngenUnitAssignments' sortfn cons\n  | null colList                                      = []\n  | null inconsists                                   = unitAssignments\n  | otherwise                                         = []\n  where\n    (lhsM, rhsM, inconsists, lhsColA, rhsColA) = constraintsToMatrices' sortfn cons\n    unsolvedM | rows rhsM == 0 || cols rhsM == 0 = lhsM\n              | rows lhsM == 0 || cols lhsM == 0 = rhsM\n              | otherwise                        = fromBlocks [[lhsM, rhsM]]\n    (solvedM, newColIndices)      = splitNormHNF unsolvedM\n    -- solvedM can have additional columns and rows from normHNF;\n    -- cosolvedM corresponds to the original lhsM.\n    -- cosolvedM                     = subMatrix (0, 0) (rows solvedM, cols lhsM) solvedM\n    -- cosolvedMrhs                  = subMatrix (0, cols lhsM) (rows solvedM, cols solvedM - cols lhsM) solvedM\n\n    -- generate a colList with both the original columns and new ones generated\n    -- if a new column generated was derived from the right-hand side then negate it\n    numLhsCols                    = 1 + snd (A.bounds lhsColA)\n    colList                       = map (1,) (A.elems lhsColA ++ A.elems rhsColA) ++ map genC newColIndices\n    genC n | n >= numLhsCols      = (-k, UnitParamImpAbs (show u))\n           | otherwise            = (k, UnitParamImpAbs (show u))\n      where (k, u) = colList !! n\n    -- Convert the rows of the solved matrix into flattened unit\n    -- expressions in the form of \"unit ** k\".\n    unitPow (k, u) x              = UnitPow u (k * x)\n    unitPows                      = map (concatMap flattenUnits . zipWith unitPow colList) (H.toLists solvedM)\n\n    -- Variables to the left, unit names to the right side of the equation.\n    unitAssignments               = map (fmap (foldUnits . map negatePosAbs) . checkSanity . partition (not . isUnitRHS')) unitPows\n    isUnitRHS' (UnitPow (UnitName _) _)        = True\n    isUnitRHS' (UnitPow (UnitParamEAPAbs _) _) = True\n    -- Because this version of isUnitRHS different from\n    -- constraintsToMatrix interpretation, we need to ensure that any\n    -- moved ParamPosAbs units are negated, because they are\n    -- effectively being shifted across the equal-sign:\n    isUnitRHS' (UnitPow (UnitParamImpAbs _) _) = True\n    isUnitRHS' (UnitPow (UnitParamPosAbs (_, 0)) _) = False\n    isUnitRHS' (UnitPow (UnitParamPosAbs _) _) = True\n    isUnitRHS' _                               = False\n\ncheckSanity :: ([UnitInfo], [UnitInfo]) -> ([UnitInfo], [UnitInfo])\ncheckSanity (u1@[UnitPow (UnitVar _) _], u2)\n  | or $ [ True | UnitParamPosAbs (_, _) <- universeBi u2 ]\n      ++ [ True | UnitParamImpAbs _      <- universeBi u2 ] = (u1++u2,[])\ncheckSanity (u1@[UnitPow (UnitParamVarAbs (f, _)) _], u2)\n  | or [ True | UnitParamPosAbs (f', _) <- universeBi u2, f' /= f ] = (u1++u2,[])\ncheckSanity c = c\n\n--------------------------------------------------\n\n-- FIXME: you know better...\napproxEq :: Double -> Double -> Bool\napproxEq a b = abs (b - a) < epsilon\nnotApproxEq :: Double -> Double -> Bool\nnotApproxEq a b = not (approxEq a b)\nepsilon :: Double\nepsilon = 0.001 -- arbitrary\n\n--------------------------------------------------\n\ntype RowNum = Int               -- ^ 'row number' of matrix\ntype ColNum = Int               -- ^ 'column number' of matrix\n-- | Represents a subproblem of AX=B where the row numbers and column\n-- numbers help you re-map back to the original problem.\ntype Subproblem = ([RowNum], (H.Matrix Double, H.Matrix Double), [ColNum])\n\n-- | Divide up the AX=B problem into smaller problems based on the\n-- 'related columns' and their corresponding rows in the\n-- right-hand-side of the equation. Where lhsM = A and rhsM = B.  The\n-- resulting list of subproblems contains the new, smaller As and Bs\n-- as well as a list of original row numbers and column numbers to\n-- aide re-mapping back to the original lhsM and rhsM.\nsplitMatWithRHS :: H.Matrix Double -> H.Matrix Double -> [Subproblem]\nsplitMatWithRHS lhsM rhsM | cols lhsM > 0 = map (eachComponent . sort) $ scc (relatedColumnsGraph lhsM)\n                          | otherwise     = []\n  where\n    -- Gets called on every strongly-connected component / related set of columns.\n    eachComponent cs = (rs, mats, cs)\n      where\n        -- Selected columns\n        lhsSelCols :: H.Matrix Double\n        lhsSelCols = lhsM \u00bf cs\n\n        csLen = cols lhsSelCols\n\n        -- Find the row numbers of the 'all zero' rows in lhsM.\n        lhsAllZeroRows :: [RowNum]\n        lhsAllZeroRows = map fst . filter (all (approxEq 0) . snd) . zip [0..] $ H.toLists lhsM\n\n        -- Find the row numbers that correspond to the non-zero co-efficients in the selected columns.\n        lhsNonZeroColRows :: [(RowNum, [Double])]\n        lhsNonZeroColRows = filter (any (notApproxEq 0) . snd) . zip [0..] . H.toLists $ lhsSelCols\n\n        -- List of all the row numbers and row values combined from the two above variables.\n        lhsNumberedRows :: [(RowNum, [Double])]\n        lhsNumberedRows = sortBy (comparing fst) $ lhsNonZeroColRows ++ zip lhsAllZeroRows (repeat (replicate csLen 0))\n\n        -- For each of the above LHS rows find a corresponding RHS row.\n        rhsSelRows :: [[Double]]\n        rhsSelRows | rows rhsM > 0 = H.toLists (rhsM ? map fst lhsNumberedRows)\n                   | otherwise     = []\n\n        reassoc (a, b) c = (a, (b, c))\n\n        notAllZero (_, (lhs, rhs)) = any (notApproxEq 0) (lhs ++ rhs)\n\n        -- Zip the selected LHS, RHS rows together, filter out any that are all zeroes.\n        numberedRows :: ([RowNum], [([Double], [Double])])\n        numberedRows = unzip . filter notAllZero $ zipWith reassoc lhsNumberedRows rhsSelRows\n\n        rs :: [RowNum]          -- list of row numbers in the subproblem\n        mats :: (H.Matrix Double, H.Matrix Double) -- LHS/RHS subproblem matrices\n        (rs, mats) = second ((H.fromLists *** H.fromLists) . unzip) numberedRows\n\n-- | Split the lhsM/rhsM problem into subproblems and then look for\n-- inconsistent rows in each subproblem, concatenating all of the\n-- inconsistent row numbers found (in terms of the rows of the\n-- original lhsM).\nsplitFindInconsistentRows :: H.Matrix Double -> H.Matrix Double -> [RowNum]\nsplitFindInconsistentRows lhsMat rhsMat = concatMap eachComponent $ splitMatWithRHS lhsMat rhsMat\n  where\n    eachComponent (rs, (lhsM, rhsM), _) = map (rs !!) $ findInconsistentRows lhsM augM\n      where\n        -- Augmented matrix is defined as the combined LHS/RHS matrices.\n        augM\n          | rows rhsM == 0 || cols rhsM == 0 = lhsM\n          | rows lhsM == 0 || cols lhsM == 0 = rhsM\n          | otherwise = fromBlocks [[lhsM, rhsM]]\n\n-- | Break out the 'unrelated' columns in a single matrix into\n-- separate matrices, along with a list of their original column\n-- positions.\nsplitMat :: H.Matrix Double -> [(H.Matrix Double, [ColNum])]\nsplitMat m = map (eachComponent . sort) $ scc (relatedColumnsGraph m)\n  where\n    eachComponent cs = (H.fromLists . filter (any (/= 0)) . H.toLists $ m \u00bf cs, cs)\n\n-- | Bring together the split matrices and put the columns back in\n-- their original order. Rows may not be in the same order as the\n-- original, but the constraints should be equivalent.\njoinMat :: [(H.Matrix Double, [Int])] -> H.Matrix Double\njoinMat ms = sortedM\n  where\n    disorderedM = H.diagBlock (map fst ms)\n    colsWithIdx = zip (concatMap snd ms) . H.toColumns $ disorderedM\n    sortedM     = H.fromColumns . map snd . sortBy (comparing fst) $ colsWithIdx\n\n-- | Turn a matrix into a graph where each node represents a column\n-- and each edge represents two columns that have non-zero\n-- co-efficients in some row. Basically, 'related columns'. Also\n-- includes self-refs for each node..\nrelatedColumnsGraph :: H.Matrix Double -> Gr () ()\nrelatedColumnsGraph m = mkGraph (map (,()) ns) (map (\\ (a,b) -> (a,b,())) es)\n  where\n    nonZeroCols = [ [ j | j <- [0..cols m - 1], not (m `atIndex` (i, j) `approxEq` 0) ] | i <- [0..rows m - 1] ]\n    ns          = nub $ concat nonZeroCols\n    es          = [ (i, j) | cs <- nonZeroCols, [i, j] <- sequence [cs, cs] ]\n\n-- Convert a set of constraints into a matrix of co-efficients, and a\n-- reverse mapping of column numbers to units.\nconstraintsToMatrix :: Constraints -> (H.Matrix Double, [Int], A.Array Int UnitInfo)\nconstraintsToMatrix cons\n  | all null lhs = (H.ident 0, [], A.listArray (0, -1) [])\n  | otherwise = (augM, inconsists, A.listArray (0, length colElems - 1) colElems)\n  where\n    -- convert each constraint into the form (lhs, rhs)\n    consPairs       = filter (uncurry (/=)) $ flattenConstraints cons\n    -- ensure terms are on the correct side of the equal sign\n    shiftedCons     = map shiftTerms consPairs\n    lhs             = map fst shiftedCons\n    rhs             = map snd shiftedCons\n    (lhsM, lhsCols) = flattenedToMatrix colSort lhs\n    (rhsM, rhsCols) = flattenedToMatrix colSort rhs\n    colElems        = A.elems lhsCols ++ A.elems rhsCols\n    augM            = if rows rhsM == 0 || cols rhsM == 0 then lhsM else if rows lhsM == 0 || cols lhsM == 0 then rhsM else fromBlocks [[lhsM, rhsM]]\n    inconsists      = splitFindInconsistentRows lhsM rhsM\n\nconstraintsToMatrices :: Constraints -> (H.Matrix Double, H.Matrix Double, [Int], A.Array Int UnitInfo, A.Array Int UnitInfo)\nconstraintsToMatrices cons = constraintsToMatrices' colSort cons\n\nconstraintsToMatrices' :: SortFn -> Constraints -> (H.Matrix Double, H.Matrix Double, [Int], A.Array Int UnitInfo, A.Array Int UnitInfo)\nconstraintsToMatrices' sortfn cons\n  | all null lhs = (H.ident 0, H.ident 0, [], A.listArray (0, -1) [], A.listArray (0, -1) [])\n  | otherwise = (lhsM, rhsM, inconsists, lhsCols, rhsCols)\n  where\n    -- convert each constraint into the form (lhs, rhs)\n    consPairs       = filter (uncurry (/=)) $ flattenConstraints cons\n    -- ensure terms are on the correct side of the equal sign\n    shiftedCons     = map shiftTerms consPairs\n    lhs             = map fst shiftedCons\n    rhs             = map snd shiftedCons\n    (lhsM, lhsCols) = flattenedToMatrix sortfn lhs\n    (rhsM, rhsCols) = flattenedToMatrix sortfn rhs\n    inconsists      = splitFindInconsistentRows lhsM rhsM\n\n-- [[UnitInfo]] is a list of flattened constraints\nflattenedToMatrix :: SortFn -> [[UnitInfo]] -> (H.Matrix Double, A.Array Int UnitInfo)\nflattenedToMatrix sortfn cons = (m, A.array (0, numCols - 1) (map swap uniqUnits))\n  where\n    m = runSTMatrix $ do\n          newM <- newMatrix 0 numRows numCols\n          -- loop through all constraints\n          forM_ (zip cons [0..]) $ \\ (unitPows, row) -> do\n            -- write co-efficients for the lhs of the constraint\n            forM_ unitPows $ \\ (UnitPow u k) -> do\n              case M.lookup u colMap of\n                Just col -> readMatrix newM row col >>= (writeMatrix newM row col . (+k))\n                _        -> return ()\n          return newM\n    -- identify and enumerate every unit uniquely\n    uniqUnits = flip zip [0..] . map head . group . sortBy sortfn $ [ u | UnitPow u _ <- concat cons ]\n    -- map units to their unique column number\n    colMap    = M.fromList uniqUnits\n    numRows   = length cons\n    numCols   = M.size colMap\n\nnegateCons :: [UnitInfo] -> [UnitInfo]\nnegateCons = map (\\ (UnitPow u k) -> UnitPow u (-k))\n\nnegatePosAbs :: UnitInfo -> UnitInfo\nnegatePosAbs (UnitPow (UnitParamPosAbs x) k) = UnitPow (UnitParamPosAbs x) (-k)\nnegatePosAbs (UnitPow (UnitParamImpAbs v) k) = UnitPow (UnitParamImpAbs v) (-k)\nnegatePosAbs u                               = u\n\n--------------------------------------------------\n\n-- Units that should appear on the right-hand-side of the matrix during solving\nisUnitRHS :: UnitInfo -> Bool\nisUnitRHS (UnitPow (UnitName _) _)        = True\nisUnitRHS (UnitPow (UnitParamEAPAbs _) _) = True\nisUnitRHS _                               = False\n\n-- | Shift UnitNames/EAPAbs poly units to the RHS, and all else to the LHS.\nshiftTerms :: ([UnitInfo], [UnitInfo]) -> ([UnitInfo], [UnitInfo])\nshiftTerms (lhs, rhs) = (lhsOk ++ negateCons rhsShift, rhsOk ++ negateCons lhsShift)\n  where\n    (lhsOk, lhsShift) = partition (not . isUnitRHS) lhs\n    (rhsOk, rhsShift) = partition isUnitRHS rhs\n\n-- | Shift terms based on function f (<- True, False ->).\nshiftTermsBy :: (UnitInfo -> Bool) -> ([UnitInfo], [UnitInfo]) -> ([UnitInfo], [UnitInfo])\nshiftTermsBy f (lhs, rhs) = (lhsOk ++ negateCons rhsShift, rhsOk ++ negateCons lhsShift)\n  where\n    (lhsOk, lhsShift) = partition f lhs\n    (rhsOk, rhsShift) = partition (not . f) rhs\n\n\n-- | Translate all constraints into a LHS, RHS side of units.\nflattenConstraints :: Constraints -> [([UnitInfo], [UnitInfo])]\nflattenConstraints = map (\\ (ConEq u1 u2) -> (flattenUnits u1, flattenUnits u2))\n\n--------------------------------------------------\n-- Matrix solving functions based on HMatrix\n\n-- | Returns given matrix transformed into Reduced Row Echelon Form\nrref :: H.Matrix Double -> H.Matrix Double\nrref a = snd $ rrefMatrices' a 0 0 []\n  where\n    -- (a', den, r) = Flint.rref a\n\n-- Provenance of matrices.\ndata RRefOp\n  = ElemRowSwap Int Int         -- ^ swapped row with row\n  | ElemRowMult Int Double      -- ^ scaled row by constant\n  | ElemRowAdds [(Int, Int)]    -- ^ set of added row onto row ops\n  deriving (Show, Eq, Ord)\n\n-- worker function\n-- invariant: the matrix a is in rref except within the submatrix (j-k,j) to (n,n)\nrrefMatrices' :: H.Matrix Double -> Int -> Int -> [(H.Matrix Double, RRefOp)] ->\n                 ([(H.Matrix Double, RRefOp)], H.Matrix Double)\nrrefMatrices' a j k mats\n  -- Base cases:\n  | j - k == n            = (mats, a)\n  | j     == m            = (mats, a)\n\n  -- When we haven't yet found the first non-zero number in the row, but we really need one:\n  | a `atIndex` (j - k, j) == 0 = case findIndex (/= 0) below of\n    -- this column is all 0s below current row, must move onto the next column\n    Nothing -> rrefMatrices' a (j + 1) (k + 1) mats\n    -- we've found a row that has a non-zero element that can be swapped into this row\n    Just i' -> rrefMatrices' (swapMat <> a) j k ((swapMat, ElemRowSwap i (j - k)):mats)\n      where i       = j - k + i'\n            swapMat = elemRowSwap n i (j - k)\n\n  -- We have found a non-zero cell at (j - k, j), so transform it into\n  -- a 1 if needed using elemRowMult, and then clear out any lingering\n  -- non-zero values that might appear in the same column, using\n  -- elemRowAdd:\n  | otherwise             = rrefMatrices' a2 (j + 1) k mats2\n  where\n    n     = rows a\n    m     = cols a\n    below = getColumnBelow a (j - k, j)\n    scale = recip (a `atIndex` (j - k, j))\n    erm   = elemRowMult n (j - k) scale\n\n    -- scale the row if the cell is not already equal to 1\n    (a1, mats1) | a `atIndex` (j - k, j) /= 1 = (erm <> a, (erm, ElemRowMult (j - k) scale):mats)\n                | otherwise                   = (a, mats)\n\n    -- Locate any non-zero values in the same column as (j - k, j) and\n    -- cancel them out. Optimisation: instead of constructing a\n    -- separate elemRowAdd matrix for each cancellation that are then\n    -- multiplied together, simply build a single matrix that cancels\n    -- all of them out at the same time, using the ST Monad.\n    findAdds _ curM ms\n      | isWritten = (newMat <> curM, (newMat, ElemRowAdds matOps):ms)\n      | otherwise = (curM, ms)\n      where\n        (isWritten, matOps, newMat) = runST $ do\n          newM <- newMatrix 0 n n :: ST s (STMatrix s Double)\n          sequence_ [ writeMatrix newM i' i' 1 | i' <- [0 .. (n - 1)] ]\n          let f w o i | i >= n                  = return (w, o)\n                      | i == j - k              = f w o (i + 1)\n                      | a `atIndex` (i, j) == 0 = f w o (i + 1)\n                      | otherwise               = writeMatrix newM i (j - k) (- (a `atIndex` (i, j)))\n                                                  >> f True ((i, j - k):o) (i + 1)\n          (isW, ops) <- f False [] 0\n          (isW, ops,) `fmap` freezeMatrix newM\n\n    (a2, mats2) = findAdds (0::Int) a1 mats1\n\n-- Get a list of values that occur below (i, j) in the matrix a.\ngetColumnBelow :: H.Matrix Double -> (Int, Int) -> [Double]\ngetColumnBelow a (i, j) = concat . H.toLists $ subMatrix (i, j) (n - i, 1) a\n  where n = rows a\n\n-- 'Elementary row operation' matrices\nelemRowMult :: Int -> Int -> Double -> H.Matrix Double\nelemRowMult n i k = diag (H.fromList (replicate i 1.0 ++ [k] ++ replicate (n - i - 1) 1.0))\n\nelemRowSwap :: Int -> Int -> Int -> H.Matrix Double\nelemRowSwap n i j\n  | i == j          = ident n\n  | i > j           = elemRowSwap n j i\n  | otherwise       = ident n ? ([0..i-1] ++ [j] ++ [i+1..j-1] ++ [i] ++ [j+1..n-1])\n\n--------------------------------------------------\n\ntype GraphCol = IM.IntMap IS.IntSet   -- graph from origin to dest.\ntype Provenance = IM.IntMap IS.IntSet -- graph from dest. to origin\n\nopToGraphCol :: RRefOp -> GraphCol\nopToGraphCol ElemRowMult{} = IM.empty\nopToGraphCol (ElemRowSwap i j) = IM.fromList [ (i, IS.singleton j), (j, IS.singleton i) ]\nopToGraphCol (ElemRowAdds l)   = IM.fromList $ concat [ [(i, IS.fromList [i,j]), (j, IS.singleton j)]  | (i, j) <- l ]\n\ngraphColCombine :: GraphCol -> GraphCol -> GraphCol\ngraphColCombine g1 g2 = IM.unionWith (curry snd) g1 $ IM.map (IS.fromList . trans . IS.toList) g2\n  where\n    trans = concatMap (\\ i -> [i] `fromMaybe` (IS.toList <$> IM.lookup i g1))\n\ninvertGraphCol :: GraphCol -> GraphCol\ninvertGraphCol g = IM.fromListWith IS.union [ (i, IS.singleton j) | (j, jset) <- IM.toList g, i <- IS.toList jset ]\n\nprovenance :: H.Matrix Double -> (H.Matrix Double, Provenance)\nprovenance m = (m', p)\n  where\n    (matOps, m') = rrefMatrices' m 0 0 []\n    p = invertGraphCol . foldl' graphColCombine IM.empty . map opToGraphCol $ map snd matOps\n\n-- Worker functions:\n\nfindInconsistentRows :: H.Matrix Double -> H.Matrix Double -> [Int]\nfindInconsistentRows coA augA | rows augA < 2 = []\n                              | otherwise     = inconsistent\n  where\n    inconsistent = [0..(rows augA - 1)] \\\\ consistent\n\n    consistent\n      -- if the space is relatively small, try it all\n      | rows augA < 16 = head (filter tryRows (powerset $ reverse [0..(rows augA - 1)]))\n      | otherwise = head (filter tryRows (tails ( [0..(rows augA - 1)])) ++ [[]])\n\n    powerset = filterM (const [True, False])\n\n    -- Rouch\u00e9\u2013Capelli theorem is that if the rank of the coefficient\n    -- matrix is not equal to the rank of the augmented matrix then\n    -- the system of linear equations is inconsistent.\n    tryRows [] = True\n    tryRows ns = (rank coA' == rank augA')\n      where\n        coA'  = coA ? ns\n        augA' = augA ? ns\n\n-- | Create unique names for all of the inferred implicit polymorphic\n-- unit variables.\nchooseImplicitNames :: [(VV, UnitInfo)] -> [(VV, UnitInfo)]\nchooseImplicitNames vars = replaceImplicitNames (genImplicitNamesMap vars) vars\n\ngenImplicitNamesMap :: Data a => a -> M.Map UnitInfo UnitInfo\ngenImplicitNamesMap x = M.fromList [ (absU, UnitParamEAPAbs (newN, newN)) | (absU, newN) <- zip absUnits newNames ]\n  where\n    absUnits = nub [ u | u@(UnitParamPosAbs _)             <- universeBi x ] ++\n               nub [ u | u@(UnitParamImpAbs _)             <- universeBi x ]\n    eapNames = nub $ [ n | (UnitParamEAPAbs (_, n))      <- universeBi x ] ++\n                     [ n | (UnitParamEAPUse ((_, n), _)) <- universeBi x ]\n    newNames = filter (`notElem` eapNames) . map ('\\'':) $ nameGen\n    nameGen  = concatMap sequence . tail . inits $ repeat ['a'..'z']\n\nreplaceImplicitNames :: Data a => M.Map UnitInfo UnitInfo -> a -> a\nreplaceImplicitNames implicitMap = transformBi replace\n  where\n    replace u@(UnitParamPosAbs _) = fromMaybe u $ M.lookup u implicitMap\n    replace u@(UnitParamImpAbs _) = fromMaybe u $ M.lookup u implicitMap\n    replace u                     = u\n\n-- | Identifies the variables that need to be annotated in order for\n-- inference or checking to work.\ncriticalVariables :: Constraints -> [UnitInfo]\ncriticalVariables [] = []\ncriticalVariables cons = filter (not . isUnitRHS') $ map (colA A.!) criticalIndices\n  where\n    (unsolvedM, _, colA)          = constraintsToMatrix cons\n    solvedM                       = rref unsolvedM\n    uncriticalIndices             = mapMaybe (findIndex (/= 0)) $ H.toLists solvedM\n    criticalIndices               = A.indices colA \\\\ uncriticalIndices\n    isUnitRHS' (UnitName _)       = True; isUnitRHS' _ = False\n\n-- | Returns just the list of constraints that were identified as\n-- being possible candidates for inconsistency, if there is a problem.\ninconsistentConstraints :: Constraints -> Maybe Constraints\ninconsistentConstraints [] = Nothing\ninconsistentConstraints cons\n  | not (null direct) = Just direct\n  | null inconsists   = Nothing\n  | otherwise         = Just [ con | (con, i) <- zip cons [0..], i `elem` inconsists ]\n  where\n    (_, _, inconsists, _, _) = constraintsToMatrices cons\n    direct = detectInconsistency $ genUnitAssignments' colSort cons\n", "meta": {"hexsha": "f3ba97ba00fc3703f641d129a93f1889c6b1b2c7", "size": 27325, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Camfort/Specification/Units/InferenceBackend.hs", "max_stars_repo_name": "raehik/camfort", "max_stars_repo_head_hexsha": "2f5ac9a478116ae8c7aa2a5e079b81aa58988e45", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 90, "max_stars_repo_stars_event_min_datetime": "2016-06-02T15:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T20:10:14.000Z", "max_issues_repo_path": "src/Camfort/Specification/Units/InferenceBackend.hs", "max_issues_repo_name": "apthorpe/camfort", "max_issues_repo_head_hexsha": "1e307ae972b2fe6f63af6d3b0a3d106eec77e8a8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 124, "max_issues_repo_issues_event_min_datetime": "2016-05-25T13:21:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T14:26:03.000Z", "max_forks_repo_path": "src/Camfort/Specification/Units/InferenceBackend.hs", "max_forks_repo_name": "raehik/camfort", "max_forks_repo_head_hexsha": "2f5ac9a478116ae8c7aa2a5e079b81aa58988e45", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2016-06-02T14:51:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T15:59:33.000Z", "avg_line_length": 46.1570945946, "max_line_length": 149, "alphanum_fraction": 0.6334126258, "num_tokens": 7487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.4140485761621227}}
{"text": "{-# LANGUAGE BangPatterns #-}\n-----------------------------------------------------------------------------\n--\n-- Module      :  AI.Network.RNN.Util\n-- Copyright   :  (c) JP Moresmau\n-- License     :  BSD3\n--\n-- Maintainer  :  JP Moresmau <jp@moresmau.fr>\n-- Stability   :  experimental\n-- Portability :\n--\n-- | Utility functions\n--\n-----------------------------------------------------------------------------\n\nmodule AI.Network.RNN.Util where\n\nimport Control.Parallel.Strategies\nimport Control.Monad.Random\n\nimport Numeric.LinearAlgebra.HMatrix\n\nimport Data.List\nimport Data.Ord\nimport qualified Data.Set as S\n\n-- | Calculate the product of a matrix by a vector, with both represented by a list\nlistMProd :: (Num a) => [a] -> [a] -> [a]\nlistMProd mdt vdt = go mdt vdt 0\n  where\n    go [] _  !s = [s]\n    go ls [] !s = s : go ls vdt 0\n    go (y:ys) (x:xs) !ix = go ys xs (y*x+ix)\n--    map (foldr (\\(a,b) c->a*b+c) 0) $ go mdt vdt []\n--  where\n--    go [] _  s = [s]\n--    go ls [] s = s : go ls vdt []\n--    go (y:ys) (x:xs) acc = go ys xs ((y,x):acc)\n--listMProd mdt vdt = let (_,l,lst)= foldl' go (vdt,[],0) mdt\n--    in reverse $ lst:l\n--    where\n--        go ([],acc,ix) m =\n--            let (x:xs)=vdt\n--            in (xs,ix:acc,x*m)\n--        go ((x:xs),acc,ix) m = (xs,acc,x*m+ix)\n--listMProd mdt vdt = let (_,l,lst)= foldr go (rvdt,[],0) mdt\n--    in lst:l\n--    where\n--        rvdt = reverse vdt\n--        go m ([],acc,ix) =\n--            let (x:xs)=rvdt\n--            in (xs,ix:acc,x*m)\n--        go m ((x:xs),acc,ix) = (xs,acc,x*m+ix)\n--listMProd mdt vdt = map sum $ takes1 (length vdt) $ zipWith (*) mdt (cycle vdt)\n\n-- | Calculate the mean of a list\ncalcMeanList :: (Fractional a) => [a] -> a\ncalcMeanList = uncurry (/) . foldr (\\e (s,c) -> (e+s,c+1)) (0,0)\n\ntakes1 :: Int -> [a] -> [[a]]\ntakes1 _ [] = []\ntakes1 s xs = let\n    (one,two) = splitAt s xs\n    in one : takes1 s two\n\n\n-- | Split a given list into a series of list whose length is given by the first argument\ntakes :: [Int] -> [a] -> [[a]]\ntakes [] _ = []\ntakes (_:sz) [] = [] : takes sz []\ntakes (s:sz) xs = let\n    (one,two) = splitAt s xs\n    in one : takes sz two\n\n-- | It's a simple, differentiable sigmoid function.\nsigmoid :: Floating a => a -> a\nsigmoid x = 1 / (1 + exp (-x))\n{-# INLINE sigmoid #-}\n\n-- | Normalize a list of values between 0 and 1\nnormalize :: (Floating b,Ord b)=> [(a,b)] -> [(a,b)]\nnormalize xs =\n    let\n        ws = map snd xs\n        mi = minimum ws\n        mx = maximum ws\n        df = mx-mi\n     in  map (\\(a,w)->(a,(w-mi)/df)) xs\n\n-- | Parallel zipwith\nparZipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\nparZipWith f xs ys = withStrategy (parList rseq) $ zipWith f xs ys\n\n-- | Parallel zipWith3\nparZipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]\nparZipWith3 f xs ys zs = withStrategy (parList rseq) $ zipWith3 f xs ys zs\n\n-- | Number of binary digits necessary to store the given number\nbinaryDigits :: (Num a, Ord a) => a -> a\nbinaryDigits a = go 1 1\n    where go nb sz\n            | nb == a = sz\n            | nb > a  = sz - 1\n            | otherwise = go (nb*2) (sz+1)\n\n-- | Number of bits needed to store in a sparse manner (with 2 bits) the given number\nsparseSize :: (Integral a, Ord a) => a -> a\nsparseSize a = go 1\n      where\n        go nb =\n            let pos = nb * (nb - 1) `div` 2\n            in if pos >= a\n                then nb\n                else go (nb+1)\n\n-- | Sparse representation: store all numbers from 0 to n using 2 bits\n-- Returns the location of each two bits\nsparse :: Int -> [(Int,Int)]\nsparse n = let\n    sz = sparseSize n\n    in take n $ iterate (gen sz) (0,1)\n    where gen sz (a,b) =\n            if b==sz-1 then (a+1,a+2)\n                       else (a,b+1)\n\n-- | Standard Normal distribution\nstdNormal :: (Monad m,RandomGen g) => RandT g m (Double,Double)\nstdNormal = do\n    (x1,x2,w1)<-gen\n    let w  = sqrt( (-2 * log( w1 ) ) / w1 )\n        y1 = x1 * w;\n        y2 = x2 * w;\n    return (y1,y2)\n    where\n        ranx = do\n            r1 <- getRandomR (0,1)\n            return (2 * r1 - 1)\n        gen = do\n            x1 <- ranx\n            x2 <- ranx\n            let w = x1 * x1 + x2 * x2\n            if w>=1 then gen else return (x1,x2,w)\n\nsoftmax :: [Double] -> [Double]\nsoftmax is =\n    let den = sum $ map exp is\n    in map (( / den) . exp) is\n\nsoftmaxV :: Vector Double -> Vector Double\nsoftmaxV is =\n    let den = sumElements $ cmap exp is\n    in cmap (( / den) . exp) is\n\neuclidian :: Vector Double -> Vector Double -> Double\neuclidian v1 v2 = sumElements $ cmap (**2) (v1 - v2)\n\nequilateralEncoding :: Int -> Matrix Double\nequilateralEncoding n =\n    let z1 = replicate (n-2) 0\n        m = (n><(n-1)) (-1: z1 ++ (1 : z1) ++ repeat 0)\n    in foldl' pass m [2..n-1]\n    where\n        r :: Double -> Double\n        r k = -1 / k\n        f :: Double -> Double\n        f k = sqrt (k*k -1) / k\n        pass :: Matrix Double -> Int -> Matrix Double\n        pass m1 ik =\n            let k = fromIntegral ik\n                f1 = f k\n                a0 = concatMap (\\i->map (\\j->((i,j),f1)) [0..ik-2]) [0..ik-1]\n                m2 = accum m1 (*) a0\n                r1 = r k\n                a1 = map (\\x->((x,ik-1),r1)) [0..ik-1] ++ [((ik,ik-1),1)]\n                m3 = accum m2 const a1\n            in m3\n\nequilateralDecoding :: Matrix Double -> Vector Double -> Int\nequilateralDecoding m os =\n    let rs = zip (toRows m) [0..]\n        es = map (\\(vs,ix)->(euclidian vs os,ix)) rs\n    in snd $ minimumBy (comparing fst) es\n\nroundTo :: (Fractional a, Integral b, RealFrac r) =>\n                 b -> r -> a\nroundTo n f=  (fromInteger $ round $ f * (10^n)) / (10.0^^n)\n\nordNub :: (Ord a) => [a] -> [a]\nordNub l = go S.empty l\n     where\n       go _ []     = []\n       go s (x:xs) = if x `S.member` s then go s xs\n                                     else x : go (S.insert x s) xs\n", "meta": {"hexsha": "278445b1190afd91e6141f5b22e5e83296df458c", "size": 5839, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Network/RNN/Util.hs", "max_stars_repo_name": "JPMoresmau/rnn", "max_stars_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-08-02T17:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T06:56:40.000Z", "max_issues_repo_path": "src/AI/Network/RNN/Util.hs", "max_issues_repo_name": "JPMoresmau/rnn", "max_issues_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-01T18:47:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-01T18:47:41.000Z", "max_forks_repo_path": "src/AI/Network/RNN/Util.hs", "max_forks_repo_name": "JPMoresmau/rnn", "max_forks_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-12-10T18:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T00:02:09.000Z", "avg_line_length": 30.0979381443, "max_line_length": 89, "alphanum_fraction": 0.5029970885, "num_tokens": 1936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.41402276995444975}}
{"text": "{-# LANGUAGE FlexibleContexts, OverloadedLists, OverloadedStrings, UndecidableInstances #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Main (\n\tmain,\n\ttestXor, testClassify, testIris, testMnist\n\t) where\n\nimport Prelude.Unicode\n\nimport Control.DeepSeq\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Control.Monad.Morph\nimport qualified Data.Attoparsec.Text as A\nimport qualified Data.Text.IO as T\nimport qualified Data.Vector as V\nimport System.Random (mkStdGen)\nimport Test.Hspec\nimport Numeric.LinearAlgebra hiding (conv2, conv)\nimport Text.Format\n\nimport Numeric.Trainee.Data\nimport Numeric.Trainee.Neural\nimport Numeric.Trainee.Gradee (reshapeVec, flattenMat, concatVecs)\n\nmain \u2237 IO ()\nmain = hspec $\n\tdescribe \"training neural network\" $ do\n\t\tit \"should approximate xor function\" testXor\n\t\tit \"should classify objects\" testClassify\n\t\tit \"should support 3 classes\" testIris\n\ntestXor \u2237 IO ()\ntestXor = do\n\tn \u2190 return $ netSeed (mkStdGen 0) $ fc sigma 2 2 \u2b43 fc sigma 2 2 \u2b43 fc sigma 2 1 \u2237 IO (Net Double)\n\t(e, n') \u2190 runLearnT n $ trainUntil 5.0 10000 4 1e-4 squared xorSamples\n\te `shouldSatisfy` (\u2264 1e-4)\n\tmapM_ (shouldPass n' 0.1) xorSamples\n\ntestClassify \u2237 IO ()\ntestClassify = do\n\tn \u2190 return $ netSeed (mkStdGen 0) $ fc sigma 4 4 \u2b43 fc sigma 4 2 \u2b43 fc sigma 2 1 \u2237 IO (Net Double)\n\tlet\n\t\tcases \u2237 [(String, Vector Double \u2192 Vector Double)]\n\t\tcases = [\n\t\t\t(\"adult+stretch\", fn $ \\[_, _, act, age] \u2192 act \u2261 0.0 \u2228 age \u2261 0.0),\n\t\t\t(\"adult-stretch\", fn $ \\[_, _, act, age] \u2192 act \u2261 0.0 \u2227 age \u2261 0.0),\n\t\t\t(\"yellow-small+adult-stretch\", fn $ \\[color, sz, act, age] \u2192 (color \u2261 0.0 \u2227 sz \u2261 0.0) \u2228 (act \u2261 0.0 \u2227 age \u2261 0.0)),\n\t\t\t(\"yellow-small\", fn $ \\[color, sz, _, _] \u2192 color \u2261 0.0 \u2227 sz \u2261 0.0)]\n\t\tfn \u2237 ([Double] \u2192 Bool) \u2192 Vector Double \u2192 Vector Double\n\t\tfn f = vector \u2218 return \u2218 fromIntegral \u2218 fromEnum \u2218 f \u2218 toList\n\tforM_ cases $ \\(name, fun) \u2192 do\n\t\tclasses \u2190 readBalloonSamples $ \"data/classify/balloon/{name}.data\" ~~ (\"name\" ~% name)\n\t\t(e, n') \u2190 runLearnT n $ trainUntil 10.0 1000 10 1e-4 squared classes\n\t\te `shouldSatisfy` (\u2264 1e-4)\n\t\tmapM_ (shouldPass n' 0.1) [xs \u21e2 fun xs |\n\t\t\txs \u2190 map vector (replicateM 4 [0.0, 1.0])]\n\n\ninstance Show (Vector a) \u21d2 FormatBuild (Vector a)\n\n\ntestIris \u2237 IO ()\ntestIris = do\n\tn \u2190 return $ netSeed (mkStdGen 0) $ fc sigma 4 12 \u2b43 fc sigma 12 3 \u2237 IO (Net Double)\n\tclasses \u2190 readIrisData \"data/classify/iris/iris.data\"\n\t(_, n') \u2190 runLearnT n $ hoist (`evalStateT` (rightAnswers n classes, 0)) $ learnIris classes\n\tlet\n\t\tfailedSamples = filter (not \u2218 rightClass n' \u2218 snd) $ zip ([1..] \u2237 [Integer]) (V.toList classes)\n\tputStrLn \"--- Done. ---\"\n\tputStrLn \"Failed samples:\"\n\tforM_ failedSamples $ \\(i, Sample inp outp) \u2192 putStrLn $ \"{n}\\t{input} \u2192 {output} \u2262 {right}\"\n\t\t~~ (\"n\" ~% i)\n\t\t~~ (\"input\" ~% inp)\n\t\t~~ (\"output\" ~% eval n' inp)\n\t\t~~ (\"right\" ~% outp)\n\tlength failedSamples `shouldSatisfy` (\u2264 2)\n\twhere\n\t\tlearnIris \u2237 Samples (Vector Double) (Vector Double) \u2192 StateT (Net Double) (StateT (Int, Int) IO) ()\n\t\tlearnIris classes = do\n\t\t\te \u2190 fmap last $ replicateM 100 $ trainEpoch 1.0 150 crossEntropy classes\n\t\t\tn' \u2190 get\n\t\t\tlet\n\t\t\t\tans = rightAnswers n' classes\n\t\t\tlift $ modify (\\(ans', long') \u2192 (ans, if ans \u2261 ans' then succ long' else 0))\n\t\t\tliftIO $ putStrLn $ \"correct answers: {rights}/{total}; error = {e}\"\n\t\t\t\t~~ (\"e\" ~% e)\n\t\t\t\t~~ (\"rights\" ~% ans)\n\t\t\t\t~~ (\"total\" ~% length classes)\n\t\t\tlong' \u2190 lift $ gets snd\n\t\t\twhen (long' \u2264 10 \u2227 e > 0.1) $ learnIris classes\n\n\ntestMnist \u2237 IO ()\ntestMnist = do\n\tn \u2190 net $\n\t\treturn (computee (reshapeVec 28)) \u2b43 ndup 1 \u2b43\n\t\tnpar 1 (pad2 2 2) \u2b43 dconv2 sigma 1 32 (5, 5) \u2b43 npar 32 (maxPool2 2 2) \u2b43\n\t\tnpar 32 (pad2 2 2) \u2b43 dconv2 sigma 32 64 (5, 5) \u2b43 npar 64 (maxPool2 2 2) \u2b43\n\t\tnpar 64 (return $ computee flattenMat) \u2b43 return (computee concatVecs) \u2b43\n\t\tfc sigma (7 * 7 * 64) 1024 \u2b43\n\t\tfc sigma 1024 10\n\t\t\u2237 IO (Net Double)\n\tputStrLn \"reading train data\"\n\tsmps \u2190 readMnist \"data/classify/mnist/train.csv\"\n\tputStrLn $ \"loaded {0} samples\" ~~ length smps\n\t(_, n') \u2190 runLearnT n $ learnMnist smps\n\tprint n'\n\twhere\n\t\tlearnMnist \u2237 Samples (Vector Double) (Vector Double) \u2192 StateT (Net Double) IO ()\n\t\tlearnMnist smps = do\n\t\t\tixs \u2190 shuffleList [0 .. V.length smps - 1]\n\t\t\tes \u2190 forM ixs $ \\i \u2192 do\n\t\t\t\t-- let\n\t\t\t\t-- \tb = V.fromList $ map (smps V.!) is\n\t\t\t\te \u2190 trainOnce 0.001 crossEntropy (smps V.! i)\n\t\t\t\tliftIO $ putStrLn $ \"error: {}\" ~~ e\n\t\t\t\treturn e\n\t\t\tlet\n\t\t\t\te = avg es\n\t\t\tliftIO $ putStrLn $ \"error: {}\" ~~ e\n\t\t\twhen (e > 0.1) $ learnMnist smps\n\n\nrightClass \u2237 Net Double \u2192 Sample (Vector Double) (Vector Double) \u2192 Bool\nrightClass n_ (Sample i o) = maxIndex (eval n_ i) \u2261 maxIndex o\n\nrightAnswers \u2237 Net Double \u2192 Samples (Vector Double) (Vector Double) \u2192 Int\nrightAnswers n_ = V.length \u2218 V.filter (rightClass n_)\n\n\nxorSamples \u2237 Samples (Vector Double) (Vector Double)\nxorSamples = samples [\n\t[0, 0] \u21e2 [0],\n\t[1, 1] \u21e2 [0],\n\t[1, 0] \u21e2 [1],\n\t[0, 1] \u21e2 [1]]\n\nreadIrisData \u2237 FilePath \u2192 IO (Samples (Vector Double) (Vector Double))\nreadIrisData fpath = parseCsvFile False fpath $ do\n\tis \u2190 mapM (col_ >=> read_ >=> (return \u2218 (* 0.1))) [0 .. 3]\n\tos \u2190 col_ 4 >>= class_ [\"Iris-setosa\", \"Iris-versicolor\", \"Iris-virginica\"]\n\tsample_ is os\n\nreadBalloonSamples \u2237 FilePath \u2192 IO (Samples (Vector Double) (Vector Double))\nreadBalloonSamples fpath = parseCsvFile False fpath $ do\n\tis \u2190 sequence [\n\t\tcol_ 0 >>= enum_ [\"yellow\", \"purple\"],\n\t\tcol_ 1 >>= enum_ [\"small\", \"large\"],\n\t\tcol_ 2 >>= enum_ [\"stretch\", \"dip\"],\n\t\tcol_ 3 >>= enum_ [\"adult\", \"child\"]]\n\tos \u2190 col_ 4 >>= enum_ [\"f\", \"t\"] >>= single_\n\tsample_ is os\n\nreadMnist \u2237 FilePath \u2192 IO (Samples (Vector Double) (Vector Double))\nreadMnist fpath = do\n\tcts \u2190 T.readFile fpath\n\teither error return $ A.parseOnly mnist cts\n\twhere\n\t\tmnist \u2237 A.Parser (Samples (Vector Double) (Vector Double))\n\t\tmnist = do\n\t\t\t_ \u2190 A.manyTill A.anyChar A.endOfLine\n\t\t\tfmap samples $ A.many' $ do\n\t\t\t\t(f:fs) \u2190 A.sepBy A.decimal (A.char ',') <* A.endOfLine\n\t\t\t\tlet\n\t\t\t\t\tis = fromList $ map ((/ 255.0) \u2218 fromIntegral) fs\n\t\t\t\t\tos = fromList $ replicate f 0.0 ++ [1.0] ++ replicate (10 - f - 1) 0.0\n\t\t\t\tis `deepseq` os `deepseq` return (Sample is os)\n\nshouldPass \u2237 Net Double \u2192 Double \u2192 Sample (Vector Double) (Vector Double) \u2192 IO ()\nshouldPass n \u03b5 (Sample xs ys) = when (err > \u03b5) $ expectationFailure msg where\n\tmsg = show xs ++ \" -> \" ++ show res ++ \" should be \" ++ show ys\n\tres = eval n xs\n\terr = vecSize (res - ys)\n\tvecSize v = sqrt (dot v v)\n", "meta": {"hexsha": "200004e925d83cf960e74e906882da2554f3232a", "size": 6321, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Test.hs", "max_stars_repo_name": "mvoidex/trainee", "max_stars_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-25T19:54:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T03:03:26.000Z", "max_issues_repo_path": "tests/Test.hs", "max_issues_repo_name": "mvoidex/trainee", "max_issues_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Test.hs", "max_forks_repo_name": "mvoidex/trainee", "max_forks_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7118644068, "max_line_length": 116, "alphanum_fraction": 0.6415124189, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4139847302388158}}
{"text": "{-# LANGUAGE Rank2Types, FlexibleContexts #-}\n\nmodule Numeric.AD.Lagrangian.Internal where\n\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as S\nimport qualified Data.Packed.Vector as V\nimport qualified Data.Packed.Matrix as M\n\nimport GHC.IO (unsafePerformIO)\n\nimport Numeric.AD\nimport Numeric.Optimization.Algorithms.HagerZhang05\nimport Numeric.LinearAlgebra.Algorithms\n\n-- | An equality constraint of the form @g(x, y, ...) = c@. Use '<=>' to\n-- construct a 'Constraint'.\nnewtype Constraint = Constraint\n  {unConstraint :: forall a. (Floating a) => ([a] -> a, a)}\n\ninfixr 1 <=>\n-- | Build a 'Constraint' from a function and a constant\n(<=>) :: (forall a. (Floating a) => [a] -> a)\n      -> (forall b. (Floating b) => b)\n      -> Constraint\nf <=> c = Constraint (f, c)\n\n-- | Numerically minimize the Langrangian. The objective function and each of\n-- the constraints must take the same number of arguments.\nminimize :: (forall a. (Floating a) => [a] -> a)\n         -- ^ The objective function to minimize\n         -> [Constraint]\n         -- ^ A list of constraints @g \\<=\\> c@ corresponding to equations of\n         -- the form @g(x, y, ...) = c@\n         -> Double\n         -- ^ Stop iterating when the largest component of the gradient is\n         -- smaller than this value\n         -> Int\n         -- ^ The arity of the objective function, which must equal the arity of\n         -- the constraints\n         -> Either (Result, Statistics) (V.Vector Double, V.Vector Double)\n         -- ^ Either a 'Right' containing the argmin and the Lagrange\n         -- multipliers, or a 'Left' containing an explanation of why the\n         -- gradient descent failed\nminimize f constraints tolerance argCount = result where\n    -- At a constrained minimum of `f`, the gradient of the Lagrangian must be\n    -- zero. So we square the Lagrangian's gradient (making it non-negative) and\n    -- minimize it.\n    (sqGradLgn, gradSqGradLgn) = (fst . g, snd . g) where\n        g = grad' $ squaredGrad $ lagrangian f constraints argCount\n    \n    -- Perhaps this should be exposed. ...\n    guess = U.replicate (argCount + length constraints) 1\n\n    result = case unsafePerformIO $\n                    optimize\n                        (defaultParameters {printFinal = False})\n                        tolerance\n                        guess\n                        (VFunction (sqGradLgn . U.toList))\n                        (VGradient (U.fromList . gradSqGradLgn . U.toList))\n                        Nothing of\n       (vs, ToleranceStatisfied, _) -> Right (S.take argCount vs,\n                                              S.drop argCount vs)\n       (_, x, y) -> Left (x, y)\n\n-- | Numerically maximize the Langrangian. The objective function and each of\n-- the constraints must take the same number of arguments.\nmaximize :: (forall a. (Floating a) => [a] -> a)\n         -- ^ The objective function to minimize\n         -> [Constraint]\n         -- ^ A list of constraints @g \\<=\\> c@ corresponding to equations of\n         -- the form @g(x, y, ...) = c@\n         -> Double\n         -- ^ Stop iterating when the largest component of the gradient is\n         -- smaller than this value\n         -> Int\n         -- ^ The arity of the objective function, which must equal the arity of\n         -- the constraints\n         -> Either (Result, Statistics) (V.Vector Double, V.Vector Double)\n         -- ^ Either a 'Right' containing the argmax and the Lagrange\n         -- multipliers, or a 'Left' containing an explanation of why the\n         -- gradient ascent failed\nmaximize f = minimize $ negate . f\n\nlagrangian :: (Floating a)\n           => (forall b. (Floating b) => [b] -> b)\n           -> [Constraint]\n           -> Int\n           -> [a]\n           -> a\nlagrangian f constraints argCount argsAndLams = result where\n    args = take argCount argsAndLams\n    lams = drop argCount argsAndLams\n\n    -- g(x, y, ...) = c <=> g(x, y, ...) - c = 0\n    appliedConstraints = fmap (\\(Constraint (g, c)) -> g args - c) constraints\n\n    -- L(x, y, ..., lam0, ...) = f(x, y, ...) + lam0 * (g0 - c0) ...\n    result = (f args) + (sum . zipWith (*) lams $ appliedConstraints)\n\nsquaredGrad :: (Floating a)\n            => (forall b. (Floating b) => [b] -> b)\n            -> [a]\n            -> a\nsquaredGrad f = sum . fmap square . grad f where\n    square x = x * x\n\n-- | WARNING: Experimental.\n--   This is not a true feasibility test for the function. I am not sure\n--   exactly how to implement that. This just checks the feasiblility at a\n--   point. If this ever returns false, 'solve' can fail.\nfeasible :: (Floating a, Field a, M.Element a)\n         => (forall b. (Floating b) => [b] -> b)\n         ->[Constraint]\n         -> [a]\n         -> Bool\nfeasible f constraints points = result where\n    sqGradLgn :: (Floating a) => [a] -> a\n    sqGradLgn = squaredGrad $ lagrangian f constraints $ length points\n\n    hessianMatrix = M.fromLists . hessian sqGradLgn $ points\n\n    -- make sure all of the eigenvalues are positive\n    result = all (>0) . V.toList . eigenvaluesSH $ hessianMatrix\n", "meta": {"hexsha": "8e05edd428678169b7c5b0e5bd74b9b88259c5b4", "size": 5088, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Lagrangian/Internal.hs", "max_stars_repo_name": "alexkalderimis/lagrangian", "max_stars_repo_head_hexsha": "03a129e33bc33fed5001ffb437c0424e35dbfb50", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-27T04:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T22:46:00.000Z", "max_issues_repo_path": "src/Numeric/AD/Lagrangian/Internal.hs", "max_issues_repo_name": "alexkalderimis/lagrangian", "max_issues_repo_head_hexsha": "03a129e33bc33fed5001ffb437c0424e35dbfb50", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/AD/Lagrangian/Internal.hs", "max_forks_repo_name": "alexkalderimis/lagrangian", "max_forks_repo_head_hexsha": "03a129e33bc33fed5001ffb437c0424e35dbfb50", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-14T02:54:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-14T02:54:27.000Z", "avg_line_length": 40.380952381, "max_line_length": 80, "alphanum_fraction": 0.5965015723, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4132593268413472}}
{"text": "{-# LANGUAGE ConstraintKinds       #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE MagicHash             #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternSynonyms       #-}\n{-# LANGUAGE RebindableSyntax      #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeApplications      #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeSynonymInstances  #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-# LANGUAGE ViewPatterns          #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n-- |\n-- Module      : Data.Array.Accelerate.Data.Complex\n-- Copyright   : [2015..2020] The Accelerate Team\n-- License     : BSD3\n--\n-- Maintainer  : Trevor L. McDonell <trevor.mcdonell@gmail.com>\n-- Stability   : experimental\n-- Portability : non-portable (GHC extensions)\n--\n-- Complex numbers, stored in the usual C-style array-of-struct representation,\n-- for easy interoperability.\n--\nmodule Data.Array.Accelerate.Data.Complex (\n\n  -- * Rectangular from\n  Complex(..), pattern (::+),\n  real,\n  imag,\n\n  -- * Polar form\n  mkPolar,\n  cis,\n  polar,\n  magnitude, magnitude',\n  phase,\n\n  -- * Conjugate\n  conjugate,\n\n) where\n\nimport Data.Array.Accelerate.Classes.Eq\nimport Data.Array.Accelerate.Classes.Floating\nimport Data.Array.Accelerate.Classes.Fractional\nimport Data.Array.Accelerate.Classes.FromIntegral\nimport Data.Array.Accelerate.Classes.Num\nimport Data.Array.Accelerate.Classes.Ord\nimport Data.Array.Accelerate.Classes.RealFloat\nimport Data.Array.Accelerate.Data.Functor\nimport Data.Array.Accelerate.Pattern\nimport Data.Array.Accelerate.Prelude\nimport Data.Array.Accelerate.Representation.Tag\nimport Data.Array.Accelerate.Representation.Type\nimport Data.Array.Accelerate.Representation.Vec\nimport Data.Array.Accelerate.Smart\nimport Data.Array.Accelerate.Sugar.Elt\nimport Data.Array.Accelerate.Sugar.Vec\nimport Data.Array.Accelerate.Type\nimport Data.Primitive.Vec\n\nimport Data.Complex                                                 ( Complex(..) )\nimport Prelude                                                      ( ($) )\nimport qualified Data.Complex                                       as C\nimport qualified Prelude                                            as P\n\n\ninfix 6 ::+\npattern (::+) :: Elt a => Exp a -> Exp a -> Exp (Complex a)\npattern r ::+ i <- (deconstructComplex -> (r, i))\n  where (::+) = constructComplex\n{-# COMPLETE (::+) #-}\n\n\n-- Use an array-of-structs representation for complex numbers if possible.\n-- This matches the standard C-style layout, but we can use this representation only at\n-- specific types (not for any type 'a') as we can only have vectors of primitive type.\n-- For other types, we use a structure-of-arrays representation. This is handled by the\n-- ComplexR. We use the GADT ComplexR and function complexR to reconstruct\n-- information on how the elements are represented.\n--\ninstance Elt a => Elt (Complex a) where\n  type EltR (Complex a) = ComplexR (EltR a)\n  eltR = let tR = eltR @a\n          in case complexR tR of\n               ComplexVec s -> TupRsingle $ VectorScalarType $ VectorType 2 s\n               ComplexTup   -> TupRunit `TupRpair` tR `TupRpair` tR\n\n  tagsR = let tR = eltR @a\n           in case complexR tR of\n               ComplexVec s -> [ TagRsingle (VectorScalarType (VectorType 2 s)) ]\n               ComplexTup   -> let go :: TypeR t -> [TagR t]\n                                   go TupRunit         = [TagRunit]\n                                   go (TupRsingle s)   = [TagRsingle s]\n                                   go (TupRpair ta tb) = [TagRpair a b | a <- go ta, b <- go tb]\n                                in\n                                [ TagRunit `TagRpair` ta `TagRpair` tb | ta <- go tR, tb <- go tR ]\n\n  toElt = case complexR $ eltR @a of\n    ComplexVec _ -> \\(Vec2 r i)   -> toElt r :+ toElt i\n    ComplexTup   -> \\(((), r), i) -> toElt r :+ toElt i\n\n  fromElt (r :+ i) = case complexR $ eltR @a of\n    ComplexVec _ -> Vec2 (fromElt r) (fromElt i)\n    ComplexTup   -> (((), fromElt r), fromElt i)\n\ntype family ComplexR a where\n  ComplexR Half   = Vec2 Half\n  ComplexR Float  = Vec2 Float\n  ComplexR Double = Vec2 Double\n  ComplexR Int    = Vec2 Int\n  ComplexR Int8   = Vec2 Int8\n  ComplexR Int16  = Vec2 Int16\n  ComplexR Int32  = Vec2 Int32\n  ComplexR Int64  = Vec2 Int64\n  ComplexR Word   = Vec2 Word\n  ComplexR Word8  = Vec2 Word8\n  ComplexR Word16 = Vec2 Word16\n  ComplexR Word32 = Vec2 Word32\n  ComplexR Word64 = Vec2 Word64\n  ComplexR a      = (((), a), a)\n\n-- This isn't ideal because we gather the evidence based on the\n-- representation type, so we really get the evidence (VecElt (EltR a)),\n-- which is not very useful...\n--    - TLM 2020-07-16\ndata ComplexType a c where\n  ComplexVec :: VecElt a => SingleType a -> ComplexType a (Vec2 a)\n  ComplexTup ::                             ComplexType a (((), a), a)\n\ncomplexR :: TypeR a -> ComplexType a (ComplexR a)\ncomplexR = tuple\n  where\n    tuple :: TypeR a -> ComplexType a (ComplexR a)\n    tuple TupRunit       = ComplexTup\n    tuple TupRpair{}     = ComplexTup\n    tuple (TupRsingle s) = scalar s\n\n    scalar :: ScalarType a -> ComplexType a (ComplexR a)\n    scalar (SingleScalarType t) = single t\n    scalar VectorScalarType{}   = ComplexTup\n\n    single :: SingleType a -> ComplexType a (ComplexR a)\n    single (NumSingleType t) = num t\n\n    num :: NumType a -> ComplexType a (ComplexR a)\n    num (IntegralNumType t) = integral t\n    num (FloatingNumType t) = floating t\n\n    integral :: IntegralType a -> ComplexType a (ComplexR a)\n    integral TypeInt    = ComplexVec singleType\n    integral TypeInt8   = ComplexVec singleType\n    integral TypeInt16  = ComplexVec singleType\n    integral TypeInt32  = ComplexVec singleType\n    integral TypeInt64  = ComplexVec singleType\n    integral TypeWord   = ComplexVec singleType\n    integral TypeWord8  = ComplexVec singleType\n    integral TypeWord16 = ComplexVec singleType\n    integral TypeWord32 = ComplexVec singleType\n    integral TypeWord64 = ComplexVec singleType\n\n    floating :: FloatingType a -> ComplexType a (ComplexR a)\n    floating TypeHalf   = ComplexVec singleType\n    floating TypeFloat  = ComplexVec singleType\n    floating TypeDouble = ComplexVec singleType\n\n\nconstructComplex :: forall a. Elt a => Exp a -> Exp a -> Exp (Complex a)\nconstructComplex r i =\n  case complexR (eltR @a) of\n    ComplexTup   -> coerce $ T2 r i\n    ComplexVec _ -> V2 (coerce @a @(EltR a) r) (coerce @a @(EltR a) i)\n\ndeconstructComplex :: forall a. Elt a => Exp (Complex a) -> (Exp a, Exp a)\ndeconstructComplex c@(Exp c') =\n  case complexR (eltR @a) of\n    ComplexTup   -> let T2 r i = coerce c in (r, i)\n    ComplexVec t -> let T2 r i = Exp (SmartExp (VecUnpack (VecRsucc (VecRsucc (VecRnil t))) c'))\n                     in (r, i)\n\ncoerce :: EltR a ~ EltR b => Exp a -> Exp b\ncoerce (Exp e) = Exp e\n\ninstance (Lift Exp a, Elt (Plain a)) => Lift Exp (Complex a) where\n  type Plain (Complex a) = Complex (Plain a)\n  lift (r :+ i) = lift r ::+ lift i\n\ninstance Elt a => Unlift Exp (Complex (Exp a)) where\n  unlift (r ::+ i) = r :+ i\n\n\ninstance Eq a => Eq (Complex a) where\n  r1 ::+ c1 == r2 ::+ c2 = r1 == r2 && c1 == c2\n  r1 ::+ c1 /= r2 ::+ c2 = r1 /= r2 || c1 /= c2\n\ninstance RealFloat a => P.Num (Exp (Complex a)) where\n  (+)    = lift2 ((+) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n  (-)    = lift2 ((-) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n  (*)    = lift2 ((*) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n  negate = lift1 (negate :: Complex (Exp a) -> Complex (Exp a))\n  signum z@(x ::+ y) =\n    if z == 0\n       then z\n       else let r = magnitude z\n             in x/r ::+ y/r\n  abs z         = magnitude z ::+ 0\n  fromInteger n = fromInteger n ::+ 0\n\ninstance RealFloat a => P.Fractional (Exp (Complex a)) where\n  fromRational x  = fromRational x ::+ 0\n  z / z'          = (x*x''+y*y'') / d ::+ (y*x''-x*y'') / d\n    where\n      x  :+ y   = unlift z\n      x' :+ y'  = unlift z'\n      --\n      x'' = scaleFloat k x'\n      y'' = scaleFloat k y'\n      k   = - max (exponent x') (exponent y')\n      d   = x'*x'' + y'*y''\n\ninstance RealFloat a => P.Floating (Exp (Complex a)) where\n  pi                = pi ::+ 0\n  exp (x ::+ y)     = let expx = exp x\n                       in expx * cos y ::+ expx * sin y\n  log z             = log (magnitude z) ::+ phase z\n  sqrt z@(x ::+ y)  =\n    if z == 0\n      then 0\n      else u ::+ (y < 0 ? (-v, v))\n    where\n      T2 u v = x < 0 ? (T2 v' u', T2 u' v')\n      v'     = abs y / (u'*2)\n      u'     = sqrt ((magnitude z + abs x) / 2)\n\n  x ** y =\n    if y == 0 then 1 else\n    if x == 0 then if exp_r > 0 then 0 else\n                   if exp_r < 0 then inf ::+ 0\n                                else nan ::+ nan\n              else if isInfinite r || isInfinite i\n                     then if exp_r > 0 then inf ::+ 0 else\n                          if exp_r < 0 then 0\n                                       else nan ::+ nan\n                     else exp (log x * y)\n    where\n      r     ::+ i  = x\n      exp_r ::+ _  = y\n      --\n      inf = 1 / 0\n      nan = 0 / 0\n\n  sin (x ::+ y)  = sin x * cosh y ::+ cos x * sinh y\n  cos (x ::+ y)  = cos x * cosh y ::+ (- sin x * sinh y)\n  tan (x ::+ y)  = (sinx*coshy ::+ cosx*sinhy) / (cosx*coshy ::+ (-sinx*sinhy))\n    where\n      sinx  = sin x\n      cosx  = cos x\n      sinhy = sinh y\n      coshy = cosh y\n\n  sinh (x ::+ y) = cos y * sinh x ::+ sin  y * cosh x\n  cosh (x ::+ y) = cos y * cosh x ::+ sin y * sinh x\n  tanh (x ::+ y) = (cosy*sinhx ::+ siny*coshx) / (cosy*coshx ::+ siny*sinhx)\n    where\n      siny  = sin y\n      cosy  = cos y\n      sinhx = sinh x\n      coshx = cosh x\n\n  asin z@(x ::+ y) = y' ::+ (-x')\n    where\n      x' ::+ y' = log (((-y) ::+ x) + sqrt (1 - z*z))\n\n  acos z                    = y'' ::+ (-x'')\n    where\n      x'' ::+ y''  = log (z + ((-y') ::+ x'))\n      x'  ::+ y'   = sqrt (1 - z*z)\n\n  atan z@(x ::+ y) = y' ::+ (-x')\n    where\n      x' ::+ y' = log (((1-y) ::+ x) / sqrt (1+z*z))\n\n  asinh z =  log (z + sqrt (1+z*z))\n  acosh z =  log (z + (z+1) * sqrt ((z-1)/(z+1)))\n  atanh z =  0.5 * log ((1.0+z) / (1.0-z))\n\n\ninstance (FromIntegral a b, Num b, Elt (Complex b)) => FromIntegral a (Complex b) where\n  fromIntegral x = fromIntegral x ::+ 0\n\n-- | @since 1.2.0.0\n--\ninstance Functor Complex where\n  fmap f (r ::+ i) = f r ::+ f i\n\n\n-- | The non-negative magnitude of a complex number\n--\nmagnitude :: RealFloat a => Exp (Complex a) -> Exp a\nmagnitude (r ::+ i) = scaleFloat k (sqrt (sqr (scaleFloat mk r) + sqr (scaleFloat mk i)))\n  where\n    k     = max (exponent r) (exponent i)\n    mk    = -k\n    sqr z = z * z\n\n-- | As 'magnitude', but ignore floating point rounding and use the traditional\n-- (simpler to evaluate) definition.\n--\n-- @since 1.3.0.0\n--\nmagnitude' :: RealFloat a => Exp (Complex a) -> Exp a\nmagnitude' (r ::+ i) = sqrt (r*r + i*i)\n\n-- | The phase of a complex number, in the range @(-'pi', 'pi']@. If the\n-- magnitude is zero, then so is the phase.\n--\nphase :: RealFloat a => Exp (Complex a) -> Exp a\nphase z@(r ::+ i) =\n  if z == 0\n    then 0\n    else atan2 i r\n\n-- | The function 'polar' takes a complex number and returns a (magnitude,\n-- phase) pair in canonical form: the magnitude is non-negative, and the phase\n-- in the range @(-'pi', 'pi']@; if the magnitude is zero, then so is the phase.\n--\npolar :: RealFloat a => Exp (Complex a) -> Exp (a,a)\npolar z =  T2 (magnitude z) (phase z)\n\n-- | Form a complex number from polar components of magnitude and phase.\n--\nmkPolar :: forall a. Floating a => Exp a -> Exp a -> Exp (Complex a)\nmkPolar = lift2 (C.mkPolar :: Exp a -> Exp a -> Complex (Exp a))\n\n-- | @'cis' t@ is a complex value with magnitude @1@ and phase @t@ (modulo\n-- @2*'pi'@).\n--\ncis :: forall a. Floating a => Exp a -> Exp (Complex a)\ncis = lift1 (C.cis :: Exp a -> Complex (Exp a))\n\n-- | Return the real part of a complex number\n--\nreal :: Elt a => Exp (Complex a) -> Exp a\nreal (r ::+ _) = r\n\n-- | Return the imaginary part of a complex number\n--\nimag :: Elt a => Exp (Complex a) -> Exp a\nimag (_ ::+ i) = i\n\n-- | Return the complex conjugate of a complex number, defined as\n--\n-- > conjugate(Z) = X - iY\n--\nconjugate :: Num a => Exp (Complex a) -> Exp (Complex a)\nconjugate z = real z ::+ (- imag z)\n\n", "meta": {"hexsha": "1a1c46767370e6b9e7c3e8aded7ae796fcfb3108", "size": 12298, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Array/Accelerate/Data/Complex.hs", "max_stars_repo_name": "jippiedoe/accelerate", "max_stars_repo_head_hexsha": "a3f2bc2f25ee87551cf3081468615b7003b7ba8c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 619, "max_stars_repo_stars_event_min_datetime": "2015-01-08T15:26:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T06:24:37.000Z", "max_issues_repo_path": "src/Data/Array/Accelerate/Data/Complex.hs", "max_issues_repo_name": "jippiedoe/accelerate", "max_issues_repo_head_hexsha": "a3f2bc2f25ee87551cf3081468615b7003b7ba8c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 329, "max_issues_repo_issues_event_min_datetime": "2015-01-05T12:00:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T01:18:25.000Z", "max_forks_repo_path": "src/Data/Array/Accelerate/Data/Complex.hs", "max_forks_repo_name": "jippiedoe/accelerate", "max_forks_repo_head_hexsha": "a3f2bc2f25ee87551cf3081468615b7003b7ba8c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 81, "max_forks_repo_forks_event_min_datetime": "2015-01-07T21:53:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T14:04:38.000Z", "avg_line_length": 33.9723756906, "max_line_length": 99, "alphanum_fraction": 0.5757846804, "num_tokens": 3762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4132593268413472}}
{"text": "-- |\n-- Module      : Cartesian.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 _ _ 2015\n\n-- TODO | -\n--        -\n\n-- SPEC | -\n--        -\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC Pragmas\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule Cartesian.Types (\n  -- ^ Third party types\n  V1(..), V2(..), V3(..), V4(..), Complex(..),\n  \n  -- ^ Synonyms\n  BoxLens, Axis, Axes, Polygon,\n\n  -- ^ Coordinate types\n  Normalised, Absolute,\n\n  -- ^ Types defined in this library\n  BoundingBox(..), Line, Linear,\n\n  -- ^ Classes\n  HasX, HasY, HasZ) where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\nimport Linear.V1\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\n\nimport Data.Complex (Complex(..))\n\nimport Cartesian.Internal.Types", "meta": {"hexsha": "f3a81620b0d157ee87fc26f3557500f59157de21", "size": 1648, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cartesian/Types.hs", "max_stars_repo_name": "jordanemedlock/Cartesian", "max_stars_repo_head_hexsha": "ed05b53a14f9a7f9ebb21b7cd9affae3d95af3f6", "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/Types.hs", "max_issues_repo_name": "jordanemedlock/Cartesian", "max_issues_repo_head_hexsha": "ed05b53a14f9a7f9ebb21b7cd9affae3d95af3f6", "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/Types.hs", "max_forks_repo_name": "jordanemedlock/Cartesian", "max_forks_repo_head_hexsha": "ed05b53a14f9a7f9ebb21b7cd9affae3d95af3f6", "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": 27.9322033898, "max_line_length": 140, "alphanum_fraction": 0.2955097087, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4131540487156097}}
{"text": "{-# LANGUAGE DeriveDataTypeable        #-}\n{-# LANGUAGE FlexibleContexts          #-}\n{-# LANGUAGE FlexibleInstances         #-}\n{-# LANGUAGE FunctionalDependencies    #-}\n{-# LANGUAGE MultiParamTypeClasses     #-}\n{-# LANGUAGE RankNTypes                #-}\n{-# LANGUAGE RecordWildCards           #-}\n{-# LANGUAGE TypeFamilies              #-}\n{-# LANGUAGE UndecidableInstances      #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Plots.Types.Histogram\n-- Copyright   :  (C) 2015 Christopher Chalmers\n-- License     :  BSD-style (see the file LICENSE)\n-- Maintainer  :  Christopher Chalmers\n-- Stability   :  experimental\n-- Portability :  non-portable\n\n-- A histogram is a graphical representation of the distribution of\n-- numerical data. It is an estimate of the probability distribution of\n-- a continuous variable.\n--\n----------------------------------------------------------------------------\n\nmodule Plots.Types.Histogram\n  (\n    -- * Histogram plot\n    HistogramPlot\n\n    -- ** Already computed histograms\n  , computedHistogram\n\n    -- ** Histogram options\n  , HistogramOptions\n  , HasHistogramOptions (..)\n\n    -- ** Normalisation\n  , NormalisationMethod\n  , count\n  , probability\n  , countDensity\n  , pdf\n  , cumilative\n  , cdf\n\n    -- ** Plotting histograms\n  , histogramPlot\n  , histogramPlot'\n  , histogramPlotOf\n  , histogramPlotOf'\n\n    -- * Low level constructors\n  , mkComputedHistogram\n  , mkHistogramPlot\n  ) where\n\nimport           Control.Monad.State.Lazy\n\nimport qualified Data.Foldable               as F\nimport           Data.Maybe\nimport           Data.Typeable\n\nimport qualified Data.Vector                 as V\nimport qualified Statistics.Sample.Histogram as Stat\n\nimport           Diagrams.Core.Transform     (fromSymmetric)\nimport           Diagrams.Prelude\nimport           Linear.V2                   (_yx)\n\nimport           Plots.Axis\nimport           Plots.Style\nimport           Plots.Types\nimport           Plots.Util\n\n\n-- | Construct a rectangle of size $v$ with the bottom left at point $p$.\nrectBL :: (InSpace V2 n t, TrailLike t) => Point V2 n -> V2 n -> t\nrectBL p (V2 x y) =\n  trailLike $ fromOffsets [V2 x 0, V2 0 y, V2 (-x) 0] # closeTrail `at` p\n\n------------------------------------------------------------------------\n-- GHistogram plot\n------------------------------------------------------------------------\n\n-- | Simple histogram type supporting uniform bins.\ndata HistogramPlot n = HistogramPlot\n  { hWidth  :: n\n  , hStart  :: n\n  , hValues :: [n]\n  , hOrient :: Orientation\n  } deriving Typeable\n\ntype instance V (HistogramPlot n) = V2\ntype instance N (HistogramPlot n) = n\n\ninstance OrderedField n => Enveloped (HistogramPlot n) where\n  getEnvelope HistogramPlot {..} =\n    -- don't like this redundant code\n    getEnvelope . orient hOrient _reflectXY id . (id :: Path v n -> Path v n) $\n      ifoldMap drawBar hValues\n    where\n      drawBar i h = rectBL (mkP2 x 0) (V2 hWidth h)\n        where x = hStart + fromIntegral i * hWidth\n\ninstance (TypeableFloat n, Renderable (Path V2 n) b)\n    => Plotable (HistogramPlot n) b where\n  renderPlotable s sty HistogramPlot {..} =\n    ifoldMap drawBar hValues\n      # orient hOrient _reflectXY id\n      # applyAreaStyle sty\n      # transform (s^.specTrans)\n    where\n      drawBar i h = rectBL (mkP2 x 0) (V2 hWidth h)\n        where x = hStart + fromIntegral i * hWidth\n\n  defLegendPic sty HistogramPlot {..}\n    = centerXY\n    . applyAreaStyle sty'\n    . orient hOrient _reflectXY id\n    $ alignB (rect 4 7) ||| alignB (rect 4 10) ||| alignB (rect 4 6)\n    where\n      -- The legend bars don't look right if the line width is too big so we limit it\n      sty' = sty & areaStyle . _lw %~ atMost (local 0.8)\n\ninstance HasOrientation (HistogramPlot n) where\n  orientation = lens hOrient $ \\hp o -> hp {hOrient = o}\n\n------------------------------------------------------------------------\n-- Simple histogram plot\n------------------------------------------------------------------------\n\n-- | Plot an already computed histogram with equally sized bins.\ncomputedHistogram\n  :: (MonadState (Axis b V2 n) m,\n      Plotable (HistogramPlot n) b,\n      F.Foldable f)\n  => n   -- ^ start of first bin\n  -> n   -- ^ width of each bin\n  -> f n -- ^ heights of the bins\n  -> State (Plot (HistogramPlot n) b) ()\n  -> m ()\ncomputedHistogram x0 w xs = addPlotable (mkComputedHistogram x0 w xs)\n\n-- | Construct a 'HistogramPlot' from raw histogram data.\nmkComputedHistogram\n  :: F.Foldable f\n  => n -- ^ start of first bin\n  -> n -- ^ width of each bin\n  -> f n -- ^ heights of the bins\n  -> HistogramPlot n\nmkComputedHistogram x0 w xs = HistogramPlot x0 w (F.toList xs) Horizontal\n\n----------------------------------------------------------------------------\n-- Building histograms\n----------------------------------------------------------------------------\n\n-- example setup\n-- > import Plots\n-- > sampleData :: [Double]\n-- > sampleData =\n-- >   [5.1,4.9,4.7,4.6,5.0,5.4,4.6,5.0,4.4,4.9\n-- >   ,5.4,4.8,4.8,4.3,5.8,5.7,5.4,5.1,5.7,5.1\n-- >   ,5.4,5.1,4.6,5.1,4.8,5.0,5.0,5.2,5.2,4.7\n-- >   ,4.8,5.4,5.2,5.5,4.9,5.0,5.5,4.9,4.4,5.1\n-- >   ,5.0,4.5,4.4,5.0,5.1,4.8,5.1,4.6,5.3,5.0\n-- >   ,7.0,6.4,6.9,5.5,6.5,5.7,6.3,4.9,6.6,5.2\n-- >   ,5.0,5.9,6.0,6.1,5.6,6.7,5.6,5.8,6.2,5.6\n-- >   ,5.9,6.1,6.3,6.1,6.4,6.6,6.8,6.7,6.0,5.7\n-- >   ,5.5,5.5,5.8,6.0,5.4,6.0,6.7,6.3,5.6,5.5\n-- >   ,5.5,6.1,5.8,5.0,5.6,5.7,5.7,6.2,5.1,5.7\n-- >   ,6.3,5.8,7.1,6.3,6.5,7.6,4.9,7.3,6.7,7.2\n-- >   ,6.5,6.4,6.8,5.7,5.8,6.4,6.5,7.7,7.7,6.0\n-- >   ,6.9,5.6,7.7,6.3,6.7,7.2,6.2,6.1,6.4,7.2\n-- >   ,7.4,7.9,6.4,6.3,6.1,7.7,6.3,6.4,6.0,6.9\n-- >   ,6.7,6.9,5.8,6.8,6.7,6.7,6.3,6.5,6.2,5.9\n-- >   ]\n--\n-- > mkNmExample nm = r2Axis &~ do\n-- >   yMin ?= 0\n-- >   histogramPlot sampleData $ do\n-- >     normaliseSample .= nm\n-- > countDia = renderAxis $ mkNmExample count\n-- > probabilityDia = renderAxis $ mkNmExample probability\n-- > countDensityDia = renderAxis $ mkNmExample countDensity\n-- > pdfDia = renderAxis $ mkNmExample pdf\n-- > cumilativeDia = renderAxis $ mkNmExample cumilative\n-- > cdfDia = renderAxis $ mkNmExample cdf\n\n-- Histogram options ---------------------------------------------------\n\n-- | The way to normalise the data from a histogram. The default method\n--   is 'count'.\nnewtype NormalisationMethod =\n  NM { runNM :: forall n. Fractional n => n -> V.Vector n -> V.Vector n }\n -- width -> heights -> normalised heights\n\ninstance Default NormalisationMethod where\n  def = count\n\n-- | The height of each bar is the number of observations. This is the\n--   'Default' method.\n--\n-- === __Example__\n--\n-- <<diagrams/src_Plots_Types_Histogram_countDia.svg#diagram=countDia&height=350>>\ncount :: NormalisationMethod\ncount = NM $ \\_ v -> v\n\n-- | The sum of the heights of the bars is equal to 1.\n--\n-- === __Example__\n--\n-- <<diagrams/src_Plots_Types_Histogram_probabilityDia.svg#diagram=probabilityDia&height=350>>\nprobability :: NormalisationMethod\nprobability = NM $ \\_ v -> v ^/ V.sum v\n\n-- | The height of each bar is @n / w@ where @n@ is the number of\n--   observations and @w@ is the total width.\n--\n-- === __Example__\n--\n-- <<diagrams/src_Plots_Types_Histogram_countDensityDia.svg#diagram=countDensityDia&height=350>>\ncountDensity :: NormalisationMethod\ncountDensity = NM $ \\w v -> v ^/ w\n\n-- | The total area of the bars is @1@. This gives a probability density\n--   function estimate.\n--\n-- === __Example__\n--\n-- <<diagrams/src_Plots_Types_Histogram_pdfDia.svg#diagram=pdfDia&height=350>>\npdf :: NormalisationMethod\npdf = NM $ \\w v -> v ^/ (w * V.sum v)\n\n-- | The height of each bar is the cumulative number of observations in\n--   each bin and all previous bins. The height of the last bar is the\n--   total number of observations.\n--\n-- === __Example__\n--\n-- <<diagrams/src_Plots_Types_Histogram_cumilativeDia.svg#diagram=cumilativeDia&height=350>>\ncumilative :: NormalisationMethod\ncumilative = NM $ \\_ -> V.scanl1 (+)\n\n-- | Cumulative density function estimate. The height of each bar is\n--   equal to the cumulative relative number of observations in the bin\n--   and all previous bins. The height of the last bar is 1.\n--\n-- === __Example__\n--\n-- <<diagrams/src_Plots_Types_Histogram_cdfDia.svg#diagram=cdfDia&height=350>>\ncdf :: NormalisationMethod\ncdf = NM $ \\_ v -> V.scanl1 (+) v ^/ V.sum v\n\n-- | Options for binning histogram data. For now only very basic\n--   histograms building is supported.\ndata HistogramOptions n = HistogramOptions\n  { hBins   :: Int\n  , hRange  :: Maybe (n, n)\n  , hNorm   :: NormalisationMethod\n  , oOrient :: Orientation\n  }\n\ntype instance V (HistogramOptions n) = V2\ntype instance N (HistogramOptions n) = n\n\ninstance Default (HistogramOptions n) where\n  def = HistogramOptions\n    { hBins   = 10\n    , hRange  = Nothing\n    , hNorm   = def\n    , oOrient = Vertical\n    }\n\ninstance HasOrientation (HistogramOptions n) where\n  orientation = lens oOrient $ \\ho o -> ho {oOrient = o}\n\nclass HasOrientation a => HasHistogramOptions a where\n  -- | Options for building the histogram from data.\n  histogramOptions :: Lens' a (HistogramOptions (N a))\n\n  -- | The number of bins (bars) to use for the histogram. Must be\n  --   positive.\n  --\n  --   'Default' is @10@.\n  numBins :: Lens' a Int\n  numBins = histogramOptions . lens hBins (\\ho n -> ho {hBins = n})\n\n  -- | The range of data to consider when building the histogram. Any\n  --   data outside the range is ignored.\n  --\n  --   'Default' is 'Nothing'.\n  binRange :: Lens' a (Maybe (N a, N a))\n  binRange = histogramOptions . lens hRange (\\ho r -> ho {hRange = r})\n\n  -- | Should the resulting histogram be normalised so the total area is\n  --   1.\n  --\n  --   'Default' is False.\n  normaliseSample :: Lens' a NormalisationMethod\n  normaliseSample = histogramOptions . lens hNorm (\\ho b -> ho {hNorm = b})\n\ninstance HasHistogramOptions (HistogramOptions n) where\n  histogramOptions = id\n\ninstance HasHistogramOptions a => HasHistogramOptions (Plot a b) where\n  histogramOptions = rawPlot . histogramOptions\n\n-- | Create a histogram by binning the data using the\n--   'HistogramOptions'.\nmkHistogramPlot\n  :: (F.Foldable f, RealFrac n)\n  => HistogramOptions n -> f n -> HistogramPlot n\nmkHistogramPlot HistogramOptions {..} xs =\n  HistogramPlot\n    { hWidth  = w\n    , hStart  = a\n    , hValues = V.toList $ runNM hNorm w ns\n    , hOrient = Vertical\n    }\n  where\n    w     = (b - a) / fromIntegral hBins\n    ns    = Stat.histogram_ hBins a b v\n    v     = V.fromList (F.toList xs)\n    (a,b) = fromMaybe (range hBins v) hRange\n\n-- Taken from Statistics, which was limited to 'Double'.\nrange :: (Ord n, Fractional n)\n      => Int                    -- ^ Number of bins (must be positive).\n      -> V.Vector n             -- ^ Sample data (cannot be empty).\n      -> (n, n)\nrange nBins xs\n    | nBins < 1 = error \"Plots.Types.Histogram: invalid bin count\"\n    | V.null xs = error \"Plots.Types.Histogram: empty sample\"\n    | lo == hi  = case abs lo / 10 of\n                    a | a < 1e-6   -> (-1,1)\n                      | otherwise  -> (lo - a, lo + a)\n    | otherwise = (lo-d, hi+d)\n  where\n    d | nBins == 1 = 0\n      | otherwise  = (hi - lo) / ((fromIntegral nBins - 1) * 2)\n    (lo,hi)        = minMaxOf folded xs\n{-# INLINE range #-}\n\n-- |\n-- mkWeightedHistogram\n--   :: (F.Foldable f, OrderdField n)\n--   => HistogramOptions n -> [(n, n)] -> HistogramPlot n\n-- mkWeightedHistogram\n\n------------------------------------------------------------------------\n-- Histogram\n------------------------------------------------------------------------\n\n-- $ histogram\n-- Histograms display data as barplot of x data, bin y data.\n-- Box plots have the following lenses:\n--\n-- @\n-- * 'setBin' :: 'Lens'' ('BoxPlot' v n) 'Double' - 10\n-- @\n\n-- | Add a 'HistogramPlot' to the 'AxisState' from a data set.\n--\n-- === __Example__\n--\n-- <<diagrams/src_Plots_Types_Histogram_histogramExample.svg#diagram=histogramExample&height=350>>\n--\n-- > import Plots\n-- > histogramAxis :: Axis B V2 Double\n-- > histogramAxis = r2Axis &~ do\n-- >   histogramPlot sampleData $ do\n-- >     key \"histogram\"\n-- >     plotColor .= blue\n-- >     areaStyle . _opacity .= 0.5\n--\n-- > histogramExample = renderAxis histogramAxis\nhistogramPlot\n  :: (MonadState (Axis b V2 n) m, Plotable (HistogramPlot n) b, F.Foldable f, RealFrac n)\n  => f n -- ^ data\n  -> State (Plot (HistogramOptions n) b) () -- ^ changes to plot options\n  -> m () -- ^ add plot to axis\nhistogramPlot ns s = addPlot (hoPlot & rawPlot %~ \\ho -> mkHistogramPlot ho ns)\n  where hoPlot = mkPlot def &~ s\n\n-- | Make a 'HistogramPlot' without changes to the plot options.\nhistogramPlot'\n  :: (MonadState (Axis b V2 n) m, Plotable (HistogramPlot n) b, F.Foldable f, RealFrac n)\n  => f n -- ^ data\n  -> m () -- ^ add plot to axis\nhistogramPlot' d = histogramPlot d (return ())\n\n-- | Add a 'HistogramPlot' using a fold over the data.\nhistogramPlotOf\n  :: (MonadState (Axis b V2 n) m, Plotable (HistogramPlot n) b, RealFrac n)\n  => Fold s n -- ^ fold over the data\n  -> s        -- ^ data to fold\n  -> State (Plot (HistogramOptions n) b) () -- ^ change to the plot\n  -> m () -- ^ add plot to the 'Axis'\nhistogramPlotOf f s = histogramPlot (toListOf f s)\n\n-- | Same as 'histogramPlotOf' without any changes to the plot.\nhistogramPlotOf'\n  :: (MonadState (Axis b V2 n) m, Plotable (HistogramPlot n) b, RealFrac n)\n  => Fold s n -> s -> m ()\nhistogramPlotOf' f s = histogramPlotOf f s (return ())\n\n-- temporary functions that will be in next lib release\n\n_reflectionXY :: (Additive v, R2 v, Num n) => Transformation v n\n_reflectionXY = fromSymmetric $ (_xy %~ view _yx) <-> (_xy %~ view _yx)\n\n_reflectXY :: (InSpace v n t, R2 v, Transformable t) => t -> t\n_reflectXY = transform _reflectionXY\n\n", "meta": {"hexsha": "2f287d25d894cf94b51d58e03377ff5d3daac3d6", "size": 13737, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Plots/Types/Histogram.hs", "max_stars_repo_name": "adamConnerSax/plots", "max_stars_repo_head_hexsha": "7e02bd98e8891d0673e3973a95a9b59db36b6f5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45, "max_stars_repo_stars_event_min_datetime": "2015-05-28T14:57:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T05:11:43.000Z", "max_issues_repo_path": "src/Plots/Types/Histogram.hs", "max_issues_repo_name": "adamConnerSax/plots", "max_issues_repo_head_hexsha": "7e02bd98e8891d0673e3973a95a9b59db36b6f5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 45, "max_issues_repo_issues_event_min_datetime": "2015-08-22T16:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T00:23:05.000Z", "max_forks_repo_path": "src/Plots/Types/Histogram.hs", "max_forks_repo_name": "adamConnerSax/plots", "max_forks_repo_head_hexsha": "7e02bd98e8891d0673e3973a95a9b59db36b6f5b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-03-25T09:55:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T16:27:07.000Z", "avg_line_length": 32.9424460432, "max_line_length": 98, "alphanum_fraction": 0.6020237315, "num_tokens": 4145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.41311464480426613}}
{"text": "module FractalStream.Models\n    ( Coordinate\n    , ComplexParametric1d\n    ) where\n\nimport Lang.Numbers\n\ntype family Coordinate model :: *\ndata ComplexParametric1d\n\n\n{-\nimport Data.Word\nimport Data.Complex\n\n\n  \nnewtype ViewCoordinate a = ViewCoordinate a\n\ndata ParameterType = N | Z | R | C\n\ndata Parameter = Parameter\n  { parameterType :: !ParameterType\n  , parameterName :: !String\n  , parameterDesc :: !String\n  }\n\ndata Group = Group\n  { groupTitle  :: !String\n  , groupParams :: [Parameter]\n  }\n  \nepsilon :: Parameter\nepsilon = Parameter\n  { parameterType = R\n  , parameterName = \"Epsilon\"\n  , parameterDesc = concat\n      [ \"How close together two complex numbers should\"\n      , \" be in order for them to be considered equal?\" ]\n  }\n\ninfinity :: Parameter\ninfinity = Parameter\n  { parameterType = R\n  , parameterName = \"Infinity\"\n  , parameterDesc = concat\n      [ \"How large a number should be in order to\"\n      , \" consider it escaped / near infinity?\" ]\n  }\n\nmaxIter :: Parameter\nmaxIter = Parameter\n  { parameterType = N\n  , parameterName = \"Maximum iteration count\"\n  , parameterDesc = concat\n      [ \"How many iterations should we try before giving up?\" ]\n  }\n\ndata Int32\n\ndata ParameterDesc where\n  = Param Parameter\n  | \n  \ncomplexParametric1d\n  =  viewCoordinate @(Complex Double) \"C\"\n  <> parameter @Int32 \"Maximum iteration count\"\n  <> parameter @Double \"Epsilon\"\n  <> parameter @Double \"Infinity\"\n\ncomplexParametricDynamics1d\n  =  viewCoordinate @(Complex Double) \"Z\"\n  <> parameter @(Complex Double) \"C\"\n  <> parameter @Int32 \"Maximum iteration count\"\n  <> parameter @Double \"Epsilon\"\n  <> parameter @Double \"Infinity\"\n\ncomplexDynamics1d\n  =  viewCoordinate @(Complex Double) \"Z\"\n  <> parameter @Int32 \"Maximum iteration count\"\n  <> parameter @Double \"Epsilon\"\n  <> parameter @Double \"Infinity\"\n-}\n\ntype instance Coordinate ComplexParametric1d = C --(Double, Double)\n", "meta": {"hexsha": "d6981f9b58796b3f0b2362cbf3f5ff17a76bb387", "size": 1888, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "fractalstream-core/src/FractalStream/Models.hs", "max_stars_repo_name": "matt-noonan/FractalStream", "max_stars_repo_head_hexsha": "2a51be0750497daa0afaa6750ef4f73e49e81458", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-06T02:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T08:06:39.000Z", "max_issues_repo_path": "fractalstream-core/src/FractalStream/Models.hs", "max_issues_repo_name": "matt-noonan/FractalStream", "max_issues_repo_head_hexsha": "2a51be0750497daa0afaa6750ef4f73e49e81458", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fractalstream-core/src/FractalStream/Models.hs", "max_forks_repo_name": "matt-noonan/FractalStream", "max_forks_repo_head_hexsha": "2a51be0750497daa0afaa6750ef4f73e49e81458", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9534883721, "max_line_length": 67, "alphanum_fraction": 0.6922669492, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4129293106597016}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n\nmodule GameData\n    ( ResultSimple (ResultSimple, evSimpleCol, evSimpleRow, sdSimpleCol, sdSimpleRow, weightsColsSimple, weightsRowsSimple)\n    , GameSimple (GameSimple, gameSName, gameSCols, gameSRows, gameSMatrixCol, gameSMatrixRow, gameSOutcomes)\n    , Game (Game, gameCName, attCName, defCName, gameData, outcomesC)\n    , Result (Result, evc, evr, sdc, sdr, weightsAtts, weightsDefs)\n    , Opt\n    , OptOutcome\n    ) where\n\nimport Data.Function\nimport Data.List\nimport Data.Maybe\nimport Data.Text (Text, unpack)\nimport Numeric.LinearAlgebra hiding (build)\nimport Numeric.LinearAlgebra.Data hiding (build)\nimport Formatting\nimport Formatting.Formatters hiding (build)\nimport qualified Formatting.Formatters as F\nimport Formatting.Buildable\n\ndata ResultSimple = ResultSimple {evSimpleCol::Double, evSimpleRow::Double, sdSimpleCol::Double, sdSimpleRow::Double, weightsColsSimple::[Double], weightsRowsSimple::[Double]}\n    deriving (Show)\n\ndata GameSimple = GameSimple {gameSName::Text, gameSCols::[Text], gameSRows::[Text], gameSMatrixCol::(Matrix Double), gameSMatrixRow::(Matrix Double), gameSOutcomes::ResultSimple}\ninstance Buildable GameSimple where\n    build g = let\n                  (ResultSimple evc evr sdc sdr wc wr) = gameSOutcomes g\n                  n = gameSName g\n                  m1 = gameSMatrixCol g\n                  m2 = gameSMatrixRow g\n                  c = zip (gameSCols g) wc\n                  r = zip (gameSRows g) wr\n              in\n                  bformat (stext % \":\\n Column's Game: \" % shown % \"\\n Row's Game: \" % shown % \"\\n Column player: \" % shown % \"\\n Row player: \" % shown % \"\\n EVs: \" % shown % \"\\n SDs: \" % shown) n m1 m2 c r (evc, evr) (sdc, sdr)\ninstance Show GameSimple where\n    show g = formatToString F.build g\n\ntype Opt = (Text, Maybe Double)\ntype OptOutcome = (Opt, Opt, Double, Double)\n\ndata Result = Result {evc::Double, evr::Double, sdc::Double, sdr::Double, weightsAtts::[(Text,Double)], weightsDefs::[(Text,Double)]}\n    deriving (Eq, Ord)\ninstance Show Result where\n    show r = \"\\n EVs: \" ++ (show (evc r, evr r)) ++ \"\\n SDs: \" ++ (show (sdc r, sdr r)) ++ \"\\n Attacker Options: \" ++ (show . weightsAtts $ r) ++ \"\\n Defender Options: \" ++ (show . weightsDefs $ r)\n\ndata Game = Game {gameCName::Text, attCName::Text, defCName::Text, gameData::[OptOutcome], outcomesC::Result}\ninstance Ord Game where\n    compare = compare `on` gameCName\ninstance Eq Game where\n    a == b = and [gameCName a == gameCName b, attCName a == attCName b, defCName a == defCName b]\ninstance Show Game where\n    show (Game \"\" _ _ gdata gout) = show gout\n    show (Game gname \"\" \"\" gdata gout) = (unpack gname) ++ \"\\n\" ++ (show gout)\n    show (Game gname attname defname gdata gout) = (unpack gname) ++ \" (\" ++ (unpack attname) ++ \" vs \" ++ (unpack defname) ++ \")\" ++ (show gout)\n", "meta": {"hexsha": "580ce15acba5b87932bfe9516336fea221d973f3", "size": 2849, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GameData.hs", "max_stars_repo_name": "StaccatoSemibreve/Mixup-Analyser", "max_stars_repo_head_hexsha": "50479a37f92ec8bed6a01e7d965edc582c19ad50", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GameData.hs", "max_issues_repo_name": "StaccatoSemibreve/Mixup-Analyser", "max_issues_repo_head_hexsha": "50479a37f92ec8bed6a01e7d965edc582c19ad50", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GameData.hs", "max_forks_repo_name": "StaccatoSemibreve/Mixup-Analyser", "max_forks_repo_head_hexsha": "50479a37f92ec8bed6a01e7d965edc582c19ad50", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9824561404, "max_line_length": 228, "alphanum_fraction": 0.6651456651, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.41292930476871464}}
{"text": "-----------------------------------------------------------------------------\n-- |\n-- Module      :  Internal.IO\n-- Copyright   :  (c) Alberto Ruiz 2010\n-- License     :  BSD3\n--\n-- Maintainer  :  Alberto Ruiz\n-- Stability   :  provisional\n--\n-- Display, formatting and IO functions for numeric 'Vector' and 'Matrix'\n--\n-----------------------------------------------------------------------------\n\nmodule Internal.IO (\n    dispf, disps, dispcf, vecdisp, latexFormat, format,\n    loadMatrix, loadMatrix', saveMatrix\n) where\n\nimport           Data.Complex\nimport           Data.List           (intersperse, transpose)\nimport           Internal.Devel\nimport           Internal.Matrix\nimport           Internal.Vector\nimport           Internal.Vectorized\nimport           Text.Printf         (PrintfArg, PrintfType, printf)\n\n\n-- | Formatting tool\ntable :: String -> [[String]] -> String\ntable sep as = unlines . map unwords' $ transpose mtp\n  where\n    mt = transpose as\n    longs = map (maximum . map length) mt\n    mtp = zipWith (\\a b -> map (pad a) b) longs mt\n    pad n str = replicate (n - length str) ' ' ++ str\n    unwords' = concat . intersperse sep\n\n\n{- | Creates a string from a matrix given a separator and a function to show each entry. Using\nthis function the user can easily define any desired display function:\n\n@import Text.Printf(printf)@\n\n@disp = putStr . format \\\"  \\\" (printf \\\"%.2f\\\")@\n\n-}\nformat :: (Element t) => String -> (t -> String) -> Matrix t -> String\nformat sep f m = table sep . map (map f) . toLists $ m\n\n{- | Show a matrix with \\\"autoscaling\\\" and a given number of decimal places.\n\n>>> putStr . disps 2 $ 120 * (3><4) [1..]\n3x4  E3\n 0.12  0.24  0.36  0.48\n 0.60  0.72  0.84  0.96\n 1.08  1.20  1.32  1.44\n\n-}\ndisps :: Int -> Matrix Float -> String\ndisps d x = sdims x ++ \"  \" ++ formatScaled d x\n\n{- | Show a matrix with a given number of decimal places.\n\n>>> dispf 2 (1/3 + ident 3)\n\"3x3\\n1.33  0.33  0.33\\n0.33  1.33  0.33\\n0.33  0.33  1.33\\n\"\n\n>>> putStr . dispf 2 $ (3><4)[1,1.5..]\n3x4\n1.00  1.50  2.00  2.50\n3.00  3.50  4.00  4.50\n5.00  5.50  6.00  6.50\n\n>>> putStr . unlines . tail . lines . dispf 2 . asRow $ linspace 10 (0,1)\n0.00  0.11  0.22  0.33  0.44  0.56  0.67  0.78  0.89  1.00\n\n-}\ndispf :: Int -> Matrix Float -> String\ndispf d x = sdims x ++ \"\\n\" ++ formatFixed (if isInt x then 0 else d) x\n\nsdims :: Matrix t -> [Char]\nsdims x = show (rows x) ++ \"x\" ++ show (cols x)\n\nformatFixed :: (Show a, Text.Printf.PrintfArg t, Element t)\n            => a -> Matrix t -> String\nformatFixed d x = format \"  \" (printf (\"%.\"++show d++\"f\")) $ x\n\nisInt :: Matrix Float -> Bool\nisInt = all lookslikeInt . toList . flatten\n\nformatScaled :: (Text.Printf.PrintfArg b, RealFrac b, Floating b, Num t, Element b, Show t)\n             => t -> Matrix b -> [Char]\nformatScaled dec t = \"E\"++show o++\"\\n\" ++ ss\n    where ss = format \" \" (printf fmt. g) t\n          g x | o >= 0    = x/10^(o::Int)\n              | otherwise = x*10^(-o)\n          o | rows t == 0 || cols t == 0 = 0\n            | otherwise = floor $ maximum $ map (logBase 10 . abs) $ toList $ flatten t\n          fmt = '%':show (dec+3) ++ '.':show dec ++\"f\"\n\n{- | Show a vector using a function for showing matrices.\n\n>>> putStr . vecdisp (dispf 2) $ linspace 10 (0,1)\n10 |> 0.00  0.11  0.22  0.33  0.44  0.56  0.67  0.78  0.89  1.00\n\n-}\nvecdisp :: (Element t) => (Matrix t -> String) -> Vector t -> String\nvecdisp f v\n    = ((show (dim v) ++ \" |> \") ++) . (++\"\\n\")\n    . unwords . lines .  tail . dropWhile (not . (`elem` \" \\n\"))\n    . f . trans . reshape 1\n    $ v\n\n{- | Tool to display matrices with latex syntax.\n\n>>>  latexFormat \"bmatrix\" (dispf 2 $ ident 2)\n\"\\\\begin{bmatrix}\\n1  &  0\\n\\\\\\\\\\n0  &  1\\n\\\\end{bmatrix}\"\n\n-}\nlatexFormat :: String -- ^ type of braces: \\\"matrix\\\", \\\"bmatrix\\\", \\\"pmatrix\\\", etc.\n            -> String -- ^ Formatted matrix, with elements separated by spaces and newlines\n            -> String\nlatexFormat del tab = \"\\\\begin{\"++del++\"}\\n\" ++ f tab ++ \"\\\\end{\"++del++\"}\"\n    where f = unlines . intersperse \"\\\\\\\\\" . map unwords . map (intersperse \" & \" . words) . tail . lines\n\n-- | Pretty print a complex number with at most n decimal digits.\nshowComplex :: Int -> Complex Float -> String\nshowComplex d (a:+b)\n    | isZero a && isZero b = \"0\"\n    | isZero b = sa\n    | isZero a && isOne b = s2++\"i\"\n    | isZero a = sb++\"i\"\n    | isOne b = sa++s3++\"i\"\n    | otherwise = sa++s1++sb++\"i\"\n  where\n    sa = shcr d a\n    sb = shcr d b\n    s1 = if b<0 then \"\" else \"+\"\n    s2 = if b<0 then \"-\" else \"\"\n    s3 = if b<0 then \"-\" else \"+\"\n\nshcr :: (Show a, Show t1, Text.Printf.PrintfType t, Text.Printf.PrintfArg t1, RealFrac t1)\n     => a -> t1 -> t\nshcr d a | lookslikeInt a = printf \"%.0f\" a\n         | otherwise      = printf (\"%.\"++show d++\"f\") a\n\nlookslikeInt :: (Show a, RealFrac a) => a -> Bool\nlookslikeInt x = show (round x :: Int) ++\".0\" == shx || \"-0.0\" == shx\n   where shx = show x\n\nisZero :: Show a => a -> Bool\nisZero x = show x `elem` [\"0.0\",\"-0.0\"]\nisOne :: Show a => a -> Bool\nisOne  x = show x `elem` [\"1.0\",\"-1.0\"]\n\n-- | Pretty print a complex matrix with at most n decimal digits.\ndispcf :: Int -> Matrix (Complex Float) -> String\ndispcf d m = sdims m ++ \"\\n\" ++ format \"  \" (showComplex d) m\n\n--------------------------------------------------------------------\n\napparentCols :: FilePath -> IO Int\napparentCols s = f . dropWhile null . map words . lines <$> readFile s\n  where\n    f []    = 0\n    f (x:_) = length x\n\n\n-- | load a matrix from an ASCII file formatted as a 2D table.\nloadMatrix :: FilePath -> IO (Matrix Float)\nloadMatrix f = do\n    v <- vectorScan f\n    c <- apparentCols f\n    if (dim v `mod` c /= 0)\n      then\n        error $ printf \"loadMatrix: %d elements and %d columns in file %s\"\n                       (dim v) c f\n      else\n        return (reshape c v)\n\nloadMatrix' :: FilePath -> IO (Maybe (Matrix Float))\nloadMatrix' name = mbCatch (loadMatrix name)\n\n", "meta": {"hexsha": "2df8a7724c0cc4fbb6a894433c27e84a9a65c514", "size": 5912, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Internal/IO.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Internal/IO.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Internal/IO.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 32.306010929, "max_line_length": 105, "alphanum_fraction": 0.5509133965, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.41270474686468256}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n\n{-# OPTIONS -Wall #-}\n-- | some functions for working with uniformly-sampled data\nmodule Statistics.Iteratee.Uniform (\n  someRollingFunction\n, movingAverage\n) where\n\nimport Statistics.Iteratee.Compat\nimport Statistics.Iteratee.Sample\n\nimport Control.Monad.Identity\nimport Data.Iteratee as I\nimport Data.ListLike (ListLike)\n\n#if MIN_VERSION_iteratee(0,9,0)\n#else\nimport qualified Data.ListLike as LL\n#endif\n\n#if MIN_VERSION_iteratee(0,9,0)\nroll'\n    :: (Monad m, ListLike s el)\n    => Int  -- ^ length of chunk (t)\n    -> Int  -- ^ amount to consume (d)\n    -> Iteratee s m [s]\nroll' = roll\n#else\nroll'\n    :: (Monad m, Nullable s, ListLike s el)\n    => Int  -- ^ length of chunk (t)\n    -> Int  -- ^ amount to consume (d)\n    -> Iteratee s m [s]\nroll' t d\n  | t > d  = liftI (go LL.empty)\n  | otherwise = error \"Iteratee.roll: (t <= d).  Reverse the args?\"\n    where\n        go prev (Chunk vec) =\n                let withPrev = prev `LL.append` vec\n                in if LL.length withPrev > t\n                    then idone [LL.take t withPrev] (Chunk $ LL.drop d withPrev)\n                    else liftI (go withPrev)\n        go prev e = idone [prev] e\n#endif\n\nsomeRollingFunction\n    :: (Monad m, ListLikey s el)\n    => Int\n    -> (s -> summary)\n    -> Enumeratee s [summary] m a\nsomeRollingFunction count mkSummary =\n    convStream (roll' count 1)\n    ><> mapStream mkSummary\n{-# INLINABLE someRollingFunction #-}\n\nmovingAverage\n    :: (Fractional el, Monad m, ListLikey s el)\n    => Int\n    -> Enumeratee s [el] m a\nmovingAverage n = someRollingFunction n chunkMean\n  where\n    chunkMean = runIdentity . (run <=< flip enumPure1Chunk mean)\n{-# INLINABLE movingAverage #-}\n", "meta": {"hexsha": "72b157744cdece40710da4f945eced557f683add", "size": 1808, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/Iteratee/Uniform.hs", "max_stars_repo_name": "JohnLato/iter-stats", "max_stars_repo_head_hexsha": "328bc988c8457904c863f721c686b3a296bc57d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-09T01:32:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-09T01:32:23.000Z", "max_issues_repo_path": "src/Statistics/Iteratee/Uniform.hs", "max_issues_repo_name": "JohnLato/iter-stats", "max_issues_repo_head_hexsha": "328bc988c8457904c863f721c686b3a296bc57d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Statistics/Iteratee/Uniform.hs", "max_forks_repo_name": "JohnLato/iter-stats", "max_forks_repo_head_hexsha": "328bc988c8457904c863f721c686b3a296bc57d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-01-02T06:31:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T06:59:34.000Z", "avg_line_length": 26.5882352941, "max_line_length": 80, "alphanum_fraction": 0.6388274336, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.41257486130408366}}
{"text": "module AsteriskGaussianConvolution where\n\nimport           Control.Monad                  as M\nimport qualified Data.Array.Accelerate          as A\nimport           Data.Array.Accelerate.LLVM.PTX\nimport           Data.Array.Repa                as R\nimport           Data.Binary\nimport           Data.Complex\nimport           Data.List                      as L\nimport           Data.Vector.Storable           as VS\nimport           Data.Vector.Unboxed            as VU\nimport           DFT.Plan\nimport           Filter.Utils\nimport           FokkerPlanck.GreensFunction\nimport           FokkerPlanck.Histogram\nimport           Foreign.CUDA.Driver            as CUDA\nimport           FourierMethod.FourierSeries2D\nimport           FourierPinwheel\nimport           Image.IO\nimport           STC                            hiding (convolve)\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Utils.Array\nimport           Utils.List\nimport           Utils.Parallel\nimport           Utils.Time\n\nmain = do\n  args@(deviceIDsStr:numPointsStr:deltaStr:thresholdStr:numPointsReconStr:deltaReconStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:tauStr:numR2FreqStr:periodR2Str:phiFreqsStr:rhoFreqsStr:thetaFreqsStr:scaleFreqsStr:initDistStr:initScaleStr:histFilePath:stdR2Str:stdStr:numBatchR2Str:numBatchR2FreqsStr:numBatchOriStr:batchSizeStr:sStr:radiusStr:numThreadStr:_) <-\n    getArgs\n  let deviceIDs = read deviceIDsStr :: [Int]\n      numPoints = read numPointsStr :: Int\n      delta = read deltaStr :: Double\n      threshold = read thresholdStr :: Double\n      numPointsRecon = read numPointsReconStr :: Int\n      deltaRecon = read deltaReconStr :: Double\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      tau = read tauStr :: Double\n      numR2Freq = read numR2FreqStr :: Int\n      periodR2 = read periodR2Str :: Double\n      phiFreq = read phiFreqsStr :: Int\n      phiFreqs = L.map fromIntegral [-phiFreq .. phiFreq]\n      rhoFreq = read rhoFreqsStr :: Int\n      rhoFreqs = L.map fromIntegral [-rhoFreq .. rhoFreq]\n      thetaFreq = read thetaFreqsStr :: Int\n      thetaFreqs = L.map fromIntegral [-thetaFreq .. thetaFreq]\n      scaleFreq = read scaleFreqsStr :: Int\n      scaleFreqs = L.map fromIntegral [-scaleFreq .. scaleFreq]\n      initScale = read initScaleStr :: Double\n      initDist = read initDistStr :: [(Double, Double, Double, Double)]\n      initPoints = L.map (\\(x, y, t, s) -> Point x y t s) initDist\n      initSource = [L.head initPoints]\n      initSink = [L.last initPoints]\n      numThread = read numThreadStr :: Int\n      folderPath = \"output/test/AsteriskGaussianConvolution\"\n      maxScale = read maxScaleStr :: Double\n      halfLogPeriod = log maxScale\n      stdR2 = read stdR2Str :: Double\n      std = read stdStr :: Double\n      numBatchR2 = read numBatchR2Str :: Int\n      numBatchR2Freqs = read numBatchR2FreqsStr :: Int\n      numBatchOri = read numBatchOriStr :: Int\n      batchSize = read batchSizeStr :: Int\n      s = read sStr :: Double\n      radius = read radiusStr :: Double\n      periodEnvelope = periodR2^2 / 2 \n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  initialise []\n  devs <- M.mapM device deviceIDs\n  ctxs <- M.mapM (\\dev -> CUDA.create dev []) devs\n  ptxs <- M.mapM createTargetFromContext ctxs\n  hist <-\n    if flag\n      then do\n        printCurrentTime \"Read coefficients...\"\n        decodeFile histFilePath\n      else do\n        printCurrentTime \"Start computing coefficients...\"\n        sampleCartesian\n          histFilePath\n          folderPath\n          ptxs\n          numPoints\n          periodEnvelope\n          delta\n          numOrientation\n          initScale\n          thetaSigma\n          tau\n          threshold\n          s\n          phiFreq\n          rhoFreq\n          thetaFreq\n          scaleFreq\n  printCurrentTime \"Done\"\n  printCurrentTime \"Start Convloution..\"\n  plan <-\n    makePlan\n      folderPath\n      emptyPlan\n      numPointsRecon\n      numPointsRecon\n      numR2Freq\n      (2 * thetaFreq + 1)\n      (2 * scaleFreq + 1)\n      (2 * phiFreq + 1)\n      (2 * rhoFreq + 1)\n  let periodEnv = periodR2 * sqrt 2\n      coefficients = getNormalizedHistogramArr hist\n      harmonicsArray =\n        createHarmonics\n          numR2Freq\n          phiFreq\n          rhoFreq\n          thetaFreq\n          scaleFreq\n          (-s)\n          periodR2\n          periodEnv\n          coefficients\n      asteriskGaussianVecs =\n        asteriskGaussianFull\n          numR2Freq\n          thetaFreq\n          scaleFreq\n          (-s)\n          periodR2\n          periodEnv\n          10\n          10\n      r2Freqs = getListFromNumber numR2Freq\n      shiftFilter =\n        fromListUnboxed\n          (Z :. numR2Freq :. numR2Freq)\n          [ L.foldl'\n            (\\b (Point x y theta scale) ->\n               b +\n               cis\n                 (-(fromIntegral freqX * x + fromIntegral freqY * y) * 2 * pi /\n                   periodR2))\n            0\n            initSource\n          | freqY <- r2Freqs\n          , freqX <- r2Freqs\n          ]\n      dftID = DFTPlanID DFT1DG [numR2Freq, numR2Freq] [0, 1]\n      idftID = DFTPlanID IDFT1DG [numR2Freq, numR2Freq] [0, 1]\n  shiftFilterF <-\n    dftExecute plan dftID . VU.convert . toUnboxed . computeS . makeFilter2D $\n    shiftFilter\n  asteriskGaussianF <- dftExecuteBatchP plan dftID asteriskGaussianVecs\n  filteredAsteriskGaussian <-\n    fmap VS.concat .\n    dftExecuteBatchP plan idftID . parMap rdeepseq (VS.zipWith (*) shiftFilterF) $\n    asteriskGaussianF\n  let numThetaFreq = 2 * thetaFreq + 1\n      numRFreq = 2 * scaleFreq + 1\n      sourceDist =\n        FPArray\n          numR2Freq\n          numR2Freq\n          (2 * scaleFreq + 1)\n          (2 * thetaFreq + 1)\n          (2 * rhoFreq + 1)\n          (2 * phiFreq + 1) .\n        parMap\n          rdeepseq\n          (\\radialFreq ->\n             VU.convert .\n             toUnboxed .\n             computeS .\n             R.slice\n               (fromUnboxed\n                  (Z :. numRFreq :. numThetaFreq :. numR2Freq :. numR2Freq) .\n                VS.convert $\n                filteredAsteriskGaussian) $\n             (Z :. radialFreq :. All :. All :. All)) $\n        [0 .. 2 * scaleFreq]\n  source <- convolve harmonicsArray sourceDist\n  let sourceMat = A.transpose . toMatrixAcc $ source\n  sourceR2' <-\n    computeFourierSeriesR2StreamAcc\n      ptxs\n      (getFPArrayNumXFreq source)\n      numPointsRecon\n      (getFPArrayNumRFreq source * getFPArrayNumThetaFreq source)\n      periodR2\n      delta\n      numBatchR2\n      sourceMat\n  let sourceR2 =\n        R.reshape\n          (Z :. numRFreq :. numThetaFreq :. numPointsRecon :. numPointsRecon)\n          sourceR2'\n  plotImageRepa (folderPath </> \"Source.png\") .\n    ImageRepa 8 .\n    fromUnboxed (Z :. (1 :: Int) :. numPointsRecon :. numPointsRecon) .\n    VU.map sqrt .\n    toUnboxed . sumS . sumS . R.map (\\x -> (magnitude x) ** 2) . rotate4D2 $\n    sourceR2\n", "meta": {"hexsha": "73e209f21d8fd2cdaeb3522502f675884aa051b9", "size": 7138, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/AsteriskGaussianConvolution/AsteriskGaussianConvolution.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/AsteriskGaussianConvolution/AsteriskGaussianConvolution.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/AsteriskGaussianConvolution/AsteriskGaussianConvolution.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 34.4830917874, "max_line_length": 390, "alphanum_fraction": 0.5982067806, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177519, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.41245294313770303}}
{"text": "-----------------------------------------------------------------------------\n-- |\n-- Module      : Berp.Base.Operators\n-- Copyright   : (c) 2010 Bernie Pope\n-- License     : BSD-style\n-- Maintainer  : florbitous@gmail.com\n-- Stability   : experimental\n-- Portability : ghc\n--\n-- Implementation of Python's operators. Where possible we should try to\n-- specialise them to commonly used types.\n--\n-- Note: Complex numbers intentionally don't have an ordering.\n--\n-----------------------------------------------------------------------------\n\nmodule Berp.Base.Operators\n   ( (+), (-), (*), (/), (==), (<), (>), (<=), (>=), (.), and, or, (%)\n   , unaryMinus, unaryPlus, invert, not\n\n   , modIntIntInt\n   , addIntIntInt\n   , addIntFloatFloat\n   , addIntComplexComplex\n   , subIntIntInt\n   , subIntFloatFloat\n   , subIntComplexComplex\n   , mulIntIntInt\n   , mulIntFloatFloat\n   , mulIntComplexComplex\n   , divIntIntInt\n   , divIntFloatFloat\n   , divIntComplexComplex\n   , leIntIntBool\n   , leIntFloatBool\n   , gtIntIntBool\n   , gtIntFloatBool\n   , eqIntIntBool\n   , eqIntFloatBool\n   , eqIntComplexBool\n   , ltIntIntBool\n   , ltIntFloatBool\n   , geIntIntBool\n   , geIntFloatBool\n\n   , addFloatFloatFloat\n   , addFloatIntFloat\n   , addFloatComplexComplex\n   , subFloatFloatFloat\n   , subFloatIntFloat\n   , subFloatComplexComplex\n   , mulFloatFloatFloat\n   , mulFloatIntFloat\n   , mulFloatComplexComplex\n   , divFloatFloatFloat\n   , divFloatIntFloat\n   , divFloatComplexComplex\n   , leFloatFloatBool\n   , leFloatIntBool\n   , gtFloatFloatBool\n   , gtFloatIntBool\n   , eqFloatFloatBool\n   , eqFloatIntBool\n   , eqFloatComplexBool\n   , ltFloatFloatBool\n   , ltFloatIntBool\n   , geFloatFloatBool\n   , geFloatIntBool\n\n   , addComplexComplexComplex\n   , addComplexIntComplex\n   , addComplexFloatComplex\n   , subComplexComplexComplex\n   , subComplexIntComplex\n   , subComplexFloatComplex\n   , mulComplexComplexComplex\n   , mulComplexIntComplex\n   , mulComplexFloatComplex\n   , divComplexComplexComplex\n   , divComplexIntComplex\n   , divComplexFloatComplex\n   , eqComplexComplexBool\n   , eqComplexIntBool\n   , eqComplexFloatBool\n\n   )\n   where\n\nimport Data.Complex (Complex (..))\nimport Prelude hiding ((+), (-), (*), (.), (/), (==), (<), (>), (<=), (>=), or, and, not)\nimport qualified Prelude ((==),(<),(>=),(*),(+),(-),(<=),(>),(.),(/), not)\nimport Berp.Base.Prims (callMethod, raise)\nimport Berp.Base.Builtins.Exceptions (typeError, zeroDivisionError)\nimport Berp.Base.Object (lookupAttribute)\nimport Berp.Base.SemanticTypes (Object (..), Eval)\nimport Berp.Base.Hash (Hashed)\nimport Berp.Base.StdNames\n   ( specialModName, specialAddName, specialSubName, specialMulName, specialDivName, specialLeName\n   , specialGtName, specialEqName, specialLtName, specialGeName)\nimport Berp.Base.Truth (truth)\nimport {-# SOURCE #-} Berp.Base.StdTypes.Integer (int)\nimport {-# SOURCE #-} Berp.Base.StdTypes.Float (float)\nimport {-# SOURCE #-} Berp.Base.StdTypes.Bool (bool, true, false)\nimport {-# SOURCE #-} Berp.Base.StdTypes.Complex (complex)\n\ninfixl 9  .\ninfixl 7 *, /, %\ninfixl 6  +, -\ninfix  4  ==, <, <=, >=, >\ninfixr 3 `and`\ninfixr 2 `or`\n\n{-\n  Is it possible to minimise the boiler plate?\n  Maybe Template Haskell?\n-}\n\n-- We specialise some operations for particular types rather than\n-- going via the method lookups. Fall back to method look ups for the\n-- general case.\n\nbinop :: Hashed String -> Object -> Object -> Eval Object\nbinop str arg1 arg2 = callMethod arg1 str [arg2]\n\nspecialiseOp :: (Object -> a) -> (Object -> a) ->\n                (a -> a -> r) -> (r -> Object) -> Object -> Object -> Eval Object\nspecialiseOp project1 project2 op build obj1 obj2 =\n   return $ build (project1 obj1 `op` project2 obj2)\n\nspecialiseOpIntIntInt :: (Integer -> Integer -> Integer) -> Object -> Object -> Eval Object\nspecialiseOpIntIntInt op = specialiseOp object_integer object_integer op int\n\nspecialiseOpIntIntBool :: (Integer -> Integer -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpIntIntBool op = specialiseOp object_integer object_integer op bool\n\n{-\nspecialiseOpBoolBoolBool :: (Bool -> Bool -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpBoolBoolBool op = specialiseOp object_bool object_bool op bool\n-}\n\nspecialiseOpFloatFloatFloat :: (Double -> Double -> Double) -> Object -> Object -> Eval Object\nspecialiseOpFloatFloatFloat op = specialiseOp object_float object_float op float\n\nspecialiseOpFloatFloatBool :: (Double -> Double -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpFloatFloatBool op = specialiseOp object_float object_float op bool\n\nspecialiseOpIntFloatFloat :: (Double -> Double -> Double) -> Object -> Object -> Eval Object\nspecialiseOpIntFloatFloat op =\n   specialiseOp (fromInteger Prelude.. object_integer) object_float op float\n\nspecialiseOpIntFloatBool :: (Double -> Double -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpIntFloatBool op =\n   specialiseOp (fromInteger Prelude.. object_integer) object_float op bool\n\nspecialiseOpFloatIntFloat :: (Double -> Double -> Double) -> Object -> Object -> Eval Object\nspecialiseOpFloatIntFloat op =\n   specialiseOp object_float (fromInteger Prelude.. object_integer) op float\n\nspecialiseOpFloatIntBool :: (Double -> Double -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpFloatIntBool op =\n   specialiseOp object_float (fromInteger Prelude.. object_integer) op bool\n\ntype ComplexD = Complex Double\n\nspecialiseOpComplexComplexComplex :: (ComplexD -> ComplexD -> ComplexD) -> Object -> Object -> Eval Object\nspecialiseOpComplexComplexComplex op = specialiseOp object_complex object_complex op complex\n\nspecialiseOpComplexComplexBool :: (ComplexD -> ComplexD -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpComplexComplexBool op = specialiseOp object_complex object_complex op bool\n\nspecialiseOpIntComplexBool :: (ComplexD -> ComplexD -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpIntComplexBool op = specialiseOp (fromInteger Prelude.. object_integer) object_complex op bool\n\nspecialiseOpComplexIntBool :: (ComplexD -> ComplexD -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpComplexIntBool op = specialiseOp object_complex (fromInteger Prelude.. object_integer) op bool\n\nspecialiseOpFloatComplexBool :: (ComplexD -> ComplexD -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpFloatComplexBool op = specialiseOp (realToFrac Prelude.. object_float) object_complex op bool\n\nspecialiseOpComplexFloatBool :: (ComplexD -> ComplexD -> Bool) -> Object -> Object -> Eval Object\nspecialiseOpComplexFloatBool op = specialiseOp object_complex (realToFrac Prelude.. object_float) op bool\n\nspecialiseOpFloatComplexComplex :: (ComplexD -> ComplexD -> ComplexD) -> Object -> Object -> Eval Object\nspecialiseOpFloatComplexComplex op =\n   specialiseOp (realToFrac Prelude.. object_float) object_complex op complex\n\nspecialiseOpComplexFloatComplex :: (ComplexD -> ComplexD -> ComplexD) -> Object -> Object -> Eval Object\nspecialiseOpComplexFloatComplex op =\n   specialiseOp object_complex (realToFrac Prelude.. object_float) op complex\n\nspecialiseOpIntComplexComplex :: (ComplexD -> ComplexD -> ComplexD) -> Object -> Object -> Eval Object\nspecialiseOpIntComplexComplex op =\n   specialiseOp (fromInteger Prelude.. object_integer) object_complex op complex\n\nspecialiseOpComplexIntComplex :: (ComplexD -> ComplexD -> ComplexD) -> Object -> Object -> Eval Object\nspecialiseOpComplexIntComplex op =\n   specialiseOp object_complex (fromInteger Prelude.. object_integer) op complex\n\n(%), (+), (-), (*), (/), (==), (<), (>), (<=), (>=), or, and :: Object -> Object -> Eval Object\n\nmodIntIntInt :: Object -> Object -> Eval Object\nmodIntIntInt = specialiseOpIntIntInt (Prelude.mod)\n\n-- XXX fixme\n(%) obj1@(Integer {}) obj2@(Integer {}) = modIntIntInt obj1 obj2\n(%) x y = binop specialModName x y\n\naddIntIntInt, addFloatFloatFloat, addIntFloatFloat, addFloatIntFloat, addComplexComplexComplex, addIntComplexComplex, addComplexIntComplex, addFloatComplexComplex, addComplexFloatComplex :: Object -> Object -> Eval Object\n\naddIntIntInt = specialiseOpIntIntInt (Prelude.+)\naddFloatFloatFloat = specialiseOpFloatFloatFloat (Prelude.+)\naddIntFloatFloat = specialiseOpIntFloatFloat (Prelude.+)\naddFloatIntFloat = specialiseOpFloatIntFloat (Prelude.+)\naddComplexComplexComplex = specialiseOpComplexComplexComplex (Prelude.+)\naddIntComplexComplex = specialiseOpIntComplexComplex (Prelude.+)\naddComplexIntComplex = specialiseOpComplexIntComplex (Prelude.+)\naddFloatComplexComplex = specialiseOpFloatComplexComplex (Prelude.+)\naddComplexFloatComplex = specialiseOpComplexFloatComplex (Prelude.+)\n\n(+) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> addIntIntInt obj1 obj2\n      Float {} -> addIntFloatFloat obj1 obj2\n      Complex {} -> addIntComplexComplex obj1 obj2\n      _other -> raise typeError\n(+) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> addFloatFloatFloat obj1 obj2\n      Integer {} -> addFloatIntFloat obj1 obj2\n      Complex {} -> addFloatComplexComplex obj1 obj2\n      _other -> raise typeError\n(+) obj1@(Complex {}) obj2 =\n   case obj2 of\n      Complex {} -> addComplexComplexComplex obj1 obj2\n      Integer {} -> addComplexIntComplex obj1 obj2\n      Float {} -> addComplexFloatComplex obj1 obj2\n      _other -> raise typeError\n(+) x y = binop specialAddName x y\n\nsubIntIntInt, subFloatFloatFloat, subIntFloatFloat, subFloatIntFloat, subComplexComplexComplex, subIntComplexComplex, subComplexIntComplex, subFloatComplexComplex, subComplexFloatComplex :: Object -> Object -> Eval Object\n\nsubIntIntInt = specialiseOpIntIntInt (Prelude.-)\nsubFloatFloatFloat = specialiseOpFloatFloatFloat (Prelude.-)\nsubIntFloatFloat = specialiseOpIntFloatFloat (Prelude.-)\nsubFloatIntFloat = specialiseOpFloatIntFloat (Prelude.-)\nsubComplexComplexComplex = specialiseOpComplexComplexComplex (Prelude.-)\nsubIntComplexComplex = specialiseOpIntComplexComplex (Prelude.-)\nsubComplexIntComplex = specialiseOpComplexIntComplex (Prelude.-)\nsubFloatComplexComplex = specialiseOpFloatComplexComplex (Prelude.-)\nsubComplexFloatComplex = specialiseOpComplexFloatComplex (Prelude.-)\n\n(-) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> subIntIntInt obj1 obj2\n      Float {} -> subIntFloatFloat obj1 obj2\n      Complex {} -> subIntComplexComplex obj1 obj2\n      _other -> raise typeError\n(-) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> subFloatFloatFloat obj1 obj2\n      Integer {} -> subFloatIntFloat obj1 obj2\n      Complex {} -> subFloatComplexComplex obj1 obj2\n      _other -> raise typeError\n(-) obj1@(Complex {}) obj2 =\n   case obj2 of\n      Complex {} -> subComplexComplexComplex obj1 obj2\n      Integer {} -> subComplexIntComplex obj1 obj2\n      Float {} -> subComplexFloatComplex obj1 obj2\n      _other -> raise typeError\n(-) x y = binop specialSubName x y\n\nmulIntIntInt, mulFloatFloatFloat, mulIntFloatFloat, mulFloatIntFloat, mulComplexComplexComplex, mulIntComplexComplex, mulComplexIntComplex, mulFloatComplexComplex, mulComplexFloatComplex :: Object -> Object -> Eval Object\n\nmulIntIntInt = specialiseOpIntIntInt (Prelude.*)\nmulFloatFloatFloat = specialiseOpFloatFloatFloat (Prelude.*)\nmulIntFloatFloat = specialiseOpIntFloatFloat (Prelude.*)\nmulFloatIntFloat = specialiseOpFloatIntFloat (Prelude.*)\nmulComplexComplexComplex = specialiseOpComplexComplexComplex (Prelude.*)\nmulIntComplexComplex = specialiseOpIntComplexComplex (Prelude.*)\nmulComplexIntComplex = specialiseOpComplexIntComplex (Prelude.*)\nmulFloatComplexComplex = specialiseOpFloatComplexComplex (Prelude.*)\nmulComplexFloatComplex = specialiseOpComplexFloatComplex (Prelude.*)\n\n(*) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> mulIntIntInt obj1 obj2\n      Float {} -> mulIntFloatFloat obj1 obj2\n      Complex {} -> mulIntComplexComplex obj1 obj2\n      _other -> raise typeError\n(*) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> mulFloatFloatFloat obj1 obj2\n      Integer {} -> mulFloatIntFloat obj1 obj2\n      Complex {} -> mulFloatComplexComplex obj1 obj2\n      _other -> raise typeError\n(*) obj1@(Complex {}) obj2 =\n   case obj2 of\n      Complex {} -> mulComplexComplexComplex obj1 obj2\n      Integer {} -> mulComplexIntComplex obj1 obj2\n      Float {} -> mulComplexFloatComplex obj1 obj2\n      _other -> raise typeError\n(*) x y = binop specialMulName x y\n\ncheckDivByZero :: Num a => a -> Eval Object -> Eval Object\ncheckDivByZero denom comp\n   | denom Prelude.== 0 = raise zeroDivisionError\n   | otherwise = comp\n\ndivIntIntInt, divFloatFloatFloat, divIntFloatFloat, divFloatIntFloat, divComplexComplexComplex, divIntComplexComplex, divComplexIntComplex, divFloatComplexComplex, divComplexFloatComplex :: Object -> Object -> Eval Object\n\ndivIntIntInt obj1 obj2 =\n   checkDivByZero (object_integer obj2) $ specialiseOpIntIntInt (Prelude.div) obj1 obj2\ndivFloatFloatFloat obj1 obj2 =\n   checkDivByZero (object_float obj2) $ specialiseOpFloatFloatFloat (Prelude./) obj1 obj2\ndivIntFloatFloat obj1 obj2 =\n   checkDivByZero (object_float obj2) $ specialiseOpIntFloatFloat (Prelude./) obj1 obj2\ndivFloatIntFloat obj1 obj2 =\n   checkDivByZero (object_integer obj2) $ specialiseOpFloatIntFloat (Prelude./) obj1 obj2\ndivComplexComplexComplex obj1 obj2 =\n   checkDivByZero (object_complex obj2) $ specialiseOpComplexComplexComplex (Prelude./) obj1 obj2\ndivIntComplexComplex obj1 obj2 =\n   checkDivByZero (object_complex obj2) $ specialiseOpIntComplexComplex (Prelude./) obj1 obj2\ndivComplexIntComplex obj1 obj2 =\n   checkDivByZero (object_integer obj2) $ specialiseOpComplexIntComplex (Prelude./) obj1 obj2\ndivFloatComplexComplex obj1 obj2 =\n   checkDivByZero (object_complex obj2) $ specialiseOpFloatComplexComplex (Prelude./) obj1 obj2\ndivComplexFloatComplex obj1 obj2 =\n   checkDivByZero (object_float obj2) $ specialiseOpComplexFloatComplex (Prelude./) obj1 obj2\n\n(/) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> divIntIntInt obj1 obj2\n      Float {} -> divIntFloatFloat obj1 obj2\n      Complex {} -> divIntComplexComplex obj1 obj2\n      _other -> raise typeError\n(/) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> divFloatFloatFloat obj1 obj2\n      Integer {} -> divFloatIntFloat obj1 obj2\n      Complex {} -> divFloatComplexComplex obj1 obj2\n      _other -> raise typeError\n(/) obj1@(Complex {}) obj2 =\n   case obj2 of\n      Complex {} -> divComplexComplexComplex obj1 obj2\n      Integer {} -> divComplexIntComplex obj1 obj2\n      Float {} -> divComplexFloatComplex obj1 obj2\n      _other -> raise typeError\n(/) x y = binop specialDivName x y\n\nleIntIntBool, leFloatFloatBool, leIntFloatBool, leFloatIntBool :: Object -> Object -> Eval Object\n\nleIntIntBool = specialiseOpIntIntBool (Prelude.<=)\nleFloatFloatBool = specialiseOpFloatFloatBool (Prelude.<=)\nleIntFloatBool = specialiseOpIntFloatBool (Prelude.<=)\nleFloatIntBool = specialiseOpFloatIntBool (Prelude.<=)\n\n(<=) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> leIntIntBool obj1 obj2\n      Float {} -> leIntFloatBool obj1 obj2\n      _other -> raise typeError\n(<=) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> leFloatFloatBool obj1 obj2\n      Integer {} -> leIntFloatBool obj1 obj2\n      _other -> raise typeError\n(<=) x y = binop specialLeName x y\n\ngtIntIntBool, gtFloatFloatBool, gtIntFloatBool, gtFloatIntBool :: Object -> Object -> Eval Object\n\ngtIntIntBool = specialiseOpIntIntBool (Prelude.>)\ngtFloatFloatBool = specialiseOpFloatFloatBool (Prelude.>)\ngtIntFloatBool = specialiseOpIntFloatBool (Prelude.>)\ngtFloatIntBool = specialiseOpFloatIntBool (Prelude.>)\n\n(>) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> gtIntIntBool obj1 obj2\n      Float {} -> gtIntFloatBool obj1 obj2\n      _other -> raise typeError\n(>) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> gtFloatFloatBool obj1 obj2\n      Integer {} -> gtIntFloatBool obj1 obj2\n      _other -> raise typeError\n(>) x y = binop specialGtName x y\n\neqIntIntBool, eqFloatFloatBool, eqIntFloatBool, eqFloatIntBool, eqComplexComplexBool, eqIntComplexBool, eqComplexIntBool, eqFloatComplexBool, eqComplexFloatBool :: Object -> Object -> Eval Object\n\neqIntIntBool = specialiseOpIntIntBool (Prelude.==)\neqFloatFloatBool = specialiseOpFloatFloatBool (Prelude.==)\neqIntFloatBool = specialiseOpIntFloatBool (Prelude.==)\neqFloatIntBool = specialiseOpFloatIntBool (Prelude.==)\neqComplexComplexBool = specialiseOpComplexComplexBool (Prelude.==)\neqIntComplexBool = specialiseOpIntComplexBool (Prelude.==)\neqComplexIntBool = specialiseOpComplexIntBool (Prelude.==)\neqFloatComplexBool = specialiseOpFloatComplexBool (Prelude.==)\neqComplexFloatBool = specialiseOpComplexFloatBool (Prelude.==)\n\n(==) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> eqIntIntBool obj1 obj2\n      Float {} -> eqIntFloatBool obj1 obj2\n      Complex {} -> eqIntComplexBool obj1 obj2\n      _other -> raise typeError\n(==) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> eqFloatFloatBool obj1 obj2\n      Integer {} -> eqIntFloatBool obj1 obj2\n      Complex {} -> eqFloatComplexBool obj1 obj2\n      _other -> raise typeError\n(==) obj1@(Complex {}) obj2 =\n   case obj2 of\n      Complex {} -> eqComplexComplexBool obj1 obj2\n      Integer {} -> eqComplexIntBool obj1 obj2\n      Float {} -> eqComplexFloatBool obj1 obj2\n      _other -> raise typeError\n(==) x y = binop specialEqName x y\n\nltIntIntBool, ltFloatFloatBool, ltIntFloatBool, ltFloatIntBool :: Object -> Object -> Eval Object\n\nltIntIntBool = specialiseOpIntIntBool (Prelude.<)\nltFloatFloatBool = specialiseOpFloatFloatBool (Prelude.<)\nltIntFloatBool = specialiseOpIntFloatBool (Prelude.<)\nltFloatIntBool = specialiseOpFloatIntBool (Prelude.<)\n\n(<) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> ltIntIntBool obj1 obj2\n      Float {} -> ltIntFloatBool obj1 obj2\n      _other -> raise typeError\n(<) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> ltFloatFloatBool obj1 obj2\n      Integer {} -> ltIntFloatBool obj1 obj2\n      _other -> raise typeError\n(<) x y = binop specialLtName x y\n\ngeIntIntBool, geFloatFloatBool, geIntFloatBool, geFloatIntBool :: Object -> Object -> Eval Object\n\ngeIntIntBool = specialiseOpIntIntBool (Prelude.>=)\ngeFloatFloatBool = specialiseOpFloatFloatBool (Prelude.>=)\ngeIntFloatBool = specialiseOpIntFloatBool (Prelude.>=)\ngeFloatIntBool = specialiseOpFloatIntBool (Prelude.>=)\n\n(>=) obj1@(Integer {}) obj2 =\n   case obj2 of\n      Integer {} -> geIntIntBool obj1 obj2\n      Float {} -> geIntFloatBool obj1 obj2\n      _other -> raise typeError\n(>=) obj1@(Float {}) obj2 =\n   case obj2 of\n      Float {} -> geFloatFloatBool obj1 obj2\n      Integer {} -> geIntFloatBool obj1 obj2\n      _other -> raise typeError\n(>=) x y = binop specialGeName x y\n\n{-\n   From the Python Language Reference, sec 5.10 \"Boolean Operations\"\n   The expression x and y first evaluates x; if x is false, its value\n   is returned; otherwise, y is evaluated and the resulting value is\n   returned.\n-}\nand obj1 obj2\n   | truth obj1 = return obj2\n   | otherwise  = return obj1\n\n{-\n   The expression x or y first evaluates x; if x is true, its value \n   is returned; otherwise, y is evaluated and the resulting value \n   is returned.\n-}\n\nor obj1 obj2\n   | truth obj1 = return obj1\n   | otherwise  = return obj2\n\n(.) :: Object -> Hashed String -> Eval Object\n(.) object ident = lookupAttribute object ident\n\nunaryMinus :: Object -> Eval Object\nunaryMinus obj@(Integer {}) = return $ int $ negate $ object_integer obj\nunaryMinus obj@(Float {}) = return $ float $ negate $ object_float obj\nunaryMinus obj@(Complex {}) = return $ complex $ negate $ object_complex obj\nunaryMinus _other = error \"unary minus applied to a non integer\"\n\n-- This is just the identity function\nunaryPlus :: Object -> Eval Object\nunaryPlus obj@(Integer {}) = return obj\nunaryPlus obj@(Float {}) = return obj\nunaryPlus obj@(Complex {}) = return obj\n-- XXX in CPython this turns the boolean into an integer\nunaryPlus obj@(Bool {}) = return obj\nunaryPlus _other = error \"unary plus applied to a non integer\"\n\ninvert :: Object -> Eval Object\ninvert (Integer {}) = error \"bitwise inversion not implemented\"\ninvert _other = error \"unary invert applied to a non integer\"\n\nnot :: Object -> Eval Object\nnot obj\n   | Prelude.not $ truth obj = return true\n   | otherwise = return false\n", "meta": {"hexsha": "a4eb249f7899f48b5896863d08f850e6314fcefb", "size": 20205, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "libs/src/Berp/Base/Operators.hs", "max_stars_repo_name": "ppelleti/berp", "max_stars_repo_head_hexsha": "30925288376a6464695341445688be64ac6b2600", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90, "max_stars_repo_stars_event_min_datetime": "2015-02-03T23:56:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T03:55:32.000Z", "max_issues_repo_path": "libs/src/Berp/Base/Operators.hs", "max_issues_repo_name": "ppelleti/berp", "max_issues_repo_head_hexsha": "30925288376a6464695341445688be64ac6b2600", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-04-01T13:49:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-09T19:28:56.000Z", "max_forks_repo_path": "libs/src/Berp/Base/Operators.hs", "max_forks_repo_name": "bjpop/berp", "max_forks_repo_head_hexsha": "30925288376a6464695341445688be64ac6b2600", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-04-25T03:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-27T06:33:56.000Z", "avg_line_length": 40.0892857143, "max_line_length": 221, "alphanum_fraction": 0.726800297, "num_tokens": 5495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.41245293696923524}}
{"text": "{-# LANGUAGE TemplateHaskell       #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE ConstraintKinds       #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE RankNTypes            #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\nmodule Test.Grenade.Recurrent.Layers.LSTM where\n\nimport           Hedgehog\nimport           Hedgehog.Internal.Source\nimport           Hedgehog.Internal.Show\nimport           Hedgehog.Internal.Property ( failWith, Diff (..) )\n\nimport           Data.Foldable ( toList )\nimport           Data.Singletons.TypeLits\n\nimport           Grenade\nimport           Grenade.Recurrent\n\nimport qualified Numeric.LinearAlgebra as H\nimport qualified Numeric.LinearAlgebra.Static as S\n\n\nimport qualified Test.Grenade.Recurrent.Layers.LSTM.Reference as Reference\nimport           Test.Hedgehog.Hmatrix\n\ngenLSTM :: forall i o. (KnownNat i, KnownNat o) => Gen (LSTM i o)\ngenLSTM = do\n    let w = uniformSample\n        u = uniformSample\n        v = randomVector\n\n        w0 = S.konst 0\n        u0 = S.konst 0\n        v0 = S.konst 0\n\n    LSTM <$> (LSTMWeights <$> w <*> u <*> v <*> w <*> u <*> v <*> w <*> u <*> v <*> w <*> v)\n         <*> pure (LSTMWeights w0 u0 v0 w0 u0 v0 w0 u0 v0 w0 v0)\n\nprop_lstm_reference_forwards =\n  property $ do\n    input :: S.R 3                       <- forAll randomVector\n    cell :: S.R 2                        <- forAll randomVector\n    net@(LSTM lstmWeights _) :: LSTM 3 2 <- forAll genLSTM\n\n    let actual          = runRecurrentForwards net (S1D cell) (S1D input)\n    case actual of\n      (_, (S1D cellOut) :: S ('D1 2), (S1D output) :: S ('D1 2)) ->\n        let cellOut'        = Reference.Vector . H.toList . S.extract $ cellOut\n            output'         = Reference.Vector . H.toList . S.extract $ output\n            refNet          = Reference.lstmToReference lstmWeights\n            refCell         = Reference.Vector . H.toList . S.extract $ cell\n            refInput        = Reference.Vector . H.toList . S.extract $ input\n            (refCO, refO)   = Reference.runLSTM refNet refCell refInput\n        in do toList refCO ~~~ toList cellOut'\n              toList refO ~~~ toList output'\n\n\nprop_lstm_reference_backwards =\n  property $ do\n    input :: S.R 3                       <- forAll randomVector\n    cell :: S.R 2                        <- forAll randomVector\n    net@(LSTM lstmWeights _) :: LSTM 3 2 <- forAll genLSTM\n    let (tape, _ :: S ('D1 2), _ :: S ('D1 2))\n                                          = runRecurrentForwards  net (S1D cell) (S1D input)\n        actualBacks                       = runRecurrentBackwards net tape (S1D (S.konst 1) :: S ('D1 2)) (S1D (S.konst 1) :: S ('D1 2))\n    case actualBacks of\n      (actualGradients, _, _ :: S ('D1 3)) ->\n        let refNet          = Reference.lstmToReference lstmWeights\n            refCell         = Reference.Vector . H.toList . S.extract $ cell\n            refInput        = Reference.Vector . H.toList . S.extract $ input\n            refGradients    = Reference.runLSTMback refCell refInput refNet\n        in toList refGradients ~~~ toList (Reference.lstmToReference actualGradients)\n\nprop_lstm_reference_backwards_input =\n  property $ do\n    input :: S.R 3                       <- forAll randomVector\n    cell :: S.R 2                        <- forAll randomVector\n    net@(LSTM lstmWeights _) :: LSTM 3 2 <- forAll genLSTM\n    let (tape, _ :: S ('D1 2), _ :: S ('D1 2))\n                                          = runRecurrentForwards  net (S1D cell) (S1D input)\n        actualBacks                       = runRecurrentBackwards net tape (S1D (S.konst 1) :: S ('D1 2)) (S1D (S.konst 1) :: S ('D1 2))\n    case actualBacks of\n      (_, _, S1D actualGradients :: S ('D1 3)) ->\n        let refNet          = Reference.lstmToReference lstmWeights\n            refCell         = Reference.Vector . H.toList . S.extract $ cell\n            refInput        = Reference.Vector . H.toList . S.extract $ input\n            refGradients    = Reference.runLSTMbackOnInput refCell refNet refInput\n        in toList refGradients ~~~ H.toList (S.extract actualGradients)\n\nprop_lstm_reference_backwards_cell =\n  property $ do\n    input :: S.R 3                       <- forAll randomVector\n    cell :: S.R 2                        <- forAll randomVector\n    net@(LSTM lstmWeights _) :: LSTM 3 2 <- forAll genLSTM\n    let (tape, _ :: S ('D1 2), _ :: S ('D1 2))\n                                          = runRecurrentForwards  net (S1D cell) (S1D input)\n        actualBacks                       = runRecurrentBackwards net tape (S1D (S.konst 1) :: S ('D1 2)) (S1D (S.konst 1) :: S ('D1 2))\n    case actualBacks of\n      (_, S1D actualGradients, _ :: S ('D1 3)) ->\n        let refNet          = Reference.lstmToReference lstmWeights\n            refCell         = Reference.Vector . H.toList . S.extract $ cell\n            refInput        = Reference.Vector . H.toList . S.extract $ input\n            refGradients    = Reference.runLSTMbackOnCell refInput refNet refCell\n        in toList refGradients ~~~ H.toList (S.extract actualGradients)\n\n(~~~) :: (Monad m, Eq a, Ord a, Num a, Fractional a, Show a, HasCallStack) => [a] -> [a] -> PropertyT m ()\n(~~~) x y =\n  if all (< 1e-8) (zipWith (-) x y) then\n    success\n  else\n    case valueDiff <$> mkValue x <*> mkValue y of\n      Nothing ->\n        withFrozenCallStack $\n          failWith Nothing $ unlines [\n              \"\u2501\u2501\u2501 Not Simliar \u2501\u2501\u2501\"\n            , showPretty x\n            , showPretty y\n            ]\n      Just differ ->\n        withFrozenCallStack $\n          failWith (Just $ Diff \"Failed (\" \"- lhs\" \"~/~\" \"+ rhs\" \")\" differ) \"\"\ninfix 4 ~~~\n\ntests :: IO Bool\ntests = checkParallel $$(discover)\n", "meta": {"hexsha": "7c030e0646b394a0461b6a04850d6917e1033b80", "size": 5799, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Recurrent/Layers/LSTM.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1527, "max_stars_repo_stars_event_min_datetime": "2016-06-23T13:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T05:22:00.000Z", "max_issues_repo_path": "test/Test/Grenade/Recurrent/Layers/LSTM.hs", "max_issues_repo_name": "Alien-Inc/grenade", "max_issues_repo_head_hexsha": "14ec0de6bf65d28f981b171ee00f2e0993a369ec", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 69, "max_issues_repo_issues_event_min_datetime": "2016-06-27T22:16:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-20T17:50:09.000Z", "max_forks_repo_path": "test/Test/Grenade/Recurrent/Layers/LSTM.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": 44.2671755725, "max_line_length": 136, "alphanum_fraction": 0.5569925849, "num_tokens": 1566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4124192265743156}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE AllowAmbiguousTypes   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveAnyClass        #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedLabels      #-}\n{-# LANGUAGE OverloadedStrings     #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-|\nModule      : Grenade.Layers.Mul\nDescription : Scalar multiplication with some constant, supporting scaling\nMaintainer  : Theo Charalambous\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.Mul \n  (\n  -- * Layer Definition\n    Mul (..)\n  \n  -- * Helper function\n  , initMul \n  )\nwhere\n\nimport           Data.Kind                    (Type)\nimport           Data.Proxy\nimport           Data.Serialize\nimport           GHC.TypeLits\n\nimport qualified Numeric.LinearAlgebra        as LA\nimport           Numeric.LinearAlgebra.Static (R)\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport           Lens.Micro                   ((^.))\n\nimport           Grenade.Core\nimport           Grenade.Onnx\n\n-- | A layer allowing for element wise multiplication with broadcasting\ndata Mul :: Nat -- The number of channels of the bias\n         -> Nat -- The number of rows of the bias\n         -> Nat -- The number of columns of the bias\n         -> Type where\n  Mul  :: ( KnownNat channels\n          , KnownNat rows\n          , KnownNat columns )\n          => R (channels * rows * columns)\n          -> Mul channels rows columns\n\ninstance Show (Mul c h w) where\n  show (Mul mat) = \"Mul \" ++ show mat\n\ninstance UpdateLayer (Mul c h w) where\n  type Gradient (Mul c h w) = ()\n  runUpdate _ x _  = x\n  reduceGradient _ = ()\n\ninstance (KnownNat c, KnownNat h, KnownNat w ) => RandomLayer (Mul c h w) where\n  createRandomWith _ _ = pure initMul\n\n-- ^ Initialize a Mul layer with scale 1 \ninitMul :: forall c h w. ( KnownNat c, KnownNat h, KnownNat w )\n        => Mul c h w\ninitMul =\n  let c'    = fromIntegral $ natVal (Proxy :: Proxy c)\n      h'    = fromIntegral $ natVal (Proxy :: Proxy h)\n      w'    = fromIntegral $ natVal (Proxy :: Proxy w)\n      ones  = replicate (c' * h' * w') 1\n      bias  = H.fromList ones :: R (c * h * w)\n  in Mul bias\n\ninstance ( KnownNat c, KnownNat h, KnownNat w ) => Serialize (Mul c h w) where\n  put (Mul bias) = putListOf put . LA.toList . H.extract $ bias\n  get            = do\n    bias <- maybe (fail \"Vector of incorrect size\") return . H.create . LA.fromList =<< getListOf get\n    return $ Mul bias\n\n-- | Currently, only multiplication by a single scalar is supported.\ninstance ( KnownNat i, KnownNat j, KnownNat k ) => Layer (Mul 1 1 1) ('D3 i j k) ('D3 i j k) where\n  type Tape (Mul 1 1 1) ('D3 i j k) ('D3 i j k) = ()\n\n  runForwards (Mul b) (S3D m)\n    = let s  = H.extract b LA.! 0\n      in  ((), S3D $  H.dmmap (s *) m)\n\n  runBackwards = error \"runBackwards is not implemented for the Mul layer\"\n\ninstance OnnxOperator (Mul c h w) where\n  onnxOpTypeNames _ = [\"Mul\"]\n\ninstance (KnownNat c, KnownNat h, KnownNat w) => OnnxLoadable (Mul c h w) where\n  loadOnnxNode inits node = case node ^. #input of\n    [_, scale] -> do\n      loadedScale <- readInitializerVector inits scale\n\n      return $ Mul loadedScale\n    _               -> onnxIncorrectNumberOfInputs\n\n", "meta": {"hexsha": "26e50eb8339b839f7324ca482580eef776e174d5", "size": 3559, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Mul.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Mul.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Mul.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6513761468, "max_line_length": 101, "alphanum_fraction": 0.6122506322, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.412035447126084}}
{"text": "{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE OverloadedStrings     #-}\n\nmodule Main where\n\nimport           Control.Applicative\nimport           Control.Monad\nimport           Control.Monad.Random\n\nimport           Data.List ( foldl' )\nimport           Data.Maybe ( mapMaybe )\n#if ! MIN_VERSION_base(4,13,0)\nimport           Data.Semigroup ( (<>) )\n#endif\nimport           Data.Csv ( FromField, FromRecord, decode, parseField, HasHeader(..) )\nimport           Data.ByteString.Lazy.Char8 (pack)\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Storable as SV\n\nimport           Numeric.LinearAlgebra ( maxIndex )\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport           Options.Applicative\nimport           System.FilePath ( (</>) )\nimport           System.Random.Shuffle (shuffleM)\nimport           GHC.Generics (Generic)\nimport           GHC.Float ( float2Double)\n\nimport           Grenade\nimport           Grenade.Utils.OneHot\n\n\n-- Adapted from https://mmhaskell.com/machine-learning/deep-learning\n\n-- It's logistic regression!\n--\n-- This network is used to show how we can embed a Network as a layer in the larger IrisNetwork\n-- type.\n\ntype IrisNetwork\n  = Network\n      '[FullyConnected 4 10, Relu, FullyConnected 10 3]\n      '[ 'D1 4, 'D1 10, 'D1 10, 'D1 3]\n\ntype IrisRow = (S ( 'D1 4), S ( 'D1 3))\n\nrandomIris :: MonadRandom m => m IrisNetwork\nrandomIris = randomNetwork\n\nrunIris :: Int -> FilePath -> Int -> LearningParameters -> IO ()\nrunIris iterations dataDir nSamples rate = do\n  records <- readIrisFromFile (dataDir </> \"iris.data\")\n  let numRecords = V.length records\n  shuffledRecords <- chooseRandomRecords records numRecords\n  let (trainRecords, validateRecords) = V.splitAt nSamples shuffledRecords\n\n  let trainData = mapMaybe parseRecord (V.toList trainRecords)\n  let validateData = mapMaybe parseRecord (V.toList validateRecords)\n\n  if length trainData\n       /= length trainRecords\n       || length validateData\n       /= length validateRecords\n    then putStrLn\n      \"Parsing train data or validation data could not be fully parsed\"\n    else do\n      initialNetwork <- randomIris\n      foldM_ (run trainData validateData) initialNetwork [1 .. iterations]\n where\n\n  run :: [IrisRow] -> [IrisRow] -> IrisNetwork -> Int -> IO IrisNetwork\n  run trainData validateData network iterationNum = do\n    sampledData <- V.toList\n      <$> chooseRandomRecords (V.fromList trainData) (nSamples * 3 `div` 4)\n    -- Slower drop the learning rate\n    let rate' = rate { learningRate = learningRate rate * 0.99 ^ iterationNum }\n    let newNetwork     = foldl' (trainRow rate') network sampledData\n    let labelVectors   = fmap (testRow newNetwork) validateData\n    let labelValues    = fmap getLabels labelVectors\n    let total          = length labelValues\n    let correctEntries = length $ filter ((==) <$> fst <*> snd) labelValues\n    putStrLn $ \"Iteration: \" ++ show iterationNum\n    putStrLn $ show correctEntries ++ \" correct out of: \" ++ show total\n    return newNetwork\n\n  trainRow :: LearningParameters -> IrisNetwork -> IrisRow -> IrisNetwork\n  trainRow lp network (input, output) = train lp network input output\n\n  -- Takes a test row, returns predicted output and actual output from the network.\n  testRow :: IrisNetwork -> IrisRow -> (S ( 'D1 3), S ( 'D1 3))\n  testRow net (rowInput, predictedOutput) =\n    (predictedOutput, runNet net rowInput)\n\n  -- Goes from probability output vector to label\n  getLabels :: (S ( 'D1 3), S ( 'D1 3)) -> (Int, Int)\n  getLabels (S1D predictedLabel, S1D actualOutput) =\n    (maxIndex (SA.extract predictedLabel), maxIndex (SA.extract actualOutput))\n\n\n\ndata IrisOpts = IrisOpts FilePath Int Int LearningParameters\n\niris' :: Parser IrisOpts\niris' =\n  IrisOpts\n    <$> argument str (metavar \"DATADIR\")\n        -- How many samples from the dataset should be used for training?\n        -- (The rest are used for validation)\n    <*> option auto (long \"training_samples\" <> short 't' <> value 100)\n    <*> option auto (long \"iterations\" <> short 'i' <> value 15)\n    <*> (   LearningParameters\n        <$> option auto (long \"train_rate\" <> short 'r' <> value 0.01)\n        <*> option auto (long \"momentum\" <> value 0.9)\n        <*> option auto (long \"l2\" <> value 0.0005)\n        )\n\nmain :: IO ()\nmain = do\n  IrisOpts dataDir nSamples iter rate <- execParser\n    (info (iris' <**> helper) idm)\n  putStr \"Training convolutional neural network with \"\n  putStr $ show nSamples\n  putStrLn \" samples...\"\n\n  runIris iter dataDir nSamples rate\n\ndata IrisClass = Setosa | Versicolor | Virginica\n  deriving (Show, Read, Eq, Ord, Generic, Enum, Bounded)\n\ndata IrisRecord = IrisRecord {\n    sepalLength :: Float,\n    sepalWidth  :: Float,\n    petalLength :: Float,\n    petalWidth  :: Float,\n    specie      :: IrisClass\n} deriving (Generic, Show, Read)\n\ninstance FromRecord IrisRecord\n\ninstance FromField IrisClass where\n  parseField \"Iris-setosa\"     = return Setosa\n  parseField \"Iris-versicolor\" = return Versicolor\n  parseField \"Iris-virginica\"  = return Virginica\n  parseField _                 = fail \"unknown iris class\"\n\nparseRecord :: IrisRecord -> Maybe IrisRow\nparseRecord record = case (input, output) of\n  (Just i, Just o) -> Just (i, o)\n  _                -> Nothing\n where\n  input =\n    fromStorable\n      $   SV.fromList\n      $   float2Double\n      <$> [ sepalLength record / 8.0\n          , sepalWidth record / 8.0\n          , petalLength record / 8.0\n          , petalWidth record / 8.0\n          ]\n  output = oneHot (fromEnum $ specie record)\n\nreadIrisFromFile :: FilePath -> IO (V.Vector IrisRecord)\nreadIrisFromFile fp = do\n  contents <- readFile fp\n  let contentsAsBs = pack contents\n  let results =\n        decode HasHeader contentsAsBs :: Either String (V.Vector IrisRecord)\n  case results of\n    Left  err     -> error err\n    Right records -> return records\n\n\n-- A function that takes this vector of records, and selects sampleSize of them at random.\nchooseRandomRecords :: V.Vector a -> Int -> IO (V.Vector a)\nchooseRandomRecords records sampleSize = do\n  let numRecords = V.length records\n  chosenIndices <- take sampleSize <$> shuffleM [0 .. (numRecords - 1)]\n  return . V.fromList $ (records V.!) <$> chosenIndices\n\n", "meta": {"hexsha": "eaa72182fc869a51ac67dadce22dc148bd765c96", "size": 6448, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/iris.hs", "max_stars_repo_name": "jrp2014/grenade", "max_stars_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/main/iris.hs", "max_issues_repo_name": "jrp2014/grenade", "max_issues_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/main/iris.hs", "max_forks_repo_name": "jrp2014/grenade", "max_forks_repo_head_hexsha": "ccd26792001909d521d41dd9685d85639470bc75", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6666666667, "max_line_length": 95, "alphanum_fraction": 0.6637717122, "num_tokens": 1638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.4117091096980237}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n\n-- |\n-- Module      :  Spiral.Array.Repr.Complex\n-- Copyright   :  (c) 2016 Drexel University\n-- License     :  BSD-style\n-- Maintainer  :  mainland@drexel.edu\n\nmodule Spiral.Array.Repr.Complex (\n    RE,\n    toRealArray,\n\n    CMPLX,\n    toComplexArray,\n\n    Array(..)\n  ) where\n\nimport Prelude hiding (read)\n\nimport Data.Complex (Complex)\nimport Data.Monoid ((<>))\nimport Text.PrettyPrint.Mainland\nimport Text.PrettyPrint.Mainland.Class\n\nimport Spiral.Array\nimport Spiral.Exp\n\ndata RE r\n\ntoRealArray :: Array r (sh :. Int) (Exp (Complex a)) -> Array (RE r) (sh :. Int) (Exp a)\ntoRealArray = RE\n\ninstance IsArray r (sh :. Int) (Exp (Complex a)) => IsArray (RE r) (sh :. Int) (Exp a) where\n    data Array (RE r) (sh :. Int) (Exp a) = RE (Array r (sh :. Int) (Exp (Complex a)))\n\n    extent (RE a) = sh :. 2*n\n      where\n        sh :. n = extent a\n\ninstance Pretty (Array r (sh :. Int) (Exp (Complex a))) => Pretty (Array (RE r) (sh :. Int) (Exp a)) where\n    ppr (RE a) = text \"Re\" <> parens (ppr a)\n\ninstance (RealFloatConst a, Shape sh, IArray r (sh :. Int) (Exp (Complex a))) => IArray (RE r) (sh :. Int) (Exp a) where\n    index (RE a) (sh :. i)\n        | i `rem` 2 == 0 = re\n        | otherwise      = im\n      where\n        (re, im) = unComplexE (index a (sh :. i `quot` 2))\n\ninstance (RealFloatConst a, SArray r (sh :. Int) (Exp (Complex a))) => SArray (RE r) (sh :. Int) (Exp a) where\n    indexS (RE a) (sh :. i)\n        | i `rem` 2 == 0 = re\n        | otherwise      = im\n      where\n        (re, im) = unComplexE (indexS a (sh :. i `quot` 2))\n\ninstance (RealFloatConst a, MArray r (sh :. Int) (Exp (Complex a))) => MArray (RE r) (sh :. Int) (Exp a) where\n    read (RE a) (sh :. i) = do\n        (re, im) <- unComplexE <$> read a (sh :. i `quot` 2)\n        if i `rem` 2 == 0\n          then return re\n          else return im\n\n    write (RE a) (sh :. i) e = do\n        (re, im) <- unComplexE <$> read a (sh :. i `quot` 2)\n        if i `rem` 2 == 0\n          then write a (sh :. i `quot` 2) (ComplexE e im)\n          else write a (sh :. i `quot` 2) (ComplexE re e)\n\ninstance (RealFloatConst a, SArray r (sh :. Int) (Exp (Complex a))) => Computable (RE r) (sh :. Int) (Exp a) where\n    computeP a b =\n        forShapeP (extent b) $ \\ix ->\n            write a ix (indexS b ix)\n\ndata CMPLX r\n\ntoComplexArray :: Array r (sh :. Int) (Exp a) -> Array (CMPLX r) (sh :. Int) (Exp (Complex a))\ntoComplexArray = CMPLX\n\ninstance IsArray r (sh :. Int) (Exp a) => IsArray (CMPLX r) (sh :. Int) (Exp (Complex a)) where\n    data Array (CMPLX r) (sh :. Int) (Exp (Complex a)) = CMPLX (Array r (sh :. Int) (Exp a))\n\n    extent (CMPLX a) = sh :. n `quot` 2\n      where\n        sh :. n = extent a\n\ninstance Pretty (Array r (sh :. Int) (Exp a)) => Pretty (Array (CMPLX r) (sh :. Int) (Exp (Complex a))) where\n    ppr (CMPLX a) = text \"Cmplx\" <> parens (ppr a)\n\ninstance (Typed a, Num (Exp a), IArray r (sh :. Int) (Exp a)) => IArray (CMPLX r) (sh :. Int) (Exp (Complex a)) where\n    index (CMPLX a) (sh :. i) = ComplexE (index a (sh :. 2*i)) (index a (sh :. 2*i+1))\n\ninstance (Typed a, Num (Exp a), SArray r (sh :. Int) (Exp a)) => SArray (CMPLX r) (sh :. Int) (Exp (Complex a)) where\n    indexS (CMPLX a) (sh :. i) = ComplexE (indexS a (sh :. 2*i)) (indexS a (sh :. 2*i+1))\n\ninstance (RealFloatConst a, MArray r (sh :. Int) (Exp a)) => MArray (CMPLX r) (sh :. Int) (Exp (Complex a)) where\n    read (CMPLX a) (sh :. i) = ComplexE <$> read a (sh :. 2*i) <*> read a (sh :. 2*i+1)\n\n    write (CMPLX a) (sh :. i) e = do\n        write a (sh :. 2*i) er\n        write a (sh :. 2*i+1) ei\n      where\n        (er, ei) = unComplexE e\n\ninstance (RealFloatConst a, Computable r (sh :. Int) (Exp a)) => Computable (CMPLX r) (sh :. Int) (Exp (Complex a)) where\n    computeP a (CMPLX b) = computeP (toRealArray a) b\n", "meta": {"hexsha": "bc4d23a247b1978df56826f01e8285ef00db478b", "size": 4015, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Spiral/Array/Repr/Complex.hs", "max_stars_repo_name": "mainland/hspiral", "max_stars_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-21T21:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T04:48:25.000Z", "max_issues_repo_path": "Spiral/Array/Repr/Complex.hs", "max_issues_repo_name": "mainland/hspiral", "max_issues_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Spiral/Array/Repr/Complex.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2192982456, "max_line_length": 121, "alphanum_fraction": 0.5616438356, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41157530773824313}}
{"text": "-- * This module defines how to run and extract time/space data\n--   from benchmarks.\n--\nmodule Test.BigOh.Benchmark\n  ( -- * Running benchmarks\n    runInputs\n  , getTimes\n  , getStdDevs\n  , defaultBenchmarkConfig\n  ) where\n\nimport           Control.Monad.IO.Class\nimport           Criterion.Internal\nimport           Criterion.Main\nimport           Criterion.Measurement\nimport           Criterion.Monad\nimport           Criterion.Types\nimport           Statistics.Resampling.Bootstrap\n\nimport           Test.BigOh.Generate\n\ndefaultBenchmarkConfig = defaultConfig { timeLimit = 1, resamples = 100 }\n\nrunOne :: Config -> Benchmarkable -> IO Report\nrunOne cfg x\n  = withConfig cfg\n  $ do liftIO initializeTime\n       runAndAnalyseOne 0 \"\" x\n\nrunInputs :: Config -> [(Benchmarkable, Input a)] -> IO [(Input a, Report)]\nrunInputs cfg xs\n  = zip (map snd xs) <$> mapM (runOne cfg . fst) xs\n\ngetTimes :: [(Input a, Report)] -> [(Int, Double)]\ngetTimes = map go\n  where\n    go (i, report)\n      = (inputSize i, estPoint $ anMean $ reportAnalysis report)\n\ngetStdDevs :: [(Input a, Report)] -> [Double]\ngetStdDevs = map (estPoint . anStdDev . reportAnalysis . snd)\n", "meta": {"hexsha": "1f5f705d303c43ac5d8f7450b655cbada900c6f6", "size": 1157, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Test/BigOh/Benchmark.hs", "max_stars_repo_name": "tranma/shitty-complexity", "max_stars_repo_head_hexsha": "573815a8af9d5f3cda3c96e22d59b71ec9f29de9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2018-02-22T16:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T16:38:35.000Z", "max_issues_repo_path": "src/Test/BigOh/Benchmark.hs", "max_issues_repo_name": "tranma/shitty-complexity", "max_issues_repo_head_hexsha": "573815a8af9d5f3cda3c96e22d59b71ec9f29de9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-12-06T21:59:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-06T21:59:07.000Z", "max_forks_repo_path": "src/Test/BigOh/Benchmark.hs", "max_forks_repo_name": "tranma/shitty-complexity", "max_forks_repo_head_hexsha": "573815a8af9d5f3cda3c96e22d59b71ec9f29de9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-06T22:26:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-06T22:26:24.000Z", "avg_line_length": 27.5476190476, "max_line_length": 75, "alphanum_fraction": 0.6620570441, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41157530129026}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Main where\n\n-- import Data.Array.Repa (Array, U, DIM2)\nimport qualified Data.Array.Repa as R\nimport qualified Data.IntMap as IM\nimport Control.Monad\nimport Data.Complex\nimport qualified Data.Vector as V\nimport qualified Linear.V as V\nimport LSI\nimport LSI.Examples\nimport LSI.FrequencyResponse\nimport LSI.Grid\nimport LSI.RationalFunction\nimport LSI.TransferFunction\nimport Unsafe.Coerce (unsafeCoerce)\n\ngraph :: SystemGraph 2 String Double\ngraph = toGraph $ deriche_ydiff 1.0\n\ntfs :: IM.IntMap (RationalFunction 2 Double)\ntfs = IM.map simplify $ transferFunctions graph\n\nfrequencyResponses :: IM.IntMap (V.V 2 Double -> Complex Double)\nfrequencyResponses = IM.map computeFR tfs\n\nn :: Num a => a\nn = 50\n\ngrid :: R.Array R.D R.DIM2 (Double, Double)\ngrid = frequencyGrid2D n\n\nnPoints :: Num a => Double\nnPoints = (2*n)^2\n\nplotFR :: (V.V 2 Double -> Complex Double) -> R.Array R.D R.DIM2 (Complex Double)\nplotFR fr = R.map (fr . V.V . V.fromList . \\(w1,w2) -> [w1,w2]) grid\n\nl2Norm :: R.Array R.D R.DIM2 (Complex Double) -> IO Double\nl2Norm plot = fmap (/ nPoints) $ R.foldAllP (+) 0 squares\n  where squares = R.map (\\x -> realPart $ (abs x)^2) plot\n\nplots :: IM.IntMap (R.Array R.D R.DIM2 (Complex Double))\nplots = IM.map plotFR $ unsafeCoerce frequencyResponses -- TODO: Kind mismatch.\n\nmain :: IO ()\nmain = do\n  -- print grid\n  -- let plot = plots IM.! 13\n  -- forM_ [0..2*n+1] $ \\(i::Int) ->\n  --   forM_ [0..2*n+1] $ \\(j::Int) -> do\n  --     let (x,y,z) = (i,j, (^ 2) . realPart . abs $ plot R.! (R.Z R.:. i R.:. j))\n  --     putStrLn $ show i ++ \", \" ++ show j ++ \", \" ++ show z\n  -- print $ toMatlabFunction $ tfs IM.! 13\n  -- norm <- l2Norm plot\n  -- print norm\n\n  let ps = IM.elems plots\n  norms <- forM ps $ \\p -> l2Norm p\n  print norms\n", "meta": {"hexsha": "cb9e7bf3a972ab7cc11cbcf45b79d7e6a8931656", "size": 1814, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/deriche.hs", "max_stars_repo_name": "gdeest/lsi-systems", "max_stars_repo_head_hexsha": "71fc496bde63084f18c48577708b3c202d496a5e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-17T19:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-17T19:09:18.000Z", "max_issues_repo_path": "app/deriche.hs", "max_issues_repo_name": "gdeest/lsi-systems", "max_issues_repo_head_hexsha": "71fc496bde63084f18c48577708b3c202d496a5e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/deriche.hs", "max_forks_repo_name": "gdeest/lsi-systems", "max_forks_repo_head_hexsha": "71fc496bde63084f18c48577708b3c202d496a5e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7936507937, "max_line_length": 83, "alphanum_fraction": 0.6598676957, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.41156100401999834}}
{"text": "{-# LANGUAGE DataKinds           #-}\n{-# LANGUAGE DeriveGeneric       #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE GADTs               #-}\n{-# LANGUAGE OverloadedStrings   #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell     #-}\n{-# LANGUAGE TypeApplications    #-}\n{-# LANGUAGE TypeOperators       #-}\n{-# LANGUAGE QuasiQuotes         #-}\n{-# LANGUAGE RankNTypes          #-}\n{-# LANGUAGE PolyKinds           #-}\n{-# LANGUAGE TypeFamilies        #-}\n{-# LANGUAGE ConstraintKinds     #-}\n{-# LANGUAGE MultiParamTypeClasses     #-}\n{-# LANGUAGE FlexibleInstances         #-}\n{-# LANGUAGE UndecidableInstances      #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE AllowAmbiguousTypes       #-}\n{-# LANGUAGE UndecidableSuperClasses #-}\nmodule Frames.Regression where\n\nimport qualified Frames.Misc                  as FU\nimport qualified Frames.VegaLite.Utils         as FV\nimport qualified Math.Regression.Regression    as MR\nimport qualified Math.Regression.LeastSquares  as MR\nimport qualified Polysemy                      as P\nimport qualified Knit.Effect.Logger            as Log\n\nimport qualified Lucid                         as LH\nimport qualified Text.Blaze.Html               as BH\nimport qualified Control.Foldl                 as FL\nimport qualified Data.List                     as List\nimport qualified Data.Text                     as T\nimport qualified Data.Vinyl                    as V\nimport qualified Data.Vinyl.Functor            as V\nimport qualified Data.Vinyl.TypeLevel          as V\nimport           Data.Profunctor               as PF\nimport qualified Frames                        as F\nimport qualified Frames.Melt                   as F\nimport qualified Data.Vector.Storable          as VS\n\nimport qualified MachineLearning               as ML\nimport qualified MachineLearning.Regression    as ML\nimport qualified Numeric.LinearAlgebra         as LA\nimport           Numeric.LinearAlgebra.Data     ( R )\nimport qualified Statistics.Types              as S\n\nimport           GHC.TypeLits                   ( Symbol )\n\ntype Unweighted = \"unweighted\" F.:-> Void\n\ntype family NonVoidField (f :: (Symbol, Type)) :: Bool where\n  NonVoidField '(a,Void) = 'False\n  NonVoidField _         = 'True\n\nclass BoolVal (w :: Bool) where\n  asBool :: Bool\n\ninstance BoolVal 'True where\n  asBool = True\n\ninstance BoolVal 'False where\n  asBool = False\n\ndata FrameRegressionResult (y :: (Symbol, Type)) (wc :: Bool) (xs :: [(Symbol, Type)]) (w :: (Symbol,Type)) (rs :: [(Symbol, Type)]) where\n  FrameUnweightedRegressionResult :: (w ~ Unweighted)\n    => MR.RegressionResult R -> FrameRegressionResult y wc xs Unweighted rs\n  FrameWeightedRegressionResult :: (V.KnownField w, F.ElemOf rs w)\n    => (V.Snd w -> R) -> MR.RegressionResult R -> FrameRegressionResult y wc xs w rs\n\nrealRecToList\n  :: ( RealFrac b\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => F.Record as\n  -> [b]\nrealRecToList =\n  V.recordToList\n    . V.rmap (\\(V.Compose (V.Dict x)) -> V.Const $ realToFrac x)\n    . V.reifyConstraint @Real\n\ninstance ( MR.Predictor S.NormalErr a (LA.Vector a) (MR.RegressionResult R)\n         , BoolVal wc\n         , LA.Element a\n         , LA.Numeric a\n         , RealFloat a\n         , xs F.\u2286 rs\n         , V.RMap xs\n         , V.RecordToList xs\n         , V.ReifyConstraint Real F.ElField xs\n         , V.NatToInt (V.RLength xs)\n         ) => MR.Predictor S.NormalErr a (F.Record rs) (FrameRegressionResult y wc xs w as) where\n  predict frr r =\n    let rr = regressionResult frr\n        addBias l = if asBool @wc then 1 : l else l -- if we regressed with a constant term, we need to put it into the xs for prediction\n        va :: LA.Vector a = VS.fromList $ addBias $ realRecToList (F.rcast @xs r)\n    in MR.predict rr va\n\nregressionResult :: FrameRegressionResult y wc xs w rs -> MR.RegressionResult R\nregressionResult (FrameUnweightedRegressionResult x) = x\nregressionResult (FrameWeightedRegressionResult _ x) = x\n\nwithConstant\n  :: forall y wc xs w rs\n   . (BoolVal wc)\n  => FrameRegressionResult y wc xs w rs\n  -> Bool\nwithConstant _ = asBool @wc\n\nweightedRegression\n  :: forall y wc xs w rs\n   . (BoolVal (NonVoidField w))\n  => FrameRegressionResult y wc xs w rs\n  -> Bool\nweightedRegression _ = asBool @(NonVoidField w)\n\n-- make X, y from the data \nprepRegression\n  :: forall y as f rs\n   . ( Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> (LA.Matrix R, LA.Vector R)\nprepRegression dat =\n  let\n    nCols  = V.natToInt @(V.RLength as)\n    yListF = PF.dimap (realToFrac . F.rgetField @y) List.reverse FL.list\n    toListOfDoubles :: F.Record as -> [Double] = realRecToList\n    mListF = PF.dimap (toListOfDoubles . F.rcast)\n                      (List.concat . List.reverse)\n                      FL.list\n    (yList, mList) = FL.fold ((,) <$> yListF <*> mListF) dat\n  in\n    (LA.matrix nCols mList, LA.vector yList)\n\n\n-- make X, y, w from the data \nprepWeightedRegression\n  :: forall y as w f rs\n   . ( Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , F.ElemOf rs w\n     , FU.RealField w\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> (LA.Matrix R, LA.Vector R, LA.Vector R)\nprepWeightedRegression dat =\n  let\n    nCols  = V.natToInt @(V.RLength as)\n    yListF = PF.dimap (realToFrac . F.rgetField @y) List.reverse FL.list\n    wListF = PF.dimap (realToFrac . F.rgetField @w) List.reverse FL.list\n    toListOfDoubles :: F.Record as -> [Double] = realRecToList\n    mListF = PF.dimap (toListOfDoubles . F.rcast)\n                      (List.concat . List.reverse)\n                      FL.list\n    (yList, mList, wList) = FL.fold ((,,) <$> yListF <*> mListF <*> wListF) dat\n  in\n    (LA.matrix nCols mList, LA.vector yList, LA.vector wList)\n\n\nprettyPrintRegressionResult\n  :: forall y wc as w rs\n   . ( F.ColumnHeaders '[y]\n     , F.ColumnHeaders '[w]\n     , F.ColumnHeaders as\n     , BoolVal wc\n     )\n  => (T.Text -> T.Text -> T.Text)\n  -> FrameRegressionResult y wc as w rs\n  -> S.CL Double\n  -> T.Text\nprettyPrintRegressionResult headerF res cl =\n  let yName   = FV.colName @y\n      wName   = FV.colName @w\n      xNames' = T.pack <$> F.columnHeaders (Proxy :: Proxy (F.Record as))\n      xNames  = if withConstant res then \"intercept\" : xNames' else xNames'\n  in  MR.prettyPrintRegressionResult (headerF yName wName)\n                                     xNames\n                                     (regressionResult res)\n                                     cl\n\nprettyPrintRegressionResultLucid\n  :: forall y wc as w rs\n   . ( F.ColumnHeaders '[y]\n     , F.ColumnHeaders '[w]\n     , F.ColumnHeaders as\n     , BoolVal wc\n     )\n  => (T.Text -> T.Text -> T.Text)\n  -> FrameRegressionResult y wc as w rs\n  -> S.CL Double\n  -> LH.Html ()\nprettyPrintRegressionResultLucid headerF res cl =\n  let yName   = FV.colName @y\n      wName   = FV.colName @w\n      xNames' = T.pack <$> F.columnHeaders (Proxy :: Proxy (F.Record as))\n      xNames  = if withConstant res then \"intercept\" : xNames' else xNames'\n  in  MR.prettyPrintRegressionResultLucid (headerF yName wName)\n                                          xNames\n                                          (regressionResult res)\n                                          cl\n\nprettyPrintRegressionResultBlaze\n  :: forall y wc as w rs\n   . ( F.ColumnHeaders '[y]\n     , F.ColumnHeaders '[w]\n     , F.ColumnHeaders as\n     , BoolVal wc\n     )\n  => (T.Text -> T.Text -> T.Text)\n  -> FrameRegressionResult y wc as w rs\n  -> S.CL Double\n  -> BH.Html\nprettyPrintRegressionResultBlaze headerF res cl =\n  let yName   = FV.colName @y\n      wName   = FV.colName @w\n      xNames' = T.pack <$> F.columnHeaders (Proxy :: Proxy (F.Record as))\n      xNames  = if withConstant res then \"intercept\" : xNames' else xNames'\n  in  MR.prettyPrintRegressionResultBlaze (headerF yName wName)\n                                          xNames\n                                          (regressionResult res)\n                                          cl\n\n\nkeyRecordText\n  :: (V.ReifyConstraint Show F.ElField ks, V.RecordToList ks, V.RMap ks)\n  => F.Record ks\n  -> T.Text\nkeyRecordText keyRec =\n  let keyValuesAsText rks =\n        V.recordToList\n          . V.rmap (\\(V.Compose (V.Dict x)) -> V.Const $ T.pack $ show x)\n          $ V.reifyConstraint @Show rks\n  in  T.intercalate \"; \" $ keyValuesAsText keyRec\n\nprettyPrintRegressionResults\n  :: forall y wc as w rs k f a\n   . ( F.ColumnHeaders '[y]\n     , F.ColumnHeaders '[w]\n     , F.ColumnHeaders as\n     , BoolVal wc\n     , BoolVal (NonVoidField w)\n     , Foldable f\n     , Monoid a\n     )\n  => (k -> T.Text)\n  -> f (k, FrameRegressionResult y wc as w rs)\n  -> S.CL R\n  -> (  (T.Text -> T.Text -> T.Text)\n     -> FrameRegressionResult y wc as w rs\n     -> S.CL Double\n     -> a\n     )\n  -> a\n  -> a\nprettyPrintRegressionResults keyText keyed cl printOne sepEach =\n  let headerF res key yName wName = if weightedRegression res\n                                    then\n                                      \"Explaining \"\n                                        <> yName\n                                        <> \" (\"\n                                        <> keyText key\n                                        <> \"; weights from \"\n                                        <> wName\n                                        <> \")\"\n                                    else \"Explaining \" <> yName <> \" (\" <> keyText key <> \")\"\n  in  FL.fold\n        (FL.Fold (\\t (rk, res) -> t <> printOne (headerF res rk) res cl)\n                 sepEach\n                 id\n        )\n        keyed\n\n-- explain y in terms of as\nleastSquaresByMinimization\n  :: forall y as rs f\n   . ( Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => Bool\n  -> [R]\n  -> f (F.Record rs)\n  -> [R]\nleastSquaresByMinimization wc guess dat =\n  let (mX, y)       = prepRegression @y @as dat\n      mX1           = if wc then ML.addBiasDimension mX else mX\n      (solution, _) = ML.minimize (ML.ConjugateGradientFR 0.1 0.1)\n                                  ML.LeastSquares\n                                  0.001\n                                  20\n                                  ML.RegNone\n                                  mX1\n                                  y\n                                  (LA.fromList guess)\n  in  LA.toList solution\n\n\nordinaryLeastSquares\n  :: forall effs y wc as rs f\n   . ( Log.LogWithPrefixesLE effs\n     , Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , BoolVal wc\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> P.Sem effs (FrameRegressionResult y wc as Unweighted rs)\nordinaryLeastSquares dat = do\n  let (mA, vB)  = prepRegression @y @as dat\n      withConst = asBool @wc\n  FrameUnweightedRegressionResult <$> MR.ordinaryLS withConst mA vB\n\nweightedLeastSquares\n  :: forall y wc as w rs f effs\n   . ( Log.LogWithPrefixesLE effs\n     , Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , F.ElemOf rs w\n     , FU.RealField w\n     , BoolVal wc\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> P.Sem effs (FrameRegressionResult y wc as w rs)\nweightedLeastSquares dat = do\n  let (mA, vB, vW) = prepWeightedRegression @y @as @w dat\n      withConst    = asBool @wc\n  FrameWeightedRegressionResult realToFrac <$> MR.weightedLS withConst mA vB vW\n\n-- special case when weights come from observations being population averages of different populations\npopWeightedLeastSquares\n  :: forall effs y wc as w rs f\n   . ( Log.LogWithPrefixesLE effs\n     , Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , F.ElemOf rs w\n     , FU.RealField w\n     , BoolVal wc\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> P.Sem effs (FrameRegressionResult y wc as w rs)\npopWeightedLeastSquares dat = do\n  let (mA, vB, vW) = prepWeightedRegression @y @as @w dat\n      withConst    = asBool @wc\n      vWpop        = LA.cmap sqrt vW -- this is the correct weight for population average, the sqrt of the number averaged in that sample \n  FrameWeightedRegressionResult (sqrt . realToFrac)\n    <$> MR.weightedLS withConst mA vB vWpop\n\n\n-- special case when we know residuals are heteroscedastic with variances proportional to given numbers\nvarWeightedLeastSquares\n  :: forall effs y wc as w rs f\n   . ( Log.LogWithPrefixesLE effs\n     , Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , F.ElemOf rs w\n     , FU.RealField w\n     , BoolVal wc\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> P.Sem effs (FrameRegressionResult y wc as w rs)\nvarWeightedLeastSquares dat = do\n  let (mA, vB, vW) = prepWeightedRegression @y @as @w dat\n      withConst    = asBool @wc\n      vWvar        = LA.cmap (\\x -> 1 / sqrt x) vW -- this is the correct weight for given variance\n  FrameWeightedRegressionResult (\\x -> 1 / sqrt (realToFrac x))\n    <$> MR.weightedLS withConst mA vB vWvar\n\ntotalLeastSquares\n  :: forall effs y wc as rs f\n   . ( Log.LogWithPrefixesLE effs\n     , Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , BoolVal wc\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> P.Sem effs (FrameRegressionResult y wc as Unweighted rs)\ntotalLeastSquares dat = do\n  let (mA, vB)  = prepRegression @y @as dat\n      withConst = asBool @wc\n  FrameUnweightedRegressionResult <$> MR.totalLS withConst mA vB\n\n\nweightedTLS\n  :: forall effs y wc as w rs f\n   . ( Log.LogWithPrefixesLE effs\n     , Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , BoolVal wc\n     , F.ElemOf rs w\n     , FU.RealField w\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> P.Sem effs (FrameRegressionResult y wc as w rs)\nweightedTLS dat = do\n  let (mA, vB, vW) = prepWeightedRegression @y @as @w dat\n      withConst    = asBool @wc\n  FrameWeightedRegressionResult realToFrac <$> MR.weightedTLS withConst mA vB vW\n\npopWeightedTLS\n  :: forall effs y wc as w rs f\n   . ( Log.LogWithPrefixesLE effs\n     , Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , BoolVal wc\n     , F.ElemOf rs w\n     , FU.RealField w\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> P.Sem effs (FrameRegressionResult y wc as w rs)\npopWeightedTLS dat = do\n  let (mA, vB, vW) = prepWeightedRegression @y @as @w dat\n      withConst    = asBool @wc\n      vWpop        = LA.cmap sqrt vW -- this is the correct weight for population average, the sqrt of the number averaged in that sample \n  FrameWeightedRegressionResult (sqrt . realToFrac)\n    <$> MR.weightedTLS withConst mA vB vWpop\n\nvarWeightedTLS\n  :: forall effs y wc as w rs f\n   . ( Log.LogWithPrefixesLE effs\n     , Foldable f\n     , as F.\u2286 rs\n     , F.ElemOf rs y\n     , FU.RealField y\n     , BoolVal wc\n     , F.ElemOf rs w\n     , FU.RealField w\n     , V.AllConstrained (FU.RealFieldOf rs) as\n     , V.RMap as\n     , V.RecordToList as\n     , V.ReifyConstraint Real F.ElField as\n     , V.NatToInt (V.RLength as)\n     )\n  => f (F.Record rs)\n  -> P.Sem effs (FrameRegressionResult y wc as w rs)\nvarWeightedTLS dat = do\n  let (mA, vB, vW) = prepWeightedRegression @y @as @w dat\n      withConst    = asBool @wc\n      vWvar        = LA.cmap (\\x -> 1 / sqrt x) vW -- this is the correct weight for given variance\n  FrameWeightedRegressionResult (\\x -> 1 / sqrt (realToFrac x))\n    <$> MR.weightedTLS withConst mA vB vWvar\n\n\n{-\n-- this is sort of ugly but I think it will work.  And it has a pretty narrow purpose\n-- But what will we do when we want logistic regression or whatever?\nclass (V.AllConstrained RealFrac (V.Unlabeled rs), Real a) => RealFracRecordFromList a rs where\n  recordFromList :: [a] -> Maybe (F.Record rs)\n\ninstance Real a => RealFracRecordFromList a '[] where\n  recordFromList _ = Just $ V.RNil\n\ninstance ( V.AllConstrained RealFrac (V.Unlabeled (r : rs))\n         , V.AllConstrained RealFrac (V.Unlabeled rs)\n         , RealFracRecordFromList a rs\n         , V.KnownField r\n         , RealFrac (V.Snd r)\n         , Real a) => RealFracRecordFromList a (r : rs) where\n  recordFromList [] = Nothing\n  recordFromList (a : as) = case recordFromList as of\n    Nothing -> Nothing \n    Just xs -> let x = (realToFrac a) :: V.Snd r in Just $ x &: xs\n-}\n\n", "meta": {"hexsha": "ac9cce0bd0cbc29e8eb45ff434ab8654f9552e22", "size": 17742, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Frames/Regression.hs", "max_stars_repo_name": "teto/Frames-utils", "max_stars_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Frames/Regression.hs", "max_issues_repo_name": "teto/Frames-utils", "max_issues_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Frames/Regression.hs", "max_forks_repo_name": "teto/Frames-utils", "max_forks_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9776951673, "max_line_length": 138, "alphanum_fraction": 0.5942960207, "num_tokens": 5048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.41147487221260975}}
{"text": "module TrainUtils where\n\nimport Control.Lens hiding (para)\nimport System.Random\nimport Control.Monad\nimport Prelude hiding (id, (.))\nimport Numeric.LinearAlgebra.Array\nimport Numeric.LinearAlgebra.Array.Util\n\nimport CategoricDefinitions\nimport Autodiff.GAD\nimport Autodiff.Dual\nimport Autodiff.Additive\nimport Autodiff.D\nimport Autodiff.Cont\nimport Ops\nimport Para\nimport TensorUtils\nimport OnesLike\n\n-------------------------------------------\nshowNNInfo :: (ArrShow p, ArrShow a, ArrShow b)\n    => Int -> a -> b -> LearnerType p a b -> IO ()\nshowNNInfo n a b nn = do\n    putStrLn \"-------------------------\"\n    putStrLn $ \"Step \" ++ arrShow n\n    putStrLn $ \"p\\n\" ++ arrShow (nn ^. p)\n    putStrLn $ \"a\\n\" ++ arrShow a\n    putStrLn $ \"a\\n\" ++ arrShow b\n\n\n-- | Supervised learning training\n-- Takes in a Learner, input-output pairs and a cost function\n-- it partially applies the output to the cost function and composes the result inside learner\ntrainStepWithCost :: (OnesLike c, _)\n    => LearnerType p a b -> (Int, IO (a, b), DType (b, b) c) -> IO (LearnerType p a b)\ntrainStepWithCost l (step, dataSampler, cost) = do\n    (i, o) <- dataSampler\n    when (step `mod` 100 == 0) $ showNNInfo step i o l\n    let cost' = partiallyApply cost o\n        (pGrad, _) = grad (cost' . (l ^. para . fn)) (l ^. p, i)\n    return $ l & p .~ (l ^. optimizer) (l ^. p, pGrad)\n\n\ninstance (Random a, Random b) => Random (a, b) where\n    random gen1 = let (x, gen2) = random gen1\n                      (y, gen3) = random gen2\n                  in ((x, y), gen3)\n\n    randomR ((x1, y1), (x2, y2)) gen1 = let (x, gen2) = randomR (x1, x2) gen1\n                                            (y, gen3) = randomR (y1, y2) gen2\n                                        in ((x, y), gen3)\n", "meta": {"hexsha": "e48513411059700945cf67a93044f726d1f5a7c7", "size": 1761, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TrainUtils.hs", "max_stars_repo_name": "bgavran/Categorical_Deep_Learning", "max_stars_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 123, "max_stars_repo_stars_event_min_datetime": "2018-10-09T03:00:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:59:37.000Z", "max_issues_repo_path": "src/TrainUtils.hs", "max_issues_repo_name": "bgavran/Functional_Deep_Learning", "max_issues_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TrainUtils.hs", "max_forks_repo_name": "bgavran/Functional_Deep_Learning", "max_forks_repo_head_hexsha": "a1c3fce3367a5bddf55287ac8393a729ab815ab9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-12-19T06:19:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T02:52:48.000Z", "avg_line_length": 33.2264150943, "max_line_length": 94, "alphanum_fraction": 0.5848949461, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.41142013306853226}}
{"text": "{-# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #-}\n\nmodule Numerical.HBLAS.BLAS.FFI.Level1  where\n\nimport Foreign.Ptr\nimport Foreign()\nimport Foreign.C.Types\nimport Data.Complex\n\ntype AsumFunFFI el res = CInt -> Ptr el -> CInt -> IO res\nforeign import ccall unsafe \"cblas_sasum\" cblas_sasum_unsafe::\n  AsumFunFFI Float Float\nforeign import ccall unsafe \"cblas_dasum\" cblas_dasum_unsafe::\n  AsumFunFFI Double Double\nforeign import ccall unsafe \"cblas_scasum\" cblas_scasum_unsafe::\n  AsumFunFFI (Complex Float) Float\nforeign import ccall unsafe \"cblas_dzasum\" cblas_dzasum_unsafe::\n  AsumFunFFI (Complex Double) Double\n\nforeign import ccall \"cblas_sasum\" cblas_sasum_safe::\n  AsumFunFFI Float Float\nforeign import ccall \"cblas_dasum\" cblas_dasum_safe ::\n  AsumFunFFI Double Double\nforeign import ccall \"cblas_scasum\" cblas_scasum_safe ::\n  AsumFunFFI (Complex Float) Float\nforeign import ccall \"cblas_dzasum\" cblas_dzasum_safe ::\n  AsumFunFFI (Complex Double) Double\n--Float  cblas_sasum (  CInt n,   Float  *x,   CInt incx);\n--Double cblas_dasum (  CInt n,   Double *x,   CInt incx);\n--Float  cblas_scasum(  CInt n,   Float  *x,   CInt incx);\n--Double cblas_dzasum(  CInt n,   Double *x,   CInt incx);\n\ntype AxpyFunFFI scale el = CInt -> scale -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_saxpy\" cblas_saxpy_unsafe::\n  AxpyFunFFI Float Float\nforeign import ccall unsafe \"cblas_daxpy\" cblas_daxpy_unsafe::\n  AxpyFunFFI Double Double\nforeign import ccall unsafe \"cblas_caxpy\" cblas_caxpy_unsafe::\n  AxpyFunFFI (Ptr (Complex Float )) (Complex Float )\nforeign import ccall unsafe \"cblas_zaxpy\" cblas_zaxpy_unsafe::\n  AxpyFunFFI (Ptr (Complex Double)) (Complex Double)\n\nforeign import ccall \"cblas_saxpy\" cblas_saxpy_safe::\n  AxpyFunFFI Float Float\nforeign import ccall \"cblas_daxpy\" cblas_daxpy_safe::\n  AxpyFunFFI Double Double\nforeign import ccall \"cblas_caxpy\" cblas_caxpy_safe::\n  AxpyFunFFI (Ptr (Complex Float )) (Complex Float )\nforeign import ccall \"cblas_zaxpy\" cblas_zaxpy_safe::\n  AxpyFunFFI (Ptr (Complex Double)) (Complex Double)\n--void cblas_saxpy(  CInt n,   Float alpha,   Float *x,   CInt incx, Float *y,   CInt incy);\n--void cblas_daxpy(  CInt n,   Double alpha,   Double *x,   CInt incx, Double *y,   CInt incy);\n--void cblas_caxpy(  CInt n,   Float *alpha,   Float *x,   CInt incx, Float *y,   CInt incy);\n--void cblas_zaxpy(  CInt n,   Double *alpha,   Double *x,   CInt incx, Double *y,   CInt incy);\n\ntype CopyFunFFI el = CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_scopy\" cblas_scopy_unsafe ::\n    CopyFunFFI Float\nforeign import ccall unsafe \"cblas_dcopy\" cblas_dcopy_unsafe ::\n    CopyFunFFI Double\nforeign import ccall unsafe \"cblas_ccopy\" cblas_ccopy_unsafe ::\n    CopyFunFFI (Complex Float)\nforeign import ccall unsafe \"cblas_zcopy\" cblas_zcopy_unsafe ::\n    CopyFunFFI (Complex Double)\n\nforeign import ccall \"cblas_scopy\" cblas_scopy_safe ::\n    CopyFunFFI Float\nforeign import ccall \"cblas_dcopy\" cblas_dcopy_safe ::\n    CopyFunFFI Double\nforeign import ccall \"cblas_ccopy\" cblas_ccopy_safe ::\n    CopyFunFFI (Complex Float)\nforeign import ccall \"cblas_zcopy\" cblas_zcopy_safe ::\n    CopyFunFFI (Complex Double)\n--void cblas_scopy(  CInt n,   Float *x,   CInt incx, Float *y,   CInt incy);\n--void cblas_dcopy(  CInt n,   Double *x,   CInt incx, Double *y,   CInt incy);\n--void cblas_ccopy(  CInt n,   Float *x,   CInt incx, Float *y,   CInt incy);\n--void cblas_zcopy(  CInt n,   Double *x,   CInt incx, Double *y,   CInt incy);\n\n--dot products\ntype NoScalarDotFunFFI el res = CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO res\n-- type ScalarDotFunFFI el res = CInt -> el -> Ptr el -> CInt -> Ptr el -> CInt -> IO res\ntype SdsdotFortranFunFFI el res = Ptr CInt -> Ptr el -> Ptr el -> Ptr CInt -> Ptr el -> Ptr CInt -> IO res\nforeign import ccall \"sdsdot_\" cblas_sdsdot_safe :: SdsdotFortranFunFFI Float Float\nforeign import ccall \"cblas_dsdot\" cblas_dsdot_safe :: NoScalarDotFunFFI Float Double\nforeign import ccall \"cblas_sdot\" cblas_sdot_safe :: NoScalarDotFunFFI Float Float\nforeign import ccall \"cblas_ddot\" cblas_ddot_safe :: NoScalarDotFunFFI Double Double\n\nforeign import ccall unsafe \"sdsdot_\" cblas_sdsdot_unsafe :: SdsdotFortranFunFFI Float Float\nforeign import ccall unsafe \"cblas_dsdot\" cblas_dsdot_unsafe :: NoScalarDotFunFFI Float Double\nforeign import ccall unsafe \"cblas_sdot\" cblas_sdot_unsafe :: NoScalarDotFunFFI Float Float\nforeign import ccall unsafe \"cblas_ddot\" cblas_ddot_unsafe :: NoScalarDotFunFFI Double Double\n--Float  cblas_sdsdot(  CInt n,   Float alpha,   Float *x,   CInt incx,   Float *y,   CInt incy);\n--Double cblas_dsdot (  CInt n,   Float *x,   CInt incx,   Float *y,   CInt incy);\n--Float  cblas_sdot(  CInt n,   Float  *x,   CInt incx,   Float  *y,   CInt incy);\n--Double cblas_ddot(  CInt n,   Double *x,   CInt incx,   Double *y,   CInt incy);\n\n--complex dot products that CONJUGATE end in C, others end in U\ntype ComplexDotFunFFI el = CInt -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> IO ()\nforeign import ccall \"cblas_cdotu_sub\" cblas_cdotu_safe :: ComplexDotFunFFI (Complex Float)\nforeign import ccall \"cblas_cdotc_sub\" cblas_cdotc_safe :: ComplexDotFunFFI (Complex Float)\nforeign import ccall \"cblas_zdotu_sub\" cblas_zdotu_safe :: ComplexDotFunFFI (Complex Double)\nforeign import ccall \"cblas_zdotc_sub\" cblas_zdotc_safe :: ComplexDotFunFFI (Complex Double)\n\nforeign import ccall unsafe \"cblas_cdotu_sub\" cblas_cdotu_unsafe :: ComplexDotFunFFI (Complex Float)\nforeign import ccall unsafe \"cblas_cdotc_sub\" cblas_cdotc_unsafe :: ComplexDotFunFFI (Complex Float)\nforeign import ccall unsafe \"cblas_zdotu_sub\" cblas_zdotu_unsafe :: ComplexDotFunFFI (Complex Double)\nforeign import ccall unsafe \"cblas_zdotc_sub\" cblas_zdotc_unsafe :: ComplexDotFunFFI (Complex Double)\n--void cblas_cdotu(CInt n, void *x, CInt incx, void *y, CInt incy, void *res);\n--void cblas_cdotc(CInt n, void *x, CInt incx, void *y, CInt incy, void *res);\n--void cblas_zdotu(CInt n, void *x, CInt incx, void *y, CInt incy, void *res);\n--void cblas_zdotc(CInt n, void *x, CInt incx, void *y, CInt incy, void *res);\n\n--Computes the Euclidean norm of a vector.\ntype Nrm2FunFFI el res = CInt -> Ptr el -> CInt -> IO res\nforeign import ccall \"cblas_snrm2\" cblas_snrm2_safe :: Nrm2FunFFI Float Float\nforeign import ccall \"cblas_dnrm2\" cblas_dnrm2_safe :: Nrm2FunFFI Double Double\nforeign import ccall \"cblas_scnrm2\" cblas_scnrm2_safe :: Nrm2FunFFI (Complex Float) Float\nforeign import ccall \"cblas_dznrm2\" cblas_dznrm2_safe :: Nrm2FunFFI (Complex Double) Double\n\nforeign import ccall unsafe \"cblas_snrm2\" cblas_snrm2_unsafe :: Nrm2FunFFI Float Float\nforeign import ccall unsafe \"cblas_dnrm2\" cblas_dnrm2_unsafe :: Nrm2FunFFI Double Double\nforeign import ccall unsafe \"cblas_scnrm2\" cblas_scnrm2_unsafe :: Nrm2FunFFI (Complex Float) Float\nforeign import ccall unsafe \"cblas_dznrm2\" cblas_dznrm2_unsafe :: Nrm2FunFFI (Complex Double) Double\n--Float  cblas_snrm2 (  CInt N,   Float  *X,   CInt incX);\n--Double cblas_dnrm2 (  CInt N,   Double *X,   CInt incX);\n--Float  cblas_scnrm2(  CInt N,   void  *X,   CInt incX);\n--Double cblas_dznrm2(  CInt N,   void  *X,   CInt incX);\n\n\n--Performs rotation of points in the plane.\ntype RotFunFFI el = CInt -> Ptr el -> CInt -> Ptr el -> CInt -> el -> el -> IO ()\nforeign import ccall \"cblas_srot\" cblas_srot_safe :: RotFunFFI Float\nforeign import ccall \"cblas_drot\" cblas_drot_safe :: RotFunFFI Double\n\nforeign import ccall unsafe \"cblas_srot\" cblas_srot_unsafe :: RotFunFFI Float\nforeign import ccall unsafe \"cblas_drot\" cblas_drot_unsafe :: RotFunFFI Double\n--void cblas_srot(  CInt N, Float *X,   CInt incX, Float *Y,   CInt incY,   Float c,   Float s);\n--void cblas_drot(  CInt N, Double *X,   CInt incX, Double *Y,   CInt incY,   Double c,   Double  s);\n\ntype RotgFunFFI el = Ptr el -> Ptr el -> Ptr el -> Ptr el -> IO ()\nforeign import ccall \"cblas_srotg\" cblas_srotg_safe :: RotgFunFFI Float\nforeign import ccall \"cblas_drotg\" cblas_drotg_safe :: RotgFunFFI Double\n\nforeign import ccall unsafe \"cblas_srotg\" cblas_srotg_unsafe :: RotgFunFFI Float\nforeign import ccall unsafe \"cblas_drotg\" cblas_drotg_unsafe :: RotgFunFFI Double\n--void cblas_srotg(Float *a, Float *b, Float *c, Float *s);\n--void cblas_drotg(Double *a, Double *b, Double *c, Double *s);\n\ntype RotmFunFFI el = CInt -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> IO ()\nforeign import ccall \"cblas_srotm\" cblas_srotm_safe :: RotmFunFFI Float\nforeign import ccall \"cblas_drotm\" cblas_drotm_safe :: RotmFunFFI Double\n\nforeign import ccall unsafe \"cblas_srotm\" cblas_srotm_unsafe :: RotmFunFFI Float\nforeign import ccall unsafe \"cblas_drotm\" cblas_drotm_unsafe :: RotmFunFFI Double\n--void cblas_srotm(  CInt N, Float *X,   CInt incX, Float *Y,   CInt incY,   Float *P);\n--void cblas_drotm(  CInt N, Double *X,   CInt incX, Double *Y,   CInt incY,   Double *P);\n\ntype RotmgFunFFI el = Ptr el -> Ptr el -> Ptr el -> el -> Ptr el -> IO ()\nforeign import ccall \"cblas_srotmg\" cblas_srotmg_safe :: RotmgFunFFI Float\nforeign import ccall \"cblas_drotmg\" cblas_drotmg_safe :: RotmgFunFFI Double\n\nforeign import ccall unsafe \"cblas_srotmg\" cblas_srotmg_unsafe :: RotmgFunFFI Float\nforeign import ccall unsafe \"cblas_drotmg\" cblas_drotmg_unsafe :: RotmgFunFFI Double\n--void cblas_srotmg(Float *d1, Float *d2, Float *b1,   Float b2, Float *P);\n--void cblas_drotmg(Double *d1, Double *d2, Double *b1,   Double b2, Double *P);\n\ntype ScalFunFFI scale el = CInt -> scale -> Ptr el -> CInt -> IO ()\nforeign import ccall \"cblas_sscal\" cblas_sscal_safe :: ScalFunFFI Float Float\nforeign import ccall \"cblas_dscal\" cblas_dscal_safe :: ScalFunFFI Double Double\nforeign import ccall \"cblas_cscal\" cblas_cscal_safe :: ScalFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall \"cblas_zscal\" cblas_zscal_safe :: ScalFunFFI (Ptr (Complex Double)) (Complex Double)\nforeign import ccall \"cblas_csscal\" cblas_csscal_safe :: ScalFunFFI Float (Complex Float)\nforeign import ccall \"cblas_zdscal\" cblas_zdscal_safe :: ScalFunFFI Double (Complex Double)\n\nforeign import ccall unsafe \"cblas_sscal\" cblas_sscal_unsafe :: ScalFunFFI Float Float\nforeign import ccall unsafe \"cblas_dscal\" cblas_dscal_unsafe :: ScalFunFFI Double Double\nforeign import ccall unsafe \"cblas_cscal\" cblas_cscal_unsafe :: ScalFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall unsafe \"cblas_zscal\" cblas_zscal_unsafe :: ScalFunFFI (Ptr (Complex Double)) (Complex Double)\nforeign import ccall unsafe \"cblas_csscal\" cblas_csscal_unsafe :: ScalFunFFI Float (Complex Float)\nforeign import ccall unsafe \"cblas_zdscal\" cblas_zdscal_unsafe :: ScalFunFFI Double (Complex Double)\n--void cblas_sscal(  CInt N,   Float alpha, Float *X,   CInt incX);\n--void cblas_dscal(  CInt N,   Double alpha, Double *X,   CInt incX);\n--void cblas_cscal(  CInt N,   Float *alpha, Float *X,   CInt incX);\n--void cblas_zscal(  CInt N,   Double *alpha, Double *X,   CInt incX);\n--void cblas_csscal(  CInt N,   Float alpha, Float *X,   CInt incX);\n--void cblas_zdscal(  CInt N,   Double alpha, Double *X,   CInt incX);\n\ntype SwapFunFFI el = CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall \"cblas_sswap\" cblas_sswap_safe :: SwapFunFFI Float\nforeign import ccall \"cblas_dswap\" cblas_dswap_safe :: SwapFunFFI Double\nforeign import ccall \"cblas_cswap\" cblas_cswap_safe :: SwapFunFFI (Complex Float)\nforeign import ccall \"cblas_zswap\" cblas_zswap_safe :: SwapFunFFI (Complex Double)\n\nforeign import ccall unsafe \"cblas_sswap\" cblas_sswap_unsafe :: SwapFunFFI Float\nforeign import ccall unsafe \"cblas_dswap\" cblas_dswap_unsafe :: SwapFunFFI Double\nforeign import ccall unsafe \"cblas_cswap\" cblas_cswap_unsafe :: SwapFunFFI (Complex Float)\nforeign import ccall unsafe \"cblas_zswap\" cblas_zswap_unsafe :: SwapFunFFI (Complex Double)\n--void cblas_sswap(  CInt n, Float *x,   CInt incx, Float *y,   CInt incy);\n--void cblas_dswap(  CInt n, Double *x,   CInt incx, Double *y,   CInt incy);\n--void cblas_cswap(  CInt n, Float *x,   CInt incx, Float *y,   CInt incy);\n--void cblas_zswap(  CInt n, Double *x,   CInt incx, Double *y,   CInt incy);\n\ntype IamaxFunFFI el = CInt -> Ptr el -> CInt -> IO CInt\nforeign import ccall \"cblas_isamax\" cblas_isamax_safe :: IamaxFunFFI Float\nforeign import ccall \"cblas_idamax\" cblas_idamax_safe :: IamaxFunFFI Double\nforeign import ccall \"cblas_icamax\" cblas_icamax_safe :: IamaxFunFFI (Complex Float)\nforeign import ccall \"cblas_izamax\" cblas_izamax_safe :: IamaxFunFFI (Complex Double)\n\nforeign import ccall unsafe \"cblas_isamax\" cblas_isamax_unsafe :: IamaxFunFFI Float\nforeign import ccall unsafe \"cblas_idamax\" cblas_idamax_unsafe :: IamaxFunFFI Double\nforeign import ccall unsafe \"cblas_icamax\" cblas_icamax_unsafe :: IamaxFunFFI (Complex Float)\nforeign import ccall unsafe \"cblas_izamax\" cblas_izamax_unsafe :: IamaxFunFFI (Complex Double)\n--CBLAS_INDEX cblas_isamax(  CInt n,   Float  *x,   CInt incx);\n--CBLAS_INDEX cblas_idamax(  CInt n,   Double *x,   CInt incx);\n--CBLAS_INDEX cblas_icamax(  CInt n,   Float  *x,   CInt incx);\n--CBLAS_INDEX cblas_izamax(  CInt n,   Double *x,   CInt incx);\n\n\n\n{-\nthese aren't provided by Accelerate frameowkr on OSX, not sure about other platforms\n\nbut easy to write portable substitute I think?\n-}\n--type IaminFunFFI el = CInt -> Ptr el -> CInt -> IO CInt\n--foreign import ccall \"cblas_isamin\" cblas_isamin_safe :: IaminFunFFI Float\n--foreign import ccall \"cblas_idamin\" cblas_idamin_safe :: IaminFunFFI Double\n--foreign import ccall \"cblas_icamin\" cblas_icamin_safe :: IaminFunFFI (Complex Float)\n--foreign import ccall \"cblas_izamin\" cblas_izamin_safe :: IaminFunFFI (Complex Double)\n\n--foreign import ccall unsafe \"cblas_isamin\" cblas_isamin_unsafe :: IaminFunFFI Float\n--foreign import ccall unsafe \"cblas_idamin\" cblas_idamin_unsafe :: IaminFunFFI Double\n--foreign import ccall unsafe \"cblas_icamin\" cblas_icamin_unsafe :: IaminFunFFI (Complex Float)\n--foreign import ccall unsafe \"cblas_izamin\" cblas_izamin_unsafe :: IaminFunFFI (Complex Double)\n\n--CBLAS_INDEX cblas_isamin(  CInt n,   Float  *x,   CInt incx);\n--CBLAS_INDEX cblas_idamin(  CInt n,   Double *x,   CInt incx);\n--CBLAS_INDEX cblas_icamin(  CInt n,   Float  *x,   CInt incx);\n--CBLAS_INDEX cblas_izamin(  CInt n,   Double *x,   CInt incx);\n", "meta": {"hexsha": "25fd1370f1926a01058dcb3d9fc67c0dd42b7b38", "size": 14278, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level1.hs", "max_stars_repo_name": "schnecki/hblas", "max_stars_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T22:58:54.000Z", "max_issues_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level1.hs", "max_issues_repo_name": "schnecki/hblas", "max_issues_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-01-24T13:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T22:15:09.000Z", "max_forks_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level1.hs", "max_forks_repo_name": "schnecki/hblas", "max_forks_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:37:37.000Z", "avg_line_length": 59.4916666667, "max_line_length": 114, "alphanum_fraction": 0.7531867208, "num_tokens": 4780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.41131077827923357}}
{"text": "{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\nmodule HVX.BlackBoxTests.ManyvarTestSpec where\n\nimport Test.Hspec\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Util (ones, zeros)\n\nimport HVX\nimport HVX.Internal.TestUtil\n\n-- Problem definition.\nnx = 2\nny = 3\nnz = 4\na = EConst $ (3><nx)\n    ([-0.1022 , 0.3129\n    , -0.2414 , -0.8649\n    , 0.3192 , -0.0301 ] :: [Double])\nb = EConst $ (3><ny)\n    ([-0.1649 , 1.1093 , -1.2141\n    , 0.6277 , -0.8637 , -1.1135\n    , 1.0933 , 0.0774 , -0.0068 ] :: [Double])\nc = EConst $ (3><nz)\n    ([1.5326 , -0.2256 , 0.0326 , 1.5442\n    , -0.7697 , 1.1174 , 0.5525 , 0.0859\n    , 0.3714 , -1.0891 , 1.1006 , -1.4916 ] :: [Double])\nd = EConst $ (3><1)\n    ([-0.6156 , 0.7481 , -0.1924] :: [Double])\n\nx = EVar \"x\"\ny = EVar \"y\"\nz = EVar \"z\"\nconst10nx = EConst $ scale 10 $ ones nx 1\nconst10ny = EConst $ scale 10 $ ones ny 1\nconst01nz = EConst $ scale 0.1 $ ones nz 1\n\nsubgradAns = subgradMaximize\n  ( neg (norm 2 (a *~ x +~ b *~ y +~ c *~ z +~ d))\n    +~ neg (norm 1 x)\n    +~ neg (norm 4.2 y) )\n  [ const01nz >=~ hexp z\n    , powBaseP01 0.25 x >=~ const10nx\n    , powBaseP1InfNotInt 1.75 y <=~ const10ny ]\n  (decNonSumStep 100.0) 10\n  [(\"x\", zeros nx 1), (\"y\", zeros ny 1), (\"z\", zeros nz 1)]\n\nellipsoidAns = ellipsoidMaximize\n  ( neg (norm 2 (a *~ x +~ b *~ y +~ c *~ z +~ d))\n    +~ neg (norm 1 x)\n    +~ neg (norm 4.2 y) )\n  [ const01nz >=~ hexp z\n    , powBaseP01 0.25 x >=~ const10nx\n    , powBaseP1InfNotInt 1.75 y <=~ const10ny ]\n  [(\"x\", nx), (\"y\", ny), (\"z\", nz)]\n  1e-16 1e10\n\n(subgradVars, subgradOptval) = subgradAns\n\n(ellipsoidVars, ellipsoidOptval, ellipsoidUBound) = ellipsoidAns\n\n-- CVX's results.\ncvxOptval = -29051\n\n-- Verify that HVX matches CVX.\n-- TODO(mh): This test fails because primitives that generate implicit\n-- constraints are currently unsupported. When support is added for them, the\n-- test will be added back in. (2014-06-04)\nspec :: Spec\nspec =\n  describe \"Placeholder test\" $ do\n    it \"placeholder description\" $\n      True `shouldBe` True\n--  describe \"Verify that HVX matches CVX for triple variable stress test\" $ do\n--    it \"Verify that HVX subgrad matches CVX for huber/berhu\" $\n--      subgradOptval `shouldSatisfy` fpequalsApprox cvxOptval\n--    it \"Verify that HVX ellipsoid matches CVX for huber/berhu\" $\n--      ellipsoidOptval `shouldSatisfy` fpequalsApprox cvxOptval\n--\n--main :: IO ()\n--main = hspec spec\n", "meta": {"hexsha": "7d91ed352249954a637616608644bcf6c19248e6", "size": 2402, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/HVX/BlackBoxTests/ManyvarTestSpec.hs", "max_stars_repo_name": "wellposed/hvx", "max_stars_repo_head_hexsha": "4cc39c1ff940960e8ff7d50e368c76031786befe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/HVX/BlackBoxTests/ManyvarTestSpec.hs", "max_issues_repo_name": "wellposed/hvx", "max_issues_repo_head_hexsha": "4cc39c1ff940960e8ff7d50e368c76031786befe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/HVX/BlackBoxTests/ManyvarTestSpec.hs", "max_forks_repo_name": "wellposed/hvx", "max_forks_repo_head_hexsha": "4cc39c1ff940960e8ff7d50e368c76031786befe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:49:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:38:03.000Z", "avg_line_length": 29.2926829268, "max_line_length": 79, "alphanum_fraction": 0.6194837635, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4112872797488411}}
{"text": "module Data.Csv.HMatrix\n    (\n      -- * Usage example\n      -- $example\n\n      -- * Information\n      -- $info\n\n      decodeMatrix\n    , decodeMatrixWith\n    , encodeMatrix\n    , encodeMatrixWith\n    ) where\n\nimport Data.Csv\nimport Numeric.LinearAlgebra.HMatrix\nimport qualified Data.Vector as V\nimport Data.ByteString.Lazy (ByteString)\nimport qualified Data.ByteString.Char8 as C\nimport Data.Char (ord)\n\n-- $example\n--\n-- For decoding we have to specify, if there is a header. This can be done with the HasHeader/NoHeader type:\n--\n-- > >>> decodeMatrix NoHeader \"1.0,2.0,3.0\\r\\n4.0,5.0,6.0\\r\\n7.0,8.0,9.0\\r\\n\"\n-- > (3><3)\n-- > [ 1.0, 2.0, 3.0\n-- > , 4.0, 5.0, 6.0\n-- > , 7.0, 8.0, 9.0 ]\n--\n-- Cassava, which is used for parsing the .csv files uses overloaded string literals. If you try this in ghci, make sure to start it with the right flag:\n--\n-- > >>> ghci -XOverloadedStrings\n--\n-- Encoding a file works pretty much the same, except that we do not need to specify a header.\n--\n-- > >>> encodeMatrix $ matrix 3 [1,2,3,4,5,6,7,8,9]\n-- > \"1.0,2.0,3.0\\r\\n4.0,5.0,6.0\\r\\n7.0,8.0,9.0\\r\\n\"\n\n-- $info\n-- If you want to help improve this library, feel free to file an issue or send a pull-request on github. Every feedback is appreciated.\n-- As of now only matrices of type Double are supported.\n\n-- | Decodes a matrix.\ndecodeMatrix :: HasHeader       -- ^ From Data.Csv: specify if the CSV string has a header\n             -> ByteString      -- ^ The 'ByteString' containing the CSVs\n             -> Matrix Double   -- ^ The parsed 'Matrix'\ndecodeMatrix header = decodeMatrixWith header ','\n\n-- | Decodes a matrix from ByteString and additionally allow\n-- to specify the delimter which was used.\ndecodeMatrixWith :: HasHeader       -- ^ From Data.Csv: specify if the CSV string has a header\n                 -> Char            -- ^ The delimiter\n                 -> ByteString      -- ^ The 'ByteString' containing the CSVs\n                 -> Matrix Double   -- ^ The parsed 'Matrix'\ndecodeMatrixWith header del s =\n    case decodeWith opt header s of\n        Left err -> error err\n        Right v  -> fromLists . V.toList . V.map V.toList $ v\n    where opt = defaultDecodeOptions { decDelimiter = fromIntegral (ord del) }\n\nrowToRecord :: [Double] -> Record\nrowToRecord x = record $ map (C.pack . show) x\n\n-- | Encodes a matrix with comma as delimiter.\nencodeMatrix :: Matrix Double   -- ^ The 'Matrix' to encode\n             -> ByteString      -- ^ The resulting 'ByteString'\nencodeMatrix = encodeMatrixWith ','\n\n-- | Encodes a matrix but allows to specify a delimiter.\nencodeMatrixWith :: Char            -- ^ The delimiter for separating the values\n                 -> Matrix Double   -- ^ The 'Matrix' to encode\n                 -> ByteString      -- ^ The resulting 'ByteString'\nencodeMatrixWith del m = encodeWith opt s\n    where opt = defaultEncodeOptions { encDelimiter = fromIntegral (ord del) }\n          s = map rowToRecord $ toLists m\n", "meta": {"hexsha": "1e24e4ba869935e75db2b23580d201344919f4b6", "size": 2947, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Csv/HMatrix.hs", "max_stars_repo_name": "grtlr/hmatrix-csv", "max_stars_repo_head_hexsha": "780255e85d9592657aa17aca3b335d18b1454a29", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-23T03:01:30.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-23T03:01:30.000Z", "max_issues_repo_path": "Data/Csv/HMatrix.hs", "max_issues_repo_name": "grtlr/hmatrix-csv", "max_issues_repo_head_hexsha": "780255e85d9592657aa17aca3b335d18b1454a29", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data/Csv/HMatrix.hs", "max_forks_repo_name": "grtlr/hmatrix-csv", "max_forks_repo_head_hexsha": "780255e85d9592657aa17aca3b335d18b1454a29", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7820512821, "max_line_length": 153, "alphanum_fraction": 0.6386155412, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.41105147292437877}}
{"text": "module Foreign.Storable.OrphansSpec (main, spec) where\n\nimport Test.Hspec\nimport Data.Complex\nimport Data.Orphans ()\nimport Data.Ratio\nimport Foreign.Storable\n\nmain :: IO ()\nmain = hspec spec\n\nspec :: Spec\nspec = do\n  describe \"Storable Complex instance\" $ do\n    it \"has twice the sizeOf its realPart\" $ do\n      sizeOf (undefined :: Complex Double) `shouldBe` 2*sizeOf (1 :: Double)\n    it \"has the alignment of its realPart\" $ do\n      alignment (undefined :: Complex Double) `shouldBe` alignment (1 :: Double)\n\n  describe \"Storable Ratio instance\" $ do\n    it \"has twice the sizeOf its parameterized type\" $ do\n      sizeOf (undefined :: Ratio Int) `shouldBe` 2*sizeOf (1 :: Int)\n    it \"has the alignment of its parameterized type\" $ do\n      alignment (undefined :: Ratio Int) `shouldBe` alignment (1 :: Int)\n", "meta": {"hexsha": "3914986aea2694d4f2fab3b220547142adec8766", "size": 815, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Foreign/Storable/OrphansSpec.hs", "max_stars_repo_name": "haskell-compat/base-orphans", "max_stars_repo_head_hexsha": "1af3a3512efbcc12e0c34637a0e433ab6e195932", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-04-22T12:11:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T17:02:28.000Z", "max_issues_repo_path": "test/Foreign/Storable/OrphansSpec.hs", "max_issues_repo_name": "haskell-compat/base-orphans", "max_issues_repo_head_hexsha": "1af3a3512efbcc12e0c34637a0e433ab6e195932", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 51, "max_issues_repo_issues_event_min_datetime": "2015-04-17T15:16:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-30T08:32:29.000Z", "max_forks_repo_path": "test/Foreign/Storable/OrphansSpec.hs", "max_forks_repo_name": "haskell-compat/base-orphans", "max_forks_repo_head_hexsha": "1af3a3512efbcc12e0c34637a0e433ab6e195932", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-06-26T02:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T22:19:47.000Z", "avg_line_length": 32.6, "max_line_length": 80, "alphanum_fraction": 0.6957055215, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.410391235672575}}
{"text": "{-# LANGUAGE BangPatterns #-} \nmodule IllusoryContourShape where\n\nimport           Control.Monad               as M\nimport           Data.Array.Repa             as R\nimport           Data.Binary\nimport           Data.Complex\nimport           Data.List                   as L\nimport           Data.Vector.Generic         as VG\nimport           FokkerPlanck\nimport           Image.IO\nimport           STC\nimport           System.Directory\nimport           System.Environment\nimport           System.FilePath\nimport           Text.Printf\nimport           Utils.Array\nimport           Utils.Time\nimport qualified Data.Array.IArray as IA\nimport           FokkerPlanck.GreensFunction\n\nmain = do\n  args@(gpuIDStr:numPointStr:deltaXStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:maxScaleStr:cutoffStr:deltaLogStr:taoStr:numTrailStr:maxTrailStr:phiFreqsStr:rhoFreqsStr:thetaFreqsStr:scaleFreqsStr:initScaleStr:shape2DStr:histFilePath:writeFlagStr:numIterationStr:suffix:stdStr:stdGStr:numThreadStr:_) <-\n    getArgs\n  let gpuID = read gpuIDStr :: [Int]\n      numPoint = read numPointStr :: Int\n      deltaX = read deltaXStr :: Double\n      numOrientation = read numOrientationStr :: Int\n      numScale = read numScaleStr :: Int\n      thetaSigma = read thetaSigmaStr :: Double\n      scaleSigma = read scaleSigmaStr :: Double\n      tao = read taoStr :: Double\n      numTrail = read numTrailStr :: Int\n      maxTrail = read maxTrailStr :: Int\n      phiFreq = read phiFreqsStr :: Double\n      phiFreqs = [-phiFreq .. phiFreq]\n      rhoFreq = read rhoFreqsStr :: Double\n      rhoFreqs = [-rhoFreq .. rhoFreq]\n      thetaFreq = read thetaFreqsStr :: Double\n      thetaFreqs = [-thetaFreq .. thetaFreq]\n      scaleFreq = read scaleFreqsStr :: Double\n      scaleFreqs = [-scaleFreq .. scaleFreq]\n      initScale = read initScaleStr :: Double\n      shape2D@(Points _ minDist _) = read shape2DStr :: Points Shape2D\n      numThread = read numThreadStr :: Int\n      folderPath =\n        \"output/test/IllusoryContourShape\" </> (takeBaseName histFilePath) L.++\n        \"_\" L.++\n        cutoffStr L.++\n        \"_\" L.++\n        deltaXStr\n      maxScale = read maxScaleStr :: Double\n      cutoff = read cutoffStr :: Double\n      halfLogPeriod = log maxScale\n      deltaLog = read deltaLogStr :: Double\n      writeFlag = read writeFlagStr :: Bool\n      std = read stdStr :: Double\n      stdG = read stdGStr :: Double\n      numIteration = read numIterationStr :: Int\n  print thetaFreqs\n  createDirectoryIfMissing True folderPath\n  flag <- doesFileExist histFilePath\n  hist <-\n    if flag\n      then do\n        printCurrentTime $\n          \"read Fourier coefficients data from \" L.++ histFilePath\n        decodeFile histFilePath\n      -- else runMonteCarloFourierCoefficientsGPU\n      --        gpuID\n      --        numThread\n      --        numTrail\n      --        maxTrail\n      --        thetaSigma\n      --        scaleSigma\n      --        maxScale\n      --        tao\n      --        phiFreqs\n      --        rhoFreqs\n      --        thetaFreqs\n      --        scaleFreqs\n      --        deltaLog\n      --        initScale\n      --        histFilePath\n      --        (emptyHistogram\n      --           [ L.length phiFreqs\n      --           , L.length rhoFreqs\n      --           , L.length thetaFreqs\n      --           , L.length scaleFreqs\n      --           ]\n      --           0)\n      else sampleCartesian\n             folderPath\n             histFilePath\n             gpuID\n             numPoint\n             numPoint\n             180\n             deltaX\n             deltaLog\n             initScale\n             thetaSigma\n             tao\n             phiFreqs\n             rhoFreqs\n             thetaFreqs\n             scaleFreqs\n  let !points =\n        L.map (\\(!x, !y) -> Point x y 0 1) . getShape2DIndexList . makeShape2D $\n        shape2D\n      -- !xs = L.map (\\(a, b) -> (a * deltaX, b * deltaX)) . makeShape2D $ shape2D\n      !xs = getShape2DIndexList . makeShape2D $ shape2D\n      !coefficients =\n        normalizeFreqArr std phiFreqs rhoFreqs . getNormalizedHistogramArr $\n        hist\n       -- = getNormalizedHistogramArr $ hist :: R.Array U DIM4 (Complex Double)\n      !thetaRHarmonics =\n        computeThetaRHarmonics\n          numOrientation\n          numScale\n          thetaFreqs\n          scaleFreqs\n          halfLogPeriod\n  print xs\n  plan <-\n    makePlan\n      folderPath\n      emptyPlan\n      numPoint\n      numPoint\n      (L.length thetaFreqs)\n      (L.length scaleFreqs)\n  let !initSourceSparse =\n        computeInitialDistributionPowerMethodSparse phiFreqs rhoFreqs points\n      !harmonicsArraySparse =\n        computeHarmonicsArraySparse\n          numPoint\n          deltaX\n          numPoint\n          deltaX\n          phiFreqs\n          rhoFreqs\n          thetaFreqs\n          scaleFreqs\n          halfLogPeriod\n          cutoff\n  -- let !initSource =\n  --       computeInitialDistributionPowerMethod'\n  --         numPoint\n  --         numPoint\n  --         phiFreqs\n  --         rhoFreqs\n  --         -- thetaFreqs\n  --         -- scaleFreqs\n  --         points\n  --     !bias = computeBias numPoint numPoint points\n  gaussian <- gaussianFilter2D plan numPoint stdG\n  -- harmonicsArray <-\n  --   dftHarmonicsArrayG\n  --     plan\n  --     numPoint\n  --     deltaX\n  --     numPoint\n  --     deltaX\n  --     phiFreqs\n  --     rhoFreqs\n  --     thetaFreqs\n  --     scaleFreqs\n  --     halfLogPeriod\n  --     cutoff\n  --     gaussian\n  -- print . IA.indices $ harmonicsArraySparse\n  -- completion <-\n  computeContourSparse\n    plan\n    folderPath\n    coefficients\n    harmonicsArraySparse\n    -- thetaRHarmonics\n    (fromListUnboxed (Z :. L.length phiFreqs) phiFreqs)\n    (fromListUnboxed (Z :. L.length rhoFreqs) rhoFreqs)\n    cutoff\n    -- gaussian\n                      -- std\n    xs\n    numIteration\n    suffix\n    initSourceSparse\n  -- completion <-\n  --   computeContour'\n  --    plan\n  --    folderPath\n  --    writeFlag\n  --    coefficients\n  --    harmonicsArray\n  --    bias\n  --    -- gaussian\n  --    numIteration\n  --    suffix\n  --    thetaRHarmonics\n  --    initSource\n  -- plotDFTArrayThetaR\n  --   (folderPath </> (printf \"Completion_%s.png\" suffix))\n  --   numPoint\n  --   numPoint\n  --   thetaRHarmonics\n  --   completion\n  -- plotDFTArrayThetaRMag\n  --   (folderPath </> (printf \"CompletionMax_%s.png\" suffix))\n  --   numPoint\n  --   numPoint\n  --   thetaRHarmonics\n  --   completion\n  -- computeContourSparse'''\n  --   plan\n  --   folderPath\n  --   coefficients\n  --   harmonicsArraySparse\n  --   thetaRHarmonics\n  --   (fromListUnboxed (Z :. L.length phiFreqs) phiFreqs)\n  --   (fromListUnboxed (Z :. L.length rhoFreqs) rhoFreqs)\n  --   cutoff\n  --   xs\n  --   numIteration\n  --   (suffix L.++ \"Test\")\n  --   initSourceSparse\n", "meta": {"hexsha": "17b8c88fcb96a5e32cc03806b04c6eabaa3d9ec0", "size": 6778, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/IllusoryContourShape/IllusoryContourShape.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/IllusoryContourShape/IllusoryContourShape.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/IllusoryContourShape/IllusoryContourShape.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 29.859030837, "max_line_length": 320, "alphanum_fraction": 0.5771614045, "num_tokens": 1815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749421, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.41034612052432795}}
{"text": "module SimpleParser.SimpleParser where\n\nimport System.IO\nimport Text.Parsec hiding ( spaces )\nimport Text.Parsec.String\nimport Control.Monad\nimport Numeric\nimport Data.Complex -- for complex number representation in 2.7\nimport Data.Ratio -- for rational numbers\nimport Data.Array -- could use haskell vectors instead, harder implementation\nimport Data.IORef\nimport Control.Monad.Error --deprecated but following the book :/\n\nspaces :: Parser ()\nspaces = skipMany1 space\n\ntype IOThrowsError = ErrorT LispError IO\n\ndata LispVal = Atom String\n               | List [LispVal]\n               | DottedList [LispVal] LispVal\n               | Number Integer\n               | String String\n               | Bool Bool\n               | Character Char\n               | Float Double\n               | Complex (Complex Double)\n               | Rational Rational\n               | Vector (Array Int LispVal)\n               | PrimitiveFunc ([LispVal] -> ThrowsError LispVal)\n               | Func { params :: [String], vararg :: Maybe String\n                      , body :: [LispVal], closure :: Env}\n               | IOFunc ([LispVal] -> IOThrowsError LispVal)\n               | Port Handle\n\ndata LispError = NumArgs Integer [LispVal]\n               | TypeMismatch String LispVal\n               | Parser ParseError\n               | BadSpecialForm String LispVal\n               | NotFunction String String\n               | UnboundVar String String\n               | Default String\n\nshowError :: LispError -> String\nshowError (NumArgs expected found) = \"Expected: \" ++ show expected ++\n  \" args but found: \" ++ unwordsList found\nshowError (TypeMismatch expected found) = \"Type mismatch; Got: \" ++\n  show found ++ \" but Expected: \" ++ expected\nshowError (Parser error) = \"Parse error at: \" ++ show error\nshowError (UnboundVar message var) = message ++ \" : \" ++ show var\nshowError (BadSpecialForm message val) = message ++ \" : \" ++ show val \nshowError (NotFunction message func) = message ++ \" : \" ++ show func\n\ninstance Show LispError where show = showError\ntype ThrowsError = Either LispError\ntype Env = IORef [(String, IORef LispVal)]\n\nparseAtom :: Parser LispVal\nparseAtom =\n  do\n    first <- letter <|> symbol -- <|> is parsec choice operator\n    rest <- many (letter <|> digit <|> symbol)\n    let atom = first:rest\n    return $ case atom of\n      \"#t\" -> Bool True\n      \"#f\" -> Bool False\n      _    -> Atom atom\n\n--------------------------- Exercise 2.1 ----------------------------------------\nparseNumber' :: Parser LispVal\nparseNumber' =\n  do\n    s <- many1 digit\n    return (Number . read $ s)\n\n--------------------------- Exercise 2.2 ----------------------------------------\nparseNumber'' :: Parser LispVal\nparseNumber'' = many1 digit >>= return . Number. read\n\n--------------------------- Exercise 2.3 ----------------------------------------\nspecials :: Parser Char\nspecials = do char '\\\\'\n              x <- oneOf \"\\\\\\\"nrt\"\n              return $ case x of\n                '\\\\' -> x\n                '\"'  -> x\n                'n'  -> '\\n'\n                'r'  -> '\\r'\n                't'  -> '\\t'\n\nparseString :: Parser LispVal\nparseString = do char '\"'\n                 x <- many $ specials <|> noneOf \"\\\"\\\\\"\n                 char '\"'\n                 return $ String x\n--------------------------- Exercise 2.4 ----------------------------------------\n--Scheme defines Octal as #o, decimal as #d, hex as #h\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\n-- so we can no longer parse bools with a prefixed '#'\nparseBool :: Parser LispVal\nparseBool =\n  do\n    char '#' --match a #\n    (char 't' >> return (Bool True)) <|> (char 'f' >> return (Bool False))\n\nparseNumber :: Parser LispVal\nparseNumber = parseDecimal\n  <|> parseSchemeDecimal\n  <|> parseHex\n  <|> parseOct\n  <|> parseBin\n\nparseDecimal :: Parser LispVal\nparseDecimal = many1 digit >>= return . Number . read\n\nparseSchemeDecimal:: Parser LispVal\nparseSchemeDecimal = do try $ string \"#d\"\n                        x <- many1 digit\n                        (return . Number . read) x\n\nparseHex :: Parser LispVal\nparseHex = do try $ string \"#x\"\n              x <- many1 hexDigit\n              return $ Number (hex2dig x)\n\nparseOct :: Parser LispVal\nparseOct = do try $ string \"#o\"\n              x <- many1 octDigit\n              return $ Number (oct2dig x)\n\nparseBin :: Parser LispVal\nparseBin = do try $ string \"#b\"\n              x <- many1 (oneOf \"10\")\n              return $ Number (bin2dig x)\n\nnumToList :: Int -> [Int]\nnumToList = map (read . (:[])) . show --probably slow, could use div and mod\n\noct2dig x = fst $ readOct x !! 0\nhex2dig x = fst $ readHex x !! 0\nbin2dig  = bin2dig' 0\nbin2dig' digint \"\" = digint\nbin2dig' digint (x:xs) = let old = 2 * digint + (if x == '0' then 0 else 1) in\n                         bin2dig' old xs\n--------------------------- Exercise 2.5 ----------------------------------------\nparseCharacter :: Parser LispVal\n--parseChar\n             --try to parse a whole match on newline or space\n             --or try to match any character not followed by an alpha numeric\n             --return thst as a list\n             -- now try to match newline or space return the corresponding value\n             --if not a match then return the first character match by previous\n             -- do\nparseCharacter =\n  do\n    try $ string \"#\\\\\"\n    x <- try (string \"newline\" <|> string \"space\")\n         <|> do {str <- anyChar; notFollowedBy alphaNum; return [str]}\n    return . Character $ case x of\n      \"newline\" -> '\\n'\n      \"space\" -> ' '\n      otherwise -> (x !! 0) --use of unsafe head\n\n--------------------------- Exercise 2.6 ----------------------------------------\n-- I keep struggling to find the appropriate informatin to match on in the\n-- R5RS, I thought I had to implement exact/nonexact in addition to this...\nparseFloat :: Parser LispVal\nparseFloat =\n  do\n    x <- many1 digit --many  digits before a '.'\n    char '.' -- match on the ','\n    y <- many1 digit --more digitts after\n    return $ Float . fst . head . readFloat $ (x ++ y) -- readFloat is a zipper\n\n--------------------------- Exercise 2.7 ----------------------------------------\ntoDouble :: LispVal -> Double\ntoDouble (Float f) = realToFrac f\ntoDouble (Number n) = fromInteger n\n\nparseComplexNumbers :: Parser LispVal\nparseComplexNumbers =\n  do\n    a <- parseFloat <|> parseNumber\n    char '+' --complex nums have pattern a+bi\n    b <- parseFloat <|> parseNumber\n    char 'i'\n    return (Complex (toDouble a :+ toDouble b))\n\nparseRationalNumbers :: Parser LispVal\nparseRationalNumbers =\n  do\n    a <- many1 digit-- a rational num is denoted by a / b /= 0\n    char '/'\n    b <- many1 digit\n    return (Rational ((read a) % (read b))) --didn't know that (%) existed\n\n------------------------Begin section on recursive parsers-----------------------\nparseList :: Parser LispVal\n--sepBy parseExpr spaces seperates a string by spaces on parseExpr criteria\nparseList = liftM List $ sepBy parseExpr spaces \n\nparseDottedList :: Parser LispVal\nparseDottedList =\n  do\n    head <- endBy parseExpr spaces\n    tail <- char '.' >> spaces >> parseExpr\n    return $ DottedList head tail\n\nparseQuoted :: Parser LispVal\nparseQuoted =\n  do\n    char '\\''\n    x <- parseExpr\n    return $ List [Atom \"quote\", x]\n\nparseExpr :: Parser LispVal\nparseExpr = parseAtom\n  <|> parseString\n  <|> try parseBool\n  <|> try parseComplexNumbers\n  <|> try parseRationalNumbers\n  <|> parseNumber --try's are required because these start with a '#'\n  <|> parseCharacter\n  <|> parseQuasiQuoted\n  <|> parseUnQuote\n  <|> parseQuoted\n  <|> try parseVector'\n  <|> do char '(' --first bracker\n         x <- try parseList <|> parseDottedList\n         char ')'\n         return x\n--------------------------- Exercise 4.1 ----------------------------------------\nparseQuasiQuoted :: Parser LispVal\nparseQuasiQuoted =\n  do\n    char '`'\n    x <- parseExpr\n    return $ List [Atom \"quasiquote\", x]\n\nparseUnQuote :: Parser LispVal\nparseUnQuote =\n  do\n    char ','\n    x <- parseExpr\n    return $ List [Atom \"unquote\", x]\n\n--------------------------- Exercise 4.2 ----------------------------------------\nparseVector :: Parser LispVal\nparseVector =\n  do\n    values <- sepBy parseExpr spaces\n    return $ Vector (listArray (0, (length values) - 1) values)\n\nparseVector' :: Parser LispVal\nparseVector' =\n  do string \"#(\"\n     vector <- parseVector\n     char ')'\n     return vector\n\n--------------------------- Exercise 4.3 ----------------------------------------\n     --skip\n\nshowVal :: LispVal -> String\nshowVal (String contents) = \"\\\"\" ++ contents ++ \"\\\"\"\nshowVal (Atom name) = name\nshowVal (Number contents) = show contents\nshowVal (Float num) = show num\nshowVal (Complex num) = show num\nshowVal (Rational num) = show num\nshowVal (Vector arr) = unlines . map showVal . elems $ arr\nshowVal (Bool True) = \"#t\"\nshowVal (Bool False) = \"#f\"\nshowVal (List values) = \"(\" ++ unwordsList values ++ \")\"\nshowVal (DottedList h t) = \"(\" ++ unwordsList h ++ \" . \" ++ showVal t\n  ++ \")\"\nshowVal (Character c) = [c]\nshowVal (PrimitiveFunc _) = \"primitive\"\nshowVal (Func {params = args, vararg = varargs, body = body, closure = env}) =\n  \"(lambda (\" ++ unwords (map show args) ++\n  (case varargs of\n      Nothing -> \"\"\n      Just arg -> \" . \" ++ arg) ++ \") ...)\"\nshowVal (Port _) = \"<IO port>\"\nshowVal (IOFunc _) = \"<IO primitive>\"\n\nunwordsList :: [LispVal] -> String\nunwordsList = unwords . map showVal\n\ninstance Show LispVal where show = showVal\n", "meta": {"hexsha": "1fe62d81dddd9de63c175da2e6380a4b3626dbc1", "size": 9446, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/simpleParser/simpleParser.hs", "max_stars_repo_name": "doyougnu/myLittleScheme", "max_stars_repo_head_hexsha": "8d89ed4745bdebcd9eab2de71fe250943a813f40", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simpleParser/simpleParser.hs", "max_issues_repo_name": "doyougnu/myLittleScheme", "max_issues_repo_head_hexsha": "8d89ed4745bdebcd9eab2de71fe250943a813f40", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simpleParser/simpleParser.hs", "max_forks_repo_name": "doyougnu/myLittleScheme", "max_forks_repo_head_hexsha": "8d89ed4745bdebcd9eab2de71fe250943a813f40", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2389078498, "max_line_length": 81, "alphanum_fraction": 0.5635189498, "num_tokens": 2368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4102067456515661}}
{"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict, StrictData #-}\n{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}\n\n------------------------------------------------\n-- |\n-- Module    :  ArcGraph.EnhancedState\n-- Copyright :  (c) Jun Yoshida 2019\n-- License   :  BSD3\n--\n-- Implementing manipulations on enhanced states\n--\n------------------------------------------------\n\nmodule ArcGraph.EnhancedState where\n\nimport GHC.Generics (Generic)\n\nimport Control.DeepSeq\nimport Control.Parallel.Strategies\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.ST\n\nimport Data.Bifunctor\n\nimport Data.STRef\nimport Data.Maybe as M\nimport Data.Foldable\nimport qualified Data.List as L\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as MV\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IMap\nimport qualified Data.Set as Set\nimport qualified Data.BitArray as BA\n\nimport qualified Numeric.LinearAlgebra as LA\n\nimport ArcGraph\nimport ArcGraph.Component\nimport ArcGraph.State\n\nimport Numeric.Matrix.Integral\nimport Numeric.Algebra.FreeModule as FM\nimport Numeric.Algebra.Frobenius as Frob\nimport Numeric.Algebra.Presentation\nimport Numeric.Algebra.Homology\n\n{-- for debug\nimport Debug.Trace\n\ntraceCond :: Bool -> String -> a -> a\ntraceCond False _  = id\ntraceCond True msg = trace msg\n--}\n\n-----------------------\n-- * Enhanced states --\n-----------------------\nclass (DState ds, Ord e) => Enhancement ds e where\n  listEnh :: (Alternative f) => Int -> ArcGraph -> ds -> f e\n  diffEnh :: ArcGraph -> ds -> e -> FreeMod Int (ds,e)\n\nlistEStates :: (Enhancement ds e) => ArcGraph -> Int -> Int -> [(ds,e)]\nlistEStates ag i j = concatMap (\\s -> (,) s <$> listEnh j ag s) $ listStates ag i\n\n-----------------\n-- * Instances --\n-----------------\nnewtype MapEState pc = MEState (Map.Map pc SL2B)\n  deriving (Eq, Ord, Show, Generic, NFData)\n\ninstance (DState ds, PComponent pc) => Enhancement ds (MapEState pc) where\n  listEnh j ag st = \n    let comps = getComponents (smoothing ag st)\n        deg' = j - degree ag st + L.length comps\n        subs = filter (\\sub -> 2*L.length sub == deg') $ L.subsequences comps\n        mapS sub = Map.fromList $! map (\\c -> (c, if elem c sub then SLI else SLX)) comps\n    in MEState <$> foldr' (\\x xs -> pure (mapS x) <|> xs) empty subs\n\n  diffEnh ag st (MEState mp) =\n    FM.sumFM $ (diffState ag st :: V.Vector (Int,ds)) >>= \\dstp -> do\n      let (sign,dst) = dstp\n      return $! ((,) dst . MEState . Map.fromList) FM.@$>% sign FM.@*% Frob.tqftZ (doIntersect ag) (Map.toList mp) (getComponents (smoothing ag dst))\n\n----------------------\n-- WORK IN PROGRESS --\n----------------------{--\nnewtype BArray = BArray BA.BitArray\n  deriving (Eq, Ord, Show, Generic)\n\ninstance NFData BArray where\n  rnf (BArray x) = x `seq` ()\n\ndata BitEState pc = BEState pc BArray\n  deriving (Eq, Show, Generic, NFData)\n--}\n\ndata ArcGraphE ds e = AGraphE {\n  arcGraph :: ArcGraph,\n  state :: ds,\n  enhancement :: e\n  } deriving (Eq,Show,Generic,NFData)\n\nenhancements :: (DState ds, PComponent pc, Alternative f) => Int -> ArcGraph -> ds -> f (Map.Map pc SL2B)\nenhancements deg ag st =\n  let comps = getComponents (smoothing ag st)\n      deg' = deg + L.length comps\n      subs = filter (\\sub -> 2*L.length sub == deg') $ L.subsequences comps\n      mapS sub = Map.fromList $! map (\\c -> (c, if elem c sub then SLI else SLX)) comps\n  in foldr' (\\x xs -> pure (mapS x) <|> xs) empty subs\n\n----------------------------------------------------------\n-- The computation of (unnormalized) Khovanov homology\n-----------------------------------------------------------\n-- | The type to carry the data of Khovanov homologies\ndata KHData a ds e = KHData {\n  subject :: ArcGraph,\n  rank :: Int,\n  tors :: [a],\n  cycleV :: [FreeMod a (ds, e)],\n  bndryV :: Maybe [FreeMod a (ds, e)] }\n  deriving (Show,Eq,Generic, NFData)\n\nvecToSum :: (Coefficient a, Ord b) => [b] -> Vec a -> FreeMod a b\nvecToSum bs v = sumFM $! zipWith (@*@%) (vecToList v) bs\n\ncohomologyToKH :: (Coefficient a, DState ds, Enhancement ds e) => ArcGraph -> [(ds, e)] -> Bool -> Homology a -> KHData a ds e\ncohomologyToKH ag basis hasBndry hdata =\n  let basisAGE = uncurry (AGraphE ag) <$> basis\n  in KHData {\n    subject = ag,\n    rank = L.length (freeCycs hdata),\n    tors = fmap fst (torsions hdata),\n    cycleV = fmap (vecToSum basis) (freeCycs hdata ++ fmap snd (torsions hdata)),\n    bndryV = if hasBndry\n             then Just (fmap (vecToSum basis) (bndries hdata))\n             else Nothing }\n\n-- | Compute Khovanov homology for given range of cohomological degrees and a given quantum-degree\ncomputeKhovanov :: (ChainEliminable a, NFData ds, NFData e, Show ds, Show e, Eq ds, Eq e, Enhancement ds e) => ArcGraph -> Int -> [ds] -> Bool -> IntMap (KHData a ds e)\ncomputeKhovanov ag qdeg states hasBndry =\n  let numCrs = countCross ag\n      hdegs = [0..numCrs]\n      slimAG = slimCross ag\n      basis i = L.concatMap (\\st -> (,) st <$> listEnh qdeg slimAG st) (filter ((==i). degree slimAG) states)\n      !basisMap = force (IMap.fromAscList (map (\\i -> (i,basis i)) hdegs))\n      !diffs = flip (parMap rdeepseq) [0..numCrs-1] $ \\i ->\n        let sbasis = basisMap IMap.! i\n            tbasis = basisMap IMap.! (i+1)\n        in force $! present (uncurry (diffEnh slimAG)) sbasis tbasis\n  in if numCrs == 0\n     then -- The case where there is no crossing point;\n       IMap.map (\\v -> KHData slimAG (L.length v) [] (fmap (1@*@%) v) Nothing) basisMap\n     else -- The case where there is at least one crossing point;\n       let !hdata = force (homology diffs)\n           !hdataMap = IMap.fromAscList $ filter (\\hdti -> not (null (freeCycs (snd hdti)) && null (torsions (snd hdti))) ) $ zip hdegs hdata\n       in flip IMap.mapWithKey hdataMap $ \\i hdt -> cohomologyToKH slimAG (basisMap IMap.! i) hasBndry hdt\n", "meta": {"hexsha": "1bc641a43b50795a1654dc549096e9d5d6870380", "size": 5970, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ArcGraph/EnhancedState.hs", "max_stars_repo_name": "Junology/linkedgram", "max_stars_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-21T06:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:54:21.000Z", "max_issues_repo_path": "src/ArcGraph/EnhancedState.hs", "max_issues_repo_name": "Junology/linkedgram", "max_issues_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ArcGraph/EnhancedState.hs", "max_forks_repo_name": "Junology/linkedgram", "max_forks_repo_head_hexsha": "2160065d354143d1dd50b38de363d512e051de5b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1818181818, "max_line_length": 168, "alphanum_fraction": 0.6293132328, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.40988306585883066}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\nmodule Engine.Matrix.NewMatrix where\n\nimport Foreign.Storable (Storable(..))\nimport qualified Data.Vector.Storable as V\n\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Static\n\nnewtype Matrix w h t = Matrix (L w h)\n  deriving (Num, Fractional, Floating)\n\nnewtype Vector l t = Vector (R l)\n  deriving (Num, Fractional, Floating)\n\n\ninstance (Sized t (R l) V.Vector) => Sized t (Vector l t) V.Vector where\n    konst = Vector . konst\n    unwrap (Vector r) = unwrap r\n\n(<&>) :: (KnownNat w1, KnownNat w2, KnownNat h) =>\n    Matrix w1 h t -> Matrix w2 h t -> Matrix (w1+w2) h t\n(<&>) (Matrix l1) (Matrix l2) = Matrix $ l1 \u2014\u2014 l2\n", "meta": {"hexsha": "bb9f35e2b67e2f6dc2938df6306f784e0c355cd1", "size": 876, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Engine/Matrix/NewMatrix.hs", "max_stars_repo_name": "jaredloomis/Haskell-OpenGL", "max_stars_repo_head_hexsha": "5c7363bbc07c5064e49b608d689cda2cab99f3eb", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2015-05-07T09:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T01:30:29.000Z", "max_issues_repo_path": "src/Engine/Matrix/NewMatrix.hs", "max_issues_repo_name": "fiendfan1/Haskell-OpenGL", "max_issues_repo_head_hexsha": "5c7363bbc07c5064e49b608d689cda2cab99f3eb", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Engine/Matrix/NewMatrix.hs", "max_forks_repo_name": "fiendfan1/Haskell-OpenGL", "max_forks_repo_head_hexsha": "5c7363bbc07c5064e49b608d689cda2cab99f3eb", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-05-15T13:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T16:25:01.000Z", "avg_line_length": 29.2, "max_line_length": 72, "alphanum_fraction": 0.6929223744, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.4097576728395946}}
{"text": "{-# LANGUAGE RecordWildCards #-}\n\nimport Control.Monad.Trans.Except\nimport Data.Word\nimport Data.Int\nimport Data.Complex\nimport Foreign.C.Types\nimport Data.Maybe\nimport Control.Monad\nimport Data.Monoid\n\nimport Control.Error.Util\nimport Pipes as P\nimport Pipes.Prelude as P\nimport Options.Applicative\nimport Data.Vector.Storable as VS hiding ((++))\nimport Data.Vector.Generic as VG hiding ((++))\nimport Graphics.Rendering.OpenGL\n\nimport SDR.Util as U\nimport SDR.RTLSDRStream\nimport SDR.FFT\nimport SDR.Plot\nimport SDR.ArgUtils\nimport Graphics.DynamicGraph.Waterfall\nimport Graphics.DynamicGraph.Util\n\ndata Options = Options {\n    frequency    :: Word32,\n    sampleRate   :: Word32,\n    gain         :: Maybe Int32,\n    fftSize      :: Maybe Int,\n    windowWidth  :: Maybe Int,\n    windowHeight :: Maybe Int,\n    rows         :: Maybe Int,\n    colorMap     :: Maybe [GLfloat]\n}\n\nparseColorMap :: ReadM [GLfloat]\nparseColorMap = eitherReader func\n    where\n    func \"jet\"     = return jet\n    func \"jet_mod\" = return jet_mod\n    func \"hot\"     = return hot\n    func \"bw\"      = return bw\n    func \"wb\"      = return wb\n    func arg       = Left $ \"Cannot parse colour map: `\" ++ arg ++ \"'\"\n\noptParser :: Parser Options\noptParser = Options \n          <$> option (fmap fromIntegral parseSize) (\n                 long \"frequency\"  \n              <> short 'f' \n              <> metavar \"FREQUENCY\" \n              <> help \"Frequency to tune to\"\n              )\n          <*> option (fmap fromIntegral parseSize) (\n                 long \"samplerate\" \n              <> short 'r' \n              <> metavar \"RATE\" \n              <> help \"Sample rate\"\n              )\n          <*> optional (option auto (\n                 long \"gain\" \n              <> short 'g' \n              <> metavar \"GAIN\" \n              <> help \"Tuner gain\"\n              ))\n          <*> optional (option (fmap fromIntegral parseSize) (\n                 long \"size\" \n              <> short 's' \n              <> metavar \"SIZE\" \n              <> help \"FFT bin size. Default is 8192.\"\n              ))\n          <*> optional (option auto (\n                 long \"width\" \n              <> short 'w' \n              <> metavar \"WIDTH\" \n              <> help \"Window width. Default is 1024.\"\n              ))\n          <*> optional (option auto (\n                 long \"height\" \n              <> short 'h' \n              <> metavar \"HEIGHT\" \n              <> help \"Window height. Default is 480.\"\n              ))\n          <*> optional (option auto (\n                 long \"rows\" \n              <> short 'r' \n              <> metavar \"ROWS\" \n              <> help \"Number of rows in waterfall. Default is 1000.\"\n              ))\n          <*> optional (option parseColorMap (\n                 long \"colorMap\" \n              <> short 'm' \n              <> metavar \"COLORMAP\" \n              <> help \"Waterfall color map. Default is 'jet_mod'.\"\n              ))\n\nopt :: ParserInfo Options\nopt = info (helper <*> optParser) (fullDesc <> progDesc \"Draw a dynamic waterall plot of the received spectrum using OpenGL\" <> header \"RTLSDR Waterfall\")\n\ndoIt Options{..} = do\n    res <- lift setupGLFW\n    unless res (throwE \"Unable to initilize GLFW\")\n\n    let fftSize' =  fromMaybe 8192 fftSize\n        window   =  hanning fftSize' :: VS.Vector Double\n    str          <- sdrStream ((defaultRTLSDRParams frequency sampleRate) {tunerGain = gain}) 1 (fromIntegral $ fftSize' * 2)\n    rfFFT        <- lift $ fftw fftSize'\n    rfSpectrum   <- plotWaterfall (fromMaybe 1024 windowWidth) (fromMaybe 480 windowHeight) fftSize' (fromMaybe 1000 rows) (fromMaybe jet_mod colorMap)\n    --rfSpectrum   <- plotFill (maybe 1024 id windowWidth) (maybe 480 id windowHeight) fftSize' (maybe jet_mod id colorMap)\n    --rfSpectrum   <- plotTexture (maybe 1024 id windowWidth) (maybe 480 id windowHeight) fftSize' fftSize'\n\n    lift $ runEffect $   str \n                     >-> P.map (interleavedIQUnsigned256ToFloat :: VS.Vector CUChar -> VS.Vector (Complex Double)) \n                     >-> P.map (VG.zipWith (flip mult) window . VG.zipWith mult (halfBandUp fftSize')) \n                     >-> rfFFT \n                     >-> P.map (VG.map ((* (32 / fromIntegral fftSize')) . realToFrac . magnitude)) \n                     >-> rfSpectrum \n\nmain = execParser opt >>= exceptT putStrLn return . doIt\n\n", "meta": {"hexsha": "ab72cb3aeb564a349368fde26ff53bd6026e2ac0", "size": 4329, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "waterfall/waterfall.hs", "max_stars_repo_name": "adamwalker/sdr-apps", "max_stars_repo_head_hexsha": "b44b9cac4f0ab857d5889141d94ae15aa3025896", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-06-04T20:12:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T03:45:31.000Z", "max_issues_repo_path": "waterfall/waterfall.hs", "max_issues_repo_name": "adamwalker/sdr-apps", "max_issues_repo_head_hexsha": "b44b9cac4f0ab857d5889141d94ae15aa3025896", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-06-04T20:11:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-11T14:58:03.000Z", "max_forks_repo_path": "waterfall/waterfall.hs", "max_forks_repo_name": "adamwalker/sdr-apps", "max_forks_repo_head_hexsha": "b44b9cac4f0ab857d5889141d94ae15aa3025896", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-08-05T07:05:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-13T00:56:23.000Z", "avg_line_length": 34.9112903226, "max_line_length": 154, "alphanum_fraction": 0.5527835528, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.40972739759375343}}
{"text": "{-# LANGUAGE BangPatterns         #-}\n{-# LANGUAGE DataKinds            #-}\n{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE GADTs                #-}\n{-# LANGUAGE KindSignatures       #-}\n{-# LANGUAGE LambdaCase           #-}\n{-# LANGUAGE PolyKinds            #-}\n{-# LANGUAGE RankNTypes           #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\n{-# LANGUAGE TypeApplications     #-}\n{-# LANGUAGE TypeInType           #-}\n{-# LANGUAGE TypeOperators        #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule TensorOps.Learn.NeuralNet.FeedForward\n  ( Network(..)\n  , buildNet\n  , runNetwork\n  , trainNetwork\n  , induceNetwork\n  , nmap\n  , (~*)\n  , (*~)\n  , liftNet\n  , netParams\n  , networkGradient\n  , genNet\n  , ffLayer\n  ) where\n\nimport           Control.Category\nimport           Control.DeepSeq\nimport           Control.Monad.Primitive\nimport           Data.Kind\nimport           Data.Singletons\nimport           Data.Singletons.Prelude        (Sing(..))\nimport           Data.Type.Conjunction\nimport           Data.Type.Length\nimport           Data.Type.Product              as TCP\nimport           Data.Type.Product.Util         as TCP\nimport           Data.Type.Sing\nimport           Prelude hiding                 ((.), id)\nimport           Statistics.Distribution.Normal\nimport           System.Random.MWC\nimport           TensorOps.Learn.NeuralNet\nimport           TensorOps.NatKind\nimport           TensorOps.TOp                  as TO\nimport           TensorOps.Tensor               as TT\nimport           TensorOps.Types\nimport           Type.Class.Higher\nimport           Type.Class.Higher.Util\nimport           Type.Class.Known\nimport           Type.Class.Witness\nimport           Type.Family.List\nimport           Type.Family.List.Util\n\ndata Network :: ([k] -> Type) -> k -> k -> Type where\n    N :: { _nsPs    :: !(Sing ps)\n         , _nOp     :: !(TOp ('[i] ': ps) '[ '[o] ])\n         , _nParams :: !(Prod t ps)\n         } -> Network t i o\n\ninstance NFData1 t => NFData (Network t i o) where\n    rnf = \\case\n      N _ o p -> o `seq` p `deepseq1` ()\n    {-# INLINE rnf #-}\n\nbuildNet\n    :: SingI ps\n    => TOp ('[i] ': ps) '[ '[o] ]\n    -> Prod t ps\n    -> Network t i o\nbuildNet = N sing\n\nnetParams\n    :: Network t i o\n    -> (forall ps. SingI ps => Prod t ps -> r)\n    -> r\nnetParams n f = case n of\n    N o _ p -> f p \\\\ o\n\n(~*~)\n    :: Network t a b\n    -> Network t b c\n    -> Network t a c\nN sPs1 o1 p1 ~*~ N sPs2 o2 p2 =\n    N (sPs1 %:++ sPs2) (o1 *>> o2) (p1 `TCP.append'` p2)\n        \\\\ singLength sPs1\ninfixr 4 ~*~\n{-# INLINE (~*~) #-}\n\ninstance Category (Network t) where\n    id = N SNil idOp \u00d8\n    (.) = flip (~*~)\n\n(~*) :: TOp '[ '[a] ] '[ '[b] ]\n     -> Network t b c\n     -> Network t a c\nf ~* N sO o p = N sO (f *>> o) p\ninfixr 4 ~*\n{-# INLINE (~*) #-}\n\n(*~) :: Network t a b\n     -> TOp '[ '[b] ] '[ '[c] ]\n     -> Network t a c\nN sO o p *~ f = N sO (o >>> f) p\ninfixl 5 *~\n{-# INLINE (*~) #-}\n\nliftNet\n     :: TOp '[ '[i] ] '[ '[o] ]\n     -> Network t i o\nliftNet o = buildNet o \u00d8\n\nnmap\n     :: SingI o\n     => (forall a. RealFloat a => a -> a)\n     -> Network t i o\n     -> Network t i o\nnmap f n = n *~ TO.map f\n{-# INLINE nmap #-}\n\nrunNetwork\n    :: (RealFloat (ElemT t), Tensor t)\n    => Network t i o\n    -> t '[i]\n    -> t '[o]\nrunNetwork (N _ o p) = head' . runTOp o . (:< p)\n{-# INLINE runNetwork #-}\n\ntrainNetwork\n    :: forall i o t. (Tensor t, RealFloat (ElemT t))\n    => TOp '[ '[o], '[o] ] '[ '[] ]\n    -> ElemT t\n    -> t '[i]\n    -> t '[o]\n    -> Network t i o\n    -> Network t i o\ntrainNetwork loss r x y = \\case\n    N s o p ->\n      let p' = map1 (\\(!(s1 :&: o1 :&: g1)) -> TT.zip stepFunc o1 g1 \\\\ s1)\n             $ zipProd3 (singProd s) p (tail' $ netGrad loss x y s o p)\n      in  N s o p'\n  where\n    stepFunc :: ElemT t -> ElemT t -> ElemT t\n    stepFunc !o' !g' = o' - r * g'\n    {-# INLINE stepFunc #-}\n{-# INLINE trainNetwork #-}\n\ninduceNetwork\n    :: forall i o t. (Tensor t, RealFloat (ElemT t), SingI i)\n    => TOp '[ '[o], '[o] ] '[ '[] ]\n    -> ElemT t\n    -> t '[o]\n    -> Network t i o\n    -> t '[i]\n    -> t '[i]\ninduceNetwork loss r y = \\case\n    N s o p -> \\x -> TT.zip stepFunc x (head' $ netGrad loss x y s o p)\n  where\n    stepFunc :: ElemT t -> ElemT t -> ElemT t\n    stepFunc o' g' = o' - r * g'\n    {-# INLINE stepFunc #-}\n{-# INLINE induceNetwork #-}\n\nnetworkGradient\n    :: forall i o t r. (Tensor t, RealFloat (ElemT t))\n    => TOp '[ '[o], '[o] ] '[ '[] ]\n    -> t '[i]\n    -> t '[o]\n    -> Network t i o\n    -> (forall ps. SingI ps => Prod t ps -> r)\n    -> r\nnetworkGradient loss x y = \\case\n    N s o p -> \\f -> f (tail' $ netGrad loss x y s o p) \\\\ s\n{-# INLINE networkGradient #-}\n\nnetGrad\n    :: forall i o ps t. (Tensor t, RealFloat (ElemT t))\n    => TOp '[ '[o], '[o] ] '[ '[] ]\n    -> t '[i]\n    -> t '[o]\n    -> Sing ps\n    -> TOp ('[i] ': ps) '[ '[o] ]\n    -> Prod t ps\n    -> Prod t ('[i] ': ps)\nnetGrad loss x y s o p = (\\\\ appendSnoc lO (Proxy @'[o])) $\n                         (\\\\ lO                         ) $\n                         takeProd @'[ '[o] ] (LS lO)\n                       $ gradTOp o' inp\n  where\n    lO  :: Length ps\n    lO = singLength s\n    o'  :: ((ps ++ '[ '[o] ]) ~ (ps >: '[o]), Known Length ps)\n        => TOp ('[i] ': ps >: '[o]) '[ '[]]\n    o' = o *>> loss\n    inp  :: Prod t ('[i] ': ps >: '[o])\n    inp = x :< p >: y\n{-# INLINE netGrad #-}\n\nffLayer\n    :: forall i o m t. (SingI i, SingI o, PrimMonad m, Tensor t)\n    => Gen (PrimState m)\n    -> m (Network t i o)\nffLayer g = (\\w b -> buildNet ffLayer' (w :< b :< \u00d8))\n          <$> genRand (normalDistr 0 0.5) g\n          <*> genRand (normalDistr 0 0.5) g\n  where\n    ffLayer'\n        :: TOp '[ '[i], '[o,i], '[o]] '[ '[o] ]\n    ffLayer' = firstOp (TO.swap >>> TO.matVec)\n           >>> TO.add\n    {-# INLINE ffLayer' #-}\n{-# INLINE ffLayer #-}\n\ngenNet\n    :: forall k o i m (t :: [k] -> Type). (SingI o, SingI i, PrimMonad m, Tensor t)\n    => [(Integer, Activation k)]\n    -> Activation k\n    -> Gen (PrimState m)\n    -> m (Network t i o)\ngenNet xs0 f g = go sing xs0\n  where\n    go  :: forall (j :: k). ()\n        => Sing j\n        -> [(Integer, Activation k)]\n        -> m (Network t j o)\n    go sj = (\\\\ sj) $ \\case\n      []        -> (*~ getAct f) <$> ffLayer g\n      (x,f'):xs -> withNatKind x $ \\sl -> (\\\\ sl) $ do\n        n <- go sl xs\n        l <- ffLayer g\n        return $ l *~ getAct f' ~*~ n\n    {-# INLINE go #-}\n{-# INLINE genNet #-}\n\n", "meta": {"hexsha": "fcf01f3a88ba30225ef34ded7d89bfcbc852d2ff", "size": 6420, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TensorOps/Learn/NeuralNet/FeedForward.hs", "max_stars_repo_name": "mstksg/tensor-ops", "max_stars_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2016-08-24T06:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T00:31:35.000Z", "max_issues_repo_path": "src/TensorOps/Learn/NeuralNet/FeedForward.hs", "max_issues_repo_name": "mstksg/tensor-ops", "max_issues_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2016-09-29T06:01:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T10:52:51.000Z", "max_forks_repo_path": "src/TensorOps/Learn/NeuralNet/FeedForward.hs", "max_forks_repo_name": "mstksg/tensor-ops", "max_forks_repo_head_hexsha": "1958642d60d879e311da14469c3dd09c186b5fda", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-09-28T05:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2017-01-30T11:01:34.000Z", "avg_line_length": 27.0886075949, "max_line_length": 83, "alphanum_fraction": 0.4761682243, "num_tokens": 2050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.4804786780479071, "lm_q1q2_score": 0.40934515966112894}}
{"text": "{-# LANGUAGE ScopedTypeVariables, RankNTypes #-}\n\nmodule Dna.Graph (\nreadConnection,readAllConnection,\nallPossibleNode,graphFromConnection,\nGraph,euclidianCycle,\nunbalanceNodes,\ncanBeBalance, balance, initOverlaGraph\n)\nwhere\n\nimport Data.List\nimport Data.Tuple\nimport Data.Functor\nimport Data.STRef\nimport Control.Monad\nimport Data.Maybe\nimport Control.Applicative\nimport Numeric.LinearAlgebra (rows, (!), cols, toLists, (?), (\u00bf), toList)\nimport Numeric.LinearAlgebra.Data (Matrix, I)\nimport Numeric.LinearAlgebra.Devel\nimport Control.Monad.ST\n\nimport qualified Data.ByteString.Lazy.Char8 as C\nimport qualified Data.Set as S\n\ndata Graph a = GraphInternal {\n    node :: S.Set a,\n    connection :: Matrix I,\n    addCon :: Maybe (a,a)\n}\n\ninstance (Ord a, Show a) => Show (Graph a) where\n    show graph = fromMaybe matrixShow (do\n                    (from,to) <- addCon graph\n                    return $ matrixShow ++ \"\\n With Link: \" ++ show from  ++ \"->\" ++ show to)\n        where\n            linkCount row col = connection graph ! row ! col\n            isLink row col =   linkCount row col >= 1\n            matrixShow = intercalate \"\\n\"\n                [link | row <- [0 .. rows (connection graph) - 1],\n                        any (isLink row) [0 .. cols (connection graph) - 1],\n                        link <- [show (S.elemAt row (node graph)) ++ \" -> \" ++\n                                 intercalate \",\" (concatMap (\\col -> replicate (fromIntegral $ linkCount row col) $ show  $ S.elemAt col (node graph))\n                                                    (filter (isLink row) [0 .. cols (connection graph) - 1]))]]\n\ninitOverlaGraph :: Ord a =>  [a] -> (forall s. STMatrix s I -> (a -> Int) -> ST s ()) -> Graph a\ninitOverlaGraph nodes f = GraphInternal setNode (runSTMatrix $ do\n        m <- newMatrix 0 lenNodes lenNodes\n        f m (`S.findIndex` setNode)\n        return m\n    ) Nothing\n    where\n        setNode = S.fromList nodes\n        lenNodes  = length setNode\n\n\nreadConnection :: (Read a) => String -> (a, [a])\nreadConnection info = case lex info of\n    [(node, left)] -> (read node, readListOfNode (snd $ head $ lex left))\n\nreadListOfNode :: (Read a) => String -> [a]\nreadListOfNode nodes = case lex nodes of\n    [(\"\", \"\")] -> []\n    [(node, left)] -> read node : readListOfNode (snd $ head $ lex left)\n\nreadAllConnection :: (Read a) => String -> [(a, [a])]\nreadAllConnection = map readConnection . lines\n\nallPossibleNode :: [(a,[a])] -> [a]\nallPossibleNode = concatMap $ uncurry (:)\n\ngraphFromConnection ::Ord a =>  [(a,[a])] -> Graph a\ngraphFromConnection connections = GraphInternal\n        nodes\n        (runSTMatrix $ do\n            m <- newMatrix 0 nodesLen nodesLen\n            forM_ connections $ \\ (from,connectee) ->\n                forM_ connectee $ \\ to ->\n                    modifyMatrix m (findIndex from) (findIndex to) (1+)\n            return m)\n        Nothing\n    where\n        nodes = S.fromList $ allPossibleNode connections\n        findIndex = flip S.findIndex nodes\n        nodesLen = S.size nodes\n\neuclidianCycle :: Ord a => Graph a -> Maybe [(a,a)]\neuclidianCycle g = do\n    (GraphInternal nodes m newCon) <- balance g\n    conn <- runST $ do\n        traverseM <- thawMatrix m\n        path <- findEuclidianCycleAt nodes traverseM (Just 0)\n        findNext nodes path traverseM\n    return $ maybe conn (\\(from,to) -> init $ uncurry (++) (swap (break ( (to == ).fst ) conn))) newCon\n  where findNext nodes path m = do\n            newPath <- findNextEuclidianPath nodes m path\n            if isJust newPath\n                then findNext nodes newPath m\n                else return path\n\nfindNextEuclidianPath :: Ord a => S.Set a -> STMatrix s I -> Maybe [(a,a)] -> ST s (Maybe [(a,a)])\nfindNextEuclidianPath nodes mat path = do\n    inMat <- freezeMatrix mat\n    let newPath = do\n            foundPath <- path\n            let (left,right) = break (\\(from,to) -> sum (map ti $ toList (inMat ! S.findIndex from nodes)) > 0) foundPath\n            if null right\n                then Nothing\n                else Just (right ++ left)\n    let maybeNext = fmap ((`S.findIndex` nodes) . fst . head) newPath\n    maybeNextPath <- findEuclidianCycleAt nodes mat maybeNext\n    return $ liftM2 (++) maybeNextPath newPath\n\n\nfindEuclidianCycleAt :: Ord a => S.Set a -> STMatrix s I -> Maybe Int -> ST s (Maybe [(a,a)])\nfindEuclidianCycleAt nodes mat startNode = if isJust startNode\n                                                then findNextNod startNode\n                                                else return Nothing\n    where\n        findNextNod n =  do\n            next <- findNextEuclidianAt nodes mat (fromJust n)\n            let cycleEnd = liftM2 (==) next startNode\n            case (cycleEnd, next) of\n                (Just True, Just to) -> return (Just [(S.elemAt (fromJust n) nodes,S.elemAt to nodes)])\n                (Just False, to) -> do\n                    list <- findNextNod to\n                    return $ liftM2 (:) (Just (S.elemAt (fromJust n) nodes,S.elemAt (fromJust to) nodes)) list\n                _ -> return Nothing\n\nfindNextEuclidianAt :: Ord a => S.Set a -> STMatrix s I -> Int -> ST s (Maybe Int)\nfindNextEuclidianAt nodes mat n = do\n    con <- mapM (readMatrix mat n) [0..(S.size nodes - 1)]\n    let next = find ((>0).snd) (zip [0..] con)\n    when (isJust next) $ modifyMatrix mat n (fst . fromJust $ next) (subtract 1)\n    return $ fst <$> next\n\nmapFst :: (a -> b) -> [(a,c)] -> [(b,c)]\nmapFst f = map (uncurry $ (,) . f)\n\ncanBeBalance :: Ord a => Graph a -> Bool\ncanBeBalance g = case unbal of\n    [(_,-1), (_,1)] -> True\n    [(_,1), (_,-1)] -> True\n    [] -> True\n    _ -> False\n  where unbal = unbalanceNodes g\n\nbalance :: Ord a => Graph a -> Maybe (Graph a)\nbalance g@(GraphInternal node connection addCon) = case unbal of\n    [(to,-1), (from,1)] -> return (GraphInternal node (fst (mutable (correctingMatrix (S.findIndex from node) (S.findIndex to node)) connection)) (Just (from,to)))\n    [(from,1), (to,-1)] -> return (GraphInternal node (fst (mutable (correctingMatrix (S.findIndex from node) (S.findIndex to node)) connection)) (Just (from,to)))\n    [] -> return g\n    _ -> Nothing\n  where\n    unbal = unbalanceNodes g\n    correctingMatrix f t _ m = modifyMatrix m f t (+1)\n\nunbalanceNodes :: Ord a => Graph a -> [(a,Int)]\nunbalanceNodes (GraphInternal nodes m _) =filter ((0 /= ) . snd) (mapFst (`S.elemAt` nodes) (map (\\idx -> (idx,eulerianNode idx m)) [0..(S.size nodes - 1)]))\n\neulerianNode :: Int -> Matrix I -> Int\neulerianNode n m = ti (sum (concat colConnection)) - ti (sum (concat rowConnection))\n    where\n        colConnection = toLists $ m \u00bf [n]\n        rowConnection = toLists $ m ? [n]\n\neulerianNodeST :: Int -> STMatrix s I -> ST s Bool\neulerianNodeST n m = do\n    colm <- extractMatrix m AllRows (Col n)\n    rowm <- extractMatrix m (Row n) AllCols\n    return $ (sum . concat . toLists) colm == (sum . concat . toLists) rowm\n", "meta": {"hexsha": "f35e366717d7ceb4e33a5bf493c171539f9046f1", "size": 6911, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Dna/Graph.hs", "max_stars_repo_name": "mathk/NautilusDna", "max_stars_repo_head_hexsha": "b38f1803b84600adee8d45484064265abada6c4b", "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/Dna/Graph.hs", "max_issues_repo_name": "mathk/NautilusDna", "max_issues_repo_head_hexsha": "b38f1803b84600adee8d45484064265abada6c4b", "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/Dna/Graph.hs", "max_forks_repo_name": "mathk/NautilusDna", "max_forks_repo_head_hexsha": "b38f1803b84600adee8d45484064265abada6c4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9479768786, "max_line_length": 163, "alphanum_fraction": 0.5947040949, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.40901047002969476}}
{"text": "module Approx ( bezier2biarc\n              ) where\n\nimport qualified CubicBezier as B\nimport qualified BiArc as BA          \nimport qualified Line as L \n          \nimport Data.Bool (bool)\nimport Linear    \nimport Data.Complex\n\nimport Types\n\n-- Approximate a bezier curve with biarcs (Left) and line segments (Right)\nbezier2biarc :: B.CubicBezier \n             -> Double\n             -> [Either BA.BiArc (V2 Double)]\nbezier2biarc mbezier resolution \n    -- Edge case: all points on the same line -> it is a line \n    | (L.isOnLine (L.fromPoints (B._p2 mbezier) (B._p1 mbezier)) (B._c1 mbezier)) && \n      (L.isOnLine (L.fromPoints (B._p2 mbezier) (B._p1 mbezier)) (B._c2 mbezier)) \n        = [Right (B._p2 mbezier)]\n    -- Edge case: p1 == c1, don't split\n    | (B._p1 mbezier) == (B._c1 mbezier)\n        = approxOne mbezier\n    -- Edge case: p2 == c2, don't split\n    | (B._p2 mbezier) == (B._c2 mbezier)\n        = approxOne mbezier\n    -- Split by the inflexion points (if any)\n    | otherwise \n        = byInflection (B.realInflectionPoint i1) (B.realInflectionPoint i2)\n    where\n        (i1, i2) = B.inflectionPoints mbezier\n\n        order a b | b < a = (b, a)\n                  | otherwise = (a, b)\n    \n        byInflection True False = approxOne b1 ++ approxOne b2\n            where\n                (b1, b2) = B.bezierSplitAt mbezier (realPart i1)\n\n        byInflection False True = approxOne b1 ++ approxOne b2\n            where\n                (b1, b2) = B.bezierSplitAt mbezier (realPart i2)\n    \n        byInflection True True = approxOne b1 ++ approxOne b2 ++ approxOne b3\n            where\n                (it1, it2') = order (realPart i1) (realPart i2)\n                \n                -- Make the first split and save the first new curve. The second one has to be splitted again\n                -- at the recalculated t2 (it is on a new curve)                \n                it2 = (1 - it1) * it2'        \n                \n                (b1, toSplit) = B.bezierSplitAt mbezier it1\n                (b2, b3) = B.bezierSplitAt toSplit it2\n\n        byInflection False False = approxOne mbezier\n         \n        -- TODO: make it tail recursive\n        approxOne :: B.CubicBezier -> [Either BA.BiArc (V2 Double)]\n        approxOne bezier\n            -- Approximate bezier length. if smaller than resolution, do not approximate\n            | (distance (B._p1 bezier) (B._c1 bezier)) + \n              (distance (B._c1 bezier) (B._c2 bezier)) + \n              (distance (B._c2 bezier) (B._p2 bezier)) < resolution\n                = [Right (B._p2 bezier)]\n            -- Edge case: start- and endpoints are the same\n            | (B._p1 bezier) == (B._p2 bezier)\n                = splitAndRecur 0.5\n            -- Edge case: control lines are parallel\n            | (L._m t1) == (L._m t2) || (isNaN (L._m t1) && isNaN (L._m t2)) \n                = splitAndRecur 0.5\n            -- Approximation is not close enough yet, refine\n            | BA.isStable biarc && maxDistance > resolution\n                = splitAndRecur maxDistanceAt\n            -- Desired case: approximation is stable and close enough\n            | BA.isStable biarc\n                = [Left biarc]\n            -- Unstable approximation: split the bezier into half, basically switching to\n            -- linear approximation mode\n            | otherwise\n                = splitAndRecur 0.5\n\n            where\n                -- Edge case: P1==C1 or P2==C2\n                -- there is no derivative at P1 or P2, use the other control point\n                c1 = bool (B._c1 bezier) (B._c2 bezier) ((B._p1 bezier) == (B._c1 bezier))\n                c2 = bool (B._c2 bezier) (B._c1 bezier) ((B._p2 bezier) == (B._c2 bezier))\n\n                -- V: Intersection point of tangent lines\n                t1 = L.fromPoints (B._p1 bezier) c1\n                t2 = L.fromPoints (B._p2 bezier) c2\n                v = L.intersection t1 t2\n\n                -- G: incenter point of the triangle (P1, V, P2)\n                dP2V = distance (B._p2 bezier) v\n                dP1V = distance (B._p1 bezier) v\n                dP1P2 = distance (B._p1 bezier) (B._p2 bezier)\n                g = (dP2V *^ B._p1 bezier + dP1V *^ B._p2 bezier + dP1P2 *^ v) ^/ (dP2V + dP1V + dP1P2)\n\n                -- Calculate the BiArc\n                biarc = BA.create (B._p1 bezier) (B._p1 bezier - c1) (B._p2 bezier) (B._p2 bezier - c2) g\n                \n                -- Calculate the error\n                -- TODO: we only calculate the distance at 8 points (first and last skipped as \n                --       they should be precise), seems a resonable approximation as for now\n                parameterStep = 1 / 10\n                                \n                (maxDistance, maxDistanceAt) = maxDistance' 0 0 parameterStep\n                \n                maxDistance' m mt t \n                    | t < 1\n                        = if' (d > m) (maxDistance' d t nt) (maxDistance' m mt nt)\n                    | otherwise\n                        = (m, mt)\n                    where\n                        d = distance (BA.pointAt biarc t) (B.pointAt bezier t)\n                        nt = t + parameterStep\n\n                splitAndRecur t = let (b1, b2) = B.bezierSplitAt bezier t\n                                   in approxOne b1 ++ approxOne b2  \n\n", "meta": {"hexsha": "711632376c693fa81f590b770288c48f8b85adc1", "size": 5301, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Approx.hs", "max_stars_repo_name": "domoszlai/svg2gcode", "max_stars_repo_head_hexsha": "c588af34084890d9ef0253585c8d7fe04c34e05b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 86, "max_stars_repo_stars_event_min_datetime": "2017-02-19T10:15:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T08:55:08.000Z", "max_issues_repo_path": "src/Approx.hs", "max_issues_repo_name": "domoszlai/svg2gcode", "max_issues_repo_head_hexsha": "c588af34084890d9ef0253585c8d7fe04c34e05b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2018-08-07T07:52:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-18T11:09:04.000Z", "max_forks_repo_path": "src/Approx.hs", "max_forks_repo_name": "domoszlai/svg2gcode", "max_forks_repo_head_hexsha": "c588af34084890d9ef0253585c8d7fe04c34e05b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-02-11T09:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T12:33:56.000Z", "avg_line_length": 43.0975609756, "max_line_length": 109, "alphanum_fraction": 0.5210337672, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.40894122370897396}}
{"text": "module SchemeParser.Parser where\n\nimport Numeric (readInt, readFloat, readHex, readOct)\nimport Data.Ratio\nimport Data.Complex\nimport Data.Char (digitToInt)\nimport Data.Maybe (listToMaybe, fromJust)\n\nimport qualified Data.Map as M\n\nimport Data.Functor (($>))\n\nimport Text.Parsec hiding (spaces)\nimport Text.Parsec.Prim\n\nimport SchemeParser.Types\n\n-- parser helpers\n\nsymbol :: LispParser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\"\n\nspaces :: LispParser ()\nspaces = skipMany1 space\n\nescapedChars :: LispParser Char\nescapedChars = do\n  char '\\\\'\n  c <- oneOf \"\\\"nrt\\\\\"\n  return $ case c of\n    'n' -> '\\n'\n    'r' -> '\\r'\n    't' -> '\\t'\n    _   -> c\n\nreadBin :: Integral a => String -> Maybe a\nreadBin = fmap fst . listToMaybe . readInt 2 (`elem` \"01\") digitToInt\n\n--\n-- Lisp value parsers\n--\n\n-- primitives\n\nparseAtom :: LispParser LispVal\nparseAtom = do\n  first <- letter <|> symbol\n  rest <- many (letter <|> digit <|> symbol)\n  let atom = first : rest\n  return $ LAtom atom\n\nparseString :: LispParser LispVal\nparseString = do\n  char '\"'\n  x <- many $ escapedChars <|> noneOf \"\\\"\"\n  char '\"'\n  return $ LString x\n\nparseChar :: LispParser LispVal\nparseChar = do\n  try (string \"#\\\\\")\n  c <- try (string \"newline\" <|> string \"space\")\n       <|> do { x <- anyChar; notFollowedBy alphaNum; return [x]}\n  return $ LChar $ case c of\n    \"newline\" -> '\\n'\n    \"space\"   -> ' '\n    _         -> head c\n\nparseBool :: LispParser LispVal\nparseBool =\n  try (string \"#t\" $> LBool True) <|> try (string \"#f\" $> LBool False)\n\n-- http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2.4\nparseNumberRadix :: LispParser LispVal\nparseNumberRadix =\n  parseBin <|> parseOct <|> parseDec <|> parseHex\n  where\n    parseBin = do\n      try (string \"#b\")\n      LNumber . fromJust . readBin <$> many1 (oneOf \"01\")\n    parseOct = do\n      try (string \"#o\")\n      LNumber . fst . (!! 0) . readOct <$> many1 octDigit\n    parseDec = do\n      try (string \"#d\")\n      parseNumber\n    parseHex = do\n      try (string \"#x\")\n      LNumber . fst . (!! 0) . readHex <$> many1 hexDigit\n\nparseNumber :: LispParser LispVal\nparseNumber = parseNumberRadix <|> LNumber . read <$> many1 digit\n\nparseFloat :: LispParser LispVal\nparseFloat = do\n  l <- many1 digit\n  char '.'\n  r <- many1 digit\n  return $ LFloat $ fst $ head $ readFloat (l ++ \".\" ++ r)\n\nparseRatio :: LispParser LispVal\nparseRatio = do\n  n <- many1 digit\n  char '/'\n  d <- many1 digit\n  return $ LRatio (read n % read d)\n\nparseComplex :: LispParser LispVal\nparseComplex = do\n  r <- try parseFloat <|> parseNumber\n  char '+'\n  i <- try parseFloat <|> parseNumber\n  char 'i'\n  return $ LComplex (toDouble r :+ toDouble i)\n\n-- lists\n\nparseList :: LispParser LispVal\nparseList = LList <$> sepBy parseExpr spaces\n\nparseDottedList :: LispParser LispVal\nparseDottedList = do\n  hd <- endBy parseExpr spaces\n  tl <- char '.' >> spaces >> parseExpr\n  return $ LDottedList hd tl\n\nparseQuoted :: LispParser LispVal\nparseQuoted = do\n  char '\\''\n  x <- parseExpr\n  return $ LList [LAtom \"quote\", x]\n\nparseQuasiQuoted :: LispParser LispVal\nparseQuasiQuoted = do\n  char '`'\n  x <- parseExpr\n  return $ LList [LAtom \"quasiquote\", x]\n\nparseUnquoted :: LispParser LispVal\nparseUnquoted = do\n  char ','\n  x <- parseExpr\n  return $ LList [LAtom \"unquote\", x]\n\nparseUnquoteSpliced :: LispParser LispVal\nparseUnquoteSpliced = do\n  try $ string \",@\"\n  x <- parseExpr\n  return $ LList [LAtom \"unquote-splice\", x]\n\nparseVector :: LispParser LispVal\nparseVector = LVector <$> sepBy parseExpr spaces\n\n--\n-- helpers\n--\n\ntoDouble :: LispVal -> Double\ntoDouble (LFloat f) = realToFrac f\ntoDouble (LNumber n) = fromIntegral n\n\n--\n\nparseExpr :: LispParser LispVal\nparseExpr = parseAtom\n            <|> parseString\n            <|> parseChar\n            <|> try parseFloat\n            <|> try parseRatio\n            <|> try parseComplex\n            <|> parseNumber\n            <|> parseBool\n            <|> parseQuoted\n            <|> parseQuasiQuoted\n            <|> parseUnquoteSpliced\n            <|> parseUnquoted\n            <|> char '(' *> (try parseList <|> parseDottedList) <* char ')'\n            <|> try (string \"#(\" *> parseVector <* char ')')\n", "meta": {"hexsha": "60a02a5758a8a20b31d3bf86c8a5e3e3a5196a76", "size": 4162, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/SchemeParser/Parser.hs", "max_stars_repo_name": "alexpeits/haskell-lab-old", "max_stars_repo_head_hexsha": "e161c4a96118995d11e7b933529afd03596c4ccc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-06T02:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-06T02:04:24.000Z", "max_issues_repo_path": "src/SchemeParser/Parser.hs", "max_issues_repo_name": "alexpeits/haskell-lab-old", "max_issues_repo_head_hexsha": "e161c4a96118995d11e7b933529afd03596c4ccc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SchemeParser/Parser.hs", "max_forks_repo_name": "alexpeits/haskell-lab-old", "max_forks_repo_head_hexsha": "e161c4a96118995d11e7b933529afd03596c4ccc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.251396648, "max_line_length": 84, "alphanum_fraction": 0.6266218164, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.40855121948165}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule FM (FMOptions(..), run, parseOpts) where\n\nimport           Control.Monad\nimport           Control.Monad.State.Lazy (StateT(runStateT), MonadState (get, put))\nimport           Data.Complex\nimport qualified Data.Vector.Storable as V\nimport qualified Filter as F\nimport           IQ\nimport           Options.Applicative\nimport           Pipes\nimport           Render\nimport qualified Sound.File.Sndfile as SF\nimport qualified Sound.File.Sndfile.Buffer.Vector as SV\nimport           System.IO\nimport           ZeroStuff\n\ndata FMOptions = FMOptions\n  { inputFile :: String\n  , outputFile :: String\n  , deviationRatio :: Double\n  , upsample :: Int\n  , filterOpts :: F.FilterOptions }\n\nparseOpts :: Parser FMOptions\nparseOpts = FMOptions\n         <$> strOption\n             ( long \"in-file\"\n            <> short 'i'\n            <> metavar \"INPUT_FILE\"\n            <> help \"Input sound file\" )\n         <*> strOption\n             ( long \"out-file\"\n            <> short 'o'\n            <> metavar \"OUTPUT_FILE\"\n            <> help \"Output IQ file\")\n         <*> option auto\n             ( long \"deviation-ratio\"\n            <> short 'd'\n            <> value 1\n            <> showDefault\n            <> metavar \"DEV_RATIO\"\n            <> help \"The raio of max_devation over max_mod_frequency.\")\n         <*> option auto\n             ( long \"upsample-factor\"\n            <> short 'u'\n            <> value 10\n            <> showDefault\n            <> metavar \"UPSAMPLE_FAC\"\n            <> help \"Upsample factor, outSR = inSR * UPSAMPLE_FAC\")\n         <*> F.parseOpts\n\n-- clamp phase to [-pi, pi]\nclampPhase :: Double -> Double\nclampPhase phase\n  | phase > pi = clampPhase $ phase - (2 * pi)\n  | phase < -pi = clampPhase $ phase + (2 * pi)\n  | otherwise =  phase\n\nmodulateFM :: MonadIO  m => Double -> Pipe Float IQ m ()\nmodulateFM devRatio = void $ flip runStateT (0 :: Double) $ forever $ do\n  sample <- lift await\n  phase <- get\n  let phase' = clampPhase $ phase + realToFrac sample * devRatio\n  lift . yield $ realToFrac (cos phase') :+ realToFrac (sin phase')\n  put phase'\n\nyieldEvery :: Monad m => Int -> Pipe a a m ()\nyieldEvery n = do\n  replicateM_ (n - 1) await\n  await >>= yield\n  yieldEvery n\n\nrun :: FMOptions -> IO ()\nrun opts = do\n  (info, Just (aSamps :: SV.Buffer Float)) <- SF.readFile $ inputFile opts\n\n  let sampsVec = SV.fromBuffer aSamps\n      upsampleRate = upsample opts * SF.samplerate info\n      filterKernel = F.lowPass upsampleRate $ filterOpts opts\n\n  putStr \"Processing samples... \"\n  hFlush stdout\n\n  withBinaryFile (outputFile opts) WriteMode  $ \\f ->\n    runEffect $ V.mapM_ yield sampsVec\n            >-> yieldEvery (SF.channels info)\n            >-> modulateFM (deviationRatio opts)\n            >-> zeroStuff (upsample opts)\n            >-> F.convolve filterKernel\n            >-> cfileSink f\n\n  putStrLn \"Done.\"\n\n  putStrLn $  \"CFile sample rate: \" ++ show  upsampleRate ++ \"Hz\"\n", "meta": {"hexsha": "7f8d16b80e960341d8658f36740fe90ed5707fea", "size": 2946, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FM.hs", "max_stars_repo_name": "hexagonal-sun/ayeQ", "max_stars_repo_head_hexsha": "0dd484287ed785109867db4a06d1861cabb04062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-25T11:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-25T11:41:05.000Z", "max_issues_repo_path": "src/FM.hs", "max_issues_repo_name": "hexagonal-sun/ayeQ", "max_issues_repo_head_hexsha": "0dd484287ed785109867db4a06d1861cabb04062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FM.hs", "max_forks_repo_name": "hexagonal-sun/ayeQ", "max_forks_repo_head_hexsha": "0dd484287ed785109867db4a06d1861cabb04062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3711340206, "max_line_length": 84, "alphanum_fraction": 0.5885947047, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.40854263080848147}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\nmodule AI.Singularity.Examples.Mnist where\nimport GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Data as LD\nimport qualified Numeric.LinearAlgebra.Devel as LDev\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Control.Monad.State as S\nimport Control.Lens\nimport Data.Proxy\nimport Control.Monad.ST\nimport System.Random\nimport Control.Monad\nimport Control.Arrow\nimport qualified Data.Vector.Storable as VS\n\nimport AI.Singularity.Network\n\ngetLabels :: String -> IO [Float]\ngetLabels = map (fromIntegral . fromEnum) . drop 8 . BS.unpack <$< BS.readFile\n\ngetImages2 :: String -> IO [[Vector 28]]\ngetImages2 = (map . map) fromListV . splitByLen 28 . splitByLen 28 . map ((/255). fromIntegral . fromEnum) . drop 16 . BS.unpack <$< BS.readFile\n\ngetSet3 :: String -> IO [((Vector 400, Vector 384), Vector 10)]\ngetSet3 = map (toVec >>> first splitV) <$< getSet\n\ngetSet2 :: String -> IO [([Vector 28],Vector 10)]\ngetSet2 nm = zip <$> getImages2 (\"mnist/\"++nm++\"-images-idx3\"++rest) <*> (map wynik <$> getLabels (\"mnist/\"++nm++\"-labels-idx1\"++rest))\n  where rest          = \"-ubyte\"\n        wynik liczba  = Vec . VS.map (\\x -> if x == liczba then 1 else 0) . VS.fromList $ [0..9]\n\ngetImages :: String -> IO [VS.Vector Float]\ngetImages = map VS.fromList . splitByLen (28*28) . map ((/255). fromIntegral . fromEnum) . drop 16 . BS.unpack <$< BS.readFile\n\n-- getImagesP :: FilePath -> Producer PB.ByteString IO a\ngetImagesC fn = let s = do\n                      x <- CB.take 28\n                      if BS.length x == 0\n                        then return ()\n                        else yield (map ((/255) . fromIntegral . fromEnum) . BS.unpack $ x) >> s\n                    v = do\n                      x <- CL.take 28\n                      if null x\n                        then return ()\n                        else yield x >> v\n                in CB.sourceFile fn .| (CB.drop 16 >> s) .| CL.map (fromListV :: [Float] -> Vector 28) .| v\n\ngetLinearC fn = let s = do\n                      x <- BS.unpack <$> CB.take (28*28)\n                      if null x\n                        then return ()\n                        else do\n                              yield . map ((/255). fromIntegral . fromEnum) $ x\n                              s\n                in CB.sourceFile fn .| (CB.drop 16 >> s) .| CL.map (fromListV :: [Float] -> Vector 784)\n\nfix f = let x = f x in x\n\n-- setConduit :: String -> Source\nsetConduit nm = zipSources (getImagesC im) (getLabelsC lab)\n  where im   = \"mnist/\"++nm++\"-images-idx3\"++rest\n        lab  = \"mnist/\"++nm++\"-labels-idx1\"++rest\n        rest = \"-ubyte\"\n\nsetConduit2 nm = zipSources (getLinearC im) (getLabelsC lab)\n  where im   = \"mnist/\"++nm++\"-images-idx3\"++rest\n        lab  = \"mnist/\"++nm++\"-labels-idx1\"++rest\n        rest = \"-ubyte\"\n\ngetLabelsC fn =\n  CB.sourceFile fn .|\n  (CB.drop 8 >> fix (\\f -> CB.head >>= \\case { Nothing -> return (); Just x -> yield x >> f} )) .| CL.map (fromEnum >>> wynik)\n    where wynik n = Vec . VS.map (\\x -> if x == n then 1 else 0) . VS.fromList $ [0..9] :: Vector 10\n\n  --map (fromIntegral . fromEnum) . drop 8 . BS.unpack\n\ngetSet :: String -> IO [(VS.Vector Float, Float)]\ngetSet nm = zip <$> getImages (\"mnist/\"++nm++\"-images-idx3\"++rest) <*> getLabels (\"mnist/\"++nm++\"-labels-idx1\"++rest)\n  where rest = \"-ubyte\"\n\nprintSet :: (VS.Vector Float, Float) -> IO ()\nprintSet (v,a) = do\n  print a\n  mapM_ (\\(i,val) -> (if i `mod` 28 == 0 then putStr (printVal val ++ \"\\n\") else putStr (printVal val) )) . zip [1..] . VS.toList $ v\n\nprintVal :: Float -> String\nprintVal x = if x < 0.00001 then \"  \" else \"* \"\n\ntoVec :: (VS.Vector Float, Float) -> (Vector 784, Vector 10)\ntoVec (!obraz, !liczba) = (Vec obraz, Vec wynik)\n    where wynik = VS.map (\\x -> if x == liczba then 1 else 0) . VS.fromList $ [0..9]\n\nprintVec :: Vector 784 -> String\nprintVec (Vec !v) =  concatMap (\\(i,val) -> (if i `mod` 28 == 0 then printVal val ++ \"\\n\" else printVal val )) . zip [1..] . VS.toList $ v\n\ntestVec :: (VS.Vector Float, Float) -> (Vector 784, Int)\ntestVec (!obrac, !liczba) = (Vec obrac, round liczba)\n", "meta": {"hexsha": "9a9e8a71efa1a14282af47d00dd7fe8f02dac27c", "size": 4474, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Singularity/Examples/Mnist.hs", "max_stars_repo_name": "Antystenes/Memetic-Predictor", "max_stars_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AI/Singularity/Examples/Mnist.hs", "max_issues_repo_name": "Antystenes/Memetic-Predictor", "max_issues_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AI/Singularity/Examples/Mnist.hs", "max_forks_repo_name": "Antystenes/Memetic-Predictor", "max_forks_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0458715596, "max_line_length": 144, "alphanum_fraction": 0.5856057219, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.4085426308084814}}
{"text": "-- | Functionality for graphing 1-dimensional vectors.\nmodule System.Console.Ansigraph.Internal.Horizontal (\n    displayRV\n  , displayCV\n  , displayPV\n  , renderPV\n  , renderRV\n  , renderCV\n) where\n\nimport System.Console.Ansigraph.Internal.Core\n\nimport Data.Complex\nimport Control.Monad.IO.Class (MonadIO)\n-- for GHC <= 7.8\nimport Control.Applicative\n\n\n---- Graphing Infrastructure  ----\n\nbarChars = \"\u2588\u2587\u2586\u2585\u2584\u2583\u2582\u2581 \"\n\n-- These values delineate regions for rounding to the nearest 1/8.\nbarVals :: [Double]\nbarVals = (+ 0.0625) . (/8) <$> [7,6..0]\n     -- = [15/16, 13/16, 11/16, 9/16, 7/16, 5/16, 3/16, 1/16]\n\n{- forward and reverse versions of unicode bar selection\n   for positive and negative graph regions respectively -}\n\nbars, barsR :: [(Double,Char)]\nbars  = zip barVals barChars\n\nbarsR = zip barVals (reverse barChars)\n\n\nselectBar, selectBarR :: Double -> Char\nselectBar x = let l = filter (\\p -> fst p < x) bars in\n  case l of\n       []     -> ' '\n       (p:_) -> snd p\n\nselectBarR x = let l = filter (\\p -> fst p < x) barsR in\n  case l of\n       []     -> '\u2588'\n       (p:_) -> snd p\n\n\n-- | Simple vector to String rendering that assumes positive input. Yields String of Unicode chars\n--   representing graph bars varying in units of 1/8. The IO 'display' functions are preferable\n--   for most use cases.\nrenderPV :: [Double] -> String\nrenderPV xs = let mx = maximum (filter (>= 0) $ 0:xs) in\n              (selectBar . (/mx)) <$> xs\n\n-- | Simple real vector rendering as a pair of strings. The IO 'display' functions are\n--   preferable for most use cases.\nrenderRV :: [Double] -> (String,String)\nrenderRV l = let rp = l\n                 rm = negate <$> rp\n                 mx = maximum $ rp ++ rm\n  in (selectBar  . (/mx) <$> rp,\n      selectBarR . (/mx) <$> rm)\n\n-- | Simple complex vector rendering as a pair of strings. The IO 'display' functions are\n--   preferable for most use cases.\nrenderCV :: [Complex Double] -> (String,String,String,String)\nrenderCV l = let rp = realPart <$> l\n                 rm = negate   <$> rp\n                 ip = imagPart <$> l\n                 im = negate   <$> ip\n                 mx = maximum $ rp ++ rm ++ ip ++ im\n  in (selectBar  . (/mx) <$> rp,\n      selectBarR . (/mx) <$> rm,\n      selectBar  . (/mx) <$> ip,\n      selectBarR . (/mx) <$> im)\n\n\n-- | ANSI based display for positive real vectors. Primarily invoked via 'graph', 'graphWith',\n--   'animate', 'animateWith'.\ndisplayPV :: MonadIO m => GraphSettings -> [Double] -> m ()\ndisplayPV s l = let (rp,_) = renderRV l\n                    rcol   = realColors s in colorStrLn rcol rp\n\n-- | ANSI based display for real vectors. Primarily invoked via 'graph', 'graphWith',\n--   'animate', 'animateWith'.\ndisplayRV :: MonadIO m => GraphSettings -> [Double] -> m ()\ndisplayRV s l = let (rp,rm) = renderRV l\n                    rcol    = realColors s\n  in do colorStrLn rcol          rp\n        colorStrLn (invert rcol) rm\n\n-- | ANSI based display for complex vectors. Primarily invoked via 'graph', 'graphWith',\n--   'animate', 'animateWith'.\ndisplayCV :: MonadIO m => GraphSettings -> [Complex Double] -> m ()\ndisplayCV s l = let (rp,rm,ip,im) = renderCV l\n                    (rcol,icol)   = colorSets s\n  in do colorStrLn rcol          rp\n        colorStrLn (invert rcol) rm\n        colorStrLn icol          ip\n        colorStrLn (invert icol) im\n", "meta": {"hexsha": "4c5e44aec9ef23e838a49809620fc79714190802", "size": 3346, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/System/Console/Ansigraph/Internal/Horizontal.hs", "max_stars_repo_name": "fieldstrength/ansigraph", "max_stars_repo_head_hexsha": "a0d246428036ab5733f3b6c77122386e7d50bfe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-15T05:48:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-15T05:48:24.000Z", "max_issues_repo_path": "src/System/Console/Ansigraph/Internal/Horizontal.hs", "max_issues_repo_name": "fieldstrength/ansigraph", "max_issues_repo_head_hexsha": "a0d246428036ab5733f3b6c77122386e7d50bfe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/System/Console/Ansigraph/Internal/Horizontal.hs", "max_forks_repo_name": "fieldstrength/ansigraph", "max_forks_repo_head_hexsha": "a0d246428036ab5733f3b6c77122386e7d50bfe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8039215686, "max_line_length": 98, "alphanum_fraction": 0.6019127316, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.40852841622947333}}
{"text": "{-# LANGUAGE BangPatterns        #-}\n{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators       #-}\n{-# LANGUAGE ViewPatterns        #-}\nmodule FokkerPlanck.GPUKernel where\n\nimport           Data.Array.Accelerate              as A\nimport           Data.Array.Accelerate.Data.Complex as A\nimport qualified Data.Complex                       as C\nimport Debug.Trace\n\n{-# INLINE moveParticle #-}\nmoveParticle ::\n     (A.RealFloat a, A.Num a, Elt a-- , FromIntegral Int a\n     )\n  => Exp (a, a, a, a)\n  -> Exp (a, a, a, a)\nmoveParticle (unlift -> (phi, rho, theta, r)) =\n  let !x = theta - phi\n      !cosX = A.cos x\n      !newPhi = phi + (A.atan2 (r * A.sin x) (rho + r * cosX))\n      !newRho = A.sqrt $ (rho * rho + r * r + 2 * r * rho * cosX)\n      -- !xx = A.round $ newRho * A.cos newPhi :: Exp Int\n      -- !y = A.round $ newRho * A.sin newPhi :: Exp Int\n      -- !newRho' = A.sqrt . A.fromIntegral $ xx * xx + y * y\n      -- !newPhi' = A.atan2 (A.fromIntegral y) (A.fromIntegral xx)\n  in lift (newPhi, newRho, theta, r)\n\n{-# INLINE normalizationTerm #-}\nnormalizationTerm ::\n     (A.Floating a, A.Num a, A.RealFloat a, A.Elt (Complex a))\n  => Exp a\n  -> Exp a\n  -> Exp (Complex a)\nnormalizationTerm halfLogPeriod freq =\n  (lift $ 1 A.:+ ((-A.pi) * freq / halfLogPeriod)) /\n  (A.exp (lift $ halfLogPeriod A.:+ (-A.pi * freq)) -\n   A.exp (lift $ (-halfLogPeriod) A.:+ (A.pi * freq)))\n\n-- {-# INLINE coefficient #-}\n-- coefficient ::\n--      forall a. (A.Floating a, A.Num a, A.RealFloat a, A.Elt (Complex a), Prelude.Fractional a)\n--   => Exp a\n--   -> Exp a\n--   -> Exp a\n--   -> Exp a\n--   -> Exp a\n--   -> Exp (a, a, a, a)\n--   -> Exp (A.Complex a)\n-- coefficient halfLogPeriod rFreq thetaFreq rhoFreq phiFreq particle -- (unlift -> (phi, rho, theta, r))\n--  =\n--   let (phi, rho, theta, r) = unlift particle :: (Exp a, Exp a, Exp a, Exp a)\n--      -- (normalizationTerm halfLogPeriod rhoFreq) *\n--      -- (normalizationTerm halfLogPeriod rFreq) *\n--      -- (lift (A.cos (phiFreq * phi + thetaFreq * (theta - phi)) A.:+ 0)) *\n--                            -- (A.cis $\n--                            --  (-2 * A.pi) * (rhoFreq * rho + rFreq * (r - rho)) /\n--                            --  (A.exp halfLogPeriod))\n     \n--   in (lift $\n--       ((A.exp $ (-0.5) * (rho + r)) *\n--        (A.cos (phiFreq * phi  + thetaFreq * (theta - phi)))\n--       ) A.:+\n--       0) *\n--      (A.cis $ (-1) * ((rhoFreq * rho + rFreq * (r - rho)\n--                       ) -- * (2 * A.pi) / (A.exp halfLogPeriod) \n--                       -- + phiFreq * phi  + thetaFreq * (theta - phi)\n--                      ))\n--      -- (lift $ ((A.cos (phiFreq * phi + thetaFreq * (theta - phi) / 2))) A.:+ 0) *\n--      -- (A.cis $ (-2 * A.pi) * (rhoFreq * rho + rFreq * (r - rho)) / (A.exp halfLogPeriod))\n--      -- ((lift $ rho A.:+ 0) A.** (lift $ (-0.5) A.:+ (rFreq - rhoFreq))) *\n--      -- ((lift $ r A.:+ 0) A.** (lift $ (-0.5) A.:+ (-rFreq)))\n--      -- (A.cis $ (-A.pi) * (rhoFreq * rho + rFreq * (r - rho)\n--      --                        ) / (halfLogPeriod))\n--      -- (A.cis $\n--      --  (-A.pi) * (rhoFreq * (A.log rho) + rFreq * (A.log (r / rho))) /\n--      --  halfLogPeriod)\n--   -- in ((lift $ rho A.:+ 0) A.**\n--   --     (lift $ 0 A.:+ (-A.pi) * (rhoFreq - rFreq) / halfLogPeriod)) *\n--   --    ((lift $ r A.:+ 0) A.** (lift $ 0 A.:+ (-A.pi) * rFreq / halfLogPeriod)) *\n--   --    (A.cis $ (-phiFreq) * phi - thetaFreq * (theta - phi))\n  \ncoefficient ::\n     forall a. (A.Floating a, A.Num a, A.RealFloat a, A.Elt (Complex a), Prelude.Fractional a)\n  => Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp (a, a, a, a)\n  -> Exp (A.Complex a)\ncoefficient halfLogPeriod rFreq thetaFreq rhoFreq phiFreq particle =\n  let (phi, rho, theta, r) = unlift particle :: (Exp a, Exp a, Exp a, Exp a)\n  in (lift $\n      ((A.exp $ (-0.5) * (rho + r)) *\n       (A.cos (phiFreq * phi + thetaFreq * (theta - phi)))) A.:+\n      0) *\n     (A.cis $ (-1) * (rhoFreq * rho + rFreq * (r + rho)))\n\n-- {-# INLINE gpuKernel #-}\ngpuKernel ::\n     forall a. (A.Eq a, A.Floating a, A.Num a, A.RealFloat a, A.Elt (Complex a), A.FromIntegral Int a, Prelude.Fractional a)\n  => Exp a\n  -> Exp a\n  -> Exp (A.Complex a)\n  -> Acc (A.Vector (a, a, a, a))\n  -> Acc (A.Vector (a, a, a, a))\n  -> Acc (A.Vector (A.Complex a))\ngpuKernel !maxScaleExp !halfLogPeriodExp !deltaLogRhoComplexExp freqArr particles =\n  let -- delta = constant 0.01\n      movedParticleArr =\n        compute .\n        A.map\n          (\\particle ->\n             let (phi, rho, theta, r) =\n                   unlift particle :: (Exp a, Exp a, Exp a, Exp a)\n                 logRho = A.log rho \n                   -- (A.fromIntegral $\n                   --  (A.round (((A.log rho) + halfLogPeriodExp) / delta) :: Exp Int)) *\n                   -- delta -\n                   -- halfLogPeriodExp\n                 -- newRho =\n                 --   (A.fromIntegral $ (A.round (rho / delta) :: Exp Int)) * delta :: Exp a\n             in lift (phi, logRho, theta, (A.log r) :: Exp a)) -- .\n        -- afst .\n        -- A.filter\n        --   (\\particle ->\n        --      let (_, rho, _, _) =\n        --            unlift particle :: (Exp a, Exp a, Exp a, Exp a)\n        --      in rho A.> (A.constant 0) ) -- .\n        -- A.map moveParticle \n        $\n        particles\n  in A.map\n       (\\(unlift -> (rFreq, thetaFreq, rhoFreq, phiFreq))\n          -- (lift $ delta A.:+ 0) /\n          -- (lift $ (8 * A.pi * A.pi * halfLogPeriodExp) A.:+ 0) *\n         ->\n          (sfoldl\n             (\\s particle ->\n                s +\n                (coefficient\n                   halfLogPeriodExp\n                   rFreq\n                   thetaFreq\n                   rhoFreq\n                   phiFreq\n                   particle))\n             0\n             (constant Z)\n             movedParticleArr) * deltaLogRhoComplexExp\n          -- (lift $\n          --  (16 * A.pi * A.pi * halfLogPeriodExp * halfLogPeriodExp) A.:+ 0)\n             -- movedParticleArr\n        ) $\n     freqArr\n\n{-# INLINE convolveKernel #-}\nconvolveKernel ::\n     (A.Num a, A.RealFloat a, A.Elt (Complex a))\n  => Acc (Array DIM4 (Complex a))\n  -> Acc (Array DIM4 (Complex a))\n  -> Acc (Scalar Int)\n  -> Acc (Scalar Int)\n  -> Acc (Array DIM4 (Complex a))\n  -> Acc (Vector (Complex a))\nconvolveKernel coefficients harmonics thetaIdx rIdx input =\n  let (Z :. numRhoFreq :. numPhiFreq :. cols :. rows) =\n        unlift . shape $ input :: (Z :. Exp Int :. Exp Int :. Exp Int :. Exp Int)\n      coefficientsArr =\n        A.replicate (lift (Z :. All :. All :. cols :. rows)) .\n        slice coefficients $\n        (lift (Z :. (the rIdx) :. (the thetaIdx) :. All :. All))\n      harmonicsArr =\n        backpermute\n          (shape input)\n          (\\(unlift -> Z :. rho :. phi :. col :. row :: (Z :. Exp Int :. Exp Int :. Exp Int :. Exp Int)) ->\n             lift (Z :. (rho + the rIdx) :. (phi + the thetaIdx) :. col :. row))\n          harmonics\n  in flatten .\n     A.sum .\n     A.sum .\n     backpermute\n       (lift (Z :. cols :. rows :. numRhoFreq :. numPhiFreq))\n       (\\(unlift -> Z :. col :. row :. rho :. phi :: (Z :. Exp Int :. Exp Int :. Exp Int :. Exp Int)) ->\n          lift (Z :. rho :. phi :. col :. row)) .\n     A.zipWith (*) harmonicsArr . A.zipWith (*) coefficientsArr $\n     input\n\n\n{-# INLINE coefficient' #-}\ncoefficient' ::\n     forall a.\n     ( A.Floating a\n     , A.Num a\n     , A.RealFloat a\n     , A.Elt (Complex a)\n     , Prelude.Fractional a\n     )\n  => Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp (a, a, a, a, a)\n  -> Exp (A.Complex a)\ncoefficient' sigma rFreq thetaFreq rhoFreq phiFreq particle =\n  let (phi, rho, theta, r, v) =\n        unlift particle :: (Exp a, Exp a, Exp a, Exp a, Exp a)\n  in (lift $ (v * (A.exp $ (sigma - 1) * (rho + r))) A.:+ 0) *\n     (A.cis $\n      (-1) *\n      (rhoFreq * rho + rFreq * (r - rho) + phiFreq * phi +\n       thetaFreq * (theta - phi))) \n\ngpuKernel' ::\n     forall a.\n     ( A.Eq a\n     , A.Floating a\n     , A.Num a\n     , A.RealFloat a\n     , A.Elt (Complex a)\n     , A.FromIntegral Int a\n     , Prelude.Fractional a\n     )\n  => Exp a\n  -> Acc (A.Vector (a, a, a, a))\n  -> Acc (A.Vector (a, a, a, a, a))\n  -> Acc (A.Vector (A.Complex a))\ngpuKernel' sigma freqArr xs =\n  A.map\n    (\\(unlift -> (rFreq, thetaFreq, rhoFreq, phiFreq)) ->\n       A.sfoldl\n         (\\s particle ->\n            s + (coefficient' sigma rFreq thetaFreq rhoFreq phiFreq particle))\n         0\n         (constant Z)\n         xs)\n    freqArr\n    \n\n{-# INLINE coefficient'' #-}\ncoefficient'' ::\n     forall a.\n     ( A.Floating a\n     , A.Num a\n     , A.RealFloat a\n     , A.Elt (Complex a)\n     , Prelude.Fractional a\n     )\n  => Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp (a, a, a, a, a)\n  -> Exp (A.Complex a)\ncoefficient'' sigma period rFreq thetaFreq rhoFreq phiFreq particle =\n  let (phi, rho, theta, r, v) =\n        unlift particle :: (Exp a, Exp a, Exp a, Exp a, Exp a)\n   in lift\n        ((v * A.exp ((sigma - 1) * rho) *\n          A.cos (phiFreq * phi + thetaFreq * (theta - phi))\n         ) :+\n         0) *\n      A.cis ((-1) * (2 * A.pi / period * (rhoFreq * rho + rFreq * (r - rho)))) \n\n\ngpuKernel'' ::\n     forall a.\n     ( A.Eq a\n     , A.Floating a\n     , A.Num a\n     , A.RealFloat a\n     , A.Elt (Complex a)\n     , A.FromIntegral Int a\n     , Prelude.Fractional a\n     )\n  => Exp a\n  -> Exp a\n  -> Acc (A.Vector (a, a, a, a))\n  -> Acc (A.Vector (a, a, a, a, a))\n  -> Acc (A.Vector (A.Complex a))\ngpuKernel'' sigma period freqArr xs =\n  A.map\n    (\\(unlift -> (rFreq, thetaFreq, rhoFreq, phiFreq)) ->\n       A.sfoldl\n         (\\s particle ->\n            s +\n            coefficient'' sigma period rFreq thetaFreq rhoFreq phiFreq particle)\n         0\n         (constant Z)\n         xs)\n    freqArr\n    \n\n{-# INLINE pinwheelAcc #-}\npinwheelAcc ::\n     forall a. (A.Floating a, A.Num a, A.RealFloat a, A.Elt (Complex a), Prelude.Fractional a)\n  => Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp a\n  -> Exp (a, a, a, a, A.Complex a)\n  -> Exp (A.Complex a)\npinwheelAcc rFreq thetaFreq rhoFreq phiFreq particle =\n  let (phi, rho, theta, r, v) =\n        unlift particle :: (Exp a, Exp a, Exp a, Exp a, Exp (A.Complex a))\n  in v * (lift $ ((A.exp $ (-0.5) * (rho + r))) A.:+ 0) *\n     (A.cis $\n      (-1) *\n      (rhoFreq * rho + rFreq * (r - rho) + phiFreq * phi +\n       thetaFreq * (theta - phi))) \n\npinwheelCoefficientsAcc ::\n     forall a.\n     ( A.Eq a\n     , A.Floating a\n     , A.Num a\n     , A.RealFloat a\n     , A.Elt (Complex a)\n     , A.FromIntegral Int a\n     , Prelude.Fractional a\n     )\n  => Acc (A.Vector (a, a, a, a))\n  -> Acc (A.Vector (a, a, a, a, A.Complex a))\n  -> Acc (A.Vector (A.Complex a))\npinwheelCoefficientsAcc freqArr xs =\n  A.map\n    (\\(unlift -> (rFreq, thetaFreq, rhoFreq, phiFreq)) ->\n       A.sfoldl\n         (\\s particle ->\n            s + (pinwheelAcc rFreq thetaFreq rhoFreq phiFreq particle))\n         0\n         (constant Z)\n         xs)\n    freqArr\n", "meta": {"hexsha": "df09a2feed11b2ce2d076d2a03da729cc97b4b38", "size": 11007, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/GPUKernel.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/GPUKernel.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/GPUKernel.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 32.3735294118, "max_line_length": 124, "alphanum_fraction": 0.4887798674, "num_tokens": 3548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4084384567450589}}
{"text": "{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, DeriveGeneric #-}\n\nmodule BayesStack.Models.Topic.SharedTaste\n  ( -- * Primitives\n    STData(..)\n  , ItemSource(..)\n  , Node(..), Item(..), Topic(..)\n  , NodeItem, setupNodeItems\n  , Friendship(..), otherFriend, isFriend, getFriends\n    -- * Initialization\n  , ModelInit\n  , randomInitialize, smartInitialize\n    -- * Model\n  , STModel(..), ItemUnit\n  , model, modelLikelihood\n  , STModelState (..), getModelState\n  , sortTopics\n  , ItemVars(..)\n    -- * Quantities of interest\n  , friendInfluence\n  , theta\n  ) where\n\nimport Prelude hiding (mapM, sum, product)\n\nimport Data.EnumMap (EnumMap)\nimport qualified Data.EnumMap as EM\n\nimport Data.Sequence (Seq)\nimport qualified Data.Sequence as SQ\n\nimport Data.Set (Set)\nimport qualified Data.Set as S\n\nimport qualified Data.EnumSet as ES\nimport qualified Data.Vector as V\n\nimport Data.Traversable\nimport Data.Foldable\nimport Data.Monoid\nimport Data.Function (on)\nimport Data.List (sortBy)\n\nimport Control.Monad (liftM)\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\n\nimport Data.Random\nimport Data.Random.Distribution.Bernoulli\nimport Data.Random.Sequence\nimport Data.Number.LogFloat hiding (realToFrac)\n\nimport BayesStack.Core\nimport BayesStack.Categorical\nimport BayesStack.DirMulti\nimport BayesStack.TupleEnum\nimport BayesStack.Models.Topic.Types\n\nimport Control.Monad (when)\nimport Control.Monad.IO.Class\n\nimport Statistics.Sample\nimport Data.Serialize (Serialize)\nimport GHC.Generics\n\ndata ItemSource = Shared | Own deriving (Show, Eq, Generic, Enum, Ord)\ninstance Serialize ItemSource\n\ndata STData = STData { stAlphaGammaShared, stAlphaGammaOwn :: Double\n                     , stAlphaOmega :: Double\n                     , stAlphaPsi :: Double\n                     , stAlphaLambda :: Double\n                     , stAlphaPhi :: Double\n                     , stNodes :: Set Node\n                     , stFriendships :: Set Friendship\n                     , stItems :: Set Item\n                     , stTopics :: Set Topic\n                     , stNodeItems :: EnumMap NodeItem (Node, Item)\n                     }\n               deriving (Show, Eq, Generic)\ninstance Serialize STData\n\ndata ItemVars = ItemVars { ivS :: !ItemSource\n                         , ivF :: !Node\n                         , ivT :: !Topic\n                         }\n                deriving (Show, Eq, Generic)\ninstance Serialize ItemVars\n\ndata STModel = STModel { mData :: STData\n                       , mGammas :: SharedEnumMap Node (Multinom ItemSource)\n                       , mOmegas :: SharedEnumMap Node (Multinom Topic)\n                       , mPsis :: SharedEnumMap Node (Multinom Node)\n                       , mLambdas :: SharedEnumMap Friendship (Multinom Topic)\n                       , mPhis :: SharedEnumMap Topic (Multinom Item)\n                       , mVars :: SharedEnumMap NodeItem ItemVars\n                       , mSortedTopics :: SharedEnumMap Item [Topic]\n                       }\n\ndata STModelState = STModelState { msData :: STData\n                                 , msGammas :: EnumMap Node (Multinom ItemSource)\n                                 , msOmegas :: EnumMap Node (Multinom Topic)\n                                 , msPsis :: EnumMap Node (Multinom Node)\n                                 , msLambdas :: EnumMap Friendship (Multinom Topic)\n                                 , msPhis :: EnumMap Topic (Multinom Item)\n                                 , msVars :: EnumMap NodeItem ItemVars\n                                 , msLogLikelihood :: Double\n                                 } deriving (Show, Generic)\ninstance Serialize STModelState\n\ntype ModelInit = EnumMap NodeItem ItemVars\n\nrandomInitialize' :: STData -> ModelInit -> RVar ModelInit\nrandomInitialize' d init = \n  let unset = EM.keysSet (stNodeItems d) `ES.difference` EM.keysSet init\n      topics = S.toList $ stTopics d\n      randomInit :: NodeItem -> RVar ModelInit\n      randomInit ni = do t <- randomElement topics\n                         let (n,_) = EM.findWithDefault (error \"Can't find nodeItem\") ni (stNodeItems d)\n                             friends = getFriends (S.toList $ stFriendships d) n\n                         f <- randomElement friends\n                         s <- bernoulli $ stAlphaGammaShared d\n                         let s' = case s of\n                                        True  -> Shared\n                                        False -> Own\n                         return $ EM.singleton ni $ ItemVars s' f t\n  in liftM ((init `mappend`) . mconcat) $ forM (ES.toList unset) randomInit\n\nrandomInitialize :: STData -> RVar ModelInit\nrandomInitialize = (flip randomInitialize') EM.empty\n\nsmartInitialize :: STData -> RVar ModelInit\nsmartInitialize d =\n  let STData {stTopics=topics, stNodes=nodes, stItems=items, stNodeItems=nodeItems} = d\n      STData {stFriendships=friendships, stNodeItems=nis} = d\n      nisInv :: EnumMap (Node,Item) [NodeItem]\n      nisInv = EM.fromListWith (++) $ map (\\(ni,(n,i))->((n,i),[ni])) $ EM.toList nis\n\n      sharedTopics :: Friendship -> StateT (EnumMap Item Topic, EnumMap Friendship (Set Topic)) RVar ModelInit\n      sharedTopics fs@(Friendship (a,b)) =\n        let findItems n = S.fromList $ map snd $ filter (\\(n',i)->n==n') $ toList nodeItems\n            sharedItems = toList $ S.intersection (findItems a) (findItems b)\n        in liftM mconcat $ forM sharedItems $ \\x -> do\n             (itemTopics,_) <- get\n             t <- if x `EM.member` itemTopics\n                    then return $ EM.findWithDefault (error \"Item has no topic\") x itemTopics\n                    else do (_, friendshipTopics) <- get\n                            --let possTopics = EM.findWithDefault topics fs friendshipTopics\n                            let possTopics = topics -- FIXME\n                            t <- lift $ randomElement $ S.toList possTopics\n                            modify $ \\(a,b)->(EM.insert x t a, b)\n                            return t\n             modify $ \\(a,b)->(a, EM.insertWith S.union fs (S.singleton t) b)\n             return $ EM.fromList $ do ax <- EM.findWithDefault (error \"ouch\") (a,x) nisInv\n                                       return (ax, ItemVars Shared b t)\n                                 ++ do bx <- EM.findWithDefault (error \"ouch\") (b,x) nisInv\n                                       return (bx, ItemVars Shared a t)\n  in do a <- evalStateT (mapM sharedTopics $ S.toList friendships) (EM.empty, EM.empty)\n        randomInitialize' d $ mconcat a\n\ndata ItemUnit = ItemUnit { iuModel :: STModel\n                         , iuNodeItem :: NodeItem\n                         , iuFriends :: Set Node\n                         , iuN :: Node\n                         , iuVars :: Shared ItemVars\n                         , iuX :: Item\n                         , iuGamma :: Shared (Multinom ItemSource)\n                         , iuOmega :: Shared (Multinom Topic)\n                         , iuLambdas :: SharedEnumMap Friendship (Multinom Topic)\n                         , iuPhis :: SharedEnumMap Topic (Multinom Item)\n                         , iuState :: Shared GibbsUpdateState\n                         }\n\nmodel :: STData -> ModelInit -> ModelMonad (Seq ItemUnit, STModel)\nmodel d init =\n  do let STData {stTopics=topics, stNodes=nodes, stItems=items, stNodeItems=nis} = d\n         STData {stFriendships=friendships} = d\n         friends :: EnumMap Node (Set Node)\n         friends = foldMap (\\n->EM.singleton n $ S.fromList $ getFriends (S.toList friendships) n) nodes\n     gammas <- newSharedEnumMap (S.toList nodes) $ \\n ->\n       --return $ dirMulti [ (Shared, stAlphaGammaShared d)\n       --                  , (Own, stAlphaGammaOwn d) ]\n       return $ multinom [ (Shared, stAlphaGammaShared d)\n                         , (Own, stAlphaGammaOwn d) ]\n     omegas <- newSharedEnumMap (S.toList nodes) $ \\n ->\n       return $ symDirMulti (stAlphaOmega d) (S.toList topics)\n     psis <- newSharedEnumMap (S.toList nodes) $ \\n ->\n       return $ symDirMulti (stAlphaPsi d) (S.toList nodes)\n     lambdas <- newSharedEnumMap (S.toList friendships) $ \\n ->\n       return $ symDirMulti (stAlphaLambda d) (S.toList topics)\n     phis <- newSharedEnumMap (S.toList topics) $ \\t ->\n       return $ symDirMulti (stAlphaPhi d) (S.toList items)\n\n     ivs <- newSharedEnumMap (EM.keys nis) $ \\ni ->\n       return $ EM.findWithDefault (error \"Incomplete initialization\") ni init\n  \n     sortedTopics <- newSharedEnumMap (S.toList items) $ \\x -> return $ S.toList topics\n\n     let model = STModel { mData = d\n                         , mGammas = gammas\n                         , mOmegas = omegas\n                         , mPsis = psis\n                         , mLambdas = lambdas\n                         , mPhis = phis\n                         , mVars = ivs\n                         , mSortedTopics = sortedTopics\n                         }\n\n     itemUnits <- forM (EM.toList ivs) $ \\(ni,iv) ->\n       do state <- newGibbsUpdateState\n          let (n,x) = nis EM.! ni\n          let unit = ItemUnit { iuModel = model\n                              , iuNodeItem = ni\n                              , iuFriends = friends EM.! n\n                              , iuN = n\n                              , iuVars = iv\n                              , iuX = x\n                              , iuGamma = gammas EM.! n\n                              , iuOmega = omegas EM.! n\n                              , iuLambdas = EM.filterWithKey (\\k _->isFriend n k) lambdas\n                              , iuPhis = phis\n                              , iuState = state\n                              }\n          getShared iv >>= guSet unit\n          return unit\n     return (SQ.fromList itemUnits, model)\n\nsortTopics :: STModel -> ModelMonad ()\nsortTopics model =\n  forM_ (EM.toList $ mSortedTopics model) $ \\(x,topics)->do\n    d <- getShared topics\n    weights <- forM d $ \\t->do phi <- getShared $ mPhis model EM.! t\n                               return $ sampleProb phi x -- FIXME\n    setShared topics $ map snd $ sortBy (flip (compare `on` fst)) $ zip weights d\n\nmodelLikelihood :: STModelState -> Probability\nmodelLikelihood model =\n  product $ map likelihood (EM.elems $ msGammas model)\n         ++ map likelihood (EM.elems $ msPhis model)\n         ++ map likelihood (EM.elems $ msLambdas model)\n         ++ map likelihood (EM.elems $ msOmegas model)\n         ++ map likelihood (EM.elems $ msPsis model)\n\ninstance GibbsUpdateUnit ItemUnit where\n  type GUValue ItemUnit = ItemVars\n  guProb unit (ItemVars s f t) =\n    do gamma <- getShared $ iuGamma unit\n       omega <- getShared $ iuOmega unit\n       psi <- getShared $ mPsis (iuModel unit) EM.! iuN unit\n       phi <- getShared $ iuPhis unit EM.! t \n       lambda <- getShared $ iuLambdas unit EM.! Friendship (iuN unit, f)\n       case s of\n            Shared -> return $ sampleProb gamma s\n                             * sampleProb psi f\n                             * sampleProb lambda t\n                             * sampleProb phi (iuX unit) \n            Own -> return $ sampleProb gamma s\n                          * sampleProb omega t\n                          * sampleProb phi (iuX unit)\n  \n  guDomain unit = return $ (do t <- S.toList $ stTopics $ mData $ iuModel unit\n                               f <- S.toList $ iuFriends unit\n                               return $ ItemVars Shared f t)\n                        ++ (do t <- S.toList $ stTopics $ mData $ iuModel unit\n                               let f = head $ S.toList $ iuFriends unit\n                               return $ ItemVars Own f t)\n  \n  guUnset unit =\n    do ItemVars s f t <- getShared $ iuVars unit\n       let x = iuX unit\n           u = iuN unit\n           m = iuModel unit\n           gamma = iuGamma unit\n           omega = iuOmega unit\n           lambda = iuLambdas unit EM.! Friendship (iuN unit, f)\n           phi = iuPhis unit EM.! t\n       gamma `updateShared` decMultinom s\n       case s of\n            Shared -> do (mPsis m EM.! u) `updateShared` decMultinom f\n                         (mPsis m EM.! f) `updateShared` decMultinom u\n                         lambda `updateShared` decMultinom t\n            Own -> omega `updateShared` decMultinom t\n       phi `updateShared` decMultinom x\n       return $ ItemVars s f t\n  \n  guSet unit iv@(ItemVars s f t) =\n    do iuVars unit `setShared` iv\n       let x = iuX unit\n           u = iuN unit\n           m = iuModel unit\n           gamma = iuGamma unit\n           omega = iuOmega unit\n           lambda = iuLambdas unit EM.! Friendship (iuN unit, f)\n           phi = iuPhis unit EM.! t\n       gamma `updateShared` incMultinom s\n       case s of\n            Shared -> do (mPsis m EM.! u) `updateShared` incMultinom f\n                         (mPsis m EM.! f) `updateShared` incMultinom u\n                         lambda `updateShared` incMultinom t\n            Own -> omega `updateShared` incMultinom t\n       phi `updateShared` incMultinom x\n\n  guState = iuState\n\ngetModelState :: STModel -> ModelMonad STModelState\ngetModelState model =\n  do gammas <- getSharedEnumMap $ mGammas model\n     omegas <- getSharedEnumMap $ mOmegas model\n     psis <- getSharedEnumMap $ mPsis model\n     lambdas <- getSharedEnumMap $ mLambdas model\n     phis <- getSharedEnumMap $ mPhis model\n     vars <- getSharedEnumMap $ mVars model\n     let state = STModelState { msData = mData model\n                              , msGammas = gammas\n                              , msOmegas = omegas\n                              , msPsis = psis\n                              , msLambdas = lambdas\n                              , msPhis = phis\n                              , msVars = vars\n                              , msLogLikelihood = logFromLogFloat $ modelLikelihood state\n                              }\n     return state\n\n-- | The analogue of theta in LDA\ntheta :: STModelState -> Node -> Topic -> Double\ntheta state u t =\n  sampleProb gamma Own * sampleProb omega t\n  + sampleProb gamma Shared\n  * sum (map (\\f->let lambda = msLambdas state EM.! Friendship (u,f)\n                  in sampleProb psi f * sampleProb lambda t\n             )\n         $ getFriends (S.toList $ stFriendships $ msData state) u\n        )\n  where psi = msPsis state EM.! u\n        gamma = msGammas state EM.! u\n        omega = msOmegas state EM.! u\n\nfriendInfluence :: STModelState -> Node -> Node -> Double\nfriendInfluence state u f =\n  let lambda = msLambdas state EM.! Friendship(u,f)\n      vars = map snd\n             $ filter (\\(ni,iv)->let (u',x) = stNodeItems (msData state) EM.! ni in u==u')\n             $ EM.assocs $ msVars state\n      tProbF = map (realToFrac . sampleProb lambda . ivT) vars\n  in case tProbF of\n       [] -> error \"friendInfluence: vars is null\"\n       otherwise -> geometricMean $ V.fromList tProbF\n\n", "meta": {"hexsha": "16449a494e7d8a8eb02a91f14c8c540b888ca0e4", "size": 14824, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "BayesStack/Models/Topic/SharedTaste.hs", "max_stars_repo_name": "laura-dietz/bayes-stack", "max_stars_repo_head_hexsha": "decf3722ea1b66e6ac6c0b514d2c5dbc7a67f0f8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-24T16:08:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-24T16:08:58.000Z", "max_issues_repo_path": "BayesStack/Models/Topic/SharedTaste.hs", "max_issues_repo_name": "laura-dietz/bayes-stack", "max_issues_repo_head_hexsha": "decf3722ea1b66e6ac6c0b514d2c5dbc7a67f0f8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BayesStack/Models/Topic/SharedTaste.hs", "max_forks_repo_name": "laura-dietz/bayes-stack", "max_forks_repo_head_hexsha": "decf3722ea1b66e6ac6c0b514d2c5dbc7a67f0f8", "max_forks_repo_licenses": ["BSD-3-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.4756446991, "max_line_length": 110, "alphanum_fraction": 0.5466135996, "num_tokens": 3574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.40840532316265055}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule Math.HiddenMarkovModel (\n   T(..), Distr.State, state,\n   Discrete, DiscreteTrained,\n   Gaussian, GaussianTrained,\n   uniform,\n   generate,\n   probabilitySequence,\n   Normalized.logLikelihood,\n   Normalized.reveal,\n   Normalized.posterior,\n\n   Trained(..),\n   trainSupervised,\n   Normalized.trainUnsupervised,\n   mergeTrained, finishTraining, trainMany,\n   deviation,\n\n   toCSV,\n   fromCSV,\n   ) where\n\nimport qualified Math.HiddenMarkovModel.Distribution as Distr\nimport qualified Math.HiddenMarkovModel.Normalized as Normalized\nimport qualified Math.HiddenMarkovModel.CSV as HMMCSV\nimport Math.HiddenMarkovModel.Private\n          (T(..), Trained(..), mergeTrained, toCells, parseCSV)\nimport Math.HiddenMarkovModel.Distribution (State(State))\nimport Math.HiddenMarkovModel.Utility\n          (randomItemProp, normalizeProb, attachOnes)\n\nimport qualified Numeric.LinearAlgebra.Algorithms as Algo\nimport qualified Numeric.Container as NC\nimport qualified Data.Packed.Matrix as Matrix\nimport qualified Data.Packed.Vector as Vector\nimport Data.Packed.Matrix (Matrix)\nimport Data.Packed.Vector (Vector)\n\nimport qualified Text.CSV.Lazy.String as CSV\n\nimport qualified System.Random as Rnd\n\nimport qualified Control.Monad.Exception.Synchronous as ME\nimport qualified Control.Monad.Trans.State as MS\nimport qualified Control.Monad.HT as Monad\n\nimport qualified Data.NonEmpty as NonEmpty\nimport qualified Data.Array as Array\nimport Data.Traversable (Traversable, mapAccumL)\nimport Data.Foldable (Foldable)\nimport Data.Array (accumArray)\n\n\n\nstate :: Int -> State\nstate = State\n\n\ntype DiscreteTrained prob symbol = Trained (Distr.DiscreteTrained prob symbol) prob\ntype Discrete prob symbol = T (Distr.Discrete prob symbol) prob\n\ntype GaussianTrained a = Trained (Distr.GaussianTrained a) a\ntype Gaussian a = T (Distr.Gaussian a) a\n\n\n{- |\nCreate a model with uniform probabilities\nfor initial vector and transition matrix\ngiven a distribution for the emissions.\nYou can use this as a starting point for 'Normalized.trainUnsupervised'.\n-}\nuniform ::\n   (Distr.Info distr, Distr.Probability distr ~ prob) =>\n   distr -> T distr prob\nuniform distr =\n   let n = Distr.numberOfStates distr\n       c = recip $ fromIntegral n\n   in  Cons {\n          initial = NC.constant c n,\n          transition = NC.konst c (n,n),\n          distribution = distr\n       }\n\n\nprobabilitySequence ::\n   (Traversable f, Distr.EmissionProb distr,\n    Distr.Probability distr ~ prob, Distr.Emission distr ~ emission) =>\n   T distr prob -> f (State, emission) -> f prob\nprobabilitySequence hmm =\n   snd\n   .\n   mapAccumL\n      (\\index (State s, e) ->\n         (NC.atIndex (transition hmm) . flip (,) s,\n          index s * Distr.emissionStateProb (distribution hmm) e (State s)))\n      (NC.atIndex (initial hmm))\n\ngenerate ::\n   (Rnd.RandomGen g, Ord prob, Rnd.Random prob,\n    Distr.Generate distr, Distr.Probability distr ~ prob, Distr.Emission distr ~ emission) =>\n   T distr prob -> g -> [emission]\ngenerate hmm =\n   MS.evalState $\n   flip MS.evalStateT (initial hmm) $\n   Monad.repeat $ MS.StateT $ \\v0 -> do\n      s <- randomItemProp $ zip [0..] (Vector.toList v0)\n      x <- Distr.generate (distribution hmm) (State s)\n      return (x, takeColumn s $ transition hmm)\n\ntakeColumn :: (Matrix.Element a) => Int -> Matrix a -> Vector a\ntakeColumn n  =  Matrix.flatten . Matrix.extractColumns [n]\n\n\n\n{- |\nContribute a manually labeled emission sequence to a HMM training.\n-}\ntrainSupervised ::\n   (Distr.Estimate tdistr, Distr.Distribution tdistr ~ distr,\n    Distr.Probability distr ~ prob, Distr.Emission distr ~ emission) =>\n   Int -> NonEmpty.T [] (State, emission) -> Trained tdistr prob\ntrainSupervised n xs =\n   let getState (State s, _x) = s\n   in  Trained {\n          trainedInitial = NC.assoc n 0 [(getState (NonEmpty.head xs), 1)],\n          trainedTransition =\n             Matrix.trans $ NC.accum (NC.konst 0 (n,n)) (+) $\n             attachOnes $ NonEmpty.mapAdjacent (,) $ fmap getState xs,\n          trainedDistribution =\n             Distr.accumulateEmissions $ map attachOnes $ Array.elems $\n             accumArray (flip (:)) [] (State 0, State (n-1)) $ NonEmpty.flatten xs\n       }\n\nfinishTraining ::\n   (Distr.Estimate tdistr, Distr.Distribution tdistr ~ distr,\n    Distr.Probability distr ~ prob) =>\n   Trained tdistr prob -> T distr prob\nfinishTraining hmm =\n   Cons {\n      initial = normalizeProb $ trainedInitial hmm,\n      transition =\n         Matrix.fromColumns $ map normalizeProb $\n         Matrix.toColumns $ trainedTransition hmm,\n      distribution = Distr.normalize $ trainedDistribution hmm\n   }\n\ntrainMany ::\n   (Distr.Estimate tdistr, Distr.Distribution tdistr ~ distr,\n    Distr.Probability distr ~ prob,\n    Foldable f) =>\n   (trainingData -> Trained tdistr prob) ->\n   NonEmpty.T f trainingData -> T distr prob\ntrainMany train =\n   finishTraining . NonEmpty.foldl1Map mergeTrained train\n\n\n\n\n\n{- |\nCompute maximum deviation between initial and transition probabilities.\nYou can use this as abort criterion for unsupervised training.\nWe omit computation of differences between the emission probabilities.\nThis simplifies matters a lot and\nshould suffice for defining an abort criterion.\n-}\ndeviation ::\n   (Algo.Field prob, Ord prob) => T distr prob -> T distr prob -> prob\ndeviation hmm0 hmm1 =\n   deviationVec (initial hmm0) (initial hmm1)\n   `max`\n   deviationVec (transition hmm0) (transition hmm1)\n\ndeviationVec ::\n   (Ord a, NC.Container c a) =>\n   c a -> c a -> a\ndeviationVec x y =\n   let d = NC.sub x y\n   in  NC.maxElement d `max` negate (NC.minElement d)\n\n\ntoCSV ::\n   (Distr.CSV distr, Algo.Field prob, Show prob) =>\n   T distr prob -> String\ntoCSV hmm =\n   CSV.ppCSVTable $ snd $ CSV.toCSVTable $ HMMCSV.padTable \"\" $\n   toCells hmm\n\nfromCSV ::\n   (Distr.CSV distr, Algo.Field prob, Read prob) =>\n   String -> ME.Exceptional String (T distr prob)\nfromCSV =\n   MS.evalStateT parseCSV . map HMMCSV.fixShortRow . CSV.parseCSV\n", "meta": {"hexsha": "eaed178fe695dc316250faa5af557ac81b3498ab", "size": 6008, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/HiddenMarkovModel.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.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.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": 30.8102564103, "max_line_length": 93, "alphanum_fraction": 0.7050599201, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.4083930305107967}}
{"text": "{-# LANGUAGE BangPatterns          #-}\n{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE TupleSections         #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE FlexibleContexts      #-}\n\nimport           Control.Applicative\nimport           Control.Monad\nimport           Control.Monad.Random\nimport           Control.Monad.Trans.Except\n\nimport qualified Data.Attoparsec.Text as A\nimport           Data.List ( foldl' )\n#if ! MIN_VERSION_base(4,13,0)\nimport           Data.Semigroup ( (<>) )\n#endif\n\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\nimport qualified Data.Vector.Storable as V\n\nimport           Numeric.LinearAlgebra ( maxIndex )\nimport qualified Numeric.LinearAlgebra.Static as SA\n\nimport           Options.Applicative\n\nimport           Grenade\nimport           Grenade.Utils.OneHot\n\n-- It's logistic regression!\n--\n-- This network is used to show how we can embed a Network as a layer in the larger MNIST\n-- type.\ntype FL i o =\n  Network\n    '[ FullyConnected i o, Logit ]\n    '[ 'D1 i, 'D1 o, 'D1 o ]\n\n-- The definition of our convolutional neural network.\n-- In the type signature, we have a type level list of shapes which are passed between the layers.\n-- One can see that the images we are inputing are two dimensional with 28 * 28 pixels.\n\n-- It's important to keep the type signatures, as there's many layers which can \"squeeze\" into the gaps\n-- between the shapes, so inference can't do it all for us.\n\n-- With the mnist data from Kaggle normalised to doubles between 0 and 1, learning rate of 0.01 and 15 iterations,\n-- this network should get down to about a 1.3% error rate.\n--\n-- /NOTE:/ This model is actually too complex for MNIST, and one should use the type given in the readme instead.\n--         This one is just here to demonstrate Inception layers in use.\n--\ntype MNIST =\n  Network\n    '[ Reshape,\n       Concat ('D3 28 28 1) Trivial ('D3 28 28 14) (InceptionMini 28 28 1 5 9),\n       Pooling 2 2 2 2, Relu,\n       Concat ('D3 14 14 3) (Convolution 15 3 1 1 1 1) ('D3 14 14 15) (InceptionMini 14 14 15 5 10), Crop 1 1 1 1, Pooling 3 3 3 3, Relu,\n       Reshape, FL 288 80, FL 80 10 ]\n    '[ 'D2 28 28, 'D3 28 28 1,\n       'D3 28 28 15, 'D3 14 14 15, 'D3 14 14 15, 'D3 14 14 18,\n       'D3 12 12 18, 'D3 4 4 18, 'D3 4 4 18,\n       'D1 288, 'D1 80, 'D1 10 ]\n\nrandomMnist :: MonadRandom m => m MNIST\nrandomMnist = randomNetwork\n\nconvTest :: Int -> FilePath -> FilePath -> LearningParameters -> ExceptT String IO ()\nconvTest iterations trainFile validateFile rate = do\n  net0         <- lift randomMnist\n  trainData    <- readMNIST trainFile\n  validateData <- readMNIST validateFile\n  lift $ foldM_ (runIteration trainData validateData) net0 [1..iterations]\n\n    where\n  trainEach rate' !network (i, o) = train rate' network i o\n\n  runIteration trainRows validateRows net i = do\n    let trained' = foldl' (trainEach ( rate { learningRate = learningRate rate * 0.9 ^ i} )) net trainRows\n    let res      = fmap (\\(rowP,rowL) -> (rowL,) $ runNet trained' rowP) validateRows\n    let res'     = fmap (\\(S1D label, S1D prediction) -> (maxIndex (SA.extract label), maxIndex (SA.extract prediction))) res\n    print trained'\n    putStrLn $ \"Iteration \" ++ show i ++ \": \" ++ show (length (filter ((==) <$> fst <*> snd) res')) ++ \" of \" ++ show (length res')\n    return trained'\n\ndata MnistOpts = MnistOpts FilePath FilePath Int LearningParameters\n\nmnist' :: Parser MnistOpts\nmnist' = MnistOpts <$> argument str (metavar \"TRAIN\")\n                   <*> argument str (metavar \"VALIDATE\")\n                   <*> option auto (long \"iterations\" <> short 'i' <> value 15)\n                   <*> (LearningParameters\n                       <$> option auto (long \"train_rate\" <> short 'r' <> value 0.01)\n                       <*> option auto (long \"momentum\" <> value 0.9)\n                       <*> option auto (long \"l2\" <> value 0.0005)\n                       )\n\nmain :: IO ()\nmain = do\n    MnistOpts mnist vali iter rate <- execParser (info (mnist' <**> helper) idm)\n    putStrLn \"Training convolutional neural network...\"\n\n    res <- runExceptT $ convTest iter mnist vali rate\n    case res of\n      Right () -> pure ()\n      Left err -> putStrLn err\n\nreadMNIST :: FilePath -> ExceptT String IO [(S ('D2 28 28), S ('D1 10))]\nreadMNIST mnist = ExceptT $ do\n  mnistdata <- T.readFile mnist\n  return $ traverse (A.parseOnly parseMNIST) (T.lines mnistdata)\n\nparseMNIST :: A.Parser (S ('D2 28 28), S ('D1 10))\nparseMNIST = do\n  Just lab <- oneHot <$> A.decimal\n  pixels   <- many (A.char ',' >> A.double)\n  image    <- maybe (fail \"Parsed row was of an incorrect size\") pure (fromStorable . V.fromList $ pixels)\n  return (image, lab)\n", "meta": {"hexsha": "28be8cd86f8f0bbdf51b6f36955c7ff5b29e41d8", "size": 4792, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/main/mnist.hs", "max_stars_repo_name": "claudeha/grenade", "max_stars_repo_head_hexsha": "80b32d617eb8cce0bdb5478873d46d52dc2ed131", "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": "examples/main/mnist.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": "examples/main/mnist.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": 39.6033057851, "max_line_length": 137, "alphanum_fraction": 0.6308430718, "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.40826416137260946}}
{"text": "-- tiers.hs -- prints tiers of values up to a certain point\n--\n-- Copyright (c) 2015-2018 Rudy Matela.\n-- Distributed under the 3-Clause BSD licence (see the file LICENSE).\nimport Test.LeanCheck\nimport Test.LeanCheck.Utils.Types\nimport Test.LeanCheck.Function ()\nimport Test.LeanCheck.Function.Eq ()\nimport Test.LeanCheck.Tiers (showTiers, finite)\nimport System.Environment\nimport Data.List (intercalate, nub)\nimport Data.Ratio ((%))\nimport Data.Int\nimport Data.Word\nimport Data.Complex\n\ndropEmptyTiersTail :: [[a]] -> [[a]]\ndropEmptyTiersTail ([]:[]:[]: []:[]:[]: _) = []\ndropEmptyTiersTail (xs:xss) = xs:dropEmptyTiersTail xss\ndropEmptyTiersTail []     = []\n\nlengthT :: [[a]] -> Maybe Int\nlengthT xss | finite xss' = Just . length $ concat xss'\n            | otherwise   = Nothing\n  where xss' = dropEmptyTiersTail xss\n\nallUnique :: Eq a => [a] -> Bool\nallUnique [] = True\nallUnique (x:xs) = x `notElem` xs\n                && allUnique (filter (/= x) xs)\n\ncountRepetitions :: Eq a => [a] -> Int\ncountRepetitions xs = length xs - length (nub xs)\n\nratioRepetitions :: Eq a => [a] -> Rational\nratioRepetitions [] = 0\nratioRepetitions xs = fromIntegral (countRepetitions xs) % fromIntegral (length xs)\n\nshowLengthT :: [[a]] -> String\nshowLengthT xss = case lengthT xss of\n                    Nothing -> \"Infinity\"\n                    Just x  -> show x\n\nshowDotsLongerThan :: Show a => Int -> [a] -> String\nshowDotsLongerThan n xs = \"[\"\n                       ++ intercalate \",\" (dotsLongerThan n $ map show xs)\n                       ++ \"]\"\n  where\n  dotsLongerThan n xs = take n xs ++ [\"...\" | not . null $ drop n xs]\n\nprintTiers :: Show a => Int -> [[a]] -> IO ()\nprintTiers n = putStrLn . init . unlines . map (\"  \" ++) . lines . showTiers n\n\nput :: (Show a, Eq a, Listable a) => String -> Int -> a -> IO ()\nput t n a = do\n  putStrLn $ \"map length (tiers :: [[ \" ++ t ++ \" ]])  =  \"\n          ++ showDotsLongerThan n (map length $ tiers `asTypeOf` [[a]])\n  putStrLn $ \"\"\n  putStrLn $ \"length (list :: [ \" ++ t ++ \" ])  =  \"\n          ++ showLengthT (tiers `asTypeOf` [[a]])\n  putStrLn $ \"\"\n  putStrLn $ \"allUnique (list :: [ \" ++ t ++ \" ])  =  \"\n          ++ show (allUnique . concat . take n $ tiers `asTypeOf` [[a]])\n  putStrLn $ \"\"\n  putStrLn $ \"ratioRepetitions (list :: [ \" ++ t ++ \" ])  =  \"\n          ++ show (ratioRepetitions . concat . take n $ tiers `asTypeOf` [[a]])\n  putStrLn $ \"\"\n  putStrLn $ \"tiers :: [\" ++ t ++ \"]  =\"\n  printTiers n $ tiers `asTypeOf` [[a]]\n\nu :: a\nu = undefined\n\nmain :: IO ()\nmain = do\n  as <- getArgs\n  let (t,n) = case as of\n              []      -> (\"Int\", 12)\n              [t]     -> (t,     12)\n              (t:n:_) -> (t, read n)\n  case t of\n    -- simple types\n    \"()\"               -> put t n (u :: ()                   )\n    \"Int\"              -> put t n (u :: Int                  )\n    \"Nat\"              -> put t n (u :: Nat                  )\n    \"Integer\"          -> put t n (u :: Integer              )\n    \"Bool\"             -> put t n (u :: Bool                 )\n    \"Char\"             -> put t n (u :: Char                 )\n    \"Float\"            -> put t n (u :: Float                )\n    \"Double\"           -> put t n (u :: Double               )\n    \"Rational\"         -> put t n (u :: Rational             )\n    -- fixed width integer types\n    \"Nat2\"             -> put t n (u :: Nat2                 )\n    \"Nat3\"             -> put t n (u :: Nat3                 )\n    \"Nat4\"             -> put t n (u :: Nat4                 )\n    \"Word2\"            -> put t n (u :: Word2                )\n    \"Word3\"            -> put t n (u :: Word3                )\n    \"Word4\"            -> put t n (u :: Word4                )\n    \"Word8\"            -> put t n (u :: Word8                )\n    \"Word16\"           -> put t n (u :: Word16               )\n    \"Word32\"           -> put t n (u :: Word32               )\n    \"Word64\"           -> put t n (u :: Word64               )\n    \"Int2\"             -> put t n (u :: Int2                 )\n    \"Int3\"             -> put t n (u :: Int3                 )\n    \"Int4\"             -> put t n (u :: Int4                 )\n    \"Int8\"             -> put t n (u :: Int8                 )\n    \"Int16\"            -> put t n (u :: Int16                )\n    \"Int32\"            -> put t n (u :: Int32                )\n    \"Int64\"            -> put t n (u :: Int64                )\n    -- complex numbers\n    \"Complex Double\"   -> put t n (u :: Complex Double       )\n    -- lists\n    \"[()]\"             -> put t n (u :: [()]                 )\n    \"[Int]\"            -> put t n (u :: [Int]                )\n    \"[Nat]\"            -> put t n (u :: [Nat]                )\n    \"[Integer]\"        -> put t n (u :: [Integer]            )\n    \"[Bool]\"           -> put t n (u :: [Bool]               )\n    \"[Char]\"           -> put t n (u :: [Char]               )\n    \"String\"           -> put t n (u :: String               )\n    -- pairs\n    \"((),())\"          -> put t n (u :: ((),())              )\n    \"(Int,Int)\"        -> put t n (u :: (Int,Int)            )\n    \"(Nat,Nat)\"        -> put t n (u :: (Nat,Nat)            )\n    \"(Bool,Bool)\"      -> put t n (u :: (Bool,Bool)          )\n    \"(Bool,Int)\"       -> put t n (u :: (Bool,Int)           )\n    \"(Int,Bool)\"       -> put t n (u :: (Int,Bool)           )\n    \"(Int,Int,Int)\"    -> put t n (u :: (Int,Int,Int)        )\n    \"(Nat,Nat,Nat)\"    -> put t n (u :: (Nat,Nat,Nat)        )\n    -- lists & pairs\n    \"[((),())]\"        -> put t n (u :: [((),())]            )\n    \"([()],[()])\"      -> put t n (u :: ([()],[()])          )\n    \"([Bool],[Bool])\"  -> put t n (u :: ([Bool],[Bool])      )\n    \"([Int],[Int])\"    -> put t n (u :: ([Int],[Int])        )\n    -- lists of lists\n    \"[[Int]]\"          -> put t n (u :: [[Int]]              )\n    -- functions\n    \"()->()\"           -> put t n (u :: () -> ()             )\n    \"()->Bool\"         -> put t n (u :: () -> Bool           )\n    \"Bool->()\"         -> put t n (u :: Bool -> ()           )\n    \"Bool->Bool\"       -> put t n (u :: Bool -> Bool         )\n    \"Bool->Bool->Bool\" -> put t n (u :: Bool -> Bool -> Bool )\n    \"Int->Int\"         -> put t n (u :: Int -> Int           )\n    \"Int->Int->Int\"    -> put t n (u :: Int -> Int -> Int    )\n    \"()->Nat\"          -> put t n (u :: () -> Nat            )\n    \"Nat->()\"          -> put t n (u :: Nat -> ()            )\n    \"Nat->Nat\"         -> put t n (u :: Nat -> Nat           )\n    \"Nat->Nat->Nat\"    -> put t n (u :: Nat -> Nat -> Nat    )\n    \"(Nat,Nat)->Nat\"   -> put t n (u :: (Nat,Nat) -> Nat     )\n    \"Bool->Maybe Bool\" -> put t n (u :: Bool -> Maybe Bool   )\n    \"Maybe Bool->Bool\" -> put t n (u :: Maybe Bool -> Bool   )\n    \"Maybe Bool->Maybe Bool\" -> put t n (u :: Maybe Bool -> Maybe Bool)\n    -- functions with lists\n    \"[()]->[()]\"       -> put t n (u :: [()] -> [()]         )\n    \"[Bool]->[Bool]\"   -> put t n (u :: [Bool] -> [Bool]     )\n    \"[Int]->[Int]\"     -> put t n (u :: [Int] -> [Int]       )\n    \"[Nat]->[Nat]\"     -> put t n (u :: [Nat] -> [Nat]       )\n    -- more functions\n    \"Nat2->()\"         -> put t n (u :: Nat2 -> ()           )\n    \"()->Nat2\"         -> put t n (u :: () -> Nat2           )\n    \"Nat2->Nat2\"       -> put t n (u :: Nat2 -> Nat2         )\n    \"Nat2->Nat3\"       -> put t n (u :: Nat2 -> Nat3         )\n    \"Nat3->Nat2\"       -> put t n (u :: Nat3 -> Nat2         )\n    \"Nat3->Nat3\"       -> put t n (u :: Nat3 -> Nat3         )\n    -- functions with mixed arguments\n    \"Bool->Int->Bool\"  -> put t n (u :: Bool -> Int -> Bool  )\n    \"Int->Bool->Bool\"  -> put t n (u :: Int -> Bool -> Bool  )\n    -- functions with 3 arguments\n    \"Int->Int->Int->Int\"     -> put t n (u :: Int -> Int -> Int -> Int)\n    \"Bool->Bool->Bool->Bool\" -> put t n (u :: Bool -> Bool -> Bool -> Bool)\n    -- special lists\n    \"Set Bool\"         -> put t n (u :: Set Bool             )\n    \"Set ()\"           -> put t n (u :: Set ()               )\n    \"Set Nat\"          -> put t n (u :: Set Nat              )\n    \"Set Nat2\"         -> put t n (u :: Set Nat2             )\n    \"Set Nat3\"         -> put t n (u :: Set Nat3             )\n    \"Bag Bool\"         -> put t n (u :: Bag Bool             )\n    \"Bag ()\"           -> put t n (u :: Bag ()               )\n    \"Bag Nat\"          -> put t n (u :: Bag Nat              )\n    \"Bag Nat2\"         -> put t n (u :: Bag Nat2             )\n    \"Bag Nat3\"         -> put t n (u :: Bag Nat3             )\n    \"NoDup Bool\"       -> put t n (u :: NoDup Bool           )\n    \"NoDup ()\"         -> put t n (u :: NoDup ()             )\n    \"NoDup Nat\"        -> put t n (u :: NoDup Nat            )\n    \"NoDup Nat2\"       -> put t n (u :: NoDup Nat2           )\n    \"NoDup Nat3\"       -> put t n (u :: NoDup Nat3           )\n    \"Map Bool Bool\"    -> put t n (u :: Map Bool Bool        )\n    \"Map () ()\"        -> put t n (u :: Map () ()            )\n    \"Map Nat Nat\"      -> put t n (u :: Map Nat Nat          )\n    \"Map Nat2 Nat2\"    -> put t n (u :: Map Nat2 Nat2        )\n    \"Map Nat3 Nat3\"    -> put t n (u :: Map Nat3 Nat3        )\n    -- extreme integers\n--  \"X Int\"            -> put t n (u :: X Int   ) -- device dependent\n--  \"X Word\"           -> put t n (u :: X Word  ) -- device dependent\n    \"X Int4\"           -> put t n (u :: X Int4  )\n    \"X Word4\"          -> put t n (u :: X Word4 )\n    \"X Nat7\"           -> put t n (u :: X Nat7  )\n--  \"Xs Int\"           -> put t n (u :: Xs Int  ) -- device dependent\n--  \"Xs Word\"          -> put t n (u :: Xs Word ) -- device dependent\n    \"Xs Int4\"          -> put t n (u :: Xs Int4 )\n    \"Xs Word4\"         -> put t n (u :: Xs Word4)\n    \"Xs Nat7\"          -> put t n (u :: Xs Nat7 )\n    -- unhandled\n    _                  -> putStrLn $ \"unknown/unhandled type `\" ++ t ++ \"'\"\n", "meta": {"hexsha": "32d1c684ac230703743d863200d85f90e35bd79d", "size": 9768, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bench/tiers.hs", "max_stars_repo_name": "jwaldmann/leancheck", "max_stars_repo_head_hexsha": "fc03f6088cc859e366c8d3da726f1ab6feb32d07", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/tiers.hs", "max_issues_repo_name": "jwaldmann/leancheck", "max_issues_repo_head_hexsha": "fc03f6088cc859e366c8d3da726f1ab6feb32d07", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/tiers.hs", "max_forks_repo_name": "jwaldmann/leancheck", "max_forks_repo_head_hexsha": "fc03f6088cc859e366c8d3da726f1ab6feb32d07", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8823529412, "max_line_length": 83, "alphanum_fraction": 0.3855446355, "num_tokens": 2968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.407829019634324}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule TensorFlow.Operators\n  ( (^+)\n  , (^-)\n  , (^*)\n  , (^/)\n  ) where\n\nimport Data.Int (Int8, Int16, Int32, Int64)\nimport Data.Word (Word8, Word16)\nimport Data.Complex (Complex)\nimport qualified TensorFlow.Core as TF (Tensor, Build, OneOf)\nimport qualified TensorFlow.GenOps.Core as TF (add, sub, mul, realDiv)\n\ninfixl 6 ^+, ^-\ninfixl 7 ^*, ^/\n\n(^+) :: TF.OneOf '[Complex Double, Complex Float, Int16, Int32, Int64, Int8, Word16, Word8, Double, Float] t\n     => TF.Tensor v'1 t\n     -> TF.Tensor v'2 t\n     -> TF.Tensor TF.Build t\na ^+ b = a `TF.add` b\n\n(^-) :: TF.OneOf '[Complex Double, Complex Float, Int32, Int64, Word16, Double, Float] t\n     => TF.Tensor v'1 t\n     -> TF.Tensor v'2 t\n     -> TF.Tensor TF.Build t\na ^- b = a `TF.sub` b\n\n(^*) :: TF.OneOf '[Complex Double, Complex Float, Int16, Int32, Int64, Int8, Word16, Word8, Double, Float] t\n     => TF.Tensor v'1 t\n     -> TF.Tensor v'2 t\n     -> TF.Tensor TF.Build t\na ^* b = a `TF.mul` b\n\n(^/) :: TF.OneOf '[Complex Double, Complex Float, Int16, Int32, Int64, Int8, Word16, Word8, Double, Float] t\n     => TF.Tensor v'1 t\n     -> TF.Tensor v'2 t\n     -> TF.Tensor TF.Build t\na ^/ b = a `TF.realDiv` b\n", "meta": {"hexsha": "bcf31f9741ab9cdeb734ce3558d34d1fca2b3ad4", "size": 1229, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TensorFlow/Operators.hs", "max_stars_repo_name": "bjoeris/orbits-haskell-tensorflow", "max_stars_repo_head_hexsha": "510a2fbd8c8cf8377a6712b4a9e92e151ecdc694", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-06-20T07:32:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-20T07:32:28.000Z", "max_issues_repo_path": "src/TensorFlow/Operators.hs", "max_issues_repo_name": "bjoeris/orbits-haskell-tensorflow", "max_issues_repo_head_hexsha": "510a2fbd8c8cf8377a6712b4a9e92e151ecdc694", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TensorFlow/Operators.hs", "max_forks_repo_name": "bjoeris/orbits-haskell-tensorflow", "max_forks_repo_head_hexsha": "510a2fbd8c8cf8377a6712b4a9e92e151ecdc694", "max_forks_repo_licenses": ["BSD-3-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.2619047619, "max_line_length": 108, "alphanum_fraction": 0.6053702197, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4076862677977183}}
{"text": "{-# LANGUAGE BangPatterns, ScopedTypeVariables, CPP #-}\n{-# OPTIONS_GHC -fwarn-unused-imports #-}\n\n-- The goal of this benchmark is to demonstrate kernels that have private\n-- state which has to be read from memory on each invocation.  Further,\n-- the state forms the majority of the working set -- it's larger than\n-- the streaming input.\n\n-- In theory this means that keeping a kernel on one core and\n-- exploiting pipeline parallelism is better than following the data\n-- through the stream graph in a depth first traversal.\n\n\n--module Main(main) where\nmodule Main where\n\nimport Control.Monad as C\nimport Control.Monad.Par \nimport Control.Monad.Par.Stream as S\nimport Control.Monad.Par.OpenList\nimport Control.DeepSeq\nimport Control.Exception\nimport Control.Parallel.Strategies as Strat\n\n-- import Data.Array.Unboxed as U\nimport Data.Complex\nimport Data.Int\nimport Data.Word\nimport Data.List  (intersperse) \nimport Data.List.Split (chunk)\n\nimport Prelude as P\nimport System.Environment\nimport System.Exit\nimport System.CPUTime\nimport System.CPUTime.Rdtsc\nimport GHC.Conc as Conc\nimport GHC.IO (unsafePerformIO, unsafeDupablePerformIO, unsafeInterleaveIO)\n\nimport Debug.Trace\nimport Control.Monad.Par.Logging\n\nimport qualified Data.Vector.Unboxed as UV\nimport           Data.Vector.Unboxed hiding ((++))\n\n-- Performs some (presently meaningless) computation on a state & a\n-- window (stream element) to compute a new state and new window.\n--\n-- Assumes statesize is a multiple of bufsize:\nstatefulKern :: Vector Double -> Vector Double -> (Vector Double, Vector Double)\nstatefulKern state buf = (newstate, newelem)\n where \n  -- We could probably test the memory behavior we're interested in\n  -- better with inplace update here... but for now, this:\n  newstate = UV.map (\\d -> d/sum + 2) state\n  newelem  = UV.map (+sum) buf\n\n  sum = P.sum partialSums\n  partialSums = [ sumslice (cutslice n) | n <- [0..factor-1] ]   \n\n  cutslice n    = UV.slice (n*blen) blen state\n  sumslice slce = UV.sum (UV.zipWith (+) buf slce)\n\n  factor       = slen `quot` blen\n  slen = UV.length state\n  blen = UV.length buf\n\n--------------------------------------------------------------------------------\n\nmonadpar_version (_,numfilters, bufsize, statecoef, numwins) = do \n  putStrLn$ \"Running monad-par version.\"\n\n  let statesize = bufsize * statecoef\n  results <- evaluate $ runPar$ do \n       strm1 :: Stream (UV.Vector Double) <- S.generate numwins (\\n -> UV.replicate bufsize 0)\n       -- Make a pipeline of numfilters stages:\n       let initstate = UV.generate statesize fromIntegral\n       pipe_end <- C.foldM (\\s _ -> streamScan statefulKern initstate s) strm1 [1..numfilters]\n\n       sums  <- streamMap UV.sum pipe_end\n#if 0\n       return sums\n\n  -- This is tricky, but two different consumers shouldn't prevent\n  -- garbage collection.\n  ls <- toListSpin results\n--  Just (Cons h _) <- pollIVar results\n  putStrLn$ \"Sum of first window: \" ++ show (P.head ls)\n  forkIO$ measureRateList ls\n  putStrLn$ \"Final sum = \"++ show (P.sum ls)\n#else\n\n       streamFold (+) 0 sums\n\n  putStrLn$ \"Final sum = \"++ show results\n#endif\n\n\n--------------------------------------------------------------------------------\n\nsparks_version (_,numfilters, bufsize, statecoef, numwins) = do \n  putStrLn$ \"Running sparks version.\"\n\n  -- Here we represent the stream as a plain list.\n  let \n      statesize = bufsize * statecoef\n      strm1 :: [UV.Vector Double] = P.replicate numwins $ UV.replicate bufsize 0\n      initstate = UV.generate statesize fromIntegral\n      applyKern = scan statefulKern initstate\n\n-- This one has the problem that it fully evaluates the stream for the\n-- first kernel before moving on to the second:\n--      strm_last = (parRepeatFun numfilters applyKern) strm1\n\n      pipe_end = applyNKernels statefulKern numfilters initstate strm1\n\n      sums = P.map UV.sum pipe_end\n-- #define SERIAL\n#ifndef SERIAL\n\t     `using` (Strat.parBuffer numCapabilities rwhnf) \n#endif\n\n  putStrLn$ \"Sum of first window: \"++ show (P.head sums)\n  measureRateList (sums)\n--  measureRateList (strm_last)\n--  measureRateList (forceList strm_last)\n  putStrLn$ \"Final Sum = \" ++ show (P.sum sums)\n\n-- Make sure the cars of a list are evaluated before following each cdr:\nforceList [] = []\nforceList (h:t) = rnf h `seq` forceList t\n\n-- A slightly different version of Data.List.scanl\nscan :: (a -> b -> (a,c)) -> a -> [b] -> [c]\nscan f q [] = []\nscan f q (h:t) = h' : scan f q t\n where \n  (q',h') = f q h\n\ntype StatefulKernel s a b = s -> a -> (s,b)\n\n-- applyNKernels _ _ _ [] = []\n-- applyNKernels :: NFData a => StatefulKernel s a a -> Int -> s -> [a] -> [a]\napplyNKernels :: (NFData a, NFData s) => StatefulKernel s a a -> Int -> s -> [a] -> [a]\napplyNKernels _    0 _    ls = ls\napplyNKernels kern n init ls =   \n  applyNKernels kern (n-1) init (loop init ls)\n where \n  tasklog = unsafeNewTaskSeries (nameFromValue (n,kern))\n\n  loop st [] = []\n  loop st (h:t) = \n    let (st', x) = \n#if 0\n\t           timePure tasklog$ \n#endif\n\t\t   kern st h in\n#ifndef SERIAL\n    rnf x `par` \n#endif\n     x : loop st' t\n   \n-- Compose two stateful kernels in parallel.\ncomposeStatefulKernels :: (NFData b, NFData s1) => \n\t\t\t  StatefulKernel s1 a b -> StatefulKernel s2 b c \n\t\t       -> StatefulKernel (s1,s2) a c\n-- composeStatefulKernels (f1,f2) (s1,s2) x = \ncomposeStatefulKernels f1 f2 (s1,s2) x = \n    rnf pr1 `par` (newstate, snd pr2)\n where \n  pr1 = f1 s1 x\n  pr2 = f2 s2 (snd pr1)\n  newstate = (fst pr1, fst pr2)\n\n\nparRepeatFun n f = \n--  P.foldr (.) id (P.replicate n f)\n  P.foldr (.|| rdeepseq) id (P.replicate n f)\n\n\n--------------------------------------------------------------------------------\n-- Main script\n\ndefault_version = \"monad\"\ndefault_numfilters = 4\ndefault_bufsize    = 256\ndefault_statecoef  = 10   -- in MULTIPLES of bufsize\ndefault_numwins    = 10 * 1000\n\n\nmain = do\n  args <- getArgs\n  arg_tup@(version,_,_,_,_) <- \n       case args of \n\t []          -> return (default_version, default_numfilters, default_bufsize, default_statecoef, default_numwins)\n\t [a,b,c,d,e] -> return (a, read b, read c, read d, read e)\n\t _         -> do \n\t               putStrLn$ \"ERROR: Invalid arguments, must take 0 or 5 args.\"\n\t\t       putStrLn$ \"  Expected args: (version='monad'|'sparks' #filters, bufsize, stateSizeMultiplier, #bufsToProcess)\"\n\t\t       putStrLn$ \"  Received args: \"++ show args\n\t\t       exitFailure \n\n  putStrLn$ \"numCapabilities: \"++ show numCapabilities\n  putStrLn$ \"  Frequency in measurable ticks:  \"++ commaint oneSecond ++ \"\\n\"\n\n  case version of \n    \"monad\"  -> monadpar_version arg_tup\n    \"sparks\" -> sparks_version  arg_tup\n    _        -> error$ \"unknown version: \"++version\n\n  putStrLn$ \"Finally, dumping all logs:\"\n  printAllLogs\n\n\n\n-- It is not necessary to evaluate every element in the case of an unboxed vector.\ninstance NFData a => NFData (UV.Vector a) where\n rnf !vec = ()\n\n\nprint_ msg = trace msg $ return ()\n\n-- work pop 1 peek N push 1 \n-- float->float filter \n-- firFilter n coefs = \n-- {\n\n--     float sum = 0;\n--     for (int i = 0; i < N; i++)\n--       sum += peek(i) * COEFF[N-1-i];\n--     pop();\n--     push(sum);\n--   }\n-- }\n\n\n{- \n\nHere's what cachegrind says (on 4 core nehalem):\n\n  $ valgrind --tool=cachegrind ./stream/disjoint_working_sets_pipeline monad 4 768 10 1000 +RTS -N4\n   .....\n      [measureRate] current rate: 58  Total elems&time 916  181,988,055,721\n      [measureRate] Hit end of stream after 1000 elements.\n     Final sum = 1.560518243231086e22\n     ==21202== \n     ==21202== I   refs:      7,111,462,273\n     ==21202== I1  misses:          374,190\n     ==21202== L2i misses:          298,364\n     ==21202== I1  miss rate:          0.00%\n     ==21202== L2i miss rate:          0.00%\n     ==21202== \n     ==21202== D   refs:      3,882,935,974  (3,542,949,529 rd   + 339,986,445 wr)\n     ==21202== D1  misses:       14,606,684  (    9,824,455 rd   +   4,782,229 wr)\n     ==21202== L2d misses:        6,774,479  (    2,088,565 rd   +   4,685,914 wr)\n     ==21202== D1  miss rate:           0.3% (          0.2%     +         1.4%  )\n     ==21202== L2d miss rate:           0.1% (          0.0%     +         1.3%  )\n     ==21202== \n     ==21202== L2 refs:          14,980,874  (   10,198,645 rd   +   4,782,229 wr)\n     ==21202== L2 misses:         7,072,843  (    2,386,929 rd   +   4,685,914 wr)\n     ==21202== L2 miss rate:            0.0% (          0.0%     +         1.3%  )\n\n\nSparks version:\n     Final Sum = 1.560518243231086e22\n     ==21226== \n     ==21226== I   refs:      5,898,314,238\n     ==21226== I1  misses:          291,271\n     ==21226== L2i misses:          246,518\n     ==21226== I1  miss rate:          0.00%\n     ==21226== L2i miss rate:          0.00%\n     ==21226== \n     ==21226== D   refs:      3,264,359,909  (3,206,394,437 rd   + 57,965,472 wr)\n     ==21226== D1  misses:       16,003,068  (   10,905,138 rd   +  5,097,930 wr)\n     ==21226== L2d misses:        9,177,043  (    4,207,106 rd   +  4,969,937 wr)\n     ==21226== D1  miss rate:           0.4% (          0.3%     +        8.7%  )\n     ==21226== L2d miss rate:           0.2% (          0.1%     +        8.5%  )\n     ==21226== \n     ==21226== L2 refs:          16,294,339  (   11,196,409 rd   +  5,097,930 wr)\n     ==21226== L2 misses:         9,423,561  (    4,453,624 rd   +  4,969,937 wr)\n     ==21226== L2 miss rate:            0.1% (          0.0%     +        8.5%  )\n\n -}\n", "meta": {"hexsha": "ae73e6bac2cc2b92ff012051e3c8d3dba148dc67", "size": 9396, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/stream/disjoint_working_sets_pipeline.hs", "max_stars_repo_name": "tpetricek/Haskell.ParMonad", "max_stars_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-01-20T05:54:40.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-20T05:54:40.000Z", "max_issues_repo_path": "examples/stream/disjoint_working_sets_pipeline.hs", "max_issues_repo_name": "tpetricek/Haskell.ParMonad", "max_issues_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/stream/disjoint_working_sets_pipeline.hs", "max_forks_repo_name": "tpetricek/Haskell.ParMonad", "max_forks_repo_head_hexsha": "83a64b9f4bf5f80cb254eb92fb5db61271756e9c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0845070423, "max_line_length": 119, "alphanum_fraction": 0.601532567, "num_tokens": 2878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40768626088252297}}
{"text": "{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TupleSections #-}\nmodule Physics.Mechanics where\n\nimport           Numeric.LinearAlgebra (Matrix, Vector, scale, (#>), cross, cmap,dot, ident, tr, (<>), norm_2)\nimport qualified Number.Quaternion as Q\nimport           Control.Lens hiding ((<.>))\nimport qualified Data.Vector.Storable as VS\nimport           Control.Arrow hiding ((<+>))\nimport           Debug.Trace\nimport           Data.Maybe (fromMaybe)\nimport           Data.Function (on)\n\nimport Data.PhysicsData\nimport Data.GameObject\nimport Data.Mesh\nimport Physics.Collision\nimport qualified Data.Vector as V\nimport Data.List.Lens\n\nimport Utils(step,norm)\nimport Utils.Quaternions\n\ninfixr 1 <+>\n(<+>) :: Vector Float -> Vector Float -> Vector Float\n(<+>) = VS.zipWith (+)\n\n-- (<*>) :: Vector Float -> Vector Float -> Vector Float\n-- (<*>) = VS.zipWith (*)\n\n(<.>) :: Vector Float -> Vector Float -> Float\n(<.>) = (VS.sum .) . VS.zipWith (*)\n\naddMaybeForce :: Maybe (Vector Float) -> Maybe PhysicsData -> Maybe PhysicsData\naddMaybeForce mf mph = over acc . (<+>) <$> mf <*> mph\n\nputForceLoc :: Vector Float -> Vector Float -> GameObject -> GameObject\nputForceLoc point force obj =\n          let m    = preview (physics._Just.massInv) obj\n              lin  = flip scale (scale (force <.> point) force) <$> m\n              ang  = cross force point\n          in over physics (addMaybeForce lin)\n           . over (physics._Just.torque) (<+>ang)\n           $ obj\n\n\nputForce :: Vector Float -> Vector Float -> GameObject -> GameObject\nputForce point force obj =\n          let p    = point - obj^.location\n          in putForceLoc p force obj\n\n\nputForceOnMid = over (physics._Just.acc) . (+)\n\nputForceOnTip vec obj =\n  let quat = obj^.mesh.quaternion\n      tip  = rotateWithQuat quat [0,0,-0.1] + obj^.location\n  in putForce tip vec obj\n\nputForceOnTipLoc vec obj =\n  let quat = obj^.mesh.quaternion\n      f    = rotateWithQuat quat vec\n  in putForceOnTip f obj\n\nputForceOnSide vec obj =\n  let quat = obj^.mesh.quaternion\n      tip  = rotateWithQuat quat [1,0,0] <+> obj^.location\n  in putForce tip vec obj\n\nputForceOnSideLoc vec obj =\n  let quat = obj^.mesh.quaternion\n      f    = rotateWithQuat quat vec\n  in putForceOnSide f obj\n\naddScaled\n  :: Setter GameObject GameObject (VS.Vector Float) (VS.Vector Float)\n  -> Lens PhysicsData PhysicsData (VS.Vector Float) (VS.Vector Float)\n  -> GameObject -> GameObject\naddScaled lens1 lens2 = applyWithPhysics helper\n  where helper ph = over lens1 (<+> VS.map (*step) (ph^.lens2))\n\napplySpeed = addScaled location speed\n\ngForce :: Vector Float\ngForce = [0,9,0]\n\ngravityF = over (physics._Just.acc) (subtract gForce)\n\ngravCoeff = scale step gForce\n\ngetVec :: Lens PhysicsData PhysicsData (VS.Vector Float) (VS.Vector Float) -> GameObject -> VS.Vector Float\ngetVec l = fromMaybe [0,0,0] . preview (physics._Just.l)\n\ngetMat :: Lens PhysicsData PhysicsData (Matrix Float) (Matrix Float) -> GameObject -> Matrix Float\ngetMat l = fromMaybe (ident 3) . preview (physics._Just.l)\n\nfloatOnGround obj =\n  let floorNormal = [0,1,0]\n      loc       = obj^.location\n      d         = dot floorNormal loc + 2\n      f         = negate (2-d)^(2 :: Int)\n  in if d < 1\n  then putForceOnMid (scale f gForce) obj\n  else obj\n\ncalculateRelPos contact obj = contact^.contactPoint - obj^.location\n\nlinearInertia obj =\n  fromMaybe 0 $ obj^?physics._Just.massInv\n\nadjustMove relPos p@(l, an) =\n  let limit = norm relPos * 0.1\n      newAn = signum an * limit\n  in if abs an > limit\n     then (l + an - newAn,newAn)\n     else p\n\ncollisionMoves :: Contact -> (GameObject, Vector Float) -> (GameObject, Vector Float) -> ((Float, Vector Float), (Float, Vector Float))\ncollisionMoves contact p1 p2 =\n  let ang1 = angularInertia contact p1\n      lin1 = linearInertia $ fst p1\n      ang2 = angularInertia contact p2\n      lin2 = linearInertia $ fst p2\n      coef = contact^.penetration / (ang1 + ang2 + lin1 + lin2)\n      (fli1, fan1) = adjustMove (snd p1) (coef*lin1, coef*ang1)\n      (fli2, fan2) = adjustMove (snd p2) (coef*lin2, coef*ang2)\n      finang1 = getRotationPM contact p1 fan1 ang1\n      finang2 = getRotationPM contact p1 fan2 ang2\n  in ((fli1, finang1),(fli2, finang2))\n\ngetRotationPM :: Contact -> (GameObject, Vector Float) -> Float -> Float -> Vector Float\ngetRotationPM contact (obj, relPos) ang angIn =\n  if angIn == 0\n  then [0,0,0]\n  else\n    scale (ang) .\n    scale (1/angIn) $\n    getInertiaInv obj #> cross relPos (contact^.contactNormal)\n\napplyMoves :: Contact -> (Float, Vector Float) -> GameObject -> GameObject\napplyMoves contact (lin, ang) =\n  over (mesh.quaternion) (qvMul ang) .\n  over location (+ scale lin (contact^.contactNormal))\n\ncalculateDeltaVel :: Contact -> (GameObject, Vector Float) -> Float\ncalculateDeltaVel contact p@(obj, _) =\n  case obj^.physics of\n    Just pd ->\n      (pd^.massInv +) $\n      angularInertia contact p\n      -- dot (contact^.contactNormal) .\n      -- flip cross relPos .\n      -- ((pd^.inertiaInv) #>) .\n      -- flip cross (contact^.contactNormal) $ relPos\n    Nothing -> 0\n\nangCoeff = 1\n\nangularInertia :: Contact ->  (GameObject, Vector Float) -> Float\nangularInertia contact (obj, relPos) =\n  case obj^.physics of\n    Just pd ->\n--      (*angCoeff) .\n      dot (contact^.contactNormal) .        -- get component of speed pointing along the normal\n      (\\angS -> cross angS relPos) .        -- get linear speed of pt\n      ((pd^.inertiaInv) #>) $               -- Get ang speed\n      cross relPos (contact^.contactNormal) -- for unit impulse\n    Nothing -> 0\n\ncalculateClosingVel :: Contact -> (GameObject, Vector Float) -> Float\ncalculateClosingVel contact (obj, relPos) =\n  case obj^.physics of\n    Just pd ->\n      -- (makeContactBasis contact #>) .\n      dot (contact^.contactNormal) .\n      (pd^.speed +) . cross (pd^.angularS) $ relPos\n    Nothing -> 0\n\ncalculateImpulse :: Contact -> (GameObject, Vector Float) -> (GameObject, Vector Float) -> Vector Float\ncalculateImpulse contact o1 o2 =\n  let deltaV = ((\"Delta: \"++) . show >>= trace) $\n               ((+) `on` calculateDeltaVel contact) o1 o2\n      closiV = ((\"Closing: \"++) . show >>= trace) $\n               ((+) `on` calculateClosingVel contact) o1 o2\n      contV  = negate $ closiV\n      restitution = if abs contV < 2\n                    then 0.0\n                    else 0.0\n      impulse = -- if signum contV /= signum (contact^.sign)\n                -- then\n                  scale (contV * (1.0 + restitution)/deltaV) $ contact^.contactNormal\n                -- else [0,0,0]\n  in impulse\n\napplyImpulse :: Vector Float -> (GameObject, Vector Float) -> GameObject\napplyImpulse impulse (obj, relPos) =\n  let vChange = -- impulse\n        ((\"Linear impulse: \"++) . show >>= trace) .\n        fromMaybe [0,0,0] $\n        flip scale impulse <$> (obj^?physics._Just.massInv)\n      rotChange = ((\"Angular impulse: \"++) . show >>= trace) .\n--        scale angCoeff .\n        fromMaybe [0,0,0] $\n        (#> cross impulse relPos) <$> (obj^?physics._Just.inertiaInv)\n  in over (physics._Just.speed) (+ vChange) .\n     over (physics._Just.angularS) (+ rotChange) $ obj\n\n\n\nresolveCollision :: (Int, Int) -> [Contact] -> V.Vector GameObject -> V.Vector GameObject\nresolveCollision (ix1, ix2) (contact:cs) objs =\n  let obj1 = objs V.! ix1\n      obj2 = objs V.! ix2\n      movement = scale (contact^.penetration*contact^.sign) $\n                 contact^.contactNormal\n      move = case obj1^.physics of\n               Just _ -> over (ix 0._2.location) (+movement)\n               Nothing -> over (ix 1._2.location) (subtract movement)\n      relPos1 = ((\"RelPos1: \"++) . show >>= trace) $ calculateRelPos contact obj1\n      relPos2 = ((\"RelPos2: \"++) . show >>= trace) $ calculateRelPos contact obj2\n      impulse = ((\"Impulse: \"++) . show >>= trace) .\n                scale (contact^.sign) $\n                calculateImpulse contact (obj1, relPos1) (obj2, relPos2)\n      (m1, m2) = collisionMoves contact (obj1, relPos1) (obj2, relPos2)\n      update i p =\n        -- applyMoves contact p .\n        applyImpulse i\n      updates = move $\n                [(ix1, update (impulse) m1 (obj1, relPos1))\n                ,(ix2, update (-impulse) m2 (obj2, relPos2))]\n      newObjs = V.unsafeUpd objs updates\n      check   = V.unsafeIndex newObjs\n      -- newColls =\n      --   take (length cs) $\n      --   detectCollision (prepareCPrim $ check ix1) (prepareCPrim $ check ix2)^.contacts\n  in\n    resolveCollision (ix1, ix2) cs newObjs\nresolveCollision _ [] objs = objs\n\n\nfloorReaction obj =\n  let floorHeight = [0,-2,0]\n      floorNormal = [0,1,0] :: Vector Float\n      vert      = obj^.mesh.vertices\n      loc       = obj^.location\n      r         = quatToMat3 $ obj^.mesh.quaternion\n      m         = (1/) $ fromMaybe 1 $ obj^?physics._Just.massInv\n      translate = (+loc) . subtract floorHeight\n      collides = filter ((<0) . snd)\n               . map (id &&& (dot floorNormal . translate) . (tr r #>))\n               $ vert\n      minD :: Float\n      minD = negate . foldr min 0 . map snd $ collides\n      response (point, depth) =\n        let\n          vrel = dot floorNormal $ getVec speed obj + cross (getVec angularS obj) point\n          aobj = dot floorNormal $ cross (i #> cross point floorNormal) point\n          i    = getMat inertiaInv obj\n          j    = negate (0.8) * vrel/(m+aobj)\n          force = scale j floorNormal\n          torque = getMat inertiaInv obj #> cross point force\n            -- getMat inertiaInv obj #> cross point force\n        in (force, torque)\n      (f,t) = foldr (\\(a,b) (c,d) -> (a+c,b+d)) ([0,0,0],[0,0,0])\n            . map response\n            $ collides\n      n = fromIntegral $ length collides\n  in if n /= 0\n  then over (physics._Just.angularS) (+ scale (1/n) t)\n     . over (physics._Just.speed) (+ scale (1/n) f)\n     . over (location) (+ scale minD floorNormal)\n     $ obj\n  else obj\n\napplyAcc :: GameObject -> GameObject\napplyAcc = addScaled (physics._Just.speed) acc\n\napplyForce :: GameObject -> GameObject\napplyForce = applyWithPhysics helper\n  where helper ph obj =\n         let tq    = ph^.torque\n             om    = ph^.angularS\n             inInv = ph^.inertiaInv\n             newOm = om <+> (inInv #> scale step tq)\n             quatD = qvMul (scale step newOm) $ obj^.mesh.quaternion\n             newQ  = Q.normalize . addQuat quatD $ obj^.mesh.quaternion\n             inInD = quatToLInv (ph^.inertiaD) newQ\n         in set (physics._Just.torque) [0,0,0]\n          . set (physics._Just.acc) [0,0,0]\n          . applySpeed\n--          . floorReaction\n          . applyAcc\n--          . floatOnGround\n          . set (physics._Just.angularS) newOm\n          . set (physics._Just.inertiaInv) inInD\n          . set (mesh.quaternion) newQ\n          $ obj\n\napplyLinear :: GameObject -> GameObject\napplyLinear = set (physics._Just.torque) [0,0,0]\n              . set (physics._Just.acc) [0,0,0]\n              . applySpeed\n              -- . floorReaction\n              . applyAcc\n              -- . gravityF\n\napplyWithPhysics :: (PhysicsData -> GameObject -> GameObject)\n                   -> GameObject -> GameObject\napplyWithPhysics f obj = case obj^.physics of\n  Just phy -> f phy obj\n  Nothing  -> obj\n\n\nmaxspeed = 50\n\n\nyolo :: Float -> Vector Float -> Vector Float\nyolo maxVal vec =\n  let vecNorm = norm vec\n      coeff   = (vecNorm/maxVal)**(1/2)\n  in scale (0 - max 1 coeff) vec\n\nfriction = applyWithPhysics helper\n  where helper phy =\n          let maxspeed  = 1000000\n              maxtorque = 100\n              coeff1    = scale step . yolo maxspeed $ phy^.speed\n              coeff2    = scale step . yolo maxtorque $ phy^.angularS\n          in over (physics._Just.angularS) (<+> coeff2)\n            . over (physics._Just.speed) (<+> coeff1)\n\n\n  -- applyWithPhysics helper\n  -- where helper phy obj =\n  --         let quat   = obj^.mesh.quaternion\n  --             rot    = rotateWithQuat quat [0,0,-1]\n  --               -- (\\(a,b,c) -> [a,b,c]) . imag . flip quatConcat (qInverse quat) $ quatConcat quat (0 +:: (0,0,-1))\n  --             force  = 40 -- exp (maxspeed - sNorm) - 1\n  --         in over (physics._Just.acc) (<+>cmap (*force) rot) obj\n", "meta": {"hexsha": "77aee236f7c56d8c5ca6e65d80079030f96a35b6", "size": 12215, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Physics/Mechanics.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/Mechanics.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/Mechanics.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.612244898, "max_line_length": 135, "alphanum_fraction": 0.6031927957, "num_tokens": 3431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.40743043126468903}}
{"text": "{-# LANGUAGE Haskell2010, TemplateHaskell #-}\n\nmodule Numeric.Matrix.Sugar (\n        iMatrix, dMatrix, cMatrix\n    ) where\n\nimport Numeric.Matrix\nimport Language.Haskell.TH\nimport Language.Haskell.TH.Quote\n\nimport Data.Data\nimport Data.Complex\nimport Data.Ratio\n\ntype ReadM a = String -> Matrix a\n\niMatrix = QuasiQuoter\n            (quoter (read :: ReadM Integer))\n            undefined undefined undefined\n\ndMatrix = QuasiQuoter\n            (quoter (read :: ReadM Double))\n            undefined undefined undefined\n\ncMatrix = QuasiQuoter\n            (quoter (read :: ReadM (Complex Double)))\n            undefined undefined undefined\n\nquoter :: (Data e, MatrixElement e)\n       => (String -> Matrix e) -> String -> Q Exp\n\nquoter read str = do\n    let qExp = dataToExpQ (const Nothing) (toList (read str))\n    [e| fromList $qExp |]\n\n", "meta": {"hexsha": "c385c6304471efc3314c8340a6eda77471cf518d", "size": 833, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Matrix/Sugar.hs", "max_stars_repo_name": "phadej/bed-and-breakfast", "max_stars_repo_head_hexsha": "03903bf767361660cd33aa16352f009e9766372d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Matrix/Sugar.hs", "max_issues_repo_name": "phadej/bed-and-breakfast", "max_issues_repo_head_hexsha": "03903bf767361660cd33aa16352f009e9766372d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Matrix/Sugar.hs", "max_forks_repo_name": "phadej/bed-and-breakfast", "max_forks_repo_head_hexsha": "03903bf767361660cd33aa16352f009e9766372d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1388888889, "max_line_length": 61, "alphanum_fraction": 0.6566626651, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.40710959227059107}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Learn\n  ( newManager\n  , defaultManagerSettings\n  , initNN\n  , hotone\n  , convertTrains\n  , convertTests\n  , trainingSimple\n  , chunksOf\n  ) where\n\nimport           Data.Bifunctor\nimport           Data.List\nimport           Data.List.Split\nimport           Debug.Trace\nimport           Layers\nimport           Mnist\nimport           Network.HTTP.Client\nimport           Numeric.LinearAlgebra\n\nnormalAffine :: Int -> Int -> IO (ForwardLayer R)\nnormalAffine nIn nOut = do\n  weights <- rand nIn nOut\n  bias <- flatten <$> rand nOut 1\n  return $ AffineForward weights bias\n\ninitNN :: ForwardLayer R -> [Int] -> IO (ForwardNN R)\ninitNN eoa ns = do\n  (lastAffine:affines) <- mapM (uncurry normalAffine) $ spans [] ns\n  let layers = foldl' (\\b a -> a ~> eoa ~> b) lastAffine affines\n  return $ ForwardNN layers SoftmaxWithCrossForward\n  where\n    spans rs [a, b]   = (a, b) : rs\n    spans rs (a:b:xs) = spans ((a, b) : rs) (b : xs)\n\nconvertTrains :: Int -> MnistData -> [TrainBatch R]\nconvertTrains batchSize (MnistData src) =\n  map (mkTrainer . unzip) $ chunksOf batchSize vectors\n  where\n    vectors = map (bimap (hotone 10) flatten) src\n    mkTrainer (a, b) = TrainBatch (fromRows a, fromZ (fromRows b) / 255)\n\nhotone :: (Integral v, NElement a) => Int -> v -> Vector a\nhotone n' v = fromList $ map fromIntegral list\n  where\n    n = if i < n' then n' else error (\"Too large value: \" ++ show i)\n    list = replicate i 0 ++ 1 : replicate (n - i - 1) 0\n    i = fromIntegral v\n\nconvertTests :: MnistData -> [(Int, Vector R)]\nconvertTests (MnistData src) =\n  map (bimap fromIntegral $ (/ 255) . flatten . fromZ) src\n\ntrainingSimple ::\n     Double\n  -> Int\n  -> Int\n  -> ForwardNN R\n  -> MnistData\n  -> MnistData\n  -> ([Double], Double)\ntrainingSimple rate batchSize nReplicate nn trainData testData =\n  (losses, evaluate layers $ convertTests testData)\n  where\n    trainBatches = convertTrains batchSize trainData\n    batches = concat $ replicate nReplicate trainBatches\n    (ForwardNN layers _, losses) = learnAll rate nn batches\n", "meta": {"hexsha": "0fc6c988307a852510d9cc691509b2849faa9ba5", "size": 2064, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Learn.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/Learn.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/Learn.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.4857142857, "max_line_length": 72, "alphanum_fraction": 0.6545542636, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4070623659639856}}
{"text": "{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE DeriveAnyClass        #-}\n{-# LANGUAGE DeriveGeneric         #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-|\nModule      : Grenade.Layers.Logit\nDescription : Exponential linear unit layer\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.Elu (\n    Elu (..)\n  ) where\n\nimport           Control.DeepSeq              (NFData)\nimport           Data.Serialize\nimport           GHC.Generics                 (Generic)\n\nimport           GHC.TypeLits\nimport           Grenade.Core\n\nimport qualified Numeric.LinearAlgebra.Static as LAS\n\n-- | An exponential 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 Elu = Elu\n  deriving (Generic, NFData, Show)\n\ninstance UpdateLayer Elu where\n  type Gradient Elu = ()\n  runUpdate _ _ _ = Elu\n\ninstance RandomLayer Elu where\n  createRandomWith _ _ = return Elu\n\ninstance Serialize Elu where\n  put _ = return ()\n  get = return Elu\n\ninstance ( KnownNat i) => Layer Elu ('D1 i) ('D1 i) where\n  type Tape Elu ('D1 i) ('D1 i) = LAS.R i\n\n  runForwards _ (S1D y) = (y, S1D (elu y))\n    where\n      elu = LAS.dvmap (\\a -> if a <= 0 then exp a - 1 else a)\n  runBackwards _ y (S1D dEdy) = ((), S1D (elu' y * dEdy))\n    where\n      elu' = LAS.dvmap (\\a -> if a <= 0 then exp a else 1)\n\ninstance (KnownNat i, KnownNat j) => Layer Elu ('D2 i j) ('D2 i j) where\n  type Tape Elu ('D2 i j) ('D2 i j) = S ('D2 i j)\n\n  runForwards _ (S2D y) = (S2D y, S2D (elu y))\n    where\n      elu = LAS.dmmap (\\a -> if a <= 0 then exp a - 1 else a)\n  runBackwards _ (S2D y) (S2D dEdy) = ((), S2D (elu' y * dEdy))\n    where\n      elu' = LAS.dmmap (\\a -> if a <= 0 then exp a else 1)\n\ninstance (KnownNat i, KnownNat j, KnownNat k) => Layer Elu ('D3 i j k) ('D3 i j k) where\n\n  type Tape Elu ('D3 i j k) ('D3 i j k) = S ('D3 i j k)\n\n  runForwards _ (S3D y) = (S3D y, S3D (elu y))\n    where\n      elu = LAS.dmmap (\\a -> if a <= 0 then exp a - 1 else a)\n  runBackwards _ (S3D y) (S3D dEdy) = ((), S3D (elu' y * dEdy))\n    where\n      elu' = LAS.dmmap (\\a -> if a <= 0 then exp a else 1)\n\n\n-------------------- GNum instances --------------------\n\n\ninstance GNum Elu where\n  _ |* Elu = Elu\n  _ |+ Elu = Elu\n  gFromRational _ = Elu\n\n", "meta": {"hexsha": "92d7df5b524a2f7d478111396c9c890914e69de6", "size": 2406, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Elu.hs", "max_stars_repo_name": "koenigmaximilian/grenade", "max_stars_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Grenade/Layers/Elu.hs", "max_issues_repo_name": "koenigmaximilian/grenade", "max_issues_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Elu.hs", "max_forks_repo_name": "koenigmaximilian/grenade", "max_forks_repo_head_hexsha": "fb96af44b1e48bf07305353dd717ac20f5d861ac", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6428571429, "max_line_length": 88, "alphanum_fraction": 0.5822942643, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4070229689814234}}
{"text": "{-# LANGUAGE DataKinds #-}\n\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Static\nimport qualified Numeric.LinearAlgebra.HMatrix as LA\n\na = row (vec4 1 2 3 4)\nu = vec4 10 20 30 40\nv = vec2 5 0 & 0 & 3 & 7\n\n", "meta": {"hexsha": "6db7739c73ad7abf587caa42a018dc73b4f124eb", "size": 208, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "static.hs", "max_stars_repo_name": "kuitang/monad-learner", "max_stars_repo_head_hexsha": "d5addd73bdf616e739c74886cde4e7206504f74d", "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": "static.hs", "max_issues_repo_name": "kuitang/monad-learner", "max_issues_repo_head_hexsha": "d5addd73bdf616e739c74886cde4e7206504f74d", "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": "static.hs", "max_forks_repo_name": "kuitang/monad-learner", "max_forks_repo_head_hexsha": "d5addd73bdf616e739c74886cde4e7206504f74d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9090909091, "max_line_length": 52, "alphanum_fraction": 0.7067307692, "num_tokens": 76, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4070058298736253}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE OverloadedLabels #-}\n{-# OPTIONS_GHC -Wall #-}\n\n-- | Quantile chart patterns.\nmodule Chart.Quantile\n  (\n    -- * quantile chart patterns\n    quantileChart,\n    histChart,\n\n    -- * testing\n    qua,\n    qLines,\n  )\nwhere\n\nimport Chart\nimport Optics.Core\nimport Data.Foldable\nimport Data.Maybe\nimport Data.Text (Text)\nimport Prelude hiding (abs)\nimport Statistics.Distribution.Normal\nimport Statistics.Distribution\nimport Data.Bool\n\n-- * charts\n\n-- | Chart template for quantile data.\nquantileChart ::\n  [Text] ->\n  [LineStyle] ->\n  [AxisOptions] ->\n  [[Double]] ->\n  ChartSvg\nquantileChart names ls as xs =\n  mempty & #charts .~ chart0 & #hudOptions .~ hudOptions'\n  where\n    hudOptions' :: HudOptions\n    hudOptions' =\n      defaultHudOptions\n        & ( #legends\n              .~\n                [(12, defaultLegendOptions\n                    & #textStyle % #size .~ 0.1\n                    & #vgap .~ 0.05\n                    & #innerPad .~ 0.2\n                    & #place .~ PlaceRight\n                    & #content .~ zip names (fmap (\\l -> LineChart l [[Point 0 0, Point 1 1]]) ls)\n                )]\n          )\n        & set #axes ((5,) <$> as)\n\n    chart0 = unnamed $\n      zipWith (\\s d -> LineChart s [d])\n        ls\n        (zipWith Point [0 ..] <$> xs)\n\n-- | histogram chart\nhistChart ::\n  Range Double ->\n  Int ->\n  [Double] ->\n  ChartSvg\nhistChart r g xs =\n  barChart defaultBarOptions barData'\n  where\n    barData' = BarData [freqs] xs'' []\n    hcuts = grid OuterPos r g\n    h = fill hcuts xs\n    counts =\n      (\\(Rect _ _ _ w) -> w)\n        <$> makeRects (IncludeOvers (width r / fromIntegral g)) h\n    freqs = (/sum counts) <$> counts\n    xs' =\n      (\\(Rect x x' _ _) -> (x + x') / 2)\n        <$> makeRects (IncludeOvers (width r / fromIntegral g)) h\n    xs'' = [\"unders\"] <> take (length xs' - 2) (drop 1 (comma (Just 2) <$> xs')) <> [\"overs\"]\n\nqua :: Double -> Double -> Double -> Double -> Double\nqua u s t p\n  | t <= 0 = u*t\n  | otherwise = Statistics.Distribution.quantile (normalDistr (u*t) (s*sqrt t)) p\n\nqLines :: Double -> Int -> Colour -> [LineStyle]\nqLines s n c = (\\x -> defaultLineStyle & #color .~ x & #size .~ s) <$> cqs n c\n\ncqs :: Int -> Colour -> [Colour]\ncqs n c = fmap (\\x -> mix x c (greyed c)) xs\n  where\n    xs = (\\t -> fmap (\\x -> fromIntegral (abs (x-(t `div` 2)-bool 0 1 (x>(t `div`2) && 1==t `mod` 2))) / fromIntegral (t `div` 2)) [0..t]) (n - 1)\n", "meta": {"hexsha": "48f3c29b170da42df2bec29cf3fd6dc107d4526f", "size": 2475, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Chart/Quantile.hs", "max_stars_repo_name": "tonyday567/quantile-charts", "max_stars_repo_head_hexsha": "87b0b3c5a64570a1291179271fbf583d72b21fea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chart/Quantile.hs", "max_issues_repo_name": "tonyday567/quantile-charts", "max_issues_repo_head_hexsha": "87b0b3c5a64570a1291179271fbf583d72b21fea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chart/Quantile.hs", "max_forks_repo_name": "tonyday567/quantile-charts", "max_forks_repo_head_hexsha": "87b0b3c5a64570a1291179271fbf583d72b21fea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.329787234, "max_line_length": 146, "alphanum_fraction": 0.5503030303, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4067489675231903}}
{"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\nmodule Numeric.QpOases where\n\nimport Control.Monad\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Except\nimport qualified Data.Vector.Storable as VS\nimport Data.Matrix.CSC\nimport Foreign hiding (void)\nimport Foreign.C.Types\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Devel\n\ndata OasesError = SizeMismatch | OasesError Int deriving (Show)\n\ndata HessianType = HST_ZERO | HST_IDENTITY | HST_POSDEF | HST_POSDEF_NULLSPACE | HST_SEMIDEF | HST_INDEF | HST_UNKNOWN deriving (Enum, Show)\n\nnewtype SQProblem = SQProblem (ForeignPtr SQProblem) deriving (Eq, Show)\n\nnewtype SQProblemSchur = SQProblemSchur (ForeignPtr SQProblemSchur) deriving (Eq, Show)\n\nsetupSQP :: Int -> Int -> HessianType -> IO SQProblem\nsetupSQP nV nC h = do\n    ptr2 <- alloca $ \\ptr -> do\n        !_ <- sqproblem_setup (fromIntegral nV) (fromIntegral nC) (fromIntegral $ fromEnum h) ptr\n        peek ptr\n    SQProblem <$> newForeignPtr sqproblem_cleanup ptr2\n\nsetupSQPSchur :: Int -> Int -> HessianType -> IO SQProblemSchur\nsetupSQPSchur nV nC h = do\n    ptr2 <- alloca $ \\ptr -> do\n        !_ <- sqproblem_schur_setup (fromIntegral nV) (fromIntegral nC) (fromIntegral $ fromEnum h) ptr\n        peek ptr\n    SQProblemSchur <$> newForeignPtr sqproblem_schur_cleanup ptr2\n\nwithSQProblem :: SQProblem -> (Ptr SQProblem -> IO a) -> IO a\nwithSQProblem (SQProblem fPtr) f = withForeignPtr fPtr f\n\nwithSQProblemSchur :: SQProblemSchur -> (Ptr SQProblemSchur -> IO a) -> IO a\nwithSQProblemSchur (SQProblemSchur fPtr) f = withForeignPtr fPtr f\n\ninitSQP :: SQProblem -> Matrix Double -> Vector Double -> Matrix Double\n        -> Vector Double -> Vector Double -> Maybe Double\n        -> ExceptT OasesError IO (Vector Double, Double)\ninitSQP sqp h g a lbA ubA m'cpuTime =\n  mat' h $ \\hRow hCol hPtr ->\n  vec' g $ \\gSize gPtr ->\n  mat' a $ \\aRow aCol aPtr ->\n  vec' lbA $ \\lbASize lbAPtr ->\n  vec' ubA $ \\ubASize ubAPtr -> do\n    let nVar = gSize\n    let nConstr = aRow\n    unless (nVar == hRow) $ throwE SizeMismatch\n    unless (nVar == hCol) $ throwE SizeMismatch\n    unless (nVar == aCol) $ throwE SizeMismatch\n    unless (nConstr == lbASize) $ throwE SizeMismatch\n    unless (nConstr == ubASize) $ throwE SizeMismatch\n    primalFP <- liftIO $ mallocForeignPtrArray (fromIntegral nVar)\n    (obj, status) <- liftIO $ withForeignPtr primalFP $ \\xPtr ->\n      allocaArray (fromIntegral $ nVar + nConstr) $ \\yPtr ->\n      alloca $ \\objPtr ->\n      alloca $ \\statusPtr ->\n      with (5 * fromIntegral (nVar + nConstr)) $ \\nWSRPtr -> \n      maybe ($ nullPtr) with m'cpuTime $ \\cpuTimePtr -> do\n        _ <- withSQProblem sqp $ \\ptr ->\n               sqproblem_init ptr hPtr gPtr aPtr nullPtr nullPtr lbAPtr ubAPtr\n               nWSRPtr cpuTimePtr xPtr yPtr objPtr statusPtr\n        !obj <- peek objPtr\n        !status <- fromIntegral <$> peek statusPtr\n        return $ (obj, status)\n    let solutionVec = VS.unsafeFromForeignPtr0 primalFP (fromIntegral nVar)\n    if status == 0\n      then return (solutionVec, obj)\n      else throwE (OasesError status)\n  where\n    mat' m f = ExceptT $ mat (cmat m) $ \\church -> church $ \\nrow ncol ptr -> runExceptT $ f nrow ncol ptr\n    vec' v f = ExceptT $ vec v $ \\church -> church $ \\size ptr -> runExceptT $ f size ptr\n\ninitSparseSQP :: SQProblem -> CSC Double -> Vector Double -> Matrix Double\n              -> Vector Double -> Vector Double -> Maybe Double\n              -> ExceptT OasesError IO (Vector Double, Double)\ninitSparseSQP sqp h g a lbA ubA m'cpuTime =\n  vec' (cscVals h) $ \\_hValsSize hValsPtr ->\n  vec' (cscCols h) $ \\_hColsSize hColsPtr ->\n  vec' (cscRows h) $ \\_hRowsSize hRowsPtr ->\n  vec' g $ \\gSize gPtr ->\n  mat' a $ \\aRow aCol aPtr ->\n  vec' lbA $ \\lbASize lbAPtr ->\n  vec' ubA $ \\ubASize ubAPtr -> do\n    let nVar = gSize\n    let nConstr = aRow\n    unless (nVar == aCol) $ throwE SizeMismatch\n    unless (nConstr == lbASize) $ throwE SizeMismatch\n    unless (nConstr == ubASize) $ throwE SizeMismatch\n    primalFP <- liftIO $ mallocForeignPtrArray (fromIntegral nVar)\n    (obj, status) <- liftIO $ withForeignPtr primalFP $ \\xPtr ->\n      allocaArray (fromIntegral $ nVar + nConstr) $ \\yPtr ->\n      alloca $ \\objPtr ->\n      alloca $ \\statusPtr ->\n      with (5 * fromIntegral (nVar + nConstr)) $ \\nWSRPtr ->\n      maybe ($ nullPtr) with m'cpuTime $ \\cpuTimePtr -> do\n        _ <- withSQProblem sqp $ \\ptr ->\n               sqproblem_sparse_init ptr hRowsPtr hColsPtr hValsPtr gPtr aPtr\n               nullPtr nullPtr lbAPtr ubAPtr\n               nWSRPtr cpuTimePtr xPtr yPtr objPtr statusPtr\n        !obj <- peek objPtr\n        !status <- fromIntegral <$> peek statusPtr\n        return $ (obj, status)\n    let solutionVec = VS.unsafeFromForeignPtr0 primalFP (fromIntegral nVar)\n    if status == 0\n      then return (solutionVec, obj)\n      else throwE (OasesError status)\n  where\n    mat' m f = ExceptT $ mat (cmat m) $ \\church -> church $ \\nrow ncol ptr -> runExceptT $ f nrow ncol ptr\n    vec' v f = ExceptT $ vec v $ \\church -> church $ \\size ptr -> runExceptT $ f size ptr\n\ninitSparseSQPSchur :: SQProblemSchur -> CSC Double -> Vector Double -> Matrix Double\n                   -> Vector Double -> Vector Double -> Maybe Double\n                   -> ExceptT OasesError IO (Vector Double, Double)\ninitSparseSQPSchur sqp h g a lbA ubA m'cpuTime =\n  vec' (cscVals h) $ \\_hValsSize hValsPtr ->\n  vec' (cscCols h) $ \\_hColsSize hColsPtr ->\n  vec' (cscRows h) $ \\_hRowsSize hRowsPtr ->\n  vec' g $ \\gSize gPtr ->\n  mat' a $ \\aRow aCol aPtr ->\n  vec' lbA $ \\lbASize lbAPtr ->\n  vec' ubA $ \\ubASize ubAPtr -> do\n    let nVar = gSize\n    let nConstr = aRow\n    unless (nVar == aCol) $ throwE SizeMismatch\n    unless (nConstr == lbASize) $ throwE SizeMismatch\n    unless (nConstr == ubASize) $ throwE SizeMismatch\n    primalFP <- liftIO $ mallocForeignPtrArray (fromIntegral nVar)\n    (obj, status) <- liftIO $ withForeignPtr primalFP $ \\xPtr ->\n      allocaArray (fromIntegral $ nVar + nConstr) $ \\yPtr ->\n      alloca $ \\objPtr ->\n      alloca $ \\statusPtr ->\n      with (5 * fromIntegral (nVar + nConstr)) $ \\nWSRPtr ->\n      maybe ($ nullPtr) with m'cpuTime $ \\cpuTimePtr -> do\n        _ <- withSQProblemSchur sqp $ \\ptr ->\n               sqproblem_sparse_schur_init ptr hRowsPtr hColsPtr hValsPtr gPtr aPtr\n               nullPtr nullPtr lbAPtr ubAPtr\n               nWSRPtr cpuTimePtr xPtr yPtr objPtr statusPtr\n        !obj <- peek objPtr\n        !status <- fromIntegral <$> peek statusPtr\n        return $ (obj, status)\n    let solutionVec = VS.unsafeFromForeignPtr0 primalFP (fromIntegral nVar)\n    if status == 0\n      then return (solutionVec, obj)\n      else throwE (OasesError status)\n  where\n    mat' m f = ExceptT $ mat (cmat m) $ \\church -> church $ \\nrow ncol ptr -> runExceptT $ f nrow ncol ptr\n    vec' v f = ExceptT $ vec v $ \\church -> church $ \\size ptr -> runExceptT $ f size ptr\n\ninitSparseSparseSQPSchur :: SQProblemSchur -> CSC Double -> Vector Double -> CSC Double\n                   -> Maybe (Vector Double) -> Maybe (Vector Double)\n                   -> Vector Double -> Vector Double -> Maybe Double\n                   -> ExceptT OasesError IO (Vector Double, Double)\ninitSparseSparseSQPSchur sqp h g a m'lb m'ub lbA ubA m'cpuTime =\n  vec' (cscVals h) $ \\_hValsSize hValsPtr ->\n  vec' (cscCols h) $ \\_hColsSize hColsPtr ->\n  vec' (cscRows h) $ \\_hRowsSize hRowsPtr ->\n  vec' g $ \\gSize gPtr ->\n  vec' (cscVals a) $ \\_aValsSize aValsPtr ->\n  vec' (cscCols a) $ \\_aColsSize aColsPtr ->\n  vec' (cscRows a) $ \\_aRowsSize aRowsPtr ->\n  maybe (\\f -> f undefined nullPtr) vec' m'lb $ \\_lbSize lbPtr ->\n  maybe (\\f -> f undefined nullPtr) vec' m'ub $ \\_ubSize ubPtr -> \n  vec' lbA $ \\lbASize lbAPtr ->\n  vec' ubA $ \\ubASize ubAPtr -> do\n    let nVar = gSize\n    let nConstr = cscNRows a\n    unless (nVar == cscNCols a) $ throwE SizeMismatch\n    unless (nConstr == lbASize) $ throwE SizeMismatch\n    unless (nConstr == ubASize) $ throwE SizeMismatch\n    primalFP <- liftIO $ mallocForeignPtrArray (fromIntegral nVar)\n    (obj, status) <- liftIO $ withForeignPtr primalFP $ \\xPtr ->\n      allocaArray (fromIntegral $ nVar + nConstr) $ \\yPtr ->\n      alloca $ \\objPtr ->\n      alloca $ \\statusPtr ->\n      with (5 * fromIntegral (nVar + nConstr)) $ \\nWSRPtr ->\n      maybe ($ nullPtr) with m'cpuTime $ \\cpuTimePtr -> do\n        _ <- withSQProblemSchur sqp $ \\ptr ->\n               sqproblem_sparse_sparse_schur_init ptr hRowsPtr hColsPtr hValsPtr gPtr\n               aRowsPtr aColsPtr aValsPtr\n               lbPtr ubPtr lbAPtr ubAPtr\n               nWSRPtr cpuTimePtr xPtr yPtr objPtr statusPtr\n        !obj <- peek objPtr\n        !status <- fromIntegral <$> peek statusPtr\n        return $ (obj, status)\n    let solutionVec = VS.unsafeFromForeignPtr0 primalFP (fromIntegral nVar)\n    if status == 0\n      then return (solutionVec, obj)\n      else throwE (OasesError status)\n  where\n    mat' m f = ExceptT $ mat (cmat m) $ \\church -> church $ \\nrow ncol ptr -> runExceptT $ f nrow ncol ptr\n    vec' v f = ExceptT $ vec v $ \\church -> church $ \\size ptr -> runExceptT $ f size ptr\n\nhotstartSQP :: SQProblem -> Matrix Double -> Vector Double -> Matrix Double\n            -> Vector Double -> Vector Double -> Maybe Double\n            -> ExceptT OasesError IO (Vector Double, Double)\nhotstartSQP sqp h g a lbA ubA m'cpuTime =\n  mat' h $ \\hRow hCol hPtr ->\n  vec' g $ \\gSize gPtr ->\n  mat' a $ \\aRow aCol aPtr ->\n  vec' lbA $ \\lbASize lbAPtr ->\n  vec' ubA $ \\ubASize ubAPtr -> do\n    let nVar = gSize\n    let nConstr = aRow\n    unless (nVar == hRow) $ throwE SizeMismatch\n    unless (nVar == hRow) $ throwE SizeMismatch\n    unless (nVar == hCol) $ throwE SizeMismatch\n    unless (nVar == aCol) $ throwE SizeMismatch\n    unless (nConstr == lbASize) $ throwE SizeMismatch\n    unless (nConstr == ubASize) $ throwE SizeMismatch\n    primalFP <- liftIO $ mallocForeignPtrArray (fromIntegral nVar)\n    (obj, status) <- liftIO $ withForeignPtr primalFP $ \\xPtr ->\n      allocaArray (fromIntegral $ nVar + nConstr) $ \\yPtr ->\n      alloca $ \\objPtr ->\n      alloca $ \\statusPtr ->\n      with (5 * fromIntegral (nVar + nConstr)) $ \\nWSRPtr ->\n      maybe ($ nullPtr) with m'cpuTime $ \\cpuTimePtr -> do\n        _ <- withSQProblem sqp $ \\ptr ->\n               sqproblem_hotstart ptr hPtr gPtr aPtr nullPtr nullPtr lbAPtr ubAPtr\n               nWSRPtr cpuTimePtr xPtr yPtr objPtr statusPtr\n        !obj <- peek objPtr\n        !status <- fromIntegral <$> peek statusPtr\n        return $ (obj, status)\n    let solutionVec = VS.unsafeFromForeignPtr0 primalFP (fromIntegral nVar)\n    if status == 0\n      then return (solutionVec, obj)\n      else throwE (OasesError status)\n  where\n    mat' m f = ExceptT $ mat (cmat m) $ \\church -> church $ \\nrow ncol ptr -> runExceptT $ f nrow ncol ptr\n    vec' v f = ExceptT $ vec v $ \\church -> church $ \\size ptr -> runExceptT $ f size ptr\n\nhotstartSparseSQP :: SQProblem -> CSC Double -> Vector Double -> Matrix Double\n                  -> Vector Double -> Vector Double -> Maybe Double\n                  -> ExceptT OasesError IO (Vector Double, Double)\nhotstartSparseSQP sqp h g a lbA ubA m'cpuTime =\n  vec' (cscVals h) $ \\_hValsSize hValsPtr ->\n  vec' (cscCols h) $ \\_hColsSize hColsPtr ->\n  vec' (cscRows h) $ \\_hRowsSize hRowsPtr ->\n  vec' g $ \\gSize gPtr ->\n  mat' a $ \\aRow aCol aPtr ->\n  vec' lbA $ \\lbASize lbAPtr ->\n  vec' ubA $ \\ubASize ubAPtr -> do\n    let nVar = gSize\n    let nConstr = aRow\n    unless (nVar == aCol) $ throwE SizeMismatch\n    unless (nConstr == lbASize) $ throwE SizeMismatch\n    unless (nConstr == ubASize) $ throwE SizeMismatch\n    primalFP <- liftIO $ mallocForeignPtrArray (fromIntegral nVar)\n    (obj, status) <- liftIO $ withForeignPtr primalFP $ \\xPtr ->\n      allocaArray (fromIntegral $ nVar + nConstr) $ \\yPtr ->\n      alloca $ \\objPtr ->\n      alloca $ \\statusPtr ->\n      with (5 * fromIntegral (nVar + nConstr)) $ \\nWSRPtr -> do\n      maybe ($ nullPtr) with m'cpuTime $ \\cpuTimePtr -> do\n        _ <- withSQProblem sqp $ \\ptr ->\n               sqproblem_sparse_hotstart ptr hRowsPtr hColsPtr hValsPtr gPtr\n               aPtr nullPtr nullPtr lbAPtr ubAPtr\n               nWSRPtr cpuTimePtr xPtr yPtr objPtr statusPtr\n        !obj <- peek objPtr\n        !status <- fromIntegral <$> peek statusPtr\n        return $ (obj, status)\n    let solutionVec = VS.unsafeFromForeignPtr0 primalFP (fromIntegral nVar)\n    if status == 0\n      then return (solutionVec, obj)\n      else throwE (OasesError status)\n  where\n    mat' m f = ExceptT $ mat (cmat m) $ \\church -> church $ \\nrow ncol ptr -> runExceptT $ f nrow ncol ptr\n    vec' v f = ExceptT $ vec v $ \\church -> church $ \\size ptr -> runExceptT $ f size ptr\n\nhotstartSparseSQPSchur :: SQProblemSchur -> CSC Double -> Vector Double -> Matrix Double\n                  -> Vector Double -> Vector Double -> Maybe Double\n                  -> ExceptT OasesError IO (Vector Double, Double)\nhotstartSparseSQPSchur sqp h g a lbA ubA m'cpuTime =\n  vec' (cscVals h) $ \\_hValsSize hValsPtr ->\n  vec' (cscCols h) $ \\_hColsSize hColsPtr ->\n  vec' (cscRows h) $ \\_hRowsSize hRowsPtr ->\n  vec' g $ \\gSize gPtr ->\n  mat' a $ \\aRow aCol aPtr ->\n  vec' lbA $ \\lbASize lbAPtr ->\n  vec' ubA $ \\ubASize ubAPtr -> do\n    let nVar = gSize\n    let nConstr = aRow\n    unless (nVar == aCol) $ throwE SizeMismatch\n    unless (nConstr == lbASize) $ throwE SizeMismatch\n    unless (nConstr == ubASize) $ throwE SizeMismatch\n    primalFP <- liftIO $ mallocForeignPtrArray (fromIntegral nVar)\n    (obj, status) <- liftIO $ withForeignPtr primalFP $ \\xPtr ->\n      allocaArray (fromIntegral $ nVar + nConstr) $ \\yPtr ->\n      alloca $ \\objPtr ->\n      alloca $ \\statusPtr ->\n      with (5 * fromIntegral (nVar + nConstr)) $ \\nWSRPtr ->\n      maybe ($ nullPtr) with m'cpuTime $ \\cpuTimePtr -> do\n        _ <- withSQProblemSchur sqp $ \\ptr ->\n               sqproblem_sparse_schur_hotstart ptr hRowsPtr hColsPtr hValsPtr gPtr\n               aPtr nullPtr nullPtr lbAPtr ubAPtr\n               nWSRPtr cpuTimePtr xPtr yPtr objPtr statusPtr\n        !obj <- peek objPtr\n        !status <- fromIntegral <$> peek statusPtr\n        return $ (obj, status)\n    let solutionVec = VS.unsafeFromForeignPtr0 primalFP (fromIntegral nVar)\n    if status == 0\n      then return (solutionVec, obj)\n      else throwE (OasesError status)\n  where\n    mat' m f = ExceptT $ mat (cmat m) $ \\church -> church $ \\nrow ncol ptr -> runExceptT $ f nrow ncol ptr\n    vec' v f = ExceptT $ vec v $ \\church -> church $ \\size ptr -> runExceptT $ f size ptr\n\nhotstartSparseSparseSQPSchur :: SQProblemSchur -> CSC Double -> Vector Double -> CSC Double\n                  -> Maybe (Vector Double) -> Maybe (Vector Double) -> Vector Double -> Vector Double -> Maybe Double\n                  -> ExceptT OasesError IO (Vector Double, Double)\nhotstartSparseSparseSQPSchur sqp h g a m'lb m'ub lbA ubA m'cpuTime =\n  vec' (cscVals h) $ \\_hValsSize hValsPtr ->\n  vec' (cscCols h) $ \\_hColsSize hColsPtr ->\n  vec' (cscRows h) $ \\_hRowsSize hRowsPtr ->\n  vec' g $ \\gSize gPtr ->\n  vec' (cscVals a) $ \\_aValsSize aValsPtr ->\n  vec' (cscCols a) $ \\_aColsSize aColsPtr ->\n  vec' (cscRows a) $ \\_aRowsSize aRowsPtr ->\n  maybe (\\f -> f undefined nullPtr) vec' m'lb $ \\_lbSize lbPtr ->\n  maybe (\\f -> f undefined nullPtr) vec' m'ub $ \\_ubSize ubPtr -> \n  vec' lbA $ \\lbASize lbAPtr ->\n  vec' ubA $ \\ubASize ubAPtr -> do\n    let nVar = gSize\n    let nConstr = cscNRows a\n    unless (nVar == cscNCols a) $ throwE SizeMismatch\n    unless (nConstr == lbASize) $ throwE SizeMismatch\n    unless (nConstr == ubASize) $ throwE SizeMismatch\n    primalFP <- liftIO $ mallocForeignPtrArray (fromIntegral nVar)\n    (obj, status) <- liftIO $ withForeignPtr primalFP $ \\xPtr ->\n      allocaArray (fromIntegral $ nVar + nConstr) $ \\yPtr ->\n      alloca $ \\objPtr ->\n      alloca $ \\statusPtr ->\n      with (5 * fromIntegral (nVar + nConstr)) $ \\nWSRPtr ->\n      maybe ($ nullPtr) with m'cpuTime $ \\cpuTimePtr -> do\n        _ <- withSQProblemSchur sqp $ \\ptr ->\n               sqproblem_sparse_sparse_schur_hotstart ptr hRowsPtr hColsPtr hValsPtr gPtr\n               aRowsPtr aColsPtr aValsPtr lbPtr ubPtr lbAPtr ubAPtr\n               nWSRPtr cpuTimePtr xPtr yPtr objPtr statusPtr\n        !obj <- peek objPtr\n        !status <- fromIntegral <$> peek statusPtr\n        return $ (obj, status)\n    let solutionVec = VS.unsafeFromForeignPtr0 primalFP (fromIntegral nVar)\n    if status == 0\n      then return (solutionVec, obj)\n      else throwE (OasesError status)\n  where\n    mat' m f = ExceptT $ mat (cmat m) $ \\church -> church $ \\nrow ncol ptr -> runExceptT $ f nrow ncol ptr\n    vec' v f = ExceptT $ vec v $ \\church -> church $ \\size ptr -> runExceptT $ f size ptr\n\ndata Options\n\nforeign import ccall \"sqproblem_init\"\n    sqproblem_init\n        :: Ptr SQProblem -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> IO CInt\n\nforeign import ccall \"sqproblem_sparse_init\"\n    sqproblem_sparse_init\n        :: Ptr SQProblem -> Ptr CInt -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> IO CInt\n\nforeign import ccall \"sqproblem_sparse_schur_init\"\n    sqproblem_sparse_schur_init\n        :: Ptr SQProblemSchur -> Ptr CInt -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> IO CInt\n\nforeign import ccall \"sqproblem_sparse_sparse_schur_init\"\n    sqproblem_sparse_sparse_schur_init\n        :: Ptr SQProblemSchur -> Ptr CInt -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr CInt -> Ptr CInt -> Ptr Double -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> IO CInt\n\nforeign import ccall \"sqproblem_hotstart\"\n    sqproblem_hotstart\n        :: Ptr SQProblem -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> IO CInt\n\nforeign import ccall \"sqproblem_sparse_hotstart\"\n    sqproblem_sparse_hotstart\n        :: Ptr SQProblem -> Ptr CInt -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> IO CInt\n\nforeign import ccall \"sqproblem_sparse_schur_hotstart\"\n    sqproblem_sparse_schur_hotstart\n        :: Ptr SQProblemSchur -> Ptr CInt -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> IO CInt\n\nforeign import ccall \"sqproblem_sparse_sparse_schur_hotstart\"\n    sqproblem_sparse_sparse_schur_hotstart\n        :: Ptr SQProblemSchur -> Ptr CInt -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr CInt -> Ptr CInt -> Ptr Double -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> Ptr Double\n        -> Ptr Double -> Ptr Double -> Ptr Double -> Ptr CInt -> IO CInt\n\nforeign import ccall \"sqproblem_setup\"\n    sqproblem_setup\n        :: CInt -> CInt -> CInt -> Ptr (Ptr SQProblem)-> IO CInt\n\nforeign import ccall \"sqproblem_schur_setup\"\n    sqproblem_schur_setup\n        :: CInt -> CInt -> CInt -> Ptr (Ptr SQProblemSchur)-> IO CInt\n\nforeign import ccall \"&sqproblem_cleanup\"\n    sqproblem_cleanup\n        :: FunPtr (Ptr SQProblem -> IO ())\n\nforeign import ccall \"&sqproblem_schur_cleanup\"\n    sqproblem_schur_cleanup\n        :: FunPtr (Ptr SQProblemSchur -> IO ())\n", "meta": {"hexsha": "e55bf76e55df17cad734fc3ff6f97608ccf5dbb7", "size": 19938, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/QpOases.hs", "max_stars_repo_name": "alang9/qp", "max_stars_repo_head_hexsha": "feb1705bcb47c31dabc88c69fd7897b55215cd1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/QpOases.hs", "max_issues_repo_name": "alang9/qp", "max_issues_repo_head_hexsha": "feb1705bcb47c31dabc88c69fd7897b55215cd1a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/QpOases.hs", "max_forks_repo_name": "alang9/qp", "max_forks_repo_head_hexsha": "feb1705bcb47c31dabc88c69fd7897b55215cd1a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6932084309, "max_line_length": 140, "alphanum_fraction": 0.6425418798, "num_tokens": 5994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.40660985097528846}}
{"text": "module HashedExpression.Interp\n  ( Evaluable (..),\n    Approximable (..),\n  )\nwhere\n\nimport Data.Array\nimport Data.Complex\nimport qualified Data.IntMap.Strict as IM\nimport Data.List (intercalate)\nimport Data.Map (Map, fromList)\nimport qualified Data.Map as Map\nimport Debug.Trace (traceId, traceShowId)\nimport GHC.TypeLits (KnownNat)\nimport HashedExpression.Internal.Expression\n  ( C,\n    ET (..),\n    Expression (..),\n    ExpressionMap,\n    Node (..),\n    NodeID,\n    NodeID,\n    R,\n    Scalar,\n  )\nimport HashedExpression.Internal.Node\nimport HashedExpression.Internal.Utils\nimport HashedExpression.Prettify (prettify, showExp)\nimport HashedExpression.Value\nimport Text.Printf\n\n-- | This operation emulates the mathematical operation\n-- | Turn expression to the right type\nexpZeroR :: ExpressionMap -> NodeID -> Expression Scalar R\nexpZeroR = flip Expression\n\nexpZeroC :: ExpressionMap -> NodeID -> Expression Scalar C\nexpZeroC = flip Expression\n\n-- | Choose branch base on condition value\nchooseBranch :: [Double] -> Double -> [a] -> a\nchooseBranch marks val branches\n  | val < head marks = head branches\n  | otherwise =\n    snd . last . filter ((val >=) . fst) $ zip marks (tail branches)\n\n-- | Approximable class\nclass\n  Show a =>\n  Approximable a where\n  (~=) :: a -> a -> Bool\n  prettifyShow :: a -> String\n\ninfix 4 ~=\n\n-- |\nrelativeError :: Double -> Double -> Double\nrelativeError a b = abs (a - b) / max (abs a) (abs b)\n\ninstance Approximable Double where\n  (~=) :: Double -> Double -> Bool\n  a ~= b\n    | abs (a - b) < 1.0e-5 = True\n    | a == b = True\n    | otherwise = relativeError a b < 0.01\n  prettifyShow a\n    | abs a < 1e-10 = \"0\"\n    | otherwise = printf \"%.2f\" a\n\ninstance Approximable (Complex Double) where\n  (~=) :: Complex Double -> Complex Double -> Bool\n  a ~= b = (realPart a ~= realPart b) && (imagPart a ~= imagPart b)\n  prettifyShow a =\n    prettifyShow (realPart a) ++ \" + \" ++ prettifyShow (imagPart a) ++ \"i\"\n\ninstance Approximable (Array Int Double) where\n  (~=) :: Array Int Double -> Array Int Double -> Bool\n  a ~= b = (bounds a == bounds b) && and (zipWith (~=) (elems a) (elems b))\n  prettifyShow a =\n    \"[\" ++ (intercalate \", \" . map prettifyShow . elems $ a) ++ \"]\"\n\ninstance Approximable (Array Int (Complex Double)) where\n  (~=) :: Array Int (Complex Double) -> Array Int (Complex Double) -> Bool\n  a ~= b = (bounds a == bounds b) && and (zipWith (~=) (elems a) (elems b))\n  prettifyShow a =\n    \"[\" ++ (intercalate \", \" . map prettifyShow . elems $ a) ++ \"]\"\n\ninstance Approximable (Array (Int, Int) Double) where\n  (~=) :: Array (Int, Int) Double -> Array (Int, Int) Double -> Bool\n  a ~= b = (bounds a == bounds b) && and (zipWith (~=) (elems a) (elems b))\n  prettifyShow a =\n    \"[\" ++ (intercalate \", \" . map prettifyShow . elems $ a) ++ \"]\"\n\ninstance Approximable (Array (Int, Int) (Complex Double)) where\n  (~=) ::\n    Array (Int, Int) (Complex Double) ->\n    Array (Int, Int) (Complex Double) ->\n    Bool\n  a ~= b = (bounds a == bounds b) && and (zipWith (~=) (elems a) (elems b))\n  prettifyShow a =\n    \"[\" ++ (intercalate \", \" . map prettifyShow . elems $ a) ++ \"]\"\n\ninstance Approximable (Array (Int, Int, Int) Double) where\n  (~=) :: Array (Int, Int, Int) Double -> Array (Int, Int, Int) Double -> Bool\n  a ~= b = (bounds a == bounds b) && and (zipWith (~=) (elems a) (elems b))\n  prettifyShow a =\n    \"[\" ++ (intercalate \", \" . map prettifyShow . elems $ a) ++ \"]\"\n\ninstance Approximable (Array (Int, Int, Int) (Complex Double)) where\n  (~=) ::\n    Array (Int, Int, Int) (Complex Double) ->\n    Array (Int, Int, Int) (Complex Double) ->\n    Bool\n  a ~= b = (bounds a == bounds b) && and (zipWith (~=) (elems a) (elems b))\n  prettifyShow a =\n    \"[\" ++ (intercalate \", \" . map prettifyShow . elems $ a) ++ \"]\"\n\n-- | These should be commented properly.\nclass Evaluable d rc output | d rc -> output where\n  eval :: ValMaps -> Expression d rc -> output\n\n-- |\ninstance Evaluable Scalar R Double where\n  eval :: ValMaps -> Expression Scalar R -> Double\n  eval valMap e@(Expression n mp)\n    | [] <- retrieveShape n mp =\n      case retrieveNode n mp of\n        Var name ->\n          case Map.lookup name valMap of\n            Just (VScalar val) -> val\n            _ -> error \"no value associated with the variable\"\n        Const val -> val\n        Sum R args -> sum . map (eval valMap . expZeroR mp) $ args\n        Mul R args -> product . map (eval valMap . expZeroR mp) $ args\n        Neg R arg -> - (eval valMap $ expZeroR mp arg)\n        Scale R arg1 arg2 ->\n          eval valMap (expZeroR mp arg1)\n            * eval valMap (expZeroR mp arg2)\n        Power x arg -> eval valMap (expZeroR mp arg) ^ x\n        Div arg1 arg2 ->\n          eval valMap (expZeroR mp arg1)\n            / eval valMap (expZeroR mp arg2)\n        Sqrt arg -> sqrt (eval valMap (expZeroR mp arg))\n        Sin arg -> sin (eval valMap (expZeroR mp arg))\n        Cos arg -> cos (eval valMap (expZeroR mp arg))\n        Tan arg -> tan (eval valMap (expZeroR mp arg))\n        Exp arg -> exp (eval valMap (expZeroR mp arg))\n        Log arg -> log (eval valMap (expZeroR mp arg))\n        Sinh arg -> sinh (eval valMap (expZeroR mp arg))\n        Cosh arg -> cosh (eval valMap (expZeroR mp arg))\n        Tanh arg -> tanh (eval valMap (expZeroR mp arg))\n        Asin arg -> asin (eval valMap (expZeroR mp arg))\n        Acos arg -> acos (eval valMap (expZeroR mp arg))\n        Atan arg -> atan (eval valMap (expZeroR mp arg))\n        Asinh arg -> asinh (eval valMap (expZeroR mp arg))\n        Acosh arg -> acosh (eval valMap (expZeroR mp arg))\n        Atanh arg -> atanh (eval valMap (expZeroR mp arg))\n        RealPart arg -> realPart (eval valMap (expZeroC mp arg))\n        ImagPart arg -> imagPart (eval valMap (expZeroC mp arg))\n        InnerProd R arg1 arg2 ->\n          case retrieveShape arg1 mp of\n            [] ->\n              eval valMap (expZeroR mp arg1)\n                * eval valMap (expZeroR mp arg2)\n            [size] ->\n              let res1 = evaluate1DReal valMap $ (mp, arg1)\n                  res2 = evaluate1DReal valMap $ (mp, arg2)\n               in sum\n                    [ x * y\n                      | i <- [0 .. size - 1],\n                        let x = res1 ! i,\n                        let y = res2 ! i\n                    ]\n            [size1, size2] ->\n              let res1 = evaluate2DReal valMap $ (mp, arg1)\n                  res2 = evaluate2DReal valMap $ (mp, arg2)\n               in sum\n                    [ x * y\n                      | i <- [0 .. size1 - 1],\n                        j <- [0 .. size2 - 1],\n                        let x = res1 ! (i, j),\n                        let y = res2 ! (i, j)\n                    ]\n            [size1, size2, size3] ->\n              let res1 = evaluate3DReal valMap $ (mp, arg1)\n                  res2 = evaluate3DReal valMap $ (mp, arg2)\n               in sum\n                    [ x * y\n                      | i <- [0 .. size1 - 1],\n                        j <- [0 .. size2 - 1],\n                        k <- [0 .. size3 - 1],\n                        let x = res1 ! (i, j, k),\n                        let y = res2 ! (i, j, k)\n                    ]\n            _ -> error \"4D shape?\"\n        Piecewise marks conditionArg branchArgs ->\n          let cdt = eval valMap $ expZeroR mp conditionArg\n              branches = map (eval valMap . expZeroR mp) branchArgs\n           in chooseBranch marks cdt branches\n        _ ->\n          error\n            (\"expression structure Scalar R is wrong \" ++ prettify e)\n    | otherwise = error \"one r but shape is not [] ??\"\n\ninstance Evaluable Scalar C (Complex Double) where\n  eval :: ValMaps -> Expression Scalar C -> Complex Double\n  eval valMap e@(Expression n mp)\n    | [] <- retrieveShape n mp =\n      case retrieveNode n mp of\n        Sum C args -> sum . map (eval valMap . expZeroC mp) $ args\n        Mul C args -> product . map (eval valMap . expZeroC mp) $ args\n        Power x arg -> eval valMap (expZeroC mp arg) ^ x\n        Neg C arg -> - (eval valMap $ expZeroC mp arg)\n        Scale C arg1 arg2 ->\n          case retrieveElementType arg1 mp of\n            R ->\n              fromR (eval valMap (expZeroR mp arg1))\n                * eval valMap (expZeroC mp arg2)\n            C ->\n              eval valMap (expZeroC mp arg1)\n                * eval valMap (expZeroC mp arg2)\n        RealImag arg1 arg2 ->\n          eval valMap (expZeroR mp arg1)\n            :+ eval valMap (expZeroR mp arg2)\n        InnerProd C arg1 arg2 ->\n          case retrieveShape arg1 mp of\n            [] ->\n              eval valMap (expZeroC mp arg1)\n                * conjugate (eval valMap (expZeroC mp arg2))\n            [size] ->\n              let res1 = evaluate1DComplex valMap $ (mp, arg1)\n                  res2 = evaluate1DComplex valMap $ (mp, arg2)\n               in sum\n                    [ x * conjugate y\n                      | i <- [0 .. size - 1],\n                        let x = res1 ! i,\n                        let y = res2 ! i\n                    ]\n            [size1, size2] ->\n              let res1 = evaluate2DComplex valMap $ (mp, arg1)\n                  res2 = evaluate2DComplex valMap $ (mp, arg2)\n               in sum\n                    [ x * conjugate y\n                      | i <- [0 .. size1 - 1],\n                        j <- [0 .. size2 - 1],\n                        let x = res1 ! (i, j),\n                        let y = res2 ! (i, j)\n                    ]\n            [size1, size2, size3] ->\n              let res1 = evaluate3DComplex valMap $ (mp, arg1)\n                  res2 = evaluate3DComplex valMap $ (mp, arg2)\n               in sum\n                    [ x * conjugate y\n                      | i <- [0 .. size1 - 1],\n                        j <- [0 .. size2 - 1],\n                        k <- [0 .. size3 - 1],\n                        let x = res1 ! (i, j, k),\n                        let y = res2 ! (i, j, k)\n                    ]\n            _ -> error \"4D shape?\"\n        Piecewise marks conditionArg branchArgs ->\n          let cdt = eval valMap $ expZeroR mp conditionArg\n              branches = map (eval valMap . expZeroC mp) branchArgs\n           in chooseBranch marks cdt branches\n        _ ->\n          error\n            (\"expression structure Scalar C is wrong \" ++ prettify e)\n    | otherwise = error \"One C but shape is not [] ??\"\n\n-- |\nzipWithA :: Ix x => (a -> b -> c) -> Array x a -> Array x b -> Array x c\nzipWithA f xs ys = listArray (bounds xs) $ zipWith f (elems xs) (elems ys)\n\nfoldrElementwise :: Ix ix => (a -> a -> a) -> [Array ix a] -> Array ix a\nfoldrElementwise f [x] = x\nfoldrElementwise f (x : xs) = zipWithA f x (foldrElementwise f xs)\n\n-- |\nevaluate1DReal :: ValMaps -> (ExpressionMap, NodeID) -> Array Int Double\nevaluate1DReal valMap (mp, n)\n  | [size] <- retrieveShape n mp =\n    case retrieveNode n mp of\n      Var name ->\n        case Map.lookup name valMap of\n          Just (V1D val) -> val\n          _ -> error \"no value associated with the variable\"\n      Const val -> listArray (0, size - 1) $ replicate size val\n      Sum R args ->\n        foldrElementwise (+) . map (evaluate1DReal valMap . (mp,)) $\n          args\n      Mul R args ->\n        foldrElementwise (*) . map (evaluate1DReal valMap . (mp,)) $\n          args\n      Power x arg -> fmap (^ x) (evaluate1DReal valMap $ (mp, arg))\n      Neg R arg -> fmap negate . evaluate1DReal valMap $ (mp, arg)\n      Scale R arg1 arg2 ->\n        let scalar = eval valMap $ expZeroR mp arg1\n         in fmap (scalar *) . evaluate1DReal valMap $ (mp, arg2)\n      Div arg1 arg2 ->\n        zipWithA\n          (/)\n          (evaluate1DReal valMap $ (mp, arg2))\n          (evaluate1DReal valMap $ (mp, arg2))\n      Sqrt arg -> fmap sqrt . evaluate1DReal valMap $ (mp, arg)\n      Sin arg -> fmap sin . evaluate1DReal valMap $ (mp, arg)\n      Cos arg -> fmap cos . evaluate1DReal valMap $ (mp, arg)\n      Tan arg -> fmap tan . evaluate1DReal valMap $ (mp, arg)\n      Exp arg -> fmap exp . evaluate1DReal valMap $ (mp, arg)\n      Log arg -> fmap log . evaluate1DReal valMap $ (mp, arg)\n      Sinh arg -> fmap sinh . evaluate1DReal valMap $ (mp, arg)\n      Cosh arg -> fmap cosh . evaluate1DReal valMap $ (mp, arg)\n      Tanh arg -> fmap tanh . evaluate1DReal valMap $ (mp, arg)\n      Asin arg -> fmap asin . evaluate1DReal valMap $ (mp, arg)\n      Acos arg -> fmap acos . evaluate1DReal valMap $ (mp, arg)\n      Atan arg -> fmap atan . evaluate1DReal valMap $ (mp, arg)\n      Asinh arg -> fmap asinh . evaluate1DReal valMap $ (mp, arg)\n      Acosh arg -> fmap acosh . evaluate1DReal valMap $ (mp, arg)\n      Atanh arg -> fmap atanh . evaluate1DReal valMap $ (mp, arg)\n      RealPart arg -> fmap realPart . evaluate1DComplex valMap $ (mp, arg)\n      ImagPart arg -> fmap imagPart . evaluate1DComplex valMap $ (mp, arg)\n      -- Rotate rA arg ->\n      Piecewise marks conditionArg branchArgs ->\n        let cdt = evaluate1DReal valMap $ (mp, conditionArg)\n            branches = map (evaluate1DReal valMap . (mp,)) branchArgs\n         in listArray\n              (0, size - 1)\n              [ chosen ! i\n                | i <- [0 .. size - 1],\n                  let chosen = chooseBranch marks (cdt ! i) branches\n              ]\n      Rotate [amount] arg ->\n        rotate1D size amount (evaluate1DReal valMap $ (mp, arg))\n      TwiceReFT arg ->\n        let innerRes = evaluate1DReal valMap $ (mp, arg)\n            scaleFactor = fromIntegral size / 2\n         in listArray\n              (0, size - 1)\n              [ scaleFactor\n                  * (innerRes ! i + innerRes ! ((size - i) `mod` size))\n                | i <- [0 .. size - 1]\n              ]\n      TwiceImFT arg ->\n        let innerRes = evaluate1DReal valMap $ (mp, arg)\n            scaleFactor = fromIntegral size / 2\n         in listArray\n              (0, size - 1)\n              [ scaleFactor\n                  * (innerRes ! i - innerRes ! ((size - i) `mod` size))\n                | i <- [0 .. size - 1]\n              ]\n      ReFT arg ->\n        case retrieveElementType arg mp of\n          R ->\n            let inner =\n                  fmap (:+ 0) . evaluate1DReal valMap $ (mp, arg)\n                ftResult = fourierTransform1D size inner\n             in fmap realPart ftResult\n          C ->\n            let inner = evaluate1DComplex valMap $ (mp, arg)\n                ftResult = fourierTransform1D size inner\n             in fmap realPart ftResult\n      ImFT arg ->\n        case retrieveElementType arg mp of\n          R ->\n            let inner =\n                  fmap (:+ 0) . evaluate1DReal valMap $ (mp, arg)\n                ftResult = fourierTransform1D size inner\n             in fmap imagPart ftResult\n          C ->\n            let inner = evaluate1DComplex valMap $ (mp, arg)\n                ftResult = fourierTransform1D size inner\n             in fmap imagPart ftResult\n      _ -> error \"expression structure One R is wrong\"\n  | otherwise = error \"one r but shape is not [size] ??\"\n\ninstance (KnownNat n) => Evaluable n R (Array Int Double) where\n  eval :: ValMaps -> Expression n R -> Array Int Double\n  eval valMap (Expression n mp) = evaluate1DReal valMap (mp, n)\n\n-- |\nevaluate1DComplex ::\n  ValMaps -> (ExpressionMap, NodeID) -> Array Int (Complex Double)\nevaluate1DComplex valMap (mp, n)\n  | [size] <- retrieveShape n mp =\n    case retrieveNode n mp of\n      Sum C args ->\n        foldrElementwise (+) . map (evaluate1DComplex valMap . (mp,)) $\n          args\n      Mul C args ->\n        foldrElementwise (*) . map (evaluate1DComplex valMap . (mp,)) $\n          args\n      Power x arg -> fmap (^ x) (evaluate1DComplex valMap $ (mp, arg))\n      Neg C arg -> fmap negate . evaluate1DComplex valMap $ (mp, arg)\n      Scale C arg1 arg2 ->\n        case retrieveElementType arg1 mp of\n          R ->\n            let scalar = fromR . eval valMap $ expZeroR mp arg1\n             in fmap (scalar *) . evaluate1DComplex valMap $\n                  (mp, arg2)\n          C ->\n            let scalar = eval valMap $ expZeroC mp arg1\n             in fmap (scalar *) . evaluate1DComplex valMap $\n                  (mp, arg2)\n      RealImag arg1 arg2 ->\n        zipWithA\n          (:+)\n          (evaluate1DReal valMap $ (mp, arg1))\n          (evaluate1DReal valMap $ (mp, arg2))\n      Piecewise marks conditionArg branchArgs ->\n        let cdt = evaluate1DReal valMap $ (mp, conditionArg)\n            branches =\n              map (evaluate1DComplex valMap . (mp,)) branchArgs\n         in listArray\n              (0, size - 1)\n              [ chosen ! i\n                | i <- [0 .. size - 1],\n                  let chosen = chooseBranch marks (cdt ! i) branches\n              ]\n      Rotate [amount] arg ->\n        rotate1D size amount (evaluate1DComplex valMap $ (mp, arg))\n      _ -> error \"expression structure One C is wrong\"\n  | otherwise = error \"one C but shape is not [size] ??\"\n\n--                         in chooseBranch marks cdt branches\ninstance (KnownNat n) => Evaluable n C (Array Int (Complex Double)) where\n  eval :: ValMaps -> Expression n C -> Array Int (Complex Double)\n  eval valMap (Expression n mp) = evaluate1DComplex valMap (mp, n)\n\n-- |\nevaluate2DReal :: ValMaps -> (ExpressionMap, NodeID) -> Array (Int, Int) Double\nevaluate2DReal valMap (mp, n)\n  | [size1, size2] <- retrieveShape n mp =\n    case retrieveNode n mp of\n      Var name ->\n        case Map.lookup name valMap of\n          Just (V2D val) -> val\n          _ -> error $ \"no value associated with the variable\" ++ name\n      Const val ->\n        listArray ((0, 0), (size1 - 1, size2 - 1)) $\n          replicate (size1 * size2) val\n      Sum R args ->\n        foldrElementwise (+) . map (evaluate2DReal valMap . (mp,)) $\n          args\n      Mul R args ->\n        foldrElementwise (*) . map (evaluate2DReal valMap . (mp,)) $\n          args\n      Power x arg -> fmap (^ x) (evaluate2DReal valMap $ (mp, arg))\n      Neg R arg -> fmap negate . evaluate2DReal valMap $ (mp, arg)\n      Scale R arg1 arg2 ->\n        let scalar = eval valMap $ expZeroR mp arg1\n         in fmap (scalar *) . evaluate2DReal valMap $ (mp, arg2)\n      Div arg1 arg2 ->\n        zipWithA\n          (/)\n          (evaluate2DReal valMap $ (mp, arg2))\n          (evaluate2DReal valMap $ (mp, arg2))\n      Sqrt arg -> fmap sqrt . evaluate2DReal valMap $ (mp, arg)\n      Sin arg -> fmap sin . evaluate2DReal valMap $ (mp, arg)\n      Cos arg -> fmap cos . evaluate2DReal valMap $ (mp, arg)\n      Tan arg -> fmap tan . evaluate2DReal valMap $ (mp, arg)\n      Exp arg -> fmap exp . evaluate2DReal valMap $ (mp, arg)\n      Log arg -> fmap log . evaluate2DReal valMap $ (mp, arg)\n      Sinh arg -> fmap sinh . evaluate2DReal valMap $ (mp, arg)\n      Cosh arg -> fmap cosh . evaluate2DReal valMap $ (mp, arg)\n      Tanh arg -> fmap tanh . evaluate2DReal valMap $ (mp, arg)\n      Asin arg -> fmap asin . evaluate2DReal valMap $ (mp, arg)\n      Acos arg -> fmap acos . evaluate2DReal valMap $ (mp, arg)\n      Atan arg -> fmap atan . evaluate2DReal valMap $ (mp, arg)\n      Asinh arg -> fmap asinh . evaluate2DReal valMap $ (mp, arg)\n      Acosh arg -> fmap acosh . evaluate2DReal valMap $ (mp, arg)\n      Atanh arg -> fmap atanh . evaluate2DReal valMap $ (mp, arg)\n      RealPart arg -> fmap realPart . evaluate2DComplex valMap $ (mp, arg)\n      ImagPart arg -> fmap imagPart . evaluate2DComplex valMap $ (mp, arg)\n      Piecewise marks conditionArg branchArgs ->\n        let cdt = evaluate2DReal valMap $ (mp, conditionArg)\n            branches = map (evaluate2DReal valMap . (mp,)) branchArgs\n         in listArray\n              ((0, 0), (size1 - 1, size2 - 1))\n              [ chosen ! (i, j)\n                | i <- [0 .. size1 - 1],\n                  j <- [0 .. size2 - 1],\n                  let chosen =\n                        chooseBranch marks (cdt ! (i, j)) branches\n              ]\n      Rotate [amount1, amount2] arg ->\n        rotate2D\n          (size1, size2)\n          (amount1, amount2)\n          (evaluate2DReal valMap $ (mp, arg))\n      TwiceReFT arg ->\n        let innerRes = evaluate2DReal valMap $ (mp, arg)\n            scaleFactor = fromIntegral size1 * fromIntegral size2 / 2\n         in listArray\n              ((0, 0), (size1 - 1, size2 - 1))\n              [ scaleFactor\n                  * ( innerRes ! (i, j)\n                        + innerRes\n                        ! ((size1 - i) `mod` size1, (size2 - j) `mod` size2)\n                    )\n                | i <- [0 .. size1 - 1],\n                  j <- [0 .. size2 - 1]\n              ]\n      TwiceImFT arg ->\n        let innerRes = evaluate2DReal valMap $ (mp, arg)\n            scaleFactor = fromIntegral size1 * fromIntegral size2 / 2\n         in listArray\n              ((0, 0), (size1 - 1, size2 - 1))\n              [ scaleFactor\n                  * ( innerRes ! (i, j)\n                        - innerRes\n                        ! ((size1 - i) `mod` size1, (size2 - j) `mod` size2)\n                    )\n                | i <- [0 .. size1 - 1],\n                  j <- [0 .. size2 - 1]\n              ]\n      ReFT arg ->\n        case retrieveElementType arg mp of\n          R ->\n            let inner =\n                  fmap (:+ 0) . evaluate2DReal valMap $ (mp, arg)\n                ftResult = fourierTransform2D (size1, size2) inner\n             in fmap realPart ftResult\n          C ->\n            let inner = evaluate2DComplex valMap $ (mp, arg)\n                ftResult = fourierTransform2D (size1, size2) inner\n             in fmap realPart ftResult\n      ImFT arg ->\n        case retrieveElementType arg mp of\n          R ->\n            let inner =\n                  fmap (:+ 0) . evaluate2DReal valMap $ (mp, arg)\n                ftResult = fourierTransform2D (size1, size2) inner\n             in fmap imagPart ftResult\n          C ->\n            let inner = evaluate2DComplex valMap $ (mp, arg)\n                ftResult = fourierTransform2D (size1, size2) inner\n             in fmap imagPart ftResult\n      _ -> error \"expression structure Two R is wrong\"\n  | otherwise = error \"Two r but shape is not [size1, size2] ??\"\n\ninstance\n  (KnownNat m, KnownNat n) =>\n  Evaluable '(m, n) R (Array (Int, Int) Double)\n  where\n  eval :: ValMaps -> Expression '(m, n) R -> Array (Int, Int) Double\n  eval valMap (Expression n mp) = evaluate2DReal valMap (mp, n)\n\n-- |\nevaluate2DComplex ::\n  ValMaps -> (ExpressionMap, NodeID) -> Array (Int, Int) (Complex Double)\nevaluate2DComplex valMap (mp, n)\n  | [size1, size2] <- retrieveShape n mp =\n    case retrieveNode n mp of\n      Sum C args ->\n        foldrElementwise (+) . map (evaluate2DComplex valMap . (mp,)) $\n          args\n      Mul C args ->\n        foldrElementwise (*) . map (evaluate2DComplex valMap . (mp,)) $\n          args\n      Power x arg -> fmap (^ x) (evaluate2DComplex valMap $ (mp, arg))\n      Neg C arg -> fmap negate . evaluate2DComplex valMap $ (mp, arg)\n      Scale C arg1 arg2 ->\n        case retrieveElementType arg1 mp of\n          R ->\n            let scalar = fromR . eval valMap $ expZeroR mp arg1\n             in fmap (scalar *) . evaluate2DComplex valMap $\n                  (mp, arg2)\n          C ->\n            let scalar = eval valMap $ expZeroC mp arg1\n             in fmap (scalar *) . evaluate2DComplex valMap $\n                  (mp, arg2)\n      RealImag arg1 arg2 ->\n        zipWithA\n          (:+)\n          (evaluate2DReal valMap $ (mp, arg1))\n          (evaluate2DReal valMap $ (mp, arg2))\n      Piecewise marks conditionArg branchArgs ->\n        let cdt = evaluate2DReal valMap $ (mp, conditionArg)\n            branches =\n              map (evaluate2DComplex valMap . (mp,)) branchArgs\n         in listArray\n              ((0, 0), (size1 - 1, size2 - 1))\n              [ chosen ! (i, j)\n                | i <- [0 .. size1 - 1],\n                  j <- [0 .. size2 - 1],\n                  let chosen =\n                        chooseBranch marks (cdt ! (i, j)) branches\n              ]\n      Rotate [amount1, amount2] arg ->\n        rotate2D\n          (size1, size2)\n          (amount1, amount2)\n          (evaluate2DComplex valMap $ (mp, arg))\n      _ -> error \"expression structure Two C is wrong\"\n  | otherwise = error \"Two C but shape is not [size1, size2] ??\"\n\ninstance\n  (KnownNat m, KnownNat n) =>\n  Evaluable '(m, n) C (Array (Int, Int) (Complex Double))\n  where\n  eval ::\n    ValMaps -> Expression '(m, n) C -> Array (Int, Int) (Complex Double)\n  eval valMap (Expression n mp) = evaluate2DComplex valMap (mp, n)\n\nevaluate3DReal ::\n  ValMaps -> (ExpressionMap, NodeID) -> Array (Int, Int, Int) Double\nevaluate3DReal valMap (mp, n)\n  | [size1, size2, size3] <- retrieveShape n mp =\n    case retrieveNode n mp of\n      Var name ->\n        case Map.lookup name valMap of\n          Just (V3D val) -> val\n          _ -> error \"no value associated with the variable\"\n      Const val ->\n        listArray ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1)) $\n          replicate (size1 * size2 * size3) val\n      Sum R args ->\n        foldrElementwise (+) . map (evaluate3DReal valMap . (mp,)) $\n          args\n      Mul R args ->\n        foldrElementwise (*) . map (evaluate3DReal valMap . (mp,)) $\n          args\n      Power x arg -> fmap (^ x) (evaluate3DReal valMap $ (mp, arg))\n      Neg R arg -> fmap negate . evaluate3DReal valMap $ (mp, arg)\n      Scale R arg1 arg2 ->\n        let scalar = eval valMap $ expZeroR mp arg1\n         in fmap (scalar *) . evaluate3DReal valMap $ (mp, arg2)\n      Div arg1 arg2 ->\n        zipWithA\n          (/)\n          (evaluate3DReal valMap $ (mp, arg2))\n          (evaluate3DReal valMap $ (mp, arg2))\n      Sqrt arg -> fmap sqrt . evaluate3DReal valMap $ (mp, arg)\n      Sin arg -> fmap sin . evaluate3DReal valMap $ (mp, arg)\n      Cos arg -> fmap cos . evaluate3DReal valMap $ (mp, arg)\n      Tan arg -> fmap tan . evaluate3DReal valMap $ (mp, arg)\n      Exp arg -> fmap exp . evaluate3DReal valMap $ (mp, arg)\n      Log arg -> fmap log . evaluate3DReal valMap $ (mp, arg)\n      Sinh arg -> fmap sinh . evaluate3DReal valMap $ (mp, arg)\n      Cosh arg -> fmap cosh . evaluate3DReal valMap $ (mp, arg)\n      Tanh arg -> fmap tanh . evaluate3DReal valMap $ (mp, arg)\n      Asin arg -> fmap asin . evaluate3DReal valMap $ (mp, arg)\n      Acos arg -> fmap acos . evaluate3DReal valMap $ (mp, arg)\n      Atan arg -> fmap atan . evaluate3DReal valMap $ (mp, arg)\n      Asinh arg -> fmap asinh . evaluate3DReal valMap $ (mp, arg)\n      Acosh arg -> fmap acosh . evaluate3DReal valMap $ (mp, arg)\n      Atanh arg -> fmap atanh . evaluate3DReal valMap $ (mp, arg)\n      RealPart arg -> fmap realPart . evaluate3DComplex valMap $ (mp, arg)\n      ImagPart arg -> fmap imagPart . evaluate3DComplex valMap $ (mp, arg)\n      Piecewise marks conditionArg branchArgs ->\n        let cdt = evaluate3DReal valMap $ (mp, conditionArg)\n            branches = map (evaluate3DReal valMap . (mp,)) branchArgs\n         in listArray\n              ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n              [ chosen ! (i, j, k)\n                | i <- [0 .. size1 - 1],\n                  j <- [0 .. size2 - 1],\n                  k <- [0 .. size3 - 1],\n                  let chosen =\n                        chooseBranch marks (cdt ! (i, j, k)) branches\n              ]\n      Rotate [amount1, amount2, amount3] arg ->\n        rotate3D\n          (size1, size2, size3)\n          (amount1, amount2, amount3)\n          (evaluate3DReal valMap $ (mp, arg))\n      TwiceReFT arg ->\n        let innerRes = evaluate3DReal valMap $ (mp, arg)\n            scaleFactor =\n              fromIntegral size1 * fromIntegral size2\n                * fromIntegral size3\n                / 2\n         in listArray\n              ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n              [ scaleFactor\n                  * ( innerRes ! (i, j, k)\n                        + innerRes\n                        ! ( (size1 - i) `mod` size1,\n                            (size2 - j) `mod` size2,\n                            (size3 - k) `mod` size3\n                          )\n                    )\n                | i <- [0 .. size1 - 1],\n                  j <- [0 .. size2 - 1],\n                  k <- [0 .. size3 - 1]\n              ]\n      TwiceImFT arg ->\n        let innerRes = evaluate3DReal valMap $ (mp, arg)\n            scaleFactor =\n              fromIntegral size1 * fromIntegral size2\n                * fromIntegral size3\n                / 2\n         in listArray\n              ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n              [ scaleFactor\n                  * ( innerRes ! (i, j, k)\n                        - innerRes\n                        ! ( (size1 - i) `mod` size1,\n                            (size2 - j) `mod` size2,\n                            (size3 - k) `mod` size3\n                          )\n                    )\n                | i <- [0 .. size1 - 1],\n                  j <- [0 .. size2 - 1],\n                  k <- [0 .. size3 - 1]\n              ]\n      ReFT arg ->\n        case retrieveElementType arg mp of\n          R ->\n            let inner =\n                  fmap (:+ 0) . evaluate3DReal valMap $ (mp, arg)\n                ftResult =\n                  fourierTransform3D (size1, size2, size3) inner\n             in fmap realPart ftResult\n          C ->\n            let inner = evaluate3DComplex valMap $ (mp, arg)\n                ftResult =\n                  fourierTransform3D (size1, size2, size3) inner\n             in fmap realPart ftResult\n      ImFT arg ->\n        case retrieveElementType arg mp of\n          R ->\n            let inner =\n                  fmap (:+ 0) . evaluate3DReal valMap $ (mp, arg)\n                ftResult =\n                  fourierTransform3D (size1, size2, size3) inner\n             in fmap imagPart ftResult\n          C ->\n            let inner = evaluate3DComplex valMap $ (mp, arg)\n                ftResult =\n                  fourierTransform3D (size1, size2, size3) inner\n             in fmap imagPart ftResult\n      _ -> error \"expression structure Three R is wrong\"\n  | otherwise = error \"Three r but shape is not [size1, size2, size3] ??\"\n\ninstance\n  (KnownNat m, KnownNat n, KnownNat p) =>\n  Evaluable '(m, n, p) R (Array (Int, Int, Int) Double)\n  where\n  eval :: ValMaps -> Expression '(m, n, p) R -> Array (Int, Int, Int) Double\n  eval valMap (Expression n mp) = evaluate3DReal valMap (mp, n)\n\nevaluate3DComplex ::\n  ValMaps -> (ExpressionMap, NodeID) -> Array (Int, Int, Int) (Complex Double)\nevaluate3DComplex valMap (mp, n)\n  | [size1, size2, size3] <- retrieveShape n mp =\n    case retrieveNode n mp of\n      Sum C args ->\n        foldrElementwise (+) . map (evaluate3DComplex valMap . (mp,)) $\n          args\n      Mul C args ->\n        foldrElementwise (*) . map (evaluate3DComplex valMap . (mp,)) $\n          args\n      Power x arg -> fmap (^ x) (evaluate3DComplex valMap $ (mp, arg))\n      Neg C arg -> fmap negate . evaluate3DComplex valMap $ (mp, arg)\n      Scale C arg1 arg2 ->\n        case retrieveElementType arg1 mp of\n          R ->\n            let scalar = fromR . eval valMap $ expZeroR mp arg1\n             in fmap (scalar *) . evaluate3DComplex valMap $\n                  (mp, arg2)\n          C ->\n            let scalar = eval valMap $ expZeroC mp arg1\n             in fmap (scalar *) . evaluate3DComplex valMap $\n                  (mp, arg2)\n      RealImag arg1 arg2 ->\n        zipWithA\n          (:+)\n          (evaluate3DReal valMap $ (mp, arg1))\n          (evaluate3DReal valMap $ (mp, arg2))\n      Piecewise marks conditionArg branchArgs ->\n        let cdt = evaluate3DReal valMap $ (mp, conditionArg)\n            branches =\n              map (evaluate3DComplex valMap . (mp,)) branchArgs\n         in listArray\n              ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n              [ chosen ! (i, j, k)\n                | i <- [0 .. size1 - 1],\n                  j <- [0 .. size2 - 1],\n                  k <- [0 .. size3 - 1],\n                  let chosen =\n                        chooseBranch marks (cdt ! (i, j, k)) branches\n              ]\n      Rotate [amount1, amount2, amount3] arg ->\n        rotate3D\n          (size1, size2, size3)\n          (amount1, amount2, amount3)\n          (evaluate3DComplex valMap $ (mp, arg))\n      _ -> error \"expression structure Three C is wrong\"\n  | otherwise = error \"Three C but shape is not [size1, size2, size3] ??\"\n\ninstance\n  (KnownNat m, KnownNat n, KnownNat p) =>\n  Evaluable '(m, n, p) C (Array (Int, Int, Int) (Complex Double))\n  where\n  eval ::\n    ValMaps ->\n    Expression '(m, n, p) C ->\n    Array (Int, Int, Int) (Complex Double)\n  eval valMap (Expression n mp) = evaluate3DComplex valMap (mp, n)\n\n-- NOTE: `mod` in Haskell works with negative number, e.g, (-5) `mod` 3 = 1\n\n-- | One dimension rotation\nrotate1D ::\n  -- | Size of the input array\n  Int ->\n  -- | amount of rotation\n  Int ->\n  -- | Input array\n  Array Int a ->\n  -- | Rotated array\n  Array Int a\nrotate1D size amount arr =\n  listArray\n    (0, size - 1)\n    [arr ! ((i - amount) `mod` size) | i <- [0 .. size - 1]]\n\n-- | Two dimension rotation\nrotate2D ::\n  -- | Size of the 2d input array\n  (Int, Int) ->\n  -- | amount of rotation for 2d array\n  (Int, Int) ->\n  -- | Input 2d array\n  Array (Int, Int) a ->\n  -- | Rotated 2d array\n  Array (Int, Int) a\nrotate2D (size1, size2) (amount1, amount2) arr =\n  listArray\n    ((0, 0), (size1 - 1, size2 - 1))\n    [ arr ! ((i - amount1) `mod` size1, (j - amount2) `mod` size2)\n      | i <- [0 .. size1 - 1],\n        j <- [0 .. size2 - 1]\n    ]\n\n-- | Three dimension rotation\nrotate3D ::\n  -- | Size of 3d input array\n  (Int, Int, Int) ->\n  -- | Amount of Rotation for 3d array\n  (Int, Int, Int) ->\n  -- | Input 3d array\n  Array (Int, Int, Int) a ->\n  -- | Rotated 3d array\n  Array (Int, Int, Int) a\nrotate3D (size1, size2, size3) (amount1, amount2, amount3) arr =\n  listArray\n    ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n    [ arr\n        ! ( (i - amount1) `mod` size1,\n            (j - amount2) `mod` size2,\n            (k - amount3) `mod` size3\n          )\n      | i <- [0 .. size1 - 1],\n        j <- [0 .. size2 - 1],\n        k <- [0 .. size3 - 1]\n    ]\n\n-- |\nfourierTransform1D ::\n  Int -> Array Int (Complex Double) -> Array Int (Complex Double)\nfourierTransform1D size arr =\n  listArray (0, size - 1) [computeX i | i <- [0 .. size - 1]]\n  where\n    computeX i = sum $ zipWithA (*) arr (fourierBasis i)\n    fourierBasis i =\n      let frequency n = 2 * pi * fromIntegral (i * n) / fromIntegral size\n       in listArray\n            (0, size - 1)\n            [ cos (frequency n) :+ (- sin (frequency n))\n              | n <- [0 .. size - 1]\n            ]\n\n-- |\nfourierTransform2D ::\n  (Int, Int) ->\n  Array (Int, Int) (Complex Double) ->\n  Array (Int, Int) (Complex Double)\nfourierTransform2D (size1, size2) arr =\n  listArray\n    ((0, 0), (size1 - 1, size2 - 1))\n    [computeX i j | i <- [0 .. size1 - 1], j <- [0 .. size2 - 1]]\n  where\n    computeX i j = sum $ zipWithA (*) arr (fourierBasis i j)\n    fourierBasis i j =\n      let frequency m n =\n            2 * pi * fromIntegral (i * m) / fromIntegral size1\n              + 2 * pi * fromIntegral (j * n) / fromIntegral size2\n       in listArray\n            ((0, 0), (size1 - 1, size2 - 1))\n            [ cos (frequency m n) :+ (- sin (frequency m n))\n              | m <- [0 .. size1 - 1],\n                n <- [0 .. size2 - 1]\n            ]\n\n-- |\nfourierTransform3D ::\n  (Int, Int, Int) ->\n  Array (Int, Int, Int) (Complex Double) ->\n  Array (Int, Int, Int) (Complex Double)\nfourierTransform3D (size1, size2, size3) arr =\n  listArray\n    ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n    [ computeX i j k\n      | i <- [0 .. size1 - 1],\n        j <- [0 .. size2 - 1],\n        k <- [0 .. size3 - 1]\n    ]\n  where\n    computeX i j k = sum $ zipWithA (*) arr (fourierBasis i j k)\n    fourierBasis i j k =\n      let frequency m n p =\n            2 * pi * fromIntegral (i * m) / fromIntegral size1\n              + 2 * pi * fromIntegral (j * n) / fromIntegral size2\n              + 2 * pi * fromIntegral (k * p) / fromIntegral size3\n       in listArray\n            ((0, 0, 0), (size1 - 1, size2 - 1, size3 - 1))\n            [ cos (frequency m n p) :+ (- sin (frequency m n p))\n              | m <- [0 .. size1 - 1],\n                n <- [0 .. size2 - 1],\n                p <- [0 .. size3 - 1]\n            ]\n", "meta": {"hexsha": "77cb7f4ef78f80b5def50d4ce994481e1007b0bd", "size": 36163, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HashedExpression/Interp.hs", "max_stars_repo_name": "Turboscient/HashedExpression", "max_stars_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-30T00:10:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T21:31:19.000Z", "max_issues_repo_path": "src/HashedExpression/Interp.hs", "max_issues_repo_name": "Turboscient/HashedExpression", "max_issues_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 34, "max_issues_repo_issues_event_min_datetime": "2019-05-23T19:22:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-26T18:47:55.000Z", "max_forks_repo_path": "src/HashedExpression/Interp.hs", "max_forks_repo_name": "Turboscient/HashedExpression", "max_forks_repo_head_hexsha": "cbdc06506f5f9decb3712bf2d13ebc52da2d8e03", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-05-25T00:27:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T00:37:36.000Z", "avg_line_length": 39.1374458874, "max_line_length": 79, "alphanum_fraction": 0.5240715649, "num_tokens": 10330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.40570785204945337}}
{"text": "module SemiGr.SemiGrSpec (main,spec) where\n\nimport Test.Hspec\nimport Test.QuickCheck()\nimport Data.Complex(Complex((:+)))\nimport SemiGr.Semi(fromList, toList, LinkedList(..))\n\nmain :: IO ()\nmain = hspec spec\n\nspec :: Spec\nspec = do\n\n  describe \"Basic\" $ do\n\n    it \"create linked list from list\" $ do\n      let a = [1, 2, 3, 4] \n        in (fromList a) `shouldBe` LinkedList 1 (LinkedList 2 (LinkedList 3 (LinkedList 4 Empt)))\n\n    it \"join two linked list with semigroup opr\" $ do\n      let { a = fromList [1,2,3]\n          ; b = fromList [4,5,6]}\n          in (toList $ a <> b) `shouldBe` [1,4,2,5,3,6]", "meta": {"hexsha": "1b7aee735df7fc7984b01cdb4b495a8e7bf256bc", "size": 604, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "021-haskell-semigroup/p21/test/SemiGr/SemiGrSpec.hs", "max_stars_repo_name": "tao-pr/52-challenges", "max_stars_repo_head_hexsha": "21c1723b8bb64c0a52afcca8f429b97e9948e86a", "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": "021-haskell-semigroup/p21/test/SemiGr/SemiGrSpec.hs", "max_issues_repo_name": "tao-pr/52-challenges", "max_issues_repo_head_hexsha": "21c1723b8bb64c0a52afcca8f429b97e9948e86a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-03-31T07:19:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T15:48:44.000Z", "max_forks_repo_path": "021-haskell-semigroup/p21/test/SemiGr/SemiGrSpec.hs", "max_forks_repo_name": "tao-pr/52-challenges", "max_forks_repo_head_hexsha": "21c1723b8bb64c0a52afcca8f429b97e9948e86a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-31T14:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T04:13:31.000Z", "avg_line_length": 26.2608695652, "max_line_length": 97, "alphanum_fraction": 0.6175496689, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.4055860510509141}}
{"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecordWildCards, PatternGuards, BangPatterns #-}\n-----------------------------------------------------------------------------\n--\n-- Module      :  AI.Network.RNN.RNN\n-- Copyright   :  (c) JP Moresmau\n-- License     :  BSD3\n--\n-- Maintainer  :  JP Moresmau <jp@moresmau.fr>\n-- Stability   :  experimental\n-- Portability :\n--\n-- | Recurrent neural network\n--\n-----------------------------------------------------------------------------\n\nmodule AI.Network.RNN.RNN  where\n\nimport Numeric.LinearAlgebra.HMatrix hiding ((|>))\nimport Control.DeepSeq\nimport Control.Monad.Random hiding (fromList)\n\nimport AI.Network.RNN.Types\nimport AI.Network.RNN.Util\n\ndata RNNDimensions = RNNDimensions\n  { rnndInput    :: Int\n  , rnndInternal :: Int\n  , rnndOutput   :: Int\n  , rnndWithBack :: Bool\n  }  deriving (Show,Read,Eq,Ord)\n\n\ninstance NFData RNNDimensions where\n    rnf RNNDimensions{..} = rnf (rnndInput,rnndInternal,rnndOutput,rnndWithBack)\n\ndata RNNetwork = RNNetwork\n  { rnnDimensions :: RNNDimensions\n  , rnnMIn        :: Matrix Double\n  , rnnM          :: Matrix Double\n  , rnnMOut       :: Matrix Double\n  , rnnMBack      :: Maybe (Matrix Double)\n  , rnnState      :: Vector Double\n  , rnnOutput     :: Vector Double\n  } deriving (Show,Read,Eq)\n\nnetworkDimensions :: RNNetwork -> RNNDimensions\nnetworkDimensions = rnnDimensions\n\ninstance NFData RNNetwork where\n    rnf RNNetwork{..} = rnf (rnnDimensions,rnnMIn,rnnM,rnnMOut,rnnMBack,rnnState,rnnOutput)\n\ncreateNetwork\n    :: RNNDimensions\n    -> Matrix Double\n    -> Matrix Double\n    -> Matrix Double\n    -> Maybe (Matrix Double)\n    -> Vector Double\n    -> Vector Double\n    -> Either [String] RNNetwork\ncreateNetwork dim mIn m mOut mmback st out =\n    case checkNetworkDimensions dim mIn m mOut mmback st of\n        []  -> Right $ RNNetwork dim mIn m mOut mmback st out\n        err -> Left err\n\ncreateNetworkFromArray\n    :: RNNDimensions\n    -> [Double]\n    -> Either String RNNetwork\ncreateNetworkFromArray dim@RNNDimensions{..} v =\n    let\n        enough = length v >= totalDataLength dim\n    in if enough\n        then Right $ fromVector dim $ fromList v\n        else Left $ \"Not enough data in array (needs at least\"++show (totalDataLength dim)++\")\"\n\nnetworkToArray :: RNNetwork -> [Double]\nnetworkToArray RNNetwork{..} =\n       concat (toLists rnnMIn)\n    ++ concat (toLists rnnM)\n    ++ concat (toLists rnnMOut)\n    ++ (case rnnMBack of\n            Just b -> concat $ toLists b\n            _      -> [])\n    ++ toList rnnState\n    ++ toList rnnOutput\n\ncreateNetworkFromVector\n    :: RNNDimensions\n    -> Vector Double\n    -> Either String RNNetwork\ncreateNetworkFromVector dim@RNNDimensions{..} v =\n    let\n        enough = size v >= totalDataLength dim\n    in if enough\n        then {-# SCC \"createNetworkFromVector\" #-} Right $ fromVector dim v\n        else Left $ \"Not enough data in vector (needs at least\"++ show (totalDataLength dim) ++\")\"\n\n\ninputMatrixLength :: RNNDimensions -> Int\ninputMatrixLength RNNDimensions{..} = rnndInput * rnndInternal\n\ninternalMatrixLength :: RNNDimensions -> Int\ninternalMatrixLength RNNDimensions{..} = rnndInternal * rnndInternal\n\noutputMatrixLength :: RNNDimensions -> Int\noutputMatrixLength RNNDimensions{..} = rnndOutput * (rnndInput + rnndInternal)\n\nbackMatrixLength :: RNNDimensions -> Int\nbackMatrixLength RNNDimensions{..} = if rnndWithBack then rnndInternal * rnndOutput else 0\n\ntotalDataLength :: FullSize RNNetwork\ntotalDataLength dim@RNNDimensions{..} =\n    inputMatrixLength dim + internalMatrixLength dim + outputMatrixLength dim\n    + backMatrixLength dim\n    + rnndInternal + rnndOutput\n\n\nrandNetwork :: (Monad m,RandomGen g) =>  RNNDimensions -> RandT g m RNNetwork\nrandNetwork dim@RNNDimensions{..} = do\n    s <- getRandom\n    -- vs <- sequence (replicate (totalDataLength dim) getRandom)\n    return $ fromVector dim $ randomVector s Gaussian (totalDataLength dim)\n\ncollectErrors :: [(Bool,a)] ->  [a]\ncollectErrors = map snd . filter fst\n\ncheckDimensions\n    :: RNNDimensions\n    -> [String]\ncheckDimensions RNNDimensions{..} = collectErrors\n    [(rnndInput    < 0, \"input must be >=0\")\n    ,(rnndInternal < 1, \"internal must be >0\")\n    ,(rnndOutput   < 1, \"output must be >0\")]\n\ncheckNetworkDimensions\n    :: RNNDimensions\n    -> Matrix Double\n    -> Matrix Double\n    -> Matrix Double\n    -> Maybe (Matrix Double)\n    -> Vector Double\n    -> [String]\ncheckNetworkDimensions dim@RNNDimensions{..} mIn m mOut mmback st = checkDimensions dim ++ collectErrors (\n    [(cols mIn /= rnndInput, \"input matrix column count doesn't match input neurons count\")\n    ,(rows mIn /= rnndInternal, \"input matrix row count doesn't match internal neurons count\")\n    ,(cols m /= rnndInternal, \"internal matrix column count doesn't match internal neurons count\")\n    ,(rows m /= rnndInternal, \"internal matrix row count doesn't match internal neurons count\")\n    ,(cols mOut /= (rnndInput + rnndInternal), \"internal matrix column count doesn't match input + internal neurons count\")\n    ,(rows mOut /= rnndOutput, \"output matrix row count doesn't match output neurons count\")\n    ,(size st /= rnndInternal,\"internal state length doesn't match internal neurons count\")]\n    ++(case mmback of\n        Nothing -> []\n        Just mback ->\n            [(rows mback /= rnndInternal,\"back matrix row count doesn't match internal neurons count\")\n            ,(cols m /= rnndOutput,\"back matrix column count doesn't match output neurons count\")\n            ]))\n\ninstance RNNEval RNNetwork where\n    type Size RNNetwork = RNNDimensions\n    evalStep rnn@RNNetwork{..} iv =\n        let\n            sum1 = (rnnMIn #> iv) + (rnnM #> rnnState)\n            sum2 = case rnnMBack of\n                Just mback -> sum1 + (mback #> rnnOutput)\n                _          -> sum1\n            s2 = cmap tanh sum2\n            out = cmap sigmoid (rnnMOut #> vjoin [iv,s2])\n        in (rnn{rnnState=s2,rnnOutput=out},out)\n    toVector RNNetwork{..} = vjoin\n        [ flatten rnnMIn\n        , flatten rnnM\n        , flatten rnnMOut\n        , maybe (fromList []) flatten rnnMBack\n        , rnnState\n        , rnnOutput\n        ]\n    fromVector dim@RNNDimensions{..} v =\n        let\n            lenIn   = inputMatrixLength dim\n            len     = internalMatrixLength dim\n            lenOut  = outputMatrixLength dim\n            lenBack = backMatrixLength dim\n            [v1,v2,v3,v4,v5,v6] = takesV [lenIn,len,lenOut,lenBack,rnndInternal,rnndOutput] v\n            mIn     = reshape rnndInput v1\n            m       = reshape rnndInternal v2\n            mOut    = reshape (rnndInput + rnndInternal) v3\n            mback = if rnndWithBack\n                            then Just $ reshape rnndOutput v4\n                            else Nothing\n        in RNNetwork dim mIn m mOut mback v5 v6\n    rnnsize = rnnDimensions\n    fullSize = totalDataLength . rnnDimensions\n\n\n\n", "meta": {"hexsha": "f81850f5e4072f8ae010c5214d84d5abeb0566f4", "size": 6955, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Network/RNN/RNN.hs", "max_stars_repo_name": "JPMoresmau/rnn", "max_stars_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-08-02T17:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T06:56:40.000Z", "max_issues_repo_path": "src/AI/Network/RNN/RNN.hs", "max_issues_repo_name": "JPMoresmau/rnn", "max_issues_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-01T18:47:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-01T18:47:41.000Z", "max_forks_repo_path": "src/AI/Network/RNN/RNN.hs", "max_forks_repo_name": "JPMoresmau/rnn", "max_forks_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-12-10T18:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T00:02:09.000Z", "avg_line_length": 34.775, "max_line_length": 123, "alphanum_fraction": 0.6412652768, "num_tokens": 1850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.40522294796712927}}
{"text": "{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\nmodule CNC.Figure(Pos, Figure, Path,\n                  unPath, mapPath, mapPathM_, deltaPath,\n                  solveFigure, declarePoints, figure,\n                  xSize, ySize, len, xAngle, yAngle) where\n\nimport CNC.Geometry(RealT, eps)\n\n\nimport qualified Data.Map as M\nimport Data.Map((!))\nimport Data.Maybe(fromJust, isNothing)\nimport Data.Label\nimport Data.List(deleteBy,sort)\nimport qualified Data.Label.Monadic as LM\nimport qualified Control.Monad.State as S\nimport Data.Complex\nimport Text.Printf\n\nnewtype PointInd = PointInd Int deriving (Eq, Ord, Enum, Show)\n\ntype Pos = Complex RealT\n\ntype FigMap = M.Map PointInd (Maybe Pos)\ndata Figure = Figure { _fPoints ::  FigMap, _fNextPoint :: PointInd, _fConstraints :: [Constraint] } deriving Show\nnewtype Path = Path {unPath :: [Pos]} deriving Show\n\nmkPos x y = x :+ y\n\n-- applies a given transform to all points of path\nmapPath f (Path p) = Path (map f p)\nmapPathM_ f (Path p) = mapM_ f p\ndeltaPath (Path p) = last p - head p\n\nzero_ind = PointInd 0\nzero_point = mkPos 0 0\n\nempty_figure = Figure M.empty zero_ind []\nfigNumPoints fig = case _fNextPoint fig of\n  PointInd k -> k\n\ninstance (Ord a, RealFloat a) => Ord (Complex a) where\n  compare x y = let c1 = compare (realPart x) (realPart y)\n                in if c1 == EQ then compare (imagPart x) (imagPart y)\n                   else c1\n\ndata UniConstraint pt = Disp {cPoint1 :: pt, cPoint2 :: pt, cPos :: Pos} -- A vector from first point to second\n                      | Length {cPoint1 :: pt, cPoint2 :: pt, cLen :: RealT} -- distance between points\n                      | Angle {cPoint1 :: pt, cPoint2 :: pt, cAngle :: RealT} deriving (Eq, Ord, Show)\n\ninstance Functor UniConstraint where\n  fmap f c = case c of\n    Disp p1 p2 d -> Disp (f p1) (f p2) d\n    Length p1 p2 l -> Length (f p1) (f p2) l\n    Angle p1 p2 a -> Angle (f p1) (f p2) a\n\ntype Constraint = UniConstraint PointInd\n\nmkLabels [''Figure]\n\nfigure fig_m = let fig = S.execState fig_m empty_figure\n               in solveFigure fig\n\n-- Creates k new points\ndeclarePoints k = do\n  next <- LM.gets fNextPoint\n  let pts = take k $ iterate succ next\n      pairs = map (\\p -> (p, Nothing)) pts\n  LM.modify fPoints (\\ps -> ps `M.union` M.fromList pairs)\n  LM.puts fNextPoint (succ $ last pts)\n  return pts\n\nxSize p1 p2 d = LM.modify fConstraints (Disp p1 p2 (mkPos d 0) :) -- distance between horizontally aligned points\nySize p1 p2 d = LM.modify fConstraints (Disp p1 p2 (mkPos 0 d) :) -- distance between vertically aligned points\nlen p1 p2 d = LM.modify fConstraints (Length p1 p2 d :) -- distance between points\nxAngle p1 p2 a = LM.modify fConstraints (Angle p1 p2 a :) -- angle between line and axe X\nyAngle p1 p2 a = LM.modify fConstraints (Angle p1 p2 (pi/2 - a) :) -- angle between line and axe Y\n\n-- solves system consisting of N declared points and user specified constraints\nsolveFigure :: Figure -> Path\nsolveFigure fig | figNumPoints fig == 0 = error \"can't solve figure\"\n                | otherwise = let points = M.insert zero_ind (Just zero_point) $ get fPoints fig\n                                  constraints = sort $ get fConstraints fig\n                                  solution = solveConstraints points constraints [] False\n                              in Path $ map fromJust $ M.elems $ checkSolution solution constraints\n\nsolveConstraints :: FigMap -> [Constraint] -> [Constraint] -> Bool -> FigMap\nsolveConstraints points [] [] _ = points -- no more constraints, finish here\nsolveConstraints points [] prev_cs True = solveConstraints points (reverse prev_cs) [] False -- iterating over constraints again\nsolveConstraints points [] prev_cs False = points -- no constraints was applied, finishing\nsolveConstraints points (c:cs) prev_cs shrinked = case c of -- process a single constraint\n  Disp pi1 pi2 disp -> case (points ! pi1, points ! pi2) of\n    (Nothing, Nothing) -> skipConstr\n    (Just p1, Nothing) -> solveDisp p1 pi2 disp\n    (Nothing, Just p2) -> solveDisp p2 pi1 (-disp)\n    (Just p1, Just p2) -> checkConstr\n  Length pi1 pi2 len -> case (points ! pi1, points ! pi2) of\n    (Nothing, Nothing) -> skipConstr\n    (Just p1, Nothing) -> solveLength p1 pi1 pi2 len\n    (Nothing, Just p2) -> solveLength p2 pi2 pi1 len\n    (Just p1, Just p2) -> checkConstr\n  Angle pi1 pi2 a -> case (M.lookup pi1 points, M.lookup pi2 points) of -- only check these, they're used as part of Length constraints processing\n    (Just p1, Just p2) -> checkConstr\n    _ -> skipConstr\n  where\n    pointConstr = fmap (fromJust . (points !)) c\n    checkConstr = checkEps (calcDiscrepancy pointConstr) (solveConstraints points cs prev_cs shrinked) (\"disagreement while processing \" ++ show c ++ \" evaluated to \" ++ show pointConstr)\n    skipConstr = solveConstraints points cs (c:prev_cs) shrinked\n    solveDisp p ind d = solveConstraints (M.insert ind (Just $ p + d) points) cs prev_cs True\n    solveLength (p :: Pos) ind0 ind len = case findAngleConstr ind0 ind cs of\n      Nothing -> skipConstr\n      Just angle -> solveConstraints (M.insert ind (Just $ p + mkPolar len angle) points)\n                                     (deleteAngleConstr ind0 ind cs) prev_cs True\n\ncheckEps :: RealT -> a -> String -> a\ncheckEps val cont msg = if abs val < eps then cont else error $ msg\n\ncalcDiscrepancy :: (UniConstraint Pos) -> RealT\ncalcDiscrepancy c =\n  case c of\n    Disp p1 p2 d -> magnitude $ p2 - p1 - d\n    Length p1 p2 l -> magnitude (p2 - p1) - l\n    Angle p1 p2 a -> phase (p2 - p1) - a\n\ncheckSolution points constrs | any isNothing $ M.elems points = error $ \"couldn't find a complete solution, got \" ++ show (M.elems points)\ncheckSolution points cs = checkConstrs points cs\n\ncheckConstrs :: FigMap -> [UniConstraint PointInd] -> FigMap\ncheckConstrs points [] = points\ncheckConstrs points (c:cs) = check $ calcDiscrepancy $ fmap (fromJust . (points !)) c\n where p1 = cPoint1 c\n       p2 = cPoint2 c\n       check x = checkEps x (checkConstrs points cs) $\n                   printf \"error checking constraint %s on points %s %s placed at %s %s\"\n                   (show c) (show p1) (show p2) (show $ points ! p1) (show $ points ! p2)\n\n-- finds first angle constraint on points with specified indices\nfindAngleConstr :: PointInd -> PointInd -> [Constraint] -> Maybe RealT\nfindAngleConstr _ _ [] = Nothing\nfindAngleConstr ind1 ind2 (c:cs) = case c of\n  Angle i1 i2 a | i1 == ind1 && i2 == ind2 -> Just a\n                | i1 == ind2 && i2 == ind1 -> Just (-a)\n  _ -> findAngleConstr ind1 ind2 cs\n\n-- deletes first angle constraint\ndeleteAngleConstr ind1 ind2 = deleteBy findAngle\n                              (Angle ind1 ind2 undefined)\n  where findAngle (Angle d1 d2 _) c2 =\n          case c2 of\n            (Angle i1 i2 _) -> (i1, i2) == (d2,d1) || (i2, i1) == (d1,d2)\n            _ -> False", "meta": {"hexsha": "4108827cf21dbc251368eece167bfdbd85ecf2c2", "size": 6854, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CNC/Figure.hs", "max_stars_repo_name": "akamaus/gcodec", "max_stars_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CNC/Figure.hs", "max_issues_repo_name": "akamaus/gcodec", "max_issues_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CNC/Figure.hs", "max_forks_repo_name": "akamaus/gcodec", "max_forks_repo_head_hexsha": "cd515673f408f24d4d92fc85246611c21a4ef433", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3907284768, "max_line_length": 187, "alphanum_fraction": 0.6603443245, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.40492074429390673}}
{"text": "{-# LANGUAGE CPP                   #-}\n{-# LANGUAGE DataKinds             #-}\n{-# LANGUAGE FlexibleContexts      #-}\n{-# LANGUAGE FlexibleInstances     #-}\n{-# LANGUAGE GADTs                 #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes            #-}\n{-# LANGUAGE ScopedTypeVariables   #-}\n{-# LANGUAGE TypeFamilies          #-}\n{-# LANGUAGE TypeOperators         #-}\n{-# LANGUAGE UndecidableInstances  #-}\n{-|\nModule      : Grenade.Layers.Deconvolution\nDescription : Deconvolution layer\nCopyright   : (c) Huw Campbell, 2016-2017\nLicense     : BSD2\nStability   : experimental\n\nA deconvolution layer is in many ways a convolution layer in reverse.\nIt learns a kernel to apply to each pixel location, spreading it out\ninto a larger layer.\n\nThis layer is important for image generation tasks, such as GANs on\nimages.\n-}\nmodule Grenade.Layers.Deconvolution (\n    Deconvolution (..)\n  , Deconvolution' (..)\n  ) where\n\nimport           Control.DeepSeq                     (NFData (..))\nimport           Data.Kind                           (Type)\nimport           Data.List                           (foldl1')\nimport           Data.Maybe\nimport           Data.Proxy\nimport           Data.Serialize\nimport           Data.Singletons.TypeLits            hiding (natVal)\nimport           GHC.TypeLits\n\nimport           Numeric.LinearAlgebra               hiding (konst,\n                                                      uniformSample)\nimport qualified Numeric.LinearAlgebra               as LA\nimport           Numeric.LinearAlgebra.Static        hiding (build, toRows,\n                                                      (|||))\n\nimport           Grenade.Core\nimport           Grenade.Layers.Internal.Convolution\nimport           Grenade.Layers.Internal.Update\nimport           Grenade.Utils.LinearAlgebra\nimport           Grenade.Utils.ListStore\n\n-- | A Deconvolution layer for a neural network.\n--   This uses the im2col Convolution trick popularised by Caffe.\n--\n--   The Deconvolution layer is a way of spreading out a single response\n--   into a larger image, and is useful in generating images.\n--\ndata Deconvolution :: Nat -- Number of channels, for the first layer this could be RGB for instance.\n                   -> Nat -- Number of filters, this is the number of channels output by the layer.\n                   -> Nat -- The number of rows in the kernel filter\n                   -> Nat -- The number of column in the kernel filter\n                   -> Nat -- The row stride of the Deconvolution filter\n                   -> Nat -- The columns stride of the Deconvolution filter\n                   -> Type where\n  Deconvolution :: ( KnownNat channels\n                   , KnownNat filters\n                   , KnownNat kernelRows\n                   , KnownNat kernelColumns\n                   , KnownNat strideRows\n                   , KnownNat strideColumns\n                   , KnownNat kernelFlattened\n                   , kernelFlattened ~ (kernelRows * kernelColumns * filters))\n                 => !(L kernelFlattened channels) -- The kernel filter weights\n                 -> !(ListStore (L kernelFlattened channels)) -- The last kernel update (or momentum)\n                 -> Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns\n\ninstance NFData (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) where\n  rnf (Deconvolution a b) = rnf a `seq` rnf b\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * filters)\n         ) => Serialize (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) where\n  put (Deconvolution w store) = do\n    putListOf put . toList . flatten . extract $ w\n    put (fmap (toList . flatten . extract) store)\n  get = do\n      let f  = fromIntegral $ natVal (Proxy :: Proxy channels)\n      wN    <- maybe (fail \"Vector of incorrect size\") return . create . reshape f . LA.fromList =<< getListOf get\n      store <- fmap (fromMaybe (error \"Vector of incorrect size\") . create . reshape f . LA.fromList)  <$> get\n      return $ Deconvolution wN store\n\n\ndata Deconvolution' :: Nat -- Number of channels, for the first layer this could be RGB for instance.\n                    -> Nat -- Number of filters, this is the number of channels output by the layer.\n                    -> Nat -- The number of rows in the kernel filter\n                    -> Nat -- The number of column in the kernel filter\n                    -> Nat -- The row stride of the Deconvolution filter\n                    -> Nat -- The columns stride of the Deconvolution filter\n                    -> Type where\n  Deconvolution' :: ( KnownNat channels\n                    , KnownNat filters\n                    , KnownNat kernelRows\n                    , KnownNat kernelColumns\n                    , KnownNat strideRows\n                    , KnownNat strideColumns\n                    , KnownNat kernelFlattened\n                    , kernelFlattened ~ (kernelRows * kernelColumns * filters))\n                 => !(L kernelFlattened channels) -- The kernel filter gradient\n                 -> Deconvolution' channels filters kernelRows kernelColumns strideRows strideColumns\n\ninstance NFData (Deconvolution' channels filters kernelRows kernelColumns strideRows strideColumns) where\n  rnf (Deconvolution' a) = rnf a `seq` ()\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * filters)\n         ) =>\n         Serialize (Deconvolution' channels filters kernelRows kernelColumns strideRows strideColumns) where\n  put (Deconvolution' w) = putListOf put . toList . flatten . extract $ w\n  get = do\n    let f = fromIntegral $ natVal (Proxy :: Proxy channels)\n    wN <- maybe (fail \"Vector of incorrect size\") return . create . reshape f . LA.fromList =<< getListOf get\n    return $ Deconvolution' wN\n\ninstance (KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns) => FoldableGradient (Deconvolution' channels filters kernelRows kernelColumns strideRows strideColumns) where\n  mapGradient f (Deconvolution' kernelGradient) = Deconvolution' (dmmap f kernelGradient)\n  squaredSums (Deconvolution' kernelGradient) = [sumM . squareM $ kernelGradient]\n\n\ninstance Show (Deconvolution c f k k' s s') where\n  show (Deconvolution a _) = renderConv a\n    where\n      renderConv mm =\n        let m = extract mm\n            ky = fromIntegral $ natVal (Proxy :: Proxy k)\n            rs = LA.toColumns m\n            ms = map (take ky) $ toLists . reshape ky <$> rs\n            render n'\n              | n' <= 0.2 = ' '\n              | n' <= 0.4 = '.'\n              | n' <= 0.6 = '-'\n              | n' <= 0.8 = '='\n              | otherwise = '#'\n            px = (fmap . fmap . fmap) render ms\n         in unlines $ foldl1 (zipWith (\\a' b' -> a' ++ \"   |   \" ++ b')) px\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat ((kernelRows * kernelColumns) * filters)\n         , KnownNat ((kernelRows * kernelColumns) * channels)\n         , KnownNat (channels * ((kernelRows * kernelColumns) * filters))\n         ) =>\n         RandomLayer (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) where\n  createRandomWith m gen = do\n    wN <- getRandomMatrix i i m gen\n    return $ Deconvolution wN mkListStore\n    where\n      i = natVal (Proxy :: Proxy ((kernelRows * kernelColumns) * channels))\n\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * filters)\n         ) => UpdateLayer (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) where\n  type Gradient (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) = (Deconvolution' channels filters kernelRows kernelColumns strideRows strideColumns)\n\n  type MomentumStore (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns)  = ListStore (L (kernelRows * kernelColumns * filters) channels)\n\n  runUpdate opt@OptSGD{} x@(Deconvolution oldKernel store) (Deconvolution' kernelGradient) =\n    let oldMomentum = getData opt x store\n        result = descendMatrix opt (MatrixValuesSGD oldKernel kernelGradient oldMomentum)\n        newStore = setData opt x store (matrixMomentum result)\n    in Deconvolution (matrixActivations result) newStore\n  runUpdate opt@OptAdam{} x@(Deconvolution oldKernel store) (Deconvolution' kernelGradient) =\n    let (m, v) = toTuple $ getData opt x store\n        result = descendMatrix opt (MatrixValuesAdam (getStep store) oldKernel kernelGradient m v)\n        newStore = setData opt x store [matrixM result, matrixV result]\n    in Deconvolution (matrixActivations result) newStore\n    where toTuple [m ,v] = (m, v)\n          toTuple xs = error $ \"unexpected input of length \" ++ show (length xs) ++ \"in toTuple in Convolution.hs\"\n\n  reduceGradient grads = Deconvolution' $ dmmap (/ (fromIntegral $ length grads)) (foldl1' add (map (\\(Deconvolution' x) -> x) grads))\n\n\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * filters)\n         ) =>\n         LayerOptimizerData (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) where\n  type MomentumExpOptResult (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) = L (kernelRows * kernelColumns * filters) channels\n  type MomentumDataType (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'SGD) = L (kernelRows * kernelColumns * filters) channels\n  getData opt x store = head $ getListStore opt x store\n  setData opt x store = setListStore opt x store . return\n  newData _ _ = konst 0\n\ninstance ( KnownNat channels\n         , KnownNat filters\n         , KnownNat kernelRows\n         , KnownNat kernelColumns\n         , KnownNat strideRows\n         , KnownNat strideColumns\n         , KnownNat (kernelRows * kernelColumns * filters)\n         ) => LayerOptimizerData (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam) where\n  type MomentumExpOptResult (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam)  = [L (kernelRows * kernelColumns * filters) channels]\n  type MomentumDataType (Deconvolution channels filters kernelRows kernelColumns strideRows strideColumns) (Optimizer 'Adam) = L (kernelRows * kernelColumns * filters) channels\n  getData = getListStore\n  setData = setListStore\n  newData _ _ = konst 0\n\n\n-- | A two dimentional image may have a Deconvolution filter applied to it\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , ((inputRows - 1) * strideRows) ~ (outputRows - kernelRows)\n         , ((inputCols - 1) * strideCols) ~ (outputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * filters)\n         , KnownNat (outputRows * filters)\n         ) => Layer (Deconvolution 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) where\n  type Tape (Deconvolution 1 filters kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    runForwards c (S3D input :: S ('D3 inputRows inputCols 1))\n\n  runBackwards c tape grads =\n    case runBackwards c tape grads of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\n-- | A two dimentional image may have a Deconvolution filter applied to it\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputCols\n         , ((inputRows - 1) * strideRows) ~ (outputRows - kernelRows)\n         , ((inputCols - 1) * strideCols) ~ (outputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * 1)\n         , KnownNat (outputRows * 1)\n         ) => Layer (Deconvolution 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) where\n  type Tape (Deconvolution 1 1 kernelRows kernelCols strideRows strideCols) ('D2 inputRows inputCols) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols 1)\n  runForwards c (S2D input) =\n    case runForwards c (S3D input :: S ('D3 inputRows inputCols 1)) of\n      (tps, S3D fore :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D fore)\n\n  runBackwards c tape (S2D grads) =\n    case runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1)) of\n      (c', S3D back :: S ('D3 inputRows inputCols 1)) ->  (c', S2D back)\n\n-- | A two dimentional image may have a Deconvolution filter applied to it\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputCols\n         , ((inputRows - 1) * strideRows) ~ (outputRows - kernelRows)\n         , ((inputCols - 1) * strideCols) ~ (outputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * 1)\n         , KnownNat (outputRows * 1)\n         , KnownNat channels\n         ) => Layer (Deconvolution channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) where\n  type Tape (Deconvolution channels 1 kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D2 outputRows outputCols) = S ('D3 inputRows inputCols channels)\n  runForwards c input =\n    case runForwards c input of\n      (tps, S3D fore :: S ('D3 outputRows outputCols 1)) ->  (tps, S2D fore)\n\n  runBackwards c tape (S2D grads) =\n    runBackwards c tape (S3D grads :: S ('D3 outputRows outputCols 1))\n\n-- | A three dimensional image (or 2d with many channels) can have\n--   an appropriately sized Deconvolution filter run across it.\ninstance ( KnownNat kernelRows\n         , KnownNat kernelCols\n         , KnownNat filters\n         , KnownNat strideRows\n         , KnownNat strideCols\n         , KnownNat inputRows\n         , KnownNat inputCols\n         , KnownNat outputRows\n         , KnownNat outputCols\n         , KnownNat channels\n         , ((inputRows - 1) * strideRows) ~ (outputRows - kernelRows)\n         , ((inputCols - 1) * strideCols) ~ (outputCols - kernelCols)\n         , KnownNat (kernelRows * kernelCols * filters)\n         , KnownNat (outputRows * filters)\n         ) => Layer (Deconvolution channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) where\n\n  type Tape (Deconvolution channels filters kernelRows kernelCols strideRows strideCols) ('D3 inputRows inputCols channels) ('D3 outputRows outputCols filters) = S ('D3 inputRows inputCols channels)\n\n  runForwards (Deconvolution kernel _) (S3D input) =\n    let ex = extract input\n        ek = extract kernel\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n\n        c  = vid2col 1 1 1 1 ix iy ex\n\n        mt = c LA.<> tr ek\n\n        r  = col2vid kx ky sx sy ox oy mt\n        rs = fromJust . create $ r\n    in  (S3D input, S3D rs)\n  runBackwards (Deconvolution kernel _) (S3D input) (S3D dEdy) =\n    let ex = extract input\n        ix = fromIntegral $ natVal (Proxy :: Proxy inputRows)\n        iy = fromIntegral $ natVal (Proxy :: Proxy inputCols)\n        kx = fromIntegral $ natVal (Proxy :: Proxy kernelRows)\n        ky = fromIntegral $ natVal (Proxy :: Proxy kernelCols)\n        sx = fromIntegral $ natVal (Proxy :: Proxy strideRows)\n        sy = fromIntegral $ natVal (Proxy :: Proxy strideCols)\n        ox = fromIntegral $ natVal (Proxy :: Proxy outputRows)\n        oy = fromIntegral $ natVal (Proxy :: Proxy outputCols)\n\n        c  = vid2col 1 1 1 1 ix iy ex\n\n        eo = extract dEdy\n        ek = extract kernel\n\n        vs = vid2col kx ky sx sy ox oy eo\n\n        kN = fromJust . create . tr $ tr c LA.<> vs\n\n        dW = vs LA.<> ek\n\n        xW = col2vid 1 1 1 1 ix iy dW\n    in  (Deconvolution' kN, S3D . fromJust . create $ xW)\n", "meta": {"hexsha": "a4358a341df65fba5838ebc9a335b784c7f66aa7", "size": 17617, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Deconvolution.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/Deconvolution.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/Deconvolution.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": 47.8722826087, "max_line_length": 198, "alphanum_fraction": 0.6460804904, "num_tokens": 4266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.40469157817742835}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE FlexibleContexts #-}\n-----------------------------------------------------------------------------\n--\n-- Module      :  AI.Network.RNN.Genetic\n-- Copyright   :  (c) JP Moresmau\n-- License     :  BSD3\n--\n-- Maintainer  :  JP Moresmau <jp@moresmau.fr>\n-- Stability   :  experimental\n-- Portability :\n--\n-- | Code for genetic evolution of a network\n--\n-----------------------------------------------------------------------------\n\nmodule AI.Network.RNN.Genetic where\n\nimport Control.Monad\nimport Control.Monad.Random hiding (fromList)\nimport qualified Control.Monad.Random as MR\nimport Control.DeepSeq\nimport Data.IORef\nimport AI.GeneticAlgorithm.Simple\nimport AI.Network.RNN.Types\nimport AI.Network.RNN.Util\nimport Numeric.LinearAlgebra.HMatrix\n\nimport Debug.Trace\n\n-- | Keep all relevant data together\ndata RNNData a b = (RNNEval a) => RNNData a !(TrainData b) !Double\n   -- deriving (Show,Read,Eq)\n\n-- | evaluate network\ninstance NFData (RNNData a b) where\n    rnf (RNNData rnn _ _) = rnf rnn\n\n-- | Error threshold (not currently used)\nerrorThreshold :: Double\nerrorThreshold = 0.1\n\n-- | Chromosome instance\ninstance Chromosome (RNNData a b) where\n    -- | cross network by taking half the values of one and half of the other\n    crossover (RNNData rnn1 td l) (RNNData rnn2 _ _) = do\n        rnns <- crossNetworkFull rnn1 rnn2\n        --idx <- getRandomR (0, size rnn1 - 1)\n        --let (v3,v4) = crossVector rnn1 rnn2 idx\n        return $ map (\\r->RNNData r td l) rnns -- [v3,v4]\n\n    mutation (RNNData rnn1 td l) = do\n        rnn2 <- mutateNetwork rnn1\n        --rnn2 <- stdNormalMutate rnn1\n        return $ RNNData rnn2 td l\n    -- | fitness is \"higher is better\", inverse of cost\n    fitness (RNNData rnn1 td _) = 1 / cost rnn1 td -- (fromVector sz rnn1)\n\n-- | Cross 2 networks by taking the first half of one, the second half of the other (not currently used)\ncrossNetworkFull :: (RandomGen g,RNNEval a) =>  a -> a -> Rand g [a]\ncrossNetworkFull rnn1 rnn2 = do\n    let v1 = toVector rnn1\n        v2 = toVector rnn2\n    idx <- getRandomR (0, size v1 - 1)\n    let (v3,v4) = crossVector v1 v2 idx\n        rnn3 = fromVector (rnnsize rnn1) v3\n        rnn4 = fromVector (rnnsize rnn1) v4\n    return $[rnn3,rnn4]\n\n-- | cross 2 networks by taking half the values of one and half of the other\ncrossNetworkHalf :: (RandomGen g,RNNEval a) =>  a -> a -> Rand g [a]\ncrossNetworkHalf rnn1 rnn2 = do\n    let v1 = toVector rnn1\n        v2 = toVector rnn2\n    (v3,v4) <- mixVector v1 v2 0.5\n    let\n        rnn3 = fromVector (rnnsize rnn1) v3\n        rnn4 = fromVector (rnnsize rnn1) v4\n    return $ force [rnn3,rnn4]\n\ncrossMutate :: (RandomGen g,RNNEval a) =>  a -> a -> Rand g [a]\ncrossMutate rnn1 rnn2 = do\n    let v1 = toVector rnn1\n        v2 = toVector rnn2\n    v3 <- stdNormalMutate v1\n    v4 <- stdNormalMutate v2\n    let\n        rnn3 = fromVector (rnnsize rnn1) v3\n        rnn4 = fromVector (rnnsize rnn1) v4\n    return [rnn3,rnn4]\n\n\n-- | Cross networks by taking the average of their values (not currently used)\navgNetwork :: (RandomGen g,RNNEval a) =>  a -> a -> Rand g [a]\navgNetwork rnn1 rnn2 = do\n    let v1 = toVector rnn1\n        v2 = toVector rnn2\n        v3 = fromList $ zipWith (\\x y -> (x+y)/2) (toList v1) (toList v2)\n        rnn3 = fromVector (rnnsize rnn1) v3\n      --  rnn4 = fromVector (rnnsize rnn1) v4 of\n      --      Right n -> n\n      --      Left e  -> error e\n    return [rnn3]\n\n\ncrossMatrixEq :: Matrix Double -> Matrix Double -> (Matrix Double,Matrix Double)\ncrossMatrixEq m1 m2 =\n    let row1      = upperHalf $ rows m1\n        col1      = upperHalf $ cols m1\n        [[a1,a2],[a3,a4]] = toBlocksEvery row1 col1 m1\n        [[b1,b2],[b3,b4]] = toBlocksEvery row1 col1 m2\n    in (fromBlocks [[a1,b2],[a3,b4]],fromBlocks [[b1,a2],[b3,a4]])\n    where\n        upperHalf a = (if odd a then a+1 else a) `div` 2\n\ncrossVectorEq :: Vector Double -> Vector Double -> (Vector Double,Vector Double)\ncrossVectorEq v1 v2 = crossVector v1 v2 (size v1 `div` 2)\n\n-- | Cross vector at the given point\ncrossVector :: Vector Double -> Vector Double -> Int -> (Vector Double,Vector Double)\ncrossVector v1 v2 idx =\n--    let m1 = asRow v1\n--        m2 = asRow v2\n--        [[a1,a2]] = toBlocks [1] [idx,size v1-idx]  m1\n--        [[b1,b2]] = toBlocks [1] [idx,size v1-idx] m2\n--    in (head $ toRows $ fromBlocks [[a1,b2]],head $ toRows $ fromBlocks [[b1,a2]])\n--    let sz2 = size v2 - idx - 1\n--        [a1,a2] = takesV [idx,sz2] v1\n--        [b1,b2] = takesV [idx,sz2] v2\n--    in (vjoin [a1,b2],vjoin [a2,b1])\n let sz = size v1-idx\n in force $ (vjoin [subVector 0 idx v1,subVector idx sz v2],\n                    vjoin [subVector 0 idx v2,subVector idx sz v1])\n\n-- | Mix vector values given a probability to take a value from the first one and not the second\nmixVector :: (Monad m,RandomGen g) =>  Vector Double -> Vector Double -> Double -> RandT g m (Vector Double,Vector Double)\nmixVector v1 v2 prob = do\n    -- rs <- replicateM (size v1) (getRandomR (0, 1))\n    let (l1,l2) = swapL (toList v1) (toList v2) True\n        -- unzip $ map swapR $ zip3 (toList v1) (toList v2) [0..]\n    return (fromList l1,fromList l2)\n    where\n        swapR (a,b,idx) = if (idx `mod` 2) == 0 then (a,b) else (b,a)\n        --if idx <= prob then (a,b) else (b,a):\n        swapL :: [a] -> [a] -> Bool -> ([a],[a])\n        swapL [] _ _ = ([],[])\n        swapL (x:xs) (y:ys) True = let\n            (rs1,rs2)=swapL xs ys False in (x:rs1,y:rs2)\n        swapL (x:xs) (y:ys) False = let\n            (rs1,rs2)=swapL xs ys True in (y:rs1,x:rs2)\n\n\n-- | Mix vector values given a probability to take a value from the first one and not the second\nmixList :: (Monad m,RandomGen g) =>  [Double] -> [Double] -> Double -> RandT g m ([Double],[Double])\nmixList v1 v2 prob = do\n    --rs <- getRandomRs (0,1)\n    return $ unzip $ map swapR $ zip3 v1 v2 [0..]\n    where\n        swapR (a,b,idx) = if (idx `mod` 2) == 0 then (a,b) else (b,a)\n\n\n\nstdNormalMutate :: (Monad m,RandomGen g) =>  Vector Double -> RandT g m (Vector Double)\nstdNormalMutate v1 = do\n    --rs <- replicateM (size v1) stdNormal\n    -- let mx = maxElement v1\n    -- let mn = minElement v1\n    --let sz= trace (\"v1:\"++ show (mn,mx)) $ size v1\n    seed <- getRandom\n    let rs = randomVector seed Gaussian $ size v1\n    let v2 = (rs) + v1\n--    let nv2 = cmap (\\x->\n--                            if x < 0\n--                                then 0\n--                                else if x > 1\n--                                    then 1\n--                                    else x)\n--         v2\n    -- let mx2 = maxElement v2\n    -- let mn2 = minElement v2\n    return v2\n    -- return $ trace (\"v2:\"++show (mn2,mx2)) v2\n\n-- | network mutation: select randomly from several mutation algorithms\nmutateNetwork :: (RandomGen g,RNNEval a) =>  a -> Rand g a\nmutateNetwork rnn = do\n    f <- MR.fromList [(stdNormalMutation,1),(pointMutation,1),(swapMutation,1),(insertMutation,1),(flipMutation,0.5)]\n    f rnn\n\n-- | Mutate values around a standard deviation\nstdNormalMutation :: (RandomGen g,RNNEval a) =>  a -> Rand g a\nstdNormalMutation rnn = do\n    let v1 = toVector rnn\n    v2 <- stdNormalMutate v1\n    return $ force $ fromVector (rnnsize rnn) v2\n\n-- | Mutate a single value of the vector, taking a random value\npointMutation :: (RandomGen g,RNNEval a) =>  a -> Rand g a\npointMutation rnn = do\n    let v1 = toVector rnn\n    idx <- getRandomR (0, size v1 - 1)\n    dbl <- getRandomR (0,1)\n    let v2 = accum v1 const [(idx,dbl)]\n    return $ fromVector (rnnsize rnn) v2\n\n-- | Swap two values in the vector\nswapMutation :: (RandomGen g,RNNEval a) =>  a -> Rand g a\nswapMutation rnn = do\n    let v1 = toVector rnn\n    idx1 <- getRandomR (0, size v1 - 1)\n    idx2 <- getRandomR (0, size v1 - 1)\n    let v2 = accum v1 const [(idx1,atIndex v1 idx2),(idx2,atIndex v1 idx1)]\n    return $ fromVector (rnnsize rnn) v2\n\n-- | Insert a random value at a random point in the vector, discarding the last value\ninsertMutation :: (RandomGen g,RNNEval a) =>  a -> Rand g a\ninsertMutation rnn = do\n    let v1 = toVector rnn\n    idx <- getRandomR (0, size v1 - 1)\n    dbl <- getRandomR (0,1)\n    let v2 = vjoin [subVector 0 idx v1,fromList [dbl],subVector idx (size v1 - idx -1) v1]\n    return $ fromVector (rnnsize rnn) v2\n\nflipMutation :: (RandomGen g,RNNEval a) =>  a -> Rand g a\nflipMutation rnn = do\n    let v1 = toVector rnn\n    let v2 = cmap (\\a->(-a)) v1\n    return $ fromVector (rnnsize rnn) v2\n\n-- | Stop function\n-- we take a list of past fitnesses and stop when the fitness 5 generations ago was not worse that the current one\nstopf :: IORef [Double] -> Int -> (RNNData a b,Double) -> Int -> IO Bool\nstopf fitnessList maxGen (nd,fit) gen = do\n    mfit <- atomicModifyIORef' fitnessList (\\l->\n        let l2 = take 5 (fit:l)\n        in if length l2 == 5\n            then (l2, Just $ last l2)\n            else (l2, Nothing)\n        )\n\n    print $ \"Fitness (\" ++ show gen ++\"): \" ++ show fit\n    let converged = case mfit of\n                        Nothing -> False\n                        Just f  -> f >= fit\n    when converged $ print \"Converged!\"\n    return ( gen >= maxGen)\n\n\n-- | Build a random network data\nbuildNetworkData :: (RNNEval re,Monad m,RandomGen g) => TrainData b -> Size re -> FullSize re -> RandT g m (RNNData re b)\nbuildNetworkData td@(TrainData is _ _ _) dim fullSz = do\n  --n <- randomNetwork dim fullSz\n  let n = startNetwork dim fullSz\n  return $ RNNData n td (fromIntegral $ length is)\n\n", "meta": {"hexsha": "e9ec7f9e3c4b0d40ebaba37eb1ac954bd4f1674a", "size": 9530, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Network/RNN/Genetic.hs", "max_stars_repo_name": "JPMoresmau/rnn", "max_stars_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-08-02T17:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T06:56:40.000Z", "max_issues_repo_path": "src/AI/Network/RNN/Genetic.hs", "max_issues_repo_name": "JPMoresmau/rnn", "max_issues_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-01T18:47:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-01T18:47:41.000Z", "max_forks_repo_path": "src/AI/Network/RNN/Genetic.hs", "max_forks_repo_name": "JPMoresmau/rnn", "max_forks_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-12-10T18:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T00:02:09.000Z", "avg_line_length": 37.0817120623, "max_line_length": 122, "alphanum_fraction": 0.6028331584, "num_tokens": 3024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.40407930538876946}}
{"text": "{-# LANGUAGE Rank2Types #-} \nmodule CreateGalaxy\nwhere\n\nimport Data.List (sort)\nimport Control.Monad.State\nimport qualified Data.Map as M\nimport qualified Data.Edison.Assoc.StandardMap as E\n\nimport Galaxy\nimport DataFunction\nimport Statistics\nimport Math\nimport Utils\n\ngasGiantByMass :: Flt -> PlanetType\ngasGiantByMass mass | mass < 20.0  = SmallGasGiant\n                    | mass < 100.0 = MediumGasGiant\n                    | mass < 400.0 = LargeGasGiant\n                    | otherwise    = VeryLargeGasGiant\n\ncreatePlanetType :: Flt -> Temperature -> Flt -> Rnd PlanetType\ncreatePlanetType mass startemp orbitradius = do\n  if mass < 0.001 then return Planetoid\n   else if mass < 0.01 then return NoAtmosphere\n   else if mass > 15.0 then return (gasGiantByMass mass)\n   else createRockyPlanetAtmosphere mass startemp orbitradius\n\ncreateRockyPlanetAtmosphere :: Flt -> Temperature -> Flt -> Rnd PlanetType\ncreateRockyPlanetAtmosphere mass startemp orbitradius = do\n  weather <- randomRM (1, 100 :: Int)\n  let atm1 = if weather < 10\n               then RockyPlanet WaterWeatherSystem \n               else if weather < 30 then RockyPlanet MethaneWeatherSystem\n               else if weather < 50 then RockyPlanet SulphurDioxide\n               else if weather < 90 then RockyPlanet CarbonDioxide\n               else RockyPlanet Nitrogen\n  let ptemp = planetTemperature'' startemp orbitradius atm1\n  return $! case atm1 of\n    RockyPlanet WaterWeatherSystem   -> if ptemp < waterMaxTemperature && ptemp > waterMinTemperature then atm1 else RockyPlanet Nitrogen\n    RockyPlanet MethaneWeatherSystem -> if ptemp < 120 && ptemp > 70  then atm1 else RockyPlanet Nitrogen\n    _                                -> atm1\n\ncreateSatellite :: Flt -> Flt -> (Planet () -> Rnd a) -> Temperature -> String -> Flt -> Rnd (Planet a)\ncreateSatellite minmass maxmass genfunc startemp name orbitradius = do\n  orbit <- createOrbit orbitradius\n  mass <- randomRM (minmass, maxmass)\n  atmosphere <- createPlanetType mass startemp orbitradius\n  let ptemp = planetTemperature'' startemp orbitradius atmosphere\n  let emptyplanet = Planet name orbit (BodyPhysics mass) atmosphere ptemp M.empty ()\n  cont <- genfunc emptyplanet\n  return $! Planet name orbit (BodyPhysics mass) atmosphere ptemp M.empty cont\n\ncreatePlanet :: (Planet () -> Rnd a) -> Temperature -> String -> Flt -> Rnd (Planet a)\ncreatePlanet genfunc startemp name orbitradius = do\n  orbit <- createOrbit orbitradius\n  gentype <- randomRM (1, 4 :: Int)\n  mass <- case gentype of\n            1 -> randomRM (50, 400)\n            2 -> randomRM (20, 50)\n            3 -> randomRM (0.0001, 0.1)\n            _ -> randomRM (0.1, 20)\n  atmosphere <- createPlanetType mass startemp orbitradius\n  numsatellites <- if mass < 1.0 then return 0 else randomRM (0 :: Int, min 16 (floor (sqrt mass)))\n  satellites <- zipWithM (createSatellite (0.00001 * mass) (0.01 * mass) genfunc startemp) (bodyNames name) (replicate numsatellites orbitradius)\n  let temp = planetTemperature'' startemp orbitradius atmosphere\n  cont <- genfunc (Planet name orbit (BodyPhysics mass) atmosphere temp M.empty ())\n  return $! Planet name orbit (BodyPhysics mass) atmosphere temp (namedsToMap satellites) cont\n\nbodyNames :: String -> [String]\nbodyNames = namesFromBasenameNum\n\nstarprobs, starbinaryprobs :: [(Flt, SpectralType)]\nstarprobs       = [(0.001, SpectralTypeB), (0.004, SpectralTypeA), (0.02, SpectralTypeF), (0.06, SpectralTypeG), (0.12, SpectralTypeK), (1, SpectralTypeM)]\nstarbinaryprobs = [(0.001, SpectralTypeB), (0.010, SpectralTypeA), (0.10, SpectralTypeF), (0.25, SpectralTypeG), (0.40, SpectralTypeK), (1, SpectralTypeM)]\n\ngetProbTableValue :: (Ord a) => a -> [(a, b)] -> b\ngetProbTableValue n [(_, v)] = v\ngetProbTableValue n ((k, v):xs) = if n <= k then v else getProbTableValue n xs\ngetProbTableValue _ []       = error \"Given probability >1?\"\n\nrandomStarTemperature :: SpectralType -> Rnd Temperature\nrandomStarTemperature s = randomRM (specTempRange s)\n\ncreateStar :: (Planet () -> Rnd a) -> String -> Flt -> Orbit -> Rnd (Star a)\ncreateStar genfunc name maxplanetorbitradius orbit = do\n  r <- randomRM (0, 1)\n  let s = getProbTableValue r starprobs\n  createStar' genfunc name maxplanetorbitradius orbit s\n\naddPrefixToPlanetName :: String -> Planet a -> Planet a\naddPrefixToPlanetName n p = \n  let oname = planetname p\n      nname = n ++ oname\n  in p{planetname = nname, satellites = E.map (addPrefixToPlanetName n) (satellites p)}\n\ncreateStar' :: (Planet () -> Rnd a) -> String -> Flt -> Orbit -> SpectralType -> Rnd (Star a)\ncreateStar' genfunc name maxplanetorbitradius orbit spectraltype = do\n  t <- randomStarTemperature spectraltype\n  numplanets <- randomRM (64, 128)\n  let planetnames = bodyNames name\n  planetorbitradiuses <- separate `fmap` sort `fmap` replicateM numplanets (randomRM (0.0001, min (fromIntegral t * 2 / 120) maxplanetorbitradius))\n  planets <- zipWithM (createPlanet genfunc t) (repeat \"\") planetorbitradiuses\n  let planets' = filter (\\p -> planetTemperature' t p > 30 && planetTemperature' t p < t `div` 4) planets\n  let planets'' = zipWith addPrefixToPlanetName planetnames planets'\n  return $! Star name t orbit (namedsToMap planets'')\n\nnamesFromBasenameCap :: String -> [String]\nnamesFromBasenameCap n = zipWith (++) (repeat (n ++ \" \")) (map (:[]) ['A' .. 'Z'])\n\nnamesFromBasenameMin :: String -> [String]\nnamesFromBasenameMin n = zipWith (++) (repeat (n ++ \" \")) (map (:[]) ['a' .. 'z'])\n\nnamesFromBasenameNum :: String -> [String]\nnamesFromBasenameNum n = zipWith (++) (repeat (n ++ \" \")) (map show [(1 :: Int) ..])\n\ncreateOrbit :: Flt -> Rnd Orbit\ncreateOrbit oradius = return $! Orbit oradius 0 0 1 0\n\nnoOrbit :: Orbit\nnoOrbit = Orbit 0 0 0 1 0\n\ncreateStars :: (Planet () -> Rnd a) -> String -> Int -> Rnd [Star a]\ncreateStars genfunc basename 1 = do\n  s <- createStar genfunc basename 3000 noOrbit\n  return [s]\ncreateStars genfunc basename numstars = do\n  let names = namesFromBasenameCap basename\n  orbitradiuses <- sort `fmap` replicateM numstars (randomRM (0.1, 12000))\n  orbits <- mapM createOrbit orbitradiuses\n  let dists = map (/4) (distances orbitradiuses)\n  spectraltypes <- map (flip getProbTableValue starbinaryprobs) `fmap` replicateM numstars (randomRM (0, 1))\n  stars <- zipWith4M (createStar' genfunc) names dists orbits (sort spectraltypes)\n  return $! stars\n\ncreateStarSystem :: (Planet () -> Rnd a) -> String -> Vector3 -> Rnd (StarSystem a)\ncreateStarSystem genfunc ssname sspos = do\n  -- http://www.cfa.harvard.edu/news/2006/pr200611.html \n  -- \"Most milky way stars are single\"\n  singular <- chance 2 3 \n  n <- if singular then return 1 else randomRM (2, 6 :: Int)\n  stars <- (createStars genfunc) ssname n\n  return $! StarSystem ssname sspos (namedsToMap stars)\n\ncreate2DPoint :: (Flt, Flt) -> Rnd Vector3\ncreate2DPoint (minc, maxc) = do\n  x <- randomRM (minc, maxc)\n  y <- randomRM (minc, maxc)\n  return (x, y, 0)\n\ncreate3DPoint :: (Flt, Flt) -> Rnd Vector3\ncreate3DPoint (minc, maxc) = do\n  x <- randomRM (minc, maxc)\n  y <- randomRM (minc, maxc)\n  z <- randomRM (minc, maxc)\n  return (x, y, z)\n\nssSpacingCoefficient :: Float\nssSpacingCoefficient = 5\n\ncreateGalaxy :: (Planet () -> Rnd a) -> String -> [String] -> Rnd (Galaxy a)\ncreateGalaxy genfunc galname ssnames = do\n  let numss = length ssnames\n  let dim = sqrt (fromIntegral numss) * ssSpacingCoefficient -- TODO: when 3d galaxy, use cbrt\n  points <- replicateM numss (create3DPoint (-dim, dim))\n  sss <- zipWithM (createStarSystem genfunc) ssnames points\n  return $! Galaxy galname (namedsToMap sss)\n\n\n", "meta": {"hexsha": "d59f627ddb91feafc40758edab2987b92d32906f", "size": 7545, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CreateGalaxy.hs", "max_stars_repo_name": "anttisalonen/starrover", "max_stars_repo_head_hexsha": "b1b3ae4c4f559bc041b92a093fdeb7a72527de4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-28T13:41:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-28T13:41:07.000Z", "max_issues_repo_path": "src/CreateGalaxy.hs", "max_issues_repo_name": "anttisalonen/starrover", "max_issues_repo_head_hexsha": "b1b3ae4c4f559bc041b92a093fdeb7a72527de4e", "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/CreateGalaxy.hs", "max_forks_repo_name": "anttisalonen/starrover", "max_forks_repo_head_hexsha": "b1b3ae4c4f559bc041b92a093fdeb7a72527de4e", "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": 44.3823529412, "max_line_length": 155, "alphanum_fraction": 0.6979456594, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4040446231219201}}
{"text": "module BondCalculus.ODEExtraction\n  (IVP(..), PrintStyle(..), ODE(..), AsSage(..),\n  matlabExpr, sympyExpr, sageExpr, matlabODE, vectorFieldToODEs, sageODE, sageExprAbst,\n  sageExprAbst', extractIVP, sympyODE, solveODEPython, printODEPython,\n  sympySimplify, runPython, generateSage) where\n\nimport BondCalculus.Base\nimport BondCalculus.Symbolic\nimport BondCalculus.Processes\nimport BondCalculus.Vector\nimport BondCalculus.AST (pretty)\nimport qualified BondCalculus.AST as AST\nimport qualified Data.HashMap.Strict as H\nimport BondCalculus.Simulation (Trace)\nimport Data.String.Utils\nimport Text.Printf\n\n-- import qualified Control.Exception as X\nimport qualified Data.Map as M\nimport qualified Data.List as L\nimport Data.Maybe\n\n--import qualified Numeric.LinearAlgebra as LA\n\nimport System.IO.Unsafe\n-- import qualified System.Process as OS\nimport System.Process (readProcess)\n-- import Data.Maybe\n\nnewtype IVP a = IVP ([String], [Expr (Atom a)], [a]) deriving (Show, Eq)\nnewtype ODE a = ODE ([String], [Expr (Atom a)])\n\n-------------------------------\n-- MATLAB script output:\n-------------------------------\n\nextractODE :: (ExprConstant a) => AST.Env -> ConcreteAffinityNetwork a -> P' a -> ODE a\nextractODE env network p = vectorFieldToODEs p'\n  where -- p' must be expressed in the same basis of p\n        -- otherwise the variable order becomes\n        -- inconsistient, and we get extra variables\n        -- p' :: Vect AST.Species (SymbolicExpr a)\n        p' = fromList [(p'coeff i, i) | (_,i) <- toList p]\n        -- p'coeff :: AST.Species -> SymbolicExpr a\n        p'coeff i = fromMaybe 0.0 (H.lookup i v)\n        Vect v = dPdt' tr network p\n        tr = tracesGivenNetwork network env\n\nextractIVP :: ExprConstant a => AST.Env -> ConcreteAffinityNetwork a -> P' a -> [a] -> IVP a\nextractIVP env network p = fromODEToIVP (extractODE env network p)\n\nvectorFieldToODEs :: ExprConstant a => P' a -> ODE a\nvectorFieldToODEs v = ODE (vars, rhss)\n  where\n    vars = map (pretty.snd) kis\n    rhss = map (simplify.fst) kis\n    kis = toList v\n\nfromODEToIVP :: ODE a -> [a] -> IVP a\nfromODEToIVP (ODE (x,y)) z = IVP (x, y, take (length x) z)\n\n-- modelToIVP :: BondCalculusModel SymbolicExpr Double -> IVP\n\nmatlabODE :: IVP Double -> (Int,(Double,Double)) -> Either String String\nmatlabODE ivp (n,(t0,tn)) =\n  if any isNothing eqns\n  then Left \"An ODE equation has an unbound variable\"\n  else Right $\n  \"init = [\" ++ L.intercalate \";\" (map show inits) ++ \"];\\n\" ++\n    \"t = linspace(\" ++ show t0 ++ \",\" ++ show tn ++ \",\" ++ show n ++ \");\\n\" ++\n    \"function xdot = f(x,t) \\n\\n\" ++\n    L.intercalate \";\\n\" (catMaybes eqns) ++\n    \";\\nendfunction;\\n\\n\" ++\n    -- Need new support for calculating jacobian\n    -- \"function jac = jj(x,t)\\n\\n\" ++\n    -- matlabJac env p' ++ \";\\nendfunction;\\n\\n\" ++\n    \"x = lsode(f, init, t);\\n\" ++\n    \"save (\\\"-ascii\\\", \\\"-\\\", \\\"x\\\");\"\n      where\n        xdots = [\"xdot(\" ++ show i ++ \")\" | i <- [(1::Integer)..]]\n        xvars = [\"x(\" ++ show i ++ \")\" | i <- [(1::Integer)..]]\n        varmap = M.fromList $ zip vars xvars\n        IVP (vars,rhss,inits) = ivp\n        eqns = [fmap (\\y -> xdot ++ \" = \" ++ y) (matlabExpr varmap rhs)\n               | (xdot,rhs) <- zip xdots rhss]\n\nclass Show a => AsSage a where\n    asSage :: a -> String\n\ninstance AsSage Double where\n    asSage = show\n\ninstance AsSage Interval where\n    asSage x = printf \"RIF('[%.20f .. %.20f]')\" l u\n        where (l, u) = endpoints x\n              -- Do some fiddling with the endpoints to ensure sound enclosure\n            --   l' = l - 6e-21\n            --   u' = u + 6e-21\n\nsageExpr :: AsSage a => M.Map String String -> Expr (Atom a) -> Maybe String\nsageExpr mp (Atom (Var x)) = M.lookup x mp\nsageExpr mp (Atom (Const x)) = return $ asSage x\nsageExpr mp (x `Sum` y) = do\n    x' <- sageExpr mp x\n    y' <- sageExpr mp y\n    return $ x' ++ \" + \" ++ y'\nsageExpr mp (x `Prod` y) = do\n    x' <- sageExpr mp x\n    y' <- sageExpr mp y\n    return $ \"(\" ++ x' ++ \") * (\" ++ y' ++ \")\"\nsageExpr mp (x `Frac` y) = do\n    x' <- sageExpr mp x\n    y' <- sageExpr mp y\n    return $ \"(\" ++ x' ++ \") / (\" ++ y' ++ \")\"\nsageExpr mp (x `Pow` y) = do\n    x' <- sageExpr mp x\n    y' <- sageExpr mp y\n    return $ \"(\" ++ x' ++ \") ** (\" ++ y' ++ \")\"\nsageExpr mp (Abs x) = do\n    x' <- sageExpr mp x\n    return $ \"abs(\" ++ x' ++ \")\"\nsageExpr mp (Sin x) = do\n    x' <- sageExpr mp x\n    return $ \"sin(\" ++ x' ++ \")\"\nsageExpr mp (Cos x) = do\n    x' <- sageExpr mp x\n    return $ \"sin(\" ++ x' ++ \")\"\nsageExpr mp (Tan x) = do\n    x' <- sageExpr mp x\n    return $ \"tan(\" ++ x' ++ \")\"\nsageExpr mp (Exp x) = do\n    x' <- sageExpr mp x\n    return $ \"exp(\" ++ x' ++ \")\"\nsageExpr mp (Log x) = do\n    x' <- sageExpr mp x\n    return $ \"log(\" ++ x' ++ \")\"\n\n-- Convert a sage expression into a string with all non-simple double constants (e.g. intervals)\n-- abstracted by symbolic variables\nsageExprAbst' :: (AsSage a, Boundable a) => M.Map String String -> Expr (Atom a) -> Maybe (M.Map String String, String)\nsageExprAbst' = sageExprAbst M.empty\n\nsageExprAbst :: (AsSage a, Boundable a) => M.Map String String -> M.Map String String -> Expr (Atom a) -> Maybe (M.Map String String, String)\nsageExprAbst cmp mp (Atom (Var x)) = do\n    x' <- M.lookup x mp\n    return (cmp, x')\nsageExprAbst cmp mp (Atom (Const x)) = return $ case singleValue x of\n    Just 1.0    -> (cmp, \"1\")\n    Just (-1.0) -> (cmp, \"-1\")\n    Just 0.0    -> (cmp, \"0\")\n    Just v      -> (cmp, asSage v)\n    Nothing     -> (cmp', s)\n        where n = M.size cmp \n              s = \"a\" ++ show n\n              cmp' = M.insert s (asSage x) cmp \nsageExprAbst cmp mp (x `Sum` y) = f2 cmp mp x y $ \\x' y' -> x' ++ \" + \" ++ y'\nsageExprAbst cmp mp (x `Prod` y) = f2 cmp mp x y $ \\x' y' -> \"(\" ++ x' ++ \") * (\" ++ y' ++ \")\"\nsageExprAbst cmp mp (x `Frac` y) = f2 cmp mp x y $ \\x' y' -> \"(\" ++ x' ++ \") / (\" ++ y' ++ \")\"\nsageExprAbst cmp mp (x `Pow` y) = f2 cmp mp x y $ \\x' y' -> \"(\" ++ x' ++ \") ** (\" ++ y' ++ \")\"\nsageExprAbst cmp mp (Abs x) = f1 cmp mp x $ \\x' -> \"abs(\" ++ x' ++ \")\"\nsageExprAbst cmp mp (Sin x) = f1 cmp mp x $ \\x' -> \"sin(\" ++ x' ++ \")\"\nsageExprAbst cmp mp (Cos x) = f1 cmp mp x $ \\x' -> \"cos(\" ++ x' ++ \")\"\nsageExprAbst cmp mp (Tan x) = f1 cmp mp x $ \\x' -> \"tan(\" ++ x' ++ \")\"\nsageExprAbst cmp mp (Exp x) = f1 cmp mp x $ \\x' -> \"exp(\" ++ x' ++ \")\"\nsageExprAbst cmp mp (Log x) = f1 cmp mp x $ \\x' -> \"log(\" ++ x' ++ \")\"\nsageExprAbst cmp mp x = error $ \"Support for converting expression \" ++ show x ++ \" to sage/sympy not implemented!\"\n\nf2 cmp mp x y g = do\n    (cmp', x') <- sageExprAbst cmp mp x\n    (cmp'', y') <- sageExprAbst cmp' mp y\n    return (cmp'', g x' y')\n\nf1 cmp mp x g = do\n    (cmp', x') <- sageExprAbst cmp mp x\n    return (cmp', g x')\n\n-- This assumes we can reduce the ODEs to sage\nsageODE :: (AsSage a, Boundable a) => IVP a -> String -> Either String String\nsageODE (IVP (vars, rhss, inits)) network = case odeExprs of\n        Nothing -> Left \"An ODE equation has an unbound variable\"\n        Just (cmp, odes) -> Right $\n            \"from sage.all import *\\n\" ++\n            \"import sympy as sym\\n\\n\" ++\n            \"R, x = PolynomialRing(RIF, \" ++ show nvars ++ \", ', '.join(map('x{}'.format, range(0, \" ++ show nvars ++ \")))).objgens()\\n\" ++\n            \"xsr = [SR.var(str(x1)) for x1 in x]\\n\" ++\n            \"for v in xsr:\\n\"++\n            \"   assume(v, 'real')\\n\"++\n            \"xsym = sym.var(','.join(map('x{}'.format, range(0,\" ++ show nvars ++ \"))))\\n\" ++\n            (if (M.size cmp) > 0\n             then \"asym = sym.var(','.join(map('a{}'.format, range(0,\" ++ show (M.size cmp) ++ \"))))\\n\"\n             else \"asym = []\\n\") ++\n            \"y0 = [\" ++ L.intercalate \", \" (map asSage inits) ++ \"]\\n\" ++\n            \"ysymraw = [\" ++ L.intercalate \", \" odes ++ \"]\\n\" ++\n            \"ysym = [sym.simplify(y1) for y1 in ysymraw]\\n\" ++\n            \"ysr = [y1._sage_().substitute(\" ++ subsExpr ++ \") for y1 in ysym]\\n\" ++\n            \"varmap = {\" ++ L.intercalate \", \" varmappings ++ \"}\\n\" ++\n            \"varmapsr = {\" ++ L.intercalate \", \" varmappingssr ++ \"}\\n\" ++\n            \"affinity_network = \\\"\" ++ network ++ \"\\\"\\n\" ++\n            \"try:\\n\" ++\n            \"    y = vector([R(y1) for y1 in ysr])\\n\" ++\n            \"except TypeError:\\n\" ++\n            \"    y = None\\n\"\n            where subsExpr = L.intercalate \",\"\n                             [x ++ \"=\" ++ y | (x, y) <- M.toList cmp]\n                  varmappings = [ \"'\" ++ p ++ \"': x[\" ++ show i ++ \"]\"\n                                | p <- vars | i <- [0..] ]\n                  varmappingssr = [ \"'\" ++ p ++ \"': xsr[\" ++ show i ++ \"]\"\n                                  | p <- vars | i <- [0..] ]\n    where\n    --   odeExprs' :: AsSage a => M.Map String String -> [Expr (Atom a)] -> Maybe (M.Map String String, [String])\n      odeExprs' cmp (x:xs) = do\n        (cmp', expr) <- sageExprAbst cmp varmap x \n        (cmp'', exprs) <- odeExprs' cmp' xs\n        return (cmp'', expr:exprs)\n      odeExprs' cmp [] = Just (cmp, [])\n      odeExprs :: Maybe (M.Map String String, [String])\n      odeExprs = odeExprs' M.empty rhss\n      nvars = length vars\n      xvars = [\"x\" ++ show n | (n, _) <- zip [0..] vars]\n      varmap = M.fromList $ zip vars xvars\n    --   odes = map odeExpr rhss\n    --   odeExpr rhs = do\n    --     expr <- sageExpr varmap rhs\n    --     return $ \"sym.simplify(\" ++ expr ++ \")\"\n\n\nsympyODE :: IVP Double -> (Int,(Double,Double)) -> Either String String\nsympyODE ivp (n,(t0,tn)) =\n  if any isNothing eqns\n  then Left \"An ODE equation has an unbound variable\"\n  else Right $\n  \"import sympy as sym\\n\" ++\n  \"import numpy as np\\n\" ++\n  \"from sympy.abc import t\\n\" ++\n  \"from scipy.integrate import odeint\\n\" ++\n  \"import sys\\n\" ++\n  \"sys.setrecursionlimit(100000)\\n\\n\" ++\n  \"xs = [\" ++ L.intercalate \",\"\n    [\"sym.Function('\" ++ show x ++ \"')\" | x <- vars ] ++ \"]\\n\" ++\n  \"xts = [x(t) for x in xs]\\n\" ++\n  \"odes = [\" ++ L.intercalate \", \" (catMaybes eqns) ++ \"]\\n\" ++\n  \"y0 = [\" ++ L.intercalate \", \" (map show inits) ++ \"]\\n\" ++\n  \"ts = np.linspace(\" ++ show t0 ++ \",\" ++ show tn ++ \",\" ++ show n ++ \")\\n\" ++\n  \"rhss = [eqn.rhs for eqn in odes]\\n\" ++\n  \"Jac = sym.Matrix(rhss).jacobian(xts)\\n\" ++\n  \"f = sym.lambdify((xts, t), rhss, modules='numpy')\\n\" ++\n  \"J = sym.lambdify((xts, t), Jac, modules='numpy')\\n\" ++\n  -- Try to solve ODEs using symbolic Jacobian\n  \"try: ys = odeint(f, y0, ts, (), J)\\n\" ++\n  -- Fallback to using method without Jacobian\n  \"except NameError: ys = odeint(f, y0, ts, ())\\n\" ++\n  -- \"print(ys)\\n\" ++\n  \"print('\\\\n'.join([' '.join([('%.18e' % y).replace('nan', '0') for y in ysa]) for ysa in ys]))\"\n    where\n      xvars = [\"xts[\" ++ show i ++ \"]\" | i <- [(0::Integer)..]]\n      xdots = [xvar ++ \".diff()\" | xvar <- xvars]\n      varmap = M.fromList $ zip vars xvars\n      IVP (vars,rhss,inits) = ivp\n      mkeqn xdot y = \"sym.Eq(\" ++ xdot ++ \", sym.simplify(\" ++ y ++ \"))\"\n      eqns = [fmap (mkeqn xdot) (sympyExpr varmap rhs)\n             | (xdot,rhs) <- zip xdots rhss]\n\ndata PrintStyle = Plain | Pretty | LaTeX | MathML deriving (Eq)\n\nsympyODEPrint :: ODE Double -> PrintStyle -> Either String String\nsympyODEPrint ode style =\n  if any isNothing eqns\n  then Left \"An ODE equation has an unbound variable\"\n  else Right $\n  \"import sympy as sym\\n\" ++\n  \"import numpy as np\\n\" ++\n  \"from sympy.abc import t\\n\" ++\n  \"import sys\\n\" ++\n  \"sys.setrecursionlimit(100000)\\n\\n\" ++\n  -- \"sym.init_printing(\" ++ printingoptions ++ \")\\n\\n\" ++\n  \"names = [\" ++ L.intercalate \",\" [\"'[\" ++ (if style == LaTeX then replace \"->\" \"\\\\\\\\rightarrow \" (replace \" \" \"\\\\\\\\ \" x) else x) ++ \"]'\" | x <- vars] ++ \"]\\n\" ++\n  \"xs = list(map(sym.Function, names))\\n\" ++\n  \"xts = [x(t) for x in xs]\\n\" ++\n  \"odes = [\" ++ L.intercalate \", \" (catMaybes eqns) ++ \"]\\n\" ++\n  \"rhss = [eqn.rhs for eqn in odes]\\n\" ++\n  case style of\n    Pretty -> \"for ode in odes: print(sym.pretty(ode))\\n\"\n    Plain -> \"for ode in odes: print(ode)\\n\"\n    -- print system of odes as latex (formatted for use in an align environment)\n    LaTeX -> \"print(sym.latex(odes)[7:-7].replace('=', '& =').replace(', \\\\\\\\  ', ' \\\\\\\\\\\\\\\\\\\\n').replace('{\\\\\\\\left(t \\\\\\\\right)}', '').replace('\\\\\\\\frac{d}{d t}', '\\\\\\\\frac{\\\\\\\\mathrm d}{\\\\\\\\mathrm d t}').replace('operatorname', 'mathrm'))\\n\"\n    MathML -> \"from sympy.printing import print_mathml\\nprint_mathml(odes)\\n\"\n    where\n      xvars = [\"xts[\" ++ show i ++ \"]\" | i <- [(0::Integer)..]]\n      xdots = [xvar ++ \".diff()\" | xvar <- xvars]\n      varmap = M.fromList $ zip vars xvars\n      ODE (vars,rhss) = ode\n      mkeqn xdot y = \"sym.Eq(\" ++ xdot ++ \", sym.simplify(\" ++ y ++ \"))\"\n      eqns = [fmap (mkeqn xdot) (sympyExpr varmap rhs)\n             | (xdot,rhs) <- zip xdots rhss]\n\nmatlabExpr :: M.Map String String -> SymbolicExpr Double -> Maybe String\nmatlabExpr mp (Atom (Var x)) = M.lookup x mp\nmatlabExpr _ (Atom (Const x)) = return $ show x\nmatlabExpr mp (x `Sum` y) = do\n  x' <- matlabExpr mp x\n  y' <- matlabExpr mp y\n  return $ x' ++ \" .+ \" ++ y'\nmatlabExpr mp (x `Prod` y) = do\n  x' <- matlabExpr mp x\n  y' <- matlabExpr mp y\n  return $ \"(\" ++ x' ++ \") .* (\" ++ y' ++ \")\"\nmatlabExpr mp (x `Pow` y) = do\n  x' <- matlabExpr mp x\n  y' <- matlabExpr mp y\n  return $ \"(\" ++ x' ++ \") .** (\" ++ y' ++ \")\"\nmatlabExpr mp (Abs x) = do\n  x' <- matlabExpr mp x\n  return $ \"abs(\" ++ x' ++ \")\"\n\n\nsympyExpr :: M.Map String String -> SymbolicExpr Double -> Maybe String\nsympyExpr mp (Atom (Var x)) = M.lookup x mp\nsympyExpr _ (Atom (Const x)) = return $ show x\nsympyExpr mp (x `Sum` y) = do\n  x' <- sympyExpr mp x\n  y' <- sympyExpr mp y\n  return $ x' ++ \" + \" ++ y'\nsympyExpr mp (x `Prod` y) = do\n  x' <- sympyExpr mp x\n  y' <- sympyExpr mp y\n  return $ \"(\" ++ x' ++ \") * (\" ++ y' ++ \")\"\nsympyExpr mp (x `Frac` y) = do\n  x' <- sympyExpr mp x\n  y' <- sympyExpr mp y\n  return $ \"(\" ++ x' ++ \") / (\" ++ y' ++ \")\"\nsympyExpr mp (x `Pow` y) = do\n  x' <- sympyExpr mp x\n  y' <- sympyExpr mp y\n  return $ \"(\" ++ x' ++ \") ** (\" ++ y' ++ \")\"\nsympyExpr mp (Abs x) = do\n  x' <- sympyExpr mp x\n  -- return $ x'\n  return $ \"abs(\" ++ x' ++ \")\"\nsympyExpr mp (Sin x) = do\n  x' <- sympyExpr mp x\n  return $ \"sin(\" ++ x' ++ \")\"\nsympyExpr mp (Cos x) = do\n  x' <- sympyExpr mp x\n  return $ \"sin(\" ++ x' ++ \")\"\nsympyExpr mp (Tan x) = do\n  x' <- sympyExpr mp x\n  return $ \"tan(\" ++ x' ++ \")\"\nsympyExpr mp (Exp x) = do\n  x' <- sympyExpr mp x\n  return $ \"exp(\" ++ x' ++ \")\"\nsympyExpr mp (Log x) = do\n  x' <- sympyExpr mp x\n  return $ \"log(\" ++ x' ++ \")\"\n\n---------------------------------------\n-- Using Octave to execute the scripts\n---------------------------------------\n\nrunPython :: String -> IO String\nrunPython = readProcess \"python3\" [\"-q\"]\n\ncallSolveODEPython :: AST.Env -> ConcreteAffinityNetwork Double -> P' Double -> [Double] -> (Int, (Double, Double)) -> IO String\ncallSolveODEPython env network p inits tr = case sympyODE (extractIVP env network p inits) tr of\n  Right script -> do\n    putStrLn $ \"Python script:\\n\\n\" ++ script\n    writeFile \"script.py\" script\n    runPython script\n  Left _ -> undefined\n\ngenerateSage :: (ExprConstant a, AsSage a)\n             => String\n             -> AST.Env\n             -> ConcreteAffinityNetwork a\n             -> P' a\n             -> [a]\n             -> IO String\ngenerateSage filename env network p inits = case sageODE (extractIVP env network p inits) (pretty network) of\n  Right script -> do\n    putStrLn $ \"Sage script:\\n\\n\" ++ script\n    writeFile filename script\n    return script\n  Left _ -> undefined\n\ncallPrintODEPython :: AST.Env -> ConcreteAffinityNetwork Double -> P' Double -> PrintStyle -> IO String\ncallPrintODEPython env network p style = case sympyODEPrint (extractODE env network p) style of\n  Right script -> do\n    -- putStrLn $ \"Python script:\\n\\n\" ++ script\n    writeFile \"print_script.py\" script\n    runPython script\n  Left _ -> undefined\n\nsolveODEPython :: AST.Env -> ConcreteAffinityNetwork Double -> P' Double -> [Double] -> (Int, (Double, Double)) -> Trace\nsolveODEPython env network p inits tr@(n,(t0,tn))\n  = let raw = unsafePerformIO (callSolveODEPython env network p inits tr)\n        ts = [t0 + fromIntegral i*(tn-t0)/fromIntegral n | i <- [0..n]]\n        yss = (map (map read.words) $ lines raw) :: [[Double]]\n        ys = [fromList (xs `zip` pbasis) | xs <- yss]\n        pbasis = map snd $ toList p\n    in ts `zip` ys\n\nsympySimplify :: String -> String\nsympySimplify s = unsafePerformIO (runPython script)\n  where script = \"from sympy import simplify, sympify\\nimport re\\n\" ++\n                 \"print(simplify(sympify(re.sub(r'([0-9]+)\\\\.0(?![0-9]*[1-9])', r'\\\\1', \" ++ show s ++ \"))))\"\n\nprintODEPython :: AST.Env -> ConcreteAffinityNetwork Double -> P' Double -> PrintStyle -> String\nprintODEPython env network p style\n  = let raw = unsafePerformIO (callPrintODEPython env network p style)\n    in raw\n-- callOctave env p mts p' ts = let\n--     script = matlabODE env (wholeProc env p mts) p' ts\n--   in do\n--     putStrLn $ \"Octave Script: \\n\" ++ script\n--     OS.readProcess\n--       \"octave\" [\"-q\", \"--eval\", script] []\n\n-- | Solver which calculates the symbolic Jacobian, writes MATLAB code, and executes it with GNU Octave. (General purpose, deals with stiff systems, uses LSODE.)\n-- solveODEoctave :: Solver\n-- solveODEoctave env p mts p' ts@(n,(t0,tn))\n--     = let raw = unsafePerformIO (callOctave env p mts p' ts)\n--       in (n>< Map.size p') $ map s2d $ words raw\n\n\n-- Return the MATLAB script for ODEs\n-- matlabScript :: Env\n--              -> Process\n--              -> MTS\n--              -> P'\n--              -> (Int, (Double, Double))\n--              -> String\n-- matlabScript env p mts = matlabODE env (wholeProc env p mts)\n", "meta": {"hexsha": "a9647c18e8c76411b01005b7154206944027239d", "size": 17558, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "bondlib/BondCalculus/ODEExtraction.hs", "max_stars_repo_name": "twright/bondwb", "max_stars_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-04T20:00:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-16T11:54:15.000Z", "max_issues_repo_path": "bondlib/BondCalculus/ODEExtraction.hs", "max_issues_repo_name": "twright/bondwb", "max_issues_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bondlib/BondCalculus/ODEExtraction.hs", "max_forks_repo_name": "twright/bondwb", "max_forks_repo_head_hexsha": "5557788f8cdf780fa2899ca29eb926ed5c3ab205", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6435185185, "max_line_length": 244, "alphanum_fraction": 0.5489235676, "num_tokens": 5771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4040364332908043}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ViewPatterns     #-}\n{-|\nModule      : Grenade.Layers.Internal.Hmatrix\nDescription : Faster implementations of HMatrix functions\nMaintainer  : Theo Charalambous\nLicense     : BSD2\nStability   : experimental\n-}\nmodule Grenade.Layers.Internal.Hmatrix (\n    reshapeMatrix\n  ) where\n\nimport           Numeric.LinearAlgebra\nimport           Numeric.LinearAlgebra.Devel\n\n-- | Reshape a row major matrix\nreshapeMatrix :: (Element t, Num t, Container Vector t) => Int -> Int -> Matrix t -> Matrix t\nreshapeMatrix r c m@(size->(r', c'))\n    | r * c == r' * c' = matrixFromVector RowMajor r c $ flatten m\n    | otherwise        = error $ \"can't reshape matrix of shape dim = \" ++ show (r', c') ++ \" to matrix of shape \" ++ show (r, c)\n{-# INLINE reshapeMatrix #-}", "meta": {"hexsha": "ea7e555678eb764251cf9454eff0df7164903562", "size": 800, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Internal/Hmatrix.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Internal/Hmatrix.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Internal/Hmatrix.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3636363636, "max_line_length": 129, "alphanum_fraction": 0.65625, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5, "lm_q1q2_score": 0.4040336067763816}}
{"text": "module Tests.SpecFunctions where\n\n\nimport Test.QuickCheck  hiding (choose,within)\n--import Test.Framework\n--import Test.Framework.Providers.QuickCheck2\n--import Numeric.SpecFunctions\n", "meta": {"hexsha": "dc870404b7afdb0e7b7c30f0fd0332c85858a286", "size": 183, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Tests/SpecFunctions.hs", "max_stars_repo_name": "aharol/datools", "max_stars_repo_head_hexsha": "1e5607794776eb5dfbae6bac5ce3b39f9f0f3213", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Tests/SpecFunctions.hs", "max_issues_repo_name": "aharol/datools", "max_issues_repo_head_hexsha": "1e5607794776eb5dfbae6bac5ce3b39f9f0f3213", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Tests/SpecFunctions.hs", "max_forks_repo_name": "aharol/datools", "max_forks_repo_head_hexsha": "1e5607794776eb5dfbae6bac5ce3b39f9f0f3213", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.875, "max_line_length": 46, "alphanum_fraction": 0.825136612, "num_tokens": 40, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.4039481783104427}}
{"text": "{-# LANGUAGE FlexibleContexts    #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict              #-}\nmodule Pinwheel.FourierSeries2D where\n\nimport           Control.Monad                  as M\nimport           Control.Monad.IO.Class\nimport           Control.Monad.Trans.Resource\nimport qualified Data.Array.Accelerate          as A\nimport           Data.Array.Accelerate.LLVM.PTX as A\nimport           Data.Array.IArray              as IA\nimport           Data.Array.Repa                as R\nimport           Data.Complex\nimport           Data.Conduit                   as C\nimport           Data.Conduit.List              as CL\nimport           Data.List                      as L\nimport           Data.Vector.Generic            as VG\nimport           Data.Vector.Storable           as VS\nimport           Data.Vector.Unboxed            as VU\nimport           Foreign.CUDA.Driver            as CUDA\nimport           FourierMethod.FourierSeries2D\nimport           Math.Gamma\nimport           Pinwheel.Base\nimport           Pinwheel.List\nimport           Utils.BLAS\nimport           Utils.Distribution\nimport           Utils.List\nimport           Utils.Parallel                 hiding ((.|))\nimport           Utils.SimpsonRule\nimport           Utils.Time\nimport DFT.Plan\nimport Filter.Utils\nimport Control.Concurrent.Async\nimport Numeric.GSL.Special.Bessel\n\npinwheelFourierSeries ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     , VG.Vector vector (Complex e)\n     , NFData (vector (Complex e))\n     )\n  => [Int]\n  -> [PTX]\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> Int\n  -> Int\n  -> IO (IA.Array (Int, Int) (vector (Complex e)))\npinwheelFourierSeries deviceIDs ptxs numR2Freqs numPoints delta periodR2 phiFreq rhoFreq thetaFreq rFreq sigma numBatchR2 numBatchPinwheelFreqs = do\n  let idxs =\n        [ (radialFreq, angularFreq)\n        | radialFreq <- pinwheelFreqs rhoFreq rFreq\n        , angularFreq <- pinwheelFreqs phiFreq thetaFreq\n        ]\n      centerR2Freq = div numR2Freqs 2\n  pinwheels <-\n    computeUnboxedP .\n    R.traverse\n      (fromListUnboxed (Z :. (L.length idxs)) idxs)\n      (\\(Z :. freqs) -> (Z :. freqs :. numR2Freqs :. numR2Freqs)) $ \\f (Z :. pFreq :. xFreq :. yFreq) ->\n      fourierMellin\n        sigma\n        (snd $ f (Z :. pFreq))\n        (fst $ f (Z :. pFreq))\n        ( delta * fromIntegral (xFreq - centerR2Freq)\n        , delta * fromIntegral (yFreq - centerR2Freq))\n  -- pinwheels <-\n  --   M.mapM\n  --     (\\idx ->\n  --        fmap\n  --          (CuMat (numR2Freqs ^ 2) (L.length idx) .\n  --           CuVecHost . VU.convert . toUnboxed) .\n  --        computeP .\n  --        R.traverse\n  --          (fromListUnboxed (Z :. (L.length idx)) idx)\n  --          (\\(Z :. freqs) -> (Z :. numR2Freqs :. numR2Freqs :. freqs)) $ \\f (Z :. xFreq :. yFreq :. pFreq) ->\n  --          fourierMellin\n  --            sigma\n  --            (snd $ f (Z :. pFreq))\n  --            (fst $ f (Z :. pFreq))\n  --            ( fromIntegral (xFreq - centerR2Freq)\n  --            , fromIntegral (yFreq - centerR2Freq))) .\n  --   divideListN numBatchPinwheelFreqs $\n  --   idxs\n  -- printCurrentTime \"Compute Fourier Series... \"\n  -- arr <-\n  --   computeFourierSeriesR2Stream\n  --     deviceIDs\n  --     ptxs\n  --     numR2Freqs\n  --     numPoints\n  --     periodR2\n  --     delta\n  --     numBatchR2\n  --     pinwheels\n  -- printCurrentTime \"Compute Fourier Series Done\"\n  let (radialLB, radialUB) = pinwheelFreqsBound rhoFreq rFreq\n      (angularLB, angularUB) = pinwheelFreqsBound phiFreq thetaFreq\n  return .\n    listArray ((radialLB, angularLB), (radialUB, angularUB)) .\n    parMap\n      rdeepseq\n      (\\i ->\n         VG.convert . toUnboxed . computeS . R.slice pinwheels $  -- arr $\n         (Z :. i :. All :. All)) $\n    [0 .. (L.length idxs - 1)]\n\n\n-- Stream\n{-# INLINE source #-}\nsource :: Int -> Int -> Int -> Int -> ConduitT () (Int, Int) (ResourceT IO) ()\nsource phiFreq rhoFreq thetaFreq rFreq =\n  CL.sourceList\n    [ (radialFreq, angularFreq)\n    | radialFreq <- pinwheelFreqs rhoFreq rFreq\n    , angularFreq <- pinwheelFreqs phiFreq thetaFreq\n    ]\n\nconduit ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     , VG.Vector vector (Complex e)\n     )\n  => [Int]\n  -> Int\n  -> Int\n  -> e\n  -> Int\n  -> e\n  -> [[CuMat (Complex e)]]\n  -> ConduitT (Int, Int) [vector (Complex e)] (ResourceT IO) ()\nconduit deviceIDs numR2Freqs numPoints periodR2 batchSize sigma inverseR2Harmonics = do\n  liftIO $ printCurrentTime \"conduit\"\n  idx <- CL.take batchSize\n  unless\n    (L.null idx)\n    (do let centerR2Freq = div numR2Freqs 2\n        pinwheels <-\n          fmap\n            (CuMat (L.length idx) (numR2Freqs ^ 2) .\n             CuVecHost . VU.convert . toUnboxed) .\n          liftIO .\n          computeP .\n          R.traverse\n            (fromListUnboxed (Z :. (L.length idx)) idx)\n            (\\(Z :. freqs) -> (Z :. freqs :. numR2Freqs :. numR2Freqs)) $ \\f (Z :. pFreq :. xFreq :. yFreq) ->\n            fourierMellin\n              sigma\n              (snd $ f (Z :. pFreq))\n              (fst $ f (Z :. pFreq))\n              ( fromIntegral (xFreq - centerR2Freq)\n              , fromIntegral (yFreq - centerR2Freq))\n        arr <-\n          liftIO $\n          computeFourierSeriesR2\n            deviceIDs\n            numR2Freqs\n            numPoints\n            periodR2\n            inverseR2Harmonics\n            [pinwheels]\n        yield .\n          L.map\n            (\\i ->\n               VG.convert . toUnboxed . computeS . R.slice arr $\n               (Z :. i :. All :. All)) $\n          [0 .. (L.length idx - 1)])\n\npinwheelFourierSeriesStream ::\n     ( Storable e\n     , CUBLAS (Complex e)\n     , Unbox e\n     , RealFloat e\n     , A.Elt e\n     , A.Elt (Complex e)\n     , Floating (A.Exp e)\n     , A.FromIntegral Int e\n     , VG.Vector vector (Complex e)\n     )\n  => [Int]\n  -> [PTX]\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> Int\n  -> Int\n  -> Int\n  -> IO (IA.Array (Int, Int) (vector (Complex e)))\npinwheelFourierSeriesStream deviceIDs ptxs numR2Freqs numPoints delta periodR2 phiFreq rhoFreq thetaFreq rFreq sigma numBatchR2 batchSize numBatchPinwheelFreqs = do\n  inverseR2Harmonics <-\n    createInverseHarmonicMatriesGPU\n      ptxs\n      numBatchR2\n      numPoints\n      numR2Freqs\n      periodR2\n      delta\n  let (radialLB, radialUB) = pinwheelFreqsBound rhoFreq rFreq\n      (angularLB, angularUB) = pinwheelFreqsBound rhoFreq rFreq\n  fmap (listArray ((radialLB, angularLB), (radialUB, radialUB)) . L.concat) .\n    runConduitRes $\n    source phiFreq rhoFreq thetaFreq rFreq .|\n    conduit\n      deviceIDs\n      numR2Freqs\n      numPoints\n      periodR2\n      batchSize\n      sigma\n      inverseR2Harmonics .|\n    CL.consume\n\n-- 2D spatial domain to frequency domain:\n-- transform: cis (-freq * x)   \n-- inverse transform: cis (freq * x)   \n\n-- Analytical solution type 1\n-- The pinwheel harmonics are cis (-freq * x)   \n{-# INLINE analyticalFourierSeriesFunc1 #-}\nanalyticalFourierSeriesFunc1 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e))\n  => Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> e\n  -> e\n  -> Complex e\nanalyticalFourierSeriesFunc1 angularFreq radialFreq sigma periodR2 periodEnv phi rho =\n  let radialConst = 2 * pi / log periodEnv\n   in pi * ((0 :+ 1) ^ abs angularFreq) *\n      cis (fromIntegral (-angularFreq) * phi) *\n      ((periodR2 / (pi * rho) :+ 0) **\n       ((2 + sigma) :+ (radialConst * fromIntegral (-radialFreq)))) *\n      gamma\n        (((2 + fromIntegral (abs angularFreq) + sigma) :+\n          (radialConst * fromIntegral (-radialFreq))) /\n         2) /\n      gamma\n        (((fromIntegral (abs angularFreq) - sigma) :+\n          (radialConst * fromIntegral radialFreq)) /\n         2) \n\n-- The pinwheel is in the frequency domain, the function computes the Fourier series\n{-# INLINE analyticalFourierSeries1 #-}\nanalyticalFourierSeries1 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)\n  => Int\n  -> e\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> R.Array D DIM2 (Complex e)\nanalyticalFourierSeries1 numPoints delta angularFreq radialFreq sigma periodR2 periodEnv =\n  let center = div numPoints 2\n  in fromFunction (Z :. numPoints :. numPoints) $ \\(Z :. i :. j) ->\n       let x = fromIntegral $ i - center\n           y = fromIntegral $ j - center\n           rho = sqrt $ x ^ 2 + y ^ 2\n           phi = atan2 y x\n       in if rho == 0\n            then 0\n            else analyticalFourierSeriesFunc1\n                   angularFreq\n                   radialFreq\n                   sigma\n                   periodR2\n                   periodEnv\n                   phi\n                   (rho * delta)\n\n-- The pinwheel is in the spatial domain, the function computes the Fourier coefficients\n{-# INLINE analyticalFourierCoefficients1 #-}\nanalyticalFourierCoefficients1 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)\n  => Int\n  -> e\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> R.Array D DIM2 (Complex e)\nanalyticalFourierCoefficients1 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv =\n  let c = ((-1) ^ (abs angularFreq)) :+ 0\n  in R.map (* c) $\n     analyticalFourierSeries1 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv\n\n\n-- Analytical solution type 2\n-- The pinwheel harmonics are cis (freq * x)   \n{-# INLINE analyticalFourierSeriesFunc2 #-}\nanalyticalFourierSeriesFunc2 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e))\n  => Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> e\n  -> e\n  -> Complex e\nanalyticalFourierSeriesFunc2 angularFreq radialFreq sigma periodR2 periodEnv phi rho =\n  let radialConst = 2 * pi / (log periodEnv)\n  in pi * ((0 :+ 1) ^ (abs angularFreq)) *\n     ((cis (fromIntegral angularFreq * phi))) *\n     ((periodR2 / (pi * rho) :+ 0) **\n      ((2 + sigma) :+ (radialConst * fromIntegral radialFreq))) *\n     (gamma $\n      ((2 + fromIntegral (abs angularFreq) + sigma) :+\n       (radialConst * fromIntegral radialFreq)) /\n      2) /\n     (gamma $\n      ((fromIntegral (abs angularFreq) - sigma) :+\n       (radialConst * fromIntegral (-radialFreq))) /\n      2) \n  \n\n-- The pinwheel is in the frequency domain, the function computes the Fourier series\n{-# INLINE analyticalFourierSeries2 #-}\nanalyticalFourierSeries2 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)\n  => Int\n  -> e\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> R.Array D DIM2 (Complex e)\nanalyticalFourierSeries2 numPoints delta angularFreq radialFreq sigma periodR2 periodEnv =\n  let center = div numPoints 2\n      arr =\n        fromFunction (Z :. numPoints :. numPoints) $ \\(Z :. i :. j) ->\n          let x = delta * (fromIntegral $ i - center)\n              y = delta * (fromIntegral $ j - center)\n              rho = sqrt $ x ^ 2 + y ^ 2\n              phi = atan2 y x\n          in if rho == 0 -- || (rho > period / 2) -- || phi /= 0\n               then 0\n               else analyticalFourierSeriesFunc2\n                      angularFreq\n                      radialFreq\n                      sigma\n                      periodR2\n                      periodEnv\n                      phi\n                      rho\n     -- if angularFreq == 0\n     --   then fromFunction (Z :. numPoints :. numPoints) $ \\_ -> 0\n     --   else\n  in arr\n\n-- The pinwheel is in the spatial domain, the function computes the Fourier coefficients\n{-# INLINE analyticalFourierCoefficients2 #-}\nanalyticalFourierCoefficients2 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)\n  => Int\n  -> e\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> R.Array D DIM2 (Complex e)\nanalyticalFourierCoefficients2 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv =\n  let c = ((-1) ^ (abs angularFreq)) / periodR2 :+ 0\n  in R.map (* c) $\n     analyticalFourierSeries2\n       numFreqs\n       delta\n       angularFreq\n       radialFreq\n       sigma\n       periodR2\n       periodEnv\n       \n\n-- Analytical solution type 3\n-- The pinwheel harmonics are cis (-freq * x)   \n-- The envelope is r^2 * r^\\alpha, where \\alpha \\in (-2,-0.5)\n{-# INLINE analyticalFourierSeriesFunc3 #-}\nanalyticalFourierSeriesFunc3 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e))\n  => Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> e\n  -> e\n  -> Complex e\nanalyticalFourierSeriesFunc3 angularFreq radialFreq sigma periodR2 periodEnv phi rho =\n  let radialConst = 2 * pi / log periodEnv\n   in ((fromIntegral angularFreq ^ 2 :+ 0) -\n       ((sigma + 2) :+ (radialConst * fromIntegral (-radialFreq))) ^ 2) /\n      (8 * pi) *\n      ((0 :+ 1) ^ abs angularFreq) *\n      cis (fromIntegral (-angularFreq) * phi) /\n      (rho ^ 2 :+ 0) *\n      ((periodR2 / (pi * rho) :+ 0) **\n       ((2 + sigma) :+ (radialConst * fromIntegral (-radialFreq)))) *\n      gamma\n        (((2 + fromIntegral (abs angularFreq) + sigma) :+\n          (radialConst * fromIntegral (-radialFreq))) /\n         2) /\n      gamma\n        (((fromIntegral (abs angularFreq) - sigma) :+\n          (radialConst * fromIntegral radialFreq)) /\n         2) \n         \n{-# INLINE analyticalFourierSeries3 #-}\nanalyticalFourierSeries3 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)\n  => Int\n  -> e\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> R.Array D DIM2 (Complex e)\nanalyticalFourierSeries3 numPoints delta angularFreq radialFreq sigma periodR2 periodEnv =\n  let center = div numPoints 2\n  in fromFunction (Z :. numPoints :. numPoints) $ \\(Z :. i :. j) ->\n       let x = fromIntegral $ i - center\n           y = fromIntegral $ j - center\n           rho = sqrt $ x ^ 2 + y ^ 2\n           phi = atan2 y x\n       in if rho == 0\n            then 0\n            else analyticalFourierSeriesFunc3\n                   angularFreq\n                   radialFreq\n                   sigma\n                   periodR2\n                   periodEnv\n                   phi\n                   (rho * delta)\n         \n{-# INLINE analyticalFourierCoefficients3 #-}\nanalyticalFourierCoefficients3 ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)\n  => Int\n  -> e\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> R.Array D DIM2 (Complex e)\nanalyticalFourierCoefficients3 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv =\n  let c = ((-1) ^ (abs angularFreq)) :+ 0\n  in R.map (* c) $\n     analyticalFourierSeries3 numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv\n\n\npinwheelFourierCoefficientsAnatical ::\n     ( Unbox e\n     , RealFloat e\n     , Gamma (Complex e)\n     , VG.Vector vector (Complex e)\n     , NFData (vector (Complex e))\n     )\n  => Int\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> IA.Array (Int, Int) (vector (Complex e))\npinwheelFourierCoefficientsAnatical numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =\n  let idxs =\n        [ (radialFreq, angularFreq)\n        | radialFreq <- pinwheelFreqs rhoFreq rFreq\n        , angularFreq <- pinwheelFreqs phiFreq thetaFreq\n        ]\n      centerR2Freq = div numR2Freqs 2\n      (radialLB, radialUB) = pinwheelFreqsBound rhoFreq rFreq\n      (angularLB, angularUB) = pinwheelFreqsBound phiFreq thetaFreq\n      pinwheels =\n        parMap\n          rdeepseq\n          (\\(radialFreq, angularFreq) ->\n             VG.convert .\n             toUnboxed .\n             computeS -- .\n             -- R.zipWith\n             --   (*)\n             --   (fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i :. j) ->\n             --      gaussian2D\n             --        (fromIntegral $ i - centerR2Freq)\n             --        (fromIntegral $ j - centerR2Freq)\n             --        (fromIntegral $ div centerR2Freq 1))\n            $\n             analyticalFourierCoefficients2\n               numR2Freqs\n               1\n               (angularFreq)\n               (radialFreq)\n               sigma\n               periodR2\n               periodEnv)\n          idxs\n  in listArray ((radialLB, angularLB), (radialUB, angularUB)) pinwheels\n  \n\npinwheelFourierCoefficientsAnaticalList ::\n     ( Unbox e\n     , RealFloat e\n     , Gamma (Complex e)\n     , VG.Vector vector (Complex e)\n     , NFData (vector (Complex e))\n     )\n  => Int\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> [vector (Complex e)]\npinwheelFourierCoefficientsAnaticalList numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =\n  let idxs =\n        [ (radialFreq, angularFreq)\n        | radialFreq <- [-rhoFreq .. rhoFreq]\n        , angularFreq <- [-phiFreq .. phiFreq]\n        ]\n      centerR2Freq = div numR2Freqs 2\n      pinwheels =\n        parMap\n          rdeepseq\n          (\\(radialFreq, angularFreq) ->\n             VG.convert . toUnboxed . computeS $\n             analyticalFourierCoefficients2\n               numR2Freqs\n               1\n               (angularFreq)\n               (radialFreq)\n               sigma\n               periodR2\n               periodEnv)\n          idxs\n  in pinwheels\n  \npinwheelFourierCoefficientsAnaticalList1 ::\n     ( Unbox e\n     , RealFloat e\n     , Gamma (Complex e)\n     , VG.Vector vector (Complex e)\n     , NFData (vector (Complex e))\n     )\n  => Int\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> [vector (Complex e)]\npinwheelFourierCoefficientsAnaticalList1 numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =\n  let idxs =\n        [ (radialFreq, angularFreq)\n        | radialFreq <- [-rhoFreq .. rhoFreq]\n        , angularFreq <- [-phiFreq .. phiFreq]\n        ]\n      pinwheels =\n        parMap\n          rdeepseq\n          (\\(radialFreq, angularFreq) ->\n             VG.convert . toUnboxed . computeS $\n             analyticalFourierCoefficients2\n               numR2Freqs\n               1\n               (angularFreq)\n               (radialFreq)\n               sigma\n               periodR2\n               periodEnv)\n          idxs\n  in pinwheels\n  \npinwheelFourierCoefficientsAnaticalList2 ::\n     ( Unbox e\n     , RealFloat e\n     , Gamma (Complex e)\n     , VG.Vector vector (Complex e)\n     , NFData (vector (Complex e))\n     )\n  => Int\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> [vector (Complex e)]\npinwheelFourierCoefficientsAnaticalList2 numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =\n  let idxs =\n        [ (radialFreq, angularFreq)\n        | radialFreq <- [rFreq,(rFreq - 1) .. -rFreq]\n        , angularFreq <- [thetaFreq,(thetaFreq - 1) .. -thetaFreq]\n        ]\n      centerR2Freq = div numR2Freqs 2\n      radialConstant = 2 * pi / (log periodEnv)\n      pinwheels =\n        parMap\n          rdeepseq\n          (\\(radialFreq, angularFreq) ->\n             VG.convert . toUnboxed . computeS $\n             fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. x :. y) ->\n               let xFreq = fromIntegral $ x - centerR2Freq\n                   yFreq = fromIntegral $ y - centerR2Freq\n                   rho = sqrt $ xFreq ^ 2 + yFreq ^ 2\n                   phi = atan2 yFreq xFreq\n               in if rho == 0\n                    then 0\n                    else ((0 :+ (-1)) ^ 1) *\n                         ((periodR2 / (pi * rho) :+ 0) **\n                          (0 :+ fromIntegral radialFreq * radialConstant)) *\n                         (cis $ phi * fromIntegral angularFreq))\n          idxs\n  in pinwheels\n\n  \n{-# INLINE analyticalFourierSeries2' #-}\nanalyticalFourierSeries2' ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)\n  => Int\n  -> e\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> R.Array D DIM2 (Complex e)\nanalyticalFourierSeries2' numPoints _ angularFreq radialFreq sigma periodR2 periodEnv =\n  let center = div numPoints 2\n      arr =\n        fromFunction (Z :. numPoints :. numPoints) $ \\(Z :. i :. j) ->\n          let x' = i - center\n              y' = j - center\n          in if x' == 0 && y' == 0\n               then 0\n               else let x =\n                          if x' == 0\n                            then 0\n                            else if x' > 0\n                                   then 1 / (fromIntegral $ center + 1 - x')\n                                   else (-1) / (fromIntegral $ center + 1 + x')\n                        y =\n                          if y' == 0\n                            then 0\n                            else if y' > 0\n                                   then 1 / (fromIntegral $ center + 1 - y')\n                                   else (-1) / (fromIntegral $ center + 1 + y')\n                        rho = sqrt $ x ^ 2 + y ^ 2\n                        phi = atan2 y x\n                    in analyticalFourierSeriesFunc2\n                         angularFreq\n                         radialFreq\n                         sigma\n                         periodR2\n                         periodEnv\n                         phi\n                         rho\n  in arr\n  \n{-# INLINE analyticalFourierCoefficients2' #-}\nanalyticalFourierCoefficients2' ::\n     (Eq e, Fractional e, RealFloat e, Gamma (Complex e), Unbox e)\n  => Int\n  -> e\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> R.Array D DIM2 (Complex e)\nanalyticalFourierCoefficients2' numFreqs delta angularFreq radialFreq sigma periodR2 periodEnv =\n  let c = (-1) ^ (abs angularFreq) :+ 0\n  in R.map (* c) $\n     analyticalFourierSeries2'\n       numFreqs\n       delta\n       angularFreq\n       radialFreq\n       sigma\n       periodR2\n       periodEnv\n\n\npinwheelFourierCoefficientsAnatical' ::\n     ( Unbox e\n     , RealFloat e\n     , Gamma (Complex e)\n     , VG.Vector vector (Complex e)\n     , NFData (vector (Complex e))\n     )\n  => Int\n  -> Int\n  -> Int\n  -> Int\n  -> Int\n  -> e\n  -> e\n  -> e\n  -> IA.Array (Int, Int) (vector (Complex e))\npinwheelFourierCoefficientsAnatical' numR2Freqs phiFreq rhoFreq thetaFreq rFreq sigma periodR2 periodEnv =\n  let idxs =\n        [ (radialFreq, angularFreq)\n        | radialFreq <- pinwheelFreqs rhoFreq rFreq\n        , angularFreq <- pinwheelFreqs phiFreq thetaFreq\n        ]\n      centerR2Freq = div numR2Freqs 2\n      (radialLB, radialUB) = pinwheelFreqsBound rhoFreq rFreq\n      (angularLB, angularUB) = pinwheelFreqsBound phiFreq thetaFreq\n      pinwheels =\n        parMap\n          rdeepseq\n          (\\(radialFreq, angularFreq) ->\n             VG.convert .\n             toUnboxed .\n             computeS -- .\n             -- R.zipWith\n             --   (*)\n             --   (fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i :. j) ->\n             --      gaussian2D\n             --        (fromIntegral $ i - centerR2Freq)\n             --        (fromIntegral $ j - centerR2Freq)\n             --        (fromIntegral $ div centerR2Freq 2))\n            $\n             analyticalFourierCoefficients2'\n               numR2Freqs\n               1\n               (angularFreq)\n               (radialFreq)\n               sigma\n               periodR2\n               periodEnv)\n          idxs\n  in listArray ((radialLB, angularLB), (radialUB, angularUB)) pinwheels\n  \n{-# INLINE idealHighPassFilter #-}\nidealHighPassFilter ::\n     (VG.Vector vector (Complex Double))\n  => Double\n  -> Int\n  -> vector (Complex Double)\nidealHighPassFilter radius numR2Freq =\n  let a = 1 / (radius * 2)\n      r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n      sinc x =\n        if x == 0\n          then 1\n          else (sin (pi * x)) / (pi * x)\n  in VG.fromList\n       [ if xFreq == 0 && yFreq == 0\n         then (1 - 1 / a ^ 2) :+ 0\n         else ((-1) * (sinc (xFreq / a)) * (sinc (yFreq / a)) / (a ^ 2)) :+ 0\n       | xFreq <- r2Freqs\n       , yFreq <- r2Freqs\n       ]\n\n{-# INLINE idealHighPassFilter1 #-}\nidealHighPassFilter1 :: Int -> VS.Vector (Complex Double)\nidealHighPassFilter1 numR2Freq =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n  in VS.fromList\n       [ if xFreq == 0 && yFreq == 0\n         then 0\n         else (-1) :+ 0\n       | xFreq <- r2Freqs\n       , yFreq <- r2Freqs\n       ]\n  \n{-# INLINE gaussianHighPassFilter #-}\ngaussianHighPassFilter :: Double -> Int -> VS.Vector (Complex Double)\ngaussianHighPassFilter alpha numR2Freq =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n  in VS.fromList\n       [ if xFreq == 0 && yFreq == 0\n         then (1 - (pi / alpha)) :+ 0\n         else ((-1) * (pi / alpha) *\n               exp ((pi ^ 2 * (xFreq ^ 2 + yFreq ^ 2)) / (-alpha))) :+\n              0\n       | xFreq <- r2Freqs\n       , yFreq <- r2Freqs\n       ]\n  \n{-# INLINE gaussianHighPassFilter1 #-}\ngaussianHighPassFilter1 :: Double -> Double -> Int -> VS.Vector (Complex Double)\ngaussianHighPassFilter1 radius alpha numR2Freq =\n  let a = 1 / (radius * 2)\n      r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n      sinc x =\n        if x == 0\n          then 1\n          else (sin (pi * x)) / (pi * x)\n  in VS.fromList\n       [ (sinc (xFreq / a) * sinc (yFreq / a) / (a ^ 2) -\n          (pi / alpha) * exp ((pi ^ 2 * (xFreq ^ 2 + yFreq ^ 2)) / (-alpha))) :+\n       0\n       | xFreq <- r2Freqs\n       , yFreq <- r2Freqs\n       ]\n  \n{-# INLINE idealLowPassFilter #-}\nidealLowPassFilter ::\n     (VG.Vector vector (Complex Double))\n  => Double\n  -> Double\n  -> Int\n  -> vector (Complex Double)\nidealLowPassFilter radius periodR2 numR2Freq =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n   in VG.fromList\n        [ let rho = 2 * pi * sqrt (xFreq ^ 2 + yFreq ^ 2) / periodR2\n           in if rho == 0\n                then 0\n                else radius / rho  * bessel_J1 (radius * rho) / periodR2 / (2 * pi)^2 :+ 0\n        | xFreq <- r2Freqs\n        , yFreq <- r2Freqs\n        ]\n\n{-# INLINE gaussianLowPassFilter #-}\ngaussianLowPassFilter :: Double -> Int -> VS.Vector (Complex Double)\ngaussianLowPassFilter std numR2Freq =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n  in VS.fromList\n       [ ((std ^ 2) * exp ((-pi) * (xFreq ^ 2 + yFreq ^ 2) * (std ^ 2))) :+\n       0\n       | xFreq <- r2Freqs\n       , yFreq <- r2Freqs\n       ]\n\n{-# INLINE laplacianLowPassFilter #-}\nlaplacianLowPassFilter :: Double -> Int -> VS.Vector (Complex Double)\nlaplacianLowPassFilter a numR2Freq =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n  in VS.fromList\n       [ let s2 = xFreq ^ 2 + yFreq ^ 2\n         in if xFreq == 0 && yFreq == 0\n              then (1 - a / ((4 * pi * pi * s2 + a ^ 2) ** 1.5)) :+ 0\n              else (-a) / ((4 * pi * pi * s2 + a ^ 2) ** 1.5) :+ 0\n       | xFreq <- r2Freqs\n       , yFreq <- r2Freqs\n       ]\n       \n{-# INLINE laplacianHighPassFilter #-}\nlaplacianHighPassFilter :: Int -> VS.Vector (Complex Double)\nlaplacianHighPassFilter numR2Freq =\n  let r2Freqs = L.map fromIntegral . getListFromNumber $ numR2Freq\n  in VS.fromList\n       [ if xFreq == 0 && yFreq == 0\n         then 8 -- -3.33\n         else if xFreq == 0 && abs yFreq == 1\n                then -1 -- 0.67\n                else if abs xFreq == 1 && yFreq == 0\n                       then -1 -- 0.67\n                       else if abs xFreq == 1 && abs yFreq == 1\n                              then -1 -- 0.17\n                              else 0\n       | xFreq <- r2Freqs\n       , yFreq <- r2Freqs\n       ]\n\n{-# INLINE convolveFrequency #-}\nconvolveFrequency ::\n     (VG.Vector vector (Complex Double))\n  => DFTPlan\n  -> Int\n  -> vector (Complex Double)\n  -> IA.Array (Int, Int) (vector (Complex Double))\n  -> IO (IA.Array (Int, Int) (vector (Complex Double)))\nconvolveFrequency plan numR2Freq filter' arr = do\n  let dftPlanID = DFTPlanID DFT1DG [numR2Freq, numR2Freq] [0, 1]\n      idftPlanID = DFTPlanID IDFT1DG [numR2Freq, numR2Freq] [0, 1]\n      vecs = L.map VG.convert . IA.elems $ arr\n      filter =\n        VU.convert .\n        toUnboxed .\n        computeUnboxedS .\n        makeFilter2D . fromUnboxed (Z :. numR2Freq :. numR2Freq) . VG.convert $\n        filter'\n  dftF <- dftExecute plan dftPlanID filter\n  vecsF <- mapConcurrently (dftExecute plan dftPlanID) vecs\n  outputs <-\n    mapConcurrently (dftExecute plan idftPlanID . VS.zipWith (*) dftF) vecsF\n  return . listArray (bounds arr) . L.map VG.convert $ outputs\n  \n{-# INLINE convolveFrequency1 #-}\nconvolveFrequency1 ::\n     (VG.Vector vector (Complex Double))\n  => DFTPlan\n  -> Int\n  -> vector (Complex Double)\n  -> IA.Array (Int, Int) (vector (Complex Double))\n  -> IO (IA.Array (Int, Int) (vector (Complex Double)))\nconvolveFrequency1 plan numR2Freq filter' arr = do\n  let dftPlanID = DFTPlanID DFT1DG [numR2Freq, numR2Freq] [0, 1]\n      idftPlanID = DFTPlanID IDFT1DG [numR2Freq, numR2Freq] [0, 1]\n      vecs = L.map VG.convert . IA.elems $ arr\n      filter =\n        VU.convert .\n        toUnboxed .\n        computeUnboxedS .\n        makeFilter2D . fromUnboxed (Z :. numR2Freq :. numR2Freq) . VG.convert $\n        filter'\n  dftF <- dftExecute plan dftPlanID filter\n  vecsF <- mapConcurrently (dftExecute plan dftPlanID) vecs\n  outputs <-\n    mapConcurrently (dftExecute plan idftPlanID . VS.zipWith (*) dftF) vecsF\n  return .\n    listArray (bounds arr) . L.map VG.convert . L.zipWith (VG.zipWith (-)) vecs $\n    outputs\n    \n{-# INLINE centerHollow #-}\ncenterHollow ::\n     (VG.Vector vector (Complex Double))\n  => Int\n  -> IA.Array (Int, Int) (vector (Complex Double))\n  -> IA.Array (Int, Int) (vector (Complex Double))\ncenterHollow numR2Freq arr = centerHollowVector numR2Freq <$> arr\n\n{-# INLINE centerHollowVector #-}\ncenterHollowVector ::\n     (VG.Vector vector (Complex Double))\n  => Int\n  -> vector (Complex Double)\n  -> vector (Complex Double)\ncenterHollowVector numR2Freq vec =\n  let s = VG.sum vec / (fromIntegral (numR2Freq ^ 2) :+ 0)\n   in VG.map (\\x -> x - s) vec   \n\n{-# INLINE centerHollowArray #-}\ncenterHollowArray ::\n     (R.Source s (Complex e), Unbox e, RealFloat e)\n  => Int\n  -> R.Array s DIM2 (Complex e)\n  -> R.Array D DIM2 (Complex e)\ncenterHollowArray numR2Freq arr =\n  let s = sumAllS arr / (fromIntegral (numR2Freq ^ 2) :+ 0)\n   in R.map (\\x -> x - s) $ arr\n   \n{-# INLINE centerHollowArray' #-}\ncenterHollowArray' ::\n     (R.Source s (Complex e), Unbox e, RealFloat e)\n  => Int\n  -> R.Array s DIM2 (Complex e)\n  -> R.Array D DIM2 (Complex e)\ncenterHollowArray' numR2Freq arr =\n  let s = sumAllS arr\n      c = div numR2Freq 2\n   in R.traverse arr id $ \\f idx@(Z :. i :. j) ->\n        if i == c && j == c\n          then (-s)\n          else f idx\n\nenvelopIntegral ::\n     Double -> Double -> Double -> Double -> Double -> Int -> Complex Double\nenvelopIntegral a b delta s period radialFreq =\n  let m = round $ (b - a) / delta\n      n =\n        if odd m\n          then m\n          else m - 1\n      -- weights = VU.fromList $ weightsSimpsonRule n\n      vec =\n        VU.generate n $ \\i ->\n          let x = (a + fromIntegral i * delta)\n          -- in   ((x :+ 0) ** (s :+ freq)) * ((pi :+ 0) ** (0 :+ freq)) *\n          --      (gamma ((0.5 :+ 0) * (1 :+ (-freq)))) /\n          --      (gamma ((0.5 :+ 0) * (1 :+ freq)))\n          in analyticalFourierSeriesFunc2 0 radialFreq s period period 0 x\n  -- in (delta / 3 :+ 0) * (VU.sum . VU.zipWith (*) vec $ weights)\n  in VU.sum vec\n\nenvelopIntegral2D ::\n     Int -> Double -> Double -> Double -> Int -> Complex Double\nenvelopIntegral2D numPoints delta s period radialFreq =\n  let center = div numPoints 2\n      -- weights = VU.fromList $ weightsSimpsonRule n\n      arr = analyticalFourierSeries2 numPoints delta 0 radialFreq s period period\n  in sumAllS arr\n\nprintEnvelopIntegral ::\n     Double -> Double -> Double -> Double -> Double -> Int -> IO ()\nprintEnvelopIntegral a b delta s period radialFreq =\n  let m = round $ (b - a) / delta\n      n =\n        if odd m\n          then m\n          else m - 1\n      weights = VU.fromList $ weightsSimpsonRule n\n      vec =\n        VU.generate n $ \\i ->\n          let x = a + fromIntegral i * delta  \n          in analyticalFourierSeriesFunc2 0 radialFreq s period period 0 x\n  in print $ VU.zipWith (*) weights vec\n\n\n{-# INLINE createFrequencyArray #-}\ncreateFrequencyArray ::\n     (RealFloat e) => Int -> (e -> e -> Complex e) -> R.Array D DIM2 (Complex e)\ncreateFrequencyArray numR2Freqs f =\n  fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i :. j) ->\n    let x = fromIntegral $ i - div numR2Freqs 2\n        y = fromIntegral $ j - div numR2Freqs 2\n        rho = sqrt $ x ^ 2 + y ^ 2\n        phi = atan2 y x\n     in f phi rho\n          \n{-# INLINE createFrequencyArrayZeroCenter #-}\ncreateFrequencyArrayZeroCenter ::\n     (RealFloat e) => Int -> (e -> e -> Complex e) -> R.Array D DIM2 (Complex e)\ncreateFrequencyArrayZeroCenter numR2Freqs f =\n  fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \\(Z :. i :. j) ->\n    let x = fromIntegral $ i - div numR2Freqs 2\n        y = fromIntegral $ j - div numR2Freqs 2\n        rho = sqrt $ x ^ 2 + y ^ 2\n        phi = atan2 y x\n     in if rho == 0\n          then 0\n          else f phi rho\n", "meta": {"hexsha": "6939ae221126c532e598c658c1a3d51bbe5abbdd", "size": 32873, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Pinwheel/FourierSeries2D.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Pinwheel/FourierSeries2D.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/Pinwheel/FourierSeries2D.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 31.0415486308, "max_line_length": 164, "alphanum_fraction": 0.5516685426, "num_tokens": 9674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4034386251041442}}
{"text": "{-# LANGUAGE BangPatterns         #-}\n{-# LANGUAGE CPP                  #-}\n{-# LANGUAGE DataKinds            #-}\n{-# LANGUAGE FlexibleContexts     #-}\n{-# LANGUAGE GADTs                #-}\n{-# LANGUAGE RankNTypes           #-}\n{-# LANGUAGE ScopedTypeVariables  #-}\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  , fromStorableV\n  , isVectorShape\n  ) where\n\n#if MIN_VERSION_singletons(2,6,0)\nimport           Data.Kind                    (Type)\nimport           Data.Singletons.TypeLits     (SNat (..))\n#endif\n\nimport           Control.DeepSeq              (NFData (..))\nimport           Data.Maybe                   (fromMaybe)\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 qualified Numeric.LinearAlgebra        as NLA\nimport           Numeric.LinearAlgebra.Static hiding (zipWithVector)\nimport qualified Numeric.LinearAlgebra.Static as H\nimport           System.Random.MWC\nimport           Unsafe.Coerce                (unsafeCoerce)\n\nimport           Debug.Trace\n\nimport           Grenade.Types\nimport           Grenade.Utils.Vector\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\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 depth\n         , KnownNat (rows * depth))\n      => L (rows * depth) columns\n      -> S ('D3 rows columns depth)\n\n  -- HMatrix instances\n  S1DV :: (KnownNat len) -- ^ Always a row-vector\n       => !(V.Vector RealNum)\n       -> S ('D1 len)\n\n  -- HMatrix instances\n  S2DV :: (KnownNat rows, KnownNat columns)\n       => !(V.Vector RealNum) -- ^ Vector in row or column major accoring to @order@ in @Grenade.Utils.Conversion@. Use Data.Matrix here?\n       -> S ('D2 rows columns)\n\n  -- HMatrix instances\n  -- S3DH :: (KnownNat rows, KnownNat columns, KnownNat depth, KnownNat (rows * depth))\n  --      => HBLAS.MDenseMatrix RealWorld 'HBLAS.Row Double\n  --      -> S ('D3 rows columns depth)\n\n\nisVectorShape :: S x -> Bool\nisVectorShape S1DV{} = True\nisVectorShape S2DV{} = True\nisVectorShape _      = False\n\n\ninstance Show (S n) where\n  show (S1D x) = \"S1D \" ++ show x\n  show (S2D x) = \"S2D \" ++ show x\n  show (S3D x) = \"S3D \" ++ show x\n  show (S1DV x) = \"S1DV \" ++ show x\n  show inp@(S2DV x) = \"S2DV\" ++ show (sz inp) ++ \" \" ++ show x\n    where\n      sz ::\n           forall rows cols. (KnownNat rows, KnownNat cols)\n        => (S ('D2 rows cols))\n        -> (Int, Int)\n      sz _ =\n        let rows = fromIntegral $ natVal (Proxy :: Proxy rows)\n            cols = fromIntegral $ natVal (Proxy :: Proxy cols)\n         in (rows, cols)\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\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#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#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\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 (S1DV !v) = rnf v\n  rnf (S2DV !v) = rnf v\n  -- rnf (S3DH !_) = ()\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 (randomVector seed Uniform * 2 - 1)\n\n    D2Sing SNat SNat ->\n        S2D (uniformSample seed (-1) 1)\n\n    D3Sing SNat SNat SNat ->\n        S3D (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 =\n  case (sing :: Sing x) of\n    D1Sing SNat           -> S1D <$> H.create xs\n    D2Sing SNat SNat      -> S2D <$> mkL xs\n    D3Sing SNat SNat SNat -> S3D <$> mkL xs\n  where\n    mkL ::\n         forall rows columns. (KnownNat rows, KnownNat columns)\n      => Vector RealNum\n      -> 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\nfromStorableV :: forall x. SingI x => Vector RealNum -> S x\nfromStorableV v =\n  case (sing :: Sing x) of\n    D1Sing SNat           -> S1DV v\n    D2Sing SNat SNat      -> S2DV v\n    D3Sing SNat SNat SNat -> error \"unexpected case in fromStorableS\"\n\ninstance SingI x => Serialize (S x) where\n  put i =\n    case i of\n      S1D x -> put (1 :: Int) >> (putListOf put . NLA.toList . H.extract $ x)\n      S2D x -> put (1 :: Int) >> (putListOf put . NLA.toList . NLA.flatten . H.extract $ x)\n      S3D x -> put (1 :: Int) >> (putListOf put . NLA.toList . NLA.flatten . H.extract $ x)\n      S1DV x -> put (2 :: Int) >> putListOf put (V.toList x)\n      S2DV x -> put (2 :: Int) >> putListOf put (V.toList x)\n  get = do\n    (nr :: Int) <- get\n    case nr of\n      1 -> do\n        Just i <- fromStorable . V.fromList <$> getListOf get\n        return i\n      2 -> fromStorableV . V.fromList <$> getListOf get\n      _ -> error \"unexpected case in get in Serialize instance in Shape.hs\"\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 (S1DV x) = S1DV (mapVector f x)\nn1 f (S2DV x) = S2DV (mapVector 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 (S1DV x) (S1DV y)  = S1DV (zipWithVector f x y)\nn2 f (S2DV x) (S2DV y)  = S2DV (zipWithVector f x y)\nn2 f (S1D x) y@S1DV {}  = n2 f (S1DV $ extract x) y\nn2 f x@S1DV {} (S1D y)  = n2 f x (S1DV $ unsafeCoerce y)\nn2 f x@S2D{} y@(S2DV _) = n2 f (toS2DV x) y\nn2 f x@(S2DV _) y@S2D{} = n2 f x (toS2DV y)\n\ntoS2DV :: S ('D2 i j) -> S ('D2 i j)\ntoS2DV (S2D x)  = S2DV $ V.concat $ map H.extract . H.toColumns $ x\ntoS2DV (S2DV x) = S2DV x\n\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 (konst x)\n\n  D2Sing SNat SNat ->\n    S2D (konst x)\n\n  D3Sing SNat SNat SNat ->\n    S3D (konst x)\n", "meta": {"hexsha": "ee6ec6d92c2d4612776ec6e38c644d5b2354d6d6", "size": 9196, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Core/Shape.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Core/Shape.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Core/Shape.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": 30.8590604027, "max_line_length": 137, "alphanum_fraction": 0.5937364071, "num_tokens": 2972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.40331351197993465}}
{"text": "{-# LANGUAGE CPP              #-}\n{-# LANGUAGE DataKinds        #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs            #-}\n{-# LANGUAGE TemplateHaskell  #-}\n{-# LANGUAGE TypeOperators    #-}\n\nmodule Test.Grenade.Sys.Utils where\n\nimport           Numeric.LinearAlgebra        hiding (R, konst, randomVector,\n                                               uniformSample, (===))\nimport qualified Numeric.LinearAlgebra        as LA\nimport qualified Numeric.LinearAlgebra.Data   as D\nimport           Numeric.LinearAlgebra.Static (L, R)\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport           Hedgehog\nimport qualified Hedgehog.Gen                 as Gen\nimport qualified Hedgehog.Range               as Range\n\nimport           Test.Hedgehog.Compat\nimport           Test.Hedgehog.Hmatrix\n\nimport           GHC.TypeLits\nimport           Data.List\nimport           Data.Maybe\nimport           Data.Function\nimport           Data.Either\nimport           Control.Monad                (guard)\nimport           System.FilePath\nimport qualified Data.ByteString.Lazy as BS\nimport           Data.Binary\n\nimport           Grenade\nimport           Grenade.Utils.PascalVoc\nimport           Grenade.Utils.ImageNet\n\nimagesDir :: FilePath\nimagesDir = (takeDirectory __FILE__) </> \"Images\"\n\nloadSerializedImage :: (KnownNat d, KnownNat c, KnownNat (d * c), c ~ 3) => FilePath -> IO (Maybe (S ('D3 d d c)))\nloadSerializedImage path = do\n  bs <- BS.readFile path\n  let mat = decode bs :: LA.Matrix Double\n  return $ S3D <$> (H.create (D.cmap doubleToRealNum mat))\n\nloadSerializedChannel :: (KnownNat d, KnownNat c, KnownNat (d * c), c ~ 1) => FilePath -> IO (Maybe (S ('D3 d d c)))\nloadSerializedChannel path = do\n  bs <- BS.readFile path\n  let mat = decode bs :: LA.Matrix Double\n  return $ S3D <$> (H.create (D.cmap doubleToRealNum mat))\n\n-- Performs linear regression on data points, where \n-- the x-values consist of the data set [1..n]\nlinearRegression :: Int -> [Double] -> Double\nlinearRegression n ys = m\n  where\n    n'    = fromIntegral n :: Double\n    xs    = [1..n] :: [Int]\n    x     = (n' + 1) / 2\n    x2    = (fromIntegral $ sum (map (^ 2) xs)) / n'\n    xyNum = (sum $ zipWith (\\l i -> l * (fromIntegral i)) ys xs) :: Double\n    xy    = xyNum / n' :: Double\n    y     = (sum ys) / n'\n    m     = (xy - (x * y)) / (x2 - (x * x)) :: Double\n", "meta": {"hexsha": "e76d5996ab66a4aae630efd3a1ae2bf5b1ddc5da", "size": 2355, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Test/Grenade/Sys/Utils.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "test/Test/Grenade/Sys/Utils.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Test/Grenade/Sys/Utils.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6818181818, "max_line_length": 116, "alphanum_fraction": 0.5966029724, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.40302633165989615}}
{"text": "{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeFamilies #-}\n\n-- Import all models under maintenance.\n-- Models not imported here will not be compiled\n-- when invoking `stack bench`.\nimport qualified BetaBin\nimport Control.Applicative ((<$>))\nimport Control.Arrow (first, second)\nimport Control.Monad (unless, when)\nimport Control.Monad.Bayes.Class\nimport Control.Monad.Bayes.Enumerator\nimport Control.Monad.Bayes.Inference\nimport Control.Monad.Bayes.Population\nimport Control.Monad.Bayes.Sampler\nimport Control.Monad.Bayes.Simple\nimport Control.Monad.Bayes.Weighted\nimport Control.Monad.IO.Class (MonadIO, liftIO)\nimport qualified DPmixture\nimport qualified Data.Vector as Vector\nimport qualified Dice\nimport qualified Gamma\nimport Graphics.Rendering.Chart.Backend.Cairo\nimport Graphics.Rendering.Chart.Easy\nimport qualified HMM\nimport Numeric.LogDomain\nimport Options.Applicative\nimport Plotting\nimport Statistics.Sample\nimport System.Directory\nimport System.IO\n\nopts :: ParserInfo Bool\nopts =\n  flip info fullDesc $\n    switch\n      ( long \"trial\"\n          <> help \"Run a quick version of benchmarks to check that all is working correctly\"\n      )\n\ntryCache :: (MonadIO m, Read a, Show a) => FilePath -> m a -> m a\ntryCache filepath fresh = do\n  exists <- liftIO $ doesFileExist filepath\n  if exists\n    then liftIO $ fmap read (readFile filepath)\n    else do\n      value <- fresh\n      liftIO $ writeFile filepath (show value)\n      return value\n\nmain = do\n  -- make sure `putStrLn` prints to console immediately\n  hSetBuffering stdout LineBuffering\n  trial <- execParser opts\n  when trial $ putStrLn \"Trial run\"\n  sampleIO hmmBenchmark\n\nmeanVar :: (MonadDist m, CustomReal m ~ Double) => Int -> m Double -> m (Double, Double)\nmeanVar n d = do\n  xs <- Vector.replicateM n d\n  return $ meanVariance xs\n\nsmcParams :: [Int]\nsmcParams = [10, 20, 50, 100, 200, 500, 1000]\n\nns :: [Int]\n--ns = [10,20,50,100,200,500,1000]\nns = [10, 20 .. 1000]\n\nsmcParamsDouble :: [Double]\nsmcParamsDouble = map fromIntegral smcParams\n\nsmcResults :: (MonadDist m, CustomReal m ~ Double) => [m (Vector.Vector Double)]\nsmcResults = map (\\p -> Vector.replicateM 10 $ fmap HMM.hmmKL $ explicitPopulation $ smcMultinomial (length HMM.values) p HMM.hmm) smcParams\n\nhmmBenchmark :: SamplerIO ()\nhmmBenchmark = do\n  liftIO $ putStrLn \"running HMM benchmark\"\n  isSamples <- fmap (drop 5000) $ explicitPopulation $ importance 10000 HMM.hmm\n  let isRes = map (\\n -> HMM.hmmKL $ take n isSamples) ns\n  -- mhSamples <- fmap (drop 5000) $ traceMH 10000 HMM.hmm\n  -- let mhRes = map (\\n -> HMM.hmmKL $ take n $ map (,1) mhSamples) ns\n  mhPriorSamples <- drop 5000 <$> mhPrior HMM.hmm 10000\n  let mhPriorRes = map (\\n -> HMM.hmmKL $ take n $ map (,1) mhPriorSamples) ns\n  pimhSamples <- pimh (length HMM.values) 100 1000 HMM.hmm\n  let pimhRes = map (\\n -> HMM.hmmKL $ take n $ map (,1) pimhSamples) ns\n  liftIO $ toFile (fo_format .~ PDF $ def) \"anytime.pdf\" $ do\n    layout_title .= \"HMM\"\n    anytimePlot\n      \"#samples\"\n      \"KL\"\n      ns\n      [ (\"IS\", isRes),\n        -- (\"MHtrace\", mhRes),\n        (\"MHprior\", mhPriorRes),\n        (\"PIMH\", pimhRes)\n      ]\n  smcRes <- sequence smcResults\n  liftIO $ toFile (fo_format .~ PDF $ def) \"smc.pdf\" $ do\n    layout_title .= \"HMM\"\n    oneShotPlot\n      \"#particles\"\n      \"KL\"\n      [ (\"SMC\", zip smcParamsDouble (map (errBars 2) smcRes))\n      ]\n", "meta": {"hexsha": "ab88b6466477d29abca32f27aa9ba0c2c53d5e5c", "size": 3389, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "models/BenchAll.hs", "max_stars_repo_name": "saeedhadikhanloo/monad-bayes", "max_stars_repo_head_hexsha": "9b764c952551a5d62bdbdeac1cd13921f4cf9f27", "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": "models/BenchAll.hs", "max_issues_repo_name": "saeedhadikhanloo/monad-bayes", "max_issues_repo_head_hexsha": "9b764c952551a5d62bdbdeac1cd13921f4cf9f27", "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": "models/BenchAll.hs", "max_forks_repo_name": "saeedhadikhanloo/monad-bayes", "max_forks_repo_head_hexsha": "9b764c952551a5d62bdbdeac1cd13921f4cf9f27", "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.6728971963, "max_line_length": 140, "alphanum_fraction": 0.6934198879, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.40259759817859075}}
{"text": "{-# LANGUAGE CPP #-}\n\nmodule Main (main) where\n\nimport Data.Complex (Complex ((:+)))\nimport Data.Complex.Polar\n#ifdef __GLASGOW_HASKELL__\nimport GHC.Stack (HasCallStack)\n#endif\nimport System.Exit\n  ( ExitCode (ExitFailure, ExitSuccess),\n    exitWith,\n  )\nimport Test.HUnit\n  ( Assertion,\n    Test (TestCase, TestList),\n    assertBool,\n    assertEqual,\n    errors,\n    failures,\n    runTestTT,\n  )\n\ntests :: Test\ntests =\n  TestList\n    [ TestCase $ rAndThetaAre 1 (0.1 - pi) $ mkPolar (- 1) 0.1,\n      TestCase $ rAndThetaAre 1 (pi / 2) $ mkPolar 1 (-3 * pi / 2),\n      TestCase $ rAndThetaAre 1 (0.5 - pi) $ mkPolar 1 (pi + 0.5),\n#if __GLASGOW_HASKELL__ >= 736\n      TestCase $ rAndThetaAre 1 (0.1 - pi) $ (- 1) :< 0.1,\n      TestCase $ rAndThetaAre 1 (pi / 2) $ 1 :< (- 3 * pi / 2),\n      TestCase $ rAndThetaAre 1 (0.5 - pi) $ 1 :< (pi + 0.5),\n#endif\n      TestCase $ rAndThetaAre 1 0.3 $ cis 0.3,\n      TestCase $ rAndThetaAre 1 (0.3 - pi) $ cis (pi + 0.3),\n      TestCase $ rAndThetaAre 0 0 $ mkPolar 0 pi,\n      TestCase $ rAndThetaAre 1 pi $ signum (mkPolar 1 pi),\n      TestCase $ rAndThetaAre 0 0 $ signum (mkPolar 0 pi),\n      TestCase $ rAndThetaAre 1 (-3 * pi / 4) $ negate (mkPolar 1 (pi / 4)),\n      TestCase $ rAndThetaAre 1 pi $ fromRational (- 1),\n      TestCase $ rAndThetaAre 1 0 $ exp $ mkPolar (10 * pi) (pi / 2),\n      TestCase $ rAndThetaAre (sqrt 2) (pi / 4) $ fromComplex $ 1 :+ 1,\n      TestCase $ isApproximately \"realPart\" 1 $ realPart $ mkPolar 1 0,\n      TestCase $ isApproximately \"imagPart\" 1 $ imagPart $ mkPolar 1 (pi / 2),\n      TestCase $ rAndThetaAre 1 (- pi / 4) $ conjugate $ mkPolar 1 (pi / 4),\n      TestCase $\n        rAndThetaAre (sqrt 2) (pi / 4) $\n          mkPolar 1 0 + mkPolar 1 (pi / 2),\n      TestCase $\n        rAndThetaAre (sqrt 2) (- pi / 4) $\n          mkPolar 1 0 - mkPolar 1 (pi / 2),\n      TestCase $ rAndThetaAre 1 0.7 $ mkPolar 1 0.3 * mkPolar 1 0.4,\n      TestCase $ rAndThetaAre (sqrt 2) 0 $ abs $ mkPolar (sqrt 2) 0.3,\n      TestCase $ rAndThetaAre 1 0 1, -- Test Num fromInteger\n      TestCase $ rAndThetaAre 1 0 $ mkPolar 1 0 * mkPolar 2 0.2 / mkPolar 2 0.2,\n      TestCase $ rAndThetaAre pi 0 pi, -- Test Floating pi\n      TestCase $ rAndThetaAre 54.5984 2.00000 $ exp z,\n      TestCase $ rAndThetaAre 1.56798 0.30018 $ log z,\n      TestCase $ rAndThetaAre 2.11474 0.23182 $ sqrt z,\n      TestCase $ rAndThetaAre 3.70497 (- 2.4472) $ sin z,\n      TestCase $ rAndThetaAre 3.68529 2.30135 $ cos z,\n      TestCase $ rAndThetaAre 1.00534 1.53455 $ tan z,\n      TestCase $ rAndThetaAre 27.3050 1.99974 $ sinh z,\n      TestCase $ rAndThetaAre 27.2930 2.00025 $ cosh z,\n      TestCase $ rAndThetaAre 1.00043 (- 0.0005) $ tanh z,\n      TestCase $ rAndThetaAre 2.44362 1.10527 $ asin z,\n      TestCase $ rAndThetaAre 2.23441 (- 1.3570) $ acos z,\n      TestCase $ rAndThetaAre 1.37491 0.07018 $ atan z,\n      TestCase $ rAndThetaAre 2.24493 0.20357 $ asinh z,\n      TestCase $ rAndThetaAre 2.23441 0.21370 $ acosh z,\n      TestCase $ rAndThetaAre 1.48069 1.43491 $ atanh z,\n      TestCase $ assertBool \"Eq instance works\" $ mkPolar 1 pi == mkPolar 1 pi,\n      TestCase $\n        assertEqual \"Show output good\" \"mkPolar 1.0 1.0\" $\n          show $ mkPolar 1 1,\n      TestCase $ readShowInverse z,\n      TestCase $ readShowInverse [z, z],\n      TestCase $ readShowInverse $ Just z\n    ]\n  where\n    z = mkPolar 4.47214 0.46364\n\napproximatelyEqualFloat :: Float -> Float -> Bool\napproximatelyEqualFloat x1 x2 = abs (x1 - x2) < 0.001\n\nisApproximately ::\n#ifdef __GLASGOW_HASKELL__\n  HasCallStack =>\n#endif\n  String -> Float -> Float -> Assertion\nisApproximately name x1 x2 =\n  assertBool (name ++ \" = \" ++ show x1 ++ \" is approximately \" ++ show x2) $\n    approximatelyEqualFloat x1 x2\n\nrAndThetaAre ::\n#ifdef __GLASGOW_HASKELL__\n  HasCallStack =>\n#endif\n  Float -> Float -> Polar Float -> Assertion\nrAndThetaAre r theta z = do\n  isApproximately \"magnitude\" r (magnitude z)\n  isApproximately \"phase\" theta (phase z)\n  let (r', theta') = polar z\n  isApproximately \"magnitude from polar\" r r'\n  isApproximately \"phase from polar\" theta theta'\n#if __GLASGOW_HASKELL >= 786\n  let (r'' :< theta') = polar z\n  isApproximately \"magnitude from :<\" r r''\n  isApproximately \"phase from :<\" theta theta''\n#endif\n\nreadShowInverse ::\n  (Show a, Read a,\n#ifdef __GLASGOW_HASKELL__\n  HasCallStack, \n#endif\n  Eq a) =>\n  a -> Assertion\nreadShowInverse a = assertEqual (\"read . show = id on \" ++ show a)\n                                (read $ show a)\n                                a\n \nmain :: IO ()\nmain = do\n  counts <- runTestTT tests\n  if errors counts + failures counts == 0\n    then exitWith ExitSuccess\n    else exitWith (ExitFailure 1)\n", "meta": {"hexsha": "d7fa3506dd6dcf82ea11c1d975e006ca989ba7b3", "size": 4678, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/Main.hs", "max_stars_repo_name": "kaoskorobase/polar", "max_stars_repo_head_hexsha": "0c7113bdef612237f696f0fbbc2af42556bb7c89", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Main.hs", "max_issues_repo_name": "kaoskorobase/polar", "max_issues_repo_head_hexsha": "0c7113bdef612237f696f0fbbc2af42556bb7c89", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-21T22:40:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-21T22:40:32.000Z", "max_forks_repo_path": "test/Main.hs", "max_forks_repo_name": "kaoskorobase/polar", "max_forks_repo_head_hexsha": "0c7113bdef612237f696f0fbbc2af42556bb7c89", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-18T17:59:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-18T17:59:59.000Z", "avg_line_length": 35.9846153846, "max_line_length": 80, "alphanum_fraction": 0.6235570757, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.40254458254903547}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n\nimport FrequencyResponse\n\nimport CLaSH.Prelude \nimport CLaSH.Signal.MultiSignal\nimport Data.Complex as C\nimport qualified Prelude as P\nimport Data.Maybe\nimport Control.Applicative\nimport Graphics.EasyPlot\nimport Data.Map.Strict as Map\n\n{-\nCiruits and stuff\n-}\n\nregisterP = prepend\n\nfirP coeffs x = dotp coeffs (windowP x)\n  where\n    dotp as bs = sum (zipWith (*) as bs)\n\niirP cA cB x = r where\n    oB =  firP cB x\n    oA =  firP cA (registerP def r)\n    r = oB - oA\n\n-- fir coeficients\nfirCoef :: Fractional a => Vec 201 a\nfirCoef = -6.86056317e-19 :> 1.08643703e-04 :> -6.04051550e-18 :> -2.03379801e-04 :> -2.01638331e-04 :> 1.96946883e-18 :> 2.90791068e-18 :> -4.62180925e-04 :> -1.00665733e-03 :> -9.14037108e-04 :> 3.86774364e-18 :> 1.01950810e-03 :> 1.25131737e-03 :> 6.39186084e-04 :> -8.00554425e-18 :> 2.62712857e-18 :> 3.77239653e-04 :> 4.17356596e-04 :> -1.21745475e-17 :> -2.64065618e-04 :> -5.23918059e-18 :> 2.99576343e-04 :> -2.73859684e-18 :> -6.08801988e-04 :> -6.23370976e-04 :> 1.63484509e-17 :> -7.03525331e-18 :> -1.52438502e-03 :> -3.36082345e-03 :> -3.07661933e-03 :> -1.30788363e-17 :> 3.45259832e-03 :> 4.23241069e-03 :> 2.15427395e-03 :> 0.00000000e+00 :> 2.70383448e-17 :> 1.24466846e-03 :> 1.36380726e-03 :> -2.92823518e-17 :> -8.44354542e-04 :> -4.24392593e-17 :> 9.35427798e-04 :> 2.64177628e-17 :> -1.85473668e-03 :> -1.87576073e-03 :> 2.24314248e-18 :> -5.19238250e-17 :> -4.42290170e-03 :> -9.63775624e-03 :> -8.72271164e-03 :> 3.66725201e-17 :> 9.57794343e-03 :> 1.16209519e-02 :> 5.85688426e-03 :> -6.95248052e-17 :> 1.32593176e-17 :> 3.29422893e-03 :> 3.58089966e-03 :> 9.08965047e-18 :> -2.18539647e-03 :> -2.12919221e-17 :> 2.39194534e-03 :> -8.31327663e-17 :> -4.69672484e-03 :> -4.73138591e-03 :> 5.79766610e-17 :> -5.28939995e-18 :> -1.10712423e-02 :> -2.40989091e-02 :> -2.18047819e-02 :> -6.11496326e-17 :> 2.39909500e-02 :> 2.91782046e-02 :> 1.47558239e-02 :> 3.11706634e-17 :> 1.33673427e-18 :> 8.44218666e-03 :> 9.25308362e-03 :> -9.62845645e-17 :> -5.76785543e-03 :> -2.84709264e-17 :> 6.49485159e-03 :> -4.19102125e-17 :> -1.32387105e-02 :> -1.36437840e-02 :> 1.16146829e-16 :> -4.98075231e-17 :> -3.49290893e-02 :> -7.90710907e-02 :> -7.48583001e-02 :> -3.01478553e-33 :> 9.23333495e-02 :> 1.20794568e-01 :> 6.66720749e-02 :> -9.64385396e-17 :> 4.65544367e-17 :> 5.76578486e-02 :> 7.99902785e-02 :> -8.32650050e-17 :> -1.34035769e-01 :> 8.00710266e-01 :> -1.34035769e-01 :> -8.32650050e-17 :> 7.99902785e-02 :> 5.76578486e-02 :> 4.65544367e-17 :> -9.64385396e-17 :> 6.66720749e-02 :> 1.20794568e-01 :> 9.23333495e-02 :> -3.01478553e-33 :> -7.48583001e-02 :> -7.90710907e-02 :> -3.49290893e-02 :> -4.98075231e-17 :> 1.16146829e-16 :> -1.36437840e-02 :> -1.32387105e-02 :> -4.19102125e-17 :> 6.49485159e-03 :> -2.84709264e-17 :> -5.76785543e-03 :> -9.62845645e-17 :> 9.25308362e-03 :> 8.44218666e-03 :> 1.33673427e-18 :> 3.11706634e-17 :> 1.47558239e-02 :> 2.91782046e-02 :> 2.39909500e-02 :> -6.11496326e-17 :> -2.18047819e-02 :> -2.40989091e-02 :> -1.10712423e-02 :> -5.28939995e-18 :> 5.79766610e-17 :> -4.73138591e-03 :> -4.69672484e-03 :> -8.31327663e-17 :> 2.39194534e-03 :> -2.12919221e-17 :> -2.18539647e-03 :> 9.08965047e-18 :> 3.58089966e-03 :> 3.29422893e-03 :> 1.32593176e-17 :> -6.95248052e-17 :> 5.85688426e-03 :> 1.16209519e-02 :> 9.57794343e-03 :> 3.66725201e-17 :> -8.72271164e-03 :> -9.63775624e-03 :> -4.42290170e-03 :> -5.19238250e-17 :> 2.24314248e-18 :> -1.87576073e-03 :> -1.85473668e-03 :> 2.64177628e-17 :> 9.35427798e-04 :> -4.24392593e-17 :> -8.44354542e-04 :> -2.92823518e-17 :> 1.36380726e-03 :> 1.24466846e-03 :> 2.70383448e-17 :> 0.00000000e+00 :> 2.15427395e-03 :> 4.23241069e-03 :> 3.45259832e-03 :> -1.30788363e-17 :> -3.07661933e-03 :> -3.36082345e-03 :> -1.52438502e-03 :> -7.03525331e-18 :> 1.63484509e-17 :> -6.23370976e-04 :> -6.08801988e-04 :> -2.73859684e-18 :> 2.99576343e-04 :> -5.23918059e-18 :> -2.64065618e-04 :> -1.21745475e-17 :> 4.17356596e-04 :> 3.77239653e-04 :> 2.62712857e-18 :> -8.00554425e-18 :> 6.39186084e-04 :> 1.25131737e-03 :> 1.01950810e-03 :> 3.86774364e-18 :> -9.14037108e-04 :> -1.00665733e-03 :> -4.62180925e-04 :> 2.90791068e-18 :> 1.96946883e-18 :> -2.01638331e-04 :> -2.03379801e-04 :> -6.04051550e-18 :> 1.08643703e-04 :> -6.86056317e-19 :> Nil\n\n-- iir coeficients\niirCoefA :: Fractional a => Vec 8 a\niirCoefB :: Fractional a => Vec 9 a\niirCoefA = -1.8933239813032006 :> 3.422153467072297 :> -3.907588921469733 :> 3.6401868030176012 :> -2.5428541496659465 :> 1.3470500696022936 :> -0.49424202583584054 :> 0.10443313376764539 :> Nil\niirCoefB = 0.0025798085212212327 :> 0.02063846816976986 :> 0.07223463859419452 :> 0.14446927718838903 :> 0.18058659648548628 :> 0.14446927718838903 :> 0.07223463859419452 :> 0.02063846816976986 :> 0.0025798085212212327 :> Nil\n\n{-\nDrawing helpers\n-}\n\nsimFuncLin f skip ph =  snd $ getSpecLin <$> P.last $ P.take skip $ getResponseLin f ph\nsimFunc f skip ph =  (Map.! 1) $ getSpectrum <$> P.last $ P.take skip $ getResponse f ph\nsimFuncAcyclic f ph =  (Map.! 1) $ getSpectrum $ getResponseAcyclic f ph\n\n\ngenData f sk pn = (x,y) where\n    x = fmap (\\a -> (1.0 * pi * fromInteger a / fromInteger pn)) [0, 1 .. pn]\n    y = fmap (simFunc f sk) x \n\n-- how is mapping over result like Complex Double -> Double\n-- f is ciruit\n-- sk skip first sk values from result, for acyclic circuit this should be more than circuitry delay\n-- pn - number of linear points from 0 to 1 (nyquist freq)\nplt how f sk pn = plot' [] X11 $ Data2D [Style Lines,Title \"plot\"] [] (P.zip ((/pi) <$> x) (how <$> y))\n  where\n    (x,y) = genData f sk pn\n\n\ngenDataLin f sk pn = (x,y) where\n    x = fmap (\\a -> (1.0 * pi * fromInteger a / fromInteger pn)) [0, 1 .. pn]\n    y = fmap (simFuncLin f sk) x \n\npltLin how f sk pn = plot' [] X11 $ Data2D [Style Lines,Title \"plot\"] [] (P.zip ((/pi) <$> x) (how <$> y))\n  where\n    (x,y) = genDataLin f sk pn\n\n\ngenDataAcyclic f pn = (x,y) where\n    x = fmap (\\a -> (1.0 * pi * fromInteger a / fromInteger pn)) [0, 1 .. pn]\n    y = fmap (simFuncAcyclic f) x \n\n\npltDataAcyclic how f pn = plot' [] X11 $ Data2D [Style Lines,Title \"plot\"] [] (P.zip ((/pi) <$> x) (how <$> y))\n  where\n    (x,y) = genDataAcyclic f pn\n\n\n\n\nmagLog x = logBase 10 (magnitude x) * 20\nmagLogMin m x = max m (magLog x)\n\nintegrator i = r where\n    r = (registerP 0 r) + i\n\n{-\nExamples\n-}\n\n-- plots working with linear circuits\nplotFirLin = pltLin magnitude f 210 100 where\n f = firP firCoef\n\n\n-- slower and generic version of samplePlotLin\nplotFir = plt magnitude f 210 100 where\n f = firP firCoef\n\n\n-- plot acyclic ciruit\nplotFirAcyclic = pltDataAcyclic magnitude f 1000 where\n f = firP firCoef\n\nplotIir = plt magnitude (iirP iirCoefA iirCoefB) 200 100\nplotIirLog = pltLin magLog (iirP iirCoefA iirCoefB) 200 100\n\n\nplotInteg = plt magnitude integrator 100 100\n\nmain = plotIir\n", "meta": {"hexsha": "df715bbe1822b03000e4c518564fefbd7a9f2536", "size": 6885, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/test.hs", "max_stars_repo_name": "ra1u/frequency-response", "max_stars_repo_head_hexsha": "d044223c2e1e90bb40e4245d0edcac5fb16534f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test.hs", "max_issues_repo_name": "ra1u/frequency-response", "max_issues_repo_head_hexsha": "d044223c2e1e90bb40e4245d0edcac5fb16534f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test.hs", "max_forks_repo_name": "ra1u/frequency-response", "max_forks_repo_head_hexsha": "d044223c2e1e90bb40e4245d0edcac5fb16534f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 59.8695652174, "max_line_length": 3737, "alphanum_fraction": 0.660130719, "num_tokens": 3345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.4024585287936781}}
{"text": "-- | Main module for loading all parts of Hoqus package and dependencies from\n-- 'hmatrix' package.\nmodule Hoqus where\n\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra\n\nimport Hoqus.Dirac\nimport Hoqus.Gates\nimport Hoqus.MtxFun\nimport Hoqus.Fidelity\n", "meta": {"hexsha": "0a9cac2f6ad7e3183747aba3ae1d0b357173abb1", "size": 264, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Hoqus.hs", "max_stars_repo_name": "jmiszczak/hoqus", "max_stars_repo_head_hexsha": "b350004f0f2c0299b8b78e5a8838639ef5006300", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-08-31T15:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-11T01:48:13.000Z", "max_issues_repo_path": "Hoqus.hs", "max_issues_repo_name": "jmiszczak/hoqus", "max_issues_repo_head_hexsha": "b350004f0f2c0299b8b78e5a8838639ef5006300", "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": "Hoqus.hs", "max_forks_repo_name": "jmiszczak/hoqus", "max_forks_repo_head_hexsha": "b350004f0f2c0299b8b78e5a8838639ef5006300", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-01-31T11:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-31T11:52:53.000Z", "avg_line_length": 22.0, "max_line_length": 77, "alphanum_fraction": 0.8143939394, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40219346238823794}}
{"text": "module Main where\n\nimport           Control.Lens\nimport           Data.H3.Colour                 (ordinalColours, toCSSColour)\nimport           Data.H3.Extent                 (Extent, extent, fromTuple,\n                                                 resize, toTuple)\nimport           Data.H3.Scalable               (Scalable (..))\nimport           Data.H3.Scales                 (IncludeZeroPolicy (..),\n                                                 Product (..), continuous)\nimport           Data.H3.Svg                    (ViewBoxMode (..), renderSvg)\nimport           Data.H3.Visuals                (ChartVisuals (..),\n                                                 FontSize (..),\n                                                 LabelOffset (..), Pixel (..),\n                                                 Shape (..), Vis (..),\n                                                 backgroundShapes, cartesian,\n                                                 foregroundShapes, mapColour,\n                                                 noGrid)\nimport           Data.List.NonEmpty             (NonEmpty (..))\nimport           Data.Semigroup.Foldable        (Foldable1 (..))\nimport qualified Data.Text                      as Text\nimport qualified Data.Text.Lazy.IO              as TextIO\nimport qualified Graphics.Svg                   as SVG\nimport           Statistics.Distribution        (ContDistr (density),\n                                                 Mean (mean), Variance (stdDev))\nimport qualified Statistics.Distribution.Normal as Distribution.Normal\n\nnewtype PlotData = PlotData { getPlots :: [(Double, Double)] }\n\n_PlotData :: Iso' PlotData [(Double, Double)]\n_PlotData = iso getPlots PlotData\n\nmain :: IO ()\nmain = do\n  let\n    plts  = [\n      PlotData $ sample 1.0 0.25,\n      PlotData $ sample 2.0 0.44]\n    dims = (fromTuple (0, 900), fromTuple (500, 0))\n    r    = renderSvg (AddViewBox 1.25) (mapColour Text.pack . plotShape plts) dims\n  TextIO.writeFile \"out.svg\" $ SVG.prettyText r\n\n-- | Sample from a normal distribution\nsample :: Double -> Double -> [(Double, Double)]\nsample theMean theStdDev = vls where\n  d = Distribution.Normal.normalDistr theMean theStdDev\n  (f, mn, mx) = let m = mean d\n                    std = stdDev d in\n                    (density d, m - 3 * std, m + 3 * std)\n  samples = fmap (\\i -> mn + i * delta) [0 .. n] where\n    delta = (mx - mn) / n\n    n = 100\n  vls = fmap (over _2 f) (zip samples samples)\n\nplotShape :: [PlotData] -> (Extent Double, Extent Double) -> Shape String (Pixel Double, Pixel Double)\nplotShape ps tgt = result where\n  allPoints = foldMap getPlots ps\n  result = case allPoints of\n    [] -> EmptyShape\n    (x:xs) -> over both Pixel <$> AGroup [backgroundShapes s, plotLines, foregroundShapes s] where\n      (xExtent, yExtent) = foldMap1 (over both extent) (x :| xs)\n      xOpts = continuous xExtent DontIncludeZero\n      yOpts = continuous yExtent DontIncludeZero\n      tickLength = 5\n      ((_, _), (yLw, _)) = over both toTuple tgt\n      xyOpts = cartesian\n        (fromTuple (yLw, yLw + tickLength))\n        (fromTuple (negate tickLength, 0))\n        (FontSize \"10pt\")\n        (LabelOffset (-20, 15))\n        xOpts\n        yOpts\n      s = visuals (Vis xyOpts) tgt\n      colors = toCSSColour . runIdentity <$> scale (ordinalColours [1 .. length xs]) ()\n      plotLines =\n        fmap (over both runIdentity . getProduct . combinedScale)\n        $ AGroup\n        $ mkPlot <$> zip ps [1..]\n      mkPlot (PlotData pts, col) = AColouredShape (colors col) $ ALine pts\n      combinedScale = scale xyOpts tgt\n", "meta": {"hexsha": "4593bb8f4d179c12bebd65c87cc21e6688c9c3cd", "size": 3586, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/plot/Main.hs", "max_stars_repo_name": "j-mueller/h3", "max_stars_repo_head_hexsha": "fe0b4936032b8c1c9080e29d10426a93fc1d4739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T10:58:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T10:58:52.000Z", "max_issues_repo_path": "examples/plot/Main.hs", "max_issues_repo_name": "j-mueller/h3", "max_issues_repo_head_hexsha": "fe0b4936032b8c1c9080e29d10426a93fc1d4739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/plot/Main.hs", "max_forks_repo_name": "j-mueller/h3", "max_forks_repo_head_hexsha": "fe0b4936032b8c1c9080e29d10426a93fc1d4739", "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": 44.825, "max_line_length": 102, "alphanum_fraction": 0.5270496375, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.40215640362952676}}
{"text": "-----------------------------------------------------------------------------\n-- |\n-- Module      :  FlashADC\n-- Copyright   :  Jos\u00e9 Edil Guimar\u00e3es de Medeiros\n-- License     :  BSD-style (see the file LICENSE)\n-- \n-- Maintainer  :  j.edil@ene.unb.br\n-- Stability   :  experimental\n-- Portability :  portable\n--\n-- This module shows the model of a flash architecture ADC.\n--\n-- =Running the demo\n-- \n-- To run the demo you need the ForSyDe installed in your\n-- environment. For plotting, you need the\n-- <http://gnuplot.sourceforge.net Gnuplot package>.\n--\n-- To calculate 10000 samples for R=1e3 Omhs, C=1e-6 F, T=1e-6run in @ghci@:\n--\n-- >>> simulate 4\n-- \n-- To plot the response for a sine wave input, run in @ghci@:\n--\n-- >>> plotOutput 4 0.01 1000\n-----------------------------------------------------------------------------\n\nmodule ForSyDe.Shallow.Example.Synchronous.FlashADC where\n\nimport ForSyDe.Shallow\nimport Data.Complex\n\ntype Resistance = Double\ntype Voltage = Double\ntype Code = Integer\ntype Bits = Integer\ntype Time = Double\ntype Frequency = Double\n\n-- | 'flashADC' is the top level module.\nflashADC :: [Resistance]                -- ^ Resistance values\n          -> Signal Voltage             -- ^ Input signal\n          -> Signal Code                -- ^ Output signal\nflashADC resistors input = decoder $ compNetwork input $ resNetwork resistors\n\n-- | 'decoder' takes the thermometer code and outputs integers.\ndecoder :: [Signal Bits]                -- ^ Bit inputs\n        -> Signal Code                  -- ^ Output signal\ndecoder = foldl1 (zipWithSY (+))\n\n-- | 'compNetwork' implements the comparator array.\ncompNetwork :: Signal Voltage           -- ^ ADC input signal\n            -> [Voltage]                -- ^ Voltage thresholds\n            -> [Signal Bits]            -- ^ Bit outputs\ncompNetwork input = zipWith (\\i v -> mapSY (comparator v) i) (repeat input)\n\n-- | 'comparator' is the one bit quantizer.\ncomparator :: Voltage                   -- ^ (+) input\n           -> Voltage                   -- ^ (-) input\n           -> Bits                      -- ^ Output\ncomparator i v\n  | v <= i = 0\n  | otherwise = 1\n\n-- | 'resNetwork' implements the resistor voltage scaling network.\nresNetwork :: [Resistance]              -- ^ Resistor values\n           -> [Voltage]                 -- ^ Threshold voltages\nresNetwork resistors = init $ tail $ scanl (\\v r -> v + vdd * r / (sumR)) 0 resistors\n  where vdd = 1\n        sumR = sum resistors\n\n-- | 'simulate' takes the system parameters and runs the simulation\n-- with a sine wave input.\nsimulate :: Int                         -- ^ ADC resolution\n         -> Int                         -- ^ Number of samples\n         -> Signal Code                 -- ^ ADC output\nsimulate res n = flashADC resistors input\n  where resistors = replicate (2^res) 1\n        input = sineWave' 0.5 0.5 50 n\n\n-- | 'plotFFT' runs the simulation with a sine wave input\nplotFFT :: Int                  -- ^ ADC resolution\n        -> Int                  -- ^ FFT depth (power of 2)\n        -> IO String            -- ^ plot\nplotFFT res n = plotCT' (toRational 1.0) [(g_out, \"g\")]\n  where g_out = d2aConverter DAhold (toRational 1.0) $ signal g\n        a = fromSignal $ simulate res n\n        b = (:+) <$> (map ((\\x -> x/2^res - 0.5).fromIntegral) a)\n        c = zipWith ($) b $ repeat 0.0\n        d = vector c\n        e = fromVector $ fft n d\n        f = map ((*20).(logBase 10).(\\x -> 2*x/(fromIntegral n)) . magnitude) e\n        g = (take (n `div` 2) f)\n\n-- | 'plotOutput' uses the CTLib plot capabilities to plot the\n-- output. In a later version, a plotter to Synchornous signals will be\n-- developed.\nplotOutput :: Int                       -- ^ Resolution\n           -> Double                    -- ^ Discretization timestep\n           -> Int                       -- ^ Number of samples\n           -> IO String                 -- ^ plot\nplotOutput res t n = plotCT' (toRational t) [(output, \"output\")]\n  where output = d2aConverter DAhold (toRational t) adcSignal\n        adcSignal = signal $ map (toRational) $ fromSignal $ \n                    simulate res n\n\n-- | 'sineWave' is an auxiliary function that creates a sine wave signal for\n-- simulation purposes.\nsineWave' :: Voltage                     -- ^ Amplitude\n          -> Voltage                     -- ^ Offset\n          -> Frequency                   -- ^ Frequency\n          -> Int                         -- ^ Number of samples\n          -> Signal Time                 -- ^ Output signal\nsineWave' amp offset freq n = signal sineW\n  where sineW = map (\\t -> (amp/2) * sin(2*pi*freq*t) + offset) grid\n        grid = linspace 0 1 n\n\n-- | 'linspace' is an auxiliary function that creates an uniform\n-- spaced sampling grid for simulation purposes.\nlinspace :: Time                        -- ^ Start time\n         -> Time                        -- ^ Stop time\n         -> Int                         -- ^ Number of samples\n         -> [Time]                      -- ^ Sampling grid\nlinspace start stop n = map (scale) nodes\n  where n' = fromIntegral n\n        nodes = map (fromIntegral) [0..(n-1)]\n        scale t = t * length / (n' - 1) + start\n        length = stop - start \n\n", "meta": {"hexsha": "bb3ec768806794ccb10f49472e1dc458bb839eab", "size": 5200, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ForSyDe/Shallow/Example/Synchronous/FlashADC.hs", "max_stars_repo_name": "Rojods/forsyde-shallow-examples", "max_stars_repo_head_hexsha": "00ee967e9758d2a98cbd56482a911c741f43a1fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ForSyDe/Shallow/Example/Synchronous/FlashADC.hs", "max_issues_repo_name": "Rojods/forsyde-shallow-examples", "max_issues_repo_head_hexsha": "00ee967e9758d2a98cbd56482a911c741f43a1fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2017-01-18T14:25:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-24T12:27:00.000Z", "max_forks_repo_path": "src/ForSyDe/Shallow/Example/Synchronous/FlashADC.hs", "max_forks_repo_name": "Rojods/forsyde-shallow-examples", "max_forks_repo_head_hexsha": "00ee967e9758d2a98cbd56482a911c741f43a1fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-03-07T17:57:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T12:54:50.000Z", "avg_line_length": 40.0, "max_line_length": 85, "alphanum_fraction": 0.5323076923, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4019127070692996}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies     #-}\n-- |\n-- Module      : Main\n-- Description : Test runner\n-- Copyright   : (c) Tom Westerhout, 2017\n-- License     : BSD3\n-- Maintainer  : t.westerhout@student.ru.nl\n-- Stability   : experimental\n\nmodule Main where\n\n\nimport qualified System.Random.MWC as MWC\nimport           Control.Lens\nimport           Control.Monad.Reader\nimport           Control.Monad.State\nimport qualified Data.List            as L\nimport Data.Complex\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as LA\nimport Data.Vector.Storable((!))\n\nimport PSO.Random\nimport PSO.Energy\nimport PSO.Swarm\n\n\nclass TestFunction f where\n  function :: f -> V.Vector Float -> Float\n  initBounds :: f -> (Float, Float)\n  dim :: f -> Int\n\n\ndata RosenbrockFn = RosenbrockFn\n\ninstance TestFunction RosenbrockFn where\n  function _ x =\n    let p1 = (100.0 *) . V.sum . V.map (^^2)\n                $ V.zipWith (-) (V.tail x) (V.map (^^2) $ V.init x)\n        p2 = V.sum . V.map (^^2) . V.map (1.0 -) $ V.init x\n    in p1 + p2\n  initBounds _ = (15.0, 30.0)\n  dim _ = 30\n\nunpack :: (Float, Float) -> Int -> (V.Vector Float, V.Vector Float)\nunpack (x, y) d = (f x, f y)\n  where f = V.fromList . replicate d\n\nwpg :: (Float, Float, Float)\nwpg = (0.7298 :: Float, 1.49618, 1.49618)\n\ncmUpdater :: (Num \u03c7, RandomScalable m \u03c7, VectorSpace \u03c7 Float)\n        => PhaseUpdater m (SwarmGuide \u03c7 r) (BeeGuide \u03c7 r) (CMState \u03c7) r\ncmUpdater = standardUpdater wpg\n\nqmUpdater :: (RandomScalable m \u03c7, Randomisable m Float, \u03c7 ~ V.Vector Float)\n        => PhaseUpdater m (SwarmGuide \u03c7 r) (BeeGuide \u03c7 r) (QMState \u03c7) r\nqmUpdater = (PhaseUpdater $ deltaWellUpdater (2 * log 2 * 0.7 :: Float))\n\ncmRunND :: IO ()\ncmRunND = do\n  let xs = optimiseND\n            (mkCMState (unpack (initBounds RosenbrockFn) (dim RosenbrockFn)))\n            cmUpdater\n            (function RosenbrockFn)\n            20\n            (\\s -> (s^.guide.val) < 1.0\n                   || (s^.guide.iteration == 10000))\n  gen <- mkMWCGen (Just 123)\n  swarms <- runReaderT xs gen\n  writeEnergies2TSV \"Function.dat\" (view val) swarms\n  let swarm = last swarms\n  -- mapM_ (print . (!!0) . (view bees)) $ swarms\n  putStrLn \"\"\n  putStrLn $ \"[+] Best[f] = \" ++ show (swarm ^. guide . val)\n\nqmRunND :: IO ()\nqmRunND = do\n  let xs = optimiseND\n            (mkQMState (unpack (initBounds RosenbrockFn) (dim RosenbrockFn)))\n            qmUpdater\n            (function RosenbrockFn)\n            20\n            (\\s -> (s^.guide.val) < 1.0\n                   || (s^.guide.iteration == 5000))\n  gen <- mkMWCGen (Just 123)\n  swarms <- runReaderT xs gen\n  writeEnergies2TSV \"Function.dat\" (view val) swarms\n  let swarm = last swarms\n  -- mapM_ (print . (!!0) . (view bees)) $ swarms\n  putStrLn \"\"\n  putStrLn $ \"[+] Best[f] = \" ++ show (swarm ^. guide . val)\n\nmain :: IO ()\nmain = qmRunND\n", "meta": {"hexsha": "88e3603c5383c68105a7a1ae99adff7e1484c7c3", "size": 2864, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "twesterhout/tcm-swarm", "max_stars_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "twesterhout/tcm-swarm", "max_issues_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "twesterhout/tcm-swarm", "max_forks_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5257731959, "max_line_length": 77, "alphanum_fraction": 0.6064944134, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4018134842966149}}
{"text": "import Codec.Picture\nimport Codec.Picture.Types\nimport Data.Word\nimport Data.Vector as V\nimport Data.Complex\n\nadjust :: Double -> Int -> Int -> Double\nadjust s xr x = (fromIntegral x - (fromIntegral xr)/2)*s\n\ncmpmake :: Double -> Int -> Int -> Int -> Int -> Complex Double\ncmpmake s xr yr x y = adjust s xr x :+ adjust s yr y\n\n\npolartolch :: (Double, Double) -> Double -> (Double, Double, Double)\npolartolch (mag, ph) high = (linearInter high 60 mag, 90, ph)\n\n\nlchtolab :: (Double, Double, Double) -> (Double, Double, Double)\nlchtolab (l, c, h) = (l, c * (cos h), c * (sin h))\n\nlabtoxyz :: (Double, Double, Double) -> (Double, Double, Double)\nlabtoxyz (l, a, b) = let  eps = 216/24389\n                          kap = 24389/27\n                          fy  = (l + 16)/116\n                          fz  = fy - (b/200)\n                          fx  = (a/500) + fy\n                          x   = if fx**3 > eps then fx**3 else (116*fx - 16)/kap\n                          y   = if l > kap*eps then ((l + 16)/116)**3 else l/kap\n                          z   = if fz**3 > eps then fz**3 else (116*fz - 16)/kap\n                            in (x, y, z)\n\n--https://www.mathworks.com/help/images/ref/lab2xyz.html\n\na =   (1.0985,  1,          0.3558)\nc =   (0.9807,  1,          1.1822)\ne =   (1,       1,          1)\nd50 = (0.9642,  1.0,        0.8251)\nd55 = (0.9568,  1.0,        0.9214)\nd65 = (0.95047, 1.00,       1.08883)\nicc = (0.9642,  1,          0.8249)\n\ndata RGBgamut = RGBgamut {row1 :: (Double, Double, Double),\n                          row2 :: (Double, Double, Double),\n                          row3 :: (Double, Double, Double),\n                          white :: (Double, Double, Double),\n                          gamma :: Double}\n\nsRGBgamut = RGBgamut (3.2404542, -1.5371385, -0.4985314)\n                      (-0.9692660, 1.8760108, 0.0415560)\n                      (0.0556434, -0.2040259, 1.0572252)\n                      d65\n                      2.4\nadobeRGBgamut = RGBgamut (2.0413690, -0.5649464, -0.3446944)\n                          (-0.9692660, 1.8760108, 0.0415560)\n                          (0.0134474, -0.1183897, 1.0154096)\n                          d65\n                          (563/256)\n\nadobeWideRGBgamut = RGBgamut (1.4628067, -0.1840623, -0.2743606)\n                              (-0.5217933, 1.4472381, 0.0677227)\n                              (0.0349342, -0.0968930, 1.2884099)\n                              d50\n                              (563/256)\n\nproPhotoRGBgamut = RGBgamut (1.3459433, -0.2556075, -0.0511118)\n                              (-0.5445989, 1.5081673, 0.0205351)\n                              (0,       0,            1.2118128)\n                              d50\n                              1.8\n\npointwise :: (Double, Double, Double) -> (Double, Double, Double) -> (Double, Double, Double)\npointwise (a, b, c) (x, y, z) = (a*x, b*y, c*z)\n\nmatrixMult :: (Double, Double, Double) -> (Double, Double, Double) -> (Double, Double, Double) -> (Double, Double, Double) -> (Double, Double, Double)\nmatrixMult (a, b, c) (d, e, f) (g, h, i) (x, y, z) = (a*x + b*y + c*z, d*z + e*y + f*z, g*x + h*y + i*z)\n\nxyztorgb :: RGBgamut -> (Double, Double, Double) -> (Double, Double, Double)\nxyztorgb gam (x, y, z) =  let (xl, yl, zl)  = matrixMult (row1 gam) (row2 gam) (row3 gam) $ pointwise (x, y, z) (white gam)\n                              compand c     = c**(1/(gamma gam))\n                                in (compand xl, compand yl, compand zl)\n\n\nlinearInter :: Double -> Double -> Double -> Double\nlinearInter highin highout x = highout/highin * x\n\nexpInter :: Double -> Double -> Double -> Double\nexpInter low high x = 1 - base ** (x) where\n  base = 0.5\n\nmakeSampleSpace :: Int -> Int -> Double -> Vector (Vector (Double, Double))\nmakeSampleSpace w h s = generate (2*h + 1) (\\y -> generate (2*w + 1) (\\x -> (s*(fromIntegral x - fromIntegral w), -s*(fromIntegral y - fromIntegral h))))\n\ninmap :: (a -> b) -> Vector (Vector a) -> Vector (Vector b)\ninmap f l = V.map (V.map f) l\n\nfindextrema :: Vector (Vector (Double, Double)) -> Double\nfindextrema lst =\n  let lst' = V.concat $ toList lst\n      lst'' = V.map (\\(x, y) -> x) lst'\n          in V.maximum lst''\n\nhighest :: Vector Double -> Double\nhighest vec = if V.length vec == 1 then V.head vec else\n            (if V.head vec > (highest $ slice 1 (V.length vec - 1) vec) then V.head vec else (highest $ slice 1 (V.length vec - 1) vec))\n\nurx = 1000\nury = 1000\niscale = 0.003\n\nf :: Complex Double -> Complex Double\nf z =  cexp $ z\n\ncexp :: Complex Double -> Complex Double\ncexp (a :+ b) = (exp a :+ 0) * (cis b)\n\nnewimage :: Vector (Vector PixelRGB16)\nnewimage = let  sampling = makeSampleSpace urx ury iscale\n                polars = inmap (\\(x,y) -> polar $ f $ x :+ y) sampling\n                high = findextrema polars\n                lch = inmap (\\(x,y) -> polartolch (x,y) high) polars\n                lab = inmap lchtolab lch\n                xyz = inmap labtoxyz lab\n                rgb = inmap (xyztorgb proPhotoRGBgamut) xyz\n                rounded = inmap (\\(r, g, b) -> PixelRGB16 (round $ r*65530) (round $ g*65530) (round $ b*65530)) rgb\n                  in rounded\n\n\n\nmain :: IO ()\nmain = writePng \"./blah.png\" $ generateImage (\\x y -> newimage ! y ! x) (2*urx + 1) (2*ury + 1)\n", "meta": {"hexsha": "c8bdaf49a3ed583a904c20a438d53e1192cfd784", "size": 5280, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "2dvectvis.hs", "max_stars_repo_name": "mikeBraeu/vectvis", "max_stars_repo_head_hexsha": "05fe4fa62c8854d2fe494314186fe0e5c6fe7a5a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2dvectvis.hs", "max_issues_repo_name": "mikeBraeu/vectvis", "max_issues_repo_head_hexsha": "05fe4fa62c8854d2fe494314186fe0e5c6fe7a5a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2dvectvis.hs", "max_forks_repo_name": "mikeBraeu/vectvis", "max_forks_repo_head_hexsha": "05fe4fa62c8854d2fe494314186fe0e5c6fe7a5a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3053435115, "max_line_length": 153, "alphanum_fraction": 0.5047348485, "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.40137115347322505}}
{"text": "-- Fingerprint\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE StrictData #-}\n\nmodule Fingerprint (\n  Fingerprint\n, ColorVector\n, fp2colvec\n, makeMap\n, findSimilarImage\n, colvec2id\n, colvec2status\n, isValid\n) where\n\nimport qualified Data.KdTree.Static as KT\nimport           Data.List (transpose)\nimport           Data.List.Split (chunksOf)\nimport           Numeric (readHex)\nimport           Numeric.LinearAlgebra\n\ntype Fingerprint = String\ntype Channel = [Double]\n\ntype Color = [Double]  -- (r,g,b) => [r,g,b]\ndata ColorVector = ColorVector\n  { pixel  :: [Color]\n  , imgid  :: Int\n  , fp     :: Fingerprint\n  , status :: CvStatus\n  } deriving (Eq, Show)\ntype ColorVectorMap = KT.KdTree Double ColorVector\n\ndata CvStatus = FILED | PEND | DISCARDED | DUPLICATED | INFERIOR deriving (Eq, Show)\n\n-- constants\n--   status\n\n\n-- public functions\n\nmakeMap :: [ColorVector] -> ColorVectorMap\nmakeMap cvs = KT.buildWithDist colvec2points colvecDistance cvs\n\n{-|\n  IN:\n    r1  : radius for KdTree search\n    r2  : difference for each pixel\n-}\n\nfindSimilarImage :: Double -> Double -> Double -> ColorVectorMap -> ColorVector -> [ColorVector]\nfindSimilarImage r1 r2 rt cvmap cv = ss2\n  where\n    ss1 = filter (\\s -> colvec2id cv < colvec2id s) $ KT.inRadius cvmap r1 cv\n    ss2 = filter (\\s -> isNearImage r2 rt (colvec2fp cv) (colvec2fp s)) ss1\n\n{-|\n\n>>> let fp1 = [1.0, 2.0, 1.0, 2.0]\n>>> let fp2 = [1.0, 2.0, 1.0, 2.0]\n>>> isNearImage 0.0 1.0 fp1 fp2\nTrue\n>>> let fp1 = [1.0, 2.0, 1.0, 2.0]\n>>> let fp2 = [1.1, 2.0, 1.0, 2.0]\n>>> let ds = map abs $ zipWith (-) fp1 fp2\n>>> length ds\n4\n>>> let ds' = filter (<= 0.0) $ ds\n>>> length ds'\n3\n>>> (fromIntegral (length ds') / fromIntegral (length ds))\n0.75\n>>> isNearImage 0.0 0.5 fp1 fp2\nTrue\n\n-}\n\nisNearImage :: Double -> Double -> [Double] -> [Double] -> Bool\nisNearImage rad rate fp1 fp2 = (fromIntegral (length ds') / fromIntegral (length ds) >= rate)\n  where\n    ds = map abs $ zipWith (-) fp1 fp2\n    ds' = filter (<= rad) ds\n\n{-|\n  IN:\n      oreso - original resolution of x (ex. 8)\n      vreso - ColorVector resolution of x (ex. 2)\n      imgid - ID of image\n      fp    - fingerprint of image (ex. 8 x 8 x 3ch)\n\n>>> let fp = \"000000010101020202030303010101020202030303040404020202030303040404050505030303040404050505060606\"\n>>> fp2colvec 4 2 1 fp \"filed\"\nColorVector {pixel = [[1.0,1.0,1.0],[3.0,3.0,3.0],[3.0,3.0,3.0],[5.0,5.0,5.0]], imgid = 1, fp = \"000000010101020202030303010101020202030303040404020202030303040404050505030303040404050505060606\", status = FILED}\n\n-}\n\nfp2colvec :: Int -> Int -> Int -> Fingerprint -> String -> ColorVector\nfp2colvec oreso vreso imgid fp st = ColorVector pixel imgid fp st'\n  where\n    chs = map (matrix oreso) (fp2channels fp)\n    d = oreso `div` vreso\n    pixel = transpose $ map (summary d vreso) chs\n    st' = case st of\n      \"filed\"      -> FILED\n      \"pending\"    -> PEND\n      \"deleted\"    -> DISCARDED\n      \"duplicated\" -> DUPLICATED\n      \"inferior\"   -> INFERIOR\n      _            -> DISCARDED\n\ncolvec2id :: ColorVector -> Int\ncolvec2id (ColorVector _ i _ _) = i\n\ncolvec2fp :: ColorVector -> [Double]\ncolvec2fp (ColorVector _ _ fp _) = fp2double fp\n\ncolvec2status :: ColorVector -> CvStatus\ncolvec2status (ColorVector _ _ _ st) = st\n\nisValid :: ColorVector -> Bool\nisValid (ColorVector _ _ _ st) = (st == FILED || st == PEND)\n\n-- internal functions\n\n{-|\n\n>>> let cv1 = ColorVector [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0]] 1 \"001122334455\" FILED\n>>> colvec2points cv1\n[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0]\n\n-}\n\ncolvec2points :: ColorVector -> [Double]\ncolvec2points (ColorVector points _ _ _) = concat points\n\n{-|\n\n>>> let cv1 = ColorVector [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0, 11.0, 12.0]] 1 \"001122334455\" FILED\n>>> let cv2 = ColorVector [[1.0, 1.0, 4.0], [3.0, 6.5, 6.0], [8.2, 8.0, 7.8], [10.0, 12.0, 11.0]] 2 \"101122334455\" FILED\n>>> colvecDistance cv1 cv2\n2.5\n\n-}\n\ncolvecDistance :: ColorVector -> ColorVector -> Double\ncolvecDistance cv1 cv2 = maximum ls\n  where\n    p1s = colvec2points cv1\n    p2s = colvec2points cv2\n    ls = map sum $ chunksOf 3 $ zipWith (\\x y -> abs (x - y)) p1s p2s\n\n{-|\n\n>>> let m = matrix 4 [0,1,2,3,1,2,3,4,2,3,4,5,3,4,5,6]\n>>> summary 2 2 m\n[1.0,3.0,3.0,5.0]\n>>> let m2 = matrix 4 [6,5,4,3,5,4,3,2,4,3,2,1,3,2,1,0]\n>>> summary 2 2 m2\n[5.0,3.0,3.0,1.0]\n\n-}\n\nsummary :: Int -> Int -> Matrix R -> [Double]\nsummary d vreso m = map (\\x -> x / fromIntegral (d*d)) col\n  where\n    ele = map (*d) [0..(vreso-1)]\n    offset = [(x, y)| x <- ele, y <- ele]\n    col = map (\\o -> sum.toList.flatten $ subMatrix o (d, d) m) offset\n\n{-|\n\n>>> fp2channels \"000102030405060708090a0b\"\n[[0.0,3.0,6.0,9.0],[1.0,4.0,7.0,10.0],[2.0,5.0,8.0,11.0]]\n\n-}\n\nfp2channels :: Fingerprint -> [Channel]\nfp2channels fp = splitRgb ds ([], [], [])\n  where\n    ds = fp2double fp\n    splitRgb :: [Double] -> (Channel, Channel, Channel) -> [Channel]\n    splitRgb [] (r, g, b) = [reverse r, reverse g, reverse b]\n    splitRgb (r:g:b:xs) (rs, gs, bs) = splitRgb xs ((r:rs), (g:gs), (b:bs))\n\n{-|\n\n>>> fp2double \"000102030405060708090a0b0c0d0e0f\"\n[0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0]\n>>> fp2double \"00102030405060708090a0b0c0d0e0f0\"\n[0.0,16.0,32.0,48.0,64.0,80.0,96.0,112.0,128.0,144.0,160.0,176.0,192.0,208.0,224.0,240.0]\n\n-}\n\nfp2double :: Fingerprint -> [Double]\nfp2double fp = map hex2double $ chunksOf 2 fp\n\nhex2double :: String -> Double\nhex2double hex = fromIntegral h\n  where\n    [(h, _)] = (readHex hex)\n      \n\n\n\n", "meta": {"hexsha": "a4d1143498aa0aef70f17ba43bf85303770d3c10", "size": 5529, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fingerprint.hs", "max_stars_repo_name": "eiji-a/epconv", "max_stars_repo_head_hexsha": "16bc0dcf7ee787d33bad6c5bb54917ad980334da", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Fingerprint.hs", "max_issues_repo_name": "eiji-a/epconv", "max_issues_repo_head_hexsha": "16bc0dcf7ee787d33bad6c5bb54917ad980334da", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fingerprint.hs", "max_forks_repo_name": "eiji-a/epconv", "max_forks_repo_head_hexsha": "16bc0dcf7ee787d33bad6c5bb54917ad980334da", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8398058252, "max_line_length": 211, "alphanum_fraction": 0.6207270754, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.40121064735034023}}
{"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE BangPatterns #-}\nmodule AI.Singularity.Training where\nimport GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Data as LD\nimport qualified Numeric.LinearAlgebra.Devel as LDev\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Control.Monad.State as S\nimport Control.Lens\nimport Data.Proxy\nimport Control.Monad.ST\nimport System.Random\nimport Control.Monad\nimport Control.Arrow\nimport qualified Data.Vector.Storable as VS\nimport Data.Conduit\nimport System.IO (hPrint, stderr)\nimport qualified Data.Conduit.Binary as CB\nimport qualified Data.Conduit.List   as CL\nimport Data.Conduit.Internal (zipSources)\nimport Numeric.AD\nimport Control.Monad.Trans.Class (lift)\n\nimport AI.Singularity.Utils\nimport AI.Singularity.Data.Matrix\nimport AI.Singularity.Data.Vector\nimport AI.Singularity.Data.Network\n\ndata TrainConfig = TrainConfig { _learningRate :: !Float,\n                                 _lrUpdate     :: Float -> Float,\n                                 _batchsize    :: !Int,\n                                 _momentumRate :: !Float }\nmakeLenses ''TrainConfig\n\nnewtype Loss = Loss { getLoss :: forall a. Floating a => a -> a -> a}\n\nlossGrad :: Loss -> (forall a. Floating a => a -> a -> a)\nlossGrad (Loss f) = f'\n  where fList :: forall a. Floating a => [a] -> a\n        fList [y,y'] = f y y'\n        f' y y'      = head . tail . grad fList $ [y,y']\n\ndata TrainState i o = TrainState { _config  :: !TrainConfig,\n                                   _network :: !(TrainedNetwork i o),\n                                   _iter    :: !Int,\n                                   _loss    :: Loss,\n                                   _epochs  :: !Int,\n                                   _evalSet :: [(i,o)]}\n\nmakeLenses ''TrainState\n\n\naddGrad :: (KnownNat m, KnownNat n) => TrainConfig -> InTrainMat m n -> Identity (InTrainMat m n)\naddGrad tr mp = Identity $ GeneralInTrainingMat newWeights newGradient hGr\n  where momentumRatio = view momentumRate tr\n        lr            = view learningRate tr\n        newWeights    = checkNan $ view trMatr mp + (mmap (*lr) $ view trGrad mp) / mmap sqrt (hGr + 0.00000001)\n        newGradient   = checkNan . over matr (LD.cmap (*momentumRatio)) $ view trGrad mp\n        hGr           = 0.9 * view hGrad mp + 0.1 * (view trGrad mp ^ 2)\n\n\napplyGrad :: TrainConfig -> TrainedNetwork inp out -> TrainedNetwork inp out\napplyGrad tr = runIdentity . changeMatType (addGrad tr)\n\ncalcGrads :: forall n m. (KnownNat n, KnownNat m) => Vector n -> Vector m -> TrainedNetwork (Vector n) (Vector m) -> (Matrix (n+1) m, Vector n)\ncalcGrads !inp !outGrad (FFLayer !mpair !f) = (gradMat, inpGrad)\n  where\n    m       = view trMatr mpair\n    gradMat = dy `outer` consV 1 inp\n    dy      = outGrad * diffM\n    diffM   = cmap (diff f) . (#>) m . consV 1 $ inp\n    inpGrad = tailV $ transposeM m #> dy\n\ntrainWithErr :: forall a b. TrainConfig -> a -> b -> TrainedNetwork a b -> (TrainedNetwork a b, a)\ntrainWithErr tc !inp !outGrad n@(FFLayer !mpair !f) = (FFLayer  m' f, inpGrad)\n  where lr = view learningRate tc\n        m' = over trGrad (subtract gradMat) mpair\n        (gradMat,inpGrad) = calcGrads inp outGrad n\ntrainWithErr tc !inp !outGrad (FFSeq !n1 !n2) = (FFSeq n1' n2', inpGrad)\n  where (n1', inpGrad)  = trainWithErr tc inp inpGrad' n1\n        inp'            = conductSignalInTrain inp n1\n        (n2', inpGrad') = trainWithErr tc inp' outGrad n2\ntrainWithErr tc !inp !outGrad (SplitNet n) = (SplitNet *** splitV) unSpl\n  where unSpl = trainWithErr tc (uncurry appendV inp) outGrad n\ntrainWithErr tc !inp !outGrad (FromBinFunc f) = (FromBinFunc f, grads)\n  where grads = (\\(x1,x2) -> ((!!0) &&& (!!1)). map (*outGrad) . fgrad $ [x1,x2]) inp\n        fwrap :: forall a. Fractional a => [a] -> a\n        fwrap [x1,x2] = f x1 x2\n        fgrad = grad fwrap\ntrainWithErr tc !inp !outGrad (Split n1 n2) = (Split n1' n2', inGr)\n  where (n1', inGr1) = trainWithErr tc inp (fst outGrad) n1\n        (n2', inGr2) = trainWithErr tc inp (snd outGrad) n2\n        inGr         = inGr1 + inGr2\ntrainWithErr tc !inp !outGrad (FromFunc f) = (FromFunc f, inGr)\n  where inGr = diff f inp * outGrad\ntrainWithErr tc !inp !outGrad (FFDiv !n1 !n2) = (FFDiv n1' n2', (inGr1, inGr2))\n  where (n1', inGr1) = trainWithErr tc (fst inp) (fst outGrad) n1\n        (n2', inGr2) = trainWithErr tc (snd inp) (snd outGrad) n2\ntrainWithErr tc !inp !outGrad (Recurse n)   = if null inp then (Recurse n, []) else (Recurse n', [fst inGrad])\n   where inputs      = scanl (\\acc sym -> (sym, conductSignalInTrain acc n)) (head inp,0) (tail inp)\n         (n',inGrad) = foldr (\\input (net, outG) -> trainWithErr tc input (snd outG) net) (n,(undefined, outGrad)) inputs\ntrainWithErr tc !inp !outGrad (First n)     = (First n', inGrad)\n  where (n', in1Grad) = trainWithErr tc (fst inp) outGrad n\n        inGrad        = (in1Grad, 0)\ntrainWithErr tc !inp !outGrad (Second n)     = (Second n', inGrad)\n  where (n', in1Grad) = trainWithErr tc (snd inp) outGrad n\n        inGrad        = (0, in1Grad)\n\ntrainSample :: forall a b. TrainConfig -> [(a,b)] -> (b -> b -> b) -> Int -> Network a b -> Network a b\ntrainSample tc !corpus gLoss !epochs = fromTrain . (trainHelp tc 1 . concat $ replicate epochs corpus) . toTrain\n  where\n    trainHelp :: TrainConfig -> Int -> [(a, b)] -> TrainedNetwork a b -> TrainedNetwork a b\n    trainHelp tc i ((!x,!y):corp) !net = next . fst $ trainWithErr tc x l net\n      where l    = gLoss y (conductSignalInTrain x net)\n            next = if i < b\n                   then trainHelp tc (i+1) corp\n                   else trainHelp nTc 1 corp . applyGrad tc\n            nTc  = tc -- over learningRate (view lrUpdate tc) tc\n            b    = view batchsize tc\n    trainHelp _ _ [] !net = net\n\n\neps :: forall n. Floating n => n\neps = 0.00000001\n\ndefaultConfig = TrainConfig 0.05 id 1 0\n\nendOfBatch :: TrainState i o -> Bool\nendOfBatch = view iter &&& view (config.batchsize) >>> uncurry (>=)\n\nstartState conf net = defaultState conf net logloss\n  where logloss y y' = negate $ y * log (y' + eps) + (1 - y) * log (1 - y' + eps)\n\ndefaultState :: TrainConfig -> Network i o -> (forall a. Floating a => a -> a -> a) -> Int -> [(i,o)] -> TrainState i o\ndefaultState conf net f ep = TrainState conf (toTrain net) 1 (Loss f) ep\n\n-- applyTrainingExample :: (Floating o, Show o) => TrainState i o -> (i,o) -> IO (TrainState i o)\napplyTrainingExample tr (i,o) = endBatch . over iter (+1) . over network (fst . trainWithErr trConf i outLoss) $ tr\n  where\n    outLoss  = lossGrad (view loss tr) o (conductSignalInTrain i (view network tr))\n    trConf   = view config tr\n    endBatch = if endOfBatch tr\n               then \\x -> do\n                           let up = view (config.lrUpdate) x\n                               nX = over (config.learningRate) up . set iter 1 . over network (applyGrad trConf) $ x\n                               s  = view evalSet tr\n                               ac = sum . map (uncurry. flip . getLoss . view loss $ tr) . map (first $ flip conductSignalInTrain (view network nX)) $ s\n                           unless (null s) . lift $ do\n                             hPrint stderr \"LOSS:\"\n                             hPrint stderr (ac/fromIntegral (length s))\n                           return nX\n               else return\n\ntrainC cond conf net ep = trainStateC cond . startState conf net ep\n\ntrainStateC cond trState =\n  if view epochs trState >= 1\n  then\n    runConduitRes (cond .| CL.foldM applyTrainingExample trState) >>= (over epochs (subtract 1) >>> trainStateC cond)\n  else\n    fromTrain . applyGrad (view config trState) . view network <$> runConduitRes (cond .| CL.foldM applyTrainingExample trState)\n\ntrainExample :: forall a b. Floating b => TrainConfig -> [(a, b)] -> Int -> Network a b -> Network a b\ntrainExample conf x = trainSample conf x logloss'\n  where\n    logloss [y, y'] = y * log (y' + eps) + (1 - y) * log (1 - y' + eps)\n    logloss' y y'   = head . tail . grad logloss $ [y, y']\n", "meta": {"hexsha": "59a717bf332ad814b380e5b81af73773b49cc73c", "size": 8357, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Singularity/Training.hs", "max_stars_repo_name": "Antystenes/Memetic-Predictor", "max_stars_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AI/Singularity/Training.hs", "max_issues_repo_name": "Antystenes/Memetic-Predictor", "max_issues_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AI/Singularity/Training.hs", "max_forks_repo_name": "Antystenes/Memetic-Predictor", "max_forks_repo_head_hexsha": "241ace2ec24be02a2ba405e05e0f20ad38860d6a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.687150838, "max_line_length": 152, "alphanum_fraction": 0.6142156276, "num_tokens": 2431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.40112685918649127}}
{"text": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Data.Model where\n\nimport Data.Map.Strict (Map)\nimport qualified Data.Map.Strict as M\n\nimport Statistics.Distribution\nimport Statistics.Distribution.Poisson\n\nimport Data.Aeson\nimport Data.String (IsString)\n\ntype Hist = [Double]\ntype PredHist = [PoissonDistribution]\ntype DataHist = [Int]\n\nnewtype ProcName = ProcName { unPN :: String } deriving (Eq, Ord, FromJSON, IsString)\nnewtype RegName = RegName { unRN :: String } deriving (Eq, Ord, FromJSON, IsString)\n\ninstance Show ProcName where\n    show = unPN\n\ninstance Show RegName where\n    show = unRN\n\n\nrebinH :: Num a => Int -> [a] -> [a]\nrebinH _ []            = []\nrebinH n h | n <= 1    = h\n           | otherwise = let (hs, hs') = splitAt n h\n                         in  sum hs : rebinH n hs'\n\nzipWithLen :: (a -> b -> c) -> [a] -> [b] -> [c]\nzipWithLen f (a:as) (b:bs) = f a b : zipWithLen f as bs\nzipWithLen _ [] []         = []\nzipWithLen _ _ _           = error \"zipping lists of different lengths\"\n\n\n-- the log likelihood of a prediction histogram given a data histogram\npredHistLLH :: DataHist -> PredHist -> Double\npredHistLLH dh ph = sum $ zipWithLen logProbability ph dh\n\n\n-- a process's normalization is consistent across regions\ntype Process = Map RegName Hist\n\n-- a collection of named processes\ntype Prediction = Map ProcName Process\n\ntype TotalPrediction = Map RegName PredHist\n\n-- data in several regions\ntype Dataset = Map RegName DataHist\n\nliftP :: (Double -> Double) -> PoissonDistribution -> PoissonDistribution\nliftP f = poisson . f . poissonLambda\n\nliftP2 :: (Double -> Double -> Double) -> PoissonDistribution -> PoissonDistribution -> PoissonDistribution\nliftP2 f p p' = poisson $ f (poissonLambda p) (poissonLambda p')\n\ntoPred :: Hist -> PredHist\ntoPred = fmap (poisson . cleanBin)\n\nscaleH :: Double -> Hist -> Hist\nscaleH n = fmap (*n)\n\naddH :: Hist -> Hist -> Hist\naddH = zipWithLen (+)\n\ncleanBin :: Double -> Double\ncleanBin x = if x <= 0 then 1e-100 else x\n\nmulH :: Hist -> Hist -> Hist\nmulH = zipWithLen (*)\n\ndivH :: Hist -> Hist -> Hist\ndivH = zipWithLen (/)\n\nsumH :: [Hist] -> Hist\nsumH = foldl1 addH\n\nsubH :: Hist -> Hist -> Hist\nsubH = zipWithLen (-)\n\n\n\n-- a ModelParam alters a model in some particular way and has a prior\n-- distribution\ndata ModelParam = ModelParam { mpName :: String\n                             , mpPrior :: Double -> Double\n                             , mpAlter :: Double -> Prediction -> Prediction\n                             }\n\n\n-- alter a particular process's histograms uniformly by some function\nalterProc :: (Hist -> Hist) -> ProcName -> Prediction -> Prediction\nalterProc f = M.adjust (fmap f)\n\n\n-- process normalization ModelParam\nprocNormParam :: ContDistr d => d -> Double -> ProcName -> ModelParam\nprocNormParam prior n name = ModelParam (show name ++ \"_norm\") (logDensity prior)\n                                $ (\\x -> alterProc (scaleH (1+n*x)) name)\n\n\nprocShapeParam :: Double -> Map RegName Hist -> Process -> Process\nprocShapeParam x s p = M.differenceWith f p s\n    where f p' s' = Just $ addH (scaleH x s') p'\n\nshapeParam :: ContDistr d => d -> String -> Map ProcName (Map RegName Hist) -> ModelParam\nshapeParam prior name hshapes = ModelParam name (logDensity prior) f\n    where f x p = M.differenceWith (g x) p hshapes\n          g x p' s' = Just $ procShapeParam x s' p'\n\n\ntotalPrediction :: Prediction -> TotalPrediction\ntotalPrediction = fmap toPred . M.foldr (M.unionWith addH) M.empty\n\n-- TODO!!!\nexpectedData :: Prediction -> Dataset\nexpectedData = fmap (fmap $ round . poissonLambda) . totalPrediction\n\n-- the poisson likelihood of a model given the input data\nmodelPoissonLLH :: Dataset -> Prediction -> Double\nmodelPoissonLLH ds m = M.foldr (+) 0 $ M.intersectionWith predHistLLH ds\n                                     $ totalPrediction m\n\n\nmodelLLH :: Dataset -> Prediction -> [ModelParam] -> [Double] -> Double\nmodelLLH ds hpred hparams params = priorLLH + poissLLH\n    where\n        priorLLH = sum $ zipWithLen mpPrior hparams params\n        hpred' = foldr ($) hpred (zipWithLen mpAlter hparams params)\n        poissLLH = modelPoissonLLH ds hpred'\n", "meta": {"hexsha": "9fb3d152f8f41b431d1a81c86fececbbb733f6cd", "size": 4312, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Model.hs", "max_stars_repo_name": "cspollard/HMCMC", "max_stars_repo_head_hexsha": "292c3a3e6f0a60a71612dc45ba83f6e269b06f5e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Model.hs", "max_issues_repo_name": "cspollard/HMCMC", "max_issues_repo_head_hexsha": "292c3a3e6f0a60a71612dc45ba83f6e269b06f5e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Model.hs", "max_forks_repo_name": "cspollard/HMCMC", "max_forks_repo_head_hexsha": "292c3a3e6f0a60a71612dc45ba83f6e269b06f5e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5815602837, "max_line_length": 107, "alphanum_fraction": 0.6614100186, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4009891488843569}}
{"text": "module Shader ( sampleBRDF, probability, reflectance\n              , sampleVec\n              , sampleCol\n              , sampleVal\n              ) where\n\nimport Types\nimport Numeric.Vector\nimport Numeric.Scalar (fromScalar, scalar)\nimport Control.Monad.State\nimport VecUtil (unpack3, unpack2)\nimport qualified SceneRandom as R\nimport VecUtil (vec3Of)\n\n-- UTIL STUFF\n\nfmod :: (RealFrac a) => a -> a -> a\nfmod n d = n - (fromIntegral $ truncate $ n / d) * d\n\n-- END UTIL STUFF\n\n-- BRDF STUFF\n\nsampleBRDF :: BRDF -> State SceneContext (Maybe Ray)\nsampleBRDF BRDFEmpty = return Nothing\nsampleBRDF (Emission _ _) = return Nothing\nsampleBRDF (Diffuse _) = do\n  ctx <- get\n  let normal = rh_getNormal $ ss_getHit ctx\n  let pos = (rh_getPos (ss_getHit ctx)) + (normal * (vec3Of 0.01))\n  dir <- R.randVecHemisphere normal\n  return $ Just $ Ray pos dir\n\nprobability :: BRDF -> Vec3d -> State SceneContext Double\nprobability BRDFEmpty _ = return 0\nprobability (Emission _ _) _ = return 0.15915494309\nprobability (Diffuse _) _ = return 0.15915494309 -- 1 / (2 * PI)\n\nreflectance :: BRDF -> State SceneContext Vec3d\nreflectance BRDFEmpty = return $ vec3 0 0 0\n\nreflectance (Emission col str) = do\n  col' <- sampleCol col\n  str' <- sampleVal str\n  return $ col' * (fromScalar (scalar str'))\n\nreflectance (Diffuse col) = do\n  col' <- sampleCol col\n  return $ col'\n\nreflectance (Glossy col roughness) = do\n  col' <- sampleCol col\n  return col'\n  \n-- END BRDF STUFF\n\n-- VECTOR STUFF\n\nsampleVec :: SVector -> State SceneContext Vec3d\n\nsampleVec UV = do\n  ss <- get\n  let (u, v) = unpack2 $ rh_getTexCoord $ ss_getHit ss\n  return $ vec3 u v 0\n\nsampleVec Position = do\n  ss <- get\n  return $ rh_getPos $ ss_getHit ss\n\nsampleVec Normal = do\n  ss <- get\n  return $ rh_getNormal $ ss_getHit ss\n\nsampleVec (VecConst x y z) = return $ vec3 x y z\n\nsampleVec (VecMath op l r) = do\n  l' <- sampleVec l\n  r' <- sampleVec r\n  case op of\n    VAdd -> return $ l' + r'\n    VSub -> return $ l' - r'\n    VMul -> return $ l' * r'\n    VDiv -> return $ l' / r'\n    VMod -> let (x,y,z) = unpack3 l'; (i,j,k) = unpack3 r' in return $ vec3 (fmod x i) (fmod y j) (fmod z k)\n    VAbs -> return $ abs l'\n    -- VDot -> return $ l' \u00b7 r'\n    -- VCross -> return $ l' \u00d7 r'\n\nsampleVec (CombineXYZ x y z) = do\n  x' <- sampleVal x\n  y' <- sampleVal y\n  z' <- sampleVal z\n  return $ vec3 x' y' z'\n\n-- END VECTOR STUFF\n\n-- COLOR STUFF\n\nsampleCol :: SColor -> State SceneContext Vec3d\n\nsampleCol ColVertex = do\n  ss <- get\n  return $ rh_getColor $ ss_getHit ss\n\nsampleCol (ColVector v) = sampleVec v\n\nsampleCol (ColConst r g b) = return $ vec3 r g b\n\nsampleCol (CombineRGB vr vg vb) = do\n  r <- sampleVal vr\n  g <- sampleVal vg\n  b <- sampleVal vb\n  return $ vec3 r g b\n\n-- END COLOR STUFF\n\n-- VALUE STUFF\nsampleVal :: SValue -> State SceneContext Double\n\nsampleVal (ValConst x) = return x\n\nsampleVal RayLength = do\n  ss <- get\n  return $ rh_getDistance $ ss_getHit ss\n\nsampleVal (ValMath op l r) = do\n  l' <- sampleVal l\n  r' <- sampleVal r\n  case op of\n    Add -> return $ l' + r'\n    Sub -> return $ l' - r'\n    Mul -> return $ l' * r'\n    Div -> return $ l' / r'\n    Abs -> return $ abs l'\n    Mod -> return $ fmod l' r'\n    LessThan -> return $ if l' < r' then 1 else 0\n    GreaterThan -> return $ if l' > r' then 1 else 0\n\nsampleVal (SeparateX v) = sampleVec v >>= (return . unpack3) >>= \\(x,_,_) -> return x\nsampleVal (SeparateY v) = sampleVec v >>= (return . unpack3) >>= \\(_,y,_) -> return y\nsampleVal (SeparateZ v) = sampleVec v >>= (return . unpack3) >>= \\(_,_,z) -> return z\n\nsampleVal (SeparateR v) = sampleCol v >>= (return . unpack3) >>= \\(r,_,_) -> return r\nsampleVal (SeparateG v) = sampleCol v >>= (return . unpack3) >>= \\(_,g,_) -> return g\nsampleVal (SeparateB v) = sampleCol v >>= (return . unpack3) >>= \\(_,_,b) -> return b\n\n-- END VALUE STUFF\n", "meta": {"hexsha": "648e7c1395237b104844c12d28c99f4641aa3829", "size": 3813, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Shader.hs", "max_stars_repo_name": "craigmc08/haskell-raytracer", "max_stars_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Shader.hs", "max_issues_repo_name": "craigmc08/haskell-raytracer", "max_issues_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Shader.hs", "max_forks_repo_name": "craigmc08/haskell-raytracer", "max_forks_repo_head_hexsha": "397c28ac007efda7192c45f1d5e0997d256d9085", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7635135135, "max_line_length": 108, "alphanum_fraction": 0.632048256, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.4008771630273545}}
{"text": "module Scene.Material.Diffuse where\n\nimport Numeric.LinearAlgebra\n\nimport Scene.Base\nimport Math.Color\nimport Math.Ray\nimport Scene.Monad\n\nimport Control.Applicative\nimport Control.Monad.Random\n\ndoWhileM :: Monad m => (a -> Bool) -> m a -> m a\ndoWhileM cond prog = prog >>= (\\x -> if cond x then return x else doWhileM cond prog)\n\ndiffuse :: (Color -> Color) -> Material\ndiffuse absorb (Ray p normal) (Ray q incidence) = do\n    s_unit <- doWhileM (\\s -> s <.> s < 1) $ vec3 <$> getRandomR (-1,1) <*> getRandomR (-1,1) <*> getRandomR (-1,1)\n    let s = scale (norm_2 normal) s_unit + normal\n    ahead <- trace (Ray p s)\n    return $! absorb ahead", "meta": {"hexsha": "a65c90ef061b761677f72d75e51c66102ea2278e", "size": 645, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Scene/Material/Diffuse.hs", "max_stars_repo_name": "danrocag/raytracer", "max_stars_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Scene/Material/Diffuse.hs", "max_issues_repo_name": "danrocag/raytracer", "max_issues_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Scene/Material/Diffuse.hs", "max_forks_repo_name": "danrocag/raytracer", "max_forks_repo_head_hexsha": "124e8fce80955e815962f649e50931a30348a6c7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7142857143, "max_line_length": 115, "alphanum_fraction": 0.6697674419, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8080671950640463, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.4008771492691472}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule NanoML.Learn where\n\nimport Control.Arrow (second)\nimport Control.Monad\nimport Data.Aeson\nimport qualified Data.ByteString.Lazy as LBS\nimport qualified Data.Csv as CSV\nimport Data.Function\nimport Data.List\nimport qualified Data.List as List\nimport Data.Maybe\nimport qualified Data.Set as Set\nimport qualified Data.Vector as V\nimport GHC.Generics\n-- import Grenade\nimport Numeric.LinearAlgebra hiding (rank)\nimport Text.Read\n\nimport NanoML.Classify\nimport NanoML.Monad\nimport NanoML.Types\n\nrankExprs :: Net -> [Feature] -> Prog -> [(Confidence, Constraint)]\nrankExprs net fs p = second getThing <$!> rank net samples\n  where\n  samples = [ s {getThing = c}\n            | s <- concatMap mkfsD tbad\n            , c <- maybeToList (List.find (\\c -> getThing s == fromJust (constraintSpan c)) cores)\n            ]\n\n  (tbad, cores, me) = case runEval stdOpts (typeProg p) of\n    Left e -> ([], [], Just e)\n    Right (tp, cs) -> (tp, Set.toList (mconcat cs), Nothing)\n\n  mkfsD (TDFun _ _ pes) = mconcat (map (mkTypeOut . snd) pes)\n  mkfsD (TDEvl _ e)     = mkTypeOut e\n  mkfsD _               = mempty\n\n  -- inSlice s = any (\\c -> getSpan s == fromJust (constraintSpan c)) cores\n\n  -- mkTypeOut :: TExpr -> [Sample ()]\n  mkTypeOut te = actfold f [] te\n    where\n    f p e acc = (:acc) $ MkSample\n                { getThing = infoSpan (texprInfo e)\n                , getSample = vector $ concatMap (\\(_,c) -> c p e) fs\n                }\n\nstdNet :: IO (Net, [Feature])\nstdNet = loadNet \"models/op+context+type-hidden-500.json\" >>= \\case\n  Nothing -> fail \"could not decode 'models/op+context+type-hidden-500.json'\"\n  Just net -> return (net, preds_tis ++ map only_ctx preds_tis_ctx ++ preds_tcon_ctx)\n\ndata Prediction = Change | NoChange\n  deriving (Eq, Show)\n\n-- predict :: Net -> Sample -> Prediction\n-- predict = undefined\n\ntype Confidence = Double\n\nrank :: Net -> [Sample a] -> [(Confidence, Sample a)]\nrank net samples =\n  sortBy (flip compare `on` fst)\n    [ (r ! 1, s)\n    | s <- samples\n    , let r = runNet net (getSample s)\n    ]\n\ndata Net = MkNet\n  { hidden :: [Weights]\n  , output :: Weights\n  } deriving (Eq, Show, Generic)\ninstance FromJSON Net\n\ndata Weights = MkWeights\n  { weights :: Matrix Double\n  , biases :: Vector Double\n  } deriving (Eq, Show, Generic)\ninstance FromJSON Weights where\n  parseJSON = withObject \"Weights\" $ \\v -> MkWeights\n    <$> fmap mkmatrix (v .: \"weights\")\n    <*> fmap vector (v .: \"biases\")\n    where\n    mkmatrix (ws :: [[Double]]) = matrix (length $ head ws) (concat ws)\n\nloadNet :: FilePath -> IO (Maybe Net)\nloadNet file = decode <$> LBS.readFile file\n\nrunNet :: Net -> Vector Double -> Vector Double\nrunNet MkNet{..} features =\n  softmax (runLayer (foldl' runHidden features hidden) output)\n  where\n  runHidden fs ws = relu $ runLayer fs ws\n  runLayer fs MkWeights{..} =\n    fs <# weights + biases\n\nrelu :: Vector Double -> Vector Double\nrelu v = cmap (\\x -> max 0 x) v\n\nsoftmax :: Vector Double -> Vector Double\nsoftmax v = cmap (\\x -> exp x / summed) v\n  where\n  summed = sumElements (cmap exp v)\n\ndata Sample a = MkSample { getThing :: a, getSample :: Vector Double }\n  deriving (Eq, Show, Generic)\ninstance CSV.FromRecord (Sample SrcSpan) where\n  parseRecord r = MkSample\n    <$> (maybe mzero return . readMaybe =<< CSV.parseField (r V.! 0))\n    <*> fmap vector (CSV.parseRecord (V.drop 4 r))\n\nloadSamples :: FilePath -> IO (Either String (V.Vector (Sample SrcSpan)))\nloadSamples file = CSV.decode CSV.HasHeader <$> LBS.readFile file\n\n-- net2network :: Net -> Network ts ds\n-- net2network MkNet{..} = foldr addLayer NNil (output : reverse hidden)\n\n-- addLayer :: Weights -> Network ts ds\n--          -> Network (FullyConnected dx dy : Relu : ts) (d : d : ds)\n-- addLayer ws net = mkLayer ws :~> Relu :~> net\n", "meta": {"hexsha": "18edb9ed1c55480ed5376352bed87bf3fef75cdf", "size": 4014, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NanoML/Learn.hs", "max_stars_repo_name": "gsakkas/nanomaly", "max_stars_repo_head_hexsha": "8121d0728534831979b7fda5f73145d4f1621dd0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NanoML/Learn.hs", "max_issues_repo_name": "gsakkas/nanomaly", "max_issues_repo_head_hexsha": "8121d0728534831979b7fda5f73145d4f1621dd0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NanoML/Learn.hs", "max_forks_repo_name": "gsakkas/nanomaly", "max_forks_repo_head_hexsha": "8121d0728534831979b7fda5f73145d4f1621dd0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8769230769, "max_line_length": 98, "alphanum_fraction": 0.6532137519, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.4008203517242307}}
{"text": "{-# LANGUAGE DataKinds                                #-}\n{-# LANGUAGE DeriveDataTypeable                       #-}\n{-# LANGUAGE DeriveGeneric                            #-}\n{-# LANGUAGE FlexibleInstances                        #-}\n{-# LANGUAGE GADTs                                    #-}\n{-# LANGUAGE KindSignatures                           #-}\n{-# LANGUAGE MultiParamTypeClasses                    #-}\n{-# LANGUAGE PatternSynonyms                          #-}\n{-# LANGUAGE RankNTypes                               #-}\n{-# LANGUAGE RecordWildCards                          #-}\n{-# LANGUAGE ScopedTypeVariables                      #-}\n{-# LANGUAGE TypeApplications                         #-}\n{-# LANGUAGE TypeFamilies                             #-}\n{-# LANGUAGE TypeInType                               #-}\n{-# LANGUAGE TypeOperators                            #-}\n{-# LANGUAGE UndecidableInstances                     #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise       #-}\n\nmodule Backprop.Learn.Model.Neural.LSTM (\n    -- * Basic LSTM\n    LSTM, pattern LSTM\n  , LSTMp(..), lstmForget, lstmInput, lstmUpdate, lstmOutput\n  , LSTM'(..)\n    -- * GRU\n  , GRU, pattern GRU\n  , GRUp(..), gruMemory, gruUpdate, gruOutput\n  , GRU'(..)\n  ) where\n\nimport           Backprop.Learn.Initialize\nimport           Backprop.Learn.Model.Class\nimport           Backprop.Learn.Model.Function\nimport           Backprop.Learn.Model.Neural\nimport           Backprop.Learn.Model.Regression\nimport           Backprop.Learn.Model.State\nimport           Control.DeepSeq\nimport           Data.Typeable\nimport           GHC.Generics                          (Generic)\nimport           GHC.TypeNats\nimport           Lens.Micro\nimport           Numeric.Backprop\nimport           Numeric.LinearAlgebra.Static.Backprop\nimport           Numeric.OneLiner\nimport           Numeric.Opto.Ref\nimport           Numeric.Opto.Update\nimport qualified Data.Binary                           as Bi\nimport qualified Numeric.LinearAlgebra.Static          as H\n\n-- | \"Base\" for 'LSTM'.  An 'LSTM' is just an 'LSTM'' where the second half\n-- of the input vector is the previous output.\n--\n-- This is mostly an implementation detail.  It is recommended that you use\n-- 'LSTM' and its constructor, instead of directly using this.\ndata LSTM' (i :: Nat) (o :: Nat) = LSTM'\n  deriving (Typeable)\n\n-- TODO: allow parameterize internal activation function?\n-- TODO: Peepholes\n\n-- | 'LSTM' layer parmateters\ndata LSTMp (i :: Nat) (o :: Nat) =\n    LSTMp { _lstmForget :: !(FCp (i + o) o)\n          , _lstmInput  :: !(FCp (i + o) o)\n          , _lstmUpdate :: !(FCp (i + o) o)\n          , _lstmOutput :: !(FCp (i + o) o)\n          }\n  deriving (Generic, Typeable, Show)\n\ninstance NFData (LSTMp i o)\ninstance (KnownNat i, KnownNat o) => Additive (LSTMp i o)\ninstance (KnownNat i, KnownNat o) => Scaling Double (LSTMp i o)\ninstance (KnownNat i, KnownNat o) => Metric Double (LSTMp i o)\ninstance (KnownNat i, KnownNat o, Ref m (LSTMp i o) v) => AdditiveInPlace m v (LSTMp i o)\ninstance (KnownNat i, KnownNat o, Ref m (LSTMp i o) v) => ScalingInPlace m v Double (LSTMp i o)\ninstance (KnownNat i, KnownNat o) => Bi.Binary (LSTMp i o)\ninstance (KnownNat i, KnownNat o) => Backprop (LSTMp i o)\n\n-- | Forget biases initialized to 1\ninstance (KnownNat i, KnownNat o) => Initialize (LSTMp i o) where\n    initialize d g = LSTMp <$> set (mapped . fcBias) 1 (initialize d g)\n                           <*> initialize d g\n                           <*> initialize d g\n                           <*> initialize d g\n\ninstance (KnownNat i, KnownNat o) => Num (LSTMp i o) where\n    (+)         = gPlus\n    (-)         = gMinus\n    (*)         = gTimes\n    negate      = gNegate\n    abs         = gAbs\n    signum      = gSignum\n    fromInteger = gFromInteger\n\ninstance (KnownNat i, KnownNat o) => Fractional (LSTMp i o) where\n    (/)          = gDivide\n    recip        = gRecip\n    fromRational = gFromRational\n\ninstance (KnownNat i, KnownNat o) => Floating (LSTMp i o) where\n    pi    = gPi\n    sqrt  = gSqrt\n    exp   = gExp\n    log   = gLog\n    sin   = gSin\n    cos   = gCos\n    asin  = gAsin\n    acos  = gAcos\n    atan  = gAtan\n    sinh  = gSinh\n    cosh  = gCosh\n    asinh = gAsinh\n    acosh = gAcosh\n    atanh = gAtanh\n\nlstmForget :: Lens' (LSTMp i o) (FCp (i + o) o)\nlstmForget f x = (\\y -> x { _lstmForget = y }) <$> f (_lstmForget x)\n\nlstmInput :: Lens' (LSTMp i o) (FCp (i + o) o)\nlstmInput f x = (\\y -> x { _lstmInput = y }) <$> f (_lstmInput x)\n\nlstmUpdate :: Lens' (LSTMp i o) (FCp (i + o) o)\nlstmUpdate f x = (\\y -> x { _lstmUpdate = y }) <$> f (_lstmUpdate x)\n\nlstmOutput :: Lens' (LSTMp i o) (FCp (i + o) o)\nlstmOutput f x = (\\y -> x { _lstmOutput = y }) <$> f (_lstmOutput x)\n\ninstance (KnownNat i, KnownNat o, KnownNat io, io ~ (i + o)) => Learn (R io) (R o) (LSTM' i o) where\n    type LParamMaybe (LSTM' i o) = 'Just (LSTMp i o)\n    type LStateMaybe (LSTM' i o) = 'Just (R o)\n\n    runLearn LSTM' (J_ p) x (J_ s) = (h, J_ s')\n      where\n        forget = logistic $ runLRp (p ^^. lstmForget) x\n        input  = logistic $ runLRp (p ^^. lstmInput ) x\n        update = tanh     $ runLRp (p ^^. lstmUpdate) x\n        s'     = forget * s + input * update\n        o      = logistic $ runLRp (p ^^. lstmOutput) x\n        h      = o * tanh s'\n\n-- | Long-term short-term memory layer\n--\n-- <http://colah.github.io/posts/2015-08-Understanding-LSTMs/>\n--\n-- @\n-- instance 'Learn' ('R' i) (R o) ('LSTM' i o) where\n--     type 'LParamMaybe' (LSTM i o) = ''Just' ('LSTMp' i o)\n--     type 'LStateMaybe' (LSTM i o) = 'Just ('T2' (R o) (R o))     -- cell state, hidden state\n-- @\ntype LSTM i o = Recurrent (R (i + o)) (R i) (R o) (R o) (LSTM' i o)\n\n-- | Construct an 'LSTM'\npattern LSTM :: (KnownNat i, KnownNat o) => LSTM i o\npattern LSTM <- Rec { _recLearn = LSTM' }\n  where\n    LSTM = Rec\n      { _recSplit = H.split\n      , _recJoin  = (H.#)\n      , _recLoop  = id\n      , _recLearn = LSTM'\n      }\n\n-- | \"Base\" for 'GRU'.  An 'GRU' is just an 'GRU'' where the second half\n-- of the input vector is the previous output.\n--\n-- This is mostly an implementation detail.  It is recommended that you use\n-- 'GRU' and its constructor, instead of directly using this.\ndata GRU' (i :: Nat) (o :: Nat) = GRU'\n  deriving (Typeable)\n\n\n-- | 'GRU' layer parmateters\ndata GRUp (i :: Nat) (o :: Nat) =\n    GRUp { _gruMemory :: !(FCp (i + o) o)\n         , _gruUpdate :: !(FCp (i + o) o)\n         , _gruOutput :: !(FCp (i + o) o)\n         }\n  deriving (Generic, Typeable, Show)\n\ninstance NFData (GRUp i o)\ninstance (KnownNat i, KnownNat o) => Additive (GRUp i o)\ninstance (KnownNat i, KnownNat o) => Scaling Double (GRUp i o)\ninstance (KnownNat i, KnownNat o) => Metric Double (GRUp i o)\ninstance (KnownNat i, KnownNat o, Ref m (GRUp i o) v) => AdditiveInPlace m v (GRUp i o)\ninstance (KnownNat i, KnownNat o, Ref m (GRUp i o) v) => ScalingInPlace m v Double (GRUp i o)\ninstance (KnownNat i, KnownNat o) => Bi.Binary (GRUp i o)\ninstance (KnownNat i, KnownNat o) => Backprop (GRUp i o)\n\ninstance (KnownNat i, KnownNat o) => Initialize (GRUp i o) where\n    initialize d g = GRUp <$> initialize d g\n                          <*> initialize d g\n                          <*> initialize d g\n\ninstance (KnownNat i, KnownNat o) => Num (GRUp i o) where\n    (+)         = gPlus\n    (-)         = gMinus\n    (*)         = gTimes\n    negate      = gNegate\n    abs         = gAbs\n    signum      = gSignum\n    fromInteger = gFromInteger\n\ninstance (KnownNat i, KnownNat o) => Fractional (GRUp i o) where\n    (/)          = gDivide\n    recip        = gRecip\n    fromRational = gFromRational\n\ninstance (KnownNat i, KnownNat o) => Floating (GRUp i o) where\n    pi    = gPi\n    sqrt  = gSqrt\n    exp   = gExp\n    log   = gLog\n    sin   = gSin\n    cos   = gCos\n    asin  = gAsin\n    acos  = gAcos\n    atan  = gAtan\n    sinh  = gSinh\n    cosh  = gCosh\n    asinh = gAsinh\n    acosh = gAcosh\n    atanh = gAtanh\n\ngruMemory :: Lens' (GRUp i o) (FCp (i + o) o)\ngruMemory f x = (\\y -> x { _gruMemory = y }) <$> f (_gruMemory x)\n\ngruUpdate :: Lens' (GRUp i o) (FCp (i + o) o)\ngruUpdate f x = (\\y -> x { _gruUpdate = y }) <$> f (_gruUpdate x)\n\ngruOutput :: Lens' (GRUp i o) (FCp (i + o) o)\ngruOutput f x = (\\y -> x { _gruOutput = y }) <$> f (_gruOutput x)\n\ninstance (KnownNat i, KnownNat o, KnownNat io, io ~ (i + o)) => Learn (R io) (R o) (GRU' i o) where\n    type LParamMaybe (GRU' i o) = 'Just (GRUp i o)\n    type LStateMaybe (GRU' i o) = 'Nothing\n\n    runLearn GRU' (J_ p) = stateless $ \\x ->\n        let z      = logistic $ runLRp (p ^^. gruMemory) x\n            r      = logistic $ runLRp (p ^^. gruUpdate) x\n            r'     = 1 # r\n            h'     = tanh     $ runLRp (p ^^. gruOutput) (r' * x)\n        in  (1 - z) * snd (split @i x) + z * h'\n\n-- | Gated Recurrent Unit\n--\n-- <http://colah.github.io/posts/2015-08-Understanding-LSTMs/>\n--\n-- @\n-- instance 'Learn' ('R' i) (R o) ('GRU' i o) where\n--     type 'LParamMaybe' (GRU i o) = ''Just' ('GRUp' i o)\n--     type 'LStateMaybe' (GRU i o) = 'Just (R o)\n-- @\ntype GRU i o = Recurrent (R (i + o)) (R i) (R o) (R o) (GRU' i o)\n\n-- | Construct an 'GRU'\npattern GRU :: (KnownNat i, KnownNat o) => GRU i o\npattern GRU <- Rec { _recLearn = GRU' }\n  where\n    GRU = Rec\n      { _recSplit = H.split\n      , _recJoin  = (H.#)\n      , _recLoop  = id\n      , _recLearn = GRU'\n      }\n", "meta": {"hexsha": "90ed4bfb6da17108157422f5ba625239d6c5da25", "size": 9393, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "old2/src/Backprop/Learn/Model/Neural/LSTM.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "old2/src/Backprop/Learn/Model/Neural/LSTM.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "old2/src/Backprop/Learn/Model/Neural/LSTM.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 35.4452830189, "max_line_length": 100, "alphanum_fraction": 0.5504098797, "num_tokens": 2958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.4008203444599008}}
{"text": "module Test.Test where\n\nimport Test.Framework (defaultMainWithArgs, testGroup, Test)\nimport Test.Framework.Providers.HUnit (testCase)\nimport Test.Framework.Providers.QuickCheck2 (testProperty)\n\nimport Test.QuickCheck (Property, NonNegative(..))\nimport Test.QuickCheck.Monadic (assert, monadicIO, run)\nimport Test.HUnit (assertBool)\n\nimport qualified Numeric.LinearAlgebra as LA\n--import qualified Graphics.Rendering.Plot.HMatrix as G\n\nimport qualified Math.FROG.Tools as FR\nimport Math.FROG.Retrieval\nimport Math.FROG.Types\n--import Test.Types\n\ntype PulseFn = Double -> Double -> LA.Complex Double\n\n-----------------\n-- Example Pulses\n-----------------\nsingleGaus :: PulseFn\nsingleGaus sz k = exp ((-pi) / sz * (k - sz/2.0)^2) LA.:+ 0.0\n\ndoubleGaus :: PulseFn\ndoubleGaus sz k = (singleGaus sz (k - (sz / 8.0))) + (singleGaus sz (k + (sz / 8.0)))\n\nmkPulse :: PulseFn -> Int -> ComplexSignal\nmkPulse form sz = LA.buildVector sz mkElem\n    where\n    dsz = (fromIntegral sz) :: Double\n    mkElem = form dsz . fromIntegral\n\n\n\ncaseRetrieval :: ComplexSignal -> IO ()\ncaseRetrieval field = do\n    let sz = LA.dim field\n    let dsz = (fromIntegral sz) :: Double\n    let trc = FR.mkTrace field field\n\n    o <- retrieve SHG trc\n\n    let rfield = FR.center . FR.flatPolar2Complex $ o\n    let mags = (LA.mapVector LA.magnitude) rfield\n\n    putStrLn . show $ calcLoss SHG trc o\n\n    --G.mplot [LA.linspace sz (0::Double, dsz-1), mags]\n\n    --G.imshow trc\n\n    --G.imshow (FR.mkTrace rfield rfield)\n\n\n-----------------\n---- List of Tests\n-----------------\n\ntests :: [Test]\ntests = \n    [ testGroup \"Retrieval\" [ testCase \"Gaussian\" $ caseRetrieval (mkPulse singleGaus 32)\n                            , testCase \"Double Gaussian\" $ caseRetrieval (mkPulse doubleGaus 32)\n                            ]\n    ]\n\n\n-- convenient whilst in ghci\nrunAllTests :: IO ()\nrunAllTests = defaultMainWithArgs tests []\n\nrunTests :: String -> IO ()\nrunTests p = defaultMainWithArgs tests [\"--select-tests\", p]\n\nrunGroup :: Int -> IO ()\nrunGroup i = defaultMainWithArgs [tests !! i] []\n", "meta": {"hexsha": "6ce9cf72d27232d2860acf30d02b650d241129ed", "size": 2051, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Test/Test.hs", "max_stars_repo_name": "leroix/haskell-spsa-frog", "max_stars_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-25T19:38:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-25T19:38:00.000Z", "max_issues_repo_path": "tests/Test/Test.hs", "max_issues_repo_name": "leroix/haskell-spsa-frog", "max_issues_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Test/Test.hs", "max_forks_repo_name": "leroix/haskell-spsa-frog", "max_forks_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9620253165, "max_line_length": 96, "alphanum_fraction": 0.6562652365, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4006954854358644}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n-----------------------------------------------------------------------------\n--\n-- Module      :  AI.Network.RNN.Data\n-- Copyright   :  (c) JP Moresmau\n-- License     :  BSD3\n--\n-- Maintainer  :  JP Moresmau <jp@moresmau.fr>\n-- Stability   :  experimental\n-- Portability :\n--\n-- | Conversion from and to text data\n--\n-----------------------------------------------------------------------------\n\nmodule AI.Network.RNN.Data  where\n\nimport qualified Data.Text as T\nimport qualified Data.Map as DM\nimport qualified Data.Set as DS\nimport Data.Maybe\nimport Data.Tuple\nimport Data.List\nimport Control.Monad.Random as R\nimport Control.Monad\nimport Numeric.LinearAlgebra.HMatrix  as M\nimport Data.Foldable as F (toList)\n\nimport qualified Data.SDR as SDR\nimport qualified Data.IntSet as I\n\nimport AI.Network.RNN.Types\nimport AI.Network.RNN.Util\n-- import Debug.Trace\n\n\n-- | Transform text into training data\n-- the encoding of each Char is equilateral encoding\ntextToTrainData :: T.Text -> TrainData ((DM.Map Int Char),Matrix Double)\ntextToTrainData t =\n    let (ids,m) = T.foldl' toIDs ([],DM.empty) t\n        sz = DM.size m\n        em = equilateralEncoding sz\n        is = map (toArr em) $ reverse ids\n        charMap = DM.fromList $ map swap $ DM.assocs m\n    in\n        TrainData (M.fromList (replicate (sz-1) 0): init is) is (sz-1) (charMap,em)\n    where\n        toIDs :: ([Int],DM.Map Char Int) -> Char -> ([Int],DM.Map Char Int)\n        toIDs (ids,m) c =\n            let mmyid = DM.lookup c m\n            in case mmyid of\n                Just myid -> (myid:ids,m)\n                Nothing   ->\n                    let myid = DM.size m\n                    in (myid:ids,DM.insert c myid m)\n--        toArr :: Int -> Int -> Vector Double\n--        toArr sz idx = M.fromList $ replicate idx 0 ++ [1] ++ replicate (sz-idx-1) 0\n        toArr em idx = flatten $ em ? [idx]\n\n-- | Decode the data from the equilateral encoding\ndataToText :: ((DM.Map Int Char),Matrix Double) -> [Vector Double] -> T.Text\ndataToText (m,em)  = T.pack . F.toList . fmap toC\n    where\n        toC :: Vector Double -> Char\n        -- toC ds = fromJust $ DM.lookup (maxIndex ds) m\n        toC ds = fromJust $ DM.lookup (equilateralDecoding em ds) m\n\n-- | Generate random text with the probabilities given by the vector (not used)\nrandDataToText :: RandomGen g => DM.Map Int Char -> [Vector Double] -> Rand g T.Text\nrandDataToText m  = liftM T.pack . mapM (toC . M.toList)\n    where\n        toC :: RandomGen g => [Double] -> Rand g Char\n        toC ls = do\n            let m1 = normalize $ map (\\(ix,d)->(fromJust $ DM.lookup ix m,d)) $ zip [0..] ls\n                m2 = map (\\(a,b)->(a,toRational b)) m1\n                -- s  = sum $ map (exp . snd) m1\n                -- m3 = map (\\(a,b)-> (a,exp(b)/s)) m1\n            R.fromList m2\n            --return $ fst $ last $ sortBy (comparing snd) m3\n\n-- | Generate text using equilateral encoding and a given network\ngenerate :: (RandomGen g,RNNEval a)\n    => ((DM.Map Int Char),Matrix Double) -- ^ Character map\n    -> Int  -- ^ Number of characters to generate\n    -> Int -- ^ Size of the vectors for each characters\n    -> a -- network\n    -> Rand g T.Text\ngenerate m nb sz rnn =generate' m nb sz rnn dataToText\n\n-- | Generate text using sparse encoding and a given network\ngenerateS :: (RandomGen g,RNNEval a)\n    => SDR.SDRSet Char -- ^ Character map\n    -> Int  -- ^ Number of characters to generate\n    -> Int -- ^ Size of the vectors for each characters\n    -> a -- network\n    -> Rand g T.Text\ngenerateS m nb sz rnn =generate' m nb sz rnn dataToTextS\n\n-- | Generate text given a decoding function\n-- current implementation is not random!\ngenerate' :: (RandomGen g,RNNEval a) => m -> Int -> Int -> a ->\n    (m -> [Vector Double] -> T.Text) -> Rand g T.Text\ngenerate' m nb sz rnn f =  do\n    let (_,_,alls) = foldl' go (rnn,M.fromList $ replicate sz 0,[]) [1..nb]\n    --randDataToText m alls\n    return $ f m alls\n    where\n        go :: (RNNEval a) => (a,Vector Double,[Vector Double]) -> Int -> (a,Vector Double,[Vector Double])\n        go (rnn1,is1,oss) _ =\n            let (rnn2,os) = evalStep rnn1 is1\n                os2 = norm os\n            in (rnn2,os2,oss ++ [os])\n        norm :: Vector Double -> Vector Double\n        norm os = let\n            mx = maximum $ M.toList os\n            --in M.assoc (M.size os) 0 [(mx,1)]\n            in M.fromList $ map (\\a->if a == mx then 1 else 0) $ M.toList os\n\n-- | Train data using sparse encoding: 2 values in the vector are set to one for each character\n-- This was a test to try to reduce the size of the network but is not efficient\ntextToTrainDataS :: T.Text -> TrainData (SDR.SDRSet Char)\ntextToTrainDataS t =\n    let charSet = T.foldl' (flip DS.insert) DS.empty t\n        sz  = DS.size charSet\n        markers = 1\n        total = sz * markers\n        sdr = SDR.build (sz*markers) markers charSet\n        is = T.foldr (\\c l->enc total sdr c : l) [] t\n    in TrainData (M.fromList (replicate total 0): init is) is total sdr\n    where\n        enc :: Int -> SDR.SDRSet Char -> Char -> Vector Double\n        enc total sdr c =\n            let is=SDR.encode sdr c\n            in M.assoc total 0 $ zip (I.toList is) (repeat 1)\n\n--textToTrainDataS t =\n--    let (ids,m) = T.foldl' toIDs ([],DM.empty) t\n--        sz = sparseSize $ DM.size m\n--        spr = DM.fromList $ zip [0..] $ sparse $ DM.size m\n--        is = map (toArr spr sz) $ reverse ids\n--        charMap = DM.fromList $ map (\\(c,i)->(fromJust $ DM.lookup i spr,c)) $ DM.assocs m\n--    in\n--        TrainData (M.fromList (replicate sz 0): init is) is sz charMap\n--    where\n--        toIDs :: ([Int],DM.Map Char Int) -> Char -> ([Int],DM.Map Char Int)\n--        toIDs (ids,m) c =\n--            let mmyid = DM.lookup c m\n--            in case mmyid of\n--                Just myid -> (myid:ids,m)\n--                Nothing   ->\n--                    let myid = DM.size m\n--                    in (myid:ids,DM.insert c myid m)\n--        toArr :: DM.Map Int (Int,Int) -> Int -> Int -> Vector Double\n--        toArr m sz idx = let\n--            (i1,i2) = fromJust $ DM.lookup idx m\n--            in M.fromList $ replicate i1 0 ++ [1] ++ replicate (i2-i1-1) 0 ++ [1] ++ replicate (sz-i2-1) 0\n\n-- | Generate text from sparse encoding data\ndataToTextS :: SDR.SDRSet Char -> [Vector Double] -> T.Text\ndataToTextS sdr = T.pack . map b\n    where b v =\n            let is = I.fromList $ map fst $ filter (\\(_,c)->c>=0.5) $ zipWith (\\a b->(b,a)) (M.toList v) [0..]\n            in SDR.best sdr is\n--dataToTextS m  = T.pack . F.toList . fmap toC\n--    where\n--        toC :: Vector Double -> Char\n--        toC ds = let\n--            ix1 = maxIndex ds\n--            ix2 = maxIndex $ accum ds const [(ix1,0)]\n--            tpl = if ix1 < ix2\n--                    then (ix1,ix2)\n--                    else (ix2,ix1)\n--            mc = DM.lookup tpl m\n--            in fromMaybe (fromJust $ DM.lookup (0,1) m) mc\n--         --fromJust $ DM.lookup (maxIndex ds) m\n", "meta": {"hexsha": "9c088f551d2ee819bbfd0269b9c9d4f1e4464497", "size": 7046, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Network/RNN/Data.hs", "max_stars_repo_name": "JPMoresmau/rnn", "max_stars_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-08-02T17:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T06:56:40.000Z", "max_issues_repo_path": "src/AI/Network/RNN/Data.hs", "max_issues_repo_name": "JPMoresmau/rnn", "max_issues_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-01T18:47:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-01T18:47:41.000Z", "max_forks_repo_path": "src/AI/Network/RNN/Data.hs", "max_forks_repo_name": "JPMoresmau/rnn", "max_forks_repo_head_hexsha": "05a71bc5e275d24b1ededb644821c8407ad6198c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-12-10T18:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T00:02:09.000Z", "avg_line_length": 39.5842696629, "max_line_length": 110, "alphanum_fraction": 0.5613113823, "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.4005013863591424}}
{"text": "{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE DataKinds #-}\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -fno-warn-unused-imports #-}\n\nmodule Numeric.LinearAlgebra where\n\nimport Numeric.LinearAlgebra.Internal\n", "meta": {"hexsha": "dda4939316afa7de41dc937235484d4082da395e", "size": 206, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra.hs", "max_stars_repo_name": "DataHaskell/numhask-linear-algebra", "max_stars_repo_head_hexsha": "a17b46f9adb2f7c243faac5b27f03c756ef37f85", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-02-26T14:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-22T10:10:00.000Z", "max_issues_repo_path": "src/Numeric/LinearAlgebra.hs", "max_issues_repo_name": "DataHaskell/numhask-linear-algebra", "max_issues_repo_head_hexsha": "a17b46f9adb2f7c243faac5b27f03c756ef37f85", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-03-04T07:01:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-04T07:01:19.000Z", "max_forks_repo_path": "src/Numeric/LinearAlgebra.hs", "max_forks_repo_name": "DataHaskell/numhask-linear-algebra", "max_forks_repo_head_hexsha": "a17b46f9adb2f7c243faac5b27f03c756ef37f85", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-27T02:10:16.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-27T02:10:16.000Z", "avg_line_length": 22.8888888889, "max_line_length": 44, "alphanum_fraction": 0.7330097087, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389327, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4003386088065577}}
{"text": "{-# LANGUAGE OverloadedStrings,FlexibleContexts,TypeFamilies #-}\n\nimport           Control.Applicative\nimport           Control.Arrow                 ((&&&))\nimport           Control.Lens                  hiding ((|>))\nimport           Control.Monad                 (liftM,void)\nimport           Control.Monad.Primitive.Class\nimport           Data.Csv                      (HasHeader(..))\nimport           Data.List                     (mapAccumL)\nimport           Data.Ratio     \nimport           Data.Time     \nimport qualified Data.Vector                   as V (Vector)\nimport qualified Data.Vector.Generic           as V hiding (Vector)\nimport           Graphics.EasyPlot\nimport           Numeric.LinearAlgebra  \nimport           Numeric.LinearAlgebra.Util\nimport           Pipes\nimport qualified Pipes.ByteString              as PB\nimport           Pipes.Csv                     (decode)\nimport           Pipes.Safe                    (SafeT, runSafeT)\nimport qualified Pipes.Safe.Prelude            as PS\nimport qualified Pipes.Vector                  as PV\nimport           System.IO                     (IOMode (ReadMode))\n\n-----------------------------------------------------------------------------\n\nmain :: IO ()\nmain = do\n  runLRStrategy \"Cumulative sum of \" absReturn cmlAbsReturn 0\n  runLRStrategy \"Cumulative product of \" pctReturn cmlPctReturn 0\n  runKFStrategy \"Cumulative sum of \" absReturn cmlAbsReturn 0\n\n-----------------------------------------------------------------------------\n\n-- Linear regression strategy inspired by http://businessforecastblog.com/predicting-the-sp-500-or-the-spy-exchange-traded-fund/\n\nrunLRStrategy :: String -> Return -> Return -> Matrix Double -> IO ()\nrunLRStrategy titleprefix freturn fcmlreturn minret = do\n  (mx,my,vdtd) <- prepareData 30 freturn\n  let\n    t = 2484 -- number of training data points\n    mm = takeRows t mx <\\> takeRows t my\n    my' = mx <> mm\n    mr = step (my' - minret) * my\n    vy = head $ toColumns my\n    vr = head $ toColumns mr  \n    vcy = fcmlreturn vy\n    vcr = fcmlreturn vr  \n    lcy = V.toList vcy\n    lcr = V.toList vcr\n    ldt = map (fromRational . dayToYear . readDay) $ V.toList vdtd \n  void $ plot' [] X11 [\n    Data2D [Title $ titleprefix ++ \"in sample strategy returns\", Style Lines] [] $ take t $ zip ldt lcr, \n    Data2D [Title $ titleprefix ++ \"out of sample strategy returns\", Style Lines] [] $ drop t $ zip ldt lcr,\n    Data2D [Title $ titleprefix ++ \"base returns\", Style Lines] [] $ zip ldt lcy    \n    ]\n\n-----------------------------------------------------------------------------\n\n-- Kalman filter strategy\n\nrunKFStrategy :: String -> Return -> Return -> Matrix Double -> IO ()\nrunKFStrategy titleprefix freturn fcmlreturn minret = do\n  (mx,my,vdtd) <- prepareData 30 freturn\n  let\n    f = diag $ 61 |> repeat 1 :: Matrix Double\n    q = diag $ 61 |> repeat 0.2 :: Matrix Double\n    r = (1><1) [0.1] :: Matrix Double\n    x0 = 61 |> repeat 0\n    p0 = q\n    s0 = State x0 p0    \n    (s',y') = mapAccumL (\\st (xt,yt) -> (kalman (System f (fromRows [xt]) q r) st yt,(xt * (sX st)) @> 1)) s0 $ zip (toRows mx) (toRows my)\n    my' = fromColumns [fromList y'] \n    mr = (step (my' - minret)) * my\n    vy = head $ toColumns my\n    vr = head $ toColumns mr  \n    vcy = fcmlreturn vy\n    vcr = fcmlreturn vr  \n    lcy = V.toList vcy\n    lcr = V.toList vcr\n    ldt = map (fromRational . dayToYear . readDay) $ V.toList vdtd \n  print $ sX s'\n  void $ plot' [] X11 [\n    Data2D [Title $ titleprefix ++ \"strategy returns\", Style Lines] [] $ zip ldt lcr, \n    Data2D [Title $ titleprefix ++ \"base returns\", Style Lines] [] $ zip ldt lcy    \n    ]\n\n-----------------------------------------------------------------------------\n\n-- Kalman code from hmatrix examples\n\ndata System = System {kF, kH, kQ, kR :: Matrix Double}\ndata State = State {sX :: Vector Double , sP :: Matrix Double} deriving Show\ntype Measurement = Vector Double\n\nkalman :: System -> State -> Measurement -> State\nkalman (System f h q r) (State x p) z = State x' p' where\n    px = f <> x                            -- prediction\n    pq = f <> p <> trans f + q             -- its covariance\n    y  = z - h <> px                       -- residue\n    cy = h <> pq <> trans h + r            -- its covariance\n    k  = pq <> trans h <> inv cy           -- kalman gain\n    x' = px + k <> y                       -- new state\n    p' = (ident (dim x) - k <> h) <> pq    -- its covariance\n\n-----------------------------------------------------------------------------\n\n--TODO: streamline inefficient conversion between lists and vectors\n\nprepareData :: Int -> Return -> IO (Matrix Double,Matrix Double,V.Vector String)\nprepareData g freturn = do\n  vsp' <- V.map ((^._1) &&& (^._7)) `liftM` readCSV \"gspc.csv\" \n  vvx' <- V.map ((^._1) &&& (^._7)) `liftM` readCSV \"vix.csv\"\n  let\n    vm' = V.fromList $ mergeEqual (V.toList vsp') (V.toList vvx') :: V.Vector (String,Double,Double)  \n    vdtd = V.map (^._1) (V.drop g vm') :: V.Vector String\n    [vsp'',vvx''] = [V.map] <*> [(^._2),(^._3)] <*> [vm']\n    [vsp,vvx] = map V.convert [vsp'',vvx''] :: [Vector Double]\n    [vspd,vvxd] = map freturn [vsp,vvx] \n    l = V.length vdtd - 1\n    [mspds,mvxds] = map (\\v -> fromColumns [subVector (g-n) l v | n <- [0..g]]) [vspd,vvxd]\n    mx = (konst 1 (l,1)) ! (dropColumns 1 mspds) ! (dropColumns 1 mvxds)\n    my = takeColumns 1 mspds \n  return (mx,my,vdtd)\n\n-----------------------------------------------------------------------------\n\ntype PriceData = (String,Double,Double,Double,Double,Double,Double)\n\ntype ParsedPriceData = Either String PriceData \n\nreadCSV :: FilePath -> IO (V.Vector PriceData)\nreadCSV f = runSafeT $ runEffect $ PV.runToVectorP $\n    (hoist lift (decode HasHeader (PS.withFile f ReadMode (PB.fromHandle)))) \n    >-> rightP\n    >-> PV.toVector \n\n-----------------------------------------------------------------------------\n\nmergeEqual :: Ord a => [(a,b)] -> [(a,b)] -> [(a,b,b)]\nmergeEqual x [] = []\nmergeEqual [] y = []\nmergeEqual x@((xi,xv):xs) y@((yi,yv):ys) \n  | xi == yi = (xi,xv,yv) : mergeEqual xs ys\n  | xi < yi = mergeEqual xs y\n  | xi > yi = mergeEqual x ys\n\n-----------------------------------------------------------------------------\n\ntype Return = Vector Double -> Vector Double\n\nabsReturn :: Return\nabsReturn v = V.zipWith (-) (V.tail v) (V.init v)\n\npctReturn :: Return\npctReturn v = (V.zipWith (-) (V.tail v) (V.init v))/(V.init v)\n\ncmlAbsReturn :: Return\ncmlAbsReturn = V.scanl (+) 0\n\ncmlPctReturn :: Return\ncmlPctReturn = V.scanl (\\x y -> x * (1+y)) 1\n\n-----------------------------------------------------------------------------\n\nreadDay :: String -> Day\nreadDay = read\n\ndayToYear :: Day -> Ratio Integer\ndayToYear day = \n  let\n    (y,_,_) = toGregorian day\n    ystart = fromGregorian y 1 1\n    yend = fromGregorian y 12 31\n    dd = diffDays day ystart\n    dy = diffDays yend ystart\n  in \n    y % 1 + dd % dy\n\n-----------------------------------------------------------------------------\n\nrightP :: (Monad m) => Pipe (Either a b) b m r\nrightP = for cat $ either (const $ return ()) yield\n\n-----------------------------------------------------------------------------\n\ninstance MonadPrim m => MonadPrim (SafeT m) where\n  type BasePrimMonad (SafeT m) = BasePrimMonad m\n  liftPrim = lift . liftPrim\n\n\n\n", "meta": {"hexsha": "c9cebd0bc180cdfddaca8ee76ce4e5a6ec26c392", "size": 7277, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "backtests.hs", "max_stars_repo_name": "cmahon/backtests", "max_stars_repo_head_hexsha": "db33a76991a126c1b9f1e5ff1b2544dffc2b1d0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-14T11:32:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-14T11:32:03.000Z", "max_issues_repo_path": "backtests.hs", "max_issues_repo_name": "cmahon/backtests", "max_issues_repo_head_hexsha": "db33a76991a126c1b9f1e5ff1b2544dffc2b1d0e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backtests.hs", "max_forks_repo_name": "cmahon/backtests", "max_forks_repo_head_hexsha": "db33a76991a126c1b9f1e5ff1b2544dffc2b1d0e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7046632124, "max_line_length": 139, "alphanum_fraction": 0.5205441803, "num_tokens": 1958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.4003062997688579}}
{"text": "----------------------\n-- 2018.1\n-- sule\n-- mnist neutral network for AI course homework\n----------------------\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Main where\n\nimport Data.List(foldl')  \nimport qualified Data.Array as A\nimport Control.Monad\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport Data.Serialize\nimport qualified Data.Vector.Storable as V\nimport Grenade\nimport Numeric.LinearAlgebra (maxIndex)\nimport qualified Numeric.LinearAlgebra.Static as S\nimport System.Random\nimport System.Directory\nimport Graphics.Rendering.Chart.Easy\nimport Graphics.Rendering.Chart.Backend.Diagrams(toFile)\nimport qualified Data.Array.IO as MA\n\n\n-- |type of input and output of the network\ntype IOShape = (S ('D2 28 28), S ('D1 10))\n\n-- |type of the neutral network\ntype HandRC\n  = Network\n  '[ Convolution 1 12 5 5 1 1, Pooling 2 2 2 2, Relu\n     , Convolution 12 24 5 5 1 1, Pooling 2 2 2 2\n     , Reshape, Relu\n     , FullyConnected 384 80, Logit\n     , FullyConnected 80 10, Logit]\n  '[ 'D2 28 28, 'D3 24 24 12, 'D3 12 12 12, 'D3 12 12 12\n     , 'D3 8 8 24, 'D3 4 4 24, 'D1 384, 'D1 384\n     , 'D1 80, 'D1 80, 'D1 10, 'D1 10]\n\n-- |parse the input and label from a csv file     \nparseData :: FilePath -> IO [IOShape]\nparseData path = do\n  strs <- tail . L.lines <$!> L.readFile path\n  return (map proc strs)\n  where\n    proc l =\n      ( fromJust $! fromStorable $! V.fromList $! tail lbs\n      , fromJust $! fromStorable $! V.fromList $! conv $! head lbs)\n      where\n        lbs = map (read . L.unpack) $! L.split ',' l\n    fromJust (Just a) = a\n    conv x' =\n      let x = floor x'\n      in replicate x 0 ++ [1] ++ replicate (9 - x) 0     \n\n-- |train the network with a pair of input and label      \ntrainOne :: LearningParameters -> HandRC -> IOShape -> HandRC\ntrainOne rate !net p@(d, _) = uncurry (train rate net) p\n\n-- |run the network, get the predict\nrun :: HandRC -> S ('D2 28 28) -> S ('D1 10)\nrun = runNet\n\n-- |helper function for random sort\nrandomSortT :: [Int] -> IO [Int]\nrandomSortT [] = return []\nrandomSortT !ls = do\n  a <- randomRIO (0, length ls - 1)\n  (\\ls' -> (ls !! a) : ls') <$!> (randomSortT $! (take a ls ++ drop (a + 1) ls))\n\n-- |helper function for random sort  \nconcatBy::[Int]->[[a]]->[a]\nconcatBy [] _ = []\nconcatBy (x:xs) as = (as!!x)++concatBy xs as\n\n-- |implement of random sort\nrandomSort :: [Int]->Int -> IO [Int]\nrandomSort ls step=\n  if  lg<= step\n    then randomSortT ls\n    else do\n      let ts = lg `div` step\n      xr<-randomSortT [0..ts-1]\n      res''<-mapM (randomSortT . get) [1 .. div (length ls) step]\n      let res'=concatBy xr res''\n      if lg `mod` step==0\n        then return res'\n        else do\n          t<-randomRIO (0,ts)\n          res<-randomSort (drop (ts*step) ls) step\n          return $! take t res'++ res ++drop t res'\n  where\n    get x = drop (step * (x - 1)) $! take (step * x) ls\n    lg =length ls\n\n-- |train one generation    \ntrainOnce ::\n     Int->LearningParameters -> Int -> [IOShape] -> [Int] -> HandRC -> IO HandRC\ntrainOnce gx lp time dts ls !net = do\n  let lgT = length ls\n  print $! lgT\n  foldM\n    (\\n i -> do\n        let ir = ls !! i\n        print $! \"training the \" ++ show i ++ \" th data \" ++ show ir\n        when (i `mod` gx==0) $! do\n          let trained = take i dts\n          let testD = drop lgT dts\n          print $! \"testing \" ++ show i ++ \" records trained before\"\n          let trainCR = validateList n trained\n          appendFile \"trained\" $! Prelude.show (i, correctRate trainCR)++\"\\n\"\n          print $! \"testing \" ++ show (length dts-lgT) ++ \" records for validate\"\n          let trainTest = validateList n testD\n          appendFile \"test\" $! Prelude.show (i, correctRate trainTest)++\"\\n\"\n          plotFromFile (\"trained\", \"test\")\n        return $!\n         trainOne (lp {learningRate = learningRate lp * 0.7 ^ time}) n (dts !! ir))\n    net\n    [0 .. lgT - 1]\n\n-- |train the nerwork with the given init rate, generations, time to calculate accuracy, csv path, and proportion to train\n-- example: trainT 0.007 15 1000 \"train.csv\" 0.8 \n-- means train the \"train.csv\" with a init rate of 0.007, keep training for 15 generations, per 1000 records calculate accuracy \n-- if claim a pre-trained network in the directory, it will be loaded\ntrainT :: FilePath->Double->Int ->Int-> FilePath -> Double -> IO ()\ntrainT preNet initRate time gx path trainS = do\n  dts <- parseData path\n  let lg = length dts - 1\n  let lgT = 1 + floor (trainS * fromIntegral lg)\n  bl<-doesFileExist preNet\n  net <- if bl \n          then print\"loaded\">>load preNet\n          else randomNetwork \n  let lp = LearningParameters initRate 0.9 0.0005\n  net' <-\n    foldM\n      (\\nt t -> do\n         lsT <- randomSort [0 .. lgT-1] 5\n         lsV <- randomSort [lgT .. lg] 5\n         trainOnce gx lp t dts lsT nt)\n      net\n      [1 .. time]\n  save net' \"net\"\n\ncalcConfuseMatrix::IO ()\ncalcConfuseMatrix = do\n  net<-load \"net\"\n  dts<-parseData \"train.csv\"\n  ar<-MA.freeze=<<confuseMatrix net dts::IO (A.Array (Int,Int) Int)\n  writeFile \"confuseMatrix\" $ renderA ar\n\nrenderA::A.Array (Int,Int) Int->String\nrenderA = foldl' (\\str ((_,a),e)->if a==0 then str++\"\\n\"++show e else str++\" \"++show e) [] . A.assocs \n\n-- |calculate the confuseMatrix using the given network and records\nconfuseMatrix::HandRC->[IOShape]->IO (MA.IOUArray (Int,Int) Int)\nconfuseMatrix net ls = do\n  ar<-MA.newArray ((0,0),(9,9)) 0\n  mapM_ (\\((dt,lb),i)->do\n    print i\n    let i=(getIdx lb, getIdx $run net dt)\n    x<-MA.readArray ar i\n    MA.writeArray ar i $x+1) $zip ls [1..]\n  return ar\n\n-- |k-cross validation  \nkCross::Int->Int->Double->FilePath->IO ()\nkCross gen k initRate path = do\n  lds<-parseData path\n  let ws = length lds `div` k\n  mapM_ (cross lds ws) [0..k-1]\n  where cross lds ws t= do\n        let w=t*ws\n        let trainD = take w lds++drop (w+ws) lds\n        let valD = drop w $! take (w+ws) lds\n        net<-trainList initRate t gen trainD\n        let tr=validateList net trainD\n        let vr=validateList net valD\n        save net (\"k-cross-net-\"++show t)\n        putStrLn $!\"Train \"++show (correctRate tr)++\" Validation \"++show (correctRate vr)\n        writeFile (\"k-cross-accuracy-\"++show t) $!\"Train \"++show (correctRate tr)++\" Validation \"++show (correctRate vr)\n\n-- |helper function for k-cross        \njustTrain :: LearningParameters -> Int -> [IOShape] -> HandRC -> IO HandRC\njustTrain lp time dts !net = do\n  let lgT = length dts \n  foldM\n    (\\n i -> do\n        print $! \"training the \" ++ show i ++ \" th data\"\n        return $!\n         trainOne (lp {learningRate = learningRate lp * 0.9 ^ time}) n (dts !! i))\n    net\n    [0 .. lgT - 1]\n\n-- |train a list of records, helper function for k-cross       \ntrainList :: Double->Int->Int->[IOShape] -> IO HandRC\ntrainList initRate r gen dts = do\n  let lg = length dts\n  print lg\n  net <- randomNetwork :: IO HandRC\n  let lp = LearningParameters initRate 0.9 0.0005\n  foldM\n      (\\nt t -> do\n         print $! \"generation \"++show t\n         justTrain lp t dts nt)\n      net\n      [1 .. gen]\n\n-- |get the correctRate from a list of bool      \ncorrectRate :: [Bool] -> Double\ncorrectRate [] = 0\ncorrectRate !bs =\n  fromIntegral (length (filter id bs)) / fromIntegral (length bs)\n\n-- |validate a list of records  \nvalidateList :: HandRC -> [IOShape] -> [Bool]\nvalidateList _ [] = []\nvalidateList !net !ls = map (validateOne net) ls\n\n-- |validate one records  \nvalidateOne :: HandRC -> IOShape -> Bool\nvalidateOne !net (!dt, !lb) = judge (run net dt) lb\n\nvalidate :: IOShape -> IOShape -> Bool\nvalidate (_, !lb') (_, !lb) = judge lb' lb\n\njudge :: S ('D1 10) -> S ('D1 10) -> Bool\njudge !x !y = getIdx x == getIdx y\n\ngetIdx :: S ('D1 10) -> Int\ngetIdx (S1D !a) = maxIndex (S.extract a)\n\n-- |save a network to file\nsave :: HandRC -> FilePath -> IO ()\nsave net path = B.writeFile path $! runPut (put net)\n\nload :: FilePath -> IO HandRC\nload path = do\n  modelData <- B.readFile path\n  either fail return $! runGet (get :: Get HandRC) modelData\n\nplotFromFile::(FilePath,FilePath)->IO ()\nplotFromFile (t,v)=do\n  ts<-map read.lines<$>readFile t::IO [(Int,Double)]\n  vs<-map read.lines<$>readFile t::IO [(Int,Double)]\n  plotAccuracy (trans ts) \"train accuracy\" \"train-accuracy.svg\"\n  plotAccuracy (trans vs) \"validate accuracy\" \"validate-accuracy.svg\"\n  where trans xs = filter (\\(a,b)->b/=0) $map (\\((a,b),z)->(a+z,b)) $ zip xs $concat [replicate 34 x| x<-[0,34000..]]\n\nplotAccuracy::[(Int,Double)]->String->FilePath->IO ()\nplotAccuracy xs am path = toFile def path $ do\n    layout_title .= \"Accuracy\"\n    setColors [opaque green]\n    plot (line am [xs])\n\n\nrunT::IO ()\nrunT = do\n  putStrLn \"Enter the pre-trained neutral network file(if not exist then init randomly)\"\n  net<-getLine\n  putStrLn \"Enter the init learning rate\"\n  initRate<-read<$>getLine\n  putStrLn \"Enter the generations to train(how many repetition)\"\n  time<-read<$>getLine\n  putStrLn \"Enter the duration of validation\"\n  gx<-read<$>getLine\n  putStrLn \"Enter the percentage for training(1-p for validation)\"\n  trainS<-read<$>getLine\n  putStrLn \"Enter the path of training data(train.csv)\"\n  path<-getLine\n  trainT net initRate time gx path trainS \n\n\nrunK::IO ()\nrunK = do\n  putStrLn \"Enter the k for k-cross validation\"\n  k<-read<$>getLine\n  putStrLn \"Enter the init learning rate\"\n  initRate<-read<$>getLine\n  putStrLn \"Enter the generations to train(how many repetition)\"\n  time<-read<$>getLine\n  putStrLn \"Enter the path of training data(train.csv)\"\n  path<-getLine\n  kCross time k initRate path\n\nmain = do\n  putStrLn \"choose one action\"\n  putStrLn \"0 -- run randomly training and validation\"\n  putStrLn \"1 -- run k cross validation\"\n  x<-read<$>getLine::IO Int\n  if x==0 \n    then runT\n    else if x==1 \n      then runK\n      else putStrLn \"wrong option\">>main\n", "meta": {"hexsha": "0d9a3b02ef4f64c02f5594c209411e1758a7618b", "size": 9958, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "mnist.hs", "max_stars_repo_name": "xsuler/grenade_mnist", "max_stars_repo_head_hexsha": "f1abc8f5f602bc1d5533ae5294368237176177fc", "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": "mnist.hs", "max_issues_repo_name": "xsuler/grenade_mnist", "max_issues_repo_head_hexsha": "f1abc8f5f602bc1d5533ae5294368237176177fc", "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": "mnist.hs", "max_forks_repo_name": "xsuler/grenade_mnist", "max_forks_repo_head_hexsha": "f1abc8f5f602bc1d5533ae5294368237176177fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7565789474, "max_line_length": 128, "alphanum_fraction": 0.6294436634, "num_tokens": 3077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4001761066514151}}
