{"text": "import qualified System.Environment as SE\nimport qualified Data.ByteString.Lazy.Char8 as LC\nimport qualified Data.ByteString.Char8 as BC\nimport qualified Data.List as DL\nimport qualified Data.Map as DM\nimport qualified Data.Vector as DV\nimport qualified Statistics.Sample as SS\nimport qualified Statistics.Quantile as SQ\nimport Text.Printf\n\nmain :: IO()\nmain = do\n input <- LC.getContents\n output (nums $ LC.lines input)\n\n-- clean input into a list of numbers \nnums :: [LC.ByteString] -> [Double]\nnums llns = floats $ map BC.unpack $ slns llns\n where \n slns = map (BC.concat . LC.toChunks)\n floats [] = []\n floats [x] = [read x :: Double]\n floats (x:xs) = [read x :: Double] ++ floats xs\n\n-- | calculate the frequency of items in a set\n-- [ [(number, frequency), ....\nfreqs xs = DM.toList $ DM.fromListWith (+) [(c, 1) | c <- xs]\n\n-- | calculate the mode of a list of numbers\nmode xs = (fst . DL.head) $ DL.sortBy sortGT $ freqs xs\n where \n sortGT (a1, b1) (a2, b2)\n | b1 < b2 = GT\n | b1 > b2 = LT\n | b1 == b2 = compare b1 b2\n\n-- | calculate a quantile point\nqtile q t xs = (SQ.continuousBy SQ.medianUnbiased q t) $ DV.fromList xs\n\n-- | calculate the midhinge\nmidhinge xs = (qtile 1 4 xs + qtile 3 4 xs) / 2\n\n-- | calculate the trimean\ntrimean xs = (qtile 2 4 xs + midhinge xs) / 2\n\nh :: (Floating a, Ord t) => [t] -> a \n-- | calculate Shannon Entropy\nh xs = negate . sum . map (\\(i,j) -> (p j xs) * (logBase 2 $ p j xs)) $ freqs xs\n where\n p n lst = (/) n tot_len\n\ttot_len = (fromIntegral $ length xs)\n\n-- | string formatter: round to 4 decimal places\nformat f n = printf \"%.4f\" (f $ DV.fromList n)\n\n-- | display output formatting\ndisplay xs = sequence_ [putStrLn (a++\" : \"++b) | (a,b) <- xs]\n\noutput :: [Double] -> IO ()\noutput xs = display table\n where table = [(\"Length\", show $ length xs)\n ,(\"Min\", show $ minimum xs)\n ,(\"Max\", show $ maximum xs)\n ,(\"Range\", printf \"%.4f\" $ maximum xs - minimum xs)\n ,(\"Q1\", format (SQ.continuousBy SQ.medianUnbiased 1 4) xs)\n ,(\"Q2\", format (SQ.continuousBy SQ.medianUnbiased 2 4) xs)\n ,(\"Q3\", format (SQ.continuousBy SQ.medianUnbiased 3 4) xs)\n ,(\"IQR\", format (SQ.midspread SQ.medianUnbiased 4) xs)\n ,(\"Trimean\", printf \"%.4f\" $ trimean xs)\n ,(\"Midhinge\", printf \"%.4f\" $ midhinge xs)\n ,(\"Mean\", format SS.mean xs)\n ,(\"Mode\", show $ mode xs)\n ,(\"Kurtosis\", format SS.kurtosis xs)\n ,(\"Skewness\", format SS.skewness xs)\n ,(\"Entropy\", printf \"%.4f\" ((h xs) :: Float))]\n\n\n", "meta": {"hexsha": "7960d35ea46af3d9359484332a0c63efe7f62678", "size": 2741, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "describe.hs", "max_stars_repo_name": "drbunsen/describe", "max_stars_repo_head_hexsha": "5bd3f35d9fd489b34ac4565eeb2d778cbc814a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2015-03-18T11:23:01.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-25T22:39:40.000Z", "max_issues_repo_path": "describe.hs", "max_issues_repo_name": "drbunsen/describe", "max_issues_repo_head_hexsha": "5bd3f35d9fd489b34ac4565eeb2d778cbc814a2d", "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": "describe.hs", "max_forks_repo_name": "drbunsen/describe", "max_forks_repo_head_hexsha": "5bd3f35d9fd489b34ac4565eeb2d778cbc814a2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.141025641, "max_line_length": 80, "alphanum_fraction": 0.5702298431, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6991940343651216}} {"text": "module ComplexPlotter where\n\nimport Data.Complex\nimport System.IO()\nimport System.Process\n\n-- Converts a number to a complex number\ntoComplex n = n :+ 0\n\n-- Adds two complex numbers\ncadd (a :+ b) (c :+ d) = (a + c) :+ (b + d)\n\n-- Subtracts two complex numbers\ncsub (a :+ b) (c :+ d) = (a - c) :+ (b - d)\n\n-- Multiplies two complex numbers\ncmul (a :+ b) (c :+ d) = (a*c - b*d) :+ (a*d + b*c)\n\n---- Complex numbers\ni = 0.0 :+ 1.0\nzero = 0.0 :+ 0.0\none = 1.0 :+ 0.0\ntwo = 2.0 :+ 0.0\n\n-- Complex functions\n-- x^2\nsquare z = cmul z z\n\n-- Uses partial application to return a function g(x, c) = c + f(x)\ncPlus c = cadd (c :+ 0.0)\n\n-- x^2 + 25\nsquarePlus25 z = cadd (25 :+ 0) $ cmul z z\n\n-- x = i\nimagPlane _ = i\n\n-- 2x**2 + 2x + 2\ncomplexPoly z = cadd ((two `cmul` z) `cadd` two) (cmul two (square z))\n\nformat (a, b, c, d) = show a ++\"\\t\" ++ show b ++\"\\t\" ++ show c ++ \"\\t\" ++ show d ++ \"\\n\\n\"\n\nplot f ss a b = do\n let axis = [a, a+ss..b]\n let graph = [(x, y, magnitude $ f (x :+ y), phase $ f (x :+ y)) | x <- axis, y <- axis]\n\n writeFile \"data.txt\" $ foldr (++) \"\" $ map format graph\n\n gnuplot <- callCommand \"gnuplot \\\"Surface-Magnitude.plt\\\"\"\n return gnuplot\n\n{--\nChanges the parameter c of a complex function f(x) + c in the interval [a, b] with a given\nstepsize ss.\n\nThe method returns a list all functions where c is set according to the interval above.\n--}\n\nfunctionList ss a b = [cPlus c | c <- [a, a+ss..b]]\n\n{--\n\nThis method gets a lists of functions and from that generates frames that get encoded into a video\n\nDefault parameters:\nFunction: square\nStep Size: 0.125\nInterval: [-10, 10]\n\nChange according to your needs in the function below.\n\nExample of how to run the function:\n\n*> animate $ functionList 1 (-25) 25\n\nThis will create a file \"plot.mp4\" showing the complex function z^2 + 0 ... z^2 + 25\n\n--}\n\nanimate fx = animate' fx 0 where\n animate' [] n = do\n video <- callCommand $ \"ffmpeg -r 30 -f image2 -s 1920x1080 -start_number 0 -i ./pics/frame%d.png -vframes \" ++ show (n-1) ++ \" -vcodec libx264 -crf 15 -pix_fmt yuv420p plot.mp4\"\n return video\n\n animate' (f:fs) n = do\n current <- plot (f . square) 0.125 (-10) (10)\n return current\n\n rename <- callCommand $ \"ren \\\"pics\\\\output.png\\\" \\\"frame\" ++ show n ++ \".png\"\n return rename\n\n animate' fs (n+1)\n", "meta": {"hexsha": "5058e954f32ff7723f52240ee238c2e61e9eb8c9", "size": 2442, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ComplexPlotter.hs", "max_stars_repo_name": "danielpetri1/complex", "max_stars_repo_head_hexsha": "814fa8f0ba7a14d3140078849faa44d1bbdadeb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-12T00:21:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-27T13:39:55.000Z", "max_issues_repo_path": "ComplexPlotter.hs", "max_issues_repo_name": "danielpetri1/complex", "max_issues_repo_head_hexsha": "814fa8f0ba7a14d3140078849faa44d1bbdadeb2", "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": "ComplexPlotter.hs", "max_forks_repo_name": "danielpetri1/complex", "max_forks_repo_head_hexsha": "814fa8f0ba7a14d3140078849faa44d1bbdadeb2", "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.2580645161, "max_line_length": 197, "alphanum_fraction": 0.5724815725, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.884039278690883, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.698859852700013}} {"text": "{-# LANGUAGE TypeOperators #-}\n\nmodule Main where\n\nimport Data.Complex\nimport Data.Word8\nimport Codec.Picture\nimport qualified Data.Array.Repa as R\nimport Data.Array.Repa (Array, DIM1, DIM2, U, D, Z (..), (:.)(..), (!))\n\n\n-- Type that represents a single Pixel that will be used by Repa\ntype RGB8 = (Pixel8, Pixel8, Pixel8)\n\nmaxIterations :: Int\nmaxIterations = 255\n\nimgWidth :: Int\nimgWidth = 1920\n\nimgHeight :: Int\nimgHeight = 1080\n\nimgPath :: String\nimgPath = \"./mandel.png\"\n\nf :: RealFloat a => Complex a -> Complex a -> Complex a\nf c z = z^2 + c\n\nfractal :: RealFloat a => Complex a -> Complex a -> Int\nfractal c init = length . takeWhile (\\x -> magnitude x <= 2) . take maxIterations $ iterated\n where iterated = iterate (f c) init\n\nscaleInterval :: Fractional a => (a, a) -> (a, a) -> a -> a\nscaleInterval (a, b) (c, d) t = c + (((d - c) * (t - a)) / (b - a))\n\nmain :: IO ()\nmain = do\n putStrLn $ \"Writing mandelbrot set in \" ++ imgPath ++ \", please wait.\"\n repaVectorImage <- R.computeUnboxedP generateImgRepa\n let mandelbrotImage = repaArrayToImage repaVectorImage\n writePng imgPath mandelbrotImage\n putStrLn \"Image successfully written.\"\n\ngeneratePixel :: (Z :. Int :. Int) -> RGB8\ngeneratePixel (Z :. x :. y) = (iters, iters, iters)\n where\n iters = fromIntegral $ fractal (scX :+ scY) (0 :+ 0)\n scY = scaleInterval (0.0, fromIntegral imgHeight) (-1.0, 1.0) $ fromIntegral y\n scX = scaleInterval (0.0, fromIntegral imgWidth) (-2.0, 0.5) $ fromIntegral x\n\ngenerateImgRepa :: Array D DIM2 RGB8\ngenerateImgRepa = R.fromFunction (Z :. imgWidth :. imgHeight) generatePixel\n\nrepaArrayToImage :: Array U DIM2 RGB8 -> Image PixelRGB8\nrepaArrayToImage a = generateImage gen imgWidth imgHeight\n where\n gen x y =\n let (r, g, b) = a ! (Z :. x :. y)\n in PixelRGB8 r g b\n", "meta": {"hexsha": "c7b79b9bec79d4f2d87cd3b28064b7230e7f0215", "size": 1825, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "ollenurb/mandelbrot", "max_stars_repo_head_hexsha": "3ac67cd076788150ff842e5b3f6a5fbbae46b121", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-17T20:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T20:32:34.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "ollenurb/mandelbrot", "max_issues_repo_head_hexsha": "3ac67cd076788150ff842e5b3f6a5fbbae46b121", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "ollenurb/mandelbrot", "max_forks_repo_head_hexsha": "3ac67cd076788150ff842e5b3f6a5fbbae46b121", "max_forks_repo_licenses": ["BSD-3-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.9180327869, "max_line_length": 92, "alphanum_fraction": 0.6542465753, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6986425987863619}} {"text": "\nmodule Data.MyPolynomial (\n\tMonomial ((:*^:))\n\t, (*^)\n\t, Equation(Eq)\n\t, getEq\n\t, getL\n\t, getR\n\t, Polynomial\n\t, Roots\n\t, mbrCoeff\n\t, mbrPower\n\t, discriminantQuadratic\n\t, roots\n\t, canonify\n\t, degree\n\t, handleNegativePowers\n\t, getABC\n\t, toMap\n\t, absurd\n\t, divergent\n\t, BroadSol(Absurd, Real)\n\t, Solution(Quadratic, Simple, Broad)\n\t, solveEquation\n\t) where\n\nimport Data.Complex (Complex((:+)))\nimport Data.List\nimport qualified Data.IntMap.Lazy as M\nimport Control.Monad.Trans.Reader\nimport Control.Monad.Trans.State\n\nimport Data.MyPolynomial.Type\nimport Data.MyPolynomial.Parser\nimport Data.MyPolynomial.Print\n\n\ntype ComplexF = Complex Float\ntype Roots = (ComplexF, ComplexF)\ntype NonRoots = [ComplexF]\n\n\n -- Sums every Monomial of equal power.\nsqueeze :: Polynomial -> Polynomial\nsqueeze poly = runReader (doSqueeze poly) (powers poly)\n\twhere\n\t\t -- Build an unique list of represented powers in @pl@\n\t\tpowers pl = nub $ fmap mbrPower pl\n\n\t\t-- Every @mn@ in @pl@ whose power is equal to the provided @pw@.\n\t\tsamePower pw pl = partition (\\ (_ :*^: mp) -> mp == pw) pl \n\n\t\t-- For each the provided power @pw@, partition out bros of power p, sum them, add them back to the other partition.\n\t\tfoldPower pw pl = let\t(bros, others) = samePower pw pl\n\t\t\t\t\tbrogogo = foldr (\\ m macc -> head $ macc +^+ m) (zeroP pw) bros\n\t\t\t\t\tin (brogogo:others)\n\n\t\t-- Pseudo type annotation : \n\t\t-- doSequeeze :: Polynomial -> Reader Env@[Power] Polynomial\n\t\tdoSqueeze pl = do\n\t\t\te:es <- ask\n\t\t\tlet pl' = foldPower e pl\n\t\t\t in case es of\t[] -> return pl'\n\t\t\t\t\t_ -> local (\\ (_:en) -> en ) (doSqueeze pl')\n\n -- Returns a, b, c coefficients as in the canonical expression aX^2 + bX + c\ngetABC :: M.IntMap Float -> (Float, Float, Float)\ngetABC mmap = (mmap M.! 2, mmap M.! 1, mmap M.! 0)\n\n\n -- Takes a condensed quadratic list polynomial; calls error otherwise.\ntoMap :: Polynomial -> M.IntMap Float\ntoMap pl = mapIt (squeeze pl) (M.singleton 0 0)\n\twhere\n\t mapIt ((c :*^: p):mn) map = mapIt mn (M.insert p c map)\n\t mapIt [] map = map\n\n -- Calls error if the polynomial degree is out of bounds ([0 <-> 2]).\nassertMap :: M.IntMap Float -> ()\nassertMap mmap = let d = degree mmap\n\t\t in if d > 2 || d < 0\n\t\t \tthen\terror \"Uncondensed or non-quadratic list polynomial.\"\n\t\t \telse\t()\n\n\n -- Expects a canonical quadratic representation\ndiscriminantQuadratic :: M.IntMap Float -> Float\ndiscriminantQuadratic mmap = let (a, b, c) = getABC mmap\n\t\t\t\tin (b ^ 2 - 4.0 * a * c)\n\n\ndata BroadSol = Absurd | Real\ndata Solution = Quadratic Roots | Simple Float | Broad BroadSol\n\nsolveEquation :: Equation -> Solution\nsolveEquation eq = (doSolve . toMap . getL . canonify) eq\n where\n doSolve mmap = let \ta = mmap M.! 2\n \t\t\tb = mmap M.! 1\n\t\t\tc = mmap M.! 0\n\t\t in dispatch a b c mmap\n quadratic m = Quadratic ( roots m )\n simple m = Simple ( solveDeg1 m )\n broad m = Broad ( broadSolve m )\n dispatch a b c m\t| a /= 0 = quadratic m\n\t\t\t| a == 0 && b /= 0 = simple m\n\t\t\t| a == 0 && b == 0 = broad m\n\n\nbroadSolve :: M.IntMap Float -> BroadSol\nbroadSolve mmap\t= case mmap M.! 0 of\t0 -> Real\n\t\t\t\t\t_ -> Absurd\n\n\nsolveDeg1 :: M.IntMap Float -> Float\nsolveDeg1 mmap = let\tb = mmap M.! 1\n\t\t\tc = mmap M.! 0\n\t\t in (-c) / b\n\n\nroots :: M.IntMap Float -> Roots\nroots mmap\n\t| delta < 0 = (cr1, cr2)\n\t| delta == 0 = (rr0, rr0)\n\t| delta > 0 = (rr1, rr2)\n\twhere\n\t (a, b, c) = getABC mmap\n\t delta = discriminantQuadratic mmap\n\t cr1 = (-b / (2 * a)) :+ (sqrt(-delta) / (2 * a))\n\t cr2 = (-b / (2 * a)) :+ (-sqrt(-delta) / (2 * a))\n\t rr1 = ((-b - sqrt(delta)) / (2 * a)) :+ 0\n\t rr2 = ((-b + sqrt(delta)) / (2 * a)) :+ 0\n\t rr0 = rr1\n\nyankLeft :: Equation -> Equation\nyankLeft (Eq (lp, rp)) = Eq (lp ++ (move rp), [zero])\n where\n move [] = []\n move ((c :*^: p):rpn) = ((-c) :*^: p):move(rpn)\n\n\ncanonify :: Equation -> Equation\ncanonify (Eq (l,r)) = let l' = zero : zeroP 1 : zeroP 2 : l\n\t\t\t Eq (l'', r') = yankLeft $ Eq (l', r)\n\t\t\t l''' = squeeze l''\n\t\t\t in Eq (l''', r')\n\ncanonifyP :: Polynomial -> Polynomial\ncanonifyP pl = let pl' = zero : zeroP 1 : zeroP 2 : pl\n\t\t in squeeze pl'\n\n\ndegree :: M.IntMap Float -> Int\ndegree mmap = highest 0\n\twhere\n\t highest k = case M.lookupGT k mmap of { Nothing -> smaller k;\tJust (kn, _) -> highest kn; }\n\t smaller k = case M.lookupLE k mmap of { Nothing -> k;\t\tJust (kn, v) -> check kn v; }\n\t check kn v = if ( v == 0 && kn > 0 )\tthen\tsmaller (kn - 1)\n\t\t\t\t \t\telse\tkn\n\n\ncutHighZeroes :: Equation -> Equation\ncutHighZeroes (Eq (l, r)) = Eq (skim l, skim r)\n\twhere skim = filter (\\(c :*^: p) -> c /= 0 || (c == 0 && p == 0))\n\n\nabsurd :: Equation -> Bool\nabsurd eq\t| Eq ([cl :*^: 0], [cr :*^: 0]) <- eq' = cl /= cr\n\t\t| otherwise = False\n\twhere\n\t Eq (l, r) = yankLeft eq\n\t eq' = cutHighZeroes $ Eq (squeeze l, squeeze r)\n\n\ndivergent :: Equation -> Bool\ndivergent eq\t| Eq ([cl :*^: 0], [cr :*^: 0]) <- eq' = cl == cr\n\t\t| otherwise = False\n\twhere\n\t Eq (l, r) = yankLeft eq\n\t eq' = cutHighZeroes $ Eq (squeeze l, squeeze r)\n\n\n-- Monomial multiplication\ninfix 5 *^*\n(*^*) :: Monomial -> Monomial -> Monomial\nc1 :*^: p1 *^* c2 :*^: p2 = (c1 * c2) :*^: (p1 + p2)\n\ninfixr 5 /^/\n(/^/) :: Monomial -> Monomial -> Monomial\nc1 :*^: p1 /^/ c2 :*^: p2 = (c1 * (1.0 / c2)) :*^: (p1 - p2)\n\n-- Monomial sum\ninfix 4 +^+\n(+^+) :: Monomial -> Monomial -> Polynomial\nm1@(c1 :*^: p1) +^+ m2@(c2 :*^: p2) | p1 == p2 = [(c1 + c2) :*^: p1]\n\t\t\t\t | otherwise = m1:m2:[]\n\ninfix 4 -^-\n(-^-) :: Monomial -> Monomial -> Polynomial\nm1 -^- (c2 :*^: p2) = m1 +^+ ((-c2) :*^: p2)\n\n\n-- Transforms negative power monomes away and adds forbidden roots to the State.\nhandleNegativePowers :: Polynomial -> State NonRoots Polynomial \nhandleNegativePowers p = case (findNeg p) of\tNothing -> get >>= (\\s -> state (\\_ -> (p, s)))\n\t\t\t\t\t\tJust mn -> handleNext mn p\n where\n bundle (a, b) = nub [a, b]\n addForbidden st nr = nub $ st ++ nr\n\n handleNext :: Monomial -> Polynomial -> State NonRoots Polynomial\n handleNext mx pl = do\n \tget >>= (\\s -> put $ addForbidden s (badRoots mx))\n\thandleNegativePowers ( applyRcp mx pl )\n\n applyRcp :: Monomial -> Polynomial -> Polynomial\n applyRcp negmn pl = canonifyP $ fmap (/^/ negmn) pl\n\n badRoots :: Monomial -> [ComplexF]\n badRoots (_ :*^: 0) = [] -- Should not happen.\n badRoots (c :*^: p)\t| (-p) == 1 = ((:[]) . (:+ 0) . solveDeg1) $ toMap [zero, (c :*^: 1), zeroP 2]\n\t\t\t| (-p) == 2 = bundle $ roots $ toMap [(c :*^: 2), zeroP 1, zeroP 0]\n\t\t\t| otherwise = error $ \"Will not solve: monomial of a higher absolute degree than 2:\\n\" ++ prettyMonomial (c :*^: p)\n\n findNeg = find (\\(c :*^: p) -> p < 0 && c /= 0)\n\n\n", "meta": {"hexsha": "f8dc4b7fff9b1e2deacfed3020cfb7b6ff03a5ea", "size": 6557, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/MyPolynomial.hs", "max_stars_repo_name": "flhorizon/haskell101-mysolver", "max_stars_repo_head_hexsha": "cbe765aece45877cf27392e0acd7423f816652a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/MyPolynomial.hs", "max_issues_repo_name": "flhorizon/haskell101-mysolver", "max_issues_repo_head_hexsha": "cbe765aece45877cf27392e0acd7423f816652a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-16T23:02:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-16T23:02:36.000Z", "max_forks_repo_path": "src/Data/MyPolynomial.hs", "max_forks_repo_name": "flhorizon/haskell101-solver", "max_forks_repo_head_hexsha": "cbe765aece45877cf27392e0acd7423f816652a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7587719298, "max_line_length": 118, "alphanum_fraction": 0.5911239896, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6982486333342619}} {"text": "module Regression where\n\nimport Control.Monad.State\nimport Numeric.LinearAlgebra (col, disp, Matrix, R, rand, scale, toLists, tr, Vector, (><))\nimport Numeric.LinearAlgebra.HMatrix (mul, sumElements)\n\nmeanMatrix :: Matrix R -> Int -> Double\nmeanMatrix inputs batchSize = (sumElements inputs) / (fromIntegral batchSize)\n\nvariance :: [Double] -> Double -> Double\nvariance inputs mean = sum [(x - mean)**2 | x <- inputs]\n\nsigmoid :: Matrix R -> Matrix R\nsigmoid inputs = 1.0 / (1.0 + exp (-1 * inputs))\n\nforward :: Matrix R -> Matrix R -> Matrix R\nforward inputs weights = sigmoid (mul inputs weights)\n\ncriterion :: Matrix R -> Matrix R -> Matrix R\ncriterion targets logits = (-1 * targets) * (log logits) - (1 - targets) * (log $ 1 - logits)\n\nloss :: Matrix R -> Matrix R -> Int -> Double\nloss targets logits batchSize = meanMatrix (criterion targets logits) batchSize\n\ngetGradient :: Matrix R -> Matrix R -> Matrix R -> Int -> Matrix R\ngetGradient inputs targets logits batchSize = (mul (tr inputs) (logits - targets)) / (fromIntegral batchSize)\n\nupdateWeights :: Double -> Matrix R -> Matrix R -> Matrix R\nupdateWeights learningRate gradient weights = (weights - (learningRate `scale` gradient))\n\ngetNewWeights :: Matrix R -> Matrix R -> Matrix R -> Int -> Matrix R\ngetNewWeights inputs targets weights batchSize =\n updateWeights 0.001 (getGradient inputs targets (forward inputs weights) batchSize) weights\n\nrunTrain :: Matrix R -> Matrix R -> Int -> State (Matrix R) (Matrix R)\nrunTrain inputs targets batchSize = do\n weights <- get\n forM_ [0..500] $ \\e -> do\n put (getNewWeights inputs targets weights batchSize)\n return weights\n\nactivate :: [Double] -> [Double]\nactivate predictions = [if x > 0.5 then 1.0 else 0.0 | x <- predictions ]\n", "meta": {"hexsha": "da180076d5e01be50b0cc23fde6ad995f34984b2", "size": 1799, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Regression.hs", "max_stars_repo_name": "staturecrane/haskell-ml", "max_stars_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-09-14T20:47:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-14T20:47:58.000Z", "max_issues_repo_path": "src/Regression.hs", "max_issues_repo_name": "staturecrane/haskell-ml", "max_issues_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Regression.hs", "max_forks_repo_name": "staturecrane/haskell-ml", "max_forks_repo_head_hexsha": "13177bf6f951500e8221fc125902929f7feb5e38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8863636364, "max_line_length": 115, "alphanum_fraction": 0.6831573096, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629194, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6982416885875256}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\n{-|\nModule : Grenade.Core.WeightInitialization\nDescription : Defines the Weight Initialization methods of Grenade.\nCopyright : (c) Manuel Schneckenreither, 2018\nLicense : BSD2\nStability : experimental\n\nThis module defines the weight initialization methods.\n\n-}\n\n\nmodule Grenade.Core.WeightInitialization\n ( getRandomVector\n , getRandomMatrix\n , WeightInitMethod (..)\n ) where\n\nimport Control.Monad\nimport Control.Monad.Primitive (PrimBase, PrimState)\nimport Data.Proxy\nimport Data.Singletons.TypeLits\nimport GHC.TypeLits hiding (natVal)\nimport Numeric.LinearAlgebra.Static\nimport System.Random.MWC\nimport System.Random.MWC.Distributions\n\n-- ^ Weight initialization method.\ndata WeightInitMethod\n = UniformInit -- ^ W_l,i ~ U(-1/sqrt(n_l),1/sqrt(n_l)) where n_l is the number of nodes in layer l\n | Xavier -- ^ W_l,i ~ U(-sqrt (6/n_l+n_{l+1}),sqrt (6/n_l+n_{l+1})) where n_l is the number of nodes in layer l\n | HeEtAl -- ^ W_l,i ~ N(0,sqrt(2/n_l)) where n_l is the number of nodes in layer l\n\n\n-- | Get a random vector initialized according to the specified method.\ngetRandomVector ::\n forall m n. (PrimBase m, KnownNat n)\n => Integer\n -> Integer\n -> WeightInitMethod\n -> Gen (PrimState m)\n -> m (R n)\ngetRandomVector i o method gen = do\n unifRands <- vector <$> replicateM n (uniformR (-1, 1) gen)\n gaussRands <- vector <$> replicateM n (realToFrac <$> standard gen)\n return $\n case method of\n UniformInit -> (1 / sqrt (fromIntegral i)) * unifRands\n Xavier -> (sqrt 6 / sqrt (fromIntegral i + fromIntegral o)) * unifRands\n HeEtAl -> sqrt (2 / fromIntegral i) * gaussRands\n where\n n = fromIntegral $ natVal (Proxy :: Proxy n)\n\n\n-- | Get a matrix with weights initialized according to the specified method.\ngetRandomMatrix ::\n forall m r n. (PrimBase m, KnownNat r, KnownNat n, KnownNat (n * r))\n => Integer\n -> Integer\n -> WeightInitMethod\n -> Gen (PrimState m)\n -> m (L r n)\ngetRandomMatrix i o method gen = do\n unifRands <- matrix <$> replicateM nr (uniformR (-1, 1) gen)\n gaussRands <- matrix <$> replicateM nr (realToFrac <$> standard gen)\n return $\n case method of\n UniformInit -> (1 / sqrt (fromIntegral i)) * unifRands\n Xavier -> (sqrt 6 / sqrt (fromIntegral i + fromIntegral o)) * unifRands\n HeEtAl -> sqrt (2 / fromIntegral i) * gaussRands\n where\n nr = fromIntegral $ natVal (Proxy :: Proxy (n * r))\n", "meta": {"hexsha": "d337ababdf58d9f60cde75344a0e7df156df9273", "size": 2886, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Core/WeightInitialization.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Core/WeightInitialization.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Core/WeightInitialization.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.1951219512, "max_line_length": 118, "alphanum_fraction": 0.6233541234, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6981750849573994}} {"text": "{-# LANGUAGE ParallelListComp #-}\n\nmodule Lib\n ( showC,\n printC,\n bitReverseMap,\n generationFFT,\n generationIFFT,\n decimationFFT,\n decimationIFFT\n ) where\n\nimport Data.Complex\n\n-- |Shows the list of complex numbers in a nice way, without reimplementing show itself.\nshowC :: Show a => [Complex a] -> String\nshowC [] = \"[]\"\nshowC xs = \"[\\n\" ++ (unlines $ map (\\i -> \" \" ++ show i ++ \",\") xs) ++ \"]\\n\"\n\n-- |Print complex numbers easily.\nprintC :: Show a => [Complex a] -> IO ()\nprintC xs = putStrLn $ showC xs\n\n-- |Moves the last item to the front. O(n)\n-- (a, b, c, d) => (d, a, b, c)\ntranslateBack :: Num a => [Complex a] -> [Complex a]\ntranslateBack [] = []\ntranslateBack xs = last xs : init xs\n\n-- |Fourier transform of translating back. It's just multiplying by e^{-2 \\pi i\n-- x / N} This will be the meat of the forward calculation.\n--\n-- (a, b, c, d) => (a, omega * b, omega^2 * c, omega^3 * d)\nmodulateForward :: RealFloat a => Int -> [Complex a] -> [Complex a]\nmodulateForward n xs =\n let twiddles = map (\\i -> cis (-2 * pi * fromIntegral i / fromIntegral n)) [0..] in\n [w * i | i <- xs | w <- twiddles]\n\n-- |Fourier transform of translating forward. This will be the meat of the\n-- inverse calculation. Uses +2 instead of -2 as the coefficient. Equivalent to\n-- moving forward one.\n--\n-- (a, b, c, d) => (a, omega * b, omega^2 * c, omega^3 * d)\nmodulateReverse :: RealFloat a => Int -> [Complex a] -> [Complex a]\nmodulateReverse n xs =\n let twiddles = map (\\i -> cis (2 * pi * fromIntegral i / fromIntegral n)) [0..] in\n [w * i | i <- xs | w <- twiddles]\n\n-- |Pad adds a zero between every other zero. It's Fourier transform is decompress.\n--\n-- (a, b, c, d) => (a, 0, b, 0, c, 0, d, 0)\npad :: Num a => [Complex a] -> [Complex a]\npad [] = []\npad (x:xs) = x:(0 :+ 0):(pad xs)\n\n-- |Opposite of pad. Takes adjacent numbers and adds them together.\n--\n-- (a, b, c, d) => (1/2) * (a + b, c + d)\nunpad :: RealFloat a => [Complex a] -> [Complex a]\nunpad [] = []\nunpad (x:[]) = [x]\nunpad (x:y:xs) = (x + y):xs\n\n-- |Fourier transform of pad. Unfolds the list, and divides by two.\n--\n-- (A, B, C, D) => (1/2) * (A, B, C, D, A, B, C, D)\ndecompress :: RealFloat a => [Complex a] -> [Complex a]\ndecompress xs = map (/ 2) (xs ++ xs)\n\n-- |Fourier transform of the unpad, where you remove \"zeros\", by\n-- squishing adjacent values. But fold would conflict with the standard Haskell\n-- syntax.\n--\n-- (A, B, C, D) => (1/2) * (A + C, B + D)\ncompress :: RealFloat a => Int -> [Complex a] -> [Complex a]\ncompress n xs =\n let (a, b) = splitAt (div n 2) xs in\n map (/2) $ zipWith (+) a b\n\n-- | Inverse version without 1/2 so that it adds to 1/N at the end.\n--\n-- (A, B, C, D) => (A + C, B + D)\ncompress' :: RealFloat a => Int -> [Complex a] -> [Complex a]\ncompress' n xs =\n let (a, b) = splitAt (div n 2) xs in\n zipWith (+) a b\n\n-- |Small helper to simplify generator function.\n--\n-- (A, B, C) + (a, b, c) => (A + a, B + b, C + c)\nadd :: Num a => [a] -> [a] -> [a]\nadd x y = zipWith (+) x y\n\n-- |One unit of a generative fast Fourier transform. See book for more details\n-- and explanation.\ngenerationUnit :: RealFloat a => Int -> [Complex a] -> [Complex a] -> [Complex a]\ngenerationUnit n x y =\n (decompress x) `add` (modulateForward n . decompress $ y)\n\n\n-- |Inverse (note that this version is basically off by a sign and a constant)\n-- |Note that (x ++ x) is used instead of decompress since it only lacks a 2.\ngenerationIUnit :: RealFloat a => Int -> [Complex a] -> [Complex a] -> [Complex a]\ngenerationIUnit n x y =\n (x ++ x) `add` (modulateReverse n $ y ++ y) -- uses ++ so it avoids 1/2 on\n -- fold\n\n-- |Decimation version. See book for more details and explanation.\ndecimationUnit :: RealFloat a => Int -> [Complex a] -> ([Complex a], [Complex a])\ndecimationUnit n x = (compress n x, compress n . modulateForward n $ x)\n\n-- |Inverse operation off by a factor and a sign. Uses compress' which doesn't\n-- have the 2.\ndecimationIUnit :: RealFloat a => Int -> [Complex a] -> ([Complex a], [Complex a])\ndecimationIUnit n x = (compress' n x, compress' n . modulateReverse n $ x)\n\n-- |Nice little feature in case you try to make this imperative (or remove the\n-- alternating costs more likely). Bit reverse doesn't improve the algorithmic\n-- complexity in this case, so I did not include it in the base program.\n--\n-- It is based on the \"Bracewell-Buneman algorithm\", but Haskell's linked lists\n-- may make it algorithmically worse than an imperative version.\n--\n-- 4 => (0, 3, 1, 2)\nbitReverseMap :: Int -> [Int]\nbitReverseMap 1 = [0]\nbitReverseMap n =\n let x = map (*2) $ bitReverseMap (div n 2) in\n x ++ map (+1) x\n\n-- |Alternate is the little cousin of a bit reverse. You take too lists and\n-- alternate between the elements. This is used in the decimationFFT to combine\n-- the two results into one.\n--\n-- (a, b), (c, d) => (a, c, b, d)\nalternate :: [a] -> [a] -> [a]\nalternate [] _ = []\nalternate _ [] = []\nalternate (x:xs) (y:ys) = x:y:(alternate xs ys)\n\n-- |Unalternate is the inverse of the alternate, where it splits up the list the\n-- exact same way. This is used in the generationFFT to feed the recursive FFTs.\n--\n-- (a, b, c, d) => ((a, c), (b, d))\nunalternate :: [a] -> ([a], [a])\nunalternate [] = ([], [])\nunalternate (x:[]) = ([x], [])\nunalternate (x:y:xs) = (x:a, y:b)\n where (a, b) = unalternate xs\n\n-- |This puts all the above functions together in a assembly-based Fourier\n-- transform. Very elegant! Note that I don't do any checks on n-size, and it\n-- fail unexpectedly and silently for those values, since the Fourier transforms\n-- depend on it being divisible by 2.\ngenerationFFT :: RealFloat a => Int -> [Complex a] -> [Complex a]\ngenerationFFT 1 x = x\ngenerationFFT n x =\n generationUnit n (generationFFT halfn a) (generationFFT halfn b)\n where (a, b) = unalternate x\n halfn = div n 2\n\n-- |Inverse of the above (really just the same with name changes). (off by a\n-- factor and a sign in the process).\ngenerationIFFT :: RealFloat a => Int -> [Complex a] -> [Complex a]\ngenerationIFFT 1 x = x\ngenerationIFFT n x =\n generationIUnit n (generationIFFT halfn a) (generationIFFT halfn b)\n where (a, b) = unalternate x\n halfn = div n 2\n\n-- |Disassembly version of the above. Note how similar it is to the version\n-- above, but with a small difference in how it proceeds in computation. This\n-- one breaks up lists into smaller values, while the generative goes\n-- recursively down first.\ndecimationFFT :: RealFloat a => Int -> [Complex a] -> [Complex a]\ndecimationFFT 1 x = x\ndecimationFFT n x =\n alternate (decimationFFT halfn a) (decimationFFT halfn b)\n where (a, b) = decimationUnit n x\n halfn = div n 2\n\n-- |Decimation inverse. Off by a constant and sign in the process.\ndecimationIFFT :: RealFloat a => Int -> [Complex a] -> [Complex a]\ndecimationIFFT 1 x = x\ndecimationIFFT n x =\n alternate (decimationIFFT halfn a) (decimationIFFT halfn b)\n where (a, b) = decimationIUnit n x\n halfn = div n 2\n\n-- TODO: Add testing features to show that it works.\n", "meta": {"hexsha": "f5e96885401cd3a96ee22fd162b614136c874b64", "size": 7159, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "josephmckinsey/simpleFFT", "max_stars_repo_head_hexsha": "372de9e59809fc7dc70ec1d2ec99e826fc4eb53e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "josephmckinsey/simpleFFT", "max_issues_repo_head_hexsha": "372de9e59809fc7dc70ec1d2ec99e826fc4eb53e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "josephmckinsey/simpleFFT", "max_forks_repo_head_hexsha": "372de9e59809fc7dc70ec1d2ec99e826fc4eb53e", "max_forks_repo_licenses": ["BSD-3-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.4816753927, "max_line_length": 88, "alphanum_fraction": 0.6255063556, "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6977958848417526}} {"text": "module Lib.Practice.P5\n (\n f5\n ) where\n\nimport Numeric.LinearAlgebra\nimport Lib.Utility\n\nf5 = do\n let sigmoid x = 1 / (1 + exp(-x))\n let calcA x w b = add b $ x <> w\n let x = (1><2) [1,0.5 :: Double]\n let w1 = (2><3) [0.1,0.3,0.5,0.2,0.4,0.6]\n let b1 = (1><3) [0.1,0.2,0.3]\n let a1 = calcA x w1 b1\n let z1 = cmap sigmoid a1\n print z1\n\n let w2 = (3><2) [0.1,0.4,0.2,0.5,0.3,0.6]\n let b2 = (1><2) [0.1,0.2]\n let a2 = calcA z1 w2 b2\n let z2 = cmap sigmoid a2\n print z2\n\n let w3 = (2><2) [0.1,0.3,0.2,0.4]\n let b3 = (1><2) [0.1,0.2]\n let a3 = calcA z2 w3 b3\n let y = a3\n print y\n\n let a4 = (1><3) [1010,1000,990 :: Double]\n print $ softmax' a4\n\nsoftmax' :: Matrix Double -> Matrix Double\nsoftmax' a = expA / sumExpA\n where (r, c) = size a\n maxs = col $ map maxElement $ toRows a\n expA = cmap exp $ a - maxs\n sumExpA = row $ map sumElements $ toRows expA\n", "meta": {"hexsha": "0b03eb8996904f764188f1f10c5c90aa88aeb88f", "size": 953, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib/Practice/P5.hs", "max_stars_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_stars_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T06:16:37.000Z", "max_issues_repo_path": "src/Lib/Practice/P5.hs", "max_issues_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_issues_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-01-04T02:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-09T12:39:40.000Z", "max_forks_repo_path": "src/Lib/Practice/P5.hs", "max_forks_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_forks_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T03:39:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T03:39:47.000Z", "avg_line_length": 23.825, "max_line_length": 55, "alphanum_fraction": 0.519412382, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6977914589103138}} {"text": "-- ch1 ex.1.23\n\nimport Statistics.Distribution.Normal \nimport qualified Statistics.Distribution as S\n\nnormalD :: NormalDistribution\nnormalD = normalDistr mean stdD\n where\n mean = 75\n stdD = 20\n\nmain :: IO () \nmain = do\n -- ratio greater than 95 sec:\n putStrLn $ \"the ratio of longer than 95 second: \" \n ++ show (S.complCumulative normalD 95)\n \n putStrLn $ \"Between 35 sec and 115 sec: \" \n ++ show ((S.complCumulative normalD 35) - (S.complCumulative normalD 115))\n\n putStrLn $ \"more than 2 min: \" \n ++ show (S.complCumulative normalD 120)\n \n\n\n", "meta": {"hexsha": "9253db9e7172b491c4950375014dc441ab81b24f", "size": 610, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ch01/ch1ex23.hs", "max_stars_repo_name": "raydsameshima/Stat", "max_stars_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch01/ch1ex23.hs", "max_issues_repo_name": "raydsameshima/Stat", "max_issues_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch01/ch1ex23.hs", "max_forks_repo_name": "raydsameshima/Stat", "max_forks_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": 23.4615384615, "max_line_length": 84, "alphanum_fraction": 0.6262295082, "num_tokens": 173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.7772998714925402, "lm_q1q2_score": 0.6977784415769064}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\n{-|\nModule : Numeric.QuadraticProgramming.PQP.Static\nDescription : Implementation of PQP QP solver using type level naturals\nCopyright : (c) Ryan Orendorff, 2020\nLicense : BSD3\nStability : experimental\n\nSolve a QP with positive definite hessian using the method known as Parallel\nQuadratic Programming (PQP).\n\nReference: Brand, Matthew, et al. \"A parallel quadratic programming algorithm for model predictive control.\" IFAC Proceedings Volumes 44.1 (2011): 1031-1039.\n\nLink: https://www.merl.com/publications/docs/TR2011-056.pdf\n-}\nmodule Numeric.QuadraticProgramming.PQP.Static\n ( pqp\n , dualToPrimalQPPoint\n )\nwhere\n\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Static\nimport Prelude hiding ( (<>) )\n\n\n-- | Solves the following quadratic program\n--\n-- \\[\n-- \\begin{aligned}\n-- \\min_x\\ \\ & \\tfrac{1}{2} x^TAx + c^Tx \\\\\n-- \\textrm{s.t}\\ \\ & B x \\leq d\n-- \\end{aligned}\n-- \\]\n--\n-- where \\(A\\) is positive definite and the primal problem above is feasible.\n--\n-- by solving the dual program with the following simple iterative update step.\n--\n-- \\[\n-- y_i \\leftarrow y_i \\left[\\frac{h_i^- + (Q^-y)_i}{h_i^+ + (Q^+y)_i}\\right]\n-- \\]\n--\n-- where\n--\n-- - \\(i\\) references the ith element of a vector.\n-- - \\(Q^+\\) is the positive elements of the hessian of the dual quadratic\n-- program (ie \\(Q^+ = \\textrm{max}(Q, 0) + diag(r), r \\succeq 0\\)).\n-- Similar statement for \\(Q^-\\) but with an absolute value.\n-- The \\(r\\) vector guarantees that the dual quadratic program is positive\n-- semidefinite after the thresholding, bounding the solution away from\n-- zero and infinity.\n-- - \\(h^+\\) is the positive elements of the dual linear cost component\n-- (\\(h^+ = \\textrm{max}(Q, 0)\\))\npqp\n :: (KnownNat m, KnownNat n)\n => L n n -- ^ Hessian of the quadratic program cost, \\(A\\)\n -> R n -- ^ Linear component of the quadratic program cost \\(c\\)\n -> L m n -- ^ Constraint matrix \\(B\\)\n -> R m -- ^ Constraint vector \\(d\\)\n -> [(R m, R n)] -- ^ Dual and primal iterations\n\n-- Initial guess must be > 0. Absent a better heuristic we use 1.\npqp a c b d = iterate update (konst 1, toPrimal (konst 1))\n where\n -- Lift max functions from operating on doubles to operating on vectors\n -- and matrices\n -- TODO: extract out into top level definition\n max0v = dvmap (max 0)\n max0m = dmmap (max 0)\n\n -- Convert to dual QP\n q = b <> (inv a) <> (tr b)\n h = d + (b <> (inv a)) #> c\n\n -- Need any r >= 0 in order to make the dual update step positive\n -- semidefinite.\n r = max0m (-q) #> konst 1\n\n hPlus = max0v h\n hMinus = max0v (-h)\n\n qPlus = max0m q + diag r\n qMinus = max0m (-q) + diag r\n\n toPrimal = dualToPrimalQPPoint a c b\n\n -- Normally this is written out for each element index individually,\n -- which makes this problem embarassingly parallel. However, we are not\n -- concerned about the parallelizability but that the algorithm is\n -- implemented correctly. There is a part that is not parallel (Q⁺y,\n -- Q⁻y), but ideally the matrix-vector multiply is fast.\n update (y, _) = let y' = y * ((hMinus + (qMinus #> y)) /\n (hPlus + (qPlus #> y)))\n in (y', toPrimal y')\n\n-- | Convert a point in the dual space to the primal space using the formula\n--\n-- \\[\n-- x = A^{-1} (c + B^T y)\n-- \\]\ndualToPrimalQPPoint\n :: (KnownNat m, KnownNat n)\n => L n n -- ^ Hessian of the quadratic program cost, \\(A\\)\n -> R n -- ^ Linear cost \\(c\\)\n -> L m n -- ^ Constraint matrix \\(B\\)\n -> R m -- ^ Dual value \\(y\\)\n -> R n -- ^ Primal value\ndualToPrimalQPPoint a c b y = (-(inv a #> (c + (tr b) #> y)))\n\n-- TODO: Define other direction (I suppose not as useful in this case)\n", "meta": {"hexsha": "5d98e85c99b32febf03915e86f0f21771981b327", "size": 4068, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/QuadraticProgramming/PQP/Static.hs", "max_stars_repo_name": "ryanorendorff/convex", "max_stars_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-06-13T21:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:53:28.000Z", "max_issues_repo_path": "src/Numeric/QuadraticProgramming/PQP/Static.hs", "max_issues_repo_name": "ryanorendorff/convex", "max_issues_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/QuadraticProgramming/PQP/Static.hs", "max_forks_repo_name": "ryanorendorff/convex", "max_forks_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9, "max_line_length": 157, "alphanum_fraction": 0.6189773845, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6977468617393461}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Backprop.Learn.Model.Function (\n -- * Statistics\n meanModel\n , varModel\n , stdevModel\n , rangeModel\n -- * Activation functions\n -- | See \n --\n -- ** Maps\n -- *** Unparameterized\n , step\n , logistic\n , softsign\n , reLU\n , softPlus\n , bentIdentity\n , siLU\n , softExponential\n , sinc\n , gaussian\n , tanh\n , atan\n , sin\n , vmap\n , vmap'\n -- *** Parameterized\n , liftUniform\n , isru\n , preLU\n , sreLU\n , sreLUPFP\n , eLU\n , isrLU\n , apl\n , aplPFP\n -- ** Mixing\n , softMax\n , maxout\n , kSparse\n ) where\n\nimport Control.Category\nimport Data.Foldable\nimport Data.Profunctor\nimport Data.Proxy\nimport Data.Type.Tuple\nimport GHC.TypeNats\nimport Numeric.Backprop\nimport Numeric.LinearAlgebra.Static.Backprop hiding (tr)\nimport Prelude hiding ((.), id)\nimport qualified Control.Foldl as F\nimport qualified Data.Vector.Sized as SV\nimport qualified Data.Vector.Storable.Sized as SVS\nimport qualified Numeric.LinearAlgebra as HU\nimport qualified Numeric.LinearAlgebra.Static as H\nimport qualified Numeric.LinearAlgebra.Static.Vector as H\n\nmeanModel\n :: (Backprop (t a), Foldable t, Functor t, Fractional a, Reifies s W)\n => BVar s (t a)\n -> BVar s a\nmeanModel = liftOp1 . op1 $ \\xs ->\n let x :# n = F.fold ((:#) <$> F.sum <*> F.length) xs\n in (x / fromIntegral n, \\d -> (d / fromIntegral n) <$ xs)\n\nvarModel\n :: (Backprop (t a), Foldable t, Functor t, Fractional a, Reifies s W)\n => BVar s (t a)\n -> BVar s a\nvarModel = liftOp1 . op1 $ \\xs ->\n let x2 :# x1 :# x0 = F.fold ((\\x2' x1' x0' -> x2' :# x1' :# x0') <$> lmap (^(2::Int)) F.sum <*> F.sum <*> F.length) xs\n meanx = x1 / fromIntegral x0\n subAll = 2 * x1 / (fromIntegral x0 ^ (2 :: Int))\n in ( (x2 / fromIntegral x0) - meanx * meanx\n , \\d -> let subAllD = d * subAll\n in (\\x -> d * 2 * x / fromIntegral x0 - subAllD) <$> xs\n )\n\nstdevModel\n :: (Backprop (t a), Foldable t, Functor t, Floating a, Reifies s W)\n => BVar s (t a)\n -> BVar s a\nstdevModel = sqrt . varModel\n\nrangeModel\n :: (Backprop (t a), Foldable t, Functor t, Ord a, Num a, Reifies s W)\n => BVar s (t a)\n -> BVar s a\nrangeModel = liftOp1 . op1 $ \\xs ->\n let mn :# mx = F.fold ((:#) <$> F.minimum <*> F.maximum) xs\n in case (:#) <$> mn <*> mx of\n Nothing -> errorWithoutStackTrace \"Backprop.Learn.Model.Function.range: empty range\"\n Just (mn' :# mx') ->\n ( mx' - mn'\n , \\d -> (\\x -> if | x == mx' -> d\n | x == mn' -> -d\n | otherwise -> 0\n ) <$> xs\n )\n\n\n-- | Softmax normalizer\nsoftMax\n :: (KnownNat i, Reifies s W)\n => BVar s (R i)\n -> BVar s (R i)\nsoftMax x = expx / konst (norm_1V expx)\n where\n expx = exp x\n\n-- | Logistic function\n--\n-- \\[\n-- \\sigma(x) = \\frac{1}{1 + e^{-x}}\n-- \\]\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\n-- | Binary step / heaviside step\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- \\[\n-- \\begin{cases}\n-- 0 & \\text{for } x < 0 \\\\\n-- 1 & \\text{for } x \\ge 0\n-- \\end{cases}\n-- \\]\nstep :: (Ord a, Num a) => a -> a\nstep x | x < 0 = 0\n | otherwise = 1\n\n-- | Softsign activation function\n--\n-- \\[\n-- \\frac{x}{1 + \\lvert x \\rvert}\n-- \\]\nsoftsign :: Fractional a => a -> a\nsoftsign x = x / (1 + abs x)\n\n-- | Inverse square root unit\n--\n-- \\[\n-- \\frac{x}{\\sqrt{1 + \\alpha x^2}}\n-- \\]\n--\n-- See 'liftUniform' to make this compatible with 'PFP'.\n--\n-- You can also just use this after partially applying it, to fix the\n-- parameter (and not have it trained).\nisru\n :: Floating a\n => a -- ^ α (scaling parameter)\n -> a -- ^ x\n -> a\nisru α x = x / sqrt (1 + α * x * x)\n\n-- | Rectified linear unit.\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n--\n-- \\[\n-- \\max(0,x)\n-- \\]\n--\n-- @\n-- 'reLU' = 'preLU' 0\n-- @\n--\nreLU :: (Num a, Ord a) => a -> a\nreLU x | x < 0 = 0\n | otherwise = x\n\n-- | Parametric rectified linear unit\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- If scaling parameter is a fixed (and not learned) parameter, this is\n-- typically called a leaky recitified linear unit (typically with\n-- α = 0.01).\n--\n-- To use as a learned parameter:\n--\n-- @\n-- 'vmap' . 'preLU' :: 'BVar' s Double -> 'BVar' s ('R' n) -> BVar s (R n)\n-- @\n--\n-- This can be give directly to 'PFP'.\n--\n-- To fix the paramater (\"leaky\"), just partially apply a parameter:\n--\n-- @\n-- 'preLU' 0.01 :: 'BVar' s ('R' n) -> BVar s (R n)\n-- preLU ('realToFrac' α) :: BVar s (R n) -> BVar s (R n)\n-- @\n--\n-- See also 'rreLU'.\n--\n-- \\[\n-- \\begin{cases}\n-- \\alpha x & \\text{for } x < 0 \\\\\n-- x & \\text{for } x \\ge 0\n-- \\end{cases}\n-- \\]\npreLU\n :: (Num a, Ord a)\n => a -- ^ α (scaling parameter)\n -> a -- ^ x\n -> a\npreLU α x | x < 0 = α * x\n | otherwise = x\n\n-- | Exponential linear unit\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- To use as a learned parameter:\n--\n-- @\n-- 'vmap' . 'eLU' :: 'BVar' s Double -> 'BVar' s ('R' n) -> BVar s (R n)\n-- @\n--\n-- This can be give directly to 'PFP'.\n--\n-- To fix the paramater, just partially apply a parameter:\n--\n-- @\n-- 'vmap'' ('eLU' 0.01) :: 'BVar' s ('R' n) -> BVar s (R n)\n-- @\n--\n-- \\[\n-- \\begin{cases}\n-- \\alpha (e^x - 1) & \\text{for } x < 0 \\\\\n-- x & \\text{for } x \\ge 0\n-- \\end{cases}\n-- \\]\neLU :: (Floating a, Ord a)\n => a -- ^ α (scaling parameter)\n -> a -- ^ x\n -> a\neLU α x | x < 0 = α * (exp x - 1)\n | otherwise = x\n\n-- | S-shaped rectified linear activiation unit\n--\n-- See 'sreLUPFP' for an uncurried and uniformly lifted version usable with\n-- 'PFP'.\n--\n-- \\[\n-- \\begin{cases}\n-- t_l + a_l (x - t_l) & \\text{for } x \\le t_l \\\\\n-- x & \\text{for } t_l < x < t_r \\\\\n-- t_r + a_r (x - t_r) & \\text{for } x \\ge t_r\n-- \\end{cases}\n-- \\]\nsreLU\n :: (Num a, Ord a)\n => a -- ^ @t_l@\n -> a -- ^ @a_l@\n -> a -- ^ @t_r@\n -> a -- ^ @a_l@\n -> a -- ^ @x@\n -> a\nsreLU tl al tr ar x\n | x < tl = tl + al * (x - tl)\n | x > tr = tr + ar * (x - tr)\n | otherwise = x\n\n-- | An uncurried and uniformly lifted version of 'sreLU' directly usable\n-- with 'PFP'.\nsreLUPFP\n :: (KnownNat n, Reifies s W)\n => BVar s ((Double :# Double) :# (Double :# Double))\n -> BVar s (R n)\n -> BVar s (R n)\nsreLUPFP ((tl :## al) :## (tr :## ar)) = vmap (sreLU tl al tr ar)\n\n-- | Inverse square root linear unit\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- \\[\n-- \\begin{cases}\n-- \\frac{x}{1 + \\alpha x^2} & \\text{for } x < 0 \\\\\n-- x & \\text{for } x \\ge 0\n-- \\end{cases}\n-- \\]\nisrLU\n :: (Floating a, Ord a)\n => a -- ^ α\n -> a -- ^ x\n -> a\nisrLU α x\n | x < 0 = x / sqrt (1 + α * x * x)\n | otherwise = x\n\n-- | Adaptive piecewise linear activation unit\n--\n-- See 'aplPFP' for an uncurried version usable with 'PFP'.\n--\n-- \\[\n-- \\max(0, x_i) + \\sum_j^M a_i^j \\max(0, -x_i + b_i^j)\n-- \\]\napl :: (KnownNat n, KnownNat m, Reifies s W)\n => BVar s (L n m) -- ^ a\n -> BVar s (L n m) -- ^ b\n -> BVar s (R m) -- ^ x\n -> BVar s (R m)\napl as bs x = vmap' (max 0) x\n + sum (toRows (as * (bs - fromRows (SV.replicate x))))\n\n-- | 'apl' uncurried, to be directly usable with 'PFP'.\naplPFP\n :: (KnownNat n, KnownNat m, Reifies s W)\n => BVar s (L n m :# L n m)\n -> BVar s (R m)\n -> BVar s (R m)\naplPFP (a :## b) = apl a b\n\n-- | SoftPlus\n--\n-- \\[\n-- \\ln(1 + e^x)\n-- \\]\nsoftPlus :: Floating a => a -> a\nsoftPlus x = log (1 + exp x)\n\n-- | Bent identity\n--\n-- \\[\n-- \\frac{\\sqrt{x^2 + 1} - 1}{2} + x\n-- \\]\nbentIdentity :: Floating a => a -> a\nbentIdentity x = (sqrt (x * x + 1) - 1) / 2 + x\n\n-- | Sigmoid-weighted linear unit. Multiply 'logistic' by its input.\n--\n-- \\[\n-- x \\sigma(x)\n-- \\]\nsiLU :: Floating a => a -> a\nsiLU x = x * logistic x\n\n-- | SoftExponential\n--\n-- To use with vectors ('R'), use 'vmap''.\n--\n-- \\[\n-- \\begin{cases}\n-- - \\frac{\\ln(1 - \\alpha (x + \\alpha))}{\\alpha} & \\text{for } \\alpha < 0 \\\\\n-- x & \\text{for } \\alpha = 0 \\\\\n-- \\frac{e^{\\alpha x} - 1}{\\alpha} + \\alpha & \\text{for } \\alpha > 0\n-- \\end{cases}\n-- \\]\nsoftExponential\n :: (Floating a, Ord a)\n => a -- ^ α\n -> a -- ^ x\n -> a\nsoftExponential α x = case compare α x of\n LT -> - log (1 - α * (x + α)) / α\n EQ -> x\n GT -> (exp (α * x) - 1) / α + α\n\n-- | Sinc\n--\n-- \\[\n-- \\begin{cases}\n-- 1 & \\text{for } x = 0 \\\\\n-- \\frac{\\sin(x)}{x} & \\text{for } x \\ne 0\n-- \\end{cases}\n-- \\]\nsinc :: (Floating a, Eq a) => a -> a\nsinc 0 = 1\nsinc x = sin x / x\n\n-- | Gaussian\n--\n-- \\[\n-- e^{-x^2}\n-- \\]\ngaussian :: Floating a => a -> a\ngaussian x = exp (- (x * x))\n\n-- | Maximum of vector.\n--\n-- Compare to 'norm_InfV', which gives the maximum absolute value.\nmaxout :: (KnownNat n, Reifies s W) => BVar s (R n) -> BVar s Double\nmaxout = liftOp1 . op1 $ \\x ->\n let n = HU.maxElement . H.extract $ x\n in ( n\n , \\d -> H.vecR . SVS.map (\\e -> if e == n then d else 0) . H.rVec $ x\n )\n\n-- | Usable with functions like '*', 'isru', etc. to turn them into a form\n-- usable with 'PFP':\n--\n-- @\n-- 'liftUniform' ('*') :: 'BVar' s 'Double' -> BVar s ('R' n) -> BVar s (R n)\n-- liftUniform 'isru' :: BVar s Double -> BVar s (R n) -> BVar s (R n)\n-- @\n--\n-- Basically turns a parmaeterized function on individual elements of\n-- into one that shares the same parameter across all elements of the\n-- vector.\nliftUniform\n :: (Reifies s W, KnownNat n)\n => (BVar s (R n) -> r)\n -> BVar s Double\n -> r\nliftUniform f = f . konst\n\n-- -- TODO: vmap can do better.\n\n-- | Keep only the top @k@ values, and zero out all of the rest.\n--\n-- Useful for postcomposing in between layers (with a logistic function\n-- before) to encourage the number of \"activated\" neurons is kept to be\n-- around @k@. Used in k-Sprase autoencoders (see 'KAutoencoder').\n--\n-- \nkSparse\n :: forall n s. (Reifies s W, KnownNat n)\n => Int -- ^ number of items to keep\n -> BVar s (R n)\n -> BVar s (R n)\nkSparse k = liftOp1 . op1 $ \\xs ->\n let xsSort = HU.sortVector (H.extract xs)\n thresh = xsSort `HU.atIndex` (n - k)\n mask = H.dvmap (\\x -> if x >= thresh then 1 else 0) xs\n in ( H.dvmap (\\x -> if x >= thresh then x else 0) xs\n , (* mask)\n )\n where\n n = fromIntegral $ natVal (Proxy @n)\n", "meta": {"hexsha": "4f5277ca584c2f9c17a4af91ef03b59ec037e887", "size": 11553, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Backprop/Learn/Model/Function.hs", "max_stars_repo_name": "mstksg/backprop-learn", "max_stars_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2017-03-14T08:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T13:41:33.000Z", "max_issues_repo_path": "src/Backprop/Learn/Model/Function.hs", "max_issues_repo_name": "mstksg/backprop-learn", "max_issues_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-06T01:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-06T01:01:46.000Z", "max_forks_repo_path": "src/Backprop/Learn/Model/Function.hs", "max_forks_repo_name": "mstksg/backprop-learn", "max_forks_repo_head_hexsha": "59aea530a0fad45de6d18b9a723914d1d66dc222", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-05-23T22:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:18.000Z", "avg_line_length": 25.3355263158, "max_line_length": 122, "alphanum_fraction": 0.504371159, "num_tokens": 3903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6975771822608503}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n---------------------------------------------------------------------------------\n-- |\n-- Module : Amby.Numeric\n-- Copyright : (C) 2016 Justin Sermeno\n-- License : BSD3\n-- Maintainer : Justin Sermeno\n--\n-- Functions for working with numerical ranges and statistics.\n---------------------------------------------------------------------------------\nmodule Amby.Numeric\n ( -- * Ranges\n contDistrDomain\n , contDistrRange\n , linspace\n , arange\n , random\n\n -- * Frequencies\n , scoreAtPercentile\n , interquartileRange\n , freedmanDiaconisBins\n\n ) where\n\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector as V\n\nimport Statistics.Distribution\nimport qualified Statistics.Quantile as Stats\nimport System.Random.MWC (withSystemRandom, asGenST)\n\n-- $setup\n-- >>> let demoData = V.fromList $ concat $ zipWith replicate [5, 4, 3, 7] [0..3]\n\n---------------------\n-- Ranges\n---------------------\n\n-- | @contDistrDomain d n@ generates a domain of 'n' evenly spaced points\n-- for the continuous distribution 'd'.\ncontDistrDomain :: (ContDistr d) => d -> Int -> U.Vector Double\ncontDistrDomain d num = linspace (quantile d 0.0001) (quantile d 0.9999) num\n\n-- | @contDistrRange d xs@ generates the pdf value of the continious distribution\n-- 'd' for each value in 'xs'.\ncontDistrRange :: (ContDistr d) => d -> U.Vector Double -> U.Vector Double\ncontDistrRange d x = U.map (density d) x\n\n-- | @linspace s e n@ generates 'n' evenly spaced values between ['s', 'e'].\nlinspace :: Double -> Double -> Int -> U.Vector Double\nlinspace start stop num\n | num < 0 = error (\"Number of samples, \" ++ show num ++ \", must be non-negative.\")\n | num == 0 || num == 1 = addStart $ U.generate num ((* delta) . fromIntegral)\n | otherwise = addStart $ U.generate num ((* step) . fromIntegral)\n where\n delta = stop - start\n step = delta / fromIntegral (num - 1)\n addStart = U.map (realToFrac . (+ start))\n\n-- | @arange s e i@ generates numbers between ['s', 'e'] spaced by amount 'i'.\n-- 'arange' is the equivalent of haskell's range notation except that it generates\n-- a 'Vector'. As a result, the last element may be greater than less than, or\n-- greater than the stop point.\narange :: Double -> Double -> Double -> U.Vector Double\narange start stop step = U.fromList [start,(start + step)..stop]\n\n-- | Generates an unboxed vectors of random numbers from a distribution\n-- that is an instance of 'ContGen'. This function is meant for ease of use\n-- and is expensive.\nrandom :: (ContGen d) => d -> Int -> IO (U.Vector Double)\nrandom d n = withSystemRandom . asGenST $ \\gen ->\n U.replicateM n $ genContVar d gen\n\n---------------------\n-- Frequencies\n---------------------\n\n-- | @scoreAtPercentile xs p@ calculates the score at percentile 'p'.\n--\n-- Examples:\n--\n-- >>> let a = arange 0 99 1\n--\n-- >>> scoreAtPercentile a 50\n-- 49.5\nscoreAtPercentile :: (G.Vector v Double) => v Double -> Int -> Double\nscoreAtPercentile xs p\n | G.length xs == 0 =\n modErr \"scoreAtPercentile\" \"Cannot find percentile of empyt list\"\n | otherwise = Stats.weightedAvg p 100 xs\n\n-- | Calculate the interquartile range.\n--\n-- Examples:\n--\n-- >>> interquartileRange demoData\n-- 2.5\ninterquartileRange :: (G.Vector v Double) => v Double -> Double\ninterquartileRange xs = scoreAtPercentile xs 75 - scoreAtPercentile xs 25\n{-# SPECIALIZE interquartileRange :: U.Vector Double -> Double #-}\n{-# SPECIALIZE interquartileRange :: V.Vector Double -> Double #-}\n\n-- | Estimate a good default bin size.\n--\n-- Examples:\n--\n-- >>> freedmanDiaconisBins demoData\n-- 2\nfreedmanDiaconisBins :: (G.Vector v Double) => v Double -> Int\nfreedmanDiaconisBins xs =\n if h == 0\n then floor $ sqrt $ (fromIntegral n :: Double)\n else ceiling $ (G.maximum xs - G.minimum xs) / h\n where\n n = G.length xs\n h = 2 * interquartileRange xs / fromIntegral n ** (1 / 3)\n\nmodErr :: String -> String -> a\nmodErr f err = error\n $ showString \"Amby.Numeric.\"\n $ showString f\n $ showString \": \" err\n", "meta": {"hexsha": "15d08de9c09567e10124b40cacfd2a55ce13d812", "size": 4064, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Amby/Numeric.hs", "max_stars_repo_name": "jsermeno/amby", "max_stars_repo_head_hexsha": "3c73501c75926eca8f3f7cc4274bc7751fc49788", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-10-25T06:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T21:09:10.000Z", "max_issues_repo_path": "src/Amby/Numeric.hs", "max_issues_repo_name": "jsermeno/amby", "max_issues_repo_head_hexsha": "3c73501c75926eca8f3f7cc4274bc7751fc49788", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Amby/Numeric.hs", "max_forks_repo_name": "jsermeno/amby", "max_forks_repo_head_hexsha": "3c73501c75926eca8f3f7cc4274bc7751fc49788", "max_forks_repo_licenses": ["BSD-3-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.512, "max_line_length": 84, "alphanum_fraction": 0.6355807087, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6975771773438147}} {"text": "module Main where\n\n\nimport System.IO\nimport Graphics.Gnuplot.Simple\nimport Numeric.LinearAlgebra\n\n\n\ndata DefIntegral a = DefIntegral (a->a) a a\n\n\n--instance Show DefIntegral where\n-- show (DefIntegral _ start end) = \"Integral from\" ++ show a ++ \"to\" ++ show b\n\n\n--mixed :: (Enum a, Field a) => DefIntegral a -> a -> a -> a\n--mixed (DefIntegral f start end) alpha steps =\n-- sum $ map (\\x -> x) (intervals start end steps)\n\naitken :: (Enum a, Field a, RealFrac a, Num a)\n => DefIntegral a\n -> a\n -> (DefIntegral a -> a -> a -> a)\n -> a\n -> (a, (a, a, a))\naitken integral@(DefIntegral _ a b) alpha method initial_step =\n let [s1, s2, s3] = map (method integral alpha) [1, 2, 4]\n error = 10**(-6)\n l = 2\n m = - log (abs $ (s3 - s2)/(s2 - s1)) / log l\n optimal_step = (b-a) * (abs (error * (1 - (b-a)**(-m) / (s2 - s1))))**(1/m)\n in (optimal_step, residue integral alpha method optimal_step)\n\n\nresidue1 :: (Enum a, Field a, RealFrac a, Ord a)\n => DefIntegral a\n -> a\n -> (DefIntegral a -> a -> a -> a)\n -> (a, a, a)\nresidue1 defintegral alpha method = residue defintegral alpha method 1\n\n\n-- richardson method with r=2\n-- returns tuple of integral value, residue and required step\nresidue :: (Enum a, Field a, RealFrac a, Ord a)\n => DefIntegral a\n -> a\n -> (DefIntegral a -> a -> a -> a)\n -> a\n -> (a, a, a)\nresidue (DefIntegral f start end) alpha method initial_step =\n let steps_from_step step = fromIntegral . floor $ (end - start) / step + 1\n quadrature step = method (DefIntegral f start end) alpha (steps_from_step step)\n find_m [s1, s2, s3] = - log (abs $ (s3 - s2)/(s2 - s1)) / log l\n error = 10**(-6)\n l = 2.0\n steps_ = [initial_step / l**i | i<-[0..]]\n\n iter steps =\n -- find vector (J, Cm, Cm+1, ...) and take J from it\n let steps' = (3><1) $ take 3 steps\n rhs = cmap quadrature steps'\n m = find_m . toList . flatten $ rhs\n lhs = (3><1) [1, 1, 1] ||| cmap (**m) steps' ||| cmap (**(m+1)) steps'\n integral = (lhs <\\> rhs) `atIndex` (0, 0)\n res = integral - (rhs `atIndex` (2, 0))\n in (integral, res)\n find_residue steps =\n if abs res < error\n then (integral, res, steps !! 2)\n else find_residue (tail steps)\n where (integral, res) = iter steps\n in find_residue steps_\n\n\ncardano :: (Field a) => a -> a -> a -> a -> [a]\ncardano a b c d =\n let p = c/a - b**2/(3*a**2)\n q = 2*b**3 / (27*a**3) - b*c/(3*a**2) + d/a\n phi = acos(3*q/(2*p) * sqrt(-3/p))\n y1 = 2*sqrt(-p/3) * cos(phi/3)\n y2 = 2*sqrt(-p/3) * cos(phi/3 + 2*pi/3)\n y3 = 2*sqrt(-p/3) * cos(phi/3 - 2*pi/3)\n in [y1 - b/(3*a), y2 - b/(3*a), y3 - b/(3*a)]\n\n\ngauss_helper :: (Enum a, Field a) => DefIntegral a -> a -> (a, a) -> a\ngauss_helper (DefIntegral f start end) alpha (left, right) =\n let -- 0) substition\n left' = end - left\n right' = end - right\n avg' = (right' + left') / 2\n f' x = f $ end - x\n\n -- 1) find weights\n weight n = - (right'**(n-alpha+1) - left'**(n-alpha+1)) / (n-alpha+1)\n\n --2) solve linear system for a's\n ws_lhs = (3><3)\n [ weight 0, weight 1, weight 2\n , weight 1, weight 2, weight 3\n , weight 2, weight 3, weight 4]\n\n ws_rhs = (3><1)\n [ -weight 3\n , -weight 4\n , -weight 5]\n\n coefs_a = ws_lhs <\\> ws_rhs\n\n -- 3) solve 3-order equation for xs\n [d, c, b] = toList . flatten $ coefs_a\n xs = (1><3) $ cardano 1 b c d\n\n -- 4) solve linear system for A's\n helper_lhs = (1><3) [1, 1, 1] === xs === cmap (**2) xs\n helper_rhs = (3><1)\n [ weight 0\n , weight 1\n , weight 2]\n coefs_A = helper_lhs <\\> helper_rhs\n\n -- then sum Ai*fi\n fs = cmap f' xs\n result_vector = fs <> coefs_A\n [[result]] = toLists result_vector\n in result\n\n\ngauss :: (Enum a, Field a) => DefIntegral a -> a -> a -> a\ngauss integral@(DefIntegral f start end) alpha steps =\n sum $ map (gauss_helper integral alpha) (intervals start end steps)\n\n\ngeneral_nc_helper :: (Enum a, Field a) => Int -> DefIntegral a -> a -> (a, a) -> a\ngeneral_nc_helper order (DefIntegral f start end) alpha (left, right) =\n let -- substitution\n left' = end - left\n right' = end - right\n f' x = f $ end - x\n\n xs = linspace order (end-left, end-right)\n fs = asColumn $ cmap f' xs\n\n weight n = - (right'**(n-alpha+1) - left'**(n-alpha+1)) / (n-alpha+1)\n\n weights = cmap weight $ (order><1) [0..toEnum order-1]\n\n xs_matrix = (order> weights\n result_vector = a_coefs <> fs\n\n [[result]] = toLists result_vector\n in result\n\n\nnewton_cotes_helper :: (Enum a, Field a) => DefIntegral a -> a -> (a, a) -> a\nnewton_cotes_helper (DefIntegral f start end) alpha (left, right) =\n let -- substitution\n left' = end - left\n right' = end - right\n avg' = (right' + left') / 2\n f' x = f $ end - x\n\n weight n = - (right'**(n-alpha+1) - left'**(n-alpha+1)) / (n-alpha+1)\n\n weights = (3><1) [weight 0, weight 1, weight 2]\n\n xs = (3><3)\n [ 1, 1, 1\n , left', avg', right'\n , left'**2, avg'**2, right'**2]\n\n fs = (3><1) [f' left', f' avg', f' right']\n\n a_coefs = tr $ xs <\\> weights\n\n result_vector = a_coefs <> fs\n in result_vector `atIndex` (0, 0)\n\n\n--alpha is power of p(x)\nnewton_cotes :: (Enum a, Field a) => DefIntegral a -> a -> a -> a\nnewton_cotes integral@(DefIntegral f start end) alpha steps =\n sum $ map (general_nc_helper 3 integral alpha) (intervals start end steps)\n\n\n-- mixed with same degree=5\nmixed1 :: (Enum a, Field a) => DefIntegral a -> a -> a -> a\nmixed1 integral@(DefIntegral f start end) alpha steps =\n sum . map (\\(interval, i) -> helper interval i) $ zip (intervals start end steps) [1..]\n where helper interval i = if odd i\n then general_nc_helper 6 integral alpha interval\n else gauss_helper integral alpha interval\n\n-- mixed with different degrees: gauss with 5 and nc with 2\nmixed2 :: (Enum a, Field a) => DefIntegral a -> a -> a -> a\nmixed2 integral@(DefIntegral f start end) alpha steps =\n sum . map (\\(interval, i) -> helper interval i) $ zip (intervals start end steps) [1..]\n where helper interval i = if odd i\n then general_nc_helper 3 integral alpha interval\n else gauss_helper integral alpha interval\n\nleft_sum :: (Fractional a, Num a, Enum a) => DefIntegral a -> a -> a\nleft_sum (DefIntegral f start end) steps =\n sum . map (\\(left, right) -> (right - left) * (f left)) $ intervals start end steps\n\n\naverage_sum :: (Fractional a, Num a, Enum a) => DefIntegral a -> a -> a\naverage_sum (DefIntegral f start end) steps =\n sum . map (\\(left, right) -> (right - left) * (f $ (left + right) / 2)) $ intervals start end steps\n\n\ntrapezoid_sum :: (Fractional a, Num a, Enum a) => DefIntegral a -> a -> a\ntrapezoid_sum (DefIntegral f start end) steps =\n sum . map (\\(left, right) -> (right - left) * (f right + f left) / 2) $ intervals start end steps\n\n\nsimpson_sum :: (Fractional a, Num a, Enum a) => DefIntegral a -> a -> a\nsimpson_sum (DefIntegral f start end) steps =\n halfstep / 3 * (sum . map (\\(left, middle, right) -> f left + 4 * f middle + f right) $ interv)\n where step = (end - start) / steps\n halfstep = step / 2\n segment = [start + halfstep, start + 3*halfstep .. end - halfstep]\n interv = map (\\x -> (x - halfstep, x, x + halfstep)) segment\n\n\nsimpsons :: (Fractional a, Num a) => DefIntegral a -> a\nsimpsons (DefIntegral f start end) =\n (end - start) / 6 * (f start + 4 * f ((start + end) / 2) + f end)\n\n\nintervals :: (Fractional a, Num a, Enum a) => a -> a -> a -> [(a, a)]\nintervals start end n_intervals =\n zip intervals' (tail intervals')\n where intervals' = [start, start + step .. end - step] ++ [end]\n -- add end to the end to escape problems with floating point arithmetics\n step = (end - start) / n_intervals\n\n\ntests :: IO ()\ntests = do\n putStrLn \"hello world\"\n -- let a = 0 :: Double\n -- let b = 10\n -- let func = \\x -> x\n let func = \\x -> 3.7 * cos(1.5 * x) * exp(-4*x / 3) + 2.4 * sin(4.5 * x) * exp(2*x / 3) + 4\n let a = 1.8 :: Double\n let b = 2.3\n\n let integral = DefIntegral func a b\n let test_input = [2, 3, 5, 10, 50, 100, 200]\n\n let test method = map (method integral) test_input\n let test2 method = map (method integral 0.6) test_input\n\n putStrLn $ \"steps: \" ++ show test_input\n putStrLn $ \"newton-cotes: \" ++ show (test2 newton_cotes)\n putStrLn $ \"gauss: \" ++ show (test2 gauss)\n putStrLn $ \"mixed1: \" ++ show (test2 mixed1)\n putStrLn $ \"mixed2: \" ++ show (test2 mixed2)\n putStrLn \"------------------------------\\n\"\n -- should be 1.18515\n putStrLn $ \"left_sum: \" ++ show (test left_sum)\n putStrLn $ \"avg_sum: \" ++ show (test average_sum)\n putStrLn $ \"trap_sum: \" ++ show (test trapezoid_sum)\n putStrLn $ \"simpsons: \" ++ show (test simpson_sum)\n\n putStrLn $ \"\\n##########################\\n\"\n\n let residue_test method = residue1 integral 0.6 method\n\n putStrLn $ \"residue newton_cotes: \" ++ show (residue_test newton_cotes)\n putStrLn $ \"residue gauss: \" ++ show (residue_test gauss)\n putStrLn $ \"residue mixed1: \" ++ show (residue_test mixed1)\n putStrLn $ \"residue mixed2: \" ++ show (residue_test mixed2)\n\n let aitken_gauss_test = aitken integral 0.6 gauss 0.1\n let (opt_step, aitken_result) = aitken_gauss_test\n putStrLn $ \"optimal step = \" ++ show opt_step\n putStrLn $ \"aitken gauss: \" ++ show aitken_result\n\n\nplots :: IO()\nplots = do\n let func = \\x -> 3.7 * cos(1.5 * x) * exp(-4*x / 3) + 2.4 * sin(4.5 * x) * exp(2*x / 3) + 4\n let a = 1.8 :: Double\n let b = 2.3\n let integral = DefIntegral func a b\n let steps = [3.0,4.0..500]\n\n let integral_value = 2.37880192961486\n --let integral_value = 1.18515\n\n let map_left = map (left_sum integral) steps\n let map_avg = map (average_sum integral) steps\n let map_trap = map (trapezoid_sum integral) steps\n let map_simps = map (simpson_sum integral) steps\n\n let map_nc = map (newton_cotes integral 0.6) steps\n let map_gauss = map (gauss integral 0.6) steps\n\n let left = zip steps $ map (-integral_value+) map_left\n let avg = zip steps $ map (-integral_value+) map_avg\n let trap = zip steps $ map (-integral_value+) map_trap\n let simps = zip steps $ map (-integral_value+) map_simps\n --plotList [] $ zip steps $ map (-integral_value+) map_nc\n --plotList [] $ zip steps $ map (-integral_value+) map_gauss\n\n let helper values name = (defaultStyle {lineSpec = CustomStyle [LineTitle name]}, values)\n plotListsStyle [Title \"Comparacent of different quadrature methods\"]\n [ helper left \"left\"\n , helper avg \"avg\"\n , helper trap \"trapezoid\"\n , helper simps \"simpson\"]\n\n\noutputToFile :: IO()\noutputToFile = do\n let func = \\x -> 3.7 * cos(1.5 * x) * exp(-4*x / 3) + 2.4 * sin(4.5 * x) * exp(2*x / 3) + 4\n let a = 1.8 :: Double\n let b = 2.3\n let integral = DefIntegral func a b\n let steps = [3.0,4.0..500]\n\n let integral_value = 2.37880192961486\n\n let map_left = map (left_sum integral) steps\n let map_avg = map (average_sum integral) steps\n tests\n\n file <- openFile \"outputnc.txt\" WriteMode\n --hPutStrLn file (\"integral_result = \" ++ show integral_value ++ \"\\n\")\n --hPutStrLn file (\"steps = \" ++ (show steps) ++ \"\\n\")\n --hPutStrLn file (\"left_sum = \" ++ (show $ map (left_sum integral) steps) ++ \"\\n\")\n --hPutStrLn file (\"avg_sum = \" ++ (show $ map (average_sum integral) steps) ++ \"\\n\")\n --hPutStrLn file (\"trap_sum = \" ++ (show $ map (trapezoid_sum integral) steps) ++ \"\\n\")\n hPutStrLn file (\"simpson_sum = \" ++ (show $ map (simpson_sum integral) steps) ++ \"\\n\")\n --hPutStrLn file (\"newton_cotes_sum = \" ++ (show $ map (newton_cotes integral 0.6) steps) ++ \"\\n\")\n hClose file\n\n\nmain :: IO ()\nmain = do\n --outputToFile\n tests\n", "meta": {"hexsha": "03da3b6c7f5f573916e2b741a2a7ff653b806c14", "size": 11943, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "zykt/quadratures", "max_stars_repo_head_hexsha": "92525e419cd77da3d5126a51211dae32669aae3f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "zykt/quadratures", "max_issues_repo_head_hexsha": "92525e419cd77da3d5126a51211dae32669aae3f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "zykt/quadratures", "max_forks_repo_head_hexsha": "92525e419cd77da3d5126a51211dae32669aae3f", "max_forks_repo_licenses": ["BSD-3-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.2206303725, "max_line_length": 101, "alphanum_fraction": 0.5879594742, "num_tokens": 3933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.697201768839533}} {"text": "{-# LANGUAGE OverloadedStrings #-}\nmodule Numeric.Clustering.Perplexity where\n\nimport qualified Data.Massiv.Array as MA\nimport qualified Numeric.NLOPT as NLOPT\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Control.Monad.Catch as X\nimport qualified Data.Text as Text\nimport Numeric (log)\n\npGivenBeta :: MA.Source r MA.Ix1 Double => MA.Ix1 -> MA.Vector r Double -> Double -> MA.Vector MA.D Double\npGivenBeta rowIndex distances beta =\n let scale ci d = if (ci == rowIndex) then 0 else exp (-d * beta)\n raw = MA.imap scale distances\n sumRaw = MA.sum raw\n in raw MA..* (1 / sumRaw)\n\nsafe_xLogx :: Double -> Double\nsafe_xLogx x = if x > 1e-7 then x * log x else 0\n\nentropy :: MA.Source r MA.Ix1 Double => MA.Vector r Double -> MA.Ix1 -> Double -> Double\nentropy distances rowIndex beta = MA.sum $ MA.map (\\x -> negate $ safe_xLogx x) $ pGivenBeta rowIndex distances beta\n\nfindBeta :: MA.Source r MA.Ix1 Double => Double -> MA.Ix1 -> MA.Vector r Double -> Either Text.Text Double\nfindBeta perplexity rowIndex distances =\n let targetEntropy = log perplexity\n obj x = abs (targetEntropy - entropy distances rowIndex (x `LA.atIndex` 0))\n algo = NLOPT.NELDERMEAD obj [] Nothing\n stopWhenAny = NLOPT.ObjectiveAbsoluteTolerance 1e-4 NLOPT.:|\n [NLOPT.MaximumEvaluations 50\n ]\n problem = NLOPT.LocalProblem 1 stopWhenAny algo\n optimizedE = NLOPT.minimizeLocal problem (LA.fromList [1])\n textError sol = (Text.pack $ show $ NLOPT.solutionResult sol)\n <> \": x = \"\n <> (Text.pack $ show $ NLOPT.solutionParams sol)\n <> \"; obj(x) = \"\n <> (Text.pack $ show $ NLOPT.solutionCost sol)\n in case optimizedE of\n Left r -> Left $ Text.pack $ show r\n Right s -> case NLOPT.solutionResult s of\n NLOPT.FTOL_REACHED -> Right $ (`LA.atIndex` 0) $ NLOPT.solutionParams s\n _ -> Left $ textError s\n\ndata SolveException = SolveException Text.Text deriving (Show)\ninstance X.Exception SolveException\n\nprobabilities :: MA.MonadThrow m => Double -> MA.Matrix MA.U Double -> m (MA.Matrix MA.U Double)\nprobabilities perplexity distances = do\n let distanceRows = MA.computeAs MA.B $ MA.outerSlices distances\n betaSolsE :: Either Text.Text (MA.Vector MA.U Double)\n betaSolsE = MA.itraverseA (\\ix v -> findBeta perplexity ix v) distanceRows\n betas <- case betaSolsE of\n Left err -> X.throwM (SolveException err)\n Right x -> return x\n fmap MA.compute $ MA.stackOuterSlicesM $ MA.izipWith pGivenBeta distanceRows betas\n", "meta": {"hexsha": "61952200ea5800b5c2cf3199440e920df55e7b87", "size": 2591, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Clustering/Perplexity.hs", "max_stars_repo_name": "adamConnerSax/data-science-utils", "max_stars_repo_head_hexsha": "cedfd4041c26a85fb94199c634da4a1f179c2905", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Clustering/Perplexity.hs", "max_issues_repo_name": "adamConnerSax/data-science-utils", "max_issues_repo_head_hexsha": "cedfd4041c26a85fb94199c634da4a1f179c2905", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Clustering/Perplexity.hs", "max_forks_repo_name": "adamConnerSax/data-science-utils", "max_forks_repo_head_hexsha": "cedfd4041c26a85fb94199c634da4a1f179c2905", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4561403509, "max_line_length": 116, "alphanum_fraction": 0.6750289464, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6968393705300595}} {"text": "\n\nmodule FinancialTimeseries.Statistics.Statistics where\n\nimport qualified Data.Vector as Vec\nimport Data.Vector (Vector)\n\nimport qualified Data.Vector.Algorithms.Merge as Merge\n\nimport qualified Statistics.Sample as Sample\n\nimport FinancialTimeseries.Type.Chart (Chart(..), LChart)\nimport FinancialTimeseries.Type.Labeled (Labeled)\nimport FinancialTimeseries.Type.Table (Table(..), Cell(..), Row, row)\n\n\n\ndata Quantiles a = Quantiles {\n q05 :: Maybe a\n , q25 :: Maybe a\n , q50 :: Maybe a\n , q75 :: Maybe a\n , q95 :: Maybe a\n } deriving (Show)\n\ninstance Row Quantiles where\n row (Quantiles a b c d e) = map (CString . maybe \"n/a\" show) [a, b, c, d, e]\n\ndata Probabilities a = Probabilities {\n p0'50 :: a\n , p0'75 :: a\n , p1'00 :: a\n , p1'25 :: a\n , p1'50 :: a\n , p1'75 :: a\n , p2'00 :: a\n } deriving (Show)\n\ninstance Row Probabilities where\n row (Probabilities a b c d e f g) = map Cell [a, b, c, d, e, f, g]\n\ndata TradeMoments a = TradeMoments {\n trMaxYield :: a\n , trMinYield :: a\n , trMeanYield :: a\n , trStdDevYield :: a\n } deriving (Show)\n \ninstance Row TradeMoments where\n row (TradeMoments a b c d) = map Cell [a, b, c, d]\n\ndata TimeseriesMoments a = TimeseriesMoments {\n tsMaxYield :: a\n , tsMinYield :: a\n , tsMeanYield :: a\n , tsStdDevYield :: a\n } deriving (Show)\n \ninstance Row TimeseriesMoments where\n row (TimeseriesMoments a b c d) = map Cell [a, b, c, d]\n\ndata Stats moments a = Stats {\n sampleSize :: Int\n , quantiles :: Quantiles a\n , probabilities :: Probabilities a\n , moments :: moments a\n , cdf :: Vector (Double, a)\n } deriving (Show)\n\n\ntradeMoments ::\n (Real a, Fractional a) =>\n Vector a -> TradeMoments a\ntradeMoments sorted =\n let sortedFrac = Vec.map realToFrac sorted\n in TradeMoments {\n trMaxYield = Vec.last sorted\n , trMinYield = Vec.head sorted\n , trMeanYield = realToFrac $ exp (Sample.mean (Vec.map log sortedFrac))\n , trStdDevYield = realToFrac $ exp (Sample.stdDev (Vec.map log sortedFrac))\n }\n \ntimeseriesMoments ::\n (Real a, Fractional a) =>\n Vector a -> TimeseriesMoments a\ntimeseriesMoments sorted =\n let sortedFrac = Vec.map realToFrac sorted\n in TimeseriesMoments {\n tsMaxYield = Vec.last sorted\n , tsMinYield = Vec.head sorted\n , tsMeanYield = realToFrac $ Sample.mean sortedFrac\n , tsStdDevYield = realToFrac $ Sample.stdDev sortedFrac\n }\n\n \nstats2list ::\n (Row moments, Show a) =>\n [Labeled params (Stats moments a)] -> [Table params a]\nstats2list xs =\n let qheaders = map CString [\"Q05\", \"Q25\", \"Q50\", \"Q75\", \"Q95\", \"Sample Size\"]\n pheaders = map CString [\"P(X < 0.5)\", \"P(X < 0.75)\", \"P(X < 1.0)\", \"P(X < 1.25)\", \"P(X < 1.5)\", \"P(X < 1.75)\", \"P(X < 2.0)\", \"Sample Size\"]\n mheaders = map CString [\"Max.\", \"Min.\", \"Mean\", \"StdDev.\", \"Sample Size\"]\n mkRow g x = row (g x) ++ [CInt (sampleSize x)]\n in Table \"Quantiles\" qheaders (map (fmap (mkRow quantiles)) xs)\n : Table \"Moments\" mheaders (map (fmap (mkRow moments)) xs)\n : Table \"Probabilities\" pheaders (map (fmap (mkRow probabilities)) xs)\n : []\n\nstats2cdfChart :: [Labeled params (Stats moments a)] -> LChart params Double a\nstats2cdfChart = Chart \"CDF\" . map (fmap ((:[]) . cdf))\n\n\nstatisticsWithMoments ::\n (Ord a, Num a, Fractional a, Real a) =>\n (Vector a -> moments a) -> Vector a -> Stats moments a\nstatisticsWithMoments mms vs =\n let noe = fromIntegral (Vec.length vs)\n sorted = Vec.modify Merge.sort vs\n\n quart s = sorted Vec.!? (round (s * noe :: Double))\n q = Quantiles {\n q05 = quart 0.05\n , q25 = quart 0.25\n , q50 = quart 0.50\n , q75 = quart 0.75\n , q95 = quart 0.95\n }\n\n prob s = fromIntegral (Vec.length (Vec.takeWhile ( (fromIntegral i / noe, x)) sorted\n }\n\n\ntimeseriesStatistics ::\n (Real a, Fractional a) =>\n Vector a -> Stats TimeseriesMoments a\ntimeseriesStatistics = statisticsWithMoments timeseriesMoments\n\ntradeStatistics ::\n (Real a, Fractional a) =>\n Vector a -> Stats TradeMoments a\ntradeStatistics = statisticsWithMoments tradeMoments\n\nyield :: (Fractional a) => Vector a -> a\nyield v = Vec.last v / Vec.head v\n\nabsoluteDrawdown :: (Ord a, Fractional a) => Vector a -> a\nabsoluteDrawdown v = Vec.minimum v / Vec.head v\n\nrelativeDrawdown :: (Ord a, Num a, Fractional a) => Vector a -> a\nrelativeDrawdown v = Vec.minimum (Vec.zipWith (/) v (Vec.postscanl max 0 v))\n\n\n", "meta": {"hexsha": "fcf3ecb6440c5bfa1baab5f41d1959c63b8ec981", "size": 4768, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FinancialTimeseries/Statistics/Statistics.hs", "max_stars_repo_name": "fphh/financial-timeseries", "max_stars_repo_head_hexsha": "9be9b8e83108889a7527dbd15df8ac9f2cf6093e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/FinancialTimeseries/Statistics/Statistics.hs", "max_issues_repo_name": "fphh/financial-timeseries", "max_issues_repo_head_hexsha": "9be9b8e83108889a7527dbd15df8ac9f2cf6093e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FinancialTimeseries/Statistics/Statistics.hs", "max_forks_repo_name": "fphh/financial-timeseries", "max_forks_repo_head_hexsha": "9be9b8e83108889a7527dbd15df8ac9f2cf6093e", "max_forks_repo_licenses": ["BSD-3-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.2130177515, "max_line_length": 145, "alphanum_fraction": 0.6329697987, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6968270223217928}} {"text": "module Net\n (\n repTrain\n , buildNetwork\n , forward\n , mse\n , sigmoid\n , sigmoid'\n , tanh'\n , printNet\n , NN\n ) where\n\nimport Numeric.LinearAlgebra\nimport Data.Traversable\n\ntype ActivationF = Double -> Double\ntype ActivationD = Double -> Double\ntype Activation = (ActivationF, ActivationD)\ntype Bias = Matrix R\ntype Weights = Matrix R\ntype Layer = (Weights, Bias, Activation)\ntype NN = [Layer]\n\ntype Input = Matrix R\ntype Output = Matrix R\ntype Deriv = Matrix R\ntype Error = Matrix R\ntype LearningRate = Double\n\nrepTrain :: Int -> LearningRate -> Input -> Output -> NN -> NN\nrepTrain 0 _ _ _ nn = nn\nrepTrain n lr x y nn = repTrain (n-1) lr x y (backprop lr x y nn)\n \nbuildNetwork :: Activation -> [Int] -> IO NN\nbuildNetwork act (a:b:xs) = do\n weights <- randn a b\n bias <- randn 1 b\n rest <- buildNetwork act (b:xs)\n return $ (weights, bias, act):rest\nbuildNetwork _ _ = return []\n\nforward :: NN -> Input -> Output\nforward = (fst .) . flip feedForward\n\nfeedForward :: Input -> NN -> (Output, [(Input, Deriv)])\nfeedForward = mapAccumL activateLayer\n\nactivateLayer :: Input -> Layer -> (Output, (Input, Deriv))\nactivateLayer input (wh, bh, act) = (output, (input, deriv))\n where\n output = cmap (fst act) ((input <> wh + bh))\n deriv = cmap (snd act) output\n\nbackprop :: LearningRate -> Input -> Output -> NN -> NN\nbackprop lr input y net = backpropLayers lr error inpDs net\n where\n (output, inpDs) = feedForward input net\n error = y - output\n\nmse :: NN -> Input -> Output -> Error\nmse net x y = let (output, _) = feedForward x net in y - output\n\nbackpropLayers :: LearningRate -> Error -> [(Input, Deriv)] -> NN -> NN\nbackpropLayers lr error inpDs = snd . mapAccumR (backpropMatrix lr) error . zip inpDs\n-- = ((snd . mapAccumR (backpropMatrix lr) error .) . zip) inpDs\n\nbackpropMatrix :: LearningRate -> Matrix R -> ((Matrix R, Matrix R), Layer) -> (Error, Layer)\nbackpropMatrix lr error (inputInfo, layer) = (prev_error, new_layer)\n where\n (layer_weights, layer_bias, act) = layer\n (layer_inp, layer_deriv) = inputInfo\n new_layer = (new_weights, new_bias, act)\n\n d_layer = layer_deriv * error\n new_weights = (+) layer_weights $ cmap (* lr) $ (tr layer_inp) <> d_layer\n new_bias = (+) layer_bias $ cmap (* lr) $ asRow $ vector $ map sumElements $ toColumns d_layer\n\n prev_error = d_layer <> (tr layer_weights)\n \nsigmoid :: Double -> Double\nsigmoid x = 1.0 / (1 + exp (-x))\n\nsigmoid' :: Double -> Double\nsigmoid' x = x * (1 - x)\n\ntanh' :: Double -> Double\ntanh' x = let fx = tanh x in 1 - fx * fx\n\nprintNet :: NN -> IO ()\nprintNet layers = do\n mapM_ (\\(w,b,_) -> do\n disp 3 w\n disp 3 b) layers\n \n", "meta": {"hexsha": "58718e857a9814f2b979cceefa50877677d24f7a", "size": 2702, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Rob537/HW1/HW1/src/Net.hs", "max_stars_repo_name": "eklinkhammer/OSU_Coursework", "max_stars_repo_head_hexsha": "ffc1d3c95ffc582fb297ac2c720ab3f3ad485cd3", "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": "Rob537/HW1/HW1/src/Net.hs", "max_issues_repo_name": "eklinkhammer/OSU_Coursework", "max_issues_repo_head_hexsha": "ffc1d3c95ffc582fb297ac2c720ab3f3ad485cd3", "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": "Rob537/HW1/HW1/src/Net.hs", "max_forks_repo_name": "eklinkhammer/OSU_Coursework", "max_forks_repo_head_hexsha": "ffc1d3c95ffc582fb297ac2c720ab3f3ad485cd3", "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.1458333333, "max_line_length": 98, "alphanum_fraction": 0.6421169504, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6968160985988412}} {"text": "module Regression where\n\nimport MHMonad\nimport Distr\nimport Data.Monoid\nimport Graphics.Rendering.Chart\nimport Graphics.Rendering.Chart.Backend.Diagrams\nimport Graphics.Rendering.Chart.State\nimport Data.Colour\nimport Data.Colour.Names\nimport Data.Default.Class\nimport Control.Lens\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal (normalDistr)\nimport Statistics.Distribution.Beta (betaDistr)\n\n\n-- A random linear function\nlinear :: Meas (Double -> Double)\nlinear =\n do a <- normal 0 3\n b <- normal 0 3\n let f = \\x -> a*x + b\n return f\n\n-- Weight a function to some data points\nfit :: Meas (a -> Double) -> [(a,Double)] -> Meas (a -> Double)\nfit prior dataset = do f <- prior\n mapM (\\(x,y) ->\n score $ normalPdf (f x) 0.3 y)\n dataset\n return f\n \ndataset :: [(Double, Double)]\ndataset = [(0,0.6), (1, 0.7), (2,1.2), (3,3.2), (4,6.8), (5, 8.2), (6,8.4)]\n\nexample :: Meas (Double -> Double)\nexample = fit linear dataset\n\n-- Some graphing routines\nplotWeightedPoints :: String -> [(Double,Double,Double)] -> Double -> Double -> Double -> Double -> IO ()\nplotWeightedPoints filename dataset xmin xmax ymin ymax =\n let plots = map (\\(x,y,w) -> toPlot $ plot_points_style .~ filledCircles 4 ((blend w blue red) `withOpacity` w)\n $ plot_points_values .~ [(x,y)]\n $ def) dataset in\n let my_layout = layout_plots .~ plots\n $ layout_x_axis .\n laxis_generate .~ scaledAxis def (xmin,xmax)\n $ layout_y_axis . laxis_generate .~ scaledAxis def (ymin,ymax)\n $ def in\n let graphic = toRenderable my_layout in\n do\n putStr (\"Generating \" ++ filename ++ \"...\")\n renderableToFile def filename graphic;\n putStrLn (\" Done!\")\n return ()\n \nplotWeightedLines :: String -> [(Double,Double,Double)] -> IO ()\nplotWeightedLines filename points =\n let plots = map (\\(x,y,w) -> toPlot $ plot_lines_style . line_color .~ (blend w blue red) `withOpacity` (w)\n $ plot_lines_values .~ [[ (0.0 :: Double,x) , (10.0 :: Double ,y*10+x) ]]\n $ def) points in\n let my_dots = plot_points_style .~ filledCircles 4 (opaque black)\n $ plot_points_values .~ dataset\n $ def in \n let my_layout = layout_plots .~ (toPlot my_dots : plots)\n $ layout_x_axis .\n laxis_generate .~ scaledAxis def (-10,10)\n $ layout_y_axis . laxis_generate .~ scaledAxis def (-10,10)\n $ def in\n let graphic = toRenderable my_layout in\n do\n putStr (\"Generating \" ++ filename ++ \"...\")\n renderableToFile def filename graphic;\n putStrLn (\" Done!\")\n return ()\n\n\nmaxlist :: [Double] -> Double\nmaxlist (x:xs) = max x (maxlist xs)\n\nminlist :: [Double] -> Double\nminlist (x:xs) = min x (minlist xs)\n\n\n-- Plot the points drawn from weighted samples\ntest1 = do\n samples <- weightedsamples example\n let xyw's = map (\\(f,w) -> (f 0, f 1 - f 0, w)) $ take 10000 samples\n let m = maximum (map (\\(_,_,w) -> w) xyw's)\n let xyws = map (\\(x,y,w) -> (x,y, max (w/m) (1/255))) xyw's\n putStr $ show $ m\n putStr $ show $ take 20 xyws\n plotWeightedPoints \"weightedpoints.svg\" xyws (-6) 6 (-6) 6\n -- plotWeightedLines \"weightedtest.svg\" xyws\n let xyw's = map (\\(f,w) -> (f 0, f 1 - f 0, w)) $ take 100000 samples\n let m = maximum (map (\\(_,_,w) -> w) xyw's)\n let xyws = filter (\\(x,y,_) -> x > -1 && x < 0 && y > 1 && y < 2) $ map (\\(x,y,w) -> (x,y, max (w / m) 0.1)) xyw's\n plotWeightedPoints \"weightedpointszoom.svg\" xyws (-1) 0 1 2\n\n-- Plot the result of MH\ntest2 = do\n samples <- mh example\n let xyw's = map (\\(f,w) -> (f 0, f 1 - f 0, getProduct w)) $ take 10000 samples\n let m = maximum (map (\\(_,_,w) -> w) xyw's)\n let xyws = map (\\(x,y,w) -> (x,y, max (w / m) 0.05)) xyw's\n plotWeightedPoints \"weightedpointsmh.svg\" xyws (-6) 6 (-6) 6\n let xyws = filter (\\(x,y,_) -> x > -1 && x < 0 && y > 1 && y < 2) $ map (\\(x,y,w) -> (x,y, max (w / m) 0.1)) xyw's\n plotWeightedPoints \"weightedpointszoommh.svg\" xyws (-1) 0 1 2\n\n\nevery n xs = case drop (n-1) xs of\n (y:ys) -> y : every n ys\n [] -> []\n\n-- More graphing routines\n-- epsilon: smallest y axis difference to worry about\n-- delta: smallest x axis difference to worry about\ninteresting_points :: (Double -> Double) -> Double -> Double -> Double -> Double -> [Double] -> [Double]\ninteresting_points f lower upper epsilon delta acc =\n if abs(upper - lower) < delta then acc\n else\n let mid = (upper - lower) / 2 + lower in\n if abs((f(upper) - f(lower)) / 2 + f(lower) - f(mid)) < epsilon \n then acc\n else interesting_points f lower mid epsilon delta (mid : (interesting_points f mid upper epsilon delta acc))\n \nsample_fun f = \n-- [ (x, f x) | x <- [(-0.25),(-0.25+0.1)..6.2]]\n let xs = ((-0.25) : (interesting_points f (-0.25) 6.2 0.3 0.001 [6.2])) in\n map (\\x -> (x,f x)) xs \n\nplot_funs :: String -> [(Double,Double)] -> [Double -> Double] -> IO ()\nplot_funs filename dataset funs =\n let graphs = map sample_fun funs in\n let my_lines = plot_lines_style . line_color .~ blue `withOpacity` 0.01\n $ plot_lines_values .~ graphs $ def in\n let my_dots = plot_points_style .~ filledCircles 4 (opaque black)\n $ plot_points_values .~ dataset\n $ def in \n let my_layout = layout_plots .~ [toPlot my_lines , toPlot my_dots]\n $ layout_x_axis .\n laxis_generate .~ scaledAxis def (0,6)\n $ layout_y_axis . laxis_generate .~ scaledAxis def (-2,10)\n $ def in\n let graphic = toRenderable my_layout in\n do\n putStr (\"Generating \" ++ filename ++ \"...\")\n renderableToFile def filename graphic;\n putStrLn (\" Done!\")\n return ()\n\n-- plot the results of linear regression\ntest3 =\n do\n fs' <- mh $ fit linear dataset\n let fs = map (\\(f,_)->f) $ take 500 $ every 100 $ drop 1000 $ fs'\n plot_funs \"lin-reg.svg\" dataset fs\n\n-- plot the linear regression prior\ntest3b =\n do\n fs' <- mh $ linear\n let fs = map (\\(f,_)->f) $ take 500 $ every 100 $ drop 1000 $ fs'\n plot_funs \"lin-reg-prior.svg\" dataset fs\n\n\n-- poissonPP lower upper rate returns a random list of points between lower and upper coming from a Poisson process with given rate\npoissonPP :: Double -> Double -> Double -> Meas [Double]\npoissonPP lower upper rate =\n do gap <- exponential rate\n if (lower + gap > upper)\n then return []\n else do rest <- poissonPP (lower + gap) upper rate\n return ((lower + gap) : rest)\n\n\n\n\n-- Splice takes a random list of points, a random function,\n-- and returns a new random function that is a piecewise version of the\n-- first one.\nsplice :: Meas [Double] -> Meas (Double -> Double) -> Meas (Double -> Double)\nsplice pointProcess randomFun =\n do xs <- pointProcess\n fs <- mapM (\\_ -> randomFun) xs\n default_f <- randomFun\n let h :: [(Double, Double -> Double)] -> Double -> Double\n h [] x = default_f x\n h ((a,f):xfs) x | x <= a = f x\n h ((a,f):xfs) x | x > a = h xfs x\n return (h (zip xs fs) )\n\ntest4 =\n do\n fs' <- mh $ fit (splice (poissonPP 0 6 0.1) linear) dataset\n let fs = map (\\(f,_)->f) $ take 500 $ every 1000 $ drop 100000 $ fs'\n plot_funs \"piecewise-lin-reg.svg\" dataset fs\n", "meta": {"hexsha": "a2bcf9668a7add1a841e7fefd13ba0c0b044a8b2", "size": 7588, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Regression.hs", "max_stars_repo_name": "PiotrJander/oplss-staton", "max_stars_repo_head_hexsha": "6357a1026f11dddde3f90e4ebea3ab3220018a0f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-20T04:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-20T04:44:45.000Z", "max_issues_repo_path": "src/Regression.hs", "max_issues_repo_name": "PiotrJander/oplss-staton", "max_issues_repo_head_hexsha": "6357a1026f11dddde3f90e4ebea3ab3220018a0f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Regression.hs", "max_forks_repo_name": "PiotrJander/oplss-staton", "max_forks_repo_head_hexsha": "6357a1026f11dddde3f90e4ebea3ab3220018a0f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1306532663, "max_line_length": 131, "alphanum_fraction": 0.5801265156, "num_tokens": 2227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.696778861048959}} {"text": "module Quadratic_Formula (csqrt, quadratic) where\n\nimport Data.Complex\n\ncsqrt z@(a :+ b) = let (mag, ph) = polar z in mkPolar (sqrt mag) (ph/2)\n\nquadratic a b c = (\n quad (conjugate a) (conjugate b) (conjugate c) (+),\n quad (conjugate a) (conjugate b) (conjugate c) (-)\n ) where quad a b c op = (-b `op` csqrt ( b^2 - 4 * a * c))/(2 * a)\n", "meta": {"hexsha": "2feeab6a19f171e383ac5bd49bb1f17e6ac02af1", "size": 347, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Maths_And_Stats/Algebra/Quadratic_Formula/Quadratic_Formula.hs", "max_stars_repo_name": "arslantalib3/algo_ds_101", "max_stars_repo_head_hexsha": "a1293f407e00b8346f93e8770727f769e7add00e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2020-10-01T17:16:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T17:52:49.000Z", "max_issues_repo_path": "Maths_And_Stats/Algebra/Quadratic_Formula/Quadratic_Formula.hs", "max_issues_repo_name": "arslantalib3/algo_ds_101", "max_issues_repo_head_hexsha": "a1293f407e00b8346f93e8770727f769e7add00e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 759, "max_issues_repo_issues_event_min_datetime": "2020-10-01T00:12:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T19:35:11.000Z", "max_forks_repo_path": "Maths_And_Stats/Algebra/Quadratic_Formula/Quadratic_Formula.hs", "max_forks_repo_name": "arslantalib3/algo_ds_101", "max_forks_repo_head_hexsha": "a1293f407e00b8346f93e8770727f769e7add00e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1176, "max_forks_repo_forks_event_min_datetime": "2020-10-01T16:02:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T19:20:19.000Z", "avg_line_length": 31.5454545455, "max_line_length": 71, "alphanum_fraction": 0.6023054755, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6965920450650651}} {"text": "module Numeric.MixtureModel.Beta ( -- * General data types\n Sample\n , SampleIdx\n , Samples\n , ComponentIdx\n , Assignments\n , Weight\n -- * Beta parameters\n , BetaParam (..)\n , BetaParams\n , ComponentParams\n , paramFromMoments\n , paramToMoments\n , paramsFromAssignments\n , paramToMode\n -- * Beta distribution\n , Prob\n , betaProb\n -- * Gibbs sampling\n , estimateWeights\n , updateAssignments\n , updateAssignments'\n -- * Likelihood\n , likelihood\n -- * Classification\n , classify\n ) where\n\nimport Data.Function (on)\nimport qualified Data.Vector as VB\nimport qualified Data.Vector.Generic as V\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Unboxed.Mutable as MV\nimport Control.Monad.ST\n\nimport Numeric.Log hiding (sum)\nimport Numeric.SpecFunctions (logBeta)\nimport Statistics.Sample (meanVarianceUnb)\n\nimport Data.Random\nimport Data.Random.Distribution.Categorical\n\ntype Prob = Log Double\ntype Sample = Double\ntype SampleIdx = Int\ntype ComponentIdx = Int\ntype Weight = Double\ndata BetaParam = BetaParam { bpAlpha :: !Double -- ^ Alpha\n , bpBeta :: !Double -- ^ Beta\n }\n deriving (Show, Eq, Ord)\n\n-- k refers to number of components\n-- N refers to number of samples\ntype Samples = VU.Vector Sample -- length == N\ntype Assignments = VU.Vector ComponentIdx -- length == N\ntype BetaParams = VB.Vector BetaParam -- length == K\ntype ComponentParams = VB.Vector (Weight, BetaParam) -- length == K\n\nbeta :: Double -> Double -> Log Double\nbeta a b = Exp $ logBeta a b\n\n-- | `betaProb (a,b) x` is the probability of `x` under Beta\n-- distribution defined by parameters `a` and `b`\nbetaProb :: BetaParam -> Sample -> Prob\nbetaProb (BetaParam a b) x =\n 1/beta a b * realToFrac (x**(a-1)) * realToFrac ((1-x)**(b-1))\n\n-- | Beta parameter from sample mean and variance\nparamFromMoments :: Double -- ^ mean\n -> Double -- ^ variance\n -> Maybe BetaParam\nparamFromMoments xbar v\n | c < 0 = Nothing\n | otherwise = Just $ BetaParam (xbar * c) ((1 - xbar) * c)\n where c = xbar * (1 - xbar) / v - 1\n\n-- | Mean and variance of the given beta parameter\nparamToMoments :: BetaParam -> (Double, Double)\nparamToMoments (BetaParam a b) =\n let mean = a / (a+b)\n var = a*b / (a+b)^2 / (a+b+1)\n in (mean, var)\n\n-- | The mode of the given beta parameter\nparamToMode :: BetaParam -> Double\nparamToMode (BetaParam a b) = (a - 1) / (a + b - 2)\n\n-- | Beta parameter from samples\nparamFromSamples :: VU.Vector Sample -> BetaParam\nparamFromSamples v | V.null v = error \"Numeric.MixtureModel.Beta: Can't estimate priors from no samples\"\nparamFromSamples v =\n case uncurry paramFromMoments $ meanVarianceUnb v of\n Just a -> a\n Nothing -> error \"Numeric.MixtureModel.Beta: Somehow we have a negative variance\"\n\n-- | Beta parameter for component given samples and their component assignments\nparamFromAssignments :: Samples -> Assignments -> ComponentIdx -> BetaParam\nparamFromAssignments samples assignments k =\n paramFromSamples $ V.map snd $ V.filter (\\(k',_)->k==k') $ V.zip assignments samples\n\n-- | Beta parameters for all components given samples and their component assignments\nparamsFromAssignments :: Samples -> Int -> Assignments -> BetaParams\nparamsFromAssignments samples ncomps assignments =\n V.fromList $ map (paramFromAssignments samples assignments) [0..ncomps-1]\n\n-- | Draw a new assignment for a sample given beta parameters\ndrawAssignment :: ComponentParams -> Sample -> RVar ComponentIdx\ndrawAssignment params x =\n let probs = map (\\(w,p)->realToFrac w * betaProb p x) $ V.toList params\n in case filter (isInfinite . ln . fst) $ zip probs [0..] of\n (x:_) -> return $ snd x\n otherwise -> categorical\n $ map (\\(p,k)->(realToFrac $ p / sum probs :: Double, k))\n $ zip probs [0..]\n\ncountIndices :: Int -> VU.Vector Int -> VU.Vector Int\ncountIndices n v = runST $ do\n accum <- V.thaw $ VU.replicate n 0\n V.forM_ v $ \\k -> do n' <- MV.read accum k\n MV.write accum k $! n'+1\n V.freeze accum\n\n-- | Estimate the component weights of a given set of parameters\nestimateWeights :: Assignments -> BetaParams -> ComponentParams\nestimateWeights assignments params =\n let counts = countIndices (V.length params) assignments\n norm = realToFrac $ V.length assignments\n weights = V.map (\\n->realToFrac n / norm) counts\n in V.zip (V.convert weights) params\n\n-- | Sample assignments for samples under given parameters\nupdateAssignments' :: Samples -> ComponentParams -> RVar Assignments\nupdateAssignments' samples params =\n V.mapM (drawAssignment params) samples\n\n-- | Gibbs update of sample assignments\nupdateAssignments :: Samples -> Int -> Assignments -> RVar Assignments\nupdateAssignments samples ncomps assignments =\n updateAssignments' samples\n $ estimateWeights assignments\n $ paramsFromAssignments samples ncomps assignments\n\n-- | Likelihood of samples assignments under given model parameters\nlikelihood :: Samples -> ComponentParams -> Assignments -> Prob\nlikelihood samples params assignments =\n V.product ( V.map (\\(k,x)->betaProb (snd $ params V.! k) x)\n $ V.zip assignments samples\n )\n * V.product (V.map (\\k->realToFrac $ fst $ params V.! k) assignments)\n\n-- | Maximum likelihood classification\nclassify :: ComponentParams -> Sample -> ComponentIdx\nclassify params x =\n fst\n $ V.maximumBy (compare `on` \\(_,(w,p))->realToFrac w * betaProb p x)\n $ V.indexed params\n", "meta": {"hexsha": "f11b4f9f43a6488f1d8b7d8be4f2753c6ebf9da5", "size": 6518, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/MixtureModel/Beta.hs", "max_stars_repo_name": "bgamari/mixture-model", "max_stars_repo_head_hexsha": "91d41b8dde6c9dab8220e6298d1cbdf30902fd53", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-09-02T17:02:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T09:07:44.000Z", "max_issues_repo_path": "Numeric/MixtureModel/Beta.hs", "max_issues_repo_name": "bgamari/mixture-model", "max_issues_repo_head_hexsha": "91d41b8dde6c9dab8220e6298d1cbdf30902fd53", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/MixtureModel/Beta.hs", "max_forks_repo_name": "bgamari/mixture-model", "max_forks_repo_head_hexsha": "91d41b8dde6c9dab8220e6298d1cbdf30902fd53", "max_forks_repo_licenses": ["BSD-3-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.253164557, "max_line_length": 104, "alphanum_fraction": 0.5817735502, "num_tokens": 1443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092014, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6946759791619139}} {"text": "import Data.Complex\n\nimport Lib\n\nfunc c z = z^2 + c\n\ndiverge maxIters f x0 = (any (\\x -> magnitude x > 4) . take maxIters) (iterate f x0)\n\npoints = [a :+ b | a <- [-2.5,-2.495..1], b <- [-1,-0.995..1]]\n\nmset = filter (\\x -> not (diverge 1000 (func x) 0)) points\n\nmain = plotPoints' \"mandelbrot.svg\" \"Mandelbrot Set\" 1.4 (map c2t mset)\n", "meta": {"hexsha": "537e366c0f2591281c1575aeb03781937a36e63e", "size": 335, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "projects/mandelbrot/Main.hs", "max_stars_repo_name": "ahaym/dynamics", "max_stars_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/mandelbrot/Main.hs", "max_issues_repo_name": "ahaym/dynamics", "max_issues_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/mandelbrot/Main.hs", "max_forks_repo_name": "ahaym/dynamics", "max_forks_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9285714286, "max_line_length": 84, "alphanum_fraction": 0.6029850746, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6944231800655473}} {"text": "module Main where\nimport Layer\nimport Models\nimport Numeric.LinearAlgebra\nimport ImageProcess\nimport Optimization\nimport Trainer\nimport Data.Vector.Storable (Vector, length, toList)\n\n\nmain :: IO()\nmain =\n do\n let inputLayer = linearLayerInit 2 2\n let sigmoidLayer = sigmoidLayerInit 2 2\n let outputLayer = linearLayerInit 2 1 in\n let model = Model [inputLayer, sigmoidLayer, outputLayer] in\n let input = (1><2)[1.0, 2.0]::Matrix R in\n let output = forward input model in\n print output\n\n\n\ntestImageRegression :: FilePath -> IO()\ntestImageRegression filepath = do\n imageM <- getImageInfo filepath\n case imageM of\n Nothing -> putStrLn \"Nohthing ! Guess what happened ? :) \" >> return ()\n Just imagePixel8 ->\n let rgbs = getImageRGBs imagePixel8\n w = getImageWidth imagePixel8\n h = getImageHeight imagePixel8\n rgbsList = Data.Vector.Storable.toList rgbs\n (rlist, glist, blist) = genRGBList rgbsList\n Just rMat = genMatrixFromList rlist w h\n Just gMat = genMatrixFromList glist w h\n Just bMat = genMatrixFromList blist w h in\n --- test\n print \"prepare the model!\" >>\n let rinputLayer = linearLayerInit w h\n rreluLayer1 = reluLayerInit w h\n rreluLayer2 = reluLayerInit w h\n rreluLayer3 = reluLayerInit w h\n routputLayer= linearLayerInit w h\n rmodel = Model [rinputLayer, rreluLayer1, rreluLayer2, rreluLayer3, routputLayer]\n ginputLayer = linearLayerInit w h\n greluLayer1 = reluLayerInit w h\n greluLayer2 = reluLayerInit w h\n greluLayer3 = reluLayerInit w h\n goutputLayer= linearLayerInit w h\n gmodel = Model [ginputLayer, greluLayer1, greluLayer2, greluLayer3, goutputLayer]\n binputLayer = linearLayerInit w h\n breluLayer1 = reluLayerInit w h\n breluLayer2 = reluLayerInit w h\n breluLayer3 = reluLayerInit w h\n boutputLayer= linearLayerInit w h\n bmodel = Model [binputLayer, breluLayer1, breluLayer2, breluLayer3, boutputLayer] in\n print \"begin to train the model\" >>\n let trainConfig = TrainConfig {\n trainConfigRowNum=w,\n trainConfigColNum=h,\n trainConfigLearningRate=0.95,\n trainConfigMomentum=1.0,\n trainConfigDecay=0.95,\n trainConfigEpsilon=0.00001,\n trainConfigBatchSize=100,\n trainConfigOptimization=\"adadelta\"\n } in\n trainSingleData rmodel trainConfig rMat \n", "meta": {"hexsha": "3170dd7a5529194dcc5b9536350bea2930f5fc00", "size": 2728, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "vortex/Main.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/Main.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/Main.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": 38.9714285714, "max_line_length": 98, "alphanum_fraction": 0.616202346, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6942519361635269}} {"text": "import Statistics.Distribution.Uniform\nimport Statistics.Distribution\n\nud :: UniformDistribution\nud = uniformDistr 0.0 30.0\n\nmain = do\n putStrLn $ \"the probability that the customer arrived within the very last 5 min:\" \n ++ show (cumulative ud 30 - cumulative ud 25)\n putStrLn $ \"this is 1/6: \" ++ show (1/6)\n", "meta": {"hexsha": "338d83053c0292fb9668ad7d30010e702fe97049", "size": 320, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ch04/ex4_07.hs", "max_stars_repo_name": "raydsameshima/Stat", "max_stars_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch04/ex4_07.hs", "max_issues_repo_name": "raydsameshima/Stat", "max_issues_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch04/ex4_07.hs", "max_forks_repo_name": "raydsameshima/Stat", "max_forks_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": 29.0909090909, "max_line_length": 85, "alphanum_fraction": 0.7125, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6942519259387303}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\n-- |\n-- Module : Statistics.Sample.Normalize\n-- Copyright : (c) 2017 Gregory W. Schwartz\n-- License : BSD3\n--\n-- Maintainer : gsch@mail.med.upenn.edu\n-- Stability : experimental\n-- Portability : portable\n--\n-- Functions for normalizing samples.\n\nmodule Statistics.Sample.Normalize\n (\n standardize\n ) where\n\nimport Statistics.Sample\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as S\n\n-- | /O(n)/ Normalize a sample using standard scores:\n--\n-- \\[ z = \\frac{x - \\mu}{\\sigma} \\]\n--\n-- Where μ is sample mean and σ is standard deviation computed from\n-- unbiased variance estimation. If sample to small to compute σ or\n-- it's equal to 0 @Nothing@ is returned.\nstandardize :: (G.Vector v Double) => v Double -> Maybe (v Double)\nstandardize xs\n | G.length xs < 2 = Nothing\n | sigma == 0 = Nothing\n | otherwise = Just $ G.map (\\x -> (x - mu) / sigma) xs\n where\n mu = mean xs\n sigma = stdDev xs\n{-# INLINABLE standardize #-}\n{-# SPECIALIZE standardize :: V.Vector Double -> Maybe (V.Vector Double) #-}\n{-# SPECIALIZE standardize :: U.Vector Double -> Maybe (U.Vector Double) #-}\n{-# SPECIALIZE standardize :: S.Vector Double -> Maybe (S.Vector Double) #-}\n", "meta": {"hexsha": "0d81a8b02dbc9a55b615c03017549859fbe9fbd4", "size": 1360, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Sample/Normalize.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Sample/Normalize.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Sample/Normalize.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 30.9090909091, "max_line_length": 76, "alphanum_fraction": 0.6610294118, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6940451609931444}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.Statistics.PCA\n-- Copyright : (c) A. V. H. McPhail 2010, 2014, 2017\n-- License : BSD3\n--\n-- Maintainer : haskell.vivian.mcphail gmail com\n-- Stability : provisional\n-- Portability : portable\n--\n-- Principal Components Analysis\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.Statistics.PCA (\n pca, pcaN, pcaTransform, pcaReduce, pcaReduceN\n ) where\n\n\n-----------------------------------------------------------------------------\n\nimport qualified Data.Array.IArray as I \n\nimport Prelude hiding ((<>))\nimport Data.List(sortBy)\nimport Data.Ord(comparing)\nimport Numeric.LinearAlgebra\nimport Numeric.GSL.Statistics\n\n--import Numeric.Statistics\n\n-----------------------------------------------------------------------------\n\n-- | find the principal components of multidimensional data greater than\n-- the threshhold\npca :: I.Array Int (Vector Double) -- the data\n -> Double -- eigenvalue threshold\n -> (Vector Double, Matrix Double) -- Eignevalues, Principal components\npca d q = let d' = fmap (\\x -> x - (scalar $ mean x)) d -- remove the mean from each dimension\n d'' = fromColumns $ I.elems d'\n (_,vec',uni') = svd d''\n vec = toList vec'\n uni = toColumns uni'\n v' = zip vec uni\n v = filter (\\(x,_) -> x > q) v' -- keep only eigens > than parameter\n (eigs,vs) = unzip v\n in (fromList eigs,fromColumns vs) \n\n-- | find N greatest principal components of multidimensional data\n-- according to size of the eigenvalue\npcaN :: I.Array Int (Vector Double) -- the data\n -> Int -- number of components to return\n -> (Vector Double, Matrix Double) -- Eignevalues, Principal components\npcaN d n = let d' = fmap (\\x -> x - (scalar $ mean x)) d -- remove the mean from each dimension\n d'' = fromColumns $ I.elems d'\n (_,vec',uni') = svd d''\n vec = toList vec'\n uni = toColumns uni'\n v' = zip vec uni\n v = take n $ reverse $ sortBy (comparing fst) v'\n (eigs,vs) = unzip v\n in (fromList eigs,fromColumns vs) \n\nv1 = fromList [1,2,3,4,5,6::Double]\nv2 = fromList [2,3,4,5,6,7::Double]\nv3 = fromList [3,4,5,6,7,8::Double]\n\na = fromColumns [v1,v2,v3]\nb = I.listArray (1,3::Int) [v1,v2,v3] :: I.Array Int (Vector Double)\n \n-- | perform a PCA transform of the original data (remove mean)\n-- | Final = M^T Data^T\npcaTransform :: I.Array Int (Vector Double) -- ^ the data\n -> Matrix Double -- ^ the principal components\n -> I.Array Int (Vector Double) -- ^ the transformed data\npcaTransform d m = let d' = fmap (\\x -> x - (scalar $ mean x)) d -- remove the mean from each dimension\n in I.listArray (1,cols m) $ toRows $ (tr' m) <> (fromRows $ I.elems d')\n\n-- | perform a dimension-reducing PCA modification, \n-- using an eigenvalue threshhold\npcaReduce :: I.Array Int (Vector Double) -- ^ the data\n -> Double -- ^ eigenvalue threshold\n -> I.Array Int (Vector Double) -- ^ the reduced data\npcaReduce d q = let u = fmap (scalar . mean) d\n d' = zipWith (-) (I.elems d) (I.elems u)\n d'' = fromColumns d'\n (_,vec',uni') = svd d''\n vec = toList vec'\n uni = toColumns uni'\n v' = zip vec uni\n v = filter (\\(x,_) -> x > q) v' -- keep only eigens > than parameter\n m = fromColumns $ snd $ unzip v\n in I.listArray (I.bounds d) $ zipWith (+) (toRows $ m <> (tr' m) <> fromRows d') (I.elems u) \n\n-- | perform a dimension-reducing PCA modification, using N components\npcaReduceN :: I.Array Int (Vector Double) -- ^ the data\n -> Int -- ^ N, the number of components\n -> I.Array Int (Vector Double) -- ^ the reduced data, with n principal components\npcaReduceN d n = let u = fmap (scalar . mean) d\n d' = zipWith (-) (I.elems d) (I.elems u)\n d'' = fromColumns d'\n (_,vec',uni') = svd d''\n vec = toList vec'\n uni = toColumns uni'\n v' = zip vec uni\n v = take n $ reverse $ sortBy (comparing fst) v'\n m = fromColumns $ snd $ unzip v\n in I.listArray (I.bounds d) $ zipWith (+) (toRows $ m <> (tr' m) <> fromRows d') (I.elems u) \n\n-----------------------------------------------------------------------------\n", "meta": {"hexsha": "276c2e3b90a6173fec76181f44eb3a1228451b94", "size": 4933, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/Statistics/PCA.hs", "max_stars_repo_name": "amcphail/hstatistics", "max_stars_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-05-14T19:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T15:23:53.000Z", "max_issues_repo_path": "lib/Numeric/Statistics/PCA.hs", "max_issues_repo_name": "amcphail/hstatistics", "max_issues_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-12-14T23:36:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T23:18:48.000Z", "max_forks_repo_path": "lib/Numeric/Statistics/PCA.hs", "max_forks_repo_name": "amcphail/hstatistics", "max_forks_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-05-24T22:51:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T19:12:30.000Z", "avg_line_length": 44.4414414414, "max_line_length": 111, "alphanum_fraction": 0.4844921954, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6940075021663152}} {"text": "import Data.Complex\nimport System.Environment\nimport System.Process\n\nimport Lib\n\nfunc c z = z^2 + c\n\nphi = (1 + sqrt 5) / 2\n\nmain = do\n args <- getArgs\n \n let real:imag:_ = if null args then [1 - phi, 0] else read <$> args\n\n points = (:+) <$> [-1.5,-1.495..1.5] <*> [-1.2,-1.195..1.2]\n jset = c2t <$> filter (not . diverges 50 (func (real :+ imag))) points\n\n fileName = \"julia\" ++ show real ++ \"-\" ++ show imag ++ \".svg\"\n title = \"Julia Set for z^2 + \" ++ show real ++ \" + \" ++ show imag ++ \"i\"\n\n plotPoints fileName title 1.7 jset\n callCommand $ \"inkview \" ++ fileName\n", "meta": {"hexsha": "c42bd801d36c731556233faa6fbbb4e798a98944", "size": 614, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "projects/julia/Main.hs", "max_stars_repo_name": "ahaym/dynamics", "max_stars_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "projects/julia/Main.hs", "max_issues_repo_name": "ahaym/dynamics", "max_issues_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/julia/Main.hs", "max_forks_repo_name": "ahaym/dynamics", "max_forks_repo_head_hexsha": "393175c9f9db1449dc121cd3c6f778ee6da024d0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5833333333, "max_line_length": 80, "alphanum_fraction": 0.5456026059, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6939809997918972}} {"text": "{- \n - Module containing a few functions about rendering the fractals.\n-}\nmodule Rendering where\n\nimport Data.Complex\nimport Data.List\n\n-- RENDERING ----\nescape :: (RealFloat a, Fractional a) => [Complex a] -- list of samples\n -> (a -> a) -- Intensity mapping function \n -> a -- pixel brightness\nescape samples mapFunc = sum $ zipWith (\\x y -> mapFunc (magnitude (y - x)))\n samples (tail samples)\n\nfollow :: (RealFloat a, Fractional a) => [Complex a] -- list of samples\n -> (Complex a -> a) -- itensity function\n -> a\nfollow [] func = 0\nfollow samples func = func $ last samples\n\nsmooth :: (RealFloat a, Fractional a) => [Complex a]\n -> a \nsmooth samples = foldl' (+) 0 (map (exp . ((-1)*) . magnitude) samples)\n\n-- to get all values from iterating Julia\nsample :: (RealFloat a, Fractional a) => Int -- nbSamples\n -> (Complex a -> Bool) -- stopping condition\n -> (Complex a -> Complex a) -- how to get next point in serie\n -> Complex a -- starting point of serie (z0)\n -> [Complex a] -- list of samples\nsample nbsamples isValid funct start = ((takeWhile isValid).(take nbsamples).(iterate (funct))) start\n\nsampleIFS :: (RealFloat a, Fractional a) => Int -- nbSamples\n -> (Complex a -> Bool) -- stop condition\n -> [(Complex a -> Complex a)] -- list of functions to apply\n -> Complex a -- starting point\n -> [Complex a]\nsampleIFS nbSamples isValid functions start = (takeWhile isValid).(take nbSamples).\n (iterateList functions) $ start\n\niterateList :: [(a -> a)] -> a -> [a]\niterateList functions x = x : iterateList fs (f x) \n where (f:fs) = cycle functions\n", "meta": {"hexsha": "0b52c09becde68a33714af510748ba841ce36d97", "size": 1608, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Rendering.hs", "max_stars_repo_name": "Vetii/Fractal", "max_stars_repo_head_hexsha": "253dbcbccfcd3ee0ac05c08d72d1e80cf27016bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-06T04:52:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-06T04:52:50.000Z", "max_issues_repo_path": "Rendering.hs", "max_issues_repo_name": "Vetii/Fractal", "max_issues_repo_head_hexsha": "253dbcbccfcd3ee0ac05c08d72d1e80cf27016bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rendering.hs", "max_forks_repo_name": "Vetii/Fractal", "max_forks_repo_head_hexsha": "253dbcbccfcd3ee0ac05c08d72d1e80cf27016bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7333333333, "max_line_length": 101, "alphanum_fraction": 0.6449004975, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6939809820087344}} {"text": "-- vectorized boolean operations defined in terms of step or cond\n\nimport Numeric.LinearAlgebra\n\ninfix 4 .==., ./=., .<., .<=., .>=., .>.\ninfixr 3 .&&.\ninfixr 2 .||.\n\na .<. b = step (b-a)\na .<=. b = cond a b 1 1 0\na .==. b = cond a b 0 1 0\na ./=. b = cond a b 1 0 1\na .>=. b = cond a b 0 1 1\na .>. b = step (a-b)\n\na .&&. b = step (a*b)\na .||. b = step (a+b)\nno a = 1-a\nxor a b = a ./=. b\nequiv a b = a .==. b\nimp a b = no a .||. b\n\ntaut x = minElement x == 1\n\nminEvery a b = cond a b a a b\nmaxEvery a b = cond a b b b a\n\n-- examples\n\nclip a b x = cond y b y y b where y = cond x a a x x\n\ndisp = putStr . dispf 3\n\neye n = ident n :: Matrix Double\nrow = asRow . fromList :: [Double] -> Matrix Double\ncol = asColumn . fromList :: [Double] -> Matrix Double\n\nm = (3><4) [1..] :: Matrix Double\n\np = row [0,0,1,1]\nq = row [0,1,0,1]\n\nmain = do\n print $ find (>6) m\n disp $ assoc (6,8) 7 $ zip (find (/=0) (eye 5)) [10..]\n disp $ accum (eye 5) (+) [((0,2),3), ((3,1),7), ((1,1),1)]\n disp $ m .>=. 10 .||. m .<. 4\n (disp . fromColumns . map flatten) [p, q, p.&&.q, p .||.q, p `xor` q, p `equiv` q, p `imp` q]\n print $ taut $ (p `imp` q ) `equiv` (no q `imp` no p)\n print $ taut $ (xor p q) `equiv` (p .&&. no q .||. no p .&&. q)\n disp $ clip 3 8 m\n disp $ col [1..7] .<=. row [1..5]\n disp $ cond (col [1..3]) (row [1..4]) m 50 (3*m)\n\n", "meta": {"hexsha": "679b8bff7692a8c220f9843b02488c054d39d11d", "size": 1376, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/bool.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/bool.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/bool.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": 25.0181818182, "max_line_length": 97, "alphanum_fraction": 0.4832848837, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6936493541219535}} {"text": "-- example 3.22\n\nimport Statistics.Distribution\nimport Statistics.Distribution.Poisson\n\n-- three accidents per month means six accidents per two-months:\npd :: PoissonDistribution\npd = poisson 6.0\n\np :: Int -> Double\np = probability pd \n\nmain = do\n putStrLn $ \"the mean = \" ++ show (mean pd)\n putStrLn $ \"the stdDev = \" ++ show (stdDev pd)\n putStrLn $ \"the probability of ten accidents in two months: \" ++ show (p 10)\n", "meta": {"hexsha": "0c23e896bf42cb0ba1d9084162bdb7e89cb2e8e3", "size": 422, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ch03/ex3_22.hs", "max_stars_repo_name": "raydsameshima/Stat", "max_stars_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch03/ex3_22.hs", "max_issues_repo_name": "raydsameshima/Stat", "max_issues_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch03/ex3_22.hs", "max_forks_repo_name": "raydsameshima/Stat", "max_forks_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": 24.8235294118, "max_line_length": 78, "alphanum_fraction": 0.6966824645, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7577943822145997, "lm_q1q2_score": 0.6933068092514406}} {"text": "{-# LANGUAGE NamedFieldPuns #-}\n\nmodule School.Unit.Affine\n( affine ) where\n\nimport Numeric.LinearAlgebra ((<>), R, add, tr')\nimport School.Unit.Unit (Unit(..))\nimport School.Unit.UnitActivation (UnitActivation(..))\nimport School.Unit.UnitParams (UnitParams(..))\nimport School.Unit.UnitGradient (UnitGradient(..))\nimport School.Utils.LinearAlgebra (mapRows, sumRows)\n\naffine :: Unit Double\naffine = Unit\n { apply = affineApply\n , deriv = affineDeriv\n }\n\naffineApply :: UnitParams R\n -> UnitActivation R\n -> UnitActivation R\naffineApply AffineParams { affineBias, affineWeights }\n (BatchActivation inMatrix) =\n BatchActivation $ mapRows (add affineBias) (inMatrix <> tr' affineWeights)\naffineApply _ (ApplyFail msg) = ApplyFail msg\naffineApply _ _ = ApplyFail \"Failure when applying affine unit\"\n\nfailure :: String\n -> ( UnitGradient R\n , UnitParams R\n )\nfailure msg = (GradientFail msg, EmptyParams)\n\naffineDeriv :: UnitParams R\n -> UnitGradient R\n -> UnitActivation R\n -> ( UnitGradient R\n , UnitParams R\n )\naffineDeriv AffineParams { affineWeights }\n (BatchGradient inGrad)\n (BatchActivation input) =\n (outGrad, paramDerivs) where\n outGrad = BatchGradient $ inGrad <> affineWeights\n bias = sumRows inGrad\n weights = tr' inGrad <> input\n paramDerivs = AffineParams { affineBias = bias\n , affineWeights = weights\n }\naffineDeriv _ (GradientFail msg) _ = failure msg\naffineDeriv _ _ (ApplyFail msg) = failure msg\naffineDeriv _ _ _ = failure \"Failure when differentiating affine unit\"\n", "meta": {"hexsha": "78a7cd224b9477a3d1ddc871a54fa0dfef30d999", "size": 1702, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/School/Unit/Affine.hs", "max_stars_repo_name": "jfulseca/School", "max_stars_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/School/Unit/Affine.hs", "max_issues_repo_name": "jfulseca/School", "max_issues_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/School/Unit/Affine.hs", "max_forks_repo_name": "jfulseca/School", "max_forks_repo_head_hexsha": "cdc66fc21fc5342596ac37d920d810879bb09c3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1132075472, "max_line_length": 76, "alphanum_fraction": 0.6504112808, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.693227971798383}} {"text": "{- |\n\nThis module defines the monad of sampling functions. See\n\nPark, Pfenning and Thrun (2005) A probabilistic language based upon sampling\nfunctions, Principles of Programming Languages 2005\n\nSampling functions allow the composition of both discrete and continuous\nprobability distributions.\n\nThe implementation and interface are similar to those in the random-fu,\nmonte-carlo and monad-mersenne-random packages.\n\nExample -- a biased coin:\n\n@\ndata Throw = Head | Tail\n\nthrow bias = do\n b <- bernoulli bias\n return $ if b then Head else Tail\n\ntenThrowsCrooked = replicateM 10 $ throw 0.3\n\ncountHeads = do\n throws <- tenThrowsCrooked\n return $ length [ () | Head <- throws]\n\nmain = do\n print =<< sampleIO tenThrowsCrooked\n print =<< eval ((\\<4) \\`fmap\\` countHeads)\n@\n\n-}\n\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}\n\nmodule Math.Probably.Sampler where\n\nimport Control.Monad\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport qualified Math.Probably.PDF as PDF\nimport Math.Probably.Types\nimport Numeric.LinearAlgebra hiding (find)\nimport System.Environment\nimport System.Random.Mersenne.Pure64\n\n-- | given a seed, return an infinite list of draws from sampling function\nrunProb :: Seed -> Prob a -> [a]\nrunProb pmt s@(Sampler sf)\n = let (x, pmt') = sf pmt\n in x : runProb pmt' s\nrunProb _ (Samples xs) = xs\n\n-- | given a seed, return an infinite list of draws from sampling function\nrunProbOne :: Seed -> Prob a -> (a,Seed)\nrunProbOne pmt (Sampler sf)\n = sf pmt\nrunProbOne pmt (Samples xs) = primOneOf xs pmt\n\n\n\n-- | Get a seed\ngetSeedIO :: IO Seed\ngetSeedIO = do\n args <- getArgs\n case mapMaybe (stripPrefix \"--seed=\") args of\n [] -> newPureMT\n sdStr:_ -> return $ pureMT $ read sdStr\n\n-- | Return an infinite list of draws from sampling function in the IO monad\nrunProbIO :: Prob a -> IO [a]\nrunProbIO s =\n fmap (`runProb` s) $ getSeedIO\n\n-- | Return a singe draw from sampling function\nsampleIO :: Prob a -> IO a\nsampleIO s = head `fmap` runProbIO s\n\n-- | Return a list of n draws from sampling function\nsampleNIO :: Int -> Prob a -> IO [a]\nsampleNIO n s = take n `fmap` runProbIO s\n\n-- | Estimate the probability that a hypothesis is true (in the IO monad)\neval :: Prob Bool -> Prob Double\neval s = do\n bs <- replicateM 1000 s\n return $ realToFrac (length (filter id bs)) / 1000\n\n\n\n{-mu :: Vector Double\nsigma :: Matrix Double\n\nmystery = -1\nmu = fromList [0,0,0]\nsigma = (3><3) [ 1, 1, 0,\n 1, 1, mystery,\n 0, mystery, 1]\n\n\nsamIt = sampleNIO 2 $ multiNormal mu sigma\n -}\n-- | The joint distribution of two independent distributions\njoint :: Prob a -> Prob b -> Prob (a,b)\njoint sf1 sf2 = liftM2 (,) sf1 sf2\n\n-- | The joint distribution of two distributions where one depends on the other\njointConditional :: Prob a -> (a-> Prob b) -> Prob (a,b)\njointConditional sf1 condsf\n = do x <- sf1\n y <- condsf x\n return (x,y)\n\n--replicateM :: Monad m => Int -> m a -> m [a]\n--replicateM n ma = forM [1..n] $ const ma\n\n\n-- * Uniform distributions\n\n-- | The unit interval U(0,1)\nunit :: Prob Double\nunit = Sampler randomDouble\n\n-- | for x and y, the uniform distribution between x and y\nuniform :: (Fractional a) => a -> a -> Prob a\nuniform a b = (\\x->(realToFrac x)*(b-a)+a) `fmap` unit\n\n-- | useful for data display\njitter :: Double -> [Int] -> Prob [Double]\njitter j = mapM $ \\i-> let x = realToFrac i in uniform (x-j) (x+j)\n\n-- * Normally distributed sampling function\n\n--http://en.wikipedia.org/wiki/Box-Muller_transform\n-- | The univariate gaussian (normal) distribution defined by mean and standard deviation\n\nunormal :: Prob Double\nunormal = do\n u1 <- unit\n u2 <- unit\n return (sqrt ((0.0-2.0) * log u1) * cos(2.0 * pi * u2))\n\nnormal :: Double -> Double -> Prob Double\nnormal mean variance = do\n u <- unormal\n return (u * (sqrt variance) + mean)\n\n\n\nnormalMany :: [(Double,Double)] -> Prob [Double]\nnormalMany means_vars = do gus <- normalManyUnit (length means_vars)\n return $ map f $ zip gus means_vars\n where f (gu, (mean, var)) = gu*(sqrt var)+mean\n\n\nnormalManyUnit :: Int -> Prob [Double]\nnormalManyUnit 0 = return []\nnormalManyUnit n | odd n = liftM2 (:) unormal (normalManyUnit (n-1))\n | otherwise = do us <- forM [1..n] $ const $ unit\n return $ gaussTwoAtATime $ map realToFrac us\n where\n gaussTwoAtATime :: Floating a => [a] -> [a]\n gaussTwoAtATime (u1:u2:rest) = sqrt(-2*log(u1))*cos(2*pi*u2) : sqrt(-2*log(u1))*sin(2*pi*u2) : gaussTwoAtATime rest\n gaussTwoAtATime _ = []\n\n\n-- | Multivariate normal distribution\nmultiNormal :: Vector Double -> Matrix Double -> Prob (Vector Double)\nmultiNormal mu sigma =\n let c = cholSH sigma\n a = trans c\n k = dim mu\n in do z <- fromList `fmap` normalManyUnit k\n-- return $ mu + (head $ toColumns $ a*asRow z)\n let c = asColumn z\n let r = asRow z\n return $ (mu + (head $ toColumns $ a `multiply` asColumn z))\n\nmultiNormalByChol :: Vector Double -> Matrix Double -> Prob (Vector Double)\nmultiNormalByChol mu cholSigma =\n let a = trans $ cholSigma\n k = dim mu\n in do z <- fromList `fmap` normalManyUnit k\n-- return $ mu + (head $ toColumns $ a*asRow z)\n let c = asColumn z\n let r = asRow z\n return $ (mu + (head $ toColumns $ a `multiply` asColumn z))\n\nmultiNormalIndep :: Vector Double -> Vector Double -> Prob (Vector Double)\nmultiNormalIndep vars mus = do\n let k = dim mus\n gs <- normalManyUnit k\n return $ fromList $ zipWith3 (\\var mu g -> g*sqrt(var) + mu) (toList vars) (toList mus) gs\n\n\n\n--http://en.wikipedia.org/wiki/Log-normal_distribution#Generating_log-normally-distributed_random_variates\n\n-- | log-normal distribution \nlogNormal :: Double -> Double -> Prob Double\nlogNormal m var =\n fmap exp $ normal m var\n\n-- * Other distribution\n\n-- | Bernoulli distribution. Returns a Boolean that is 'True' with probability 'p'\nbernoulli :: Double -> Prob Bool\nbernoulli p = ( Prob a\ndiscrete weightedSamples =\n let sumWeights = sum $ map fst weightedSamples\n cummWeightedSamples = scanl (\\(csum,_) (w,x) -> (csum+w,x)) (0,undefined) $ sortBy (comparing fst) weightedSamples\n in do u <- unit\n case find ((>=u*sumWeights) . fst) cummWeightedSamples of\n Just (_,x) -> return x\n Nothing -> error $ \"discrete error u*sumweigts=\"++show (u*sumWeights)++\"wsams=\"++show (map fst cummWeightedSamples)\n\n-- primOneOf :: [a] -> Seed -> (a, Seed)\n-- primOneOf xs seed\n-- = let (u, nextSeed) = randomDouble seed\n-- idx = floor $ (realToFrac u)*(realToFrac $ length xs )\n-- in (xs !! idx, nextSeed)\n\nshuffle :: [a] -> Prob [a]\nshuffle xs = do\n uxs <- forM xs $ \\x -> do\n u <- unit\n return (u,x)\n return $ map snd $ sortBy (comparing fst) uxs\n\noneOf :: [a] -> Prob a\noneOf xs = do idx <- floor `fmap` uniform (0::Double) (realToFrac $ length xs )\n return $ xs !! idx\n\nnOf :: Int -> [a] -> Prob [a]\nnOf n xs = sequence $ replicate n $ oneOf xs\n\n\n--sampling without replacement. Terrible performance\nnDistinctOf :: Int -> [a] -> Prob [a]\nnDistinctOf wantN xs = do\n let haveN = length xs\n select ys | length ys == wantN = return ys\n | otherwise = do\n y <- floor `fmap` uniform (0::Double) (realToFrac $ length xs )\n if y `elem` ys\n then select ys\n else select (y:ys)\n ixs <- select []\n return $ map (xs!!) ixs\n\nwithoutReplacementFrom :: Eq a => Int -> Prob a -> Prob [a]\nwithoutReplacementFrom wantN p = select [] where\n select ys | length ys == wantN = return ys\n | otherwise = do\n y <- p\n if y `elem` ys\n then select ys\n else select (y:ys)\n\n\n-- | Bayesian inference from likelihood and prior using rejection sampling.\nbayesRejection :: (PDF.PDF a) -> Double -> Prob a -> Prob a\nbayesRejection p c q = bayes\n where bayes = do x <- q\n u <- unit\n if u < p x / c\n then return x\n else bayes\n\n--poisson :: :: Double -> [Double] -> IO Double\n-- | Exponential distribution\nexpDist rate = (\\u-> negate $ (log(1-u))/rate) `fmap` unit\n\npoissonAux :: Double -> Int -> Double -> Prob Int\npoissonAux bigl k p = if p>bigl\n then do\n u<- unit\n poissonAux bigl (k+1) (p*u)\n else return (k-1)\n\npoisson :: Double -> (Prob Int)\npoisson lam = poissonAux (exp (-lam)) 0 1\n\n\n-- | binomial distribution\nbinomial :: Int -> Double -> Prob Int\nbinomial n p = do\n bools <- forM [1..n] $ const $ fmap ( Double -> Prob Double\ngamma a b\n | a < 1\n = do\n u <- unit\n x <- gamma (1 + a) b\n return (x * u ** recip a)\n | otherwise\n = go\n where\n d = a - (1 / 3)\n c = recip (3 * sqrt d) -- (1 / 3) / sqrt d\n\n go = do\n x <- unormal\n\n let cx = c * x\n v = (1 + cx) ^ 3\n\n x_2 = x * x\n x_4 = x_2 * x_2\n\n if cx <= (-1)\n then go\n else do\n u <- unit\n\n if u < 1 - 0.0331 * x_4\n || log u < 0.5 * x_2 + d * (1 - v + log v)\n then return (b * d * v)\n else go\n\n-- | inverse gamma distribution\ninvGamma :: Double -> Double -> Prob Double\ninvGamma a b = recip `fmap` gamma a b\n\n-- | beta distribution\nbeta :: Int -> Int -> Prob Double\nbeta a b =\n let gam n = do us <- forM [1..n] $ const unit\n return $ log $ product us\n in do gama1 <- gamma (realToFrac a) 1\n\n gamb <- gamma (realToFrac b) 1\n return $ gama1/(gama1+gamb)\n", "meta": {"hexsha": "fe40b117a5138993ef30b33b39845282ff66e462", "size": 10199, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/Sampler.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/Sampler.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/Sampler.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 29.5623188406, "max_line_length": 126, "alphanum_fraction": 0.5926071183, "num_tokens": 2918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6932255466131693}} {"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Grenade.Utils.LinearAlgebra\n ( bmean\n , bvar\n , bvar'\n , vsqrt\n , msqrt\n , sreshape\n , sflatten\n , vscale\n , vadd\n , vflatten\n , nsum\n , sumV\n , sumM\n , squareV\n , squareM\n , extractV\n , extractM2D\n , batchNormMean\n , batchNormVariance\n , vectorToList\n , listToVector\n ) where\n\nimport Data.List (foldl')\nimport Data.Maybe (fromJust)\nimport Data.Proxy\nimport Data.Singletons\n\nimport GHC.TypeLits\n\nimport Numeric.LinearAlgebra hiding (R)\nimport Numeric.LinearAlgebra.Static (L, R)\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport Grenade.Core.Shape\nimport Grenade.Types\n\nsumV :: (KnownNat n) => R n -> RealNum\nsumV v = v H.<.> 1\n\nsumM :: (KnownNat m, KnownNat n) => L m n -> RealNum\nsumM m = (m H.#> 1) H.<.> 1\n\nsquareV :: (KnownNat n) => R n -> R n\nsquareV = H.dvmap (^ (2 :: Int))\n\nsquareM :: (KnownNat m, KnownNat n) => L m n -> L m n\nsquareM = H.dmmap (^ (2 :: Int))\n\n-- | Helper function that sums the elements of a matrix\nnsum :: S s -> RealNum\nnsum (S1D x) = sumElements $ H.extract x\nnsum (S2D x) = sumElements $ H.extract x\nnsum (S3D x) = sumElements $ H.extract x\nnsum (S4D x) = sumElements $ H.extract x\n\n-- | Calculate elementwise mean of list of matrices\nbmean :: forall s. SingI s => [S s] -> S s\nbmean xs\n = let (!m, !l) = foldl' (\\(m, l) x -> (m + x, l + 1)) (0 :: S s, 0) xs :: (S s, Int)\n in case (m, l) of\n (S1D x, _) -> S1D $ H.dvmap (/ fromIntegral l) x\n (S2D x, _) -> S2D $ H.dmmap (/ fromIntegral l) x\n (S3D x, _) -> S3D $ H.dmmap (/ fromIntegral l) x\n (S4D x, _) -> S4D $ H.dmmap (/ fromIntegral l) x\n\n-- | Calculate element wise variance\nbvar :: forall s. SingI s => [S s] -> S s\nbvar xs\n = let !m = bmean xs\n (!v, !l) = foldl' (\\(v, l) x -> (v + (x - m)**2, l + 1)) (0 :: S s, 0) xs :: (S s, Int)\n in case (v, l) of\n (S1D x, _) -> S1D $ H.dvmap (/ fromIntegral l) x\n (S2D x, _) -> S2D $ H.dmmap (/ fromIntegral l) x\n (S3D x, _) -> S3D $ H.dmmap (/ fromIntegral l) x\n (S4D x, _) -> S4D $ H.dmmap (/ fromIntegral l) x\n\n-- | Calculate element wise variance, with the mean precalculated\nbvar' :: forall s. SingI s => S s -> [S s] -> S s\nbvar' m xs\n = let (!v, !l) = foldl' (\\(v, l) x -> (v + (x - m)**2, l + 1)) (0 :: S s, 0) xs :: (S s, Int)\n in case (v, l) of\n (S1D x, _) -> S1D $ H.dvmap (/ fromIntegral l) x\n (S2D x, _) -> S2D $ H.dmmap (/ fromIntegral l) x\n (S3D x, _) -> S3D $ H.dmmap (/ fromIntegral l) x\n (S4D x, _) -> S4D $ H.dmmap (/ fromIntegral l) x\n\nbatchNormMean :: forall n. KnownNat n => [R n] -> RealNum\nbatchNormMean vs \n = let hw = fromIntegral $ natVal (Proxy :: Proxy n)\n vs' = map (sumElements . H.extract) vs :: [RealNum]\n n = fromIntegral $ length vs \n in sum vs' / (hw * n)\n\nbatchNormVariance :: forall n. KnownNat n => [R n] -> RealNum\nbatchNormVariance vs \n = let mu = batchNormMean vs\n hw = fromIntegral $ natVal (Proxy :: Proxy n)\n vs' = map (sumElements . H.extract . H.dvmap (\\a -> (a - mu) ^ (2 :: Int))) vs :: [RealNum] \n n = fromIntegral $ length vs \n in sum vs' / (hw * n)\n\nextractV :: S ('D1 x) -> R x\nextractV (S1D v) = v\n\nextractM2D :: S ('D2 x y) -> L x y\nextractM2D (S2D m) = m\n\nvscale :: KnownNat n => RealNum -> R n -> R n\nvscale = H.dvmap . (*)\n\nvadd :: KnownNat n => RealNum -> R n -> R n\nvadd = H.dvmap . (+)\n\nvsqrt :: KnownNat n => R n -> R n\nvsqrt = H.dvmap sqrt\n\nmsqrt :: (KnownNat n, KnownNat m) => L m n -> L m n\nmsqrt = H.dmmap sqrt\n\nvflatten :: (KnownNat m, KnownNat n) => [R n] -> R m\nvflatten xs = fromJust . H.create . flatten . fromRows $ map H.extract xs\n\nsflatten :: (KnownNat m, KnownNat n) => L m n -> R (m * n)\nsflatten = fromJust . H.create . flatten . H.extract\n\nsreshape :: forall m n. (KnownNat m, KnownNat n) => R (m * n) -> L m n\nsreshape v\n = let rows = fromIntegral $ natVal (Proxy :: Proxy m)\n in fromJust . H.create . reshape rows . H.extract $ v\n\nvectorToList :: KnownNat n => R n -> [RealNum]\nvectorToList = toList . H.extract\n\nlistToVector :: KnownNat n => [RealNum] -> R n\nlistToVector = fromJust . H.create . fromList\n\n-- bsqrt :: SingI s => [S s] -> [S s]\n-- bsqrt xs = map msqrt xs\n\n-- msqrt :: SingI s => S s -> S s\n-- msqrt (S1D x) = S1D $ dvmap sqrt x\n-- msqrt (S2D x) = S2D $ dmmap sqrt x\n-- msqrt (S3D x) = S3D $ dmmap sqrt x\n\n-- mscale :: SingI s => RealNum -> S s -> S s\n-- mscale r (S1D x) = S1D $ dvmap (* r) x\n-- mscale r (S2D x) = S2D $ dmmap (* r) x\n-- mscale r (S3D x) = S3D $ dmmap (* r) x\n\n-- madd :: SingI s => RealNum -> S s -> S s\n-- madd r (S1D x) = S1D $ dvmap (+ r) x\n-- madd r (S2D x) = S2D $ dmmap (+ r) x\n-- madd r (S3D x) = S3D $ dmmap (+ r) x\n", "meta": {"hexsha": "3a3dd14e13e4002522664b0bc4dfbcef1d2f52c4", "size": 5160, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Utils/LinearAlgebra.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/Utils/LinearAlgebra.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/Utils/LinearAlgebra.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2727272727, "max_line_length": 100, "alphanum_fraction": 0.5445736434, "num_tokens": 1861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6932045970815609}} {"text": "module Math.Probably.Student where\n\nimport Numeric.LinearAlgebra\nimport Math.Probably.FoldingStats\nimport Text.Printf\n\n--http://www.haskell.org/haskellwiki/Gamma_and_Beta_function\n--cof :: [Double]\ncof = [76.18009172947146,-86.50532032941677,24.01409824083091,\n -1.231739572450155,0.001208650973866179,-0.000005395239384953]\n \n--ser :: Double\nser = 1.000000000190015\n \n--gammaln :: Double -> Double\ngammaln xx = let tmp' = (xx+5.5) - (xx+0.5)*log(xx+5.5)\n ser' = foldl (+) ser $ map (\\(y,c) -> c/(xx+y)) $ zip [1..] cof\n in -tmp' + log(2.5066282746310005 * ser' / xx)\n\nbeta z w = exp (gammaln z + gammaln w - gammaln (z+w))\n\nfac :: (Enum a, Num a) => a -> a\nfac n = product [1..n]\n\nixbeta :: (Enum a, Floating a) => a -> a -> a -> a\nixbeta x a b = let top = fac $ a+b-1 \n down j = fac j * fac (a+b-1-j) \n in sum $ map (\\j->(top/down j)*(x**j)*(1-x)**(a+b-1-j)) [a..a+b-1]\n\nstudentIntegral :: (Enum a, Floating a) => a -> a -> a\nstudentIntegral t v = 1-ixbeta (v/(v+t*t)) (v/2) (1/2)\n\n\ntTerms :: Vector Double\ntTerms = fromList $ map tTermUnmemo [1..100]\n\ntTermUnmemo :: Int -> Double\ntTermUnmemo nu = gammaln ((realToFrac nu+1)/2) - log(realToFrac nu*pi)/2 - gammaln (realToFrac nu/2)\n\ntTerm1 :: Int -> Double\ntTerm1 df | df <= 100 = tTerms@>df\n | otherwise = tTermUnmemo df\n\ntDist :: Int -> Double -> Double\ntDist df t = tTerm1 df - (realToFrac df +1/2) * log (1+(t*t)/(realToFrac df))\n\ntDist3 :: Double -> Double -> Int -> Double -> Double\ntDist3 mean prec df x \n = tTerm1 df \n + log(prec)/2 \n - (realToFrac df +1/2) * log (1+(prec*xMinusMu*xMinusMu)/(realToFrac df))\n where xMinusMu = x-mean\n\noneSampleT :: Floating b => b -> Fold b b\noneSampleT v0 = fmap (\\(mean,sd,n)-> (mean - v0)/(sd/(sqrt n))) meanSDNF \n\npairedSampleT :: Fold (Double, Double) Double\npairedSampleT = before (fmap (\\(mean,sd,n)-> (mean)/(sd/(sqrt n))) meanSDNF)\n (uncurry (-))\n\ndata TTestResult = TTestResult { degFreedom :: Int,\n tValue :: Double,\n pValue :: Double }\n\nppTTestRes :: TTestResult -> String\nppTTestRes (TTestResult df tval pval) = printf \"paired t(%d)=%.3g, p=%.3g\" df tval pval\n\npairedTTest :: [(Double,Double)] -> TTestResult\npairedTTest vls =\n let tval = runStat pairedSampleT vls\n df = length vls - 1\n pval = (1-) $ studentIntegral (tval) (realToFrac df)\n in TTestResult df tval pval\n\noneSampleTTest :: [Double] -> TTestResult\noneSampleTTest vls =\n let tval = runStat (oneSampleT 0) vls\n df = length vls - 1\n pval = (1-) $ studentIntegral (tval) (realToFrac df)\n in TTestResult df tval pval\n", "meta": {"hexsha": "7c076af47b0e0c138d86dcafe49b46d757dbca82", "size": 2739, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/Student.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/Student.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/Student.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": 33.8148148148, "max_line_length": 100, "alphanum_fraction": 0.5932822198, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6927220023264384}} {"text": "\n{-# LANGUAGE BangPatterns, TypeFamilies #-}\n\nmodule Fractal2D ( mandelbrot\n , juliaAnimated\n ) where\n\nimport Control.Loop\nimport Control.Monad\nimport Data.Complex\nimport Data.Word\nimport Data.Bits\nimport qualified Data.Vector.Storable.Mutable as VSM\n\nimport ConcurrentSegments\n\n-- A few simple 2D fractals, just for testing\n\nmagnitudeSq :: RealFloat a => Complex a -> a\nmagnitudeSq c = realPart c * realPart c + imagPart c * imagPart c\n\n-- http://linas.org/art-gallery/escape/escape.html\n-- http://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring\nfractionalIterCnt :: Int -> Complex Float -> Float\nfractionalIterCnt iter escZ = max 0 $ fromIntegral iter - (log (log $ magnitudeSq escZ)) / log 2\n\n-- Mandelbrot Set\n--\n-- http://en.wikipedia.org/wiki/Mandelbrot_set#Computer_drawings\nmandelbrot :: Int -> Int -> VSM.IOVector Word32 -> Bool -> IO ()\nmandelbrot w h fb smooth =\n forLoop 0 (< h) (+ 1) $ \\py -> forLoop 0 (< w) (+ 1) $ \\px ->\n let idx = px + py * w\n fpx = fromIntegral px :: Float\n fpy = fromIntegral py :: Float\n fw = fromIntegral w :: Float\n fh = fromIntegral h :: Float\n ratio = fw / fh\n y = (fpy / fh) * 2 - 1 -- Y axis is [-1, +1]\n xshift = (- 2) - ((2 * ratio - 2.5) * 0.5)\n x = (fpx / fw) * 2 * ratio + xshift -- Keep aspect and center [-1, +0.5]\n c = x :+ y\n maxIter = 40\n (iCnt, escZ) = go (0 :: Int) (0 :+ 0)\n go iter z | (iter == maxIter) || -- Iteration limit?\n magnitudeSq z > 4 * 4 = (iter, z) -- Hit escape radius?\n | otherwise = let newZ = z * z + c\n in if newZ == z -- Simple 1-cycle detection\n then (maxIter, z)\n else go (iter + 1) newZ\n icCont | iCnt == maxIter = fromIntegral maxIter -- Interior in case of limit\n | otherwise = fractionalIterCnt iCnt escZ\n toGreen v = v `unsafeShiftL` 8\n in VSM.unsafeWrite fb idx . toGreen . truncate $\n if smooth\n then icCont / fromIntegral maxIter * 255 :: Float\n else fromIntegral iCnt / fromIntegral maxIter * 255 :: Float\n\n-- Julia Set, computed in parallel\n--\n-- http://en.wikipedia.org/wiki/Julia_set\n-- http://www.relativitybook.com/CoolStuff/julia_set.html\njuliaAnimated :: Int -> Int -> VSM.IOVector Word32 -> Bool -> Double -> IO ()\njuliaAnimated w h fb smooth tick =\n let !fTick = realToFrac tick :: Float\n !scaledTick = snd (properFraction $ fTick / 17 :: (Int, Float))\n !scaledTick2 = snd (properFraction $ fTick / 61 :: (Int, Float))\n !scaledTick3 = snd (properFraction $ fTick / 71 :: (Int, Float))\n !twoPi = scaledTick * 2 * pi\n !juliaR = sin twoPi * max 0.7 scaledTick2\n !juliaI = cos twoPi * max 0.7 scaledTick3\n !fw = fromIntegral w :: Float\n !fh = fromIntegral h :: Float\n !ratio = fw / fh\n !xshift = 1.45 * ratio\n !maxIter = 40\n doSeg lo hi = forLoop lo (< hi) (+ 1) $ \\py -> forLoop 0 (< w) (+ 1) $ \\px ->\n let idx = px + py * w\n fpx = fromIntegral px :: Float\n fpy = fromIntegral py :: Float\n y = (fpy / fh) * 2.9 - 1.45 -- Y axis is [-1.45, +1.45]\n x = (fpx / fw) * 2.9 * ratio - xshift -- Keep aspect and center\n c = x :+ y\n (iCnt, escZ) = go (0 :: Int) c\n go iter z | (iter == maxIter) || -- Iteration limit?\n magnitudeSq z > 4 * 4 = (iter, z) -- Hit escape radius?\n | otherwise = let newZ = z * z + (juliaR :+ juliaI)\n in if newZ == z -- Simple 1-cycle detection\n then (maxIter, z)\n else go (iter + 1) newZ\n icCont | iCnt == maxIter = fromIntegral maxIter -- Interior in case of limit\n | otherwise = fractionalIterCnt iCnt escZ\n toGreen v = v `unsafeShiftL` 8\n in VSM.unsafeWrite fb idx . toGreen . truncate $\n if smooth\n then icCont / fromIntegral maxIter * 255 :: Float\n else fromIntegral iCnt / fromIntegral maxIter * 255 :: Float\n in void $ forSegmentsConcurrently Nothing 0 h doSeg\n\n", "meta": {"hexsha": "605f67d1511c2088d2072ec9a41c2f4d1cdfdb19", "size": 4574, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Fractal2D.hs", "max_stars_repo_name": "blitzcode/ray-marching-distance-fields", "max_stars_repo_head_hexsha": "0578d01e75f819b1242fa1378e3963bd48842acc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2015-01-25T17:14:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T01:51:05.000Z", "max_issues_repo_path": "Fractal2D.hs", "max_issues_repo_name": "blitzcode/ray-marching-distance-fields", "max_issues_repo_head_hexsha": "0578d01e75f819b1242fa1378e3963bd48842acc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-10T17:17:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-10T17:17:39.000Z", "max_forks_repo_path": "Fractal2D.hs", "max_forks_repo_name": "blitzcode/ray-marching-distance-fields", "max_forks_repo_head_hexsha": "0578d01e75f819b1242fa1378e3963bd48842acc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-10-30T20:46:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:08:55.000Z", "avg_line_length": 45.74, "max_line_length": 96, "alphanum_fraction": 0.519239178, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6923195035144171}} {"text": "-- nonlinear least-squares fitting\n\n\nimport Spinell.Fitting\nimport Spinell.Graphing\nimport Numeric.LinearAlgebra\n\nmodel [a,lambda,b] t = a * exp (-lambda * t)+b --the function we will be fitting\n\njac [a,lambda,b] [t] = [[exp (-lambda * t), -t * a * exp(-lambda*t) , 1]]\n\nxs = [0..100]\n\nsigma = replicate (length xs) 0.1 -- will create an array of repeating '0.1': [0.1,0.1...]\n\nnoise = toList $ scalar 0.1 * (randomVector 0 Gaussian (length xs)) --a list of random small values, that will play the role of the noise in the data\n\nys = map (model [5,0.1,1]) xs --we plainly apply the model to the data\n\nysNoisy = [ y + err | (y,err) <- zip ys noise] -- and then add the noise, just to make it look more realistic\n\nres = fit xs ys sigma model [1,1,1] defFitOpt{jacob = ManualJacob jac}\n\nmain :: IO()\nmain = plotFit xs ysNoisy sigma model (getParams res) defGraphOpt\n", "meta": {"hexsha": "18a168291745f0c9e5baf5c1a0d89037ba35e5e9", "size": 863, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/fitting.hs", "max_stars_repo_name": "Magalame/Spinell", "max_stars_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/fitting.hs", "max_issues_repo_name": "Magalame/Spinell", "max_issues_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/fitting.hs", "max_forks_repo_name": "Magalame/Spinell", "max_forks_repo_head_hexsha": "03e819e4164f6e0361b9b320002a34f123d47ecd", "max_forks_repo_licenses": ["BSD-3-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.1923076923, "max_line_length": 149, "alphanum_fraction": 0.6778679027, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6922331215618199}} {"text": "#!/usr/bin/env stack\n-- stack --resolver lts-11.1 --install-ghc runghc --package random\n{-# LANGUAGE TypeApplications #-}\nimport Data.Complex (Complex(..), magnitude)\nimport Control.Monad (replicateM, forM_)\nimport System.Random (randomIO)\nimport Text.Printf (printf)\n\napproximate :: Int -> IO Double\napproximate count = do\n let randomPoint = (:+) <$> randomIO <*> randomIO @Double\n randomPoints = flip replicateM randomPoint\n inCircle <- (length . filter (\\z -> magnitude z <= 1)) <$> randomPoints count\n pure $ 4 * (fromIntegral inCircle / fromIntegral count)\n\nmain = forM_ [1 .. 100000] $ \\n -> printf \"%6d %f\\n\" n =<< approximate n\n", "meta": {"hexsha": "d21cd0bb0efc3df1cc0792d172db355b13be9ebf", "size": 652, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/apiroximate.hs", "max_stars_repo_name": "kmein/a-pi-roximate", "max_stars_repo_head_hexsha": "26ee7c16ae26407420866fe77a565b53a73fe954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-16T08:54:13.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-16T08:54:13.000Z", "max_issues_repo_path": "haskell/apiroximate.hs", "max_issues_repo_name": "kmein/a-pi-roximate", "max_issues_repo_head_hexsha": "26ee7c16ae26407420866fe77a565b53a73fe954", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/apiroximate.hs", "max_forks_repo_name": "kmein/a-pi-roximate", "max_forks_repo_head_hexsha": "26ee7c16ae26407420866fe77a565b53a73fe954", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3529411765, "max_line_length": 81, "alphanum_fraction": 0.6809815951, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6920255738441452}} {"text": "{-|\nModule: MachineLearning.LogisticModel\nDescription: Logistic Regression Model\nCopyright: (c) Alexander Ignatyev, 2016\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\n-}\n\nmodule MachineLearning.LogisticModel\n(\n module MachineLearning.Model\n , LogisticModel(..)\n , sigmoid\n , sigmoidGradient\n)\n\nwhere\n\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra((<>), (#>), (<.>))\nimport qualified Data.Vector.Storable as V\n\nimport MachineLearning.Model\nimport qualified MachineLearning.Regularization as R\n\ndata LogisticModel = Logistic\n\n\n-- | Calculates sigmoid\nsigmoid :: Floating a => a -> a\nsigmoid z = 1 / (1+exp(-z))\n\n\n-- | Calculates derivatives of sigmoid\nsigmoidGradient :: Floating a => a -> a\nsigmoidGradient z = s * (1-s)\n where s = sigmoid z\n\n\ninstance Model LogisticModel where\n hypothesis Logistic x theta = sigmoid (x #> theta)\n\n cost m lambda x y theta =\n let h = hypothesis m x theta\n nExamples = fromIntegral $ LA.rows x\n tau = 1e-7\n jPositive = log(tau + h) <.> (-y)\n jNegative = log((1 + tau) - h) <.> (1-y)\n regTerm = R.costReg lambda theta\n in (jPositive - jNegative + regTerm) / nExamples\n\n gradient m lambda x y theta = (((LA.tr x) #> (h - y)) + regTerm) / nExamples\n where h = hypothesis m x theta\n nExamples = fromIntegral $ LA.rows x\n regTerm = R.gradientReg lambda theta\n", "meta": {"hexsha": "72484d2c1e58069bee3629e134bfe71c59aebe0c", "size": 1398, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/LogisticModel.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/LogisticModel.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/LogisticModel.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 24.1034482759, "max_line_length": 79, "alphanum_fraction": 0.6788268956, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.691436851868591}} {"text": "module NaiveBayes.GaussianNB\n ( train\n , predict\n , GaussianNB(..)\n ) where\nimport Data.List ((++))\nimport qualified Data.List as L\nimport Data.Map ((!))\nimport qualified Data.Map as M\nimport qualified Data.Vector.Unboxed as U\nimport Prelude hiding ((++))\nimport Statistics.Matrix as S\nimport Statistics.Sample as S\n\n-- Implementation taken from\n-- https://chrisalbon.com/machine_learning/naive_bayes/naive_bayes_classifier_from_scratch/\n\n-- | Usage Example\n--\n-- trainFeatures :: S.Matrix\n-- trainFeatures = S.fromRowLists\n-- [ [6.00, 180, 12]\n-- , [5.92, 190, 11]\n-- , [5.58, 170, 12]\n-- , [5.92, 165, 10]\n-- , [5.00, 100, 6]\n-- , [5.50, 150, 8]\n-- , [5.42, 130, 7]\n-- , [5.75, 150, 9]\n-- ]\n--\n-- trainLabels :: U.Vector Int\n-- trainLabels = U.fromList [0, 0, 0, 0, 1, 1, 1, 1]\n--\n-- trainedData = train trainFeatures trainLabels\n-- predict trainedData [6.00, 130, 8]\n-- 1\n\ndata GaussianNB = GaussianNB\n { cMeans :: M.Map Int [Double]\n , cVariances :: M.Map Int [Double]\n , cPriorProbs :: M.Map Int Double\n }\n\n\n deriving (Show)\n\nlabelsCounts :: U.Vector Int -> M.Map Int Int\nlabelsCounts = U.foldr' (\\x acc -> M.insertWith (+) x 1 acc) M.empty\n\nlabelsFeatures :: S.Matrix -> U.Vector Int -> M.Map Int [U.Vector Double]\nlabelsFeatures features labels =\n L.foldr\n (\\(l, fs) acc -> M.insertWith (++) l [fs] acc)\n M.empty\n (zip' labels features)\n\nzip' :: U.Vector Int -> S.Matrix -> [(Int, U.Vector Double)]\nzip' vec mx = U.ifoldr' (\\i x acc -> (x, S.row mx i):acc) [] vec\n\nmeans :: M.Map Int [U.Vector Double] -> M.Map Int [Double]\nmeans = fmap (fmap S.mean . S.toRows . S.transpose . S.fromRows)\n\nvariances :: M.Map Int [U.Vector Double] -> M.Map Int [Double]\nvariances =\n fmap (fmap S.variance . S.toRows . S.transpose . S.fromRows)\n\npriorProbs :: M.Map Int Int -> Int -> M.Map Int Double\npriorProbs mp totalCount =\n fmap (\\x -> fromIntegral x / fromIntegral totalCount) mp\n\ntrain :: Matrix -> U.Vector Int -> GaussianNB\ntrain features labels =\n let countMap = labelsCounts labels\n featuresMap = labelsFeatures features labels\n meansMap = means featuresMap\n variancesMap = variances featuresMap\n priorProbsMap = priorProbs countMap (U.length labels)\n in GaussianNB meansMap variancesMap priorProbsMap\n\npredict :: GaussianNB -> [Double] -> Int\npredict cf feature =\n fst $ L.maximumBy\n (\\(_, a) (_, b) -> a `compare` b)\n (M.toList (posteriorProbs cf feature))\n\nposteriorProbs :: GaussianNB -> [Double] -> M.Map Int Double\nposteriorProbs (GaussianNB ms vs pp) feature =\n M.mapWithKey (\\k x -> x * likelihoods k) pp\n where likelihoods k = L.product $\n L.map\n (\\(x, m, v) -> exp ((- ((x - m) ** 2)) / (2 * v)) / (sqrt (2 * pi * v)))\n (L.zip3 feature (ms ! k) (vs ! k))\n\n", "meta": {"hexsha": "1f655b66f0fc956db3364c1629f8a154ad95e920", "size": 2890, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NaiveBayes/GaussianNB.hs", "max_stars_repo_name": "abs-zero/haskellml", "max_stars_repo_head_hexsha": "9a8e40a4c06d4a9be8d439400e2722b8b2e3bf48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-01-28T01:22:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-29T02:38:10.000Z", "max_issues_repo_path": "src/NaiveBayes/GaussianNB.hs", "max_issues_repo_name": "abs-zero/haskellml", "max_issues_repo_head_hexsha": "9a8e40a4c06d4a9be8d439400e2722b8b2e3bf48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NaiveBayes/GaussianNB.hs", "max_forks_repo_name": "abs-zero/haskellml", "max_forks_repo_head_hexsha": "9a8e40a4c06d4a9be8d439400e2722b8b2e3bf48", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4210526316, "max_line_length": 91, "alphanum_fraction": 0.6093425606, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6911360809923747}} {"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GADTs, DataKinds, PolyKinds, ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-|\nModule : Grenade.Core.WeightInitialization\nDescription : Defines the Weight Initialization methods of Grenade.\nCopyright : (c) Manuel Schneckenreither, 2018\nLicense : BSD2\nStability : experimental\n\nThis module defines the weight initialization methods.\n\n-}\n\n\nmodule Grenade.Core.WeightInitialization\n ( getRandomVector\n , getRandomMatrix\n , WeightInitMethod (..)\n ) where\n\nimport Data.Proxy\nimport Control.Monad\n\nimport Data.Singletons.TypeLits\n\nimport Control.Monad.Primitive (PrimBase, PrimState)\nimport System.Random.MWC\nimport System.Random.MWC.Distributions\n\nimport GHC.TypeNats (type (*))\n\nimport Numeric.LinearAlgebra.Static\n\n\ndata WeightInitMethod = UniformInit -- ^ W_l,i ~ U(-1/sqrt(n_l),1/sqrt(n_l)) where n_l is the number of nodes in layer l\n | Xavier -- ^ W_l,i ~ U(-sqrt (6/n_l+n_{l+1}),sqrt (6/n_l+n_{l+1})) where n_l is the number of nodes in layer l\n | HeEtAl -- ^ W_l,i ~ N(0,sqrt(2/n_l)) where n_l is the number of nodes in layer l\n\n\n-- | Get a random vector initialized according to the specified method.\ngetRandomVector :: forall m n . (PrimBase m, KnownNat n) => Integer -> Integer -> WeightInitMethod -> Gen (PrimState m) -> m (R n)\ngetRandomVector i o method gen = do\n unifRands <- vector <$> replicateM n (uniformR (-1,1) gen)\n gaussRands <- vector <$> replicateM n (standard gen)\n\n return $ case method of\n UniformInit -> (1/sqrt (fromIntegral i)) * unifRands\n Xavier -> (sqrt 6/sqrt (fromIntegral i + fromIntegral o)) * unifRands \n HeEtAl -> sqrt (2/fromIntegral i) * gaussRands\n where n = fromIntegral $ natVal (Proxy :: Proxy n)\n\n\n-- | Get a matrix with weights initialized according to the specified method.\ngetRandomMatrix :: forall m r n nr . (PrimBase m, KnownNat r, KnownNat n, KnownNat nr, nr ~ (n*r))\n => Integer -> Integer -> WeightInitMethod -> Gen (PrimState m) -> m (L r n)\ngetRandomMatrix i o method gen = do\n unifRands <- matrix <$> replicateM nr (uniformR (-1,1) gen)\n gaussRands <- matrix <$> replicateM nr (standard gen)\n\n return $ case method of\n UniformInit -> (1/sqrt (fromIntegral i)) * unifRands\n Xavier -> (sqrt 6/sqrt (fromIntegral i + fromIntegral o)) * unifRands\n HeEtAl -> (sqrt (2/fromIntegral i)) * gaussRands\n\n\n where nr = fromIntegral $ natVal (Proxy :: Proxy nr)\n", "meta": {"hexsha": "ebf2f14e7f609e70b00d4c82ca2be1bbfe5fefe5", "size": 2735, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Core/WeightInitialization.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/Core/WeightInitialization.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/Core/WeightInitialization.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": 39.0714285714, "max_line_length": 144, "alphanum_fraction": 0.6314442413, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430803622103, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6909015388786919}} {"text": "import Data.Complex\nimport Data.Array\nimport Data.Ratio\nimport qualified Data.Map as M\n\nfft :: [Complex Double] -> [Complex Double]\nfft x = let n = length x\n i = 0 :+ 1\n w = M.fromList [(k%n, exp ((-2)*pi*i*(fromIntegral k)/(fromIntegral n)) ) | k<-[0..n-1]]\n arr = fft' n w (listArray (0,n-1) x)\n in [arr!k | k<-[0..n-1]]\n where\n fft' 1 _ x = x\n fft' n w x = let n2 = div n 2\n e = fft' n2 w (listArray (0, n2-1) [x!k | k<-[0,2..n-1]])\n o = fft' n2 w (listArray (0, n2-1) [x!k | k<-[1,3..n-1]])\n in array (0, n-1) $ concat [[(k, e!k + o!k * w M.!(k%n)),\n (k + n2, e!k - o!k * w M.!(k%n))]\n | k <- [0..n2-1]]\n\nmain = do\n print $ fft [0,1,2,3]\n", "meta": {"hexsha": "2c3eb11ba43a3d7b857351ce4bd17f4b912327a8", "size": 841, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "contents/cooley_tukey/code/haskell/fft.hs", "max_stars_repo_name": "atocil/algorithm-archive", "max_stars_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-16T17:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-16T17:42:24.000Z", "max_issues_repo_path": "contents/cooley_tukey/code/haskell/fft.hs", "max_issues_repo_name": "atocil/algorithm-archive", "max_issues_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-07-12T01:07:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-04T19:37:47.000Z", "max_forks_repo_path": "contents/cooley_tukey/code/haskell/fft.hs", "max_forks_repo_name": "atocil/algorithm-archive", "max_forks_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-19T10:04:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T10:04:37.000Z", "avg_line_length": 36.5652173913, "max_line_length": 100, "alphanum_fraction": 0.4042806183, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6901780341931393}} {"text": "module Vectorspace where\n\nimport Data.Complex\nimport Data.Maybe\n\nnewtype Vector a = Vector [a] deriving (Eq)\nnewtype Matrix a = Matrix [[a]] deriving (Eq)\n\ninstance Show a => Show (Vector a) where\n show (Vector v)\n | length v == 0 = \"()\"\n | length v == 1 = \"(\" ++ show (v!!0) ++ \")\"\n | length v == 2 = start v ++ end v\n | length v >= 3 = start v ++ center v ++ end v where\n start v = vectortop $ (show.head) v\n center v = concatMap (vectorcenter.show) ( (init.tail) v)\n end v = vectorbottom $ (show.last) v\n vectortop x = \"/\" ++ x ++ \"\\\\\\n\"\n vectorcenter x = \"|\" ++ x ++ \"|\\n\"\n vectorbottom x = \"\\\\\" ++ x ++ \"/\"\n\ninstance Show a => Show (Matrix a) where\n show (Matrix m) = start m ++ \"\\n\" ++ center m ++ \"\\n\" ++ end m where\n start m = (matrixtop.concat) [ cell v | v <- head m ]\n center m = (matrixcenter.concat) [ cell v | v <- (head.init.tail) m ]\n end m = (matrixbottom.concat) [ cell v | v <- last m ]\n matrixtop v = \"┌\" ++ v ++ \"┐\"\n matrixcenter v = \"│\" ++ v ++ \"│\"\n matrixbottom v = \"└\" ++ v ++ \"┘\"\n cell v = [ if i< length (show v) then (show v)!!i else ' ' | i <- [0..cellWidth] ]\n cellWidth = maximum $ map (length.show) $ concat m\n\ninstance Floating a => Num (Vector a) where\n -- componentwise addition\n (Vector v) + (Vector w)\n | length v == length w = Vector $ zipWith (+) v w\n | length v > length w = Vector v + Vector (take (length v) (w++repeat 0))\n | length v < length w = Vector w + Vector v\n (Vector v) * (Vector w) = Vector $ zipWith (*) v w\n negate (Vector v) = Vector $ map (*(-1)) v\n abs (Vector v) = Vector [sqrt $ sum (map (**2) v)]\n signum (Vector v) = Vector $ map signum v\n fromInteger n = Vector [fromInteger n]\n\n-- multiplies a vector by a scalar\nvecmul :: Integer -> [Integer] -> [Integer]\nvecmul a = map (*a)\n\n-- multiplies a matrix by a scalar\nmatscalmult :: Num a => [[a]] -> a -> [[a]]\nmatscalmult m s = map (\\y -> map (\\x -> (m!!y!!x)*s) [0..length (m!!y)-1]) [0..length m-1]\n\n-- multiplies / composes two matrices\nmatmult :: Num a => [[a]] -> [[a]] -> [[a]]\nmatmult m n\n | length m > length n = matmult m (scale n (length m))\n | length m /= length (head m) = matmult (sqrify m) n\n | length n /= length (head n) = matmult m (sqrify n)\n | otherwise = [[\n sum (zipWith (*) (getColMat m y) (getRowMat n x))\n | x<-[0..(length (m!!y)-1)] ]\n | y<-[0..(length m-1)]]\n\n-- multiplies a matrix by a vector / applies a matrix to a vector\nmatvecmult :: Num a => [[a]] -> [a] -> [a]\nmatvecmult m v = map head $ matmult m (map (\\e-> [e]) v)\n\napplyMatrix :: Num a => [[a]] -> [a] -> [a]\napplyMatrix m v = map (sum . zipWith (*) v) m\n\n\n-- adds two matrices together\nmatadd :: Num a => [[a]] -> [[a]] -> [[a]]\nmatadd m n\n | length m > length n = matadd m (scale n (length m))\n | length m /= length (m!!0) = matadd (sqrify m) n\n | length n /= length (n!!0) = matadd m (sqrify n)\n | otherwise = [[\n (m!!y!!x) + (n!!y!!x)\n | x <- [0..((length(m!!0))-1)]]\n | y <- [0..((length m)-1)]]\n\n-- subtracts one matrix from another\nmatsub :: Num a => [[a]] -> [[a]] -> [[a]]\nmatsub m n = matadd m (matscalmult n (-1))\n\n-- creates an identity matrix of dimension n\nmatid :: Num a => Int -> [[a]]\nmatid n = matgen n (\\ i j -> if i==j then 1 else 0 )\n\n-- maps a matrices entries based on a function that takes the indices as input\nmatmap :: Num a => [[a]] -> ( Int -> Int -> a -> a ) -> [[a]]\nmatmap m f = map (\\y -> map (\\x -> f y x (m!!y!!x) ) [0..(length (m!!y)-1)]) [0..( length m -1)]\n\n-- complex conjugat of a matrix\nmatcon :: RealFloat a => [[Complex a]] -> [[Complex a]]\nmatcon m = matmap m (\\y x a -> conjugate a)\n\n-- generates a matrix of size t and then maps it with values\nmatgen :: (Num a, Num t, Enum t) => t -> (t -> t -> a) -> [[a]]\nmatgen s f = [[\n f x y\n | x<- [0..(s-1)]]\n | y<- [0..(s-1)]]\n\n-- fills in entries with 0's, so that a matrix is square\nsqrify :: Num a => [[a]] -> [[a]]\nsqrify m = scale m (max (length m) (length (head m)))\n\n-- scales a matrix m to a size s (also makes it a square matrix\nscale :: Num a => [[a]] -> Int -> [[a]]\nscale m s = [[ if (y<(length m) && x<(length (m!!0))) then(m!!y!!x) else(0) | x <- [0..(s-1)] ] | y <- [0..(s-1)] ]\n\n-- pretty prints a matrix\nprintMat :: (Foldable t, Show a) => t a -> IO ()\nprintMat m = mapM_ print m\n\n-- all non zero elements of a matrix are replaces by '.', otherwise they are replaced by ' '\nprettifyMat m = [[ if(m!!y!!x == 0)then(' ')else('.') | x<-[0..(length (m!!y)-1)] ] | y<-[0..((length m)-1)]]\n\nindexMatrix :: (Num a, Num b,Enum b) => [[a]] -> [([(a,b)], b)]\nindexMatrix m = (map (\\i -> zip i [0..]) m) `zip` [0..]\n\n-- gets the element of the y th row and x th collumn of a matrix\nmatxy :: Num a => [[a]] -> Int -> Int -> a\nmatxy m x y = m!!x!!y\n\n-- transposes a matrix\ntranspose :: Num a => [[a]] -> [[a]]\ntranspose m = do\n let im = indexMatrix m\n map (\\i -> map (\\j -> matxy m (snd j) (snd i)) (fst i)) im\n\n-- transposes a vector\nvectrans :: Num a => [a] -> [[a]]\nvectrans v = [ [x] | x<-v ]\n\n-- adjugate matrix of m\nadju :: Num a => [[a]] -> [[a]]\nadju m = transpose (cof m)\n\n-- cut out the matrix from x1-x2 and y1-y2 of a matrix m\nsubmatrix :: Num a => [[a]] -> Int -> Int -> Int -> Int -> [[a]]\nsubmatrix m x1 y1 x2 y2 = do\n let ycut = take (y2-y1) (drop y1 m)\n map (\\i -> take (x2-x1) (drop x1 i)) ycut\n\n-- gets the elements of a matrix in row r\ngetRowMat :: Num a => [[a]] -> Int -> [a]\ngetRowMat m r = [ m!!r!!x | x <- [0..((length (m!!0))-1)]]\n\n-- gets the elements of a matrix in collumn c\ngetColMat :: Num a => [[a]] -> Int -> [a]\ngetColMat m c = [ m!!x!!c | x <- [0..((length m)-1)]]\n\n-- return the matrix with collumn c removed\nelimRowMat :: Num a => [[a]] -> Int -> [[a]]\nelimRowMat m r = map (\\i -> take r i ++ drop (r+1) i) m\n\n-- returns the matrix with row r removed\nelimColMat :: Num a => [[a]] -> Int -> [[a]]\nelimColMat m c = take c m ++ drop (c+1) m\n\n-- eliminates row y and collumn x\nelimRowColMat :: (Num a) => [[a]] -> Int -> Int -> [[a]]\nelimRowColMat m x y = elimRowMat (elimColMat m y) x\n\n-- takes a matrix and replaces the n th collumn with a vector\nreplCol :: Num a => [[a]] -> Int -> [a] -> [[a]]\nreplCol m i v = map (\\y -> map (\\x -> if(x==i && y [[a]] -> Int -> [a] -> [[a]]\nreplRow m i v = map (\\y -> map (\\x -> if(y==i && x [[a]] -> a\ndet m = case (length m, length (m!!0)) of\n (1,1) -> m!!0!!0\n (p,q) -> do\n let grid = [ (m!!0!!x)*(-1)^x | x<-[0..p-1] ]\n let underdet = [ (grid!!x) * det(elimRowColMat m x 0) | x<-[0..p-1]]\n sum underdet\n\n-- returns the minor of a matrix from row x and col y\nminor :: Num a => [[a]] -> Int -> Int -> a\nminor m x y = det (elimRowColMat m x y)\n\n-- cofactor matrix / i.e. replace each entry with their minor and apply the checkerboard pattern of (1) and (-1)\ncof :: Num a => [[a]] -> [[a]]\ncof m = [\n [\n ((-1)^(x+y)) * (minor m x y)\n | x<-[0..(length (m!!y))-1]]\n | y<-[0..(length m)-1]]\n\n-- returns if a matrix is invertible or nor\ninvertible :: (Eq a, Num a) => [[a]]-> Bool\ninvertible m = (det m) /= 0\n\n-- returns the inverse of a matrix, if it exists\ninv :: (Eq a, Fractional a) => [[a]] -> Maybe [[a]]\ninv m\n | not (invertible m) = Nothing\n | otherwise = Just (matscalmult (adju m) (1/det(m)))\n\n-- removes duplicates inside a list\nremDupl :: (Eq a) => [a] -> [a]\nremDupl a\n | a == [] = []\n | not (elem (a!!0) (drop 1 a)) = (a!!0):(remDupl(drop 1 a))\n | otherwise = remDupl (drop 1 a)\n\n-- true if list a and list b are linearily dependent\nlinDep :: (Fractional a, Eq a, Enum a) => [a] -> [a] -> Bool\nlinDep a b\n | length a < length b = linDep b a\n | length a == 0 = True\n | a!!0==b!!0 && a!!0==0 = linDep (tail a) (tail b)\n | a!!0/=0 && b!!0/=0 = all (\\e -> (fst e)/b!!0 == (snd e)/a!!0) $ zip a (b++[0,0..])\n | otherwise = False\n\n-- adds a collumn of 0 at the beginning\naddCol :: Num a => [[a]] -> [[a]]\naddCol m = map (\\e -> 0:e) m\n\n-- reduced row-echelon form (TODO)\nrref :: (Fractional a, Eq a) => [[a]] -> [[a]]\nrref m = rref_step 0 m\n\nrref_step :: (Fractional a, Eq a) => Int -> [[a]] -> [[a]]\nrref_step s m\n | coef s == 0 = rref_step (s+1) m\n | length (newPivot (normalize s) s) == 0 = normalize s\n | s+1 < length m = rref_step (s+1) (elim s)\n | otherwise = normalize s\n where\n coef s = length ( filter (\\i-> i/=0) (getRowMat m s) )\n ones s = length ( filter (\\i-> i==1) (getRowMat m s) )\n emptyUntil s r = 0 == length ( filter (\\i-> i/=0) (take s (getColMat m r)))\n normalize s = map (\\y-> if(m!!y!!s /= 0 && emptyUntil s y)then(map (/m!!y!!s) (m!!y))else(m!!y) ) [0..((length m)-1)]\n newPivot n s = (take 1 (filter (\\y-> (emptyUntil s y) && (n!!y!!s==1)) [0..((length n)-1)]))\n elim s = do\n let n = normalize s\n let np = (newPivot n s)!!0\n map (\\y-> if(n!!y!!s /=0 && y/=np)then( map (\\x-> (n!!y!!x)- ((n!!y!!s)*(n!!np!!x))) [0..((length (n!!0))-1)] )else( n!!y )) [0..((length n)-1)]\n\ndimKer :: (Fractional a, Eq a) => [[a]] -> Int\ndimKer m = length $ filter (\\e-> 0 == (length ( filter (\\i-> i/=0) e)) ) (rref m)\n\n--rank :: (Fractional a, Eq a) => [[a]] -> Int\nrank m = length m - dimKer m\n\nker :: (Fractional a, Eq a) => [[a]] -> Maybe [[a]]\nker m\n | det m /= 0 = Nothing\n | otherwise = do\n let r = rref m\n let f = filter (\\i-> any (\\j-> j/=0) i) r\n Just f\n\nsolvMat :: Fractional a => [[a]] -> [a] -> [a]\nsolvMat m v = map (\\x-> det (replCol m x v) / det m) [0..((length (m!!0))-1)]\n\n--jord :: Num a => [[a]] -> [[a]]\n--jord m =\n\n--charpoly :: Num a => [[a]] -> a -> a\n--charpoly m x = det (matadd m (matscalmult (matid (length m)) x ))\n--\n--eigenVal :: (RealFrac a, Enum a, Integral b) => [[a]] -> [b]\n--eigenVal m = filter (\\i-> i/=0) $ remDupl $ map (round) $ filter (\\x -> round (charpoly m x)>(-10) && round (charpoly m x)<10) [-20,-19.9 .. 20]\n--\n--geoMult :: (Fractional a, Eq a) => [[a]] -> a -> Int\n--geoMult m e = dimKer $ matadd (matscalmult (matid (length (sqrify m))) e) (matscalmult m (-1))\n\ntr :: Num a => [[a]] -> a\ntr m = sum $ map (\\i -> (sqrify m)!!i!!i) [0..((length (m!!0))-1)]\n\npolyadd :: Num a => [a] -> [a] -> [a]\npolyadd p q\n | length p < length q = polyadd q p\n | otherwise = [ p!!x + if(x [a] -> (a,Int) -> [a]\npolymonomult p m = [0| x<-[1..(snd m)]] ++ map (* (fst m)) p\n\n--polymult :: Num a => [a] -> [a] -> [a]\npolymult p q = finish $ map (\\i -> polymonomult q (p!!i,i) ) [0..((length p)-1)]\n where\n finish x\n | length x == 1 = x\n | otherwise = finish $ polyadd (x!!0) (x!!1) : tail (tail x)\n\n--jnf :: Num a => [[a,Int,Int]] => [[a]]\n\n--algMult ::\n--algMult m es =\n-- where s = length (sqrify m)\n--\n--partitions :: Int -> [Int]\n--partitions x =\n\ndotprod :: Num a => [a] -> [a] -> a\ndotprod v w = sum $ matvecmult (vectrans v) w\n\northoVec :: (Num a, Eq a) => [a] -> [a] -> Bool\northoVec v w = (dotprod v w) == 0\n\nadjo :: RealFloat a => [[Complex a]] -> [[Complex a]]\nadjo m = transpose $ matcon m\n\northo :: (Num a, Eq a) => [[a]] -> Bool\northo m = matid (length (sqrify m)) == matmult m (transpose m)\n\nhermit :: RealFloat a => [[Complex a]] -> Bool\nhermit m = adjo m == m\n\nunitar :: RealFloat a => [[Complex a]] -> Bool\nunitar m = adjo m == fromMaybe [[0]] (inv m)\n\nkroneck :: Num a => [[a]] -> [[a]] -> [[a]]\nkroneck m n = [\n [ (m!!( yPosM y )!!( xPosM x )) * (n!!( yPosN y )!!( xPosN x ))\n | x<-[0..((length (m!!0))*(length (n!!0))-1)]]\n | y<-[0..((length m)*(length n)-1)]]\n where\n yPosM y = y `mod` (length m)\n xPosM x = x `mod` (length (m!!0))\n yPosN y = if (y==0)then(0)else( y `div` (length m) )\n xPosN x = if (x==0)then(0)else( x `div` (length (m!!0)) )\n", "meta": {"hexsha": "ce9b5c9a16dd1b6141252025d6bb65d167f8bb2b", "size": 12842, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Vectorspace.hs", "max_stars_repo_name": "Quoteme/vectorspace", "max_stars_repo_head_hexsha": "45fbe4feea5b1affd2f1ca46f2c96799cb06a083", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Vectorspace.hs", "max_issues_repo_name": "Quoteme/vectorspace", "max_issues_repo_head_hexsha": "45fbe4feea5b1affd2f1ca46f2c96799cb06a083", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Vectorspace.hs", "max_forks_repo_name": "Quoteme/vectorspace", "max_forks_repo_head_hexsha": "45fbe4feea5b1affd2f1ca46f2c96799cb06a083", "max_forks_repo_licenses": ["BSD-3-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.6807228916, "max_line_length": 172, "alphanum_fraction": 0.4907335306, "num_tokens": 4447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6900598965666376}} {"text": "module Layer where\nimport Numeric.LinearAlgebra\nimport Utils\n\ndata LayerType =\n SigmoidLayer\n | LinearLayer\n | SoftmaxLayer\n | ReluLayer\n\ndata VLayer = VLayer {\n layerType :: LayerType,\n rowNum :: Int,\n colNum :: Int,\n weight :: Matrix R,\n bias :: Matrix R,\n val :: Matrix R,\n delta :: Matrix R\n }\n\n{-- Linear Layer --}\nlinearLayerInit :: Int -> Int -> VLayer\nlinearLayerInit r c = VLayer {\n layerType = LinearLayer,\n rowNum = r,\n colNum = c,\n weight = (r >< c) genNormal,\n bias = (r >< c) genNormal,\n val = (r >< c) [0..]\n }\n\nforwardLinearLayer :: Matrix R -> VLayer -> Matrix R\nforwardLinearLayer input inputLayer = (weight inputLayer) * input + (bias inputLayer)\n\nbackwardLinearLayer :: Matrix R -> VLayer -> Matrix R\nbackwardLinearLayer backInput inputLayer = backInput\n\n{-- Sigmoid Layer --}\nsigmoidLayerInit :: Int -> Int -> VLayer\nsigmoidLayerInit r c = VLayer {\n layerType = SigmoidLayer,\n rowNum = r,\n colNum = c,\n weight = (r >< c) genNormal,\n bias = (r >< c) genNormal,\n val = (r >< c) [0..]\n }\n\ngetSigmoidMatrix :: Matrix R -> Matrix R\ngetSigmoidMatrix linear = 1.0 / (1.0 + (exp (- linear)))\n\n\n \nforwardSigmoidLayer :: Matrix R -> VLayer -> Matrix R\nforwardSigmoidLayer input layer =\n let linear = (weight layer) * input + (bias layer) in\n getSigmoidMatrix linear\n\nbackwardSigmoidLayer :: Matrix R -> VLayer -> Matrix R\nbackwardSigmoidLayer input layer =\n let linear = (weight layer) * input + (bias layer) in\n let sigmoid = getSigmoidMatrix linear in\n sigmoid * (1.0 - sigmoid)\n\n{-- Softmax Layer --}\nsoftmaxLayerInit :: Int -> Int -> VLayer\nsoftmaxLayerInit r c = VLayer {\n layerType = SoftmaxLayer,\n rowNum = r,\n colNum = c,\n weight = (r >< c) genNormal,\n bias = (r >< c) genNormal,\n val = (r >< c) [0..]\n }\n\n-- TODO: backward of softmax layer\n\n{-- Relu Layer --}\nreluLayerInit :: Int -> Int -> VLayer\nreluLayerInit r c = VLayer {\n layerType = ReluLayer,\n rowNum = r,\n colNum = c,\n weight = (r >< c\n ) genNormal,\n bias = (r >< c) genNormal,\n val = (r >< c) [0..]\n }\nforwardReluLayer :: Matrix R -> VLayer -> Matrix R\nforwardReluLayer input layer =\n let flagMatrix = cmap (\\x -> if x >= 0.0 then 1.0 else 0.0 ) (weight layer) in\n flagMatrix * input\n\n\nbackwardReluLayer :: Matrix R -> VLayer -> Matrix R\nbackwardReluLayer backInput layer =\n cmap (\\x -> if x <= 0.0 then x else 0.0) backInput \n\n", "meta": {"hexsha": "290a645129ae3495301dae6b6f0f96247aa3546f", "size": 2470, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "vortex/Layer.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/Layer.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/Layer.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": 24.9494949495, "max_line_length": 85, "alphanum_fraction": 0.6186234818, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.689141730638974}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra.Matrix.Cholesky\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Cholesky factorizations of symmetric (Hermitian) positive-definite\n-- matrices.\n--\n\nmodule Numeric.LinearAlgebra.Matrix.Cholesky (\n -- * Immutable interface\n cholFactor,\n cholSolveVector,\n cholSolveMatrix,\n \n -- * Mutable interface\n cholFactorM,\n cholSolveVectorM_,\n cholSolveMatrixM_,\n \n ) where\n\nimport Control.Monad( when )\nimport Control.Monad.ST( ST, runST, unsafeIOToST )\nimport Text.Printf( printf )\n\nimport qualified Foreign.LAPACK as LAPACK\n\nimport Numeric.LinearAlgebra.Types\n\nimport Numeric.LinearAlgebra.Matrix.Base( Matrix )\nimport Numeric.LinearAlgebra.Matrix.STBase( RMatrix, STMatrix )\nimport qualified Numeric.LinearAlgebra.Matrix.STBase as M\n\nimport Numeric.LinearAlgebra.Vector( Vector, STVector )\nimport qualified Numeric.LinearAlgebra.Vector as V\n\n\n-- | @cholFactor a@ tries to compute the Cholesky\n-- factorization of @a@. If @a@ is positive-definite then the routine\n-- returns @Right@ with the factorization. If the leading minor of order @i@\n-- is not positive-definite then the routine returns @Left i@.\ncholFactor :: (LAPACK e)\n => Herm Matrix e\n -> Either Int (Chol Matrix e)\ncholFactor (Herm uplo a) = runST $ do\n ma <- M.newCopy a\n cholFactorM (Herm uplo ma)\n >>= either (return . Left) (\\(Chol uplo' ma') -> do\n a' <- M.unsafeFreeze ma'\n return $ Right (Chol uplo' a')\n )\n\n-- | @cholSolveVector a x@ returns @a \\\\ x@.\ncholSolveVector :: (LAPACK e)\n => Chol Matrix e\n -> Vector e\n -> Vector e\ncholSolveVector a x = V.create $ do\n x' <- V.newCopy x\n cholSolveVectorM_ a x'\n return x'\n\n-- | @cholSolveMatrix a b@ returns @a \\\\ b@.\ncholSolveMatrix :: (LAPACK e)\n => Chol Matrix e\n -> Matrix e\n -> Matrix e\ncholSolveMatrix a c = M.create $ do\n c' <- M.newCopy c\n cholSolveMatrixM_ a c'\n return c'\n\n-- | @cholFactorM a@ tries to compute the Cholesky\n-- factorization of @a@ in place. If @a@ is positive-definite then the\n-- routine returns @Right@ with the factorization, stored in the same\n-- memory as @a@. If the leading minor of order @i@ is not\n-- positive-definite then the routine returns @Left i@.\n-- In either case, the original storage of @a@ is destroyed.\ncholFactorM :: (LAPACK e)\n => Herm (STMatrix s) e\n -> ST s (Either Int (Chol (STMatrix s) e))\ncholFactorM (Herm uplo a) = do\n (ma,na) <- M.getDim a\n let n = na\n\n when (not $ (ma,na) == (n,n)) $ error $\n printf (\"cholFactorM\"\n ++ \" (Herm _ ): nonsquare matrix\"\n ) ma na\n\n unsafeIOToST $\n M.unsafeWith a $ \\pa lda -> do\n info <- LAPACK.potrf uplo n pa lda\n return $ if info > 0 then Left info\n else Right (Chol uplo a)\n\n\n-- | @cholSolveVectorM_ a x@ sets @x := a \\\\ x@.\ncholSolveVectorM_ :: (LAPACK e, RMatrix m)\n => Chol m e\n -> STVector s e\n -> ST s ()\ncholSolveVectorM_ a x =\n M.withFromColM x $ \\x' ->\n cholSolveMatrixM_ a x'\n\n-- | @cholSolveMatrixM_ a b@ sets @b := a \\\\ b@.\ncholSolveMatrixM_ :: (LAPACK e, RMatrix m)\n => Chol m e\n -> STMatrix s e\n -> ST s ()\ncholSolveMatrixM_ (Chol uplo a) b = do\n (ma,na) <- M.getDim a\n (mb,nb) <- M.getDim b\n let (n,nrhs) = (mb,nb)\n \n when ((not . and) [ (ma,na) == (n,n)\n , (mb,nb) == (n,nrhs)\n ]) $ error $\n printf (\"cholSolveMatrixM_\"\n ++ \" (Chol _ )\"\n ++ \" \"\n ++ \": dimension mismatch\")\n ma na mb nb\n\n unsafeIOToST $\n M.unsafeWith a $ \\pa lda ->\n M.unsafeWith b $ \\pb ldb ->\n LAPACK.potrs uplo n nrhs pa lda pb ldb\n", "meta": {"hexsha": "68138ac146e6027cd9325faafa143373c46bea44", "size": 4288, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Cholesky.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Cholesky.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Matrix/Cholesky.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": 32.0, "max_line_length": 77, "alphanum_fraction": 0.5611007463, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6889259619894335}} {"text": "-------------------------------------------------------------------------------\n-- |\n-- Module : Supervised.LinearRegression\n-- Copyright : (c) Sam Stites 2017\n-- License : MIT\n-- Maintainer: sam@stites.io\n-- Stability : experimental\n-- Portability: non-portable\n--\n-- Fits a linear model with coefficients w = (w_1, ..., w_p) to minimize the\n-- residual sum of squares between the observed responses in the dataset, and\n-- the responses predicted by the linear approximation. Mathematically it solves\n-- a problem of the form:\n--\n-- \\underset{w}{min\\,} {|| X w - y||_2}^2\n--\n-- === Ordinary Least Squares Complexity\n--\n-- This method computes the least squares solution using a singular value\n-- decomposition of X. If X is a matrix of size (n, p) this method has a cost of\n-- O(n p^2), assuming that n \\geq p.\n-------------------------------------------------------------------------------\n{-# LANGUAGE TypeFamilies #-}\nmodule Supervised.LinearRegression where\n\nimport Prelude\nimport qualified Data.Monoid as M\nimport Numeric.LinearAlgebra\nimport qualified Numeric.LinearAlgebra.Data as LD\nimport Debug.Trace\n\n\n\ntype Labels = Vector Double\ntype Weights = Vector Double\ntype Inputs = Matrix Double\ntype Model = (Weights, Inputs -> Labels)\n\n\ndata LinearRegression = LinearRegression\n { nIters :: Integer -- ^ The number of iterations the algorithm will train weights for.\n , learningRate :: Double -- ^ Step length for updating weights\n }\n\n\n-- \"scikit-learn style\" naming\nmkModel :: LinearRegression\nmkModel = LinearRegression 100 0.001\n\n\nfit :: LinearRegression -> Inputs -> Labels -> Model\nfit cfg i l = weightedFit cfg w i l\n where\n nfs :: Int\n nfs = cols i\n\n w :: Weights\n w = (vector $ replicate nfs 1) / (konst (fromIntegral nfs) nfs)\n\n\nweightedFit :: LinearRegression -> Weights -> Inputs -> Labels -> Model\nweightedFit cfg _ _xs y = (w, \\i -> snocBias i #> w)\n where\n xs :: Matrix Double\n xs = snocBias _xs\n\n u, s, v :: Matrix Double\n (u, s, v) = svdM $ tr xs <> xs\n\n xSqInv :: Matrix Double\n xSqInv = (v <> pinv s) <> tr u\n\n w :: Vector Double\n w = (xSqInv <> tr xs) #> y\n\n\nsvdM :: Matrix Double -> (Matrix Double, Matrix Double, Matrix Double)\nsvdM = (\\(a,b,c) -> (a, diag b, c)) . svd\n\n\nconsBias :: Matrix Double -> Matrix Double\nconsBias m = LD.fromColumns $ ones (snd $ size m) : LD.toColumns m\n\n\nsnocBias :: Matrix Double -> Matrix Double\nsnocBias m = m ||| konst 1 (fst (size m), 1)\n\n\nones :: Int -> Vector Double\nones = konst 1\n\n\npredict :: Model -> Inputs -> Labels\npredict (_, fn) i = fn i\n\n\n-- | Returns the coefficient of determination R^2 of the prediction.\nscoreR2Regressor :: (truth ~ Labels) => Model -> truth -> Inputs -> Double\nscoreR2Regressor (_, fn) truth i = rSquare truth (fn i)\n\n\n-- | Compute R^2, the coefficient of determination that\n-- indicates goodness-of-fit of a regression.\nrSquare :: (truth ~ Labels) => truth -> Labels -> Double\nrSquare truth pred = 1 - numerator / denominator\n where\n weight :: Vector Double\n weight = 1\n\n numerator :: Double\n numerator = sumElements $ weight * ((truth - pred) ** 2)\n\n denominator :: Double\n denominator = sumElements $ weight * ((truth - averageTruth) ** 2)\n\n averageTruth :: Vector Double\n averageTruth = konst ((sumElements truth) / (fromIntegral n)) n\n where\n n :: Int\n n = size truth\n\n\nsumColumns :: Matrix Double -> Vector Double\nsumColumns = vector . fmap sumElements . toColumns\n\n\ncoefficients :: Model -> Weights\ncoefficients = fst\n\n\n", "meta": {"hexsha": "185a09b88617d802e8c841d2dfd34762dfd30db4", "size": 3533, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Supervised/LinearRegression.hs", "max_stars_repo_name": "stites/hasklearn", "max_stars_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Supervised/LinearRegression.hs", "max_issues_repo_name": "stites/hasklearn", "max_issues_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-08-02T15:05:37.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T16:12:39.000Z", "max_forks_repo_path": "src/Supervised/LinearRegression.hs", "max_forks_repo_name": "stites/hasklearn", "max_forks_repo_head_hexsha": "188464e47d624621c01c7851297b85f9446ffaf4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9694656489, "max_line_length": 96, "alphanum_fraction": 0.6374186244, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6887013499463466}} {"text": "module Numeric.MixtureModel.Exponential ( -- * General data types\n Sample\n , SampleIdx\n , Samples\n , ComponentIdx\n , Assignments\n , Weight\n -- * Exponential parameters\n , Rate, Beta\n , Exponential(..)\n , ComponentParams\n , paramFromSamples\n , paramsFromAssignments\n -- * Exponential distribution\n , Prob\n , prob\n , tauMean, tauVariance\n , modelProb\n -- * Gibbs sampling\n , estimateWeights\n , updateAssignments\n -- * Score\n , scoreAssignments\n , maxLikelihoodScore\n -- * Classification\n , classify\n ) where\n \nimport Control.Monad.ST\nimport Data.Function (on)\nimport qualified Data.Vector as VB\nimport Data.Vector.Algorithms.Heap\nimport qualified Data.Vector.Mutable as MV\nimport qualified Data.Vector.Unboxed as V\n\nimport Numeric.Log hiding (Exp, sum)\nimport qualified Numeric.Log as Log\nimport Numeric.SpecFunctions (logBeta)\nimport Statistics.Sample (mean)\nimport Numeric.Newton\nimport Math.Gamma (gamma)\n \nimport Data.Random hiding (gamma)\nimport Data.Random.Distribution.Categorical\n \ntype Prob = Log Double \ntype Sample = Double\ntype SampleIdx = Int \ntype ComponentIdx = Int \ntype Weight = Double \n\ntype Rate = Double -- ^ The rate parameter\ntype Beta = Double -- ^ The stretching parameter\ndata Exponential = Exp Rate\n | StretchedExp Rate Beta\n | FixedExp Rate Beta\n deriving (Show, Read, Eq)\n \n-- k refers to number of components\n-- N refers to number of samples\ntype Samples = V.Vector Sample -- length == N\ntype Assignments = V.Vector ComponentIdx -- length == N\ntype ComponentParams = VB.Vector (Weight, Exponential) -- length == K \n \n-- | `expProb lambda tau` is the probability of `tau` under Exponential\n-- distribution defined by rate `lambda`\nprob :: Exponential -> Sample -> Prob\nprob _ tau | tau < 0 = error \"Exponential distribution undefined for tau<0\"\nprob (FixedExp lambda 1) tau = prob (Exp lambda) tau\nprob (FixedExp lambda beta) tau = prob (StretchedExp lambda beta) tau\nprob (StretchedExp lambda 1) tau = prob (Exp lambda) tau\nprob (StretchedExp lambda beta) tau =\n Log.Exp $ log beta + (beta-1) * log tau + beta * log lambda - (tau * lambda)**beta\nprob (Exp lambda) tau = Log.Exp $ log lambda - lambda * tau\n\n-- | Probability of a sample under a mixture \nmodelProb :: ComponentParams -> Sample -> Prob\nmodelProb _ tau | tau < 0 = error \"Exponential distribution undefined for tau<0\"\nmodelProb model tau = VB.sum $ VB.map (\\(w,e)->prob e tau) model\n\n-- | Mean of the given distribution\ntauMean :: Exponential -> Double\ntauMean (Exp lambda) = 1 / lambda\ntauMean (StretchedExp lambda beta) = gamma (1/beta) / beta / lambda\ntauMean (FixedExp lambda beta) = tauMean (StretchedExp lambda beta)\n\n-- | Variance of the given distribution\ntauVariance :: Exponential -> Double\ntauVariance (Exp lambda) = 1/lambda^2\ntauVariance (StretchedExp lambda beta) = 2 * gamma (2/beta) / lambda^2 / beta \ntauVariance (FixedExp lambda beta) = tauVariance (StretchedExp lambda beta)\n\n-- | Exponential parameter from samples\nparamFromSamples :: Exponential -> V.Vector Sample -> Exponential\nparamFromSamples (FixedExp lambda beta) _ = FixedExp lambda beta \nparamFromSamples _ v | V.null v = error \"Can't estimate parameters without samples\"\nparamFromSamples (Exp _) v = Exp $ 1 / mean v\nparamFromSamples (StretchedExp _ betaOld) v =\n let v' = runST $ do a <- V.thaw v\n sort a\n V.freeze a\n n = realToFrac $ V.length v'\n tn = V.head v'\n s beta = V.sum (V.map (\\t->t**beta) v') - n*tn**beta\n betaOpt beta = let num = V.sum (V.map (\\t->t**beta * log t) v') - n*tn**beta*log tn\n in num / s beta - V.sum (V.map log v') / n - 1 / beta\n betaOpt' beta = let denom = V.sum (V.map (**beta) v') - n*tn**beta\n num1 = V.sum (V.map (\\t->t**beta * log t) v')\n - n*tn**beta * log tn\n num2 = V.sum (V.map (\\t->t**beta * (log t)^2) v')\n - n*tn**beta * (log tn)^2\n in 1/beta^2 - (num1/denom)^2 + num2/denom\n beta' = findRoot 1e-5 betaOpt betaOpt' betaOld\n lambda' = (s beta' / n)**(-1/beta')\n in StretchedExp lambda' beta'\n\n-- | Exponential parameter for component given samples and their\n-- component assignments\nparamFromAssignments :: Samples -> Assignments -> (ComponentIdx, Exponential) -> Exponential\nparamFromAssignments samples assignments (k,p) =\n paramFromSamples p $ V.map snd $ V.filter (\\(k',_)->k==k') $ V.zip assignments samples\n\n-- | Exponential parameters for all components given samples and their\n-- component assignments\nparamsFromAssignments :: Samples -> VB.Vector Exponential -> Assignments -> VB.Vector Exponential\nparamsFromAssignments samples params assignments =\n VB.map (paramFromAssignments samples assignments) $ VB.indexed params\n\n-- | Draw a new assignment for a sample given beta parameters\ndrawAssignment :: ComponentParams -> Sample -> RVar ComponentIdx\ndrawAssignment params x =\n let probs = map (\\(w,p)->realToFrac w * prob p x) $ VB.toList params\n in case filter (isInfinite . ln . fst) $ zip probs [0..] of\n (x:_) -> return $ snd x\n otherwise -> categorical\n $ map (\\(p,k)->(realToFrac $ p / sum probs :: Double, k))\n $ zip probs [0..]\n \n-- | `countIndices n v` is the list of counts\ncountIndices :: Int -> V.Vector Int -> VB.Vector Int\ncountIndices n v = runST $ do\n accum <- VB.thaw $ VB.replicate n 0\n V.forM_ v $ \\k -> do n' <- MV.read accum k\n MV.write accum k $! n'+1\n VB.freeze accum\n\n-- | Estimate the component weights of a given set of parameters\nestimateWeights :: Assignments -> VB.Vector Exponential -> ComponentParams\nestimateWeights assignments params =\n let counts = countIndices (VB.length params) assignments\n norm = realToFrac $ V.length assignments\n weights = VB.map (\\n->realToFrac n / norm) counts\n in VB.zip weights params\n\n-- | Sample new assignments for observations under given model parameters\nupdateAssignments :: Samples -> ComponentParams -> RVar Assignments\nupdateAssignments samples params =\n V.mapM (drawAssignment params) samples\n\n-- | \"Likelihood\" of sample assignments under given model\n-- parameters. Note that the exponential distribution is a density\n-- function and as such this will give an unnormalized result unless\n-- multiplied by dtau^N\nscoreAssignments :: Samples -> ComponentParams -> Assignments -> Prob\nscoreAssignments samples params assignments =\n V.product\n $ V.map (\\(k,x)->let (w,p) = params VB.! k\n in realToFrac w * prob p x\n )\n $ V.zip assignments samples\n\n-- | Maximum likelihood classification\nclassify :: ComponentParams -> Sample -> ComponentIdx\nclassify params x =\n fst\n $ VB.maximumBy (compare `on` \\(_,(w,p))->realToFrac w * prob p x)\n $ VB.indexed params\n\n-- | Score of the maximum likelihood assignment for a set of samples\nmaxLikelihoodScore :: ComponentParams -> Samples -> Prob\nmaxLikelihoodScore params samples = \n let assignments = V.map (classify params) samples\n in scoreAssignments samples params assignments\n\n", "meta": {"hexsha": "961fb3c90f77d4c24787842a06cdc460eaf7b4a8", "size": 8451, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/MixtureModel/Exponential.hs", "max_stars_repo_name": "bgamari/mixture-model", "max_stars_repo_head_hexsha": "91d41b8dde6c9dab8220e6298d1cbdf30902fd53", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-09-02T17:02:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T09:07:44.000Z", "max_issues_repo_path": "Numeric/MixtureModel/Exponential.hs", "max_issues_repo_name": "bgamari/mixture-model", "max_issues_repo_head_hexsha": "91d41b8dde6c9dab8220e6298d1cbdf30902fd53", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/MixtureModel/Exponential.hs", "max_forks_repo_name": "bgamari/mixture-model", "max_forks_repo_head_hexsha": "91d41b8dde6c9dab8220e6298d1cbdf30902fd53", "max_forks_repo_licenses": ["BSD-3-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.6810810811, "max_line_length": 97, "alphanum_fraction": 0.5722399716, "num_tokens": 1851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6886017953851997}} {"text": "{-# LANGUAGE NoMonomorphismRestriction, QuasiQuotes #-}\nimport Control.Arrow\nimport Control.Monad\nimport NeuralNetwork\nimport Numeric.LinearAlgebra.HMatrix\nimport Text.Printf.TH\nimport VisualizeFunction\n\nandDataSet = map (vector *** vector) [\n ([0,0], [0]),\n ([0,1], [0]),\n ([1,0], [0]),\n ([1,1], [1])\n ]\n\nxorDataSet = map (vector *** vector) [\n ([0,0], [0]),\n ([0,1], [1]),\n ([1,0], [1]),\n ([1,1], [0])\n ]\n\nnn = randomlyWeightedNetwork 0 [2, 9, 1] logisticAF\ntrainOn dataset = iterate (stochasticGradientDescent dataset 0.25) nn\n\nandNNs = trainOn andDataSet\nxorNNs = trainOn xorDataSet\n\noutputs dataset nns = map (\\nn -> map (applyNN nn) (map fst dataset)) nns\nandOutputs = outputs andDataSet andNNs\nxorOutputs = outputs xorDataSet xorNNs\n\nimage = visualizeFunctionBMP (0,0) (1,1) (1024,1024) (0,1) . ((!0).) . applyNN\n\nmain = forM_ [0..10] $ \\i -> do\n saveImage ([s|neuralnetwork_and_%04d.bmp|] (2^i)) (image (andNNs !! (2^i)))\n saveImage ([s|neuralnetwork_xor_%04d.bmp|] (2^i)) (image (xorNNs !! (2^i)))\n", "meta": {"hexsha": "7f45213a3d7f3de94d8d455f3a3992c0a6f6174a", "size": 1043, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "TestNeuralNetwork.hs", "max_stars_repo_name": "aweinstock314/neural-networks", "max_stars_repo_head_hexsha": "ac9227a47b5457a12b61623de73c96e3a04a296a", "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": "TestNeuralNetwork.hs", "max_issues_repo_name": "aweinstock314/neural-networks", "max_issues_repo_head_hexsha": "ac9227a47b5457a12b61623de73c96e3a04a296a", "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": "TestNeuralNetwork.hs", "max_forks_repo_name": "aweinstock314/neural-networks", "max_forks_repo_head_hexsha": "ac9227a47b5457a12b61623de73c96e3a04a296a", "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": 27.4473684211, "max_line_length": 79, "alphanum_fraction": 0.6385426654, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6881648998748523}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Lib.Utility.NeuralNet where\n\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Static\nimport Numeric.LinearAlgebra.Devel\nimport Control.Monad.State\nimport Control.Arrow\nimport GHC.TypeLits\nimport Data.Proxy\n\ndata Layer (il :: Nat) (is :: Nat) (wc :: Nat) (state :: *) where\n Layer :: state -> (X il is -> (Y il wc, state)) -> (state -> Delta il wc -> (DX il is, state)) -> Layer il is wc state\n\ntype ReluState il wc = Maybe (L il wc)\nreluLayer :: forall il wc. (KnownNat il, KnownNat wc) =>\n Layer il wc wc (ReluState il wc)\nreluLayer = Layer Nothing forwardF backwardF\n where forwardF x = (lt0, Just lt0)\n where (Just lt0) = create $ LA.cmap (\\ e -> if e <= 0 then 0 else e) $ extract x\n backwardF Nothing _ = error \"State is Nothing\"\n backwardF (Just lt0) d = (zipWithM' (\\ e1 e2 -> if e1 == 0 then 0 else e2) lt0 d, Just lt0)\n\ntype SigmoidState il wc = Maybe (L il wc)\nsigmoidLayer :: forall il wc. (KnownNat il, KnownNat wc) =>\n Layer il wc wc (ReluState il wc)\nsigmoidLayer = Layer Nothing forwardF backwardF\n where forwardF x = (y, Just y)\n where y = 1 / (1 + exp (-x))\n backwardF Nothing _ = error \"State Y is Nothing\"\n backwardF (Just s) d = (d * (1 - s) * s, Just s)\n\ntype AffineState il is wc = (NeuralParam is wc, Maybe (X il is), Maybe (NeuralParam is wc))\naffineLayer :: forall il is wc. (KnownNat il, KnownNat is, KnownNat wc) =>\n NeuralParam is wc -> Layer il is wc (AffineState il is wc)\naffineLayer param@(w, b) = Layer (param, Nothing, Nothing) forwardF backwardF\n where forwardF x = (x <> w + v2m b, (param, Just x, Nothing))\n backwardF (_, Nothing, _) _ = error \"State X is Nothing\"\n backwardF (param@(w, b), Just x, _) d = (dx, (param, Just x, Just (dw, db)))\n where dx = d <> tr w\n dw = tr x <> d\n db = unrow $ (1 :: L 1 il) <> d\n\ntype SoftmaxWithLossState il os = (T il os, Maybe (Y il os), Maybe (Loss il 1))\nsoftmaxWithLossLayer :: forall il os. (KnownNat il, KnownNat os) =>\n T il os -> Layer il os 1 (SoftmaxWithLossState il os)\nsoftmaxWithLossLayer t = Layer (t, Nothing, Nothing) forwardF backwardF\n where forwardF x = (loss, (t, Just y, Just loss))\n where y = softmax x\n loss = crossEntropyError t y\n backwardF (_, Nothing, _) d = error \"State Y is Nothing\"\n backwardF state@(t, Just y, _) d = ((y - t) / fromIntegral il, state)\n where (il, _) = size d\n\nclass NeuralNet (a :: Nat -> Nat -> Nat -> *) where\n predict :: forall il is os. (KnownNat il, KnownNat is, KnownNat os)\n => a il is os -> X il is -> Prediction il os\n loss :: forall il is os. (KnownNat il, KnownNat is, KnownNat os)\n => a il is os -> X il is -> Loss il os\n accuracy :: forall il is os. (KnownNat il, KnownNat is, KnownNat os)\n => a il is os -> X il is -> T il os -> Double\n gradients :: forall il is os. (KnownNat il, KnownNat is, KnownNat os)\n => a il is os -> X il is -> T il os -> ()\n training :: forall il is os. (KnownNat il, KnownNat is, KnownNat os)\n => a il is os -> X il is -> T il os -> a il is os\n\n accuracy a x t = LA.sumElements (extract t1f0) / fromIntegral (size t1f0)\n where y = predict a x\n (y', t') = (maxIndex' y, maxIndex' t)\n t1f0 = uncol $ zipWithM' (\\ e1 e2 -> if e1 == e2 then 1 else 0) y' t'\n\ndata MnistTwoLayerNet (wc :: Nat) (il :: Nat) (is :: Nat) (os :: Nat) where\n MnistTwoLayerNet ::\n Layer il is wc (AffineState il is wc)\n -> Layer il wc wc (ReluState il wc)\n -> Layer il wc os (AffineState il wc os)\n -> AdaGrad wc il is os\n -> MnistTwoLayerNet wc il is os\ninstance NeuralNet (MnistTwoLayerNet 50) where\n predict (MnistTwoLayerNet af1 relu af2 _) x = y3\n where (y1, af1s) = case af1 of (Layer _ ff _) -> ff x\n (y2, relus) = case relu of (Layer _ ff _) -> ff y1\n (y3, af2s) = case af2 of (Layer _ ff _) -> ff y2\n loss = undefined\n gradients = undefined\n training = undefined\n\nclass Updater (a :: Nat -> Nat -> Nat -> Nat -> *) where\n update :: forall wc il is os. (KnownNat wc, KnownNat il, KnownNat is, KnownNat os)\n => a wc il is os\n -> (NeuralParam is wc, NeuralParam wc os)\n -> (NeuralParam is wc, NeuralParam wc os)\n -> ((NeuralParam is wc, NeuralParam wc os), a wc il is os)\n\ndata SGD (wc :: Nat) (il :: Nat) (is :: Nat) (os :: Nat) where\n SGD :: Double -> SGD wc il is os\ninstance Updater SGD where\n update (SGD lr) (p1, p2) (dp1, dp2) = ((newParam lr p1 dp1, newParam lr p2 dp2), SGD lr)\n\nnewParam :: forall is wc. (KnownNat is, KnownNat wc) => Double\n -> NeuralParam is wc -> NeuralParam is wc -> NeuralParam is wc\nnewParam lr (w, b) (dw, db) = (w - lr_w * dw, b - lr_b * db)\n where (lr_w, lr_b) = (realToFrac lr, realToFrac lr)\n\ndata AdaGrad (wc :: Nat) (il :: Nat) (is :: Nat) (os :: Nat) where\n AdaGrad :: Double -> (NeuralParam is wc, NeuralParam wc os) -> AdaGrad wc il is os\ninstance Updater AdaGrad where\n update (AdaGrad lr (h1, h2)) (p1, p2) (dp1, dp2) = (result, AdaGrad lr newH)\n where result = (newParam lr p1 dp1', newParam lr p2 dp2')\n (dp1', dp2') = (f' newH1 dp1, f' newH2 dp2)\n where f h dx = dx / sqrt (h + 1e-7)\n f' (hw, hb) (dw, db) = (f hw dw, f hb db)\n newH@(newH1, newH2) = (f h1 dp1, f h2 dp2)\n where f (hw, hb) (dw, db) = (dw ** 2 + hw, db ** 2 + hb)\nnewAdaGrad lr = AdaGrad lr ((0, 0), (0, 0))\n\ninitTestNet :: forall wc il is os. (KnownNat wc, KnownNat il, KnownNat is, KnownNat os) => Double -> IO (MnistTwoLayerNet wc il is os)\ninitTestNet wis = result\n where initParams = do\n w1 <- randn'\n let b1 = konst 0\n w2 <- randn'\n let b2 = konst 0\n return (w1 * realToFrac wis, b1, w2 * realToFrac wis, b2)\n result = do\n (w1, b1, w2, b2) <- initParams\n let affine1 = affineLayer (w1, b1)\n let relu = reluLayer\n let affine2 = affineLayer (w2, b2)\n return $ MnistTwoLayerNet affine1 relu affine2 $ newAdaGrad 0.1\n\ntype LastLayer il hs os = X il hs -> T il os\n\ntype X il is = L il is\ntype Y il wc = L il wc\ntype T il os = Y il os\ntype W is wc = L is wc\ntype B wc = R wc\ntype NeuralParam is wc = (W is wc, B wc)\ntype Prediction il wc = Y il wc\ntype Loss il wc = Y il wc\ntype Delta il is = X il is \ntype DX il is = X il is\ntype ForwardF il is wc = X il is -> Y il wc\ntype BackwardF il is wc = Y il wc -> X il is\n\nv2m :: forall m n. (KnownNat m, KnownNat n) => R n -> L m n\nv2m v = fromList $ (>>= id) $ replicate mVal $ LA.toList $ extract v\n where mVal = fromIntegral $ natVal (Proxy :: Proxy m)\n\nsoftmax :: forall m n. (KnownNat m, KnownNat n) => L m n -> L m n\nsoftmax a = expA / sumExpA\n where maxs = foldAndExtractRow' LA.maxElement a\n a' = a - maxs\n expA = exp a'\n sumExpA = foldAndExtractRow' LA.sumElements expA\n\ncrossEntropyError :: forall m n. (KnownNat m, KnownNat n) => L m n -> L m n -> L m 1\ncrossEntropyError t y = negate $ foldRow' LA.sumElements $ t * log (y + delta)\n where delta = 1e-7\n\nfoldRow' :: forall m n. (KnownNat m, KnownNat n) => (LA.Vector Double -> Double) -> L m n -> L m 1\nfoldRow' f m = fromList $ map (f . extract) $ toRows m\n\nfoldAndExtractRow' :: forall m n. (KnownNat m, KnownNat n) => (LA.Vector Double -> Double) -> L m n -> L m n\nfoldAndExtractRow' f m = fromList $ toRows m >>= (replicate nVal . f . extract)\n where nVal = fromIntegral $ natVal (Proxy :: Proxy n)\n\nrandn' :: forall m n. (KnownNat m, KnownNat n) => IO (L m n)\nrandn' = result\n where mVal = fromIntegral $ natVal (Proxy :: Proxy m)\n nVal = fromIntegral $ natVal (Proxy :: Proxy n)\n result = do\n m <- LA.randn mVal nVal\n return $ case create m of\n Nothing -> error \"Something wrong\"\n Just x -> x\n\ndmmap' :: forall m n. (KnownNat m, KnownNat n) => (Double -> Double) -> L m n -> L m n\ndmmap' f m = mapped\n where m' = extract m\n mapped = case create $ LA.cmap f m' of\n Nothing -> error \"Something wrong\"\n Just x -> x\n\nzipWithM' :: forall m n. (KnownNat m, KnownNat n) => (Double -> Double -> Double) -> L m n -> L m n -> L m n\nzipWithM' f m1 m2 = result\n where m1' = extract m1\n m2' = extract m2\n result = build (\\ r c -> f (atIndex m1' r c) (atIndex m2' r c))\n where atIndex m r c = LA.atIndex m (truncate r, truncate c)\n\nmaxIndex' :: forall m n. (KnownNat m, KnownNat n) => L m n -> L m 1\nmaxIndex' = foldRow' (fromIntegral . LA.maxIndex)\n", "meta": {"hexsha": "ee978f47bd5dd76a1ace5c29b5bb18c947386bf5", "size": 8944, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib/Utility/NeuralNet.hs", "max_stars_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_stars_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T06:16:37.000Z", "max_issues_repo_path": "src/Lib/Utility/NeuralNet.hs", "max_issues_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_issues_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-01-04T02:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-09T12:39:40.000Z", "max_forks_repo_path": "src/Lib/Utility/NeuralNet.hs", "max_forks_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_forks_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T03:39:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T03:39:47.000Z", "avg_line_length": 44.72, "max_line_length": 134, "alphanum_fraction": 0.5863148479, "num_tokens": 2815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100817, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6879329505345209}} {"text": "-- | Module for operating on vectors and matrices. It includes some functions\n-- for using bra-ket notation, based on data types and functions from 'hmarix'\n-- package.\nmodule Hoqus.Dirac where\n\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra\n\n-- This can be used to hide the standard operators.\n-- import Prelude hiding ((+))\n-- import qualified Prelude\n\n-- | Function 'ket' provides basic functionality for producing vectors from the\n-- canonical basis. Vectors and matrices are not represented as lists (as in \n-- Mathematica), but using data types from \"Numeric.LinearAlgebra.Data\" in\n-- 'hmatrix' package. This makes possible to use operations on vectors and\n-- matrices defined in 'hmatrix'.\nket :: Int -> Int -> Vector C\nket d i = fromList $ (take i zeros) ++ [1] ++ (take (d-1-i) zeros)\n where zeros = replicate (d-1) 0\n \n-- | The 'proj' function builds d-dimensional operator |i> Int -> Int -> Matrix C\nproj d i j = (d> [b] -> [(a,b)]\nouter a b = [ (x,y) | x<-a, y<-b ]\n\n-- | General form of the outer product resulting in paris of elements.\nouterWith :: (a -> b -> c) -> [a] -> [b] -> [c]\nouterWith f a b = [ f x y | x<-a, y<-b ]\n\n-- | Function `overlap` is just an alternative for the scalar product from\n-- hmatrix.\noverlap :: Vector C -> Vector C -> C\noverlap = (<.>) \n", "meta": {"hexsha": "6ce5a5044d893141f205a6042b44060a09dcd050", "size": 1477, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Hoqus/Dirac.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/Dirac.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/Dirac.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": 38.8684210526, "max_line_length": 83, "alphanum_fraction": 0.6702775897, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6877630421169938}} {"text": "module Mandroots where \n\nimport Data.Complex\n\ndata Qaudratic a = Qaudratic a a a deriving (Show, Eq)\n\nsolveQuadratic :: Qaudratic (Complex Double) -> (Complex Double, Complex Double)\nsolveQuadratic (Qaudratic a b c) = let d = sqrt (b*b - 4 * a * c) in ((-b + d)/(2 * a), (-b - d)/(2 * a)) \n\nevalQuadratic :: Num a => Qaudratic a -> a -> a\nevalQuadratic (Qaudratic a b c) x = x*x * a + x * b + c\n\nrootsIteration :: Qaudratic (Complex Double) -> Qaudratic (Complex Double)\nrootsIteration q@(Qaudratic a b c) = let (rt1, rt2) = solveQuadratic q in (Qaudratic rt1 rt2 c) \n\ntype QCD = Qaudratic (Complex Double)\n\ntimeToEscape :: (QCD -> QCD) -> QCD -> Int -> Int\ntimeToEscape f q max = count q 0 \n where \n count p n \n | n == max = max\n | let a = evalQuadratic p (1 :+ 0) in realPart (a * conjugate a) > 25 = n\n | otherwise = count (f q) (n + 1)\n", "meta": {"hexsha": "62d9ae975e4740d5cd731e7ae565f3bf2a2a4c61", "size": 861, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MandRoot.hs", "max_stars_repo_name": "AlwinHughes/Derivative", "max_stars_repo_head_hexsha": "3fb0fbcf7faee9b66aa6fa1889e1de373c2cc416", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-29T09:49:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T09:49:30.000Z", "max_issues_repo_path": "src/MandRoot.hs", "max_issues_repo_name": "AlwinHughes/Derivative", "max_issues_repo_head_hexsha": "3fb0fbcf7faee9b66aa6fa1889e1de373c2cc416", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MandRoot.hs", "max_forks_repo_name": "AlwinHughes/Derivative", "max_forks_repo_head_hexsha": "3fb0fbcf7faee9b66aa6fa1889e1de373c2cc416", "max_forks_repo_licenses": ["BSD-3-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.44, "max_line_length": 106, "alphanum_fraction": 0.6236933798, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362858, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6871843931287024}} {"text": "import AI.HNN.FF.Network\nimport Numeric.LinearAlgebra\n\nsamples :: Samples Double\nsamples = [\n (fromList [ 1, 1, 1, 1, 1\n , 0, 0, 0, 0, 1\n , 0, 0, 1, 1, 1\n , 0, 0, 0, 0, 1\n , 1, 1, 1, 1, 1 ], fromList [1]), -- three\n \n (fromList [ 1, 1, 1, 1, 1\n , 0, 0, 0, 0, 1\n , 1, 1, 1, 1, 1\n , 0, 0, 0, 0, 1\n , 1, 1, 1, 1, 1 ], fromList [1]), -- three\n \n (fromList [ 0, 1, 1, 1, 1\n , 0, 0, 0, 0, 1\n , 0, 0, 0, 1, 1\n , 0, 0, 0, 0, 1\n , 0, 1, 1, 1, 1 ], fromList [1]), -- three\n \n (fromList [ 1, 1, 1, 1, 1\n , 1, 0, 0, 0, 1\n , 1, 0, 0, 0, 1\n , 1, 0, 0, 0, 1\n , 1, 1, 1, 1, 1 ], fromList [0]), -- not a three\n \n (fromList [ 1, 1, 1, 1, 1\n , 1, 0, 0, 0, 0\n , 1, 0, 0, 0, 0\n , 1, 0, 0, 0, 0\n , 1, 0, 0, 0, 0 ], fromList [0]), -- not a three\n\n (fromList [ 0, 1, 1, 1, 0\n , 0, 1, 0, 1, 0\n , 0, 1, 1, 1, 0\n , 0, 1, 0, 1, 0\n , 0, 1, 1, 1, 0 ], fromList [0]), -- not a three\n\n (fromList [ 0, 0, 1, 0, 0\n , 0, 1, 1, 0, 0\n , 1, 0, 1, 0, 0\n , 0, 0, 1, 0, 0\n , 0, 0, 1, 0, 0 ], fromList [0]) ] -- not a three\n\nmain :: IO ()\nmain = do\n n <- createNetwork 25 [250] 1\n let n' = trainNTimes 10000 0.5 tanh tanh' n samples\n mapM_ (print . output n' tanh . fst) samples\n putStrLn \"-------------\"\n print . output n' tanh $ testInput\n\n where testInput = fromList [ 0, 0, 1, 1, 1\n , 0, 0, 0, 0, 1\n , 0, 0, 1, 1, 1\n , 0, 0, 0, 0, 1\n , 0, 0, 1, 1, 1 ]\n\n{-\n\nOUTPUT:\nfromList [0.9996325368507625] \nfromList [0.9997784075859734]\nfromList [0.9996165887689248]\nfromList [-2.8107935971909852e-2]\nfromList [7.001808876464477e-3]\nfromList [2.54989546107178e-2]\nfromList [5.286805464313172e-4]\n-------------\nfromList [0.9993713524712442]\n-}\n", "meta": {"hexsha": "328e11bd8a2f5c0f0543c94ebc27f1f7389524ce", "size": 2044, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/ff/three.hs", "max_stars_repo_name": "EditResearch/HsANN", "max_stars_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 98, "max_stars_repo_stars_event_min_datetime": "2015-01-15T08:32:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T07:31:55.000Z", "max_issues_repo_path": "examples/ff/three.hs", "max_issues_repo_name": "EditResearch/HsANN", "max_issues_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-03-13T05:01:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T19:26:01.000Z", "max_forks_repo_path": "examples/ff/three.hs", "max_forks_repo_name": "EditResearch/HsANN", "max_forks_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-01-30T16:48:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T07:45:31.000Z", "avg_line_length": 27.2533333333, "max_line_length": 62, "alphanum_fraction": 0.3957925636, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6871317157431264}} {"text": "-- DTMF Analyzer\n-- Haskell School Project (Faculty of Mathematics and Physics, Charles University in Prague)\n-- Author: Lukas Jendele\nimport System.Environment\nimport qualified Data.ByteString.Lazy as B\nimport qualified Data.Complex as C\nimport Data.Binary.Get\nimport Data.Word\nimport qualified Numeric as Numeric\nimport qualified Data.List as List\nimport qualified Data.Set as Set\nimport qualified Data.Map as Map\nimport qualified Data.Function as DataFunction\n\nnthPrimitiveSquareRoot :: Int -> C.Complex Float\nnthPrimitiveSquareRoot 0 = 1\nnthPrimitiveSquareRoot n = C.conjugate $ C.mkPolar 1 (2*pi/(fromIntegral n))\n\n-- returns filters odd-indexed elements\ntakeOdd :: [C.Complex a] -> [C.Complex a]\ntakeOdd lst = map snd $ filter (\\(x,_) -> x `mod` 2 == 1) $ zip [0..] lst\n-- returns filters even-indexed elements\ntakeEven :: [C.Complex a] -> [C.Complex a]\ntakeEven lst = map snd $ filter (\\(x,_) -> x `mod` 2 == 0) $ zip [0..] lst\n\n--FFT see: http://mj.ucw.cz/vyuka/ads/44-fft.pdf\nfftHelper1 :: Int -> Int -> C.Complex Float -> [C.Complex Float] -> [C.Complex Float] -> [C.Complex Float]\nfftHelper1 _ _ _ [] [] = []\nfftHelper1 i n omega (e:evenLst) (o:oddLst) | i == n = []\n | otherwise = (e + ((omega^i) * o)):(fftHelper1 (i+1) n omega evenLst oddLst)\n--FFT see: http://mj.ucw.cz/vyuka/ads/44-fft.pdf\nfftHelper2 :: Int -> Int -> C.Complex Float -> [C.Complex Float] -> [C.Complex Float] -> [C.Complex Float]\nfftHelper2 _ _ _ [] [] = []\nfftHelper2 i n omega (e:evenLst) (o:oddLst) | i == n = []\n | otherwise = (e - ((omega^i) * o)):(fftHelper2 (i+1) n omega evenLst oddLst)\n\n--FFT see: http://mj.ucw.cz/vyuka/ads/44-fft.pdf\n--fft :: (Integral a) => a -> C.Complex Float -> [C.Complex Float] -> [C.Complex Float]\nfft :: Int -> C.Complex Float -> [C.Complex Float] -> [C.Complex Float]\nfft n omega lst = if n == 1 then (take 1 lst) else \n let evenLst = (fft (n `div` 2) (omega^2) (takeEven lst))\n oddLst = (fft (n `div` 2) (omega^2) (takeOdd lst))\n in ((fftHelper1 0 (n `div` 2) omega evenLst oddLst) ++ (fftHelper2 0 (n `div` 2) omega evenLst oddLst))\n\n\n \n--fftForward :: (Integral a, RealFloat a) => a -> [C.Complex Float] -> [C.Complex Float]\nfftForward :: Int -> [C.Complex Float] -> [C.Complex Float]\nfftForward n lst = fft n (nthPrimitiveSquareRoot n) lst\n\n-- divides complex number by components\ndiv' :: C.Complex Float -> Int -> C.Complex Float\ndiv' c r = ((C.realPart c) / (fromIntegral r)) C.:+ ((C.imagPart c) / (fromIntegral r))\n\n--fftBackward :: (Integral a, RealFloat a) => a -> [C.Complex a] -> [C.Complex a]\nfftBackward :: Int -> [C.Complex Float] -> [C.Complex Float]\nfftBackward n lst = map (`div'` n) $ fft n ((C.conjugate (nthPrimitiveSquareRoot n))) lst\n\n\nmain = do \n (filePath:_) <- getArgs\n analyzeFile filePath\n \n--loads the WaveFile from a file given a path\nparseFile filePath = do\n fileContents <- B.readFile filePath\n let result = runGet getWaveFile fileContents\n putStrLn (filePath ++ \" loaded!\")\n return (result)\n\ndata WaveFile = WaveFile {\n chunkID :: Int,\n fileSize :: Int,\n riffType :: Int, \n fmtId :: Int, \n fmtSize :: Int, \n fmtCode :: Int, \n channels :: Int, \n sampleRate :: Int, \n fmtAvgBPS :: Int, \n fmtBlockAlign ::Int, \n bitDepth :: Int,\n dataID :: Int,\n dataSize :: Int,\n fileData :: [Float]\n} -- deriving (Show)\n\ninstance Show WaveFile where \n show wav = \"FileSize: \" ++ (show $ fileSize wav) ++ \"\\nDataSize: \" ++ (show $ dataSize wav) ++ \"\\nSampleRate: \" ++ (show $ sampleRate wav) ++ \"\\nBitDepth: \" ++ (show $ bitDepth wav) ++ \"\\nChannels: \" ++ (show $ channels wav) ++ \"\\n\"\n\n-- parses the header of wav file and reads its contents\ngetWaveFile :: Get WaveFile\ngetWaveFile = do\n w_chunkID <- getWord32le\n let chunkID = (fromIntegral w_chunkID)\n w_fileSize <- getWord32le\n let fileSize = fromIntegral w_fileSize\n w_riffType <- getWord32le\n let riffType = fromIntegral w_riffType\n w_fmtID <- getWord32le\n let fmtID = fromIntegral w_fmtID\n w_fmtSize <- getWord32le\n let fmtSize = fromIntegral w_fmtSize\n w_fmtCode <- getWord16le\n let fmtCode = fromIntegral w_fmtCode\n w_channels <- getWord16le\n let channels = fromIntegral w_channels\n w_sampleRate <- getWord32le\n let sampleRate = fromIntegral w_sampleRate\n w_fmtAvgBPS <- getWord32le\n let fmtAvgBPS = fromIntegral w_fmtAvgBPS\n w_fmtBlockAlign <- getWord16le\n let fmtBlockAlign = fromIntegral w_fmtBlockAlign\n w_bitDepth <- getWord16le\n let bitDepth = fromIntegral w_bitDepth\n w_dataID <- getWord32le\n let dataID = fromIntegral w_dataID\n w_dataSize <- getWord32le\n let dataSize = fromIntegral w_dataSize\n fileData <- getWaveContents 0 dataSize\n return $! WaveFile chunkID fileSize riffType fmtID fmtSize fmtCode channels sampleRate fmtAvgBPS fmtBlockAlign bitDepth dataID dataSize fileData\n\n\n--getWaveContents :: (Integral a) => a -> a-> Get [Float]\ngetWaveContents i size = do\n if i == size \n then return []\n else do\n fl <- getFloat\n rest <- getWaveContents (i+2) size\n return (fl:rest)\n\n-- turns UInt16 to Int16\nwordToInt :: Word16 -> Int\nwordToInt word | word < notWord = (fromIntegral word :: Int)\n | otherwise = (-1) * (fromIntegral notWord :: Int)\n where notWord = (-word)\n\n-- read 16bit Float from the stream\ngetFloat :: Get Float\ngetFloat = do \n word <- getWord16le\n let signedWord = wordToInt word\n return ((fromIntegral signedWord :: Float)/(2^15))\n\n-- Duration of the file\nwavDuration :: WaveFile -> Float\nwavDuration wav = ((fromIntegral $ dataSize wav) * (fromIntegral $ channels wav) * 8) / ((fromIntegral $ sampleRate wav) * (fromIntegral $ bitDepth wav) )\n\n-- turns the list into a list of small intervals\nintervalLength = 100\n\nintervals_internal [] = []\nintervals_internal lst@(head:tail) = (take (intervalLength) lst) : (intervals_internal tail)\n\nintervals lst = filter (\\l -> (length l) == (intervalLength)) (intervals_internal lst)\n\n-- calculates the average of the absolute values in the list\nmy_average :: [Float] -> Float\nmy_average lst = (sum $ map (abs) lst) / (fromIntegral $ length lst)\n\n-- get the interval of values from to in msec\ngetInterval :: Float -> Float -> WaveFile -> [Float]\ngetInterval from to wav = let rate = ((fromIntegral $ sampleRate wav) :: Float)\n fromIndex = floor $ (rate * from)\n toIndex = floor $ (rate * to)\n in take (toIndex - fromIndex) (drop fromIndex $ fileData wav)\n\n-- helper function for getBeepIntervals\ngetBeeps _ [] _ = []\ngetBeeps i (interval:tailOfIntervals) globalAverage = (i, if globalAverage < intervalAverage then True else False, head interval):(getBeeps (i+1) tailOfIntervals globalAverage) \n where intervalAverage = my_average interval\n-- handy function for debugging\nindexToTime index wav = (fromIntegral index) / (fromIntegral $ sampleRate wav)\n\nfilterBeepValues [] = []\nfilterBeepValues ((index, isQuiet, value):tail) | (not isQuiet) = []\n | otherwise = (index, value):(filterBeepValues tail)\n\n-- splits the wav file into into intervals and returns only non-quiet ones\n-- it takes little windows and if the abs average value of the window > abs average of the file, the window is regarded as non-quite \ngetBeepIntervals wav = let wavData = fileData wav\n globalAverage = my_average wavData\n listOfIntervals = intervals wavData\n beeps = getBeeps 0 listOfIntervals globalAverage\n listOfBeeps = List.groupBy (\\(_, isQuiet1, _) (_, isQuiet2, _) -> isQuiet1 == isQuiet2) beeps\n in filter (\\lst -> length lst > 9) $ filter (not . null) $ map (filterBeepValues) listOfBeeps\n -- firstLast = map (\\lst -> (head lst, last lst)) listOfBeeps\n -- in filter (\\t -> (snd $ fst t)) firstLast\n\n{-\nDTMF keypad frequencies (with sound clips) \t\n 5/1209 Hz \t6/1336 Hz \t7/1477 Hz \t8/1633 Hz\n1/697 Hz \t 1 / 5 \t 2 / 6 \t 3 / 7 \t A / 8\n2/770 Hz \t 4 / 10 \t 5 / 12 \t 6 / 14 \t B / 16\n3/852 Hz \t 7 / 15 \t 8 / 18 \t 9 / 21 \t C / 24 \n4/941 Hz \t * / 20 \t 0 / 24 \t # / 28 \t D / 32\n\nEach frequency button and frequency has its index. If you multiply the indices of two DTMF frequencies, you get index of the button\n-} \n\n-- constant - range around the precise DTMF freq\nfreqLimit = 15 \n\ndtmfFrequencies = [697,770,852,941,1209,1336,1477,1633]\n\ndtmfFrequencyRanges_internal :: [Int] -> [Set.Set Int]\ndtmfFrequencyRanges_internal [] = []\ndtmfFrequencyRanges_internal (freq:rest) = (Set.fromList [(freq - freqLimit)..(freq + freqLimit)]):(dtmfFrequencyRanges_internal rest)\n\n-- set for looking up if frequency is regarded as DTMF frequency or not\ndtmfFrequencyRanges :: [Set.Set Int]\ndtmfFrequencyRanges = dtmfFrequencyRanges_internal dtmfFrequencies\n\n-- dictionary to look up chars representing buttons, we look up by the index of the button\ndtmfTonesDict = Map.fromList $ zip ([x*y | x<- [1..4], y<-[5..8]]) ['1','2','3','A','4','5','6','B','7','8','9','C','*','0','#','D']\n\n-- returns 0 if no otherwise index of frequency from table above\nisDTMFFreq :: Int -> Int\nisDTMFFreq freq = snd $ foldl f (1,0) dtmfFrequencyRanges\n where f acc@(index, result) set = if result /= 0 then acc \n else \n if freq `Set.member` set then (index+1, index) \n else (index+1, 0)\n\n-- given FFT Output, it returns recognized DTMF frequencies\nanalyzeFFTOutput :: Int -> Int -> [C.Complex Float] -> Int -> Float -> [(Int, Float)] \nanalyzeFFTOutput i n (x:xs) smplRate avrgValue | i == n = []\n | i > (n `div` 2) = []\n | otherwise = let freq = (fromIntegral i) / ((fromIntegral n) / (fromIntegral smplRate)) -- calculate the frequency\n dfmtFreq = isDTMFFreq $ floor freq\n currentVal = (C.realPart $ abs x)\n in if dfmtFreq == 0 then restOfRecurrsion\n else if currentVal > avrgValue then (dfmtFreq, currentVal):(restOfRecurrsion)\n else restOfRecurrsion\n where restOfRecurrsion = analyzeFFTOutput (i+1) n xs smplRate avrgValue\n\nmaybeCharToChar :: Maybe Char -> Char\nmaybeCharToChar Nothing = '?'\nmaybeCharToChar (Just c) = c\n\n-- analyzes interval of function and returns which button it is dialing \nanalyzeInterval :: [(Int, Float)] -> Int -> Char\nanalyzeInterval interval smplRate = let len = length interval\n floorPow2 = if len <= 1 then 0 else 2 ^ (floor $ logBase 2 (fromIntegral len)) -- calculate the n for FFT\n --startIndex = fst $ head interval\n --endIndex = fst $ last interval\n cmplxValues = map ((C.:+0).snd) interval -- make the values complex and trim the index\n fftImage = fftForward floorPow2 cmplxValues\n avrgValue = (sum $ map (C.realPart . abs) fftImage) / (fromIntegral floorPow2)\n frequencies = reverse $ List.sortBy (compare `DataFunction.on` snd) $ analyzeFFTOutput 0 floorPow2 fftImage smplRate avrgValue\n tone = if (length frequencies) < 2 then 0 else (fst $ head frequencies) * (fst $ head (tail frequencies))\n in maybeCharToChar $ Map.lookup tone dtmfTonesDict\n\n\nanalyzeIntervals :: [[(Int, Float)]] -> Int -> String\nanalyzeIntervals [] _ = []\nanalyzeIntervals (interval:rest) smplRate = (analyzeInterval interval smplRate):(analyzeIntervals rest smplRate)\n\nanalyzeFile filePath = do\n wav <- parseFile filePath\n let beeps = getBeepIntervals wav\n putStrLn (analyzeIntervals beeps (sampleRate wav))\n", "meta": {"hexsha": "ea5a253624228d55aaaa79c4a18daf5607cc908d", "size": 12883, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "DTMFAnalyzer.hs", "max_stars_repo_name": "jendelel/DTMFAnalyzerHaskell", "max_stars_repo_head_hexsha": "f2dd19e0ff79bf2c4c2fa0eaaa0a853976a48998", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-06-12T09:16:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-12T09:16:17.000Z", "max_issues_repo_path": "DTMFAnalyzer.hs", "max_issues_repo_name": "jendelel/DTMFAnalyzerHaskell", "max_issues_repo_head_hexsha": "f2dd19e0ff79bf2c4c2fa0eaaa0a853976a48998", "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": "DTMFAnalyzer.hs", "max_forks_repo_name": "jendelel/DTMFAnalyzerHaskell", "max_forks_repo_head_hexsha": "f2dd19e0ff79bf2c4c2fa0eaaa0a853976a48998", "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": 48.7992424242, "max_line_length": 236, "alphanum_fraction": 0.5909337887, "num_tokens": 3359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6870962304209598}} {"text": "module Fractal.Math.Kernel(\n evaluateFractal\n)where\n\nimport Data.Complex\n\ntype Point = Complex Double\ntype Limit = Double\ntype Iteration = Complex Double\ntype Magnitude = Double\ntype MaxIter = Int\ntype Iter = Int\n\n\nevaluateFractal :: (Point -> Iteration -> Iteration) -> Limit -> MaxIter -> Point -> Iter\nevaluateFractal f l m c = res c (0.0 :+ 0.0) 0\n where res c z i = if i == m then i else rest (f c z) i\n rest val i = if checkAcceptance l (magnitude val) then i else res c val (i + 1)\n\n\ncheckAcceptance :: Limit -> Double -> Bool\ncheckAcceptance l val\n | val >= l = True\n | val == 0.0 = True\n | otherwise = False\n", "meta": {"hexsha": "f42272b6b9ef45fba134b28cd477dbfd17a2763b", "size": 659, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fractal/Math/Kernel.hs", "max_stars_repo_name": "sigmaticsMUC/FractalHaskell", "max_stars_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Fractal/Math/Kernel.hs", "max_issues_repo_name": "sigmaticsMUC/FractalHaskell", "max_issues_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fractal/Math/Kernel.hs", "max_forks_repo_name": "sigmaticsMUC/FractalHaskell", "max_forks_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_forks_repo_licenses": ["BSD-3-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.3461538462, "max_line_length": 99, "alphanum_fraction": 0.6403641882, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6867926292196188}} {"text": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Main where\n\nimport Lib\n\nimport Numeric.AD\nimport Numeric.AD.Internal.Forward\nimport Numeric.AD.Rank1.Tower(Tower)\nimport Numeric.SpecFunctions\nimport Data.Csv\nimport qualified Data.ByteString.Lazy.Char8 as C\n\n--c :: Num a => (a -> a) -> a -> a -> a\ndifference :: Fractional a => (forall s. AD s (Tower a) -> AD s (Tower a)) -> a -> (forall s. AD s (Tower a) -> AD s (Tower a))\ndifference v base = \\x -> v x - v (auto base)\n\ndifference' :: Num a => (t -> a) -> t -> t -> a\ndifference' v base x = v x - v base\n\noptValLin :: Num a => a -> a\noptValLin r = 1000 * r\n\noptValQuad :: Num a => a -> a\n--optValQuad r = 1000 * (r + r*r)\noptValQuad r = 10000 * (r*r) + 10* r\n\n-- Truncate a taylor exapansion\n-- If nothing don't take a taylor expansion just evaluate the 0th derivative a.k.a zero\ntrunTay :: Fractional a => Maybe Int -> (forall s. AD s (Tower a) -> AD s (Tower a)) -> a -> a -> a\ntrunTay Nothing f centre x = (diffs f x)!!0\ntrunTay (Just n) f centre x = foldr (+) 0 $ take (n+1) $ (taylor0 f centre (x-centre))\n\n-- create convexity correction function\n-- takes a function and two points and calculates the adjustment needed for the difference\nconvexityAdj :: Fractional a => (forall s. AD s (Tower a) -> AD s (Tower a)) -> a -> a -> a\nconvexityAdj f centre b = difference' (\\x -> trunTay (Just x) (difference f centre) centre b ) 1 2\n\nmain :: IO ()\nmain = do\n --tr (Just 1) (c d 0.02) 0.02 0.04\n print $ trunTay (Just 0) (difference optValLin 0.02) 0.02 0.04\n --print $ trunTay (Just 1) (difference optionVal 0.02) 0.02 0.04\n --print $ trunTay (Just 2) (difference optionVal 0.02) 0.02 0.04\n --print $ trunTay Nothing (difference optionVal 0.02) 0.02 0.04\n\n print $ \"convexity\"\n print $ convexityAdj optValLin 0.02 0.04\n print $ convexityAdj optValQuad 0.02 0.04\n -- just get the second derivative of the adjustment\n\n -- plot a function trunTay for a range from like 0 -> 0.1 for examples with Nothing\n let xFunValues = [ x*0.001 | x <- [1..100] ]\n linValues = map (\\x -> trunTay Nothing optValLin 0.02 x) xFunValues\n quadValues = map (\\x -> trunTay Nothing optValQuad 0.02 x) xFunValues\n\n-- print $ (linValues :: [(Double,Double)])\n C.writeFile \"./plotting/funVals.csv\" $ encode (zip3 xFunValues linValues quadValues :: [(Double,Double,Double)])\n\n -- Then plot first order derivaitve trunTay (Just 1) centred at 0.02 up to 0.04 to get straight line\n let xApproxValues = [ x*0.001 + 0.02 | x <- [0..60] ]\n quadApproxVals1 = map (\\x -> trunTay (Just 1) optValQuad 0.02 x) xApproxValues\n quadApproxVals2 = map (\\x -> trunTay (Just 2) optValQuad 0.02 x) xApproxValues\n\n C.writeFile \"./plotting/approxVals.csv\" $ encode (zip3 xApproxValues quadApproxVals1 quadApproxVals2 :: [(Double,Double,Double)])\n\n -- Now plot the convexity adustment as a constant values starting at 0.8\n let sPoint = trunTay (Just 1) optValQuad 0.02 0.08\n convexAdj = (convexityAdj optValQuad 0.02 0.08)\n writeFile \"./plotting/convexAdj.csv\" $ \"0.08,\" ++ show sPoint ++ \",0,\" ++ show convexAdj\n\n\n print \"done\"\n", "meta": {"hexsha": "ad424bc487c5d78ef4ba0ef2a4cdf73d064c7fd6", "size": 3156, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "collinstmatthew/taylorConvexity", "max_stars_repo_head_hexsha": "00b3100d2a49ae20aea00a16a1c0f104c1855b7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "collinstmatthew/taylorConvexity", "max_issues_repo_head_hexsha": "00b3100d2a49ae20aea00a16a1c0f104c1855b7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "collinstmatthew/taylorConvexity", "max_forks_repo_head_hexsha": "00b3100d2a49ae20aea00a16a1c0f104c1855b7c", "max_forks_repo_licenses": ["BSD-3-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.08, "max_line_length": 133, "alphanum_fraction": 0.6543092522, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6867917229323309}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Statistics.LinearRegression (\n -- * Simple linear regression functions\n linearRegression,\n linearRegressionRSqr,\n linearRegressionTLS,\n -- * Related functions\n correl,\n covar,\n -- * Estimated errors and distribution parameters\n linearRegressionMSE,\n linearRegressionDistributions,\n -- * Robust linear regression\n robustFit,\n nonRandomRobustFit,\n robustFitRSqr,\n -- ** Related types\n EstimationParameters(..),\n ErrorFunction,\n Estimator,\n EstimatedRelation,\n -- ** Provided values\n defaultEstimationParameters,\n linearRegressionError,\n linearRegressionTLSError,\n -- ** Helper functions\n converge,\n -- * References\n -- $references\n ) where\n\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\nimport Data.Vector.Generic (Vector, (!))\nimport Safe (at)\nimport System.Random\nimport System.Random.Shuffle (shuffleM)\nimport Control.Monad.Random.Class\nimport Control.Monad.Random (evalRand)\nimport Control.Monad (liftM)\nimport Data.Function (on)\nimport Data.List (minimumBy, sortBy)\nimport Data.Maybe (fromMaybe)\nimport qualified Statistics.Sample as S\nimport qualified Statistics.Distribution as D\nimport qualified Statistics.Distribution.Transform as T\nimport qualified Statistics.Distribution.StudentT as ST\n\n--- * Simple linear regression\n\n-- | Covariance of two samples\ncovar :: Vector v Double => v Double -> v Double -> Double\ncovar xs ys = covar' m1 m2 n xs ys\n where\n !n = fromIntegral $ G.length xs\n !m1 = S.mean xs\n !m2 = S.mean ys\n{-# INLINE covar #-}\n\n-- internal function that avoids duplicate calculation of means and lengths where possible\n-- Note: trying to make the calculation even more efficient by subtracting m1*m1*n instead of individual subtractions increased errors, probably due to rounding issues.\ncovar' :: Vector v Double => Double -> Double -> Double -> v Double -> v Double -> Double\ncovar' m1 m2 n xs ys = G.sum (G.zipWith (*) (G.map (subtract m1) xs) (G.map (subtract m2) ys)) / (n-1)\n{-# INLINE covar' #-}\n\n-- | Pearson's product-moment correlation coefficient\ncorrel :: Vector v Double => v Double -> v Double -> Double\ncorrel xs ys = let !c = covar xs ys\n !sx = S.stdDev xs\n !sy = S.stdDev ys\n in c / (sx * sy)\n{-# INLINE correl #-}\n\n-- | Simple linear regression between 2 samples.\n-- Takes two vectors Y={yi} and X={xi} and returns\n-- (alpha, beta, r*r) such that Y = alpha + beta*X\n-- and where r is the Pearson product-moment correlation\n-- coefficient\nlinearRegressionRSqr :: Vector v Double => v Double -> v Double -> (Double, Double, Double)\nlinearRegressionRSqr xs ys = (alpha, beta, r2)\n where \n !c = covar' m1 m2 n xs ys\n !r2 = c*c / (v1*v2)\n !(m1,v1) = S.meanVarianceUnb xs \n !(m2,v2) = S.meanVarianceUnb ys\n !n = fromIntegral $ G.length xs\n !beta = c / v1\n !alpha = m2 - beta * m1\n{-# INLINE linearRegressionRSqr #-}\n \n-- | Simple linear regression between 2 samples.\n-- Takes two vectors Y={yi} and X={xi} and returns\n-- (alpha, beta) such that Y = alpha + beta*X \nlinearRegression :: Vector v Double => v Double -> v Double -> (Double, Double)\nlinearRegression xs ys = (alpha, beta)\n where \n (alpha, beta, _) = linearRegressionRSqr xs ys\n{-# INLINE linearRegression #-}\n\n-- | The error (or residual) mean square of a sample w.r.t. an estimated regression line.\n-- This serves as an estimate for the variance of the sampled data.\n-- Accepts the regression parameters (alpha,beta) and the sample vectors X and Y.\nlinearRegressionMSE :: (Vector v Double, Vector v (Double, Double)) => (Double,Double) -> v Double -> v Double -> Double\nlinearRegressionMSE ab xs ys = (G.sum . G.map (linearRegressionError ab) . G.zip xs $ ys)/(n-2)\n where\n !n = fromIntegral $ G.length xs\n\n-- | The estimated distributions of the regression parameters (alpha and beta) assuming normal, identical distributions of Y, the sampled data.\n-- These can serve to get confidence intervals for the regression parameters.\n-- Accepts the regression parameters (alpha,beta) and the sample vectors X and Y.\n-- The distributions are StudnetT distributions centered at the estimated (alpha,beta) respectively, with parameter numbers n-2 (where n is the initial sample size) and with standard deviations that are extracted from the sampled data based on its MSE. See chapter 2 of reference [3] for details.\nlinearRegressionDistributions :: (Vector v Double, Vector v (Double, Double)) => (Double,Double) -> v Double -> v Double -> (T.LinearTransform ST.StudentT,T.LinearTransform ST.StudentT)\nlinearRegressionDistributions (alpha,beta) xs ys = (ST.studentTUnstandardized (n-2) alpha va,ST.studentTUnstandardized (n-2) beta vb)\n where\n !n = fromIntegral $ G.length xs\n !mse = linearRegressionMSE (alpha,beta) xs ys\n !vb = mse/(xv)\n !mx = S.mean xs\n !va = mse*(1/n+mx^2/xv)\n !xv = G.sum . G.map (\\x -> (x-mx)^2) $ xs\n\n-- | Total Least Squares (TLS) linear regression.\n-- Assumes x-axis values (and not just y-axis values) are random variables and that both variables have similar distributions.\n-- interface is the same as 'linearRegression'.\nlinearRegressionTLS :: Vector v Double => v Double -> v Double -> (Double,Double)\nlinearRegressionTLS xs ys = (alpha, beta)\n where\n !c = covar' m1 m2 n xs ys\n !b = (v1 - v2) / c\n !(m1,v1) = S.meanVarianceUnb xs \n !(m2,v2) = S.meanVarianceUnb ys\n !n = fromIntegral $ G.length xs\n !betas = [(-b - sqrt(b^2+4))/2,(-b + sqrt(b^2+4)) /2]\n !beta = if c > 0 then maximum betas else minimum betas\n !alpha = m2 - beta * m1\n{-# INLINE linearRegressionTLS #-}\n\n-- | An estimated linear relation between 2 samples is (alpha,beta) such that Y = alpha + beta*X.\ntype EstimatedRelation = (Double,Double)\n\n-- | An 'Estimator' is a function that generates an estimated linear regression based on 2 samples. This module provides two estimator functions:\n-- 'linearRegression' and 'linearRegressionTLS'\ntype Estimator = (S.Sample -> S.Sample -> EstimatedRelation)\n\n-- | An 'ErrorFunction' is a function that computes the error of a given point from an estimate. This module provides two error functions correspoinding to the two 'Estimator' functions it defines:\n-- \n-- * Vertical distance squared via 'linearRegressionError' that should be used with 'linearRegression'\n-- \n-- * Total distance squared vie 'linearRegressionTLSError' that should be used with 'linearRegressionTLS'\ntype ErrorFunction = (EstimatedRelation -> (Double,Double) -> Double)\n\n-- | The robust fit algorithm used has various parameters that can be specified using the 'EstimationParameters' record.\ndata EstimationParameters = EstimationParameters {\n -- | Maximal fraction of outliers expected in the sample (default 0.25)\n outlierFraction :: !Double,\n -- | Number of concentration steps to take for initial evaluation of a solution (default 3)\n shortIterationSteps :: !Int,\n -- | Maximal number of sampled subsets (pairs of points) to use as starting points (default 500)\n maxSubsetsNum :: !Int,\n -- | If the initial sample is large, and thus gets subdivided, this is the number of candidate-estimations to take from each subgroup, on which complete convergence will be executed (default 10)\n groupSubsets :: !Int,\n -- | Maximal size of sample that can be analyzed without any sub-division (default 600)\n mediumSetSize :: !Int,\n -- | Maximal size of sample that does not require two-step sub-division (see reference article) (default 1500)\n largeSetSize :: !Int,\n -- | Estimator function to use (default linearRegression)\n estimator :: Estimator,\n -- | ErrorFunction to use (default linearRegressionError)\n errorFunction :: ErrorFunction\n }\n\n-- | Default set of parameters to use (see reference for details).\ndefaultEstimationParameters = EstimationParameters {\n outlierFraction = 0.25,\n shortIterationSteps = 3,\n maxSubsetsNum = 500,\n groupSubsets = 10,\n mediumSetSize = 600,\n largeSetSize = 1500,\n estimator = linearRegression,\n errorFunction = linearRegressionError\n}\n\n-- | linearRegression error function is the square of the /vertical/ distance of a point from the line.\nlinearRegressionError :: ErrorFunction\nlinearRegressionError (alpha,beta) (x,y) = (y-(beta*x+alpha))^2\n\n-- | linearRegressionTLS error function is the square of the /total/ distance of a point from the line.\nlinearRegressionTLSError :: ErrorFunction\nlinearRegressionTLSError (alpha,beta) (x,y) = ey/(1+beta^2)\n where\n ey = linearRegressionError (alpha,beta) (x,y)\n\n-- | Helper function to calculate the minimal expected size of uncontaminated data based on the maximal fraction of outliers.\nsetSize :: Vector v Double => EstimationParameters -> v Double -> Int\nsetSize ep xs = max (n `div` 2 + 1) . round $ (1-outlierFraction ep) * (fromIntegral n)\n where\n n = G.length xs\n\n-- | Helper function that, given an initial estimated relation and the error of the perivous estimation, performs a \"concentration\" step, generating a new estimate based on a fraction of points laying closest to the previous estimate and estimates the error of the previous estimate based on the same fraction.\n-- The result is an estimate that is at least as good as the previous one.\n-- The reason the error is calculated for the previous parameters is calculation optimization.\nconcentrationStep :: Vector v Double => EstimationParameters -> v Double -> v Double -> (EstimatedRelation, Double) -> (EstimatedRelation, Double)\nconcentrationStep ep xs ys (prev, prev_err) = (new_estimate, new_err)\n where\n set_size = setSize ep xs\n xyerrors = map (\\p -> (p,errorFunction ep prev p)) $ zip (G.toList xs) (G.toList ys)\n (xys,errors) = unzip . take set_size . sortBy (compare `on` snd) $ xyerrors\n (good_xs,good_ys) = unzip xys\n new_estimate = estimator ep (G.fromList good_xs) (G.fromList good_ys)\n new_err = sum errors\n\n-- | Infinite set of consecutive concentration steps.\nconcentration :: Vector v Double => EstimationParameters -> v Double -> v Double -> EstimatedRelation -> [(EstimatedRelation, Double)]\nconcentration ep xs ys params = tail $ iterate (concentrationStep ep xs ys) (params,-1)\n\n-- | Calculate the optimal (local minimum) estimate based on an initial estimate.\n-- The local minimum may not be the global (a.k.a. best) estimate but starting from enough different initial estimates should yield the global optimum eventually.\nconverge :: Vector v Double => EstimationParameters -> v Double -> v Double -> EstimatedRelation -> EstimatedRelation\nconverge ep xs ys = fst . findConvergencePoint . concentration ep xs ys\n\n-- | The convergence point is defined as the point the error estimate of which is equal to the next estimate's error.\nfindConvergencePoint :: Ord a => [(b,a)] -> (b,a)\nfindConvergencePoint (x:y:ys)\n | snd x <= snd y = x -- rounding issues my cause an actual increase in error resulting in an infinite loop so the actual stop condition is when the errors stop decreasing\n | otherwise = findConvergencePoint (y:ys)\nfindConvergencePoint xs = error \"Too short a list for conversion (size < 2)\"\n\n-- | Many times there is no need for full concentration as bad initial estimates can be discovered after only a few concentration steps.\nconcentrateNSteps :: Vector v Double => EstimationParameters -> v Double -> v Double -> EstimatedRelation -> (EstimatedRelation,Double)\nconcentrateNSteps ep xs ys params = concentration ep xs ys params !! shortIterationSteps ep\n\n-- | Finding a robust fit linear estimate between two samples. The procedure requires randomization and is based on the procedure described in the reference.\nrobustFit :: (MonadRandom m, Vector v Double) => EstimationParameters -> v Double -> v Double -> m EstimatedRelation\nrobustFit ep xs ys = do\n let n = G.length xs\n-- For optimal performance the exact procedure executed depends on the set size.\n if n < 2\n then\n error \"cannot fit an input of size < 2\"\n else if n == 2\n then return $ lineParams ((G.head xs,G.head ys),(G.last xs,G.last ys))\n else \n liftM (candidatesToWinner ep xs ys) $ if n < mediumSetSize ep\n then\n singleGroupFitCandidates ep Nothing xs ys\n else if n < largeSetSize ep\n then largeGroupFitCandidates ep xs ys\n else do\n (nxs,nys) <- liftM unzip $ randomSubset (zip (G.toList xs) (G.toList ys)) (largeSetSize ep)\n largeGroupFitCandidates ep (U.fromList nxs) (G.fromList nys)\n\n-- | Robust fit yielding also the R-square value of the \\\"clean\\\" dataset.\nrobustFitRSqr :: (MonadRandom m, Vector v Double, Vector v (Double, Double)) => EstimationParameters -> v Double -> v Double -> m (EstimatedRelation,Double)\nrobustFitRSqr ep xs ys = do\n er <- robustFit ep xs ys\n let (good_xs,good_ys) = U.unzip . G.fromList . take (setSize ep xs) . sortBy (compare `on` errorFunction ep er) . G.toList $ G.zip xs ys\n return (er,correl good_xs good_ys ^ 2)\n\n-- | A wrapper that executes 'robustFit' using a default random generator (meaning it is only pseudo-random)\nnonRandomRobustFit :: Vector v Double => EstimationParameters -> v Double -> v Double -> EstimatedRelation\nnonRandomRobustFit ep xs ys = evalRand (robustFit ep xs ys) (mkStdGen 1)\n\n-- | Given a set of initial estimates converge them all and find the optimal one.\ncandidatesToWinner :: Vector v Double => EstimationParameters -> v Double -> v Double -> [EstimatedRelation] -> EstimatedRelation\ncandidatesToWinner ep xs ys = fst . minimumBy (compare `on` snd) . map (findConvergencePoint . concentration ep xs ys)\n\n-- | for a large initial sample - subdivide it, then get candidates from each subgroup. Perform full convergence on all the candidates and return the best ones.\nlargeGroupFitCandidates :: (MonadRandom m, Vector v Double) => EstimationParameters -> v Double -> v Double -> m [EstimatedRelation]\nlargeGroupFitCandidates ep xs ys = do\n let n = G.length xs\n let sub_groups_num = n `div` (mediumSetSize ep `div` 2)\n let sub_groups_size = n `div` sub_groups_num\n shuffled <- shuffleM $ zip (G.toList xs) (G.toList ys)\n let sub_groups = map (G.unzip . U.fromList) $ splitTo sub_groups_size shuffled\n let sub_groups_candidates = maxSubsetsNum ep `div` sub_groups_num\n candidates_list <- mapM (applyTo $ singleGroupFitCandidates ep (Just sub_groups_candidates)) sub_groups\n let candidates = concat candidates_list\n return . map fst . take (groupSubsets ep) . sortBy (compare `on` snd) . map (findConvergencePoint . concentration ep xs ys) $ candidates\n\n-- | For a single group (a group that will not be subdivided) pick an initial set of pairs of points, run a few steps on each, then return the most promising candidates.\nsingleGroupFitCandidates :: (MonadRandom m, Vector v Double) => EstimationParameters -> Maybe Int -> v Double -> v Double -> m [EstimatedRelation]\nsingleGroupFitCandidates ep m_subsets xs ys = do\n let all_pairs = allPairs $ zip (G.toList xs) (G.toList ys)\n let return_size = fromMaybe (maxSubsetsNum ep) m_subsets\n initial_sets <- if return_size > length all_pairs\n then return all_pairs\n else randomSubset all_pairs return_size \n return . map fst . take (groupSubsets ep) . sortBy (compare `on` snd) . map (concentrateNSteps ep xs ys . lineParams) $ initial_sets\n\n-- | Find the line passing between two points. This is the initial estimate to use given two random points.\nlineParams :: ((Double,Double),(Double,Double)) -> EstimatedRelation\nlineParams ((x1,y1),(x2,y2)) = (alpha,beta)\n where\n beta = (y2-y1)/(x2-x1)\n alpha = y1 - beta*x1\n\n-- | A list of all possible two-element pairs from a list.\nallPairs :: [a] -> [(a,a)]\nallPairs [] = []\nallPairs [x] = []\nallPairs [x,y] = [(x,y)]\nallPairs (x:xs) = (zip xs . repeat $ x) ++ allPairs xs\n\n-- | Get a random subset of a given size.\nrandomSubset :: MonadRandom m => [a] -> Int -> m [a]\nrandomSubset xs size = liftM (take size) $ shuffleM xs\n\n-- | Split a list into sublists of length n.\nsplitTo :: Int -> [a] -> [[a]]\nsplitTo n = map (take n) . takeWhile (not . null) . iterate (drop n)\n\n-- | Helper function to adjust parameter handling\napplyTo :: (a->b->c) -> (a,b) -> c\napplyTo f (x,y) = f x y\n\n-- $references\n--\n-- * Two Dimensional Euclidean Regression (Stein) \n--\n-- * Computing LTS Regression For Large Data Sets (Rousseeuw and Driessen) \n--\n-- * Applied linear statistical models (Kutner et al.)\n", "meta": {"hexsha": "d861f3465bca34186ec48440fb198faf75b0f356", "size": 17217, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/LinearRegression.hs", "max_stars_repo_name": "alpmestan/statistics-linreg", "max_stars_repo_head_hexsha": "14c2f10088d1914b0303c191ec0d7243c8eb83ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2016-01-09T12:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-13T01:29:03.000Z", "max_issues_repo_path": "Statistics/LinearRegression.hs", "max_issues_repo_name": "alpmestan/statistics-linreg", "max_issues_repo_head_hexsha": "14c2f10088d1914b0303c191ec0d7243c8eb83ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-02-23T12:40:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-23T13:05:49.000Z", "max_forks_repo_path": "Statistics/LinearRegression.hs", "max_forks_repo_name": "alpmestan/statistics-linreg", "max_forks_repo_head_hexsha": "14c2f10088d1914b0303c191ec0d7243c8eb83ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.8128834356, "max_line_length": 310, "alphanum_fraction": 0.6883893826, "num_tokens": 4215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6865539931979632}} {"text": "import Numeric.LinearAlgebra\nimport Graphics.Plot\n\nvector l = fromList l :: Vector Double\nmatrix ls = fromLists ls :: Matrix Double\ndiagl = diag . vector\n\nf = matrix [[1,0,0,0],\n [1,1,0,0],\n [0,0,1,0],\n [0,0,0,1]]\n\nh = matrix [[0,-1,1,0],\n [0,-1,0,1]]\n\nq = diagl [1,1,0,0]\n\nr = diagl [2,2]\n\ns0 = State (vector [0, 0, 10, -10]) (diagl [10,0, 100, 100])\n\ndata System = System {kF, kH, kQ, kR :: Matrix Double}\ndata State = State {sX :: Vector Double , sP :: Matrix Double}\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\nsys = System f h q r\n\nzs = [vector [15-k,-20-k] | k <- [0..]]\n\nxs = s0 : zipWith (kalman sys) xs zs\n\ndes = map (sqrt.takeDiag.sP) xs\n\nevolution n (xs,des) =\n vector [1.. fromIntegral n]:(toColumns $ fromRows $ take n (zipWith (-) (map sX xs) des)) ++\n (toColumns $ fromRows $ take n (zipWith (+) (map sX xs) des))\n\nmain = do\n print $ fromRows $ take 10 (map sX xs)\n mapM_ (print . sP) $ take 10 xs\n mplot (evolution 20 (xs,des))\n", "meta": {"hexsha": "7fbe3d2f8459daed146a955f71fbfb6099d7cb99", "size": 1510, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/kalman.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/kalman.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/kalman.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.0384615385, "max_line_length": 96, "alphanum_fraction": 0.517218543, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6864105327619034}} {"text": "module AI.Learning.Core where\r\n\r\nimport Numeric.LinearAlgebra\r\nimport Numeric.GSL.Minimization\r\n\r\n---------------\r\n-- Utilities --\r\n---------------\r\n\r\n-- |Sigmoid function:\r\n--\r\n-- > sigmoid x = 1 / (1 + exp (-x))\r\n--\r\n-- Used in the logistic regression and neural network modules.\r\nsigmoid :: Floating a => a -> a\r\nsigmoid x = 1 / (1 + exp (-x))\r\n\r\n------------------\r\n-- Optimization --\r\n------------------\r\n\r\n-- |Simplified minimization function. You supply functions that compute the\r\n-- quantity to be minimized and its gradient, and an initial guess, and the\r\n-- final solution is returned.\r\nminimizeS :: (Vector Double -> Double) -- f\r\n -> (Vector Double -> Vector Double) -- gradient\r\n -> Vector Double -- initial x\r\n -> Vector Double\r\nminimizeS f g x = fst $ minimizeVD VectorBFGS2 prec niter sz tol f g x\r\n where prec = 1e-9\r\n niter = 1000\r\n sz = 0.1\r\n tol = 0.1\r\n", "meta": {"hexsha": "fdcf98e4b591c6a1898e097522477b6c0df4e03d", "size": 981, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AI/Learning/Core.hs", "max_stars_repo_name": "cagix/aima-haskell", "max_stars_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 245, "max_stars_repo_stars_event_min_datetime": "2015-01-08T18:52:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T06:58:10.000Z", "max_issues_repo_path": "src/AI/Learning/Core.hs", "max_issues_repo_name": "bemcho/aima-haskell-1", "max_issues_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-11-09T12:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-10T23:14:19.000Z", "max_forks_repo_path": "src/AI/Learning/Core.hs", "max_forks_repo_name": "bemcho/aima-haskell-1", "max_forks_repo_head_hexsha": "538dcfe82a57a623e45174e911ce68974d8aa839", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2015-01-12T00:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T03:09:12.000Z", "avg_line_length": 28.8529411765, "max_line_length": 77, "alphanum_fraction": 0.5392456677, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6860465334567339}} {"text": "import Numeric.LinearAlgebra\nimport Control.Monad\nimport System.Random\n\n\nmakeNetwork :: [Int] -> IO [Matrix R]\nmakeNetwork layersDesc = zipWithM randn (tail layersDesc) layersDesc\n\nlearnExample :: R -> [Matrix R] -> (Vector R, Vector R) -> [Matrix R]\nlearnExample learingRate network (input, output) =\n backpropagate learingRate output (propagate input network) network\n\ntrain :: R -> [Matrix R] -> Int -> [(Vector R, Vector R)] -> [Matrix R]\ntrain learingRate network epochs trainingData =\n foldl (learnExample learingRate) network (concat $ replicate epochs trainingData)\n\npropagate :: Vector R -> [Matrix R] -> [Vector R]\npropagate = scanl (\\out w -> cmap (\\x -> 1 / (1 + exp (-x))) $ w #> out)\n\nbackpropagate :: R -> Vector R -> [Vector R] -> [Matrix R] -> [Matrix R]\nbackpropagate learingRate targetOutput layerOutputs network = reverse revNewWeights\n where\n out = last layerOutputs\n outputDelta = (out - targetOutput)*out*(scalar 1 - out)\n revNetwork = reverse network\n revOutputs = reverse layerOutputs\n revDeltas = outputDelta : zipWith3 (\\o w nextDelta -> (nextDelta <# w)*o*(scalar 1 - o))\n (tail revOutputs) revNetwork revDeltas\n revNewWeights = zipWith3 (\\o d w -> w - scale learingRate (outer d o)) (tail revOutputs) revDeltas revNetwork\n\nmain :: IO ()\nmain = do\n network <- makeNetwork [3,4,1] -- we need a bias neuron\n xs <- replicateM samples (randomRIO (-val, val))\n ys <- replicateM samples (randomRIO (-val, val))\n let trainInput = zipWith (\\x y -> vector [x,y,1]) xs ys\n let trainOutput = map targetFunction2 trainInput\n let trainedNetwork = train 0.03 network 100 (zip trainInput trainOutput)\n mapM_ (\\y -> do\n mapM_ (\\x ->\n putChar $ let out = last $ propagate (vector [x,y,1]) trainedNetwork in if (out ! 0) > 0.5 then '#' else '.')\n --putStr $ let out = last $ propagate (vector [x,y,1]) trainedNetwork in show (out ! 0) ++ \" \")\n [-val, -val + 0.1 .. val]\n putChar '\\n')\n [-val, -val + 0.1 .. val]\n where\n targetFunction v = if sqrt ((v ! 0)^(2::Int) + (v ! 1)^(2::Int)) <= r then vector [0] else vector [1]\n targetFunction2 v = if (v ! 0) >= 0 then vector [0] else vector [1]\n r = 1.5\n samples = 1000\n val = 2\n", "meta": {"hexsha": "14dfee93757b87ee6d6554b2b4c87a13795d46fd", "size": 2341, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Network.hs", "max_stars_repo_name": "cosmo-jana/numerics-physics-stuff", "max_stars_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-16T16:35:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T16:35:35.000Z", "max_issues_repo_path": "Network.hs", "max_issues_repo_name": "cosmo-jana/numerics-physics-stuff", "max_issues_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "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.hs", "max_forks_repo_name": "cosmo-jana/numerics-physics-stuff", "max_forks_repo_head_hexsha": "f5fb35c00c84ca713877e20c1d8186e76883cd28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0192307692, "max_line_length": 121, "alphanum_fraction": 0.6159760786, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6859577495567329}} {"text": "-- ch03 example 3.9\n\nimport Statistics.Distribution\nimport Statistics.Distribution.Binomial\n\nb :: BinomialDistribution\nb = binomial 20 0.05\n\nmain = do\n putStrLn $ \"P(Y>=4) is given by 1-P(Y<=3): \" ++ show (1 - cumulative b 3.00)\n putStrLn $ \"P(Y>=4) is given by 1-P(Y<=3): \" ++ show (complCumulative b 3.00)\n putStrLn $ \"P(Y>=4) is given by 1-P(Y<=3): \" \n ++ show (1 - sum (map (probability b) [0 .. 3]))\n", "meta": {"hexsha": "daca663ad2ea9b3dbe066269cc4f4f37f213fb98", "size": 417, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ch03/ex3_09.hs", "max_stars_repo_name": "raydsameshima/Stat", "max_stars_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch03/ex3_09.hs", "max_issues_repo_name": "raydsameshima/Stat", "max_issues_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch03/ex3_09.hs", "max_forks_repo_name": "raydsameshima/Stat", "max_forks_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": 29.7857142857, "max_line_length": 79, "alphanum_fraction": 0.6163069544, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6853757849741181}} {"text": "module Numeric.Chebyshev.Internal\n ( -- * Interpolation on Chebyshev points\n Chebvals\n , chebpoints\n , sample\n , interpolate\n\n -- * Sum of Chebyshev polynomials\n , Chebpoly\n , integral\n\n -- * Conversion\n , valsToPoly\n , polyToVals\n\n -- * Testing\n , prop_interpolate_on\n , prop_inverse\n , prop_chebyshev\n )\n where\n\nimport Data.Maybe ( fromMaybe )\nimport Data.Vector.Unboxed ( Vector, (!), Unbox )\nimport Data.Complex ( Complex((:+)), realPart )\n\nimport Numeric.Fourier\n\nimport qualified Data.Vector.Unboxed as V\n\n{-----------------------------------------------------------------------------\n Chebyshev interpolation\n------------------------------------------------------------------------------}\n-- | A polynomial, given by its values at Chebyshev points.\n--\n-- The value @(Chebvals fs)@ represents the unique polynomial\n-- $f(x)$ of order $n$ that satisfies\n--\n-- > f (chebpoints n !! j) = fs ! j for all j = [0..n]\nnewtype Chebvals = Chebvals { getChebvals :: Vector Double }\n deriving (Eq, Show)\n\n-- | Chebyshev points of order $n$.\nchebpoints :: Int -> Vector Double\nchebpoints n = getChebvals $ sample n id\n\n-- | Sample a function at the Chebyshev points\nsample :: Int -> (Double -> Double) -> Chebvals\nsample n f = Chebvals $ V.generate (n+1) $ \\j ->\n f $ cos (pi * fromIntegral j / fromIntegral n)\n\n-- | Evaluate a 'Chebvals' at any point in the interval $[-1,1]$\n-- through interpolation.\ninterpolate :: Chebvals -> Double -> Double\ninterpolate (Chebvals fs) = \\x ->\n let ys = barycenters x\n in correctNaN x $ sumMap (\\j y -> fs!j * y) ys / V.sum ys\n where\n n = V.length fs - 1\n xs = chebpoints n\n sign j = if even j then 1 else (-1)\n weight j\n | j == 0 = 0.5\n | j == n = 0.5 * sign j\n | otherwise = sign j\n barycenters x = V.generate (n+1) $ \\j -> weight j / (x - xs!j)\n correctNaN x result\n | isNaN result = fs ! (fromMaybe 0 $ binarySearchReverse x xs)\n | otherwise = result\n\n-- | Binary search in a vector that is sorted from /largest/ to /smallest/.\nbinarySearchReverse :: (Ord a, Unbox a) => a -> Vector a -> Maybe Int\nbinarySearchReverse x xs = go 0 (n-1)\n where\n n = V.length xs\n go a b\n | b - a <= 1 =\n if x == xs!a then Just a\n else if x == xs!b then Just b\n else Nothing\n | otherwise = case x `compare` (xs!m) of\n LT -> go m b\n GT -> go a m\n EQ -> Just m\n where\n m = a + (b-a) `div` 2\n\n{-----------------------------------------------------------------------------\n Chebyshev polynomials\n------------------------------------------------------------------------------}\n-- | A polynomial, given as a linear combination of Chebyshev polynomials.\n--\n-- The $k$-the Chebyshev polynomial in the variable $x \\in [-1,1]$\n-- is defined as\n-- \n-- $T^k(x) := \\frac12 (z^k + z^{-k})$\n--\n-- where $z = e^{iθ}$ for $x = \\cos θ$. This function is, in fact,\n-- a polynomial in $x$.\nnewtype Chebpoly = Chebpoly (Vector Double)\n deriving (Eq, Show)\n\n-- | Definite integral of a polynomial over the interval [-1,1].\nintegral :: Chebpoly -> Double\nintegral (Chebpoly cs) = sumMap (\\j c -> c * integral j) cs\n where\n integral k = if odd k then 0 else 2/(1-fromIntegral k^2)\n\n{-----------------------------------------------------------------------------\n Conversion\n------------------------------------------------------------------------------}\ntoComplex :: Vector Double -> Vector (Complex Double)\ntoComplex = V.map (:+ 0)\n\ntoReal :: Vector (Complex Double) -> Vector Double\ntoReal = V.map realPart\n\n-- | Expansion of a polynomial in terms of\n-- Chebyshev polynomials, using the fast Fourier transform (FFT).\nvalsToPoly :: Chebvals -> Chebpoly\nvalsToPoly (Chebvals fs) =\n Chebpoly $ toReal $ uncircle $ fft $ toComplex $ circle fs\n where\n n = V.length fs - 1\n m = 2*n\n circle v = V.generate m $ \\j ->\n if j <= n then v!j else v!(m-j)\n uncircle v = V.generate (n+1) $ \\k -> (1/fromIntegral m)\n * (if k == 0 || k == n then v!k else v!k + v!(m-k))\n\n-- | Evaluation of a sum of Chebyshev polynomials\n-- using the fast Fourier transform (FFT).\npolyToVals :: Chebpoly -> Chebvals\npolyToVals (Chebpoly as) =\n Chebvals $ toReal $ uncircle $ ifft $ circle $ toComplex as\n where\n n = V.length as - 1\n m = 2*n\n circle v = V.generate m $ \\k -> fromIntegral m *\n (if k == 0 || k == n\n then v!k\n else 0.5 * (if k < n then v!k else v!(m-k)))\n uncircle v = V.generate (n+1) $ \\k ->\n if k == 0 || k == n then v!k else 0.5*(v!k + v!(m-k))\n\n{- Note [ChebyshevFourier]\n\nExpansion in terms of Chebyshev polynomials in terms of the Fourier\ntransform.\n\nAssume that f(x) is a sum of Chebyshev polynomials of degree <= N\n\n f(x) = \\sum_{k = 0…N} a_k 1/2·(z^k + z^{ -k})\n\nLet M = 2N. Then, the values of this polynomial at the Chebyshev points\n\n x_j = cos(2πi/M j) j = 0 … M-1\n = x_{M - j}\n\nare given by the Fourier sum\n\n f(x_j) = \\frac1M \\sum_{k = 0 … M-1} c_k exp(2πi/M·jk)\n\nwhere\n\n a_0 = 1/M·c_0\n a_k = 1/2·1/M·c_k = 1/2·1/M·c_{M-k}\n a_N = 1/M·c_N\n\n-}\n\n{-----------------------------------------------------------------------------\n Testing\n------------------------------------------------------------------------------}\n-- | 'interpolate' returns exact values when evaluated on Chebyshev points.\nprop_interpolate_on :: Int -> (Double -> Double) -> Bool\nprop_interpolate_on n f =\n V.map (interpolate (sample n f)) xs == V.map f xs\n where\n xs = chebpoints n\n\n-- | 'polyToVals' and 'valsToPoly' are inverses of each other.\nprop_inverse :: Chebvals -> Bool\nprop_inverse xs = vec xs `approx` vec (polyToVals (valsToPoly xs))\n where vec (Chebvals v) = v\n\n-- | Evaluating a Chebyshev polynomial using `polyToVals'\n-- gives the same result as using the recursion formula.\nprop_chebyshev :: Int -> Bool\nprop_chebyshev k =\n vec (polyToVals fun) `approx` vec (sample n $ chebyshev k)\n where\n vec (Chebvals v) = v\n m = ceiling $ log (fromIntegral k) / log 2\n n = 2^m\n fun = Chebpoly $ V.generate (n+1) $ \\j -> if j == k then 1 else 0\n\n-- | Evaluate the $k$-the Chebyshev polynomial at argument @x@\n-- using the recursive formula\n--\n-- \\[\\begin{aligned}\n-- T_0(x) &= 1 \\\\\n-- T_1(x) &= x \\\\\n-- T_{n}(x) &= 2xT_{n-1}(x) - T_{n-2}(x) \\\\\n-- \\end{aligned}\n-- \\]\nchebyshev :: Int -> Double -> Double\nchebyshev k x = chebs !! k\n where\n chebs = 1 : x : zipWith (-) (map (2*x*) $ tail chebs) chebs\n\n{-----------------------------------------------------------------------------\n Utilities\n------------------------------------------------------------------------------}\n-- | Efficient implementation of\n--\n-- > sumMap f = V.sum (V.imap f)\nsumMap :: (Int -> Double -> Double) -> Vector Double -> Double\nsumMap f = V.ifoldl' (\\total j a -> total + f j a) 0\n{-# INLINE sumMap #-}\n\n-- | L1 distance between two vectors.\ndist :: Vector Double -> Vector Double -> Double\ndist xs ys = V.sum $ V.zipWith (\\x y -> abs (x-y)) xs ys\n\n-- | Approximate equality up to machine precision\napprox xs ys = dist xs ys / dist xs (V.map (const 0) ys) < eps\n where eps = 1e-15\n", "meta": {"hexsha": "11159193323f92e8ebfeff23315cca605a8cc211", "size": 7203, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Chebyshev/Internal.hs", "max_stars_repo_name": "HeinrichApfelmus/chebyshev", "max_stars_repo_head_hexsha": "ee84bbc82f85fcf3f5a0c2b64d3549f6dc13d692", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Chebyshev/Internal.hs", "max_issues_repo_name": "HeinrichApfelmus/chebyshev", "max_issues_repo_head_hexsha": "ee84bbc82f85fcf3f5a0c2b64d3549f6dc13d692", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Chebyshev/Internal.hs", "max_forks_repo_name": "HeinrichApfelmus/chebyshev", "max_forks_repo_head_hexsha": "ee84bbc82f85fcf3f5a0c2b64d3549f6dc13d692", "max_forks_repo_licenses": ["BSD-3-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.4541484716, "max_line_length": 79, "alphanum_fraction": 0.5389421075, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6853139243956617}} {"text": "module LeastSquares where\n\nimport Numeric.LinearAlgebra\n\nn = 20\nx = linspace n (-3,7::Double)\ny0 = 3 * x\n\nmain = do\n noise <- randn 1 n\n let y = (flatten noise) + y0\n let sampleMatrix = (asColumn x) ||| (konst 1 (n,1))\n let sol = (sampleMatrix <\\> y) \n print $ \"Best fit is y = \" ++ show (sol ! 0) ++ \" * x + \" ++ (show (sol ! 1))\n\n\n", "meta": {"hexsha": "aa459b928f4e1602b26da47c8cf7a257e1ae2d25", "size": 368, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/LeastSquares.hs", "max_stars_repo_name": "philzook58/basic-ass-shit", "max_stars_repo_head_hexsha": "3a0726867038c40d7d9c4843eadecdba848ce55a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-06-30T14:24:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T04:11:18.000Z", "max_issues_repo_path": "app/LeastSquares.hs", "max_issues_repo_name": "philzook58/basic-ass-shit", "max_issues_repo_head_hexsha": "3a0726867038c40d7d9c4843eadecdba848ce55a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/LeastSquares.hs", "max_forks_repo_name": "philzook58/basic-ass-shit", "max_forks_repo_head_hexsha": "3a0726867038c40d7d9c4843eadecdba848ce55a", "max_forks_repo_licenses": ["BSD-3-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.6470588235, "max_line_length": 85, "alphanum_fraction": 0.5244565217, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6852497948952847}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE GADTs #-}\n\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\n\n{-|\nModule : Numeric.LinearProgramming.LP.Static\nDescription : Solve linear programs using static vectors/matrices.\nCopyright : (c) Ryan Orendorff, 2020\nLicense : BSD3\nStability : experimental\n-}\nmodule Numeric.LinearProgramming.LP.Static (\n affineScaling\n)\nwhere\n\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Static\nimport qualified Numeric.LinearAlgebra.Static as S\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.UnitaryRational\n\n-- | https://en.wikipedia.org/wiki/Karmarkar%27s_algorithm\naffineScaling :: (KnownNat m, KnownNat n, KnownNat p, KnownNat q) => L m n -> R m -> R n -> R n -> UnitaryRational p q -> [Maybe (R n)]\naffineScaling a b c x0 gamma = iterate (>>= go) (Just x0)\n where\n gamma' = unitaryToFractional gamma\n\n min_vh :: (KnownNat n) => R n -> R n -> Double\n min_vh v h = minimum . map fst . filter ((<0) . snd) $ vals_with_h\n where\n vals = zipWithVector (\\vi hi -> -vi/hi) v h\n vals_with_h = zip (LA.toList $ extract vals) (LA.toList $ extract h)\n\n go xk = let\n vk = b - a #> xk\n dm_negsq = diag $ dvmap (**(-2)) vk\n hx = inv ((tr a) S.<> dm_negsq S.<> a) #> c\n hv = ((konst (-1)) * a #> hx)\n alpha = gamma' * min_vh vk hv\n xkp1 = xk + (konst alpha) * hx\n in \n if ((>=0) . maximum . LA.toList . extract $ hv)\n then Nothing\n else Just xkp1\n\n-- Example\n-- -------\n--\n-- \n-- p = vector [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] :: R 11\n-- \n-- -- min c^Tx\n-- c = vec2 1 1\n-- \n-- -- s.t Ax <= b\n-- a = ((konst 2) * (col p)) ||| (1 :: L 11 1)\n-- b = p**2 + 1\n-- \n-- lpSol = affineScaling a b c (konst 0) (UnitaryRational :: UnitaryRational 50 100)\n-- \n-- mapM_ (disp 10 . fromJust) . take 20 $ lpSol\n", "meta": {"hexsha": "53725611298916133e91f490b0c7a9d6c4a1e6e6", "size": 2292, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearProgramming/LP/Static.hs", "max_stars_repo_name": "ryanorendorff/convex", "max_stars_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-06-13T21:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:53:28.000Z", "max_issues_repo_path": "src/Numeric/LinearProgramming/LP/Static.hs", "max_issues_repo_name": "ryanorendorff/convex", "max_issues_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/LinearProgramming/LP/Static.hs", "max_forks_repo_name": "ryanorendorff/convex", "max_forks_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.972972973, "max_line_length": 135, "alphanum_fraction": 0.5785340314, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6849885687409961}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule TheField where\n\nimport Data.Complex\nimport Data.Char\nimport Data.List as L\nimport Graphics.Rendering.Chart.Easy hiding (transform)\nimport Graphics.Rendering.Chart.Backend.Diagrams\n--\nimport TheField.Image\nimport TheField.Plot\n\ni :: Num a => a -> Complex a\ni n = 0 :+ n\n\ne :: Floating a => Complex a\ne = exp 1 :+ 0\n\ns :: [Complex Double]\ns = [ 2 + i 2\n , 3 + i 2\n , 1.75 + i 1\n , 2 + i 1\n , 2.25 + i 1\n , 2.5 + i 1\n , 2.75 + i 1\n , 3 + i 1\n , 3.25 + i 1\n ]\n\n-- Task 1.4.1\nplotComplex :: EC (Layout Double Double) ()\nplotComplex = plot' pts 4 4\n where pts = s\n\n-- Task 1.4.3\nplotTranslate :: EC (Layout Double Double) ()\nplotTranslate = plot' pts 5 5\n where pts = [ pt + (1 + i 2) | pt <- s ]\n\n-- Task 1.4.4\nplotEyeCentral :: EC (Layout Double Double) ()\nplotEyeCentral = plot' pts 4 4\n where pts = [ - 1 * (2 :+ 2) + pt | pt <- s ]\n\n-- Task 1.4.7\nplotScaled :: EC (Layout Double Double) ()\nplotScaled = plot' pts 4 4\n where pts = [ 0.5 * pt | pt <- s ]\n\n-- Task 1.4.8\nplotRotation :: EC (Layout Double Double) ()\nplotRotation = plot' pts 4 4\n where pts = [ i 0.5 * pt | pt <- s ]\n\n-- Task 1.4.9\nplotTranslatedRotation :: EC (Layout Double Double) ()\nplotTranslatedRotation = plot' pts 4 4\n where pts = [ (i 0.5 * pt) + i (-1) + 2 | pt <- s ]\n\n-- Task 1.4.10\nplotImage :: [(Double, Double)] -> EC (Layout Double Double) ()\nplotImage img = plot' pts 200 200\n where pts = [ x :+ y | (x, y) <- img ]\n\nexamplePng :: IO [(Double, Double)]\nexamplePng = do\n withIntensity 120 . pixels <$> readImage \"./src/TheField/img01.png\"\n where\n withIntensity ins pts =\n [ (fromIntegral x, fromIntegral y) | (x, y, pxl) <- pts, intensity pxl > ins ]\n\n-- Task 1.4.17\nplotE :: EC (Layout Double Double) ()\nplotE = plot' pts 2 2\n where pts = [ e ** ((x * pi :+ 0) * i 2 / (n :+ 0)) | x <- [0..n-1] ]\n n = 20\n\n-- Task 1.4.18\nplotRotation' :: EC (Layout Double Double) ()\nplotRotation' = plot' pts 4 4\n where pts = [ pt * e ** i (pi / 4) | pt <- s ]\n\n-- Task 1.4.19\nplotImageRotation :: [(Double, Double)] -> EC (Layout Double Double) ()\nplotImageRotation img = plot' pts 200 200\n where\n pts = [ rotate $ x :+ y | (x, y) <- img ]\n rotate pt = pt * e ** i (pi / 4)\n\n-- Task 1.4.20\nplotMultipleOperations :: [(Double, Double)] -> EC (Layout Double Double) ()\nplotMultipleOperations img = plot' pts 200 200\n where\n pts = [ scale . rotate . transform $ x :+ y | (x, y) <- img ]\n rotate = (*) (e ** i (pi / 4))\n scale = (*) 0.5\n transform = (+) (-1 * (100 :+ 100))\n\n-- Task 1.5.1\nmessage :: [String]\nmessage =\n [ \"10101\"\n , \"00100\"\n , \"10101\"\n , \"01011\"\n , \"11001\"\n , \"00011\"\n , \"01011\"\n , \"10101\"\n , \"00100\"\n , \"11001\"\n , \"11010\"\n ]\n\ndecryptMessage :: String\ndecryptMessage = decryptCyphertext [1,0,0,0,1] message\n\ndecryptCyphertext :: [Int] -> [String] -> String\ndecryptCyphertext key = L.foldr ((:) . decode) \"\"\n where\n decode = decodeChar . decodeNumber . L.map (uncurry decryptBit) . zip key . L.map toBit\n toBit b = if b == '1' then 1 else 0\n\n-- try all possible keys in attempt to find the answer\nbrute :: [([Int], String)]\nbrute = L.map (\\k -> (k, decryptCyphertext k message)) keys\n where\n keys = [ [a,b,c,d,e] | a <- [0..1], b <- [0..1], c <- [0..1], d <- [0..1], e <- [0..1] ]\n\ndecryptBit :: Int -> Int -> Int\ndecryptBit k v = (k + v) `mod` 2\n\ndecodeNumber :: [Int] -> Int\ndecodeNumber str = L.foldr ((+) . uncurry decode) 0 $ zip [0..] (reverse str)\n where decode idx val = val * 2 ^ idx\n\ndecodeChar :: Int -> Char\ndecodeChar n =\n case n' of\n 26 -> ' '\n _ -> chr $ n' + 65\n where n' = n `mod` 27\n\n-- Task 1.7.10\nsumComplexNumbersA :: EC (Layout Double Double) ()\nsumComplexNumbersA = plotComplexAddition (3.0 :+ 1.0) (2.0 :+ 2.0)\n\nsumComplexNumbersB :: EC (Layout Double Double) ()\nsumComplexNumbersB = plotComplexAddition ((-1.0) :+ 2.0) (1.0 :+ (-1.0))\n\nsumComplexNumbersC :: EC (Layout Double Double) ()\nsumComplexNumbersC = plotComplexAddition (2.0 :+ 0.0) ((-3.0) :+ 0.001)\n\nsumComplexNumbersD :: EC (Layout Double Double) ()\nsumComplexNumbersD = plotComplexAddition (4 * (0.0 :+ 2.0)) (0.001 :+ 1.0)\n\ngenerateImages :: IO ()\ngenerateImages = do\n toFile def \"./src/TheField/task-1.4.1.svg\" plotComplex\n toFile def \"./src/TheField/task-1.4.3.svg\" plotTranslate\n toFile def \"./src/TheField/task-1.4.4.svg\" plotEyeCentral\n toFile def \"./src/TheField/task-1.4.7.svg\" plotScaled\n toFile def \"./src/TheField/task-1.4.8.svg\" plotRotation\n toFile def \"./src/TheField/task-1.4.9.svg\" plotTranslatedRotation\n toFile def \"./src/TheField/task-1.4.10.svg\" =<< plotImage <$> examplePng\n toFile def \"./src/TheField/task-1.4.17.svg\" plotE\n toFile def \"./src/TheField/task-1.4.18.svg\" plotRotation'\n toFile def \"./src/TheField/task-1.4.19.svg\" =<< plotImageRotation <$> examplePng\n toFile def \"./src/TheField/task-1.4.20.svg\" =<< plotMultipleOperations <$> examplePng\n toFile def \"./src/TheField/task-1.7.10-a.svg\" sumComplexNumbersA\n toFile def \"./src/TheField/task-1.7.10-b.svg\" sumComplexNumbersB\n toFile def \"./src/TheField/task-1.7.10-c.svg\" sumComplexNumbersC\n toFile def \"./src/TheField/task-1.7.10-d.svg\" sumComplexNumbersD\n", "meta": {"hexsha": "0298bd750a87aa83459977e37468d5a3f9b35f35", "size": 5233, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TheField.hs", "max_stars_repo_name": "danbroooks/coding-the-matrix", "max_stars_repo_head_hexsha": "4eceaf308f74f919effb3f8b67f9bf9a4f31d315", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-20T07:16:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:16:23.000Z", "max_issues_repo_path": "src/TheField.hs", "max_issues_repo_name": "danbroooks/coding-the-matrix", "max_issues_repo_head_hexsha": "4eceaf308f74f919effb3f8b67f9bf9a4f31d315", "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/TheField.hs", "max_forks_repo_name": "danbroooks/coding-the-matrix", "max_forks_repo_head_hexsha": "4eceaf308f74f919effb3f8b67f9bf9a4f31d315", "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.7329545455, "max_line_length": 92, "alphanum_fraction": 0.6059621632, "num_tokens": 1857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6845373052796001}} {"text": "module Math.AlgebraicNumbers.Overloads where\nimport Math.AlgebraicNumbers.Prelude\nimport Math.AlgebraicNumbers.Class\nimport Math.AlgebraicNumbers.AReal\nimport Math.AlgebraicNumbers.AComplex\nimport qualified Prelude\nimport qualified Data.Complex\n\n-- Prelude functions generalized from Integral a to GCDDomain a / EuclideanDomain a\n\ngcd :: (GCDDomain a) => a -> a -> a\ngcd = gcdD\n\nlcm :: (GCDDomain a) => a -> a -> a\nlcm = lcmD\n\ndivMod :: (EuclideanDomain a) => a -> a -> (a, a)\ndivMod = divModD\n\ninfixl 7 `div`, `mod`\n\ndiv, mod :: (EuclideanDomain a) => a -> a -> a\ndiv = divD\nmod = modD\n\nclass Sqrt a where\n sqrt :: a -> a\n maybeSqrt :: a -> Maybe a\n\ninstance Sqrt Prelude.Float where\n sqrt = Prelude.sqrt\n maybeSqrt x | x >= 0 = Just $ Prelude.sqrt x\n | otherwise = Nothing\n\ninstance Sqrt Prelude.Double where\n sqrt = Prelude.sqrt\n maybeSqrt x | x >= 0 = Just $ Prelude.sqrt x\n | otherwise = Nothing\n\ninstance (RealFloat a) => Sqrt (Data.Complex.Complex a) where\n sqrt = Prelude.sqrt\n maybeSqrt = Just . Prelude.sqrt\n\ninstance Sqrt AReal where\n sqrt = sqrtA\n maybeSqrt x | x >= 0 = Just $ sqrtA x\n | otherwise = Nothing\n\ninstance Sqrt AComplex where\n sqrt = sqrtAN\n maybeSqrt = Just . sqrtAN\n\n-- toRational?\n", "meta": {"hexsha": "a22e0555ada394d21fff271281dac670cb4797cc", "size": 1260, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/AlgebraicNumbers/Overloads.hs", "max_stars_repo_name": "minoki/algebraic-numbers", "max_stars_repo_head_hexsha": "8b81dc2e2ee1f3edfad427990b771557a030ae83", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/AlgebraicNumbers/Overloads.hs", "max_issues_repo_name": "minoki/algebraic-numbers", "max_issues_repo_head_hexsha": "8b81dc2e2ee1f3edfad427990b771557a030ae83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/AlgebraicNumbers/Overloads.hs", "max_forks_repo_name": "minoki/algebraic-numbers", "max_forks_repo_head_hexsha": "8b81dc2e2ee1f3edfad427990b771557a030ae83", "max_forks_repo_licenses": ["BSD-3-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.3333333333, "max_line_length": 83, "alphanum_fraction": 0.6777777778, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676514011486, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6844234038051834}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule Stats where\n\nimport Control.Applicative\nimport Control.Monad.State\nimport Data.Random\nimport Data.Random.Distribution.Exponential\nimport Data.Random.Source.PureMT\nimport qualified Data.Vector as V\nimport Data.Word\nimport qualified Statistics.Sample.Histogram as S\n\nseed :: Word64\nseed = 123\n\nsampleStream :: (Num t, Distribution d t) => d t -> [t]\nsampleStream distribution = evalState (iterateM $ sample distribution) (pureMT seed)\n\niterateM :: (Applicative m) => m a -> m [a]\niterateM f = liftA2 (:) f (iterateM f)\n\nsampleVector :: (Num t, Distribution d t) => d t -> Int -> V.Vector t\nsampleVector distribution size = V.fromList . take size $ sampleStream distribution\n\nsampleExp :: Int -> V.Vector Double\nsampleExp = sampleVector (Exp 1)\n\nsampleExp' :: Int -> V.Vector Double\nsampleExp' = fmap (negate . log) . sampleVector StdUniform\n\nexpHistograms :: (V.Vector Double, V.Vector Double)\nexpHistograms = S.histogram 30 (sampleExp 1000)\n\nexpHistograms' :: (V.Vector Double, V.Vector Double)\nexpHistograms' = S.histogram 30 (sampleExp' 1000)\n\nmean :: Floating a => V.Vector a -> a\nmean xs = V.sum xs / fromIntegral (V.length xs)\n\nvar :: Floating a => V.Vector a -> a\nvar xs = mean (fmap (** 2) xs) - mean xs ** 2\n\nisCloseWithTolerance :: (Ord a, Floating a) => a -> a -> a -> a -> Bool\nisCloseWithTolerance aTol rTol x y = abs (x - y) <= aTol + rTol * abs y\n\nisClose :: (Ord a, Floating a) => a -> a -> Bool\nisClose = isCloseWithTolerance 1e-8 1e5\n", "meta": {"hexsha": "69afec63538dc9f60503231ecbe152f24377d7d6", "size": 1591, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Stats.hs", "max_stars_repo_name": "anthony-khong/montecarlo", "max_stars_repo_head_hexsha": "22cdaa84b7215d7925bd4ad1f06d7d5af4bbf819", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Stats.hs", "max_issues_repo_name": "anthony-khong/montecarlo", "max_issues_repo_head_hexsha": "22cdaa84b7215d7925bd4ad1f06d7d5af4bbf819", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Stats.hs", "max_forks_repo_name": "anthony-khong/montecarlo", "max_forks_repo_head_hexsha": "22cdaa84b7215d7925bd4ad1f06d7d5af4bbf819", "max_forks_repo_licenses": ["BSD-3-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.4693877551, "max_line_length": 84, "alphanum_fraction": 0.6656191075, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6841074519429383}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -fno-warn-missing-methods #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module : Diagrams.TwoD.Apollonian\n-- Copyright : (c) 2011, 2016 Brent Yorgey\n-- License : BSD-style (see LICENSE)\n-- Maintainer : byorgey@cis.upenn.edu\n--\n-- Generation of Apollonian gaskets. Any three mutually tangent\n-- circles uniquely determine exactly two others which are mutually\n-- tangent to all three. This process can be repeated, generating a\n-- fractal circle packing.\n--\n-- See J. Lagarias, C. Mallows, and A. Wilks, \\\"Beyond the Descartes\n-- circle theorem\\\", /Amer. Math. Monthly/ 109 (2002), 338--361.\n-- .\n--\n-- A few examples:\n--\n-- > import Diagrams.TwoD.Apollonian\n-- > apollonian1 = apollonianGasket 0.01 2 2 2\n--\n-- <>\n--\n-- > import Diagrams.TwoD.Apollonian\n-- > apollonian2 = apollonianGasket 0.01 2 3 3\n--\n-- <>\n--\n-- > import Diagrams.TwoD.Apollonian\n-- > apollonian3 = apollonianGasket 0.01 2 4 7\n--\n-- <>\n--\n-----------------------------------------------------------------------------\n\nmodule Diagrams.TwoD.Apollonian\n ( -- * Circles\n\n Circle(..), mkCircle, center, radius\n\n -- * Descartes' Theorem\n , descartes, other, initialConfig\n\n -- * Apollonian gasket generation\n\n , apollonian\n\n -- ** Kissing sets\n\n , KissingSet(..), kissingSets, flipSelected, selectOthers\n\n -- ** Apollonian trees\n\n , apollonianTrees, apollonianTree\n\n -- * Diagram generation\n\n , drawCircle\n , drawGasket\n , apollonianGasket\n\n ) where\n\nimport Data.Complex\nimport qualified Data.Foldable as F\nimport Data.Maybe (catMaybes)\nimport Data.Tree\n\nimport Diagrams.Prelude hiding (center, radius)\n\nimport Control.Arrow (second, (&&&))\n\n------------------------------------------------------------\n-- Circles\n------------------------------------------------------------\n\n-- | Representation for circles that lets us quickly compute an\n-- Apollonian gasket.\ndata Circle n = Circle\n { bend :: n\n -- ^ The bend is the reciprocal of signed\n -- radius: a negative radius means the\n -- outside and inside of the circle are\n -- switched. The bends of any four mutually\n -- tangent circles satisfy Descartes'\n -- Theorem.\n , cb :: Complex n\n -- ^ /Product/ of bend and center represented\n -- as a complex number. Amazingly, these\n -- products also satisfy the equation of\n -- Descartes' Theorem.\n }\n deriving (Eq, Show)\n\n-- | Create a @Circle@ given a signed radius and a location for its center.\nmkCircle :: Fractional n =>\n n -- ^ signed radius\n -> P2 n -- ^ center\n -> Circle n\nmkCircle r (unp2 -> (x,y)) = Circle (1/r) (b*x :+ b*y)\n where b = 1/r\n\n-- | Get the center of a circle.\ncenter :: Fractional n => Circle n -> P2 n\ncenter (Circle b (cbx :+ cby)) = p2 (cbx / b, cby / b)\n\n-- | Get the (unsigned) radius of a circle.\nradius :: Fractional n => Circle n -> n\nradius = abs . recip . bend\n\nliftF :: RealFloat n => (forall a. Floating a => a -> a) -> Circle n -> Circle n\nliftF f (Circle b c) = Circle (f b) (f c)\n\nliftF2 :: RealFloat n => (forall a. Floating a => a -> a -> a) ->\n Circle n -> Circle n -> Circle n\nliftF2 f (Circle b1 cb1) (Circle b2 cb2) = Circle (f b1 b2) (f cb1 cb2)\n\ninstance RealFloat n => Num (Circle n) where\n (+) = liftF2 (+)\n (-) = liftF2 (-)\n (*) = liftF2 (*)\n negate = liftF negate\n abs = liftF abs\n fromInteger n = Circle (fromInteger n) (fromInteger n)\n\ninstance RealFloat n => Fractional (Circle n) where\n (/) = liftF2 (/)\n recip = liftF recip\n\n-- | The @Num@, @Fractional@, and @Floating@ instances for @Circle@\n-- (all simply lifted elementwise over @Circle@'s fields) let us use\n-- Descartes' Theorem directly on circles.\ninstance RealFloat n => Floating (Circle n) where\n sqrt = liftF sqrt\n\n------------------------------------------------------------\n-- Descartes' Theorem\n------------------------------------------------------------\n\n-- XXX generalize these for higher dimensions?\n\n-- | Descartes' Theorem states that if @b1@, @b2@, @b3@ and @b4@ are\n-- the bends of four mutually tangent circles, then\n--\n-- @\n-- b1^2 + b2^2 + b3^2 + b4^2 = 1/2 * (b1 + b2 + b3 + b4)^2.\n-- @\n--\n-- Surprisingly, if we replace each of the @bi@ with the /product/\n-- of @bi@ and the center of the corresponding circle (represented\n-- as a complex number), the equation continues to hold! (See the\n-- paper referenced at the top of the module.)\n--\n-- @descartes [b1,b2,b3]@ solves for @b4@, returning both solutions.\n-- Notably, @descartes@ works for any instance of @Floating@, which\n-- includes both @Double@ (for bends), @Complex Double@ (for\n-- bend/center product), and @Circle@ (for both at once).\ndescartes :: Floating n => [n] -> [n]\ndescartes [b1,b2,b3] = [r + s, -r + s]\n where r = 2 * sqrt (b1*b2 + b1*b3 + b2*b3)\n s = b1+b2+b3\ndescartes _ = error \"descartes must be called on a list of length 3\"\n\n-- | If we have /four/ mutually tangent circles we can choose one of\n-- them to replace; the remaining three determine exactly one other\n-- circle which is mutually tangent. However, in this situation\n-- there is no need to apply 'descartes' again, since the two\n-- solutions @b4@ and @b4'@ satisfy\n--\n-- @\n-- b4 + b4' = 2 * (b1 + b2 + b3)\n-- @\n--\n-- Hence, to replace @b4@ with its dual, we need only sum the other\n-- three, multiply by two, and subtract @b4@. Again, this works for\n-- bends as well as bend/center products.\nother :: Num n => [n] -> n -> n\nother xs x = 2 * sum xs - x\n\n-- | Generate an initial configuration of four mutually tangent\n-- circles, given just the signed bends of three of them.\ninitialConfig :: RealFloat n => n -> n -> n -> [Circle n]\ninitialConfig b1 b2 b3 = cs ++ [c4]\n where cs = [Circle b1 0, Circle b2 ((b2/b1 + 1) :+ 0), Circle b3 cb3]\n a = 1/b1 + 1/b2\n b = 1/b1 + 1/b3\n c = 1/b2 + 1/b3\n x = (b*b + a*a - c*c)/(2*a)\n y = sqrt (b*b - x*x)\n cb3 = b3*x :+ b3*y\n [c4,_] = descartes cs\n\n------------------------------------------------------------\n-- Gasket generation\n------------------------------------------------------------\n\nselect :: [a] -> [(a, [a])]\nselect [] = []\nselect (x:xs) = (x,xs) : (map . second) (x:) (select xs)\n\n-- | The basic idea of a kissing set is supposed to represent a set of\n-- four mutually tangent circles with one selected, though in fact\n-- it is more general than that: it represents any set of objects\n-- with one distinguished object selected.\ndata KissingSet n = KS { selected :: n, others :: [n] }\n deriving (Show)\n\n-- | Generate all possible kissing sets from a set of objects by\n-- selecting each object in turn.\nkissingSets :: [n] -> [KissingSet n]\nkissingSets = map (uncurry KS) . select\n\n-- | \\\"Flip\\\" the selected circle to the 'other' circle mutually tangent\n-- to the other three. The new circle remains selected.\nflipSelected :: Num n => KissingSet n -> KissingSet n\nflipSelected (KS c cs) = KS (other cs c) cs\n\n-- | Make the selected circle unselected, and select each of the\n-- others, generating a new kissing set for each.\nselectOthers :: KissingSet n -> [KissingSet n]\nselectOthers (KS c cs) = [ KS c' (c:cs') | (c',cs') <- select cs ]\n\n-- | Given a threshold radius and a list of /four/ mutually tangent\n-- circles, generate the Apollonian gasket containing those circles.\n-- Stop the recursion when encountering a circle with an (unsigned)\n-- radius smaller than the threshold.\napollonian :: RealFloat n => n -> [Circle n] -> [Circle n]\napollonian thresh cs\n = (cs++)\n . concat\n . map (maybe [] flatten . prune p . fmap selected)\n . apollonianTrees\n $ cs\n where\n p c = radius c >= thresh\n\n-- | Given a set of /four/ mutually tangent circles, generate the\n-- infinite Apollonian tree rooted at the given set, represented as\n-- a list of four subtrees. Each node in the tree is a kissing set\n-- with one circle selected which has just been flipped. The three\n-- children of a node represent the kissing sets obtained by\n-- selecting each of the other three circles and flipping them. The\n-- initial roots of the four trees are chosen by selecting and\n-- flipping each of the circles in the starting set. This\n-- representation has the property that each circle in the\n-- Apollonian gasket is the selected circle in exactly one node\n-- (except that the initial four circles never appear as the\n-- selected circle in any node).\napollonianTrees :: RealFloat n => [Circle n] -> [Tree (KissingSet (Circle n))]\napollonianTrees = map (apollonianTree . flipSelected) . kissingSets\n\n-- | Generate a single Apollonian tree from a root kissing set. See\n-- the documentation for 'apollonianTrees' for an explanation.\napollonianTree :: RealFloat n => KissingSet (Circle n) -> Tree (KissingSet (Circle n))\napollonianTree = unfoldTree (id &&& (map flipSelected . selectOthers))\n\n-- | Prune a tree at the shallowest points where the predicate is not\n-- satisfied.\nprune :: (a -> Bool) -> Tree a -> Maybe (Tree a)\nprune p (Node a ts)\n | not (p a) = Nothing\n | otherwise = Just $ Node a (catMaybes (map (prune p) ts))\n\n------------------------------------------------------------\n-- Diagram generation\n------------------------------------------------------------\n\n-- | Draw a circle.\ndrawCircle :: (Renderable (Path V2 n) b, TypeableFloat n) =>\n Circle n -> QDiagram b V2 n Any\ndrawCircle c = circle (radius c) # moveTo (center c)\n # fcA transparent\n\n-- | Draw a generated gasket, using a line width 0.003 times the\n-- radius of the largest circle.\ndrawGasket :: (Renderable (Path V2 n) b, TypeableFloat n) =>\n [Circle n] -> QDiagram b V2 n Any\ndrawGasket cs = F.foldMap drawCircle cs\n\n-- | Draw an Apollonian gasket: the first argument is the threshold;\n-- the recursion will stop upon reaching circles with radii less than\n-- it. The next three arguments are bends of three circles.\napollonianGasket :: (Renderable (Path V2 n) b, TypeableFloat n)\n => n -> n -> n -> n -> QDiagram b V2 n Any\napollonianGasket thresh b1 b2 b3 = drawGasket . apollonian thresh $ (initialConfig b1 b2 b3)\n\n------------------------------------------------------------\n-- Some notes on floating-point error\n-- (only for the intrepid)\n------------------------------------------------------------\n{-\n\n-- code from Gerald Gutierrez, personal communication\n\nmodule Main where\n\nimport Data.Complex\nimport Diagrams.Backend.SVG.CmdLine\nimport Diagrams.Prelude\n\n-- ------^---------^---------^---------^---------^---------^---------^--------\n\ndata Circle = Circle Double (Complex Double) deriving (Show)\n\ndescartes a b c\n = (s + r, s - r)\n where\n s = a + b + c\n r = 2 * sqrt ((a * b) + (b * c) + (c * a))\n\ndescartesDual a b c d\n = 2 * (a + b + c) - d\n\nsoddies (Circle k1 b1) (Circle k2 b2) (Circle k3 b3)\n = ( Circle k4 b4\n , Circle k5 b5 )\n where\n (k4, k5) = descartes k1 k2 k3\n (b4, b5) = descartes b1 b2 b3\n\nsoddiesDual (Circle k1 b1) (Circle k2 b2) (Circle k3 b3) (Circle k4 b4)\n = Circle (descartesDual k1 k2 k3 k4) (descartesDual b1 b2 b3 b4)\n\nmutuallyTangentCirclesFromTriangle z1 z2 z3\n = ( Circle k1 (z1 * (k1 :+ 0))\n , Circle k2 (z2 * (k2 :+ 0))\n , Circle k3 (z3 * (k3 :+ 0)) )\n where\n a = magnitude (z2 - z3)\n b = magnitude (z3 - z1)\n c = magnitude (z1 - z2)\n s = (a + b + c) / 2\n k1 = 1 / (s - a)\n k2 = 1 / (s - b)\n k3 = 1 / (s - c)\n\nmain :: IO ()\nmain = mainWith picture\n\npic = mainWith picture\n\nmkCircle :: Circle -> Diagram B\nmkCircle (Circle k b)\n = circle (1 / k) # moveTo (p2 (realPart z, imagPart z))\n where\n z = b / (k :+ 0)\n\npicture :: Diagram B\npicture\n = mkCircle c1 <> mkCircle c2 <> mkCircle c3 <> mkCircle c4 <> mkCircle c5\n where\n (c1, c2, c3) = mutuallyTangentCirclesFromTriangle z1 z2 z3\n (c4, c5) = soddies c1 c2 c3\n\n -- z1 = 0 :+ 0\n -- z2 = 3 :+ 0\n -- z3 = 0 :+ 4\n\n -- z1 = (-0.546) :+ (-0.755)\n -- z2 = ( 0.341) :+ (-0.755)\n -- z3 = (-0.250) :+ ( 0.428)\n\nofsBad = 0.15397 -- doesn't work\nofsGood = 0.15398 -- works\n\nofs = ofsGood\n\nz1 = ofs + ((-0.546) :+ (-0.755))\nz2 = ofs + (( 0.341) :+ (-0.755))\nz3 = ofs + ((-0.250) :+ ( 0.428))\n\n\n------------------------------------------------------------\n\nEmail to Gerald Gutierrez, 30 Sep 2016:\n\nI got a chance to sit down and think hard about your code today, and\nI think I have figured out what the problem is.\n\nIf you look at the outputs of 'soddies c1 c2 c3' using the two\ndifferent values for 'ofs', you will see that they are *almost* the\nsame, except that the complex numbers have been switched (though in\nfact their real components are almost the same so you only notice the\ndifference in the imaginary components). This clearly causes\nincorrect results since the y-coordinates represented by the imaginary\ncomponents are now getting scaled by different bend values. So the\nresulting circles are of the right size and have (close to) the\ncorrect x-coordinates, but their y-coordinates are wrong.\n\nThe problem is that in the 'soddies' function, you make independent\ncalls to 'descartes k1 k2 k3' (to solve for the bends) and 'descartes\nb1 b2 b3' (to solve for the bend-center products), and then *assume*\nthat they return their solutions *in the same order*, so that you can\nmatch up the first values to make one circle and the second values to\nmake another circle. I would guess that this is *usually* true but\napparently not when certain values are hovering right around a branch\ncut of sqrt, or something like that.\n\nI think my code in Diagrams.TwoD.Apollonian suffers from the same\nproblem. Ultimately I think it is due to the inherent inaccuracy of\nfloating-point numbers; there is nothing wrong with the formula\nitself. It would be nice to figure out how to correct for this, but I\nam not sure how off the top of my head. The interesting thing is that\nswitching the bend-center products does not seem to violate the\ngeneralized Descartes' Theorem at all --- so it would seem that it\ndoes not actually completely characterize mutually tangent circles,\nthat is, there exist sets of circles satisfying the theorem which are\nnot in fact mutually tangent.\n\n-}\n", "meta": {"hexsha": "301c8fa6073cc54b1760de51c7c2f084d9f1860c", "size": 14924, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Diagrams/TwoD/Apollonian.hs", "max_stars_repo_name": "phadej/diagrams-contrib", "max_stars_repo_head_hexsha": "a149d4b18b6e22178d1169bf8cc24283e477d07b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-04-30T07:37:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T16:10:52.000Z", "max_issues_repo_path": "src/Diagrams/TwoD/Apollonian.hs", "max_issues_repo_name": "phadej/diagrams-contrib", "max_issues_repo_head_hexsha": "a149d4b18b6e22178d1169bf8cc24283e477d07b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2015-02-24T17:49:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:58:45.000Z", "max_forks_repo_path": "src/Diagrams/TwoD/Apollonian.hs", "max_forks_repo_name": "phadej/diagrams-contrib", "max_forks_repo_head_hexsha": "a149d4b18b6e22178d1169bf8cc24283e477d07b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2015-01-08T19:24:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T13:52:54.000Z", "avg_line_length": 35.7889688249, "max_line_length": 92, "alphanum_fraction": 0.611163227, "num_tokens": 4284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6834489000259937}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule SVM\n ( multiplyByItself\n , testmatrix\n , testvector\n , replicateVector\n , replicateVectorSquared\n , makeLabelAgreementMatrix\n , makeQuadraticMatrix\n , testmatrixsize\n , alphasQuadProg\n , trainPLAandSVM\n , countSV\n ) where\n\nimport LinearRegression (createMatrixX,\n createRandomPoints,\n createVectorY,\n makeTargetFunction, y)\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra.HMatrix as HMatrix\nimport Numeric.Minimization.QuadProgPP\nimport PLA\n\n----------------------------------------------------\n-- Solutions to Homework 7 on SVM\n----------------------------------------------------\n-- | a test matrix - not part of homework\ntestmatrix :: Matrix R\ntestmatrix = matrix 2 [1, 1, 1, -1, -1, -1, 3, 4, 5, 6]\n\ntestmatrixsize = size testmatrix\n\n-- | a test vector - not part of homework\ntestvector :: Vector R\ntestvector = vector [-1, 1, 1, -1, 1]\n\n-- | create a matrix where every entry x_n_m is the dot product of the nth vector with the mth vector\nmultiplyByItself :: Matrix R -> Matrix R\nmultiplyByItself matrixA = matrixA HMatrix.<> (tr matrixA)\n\n-- | make a matrix where every entry corresponds to the product of the labels of the corresponding data - it will be 1 if they agree and -1 otherwise\nmakeLabelAgreementMatrix :: Vector R -> Matrix R\nmakeLabelAgreementMatrix labelvector =\n diag labelvector HMatrix.<> replicateVectorSquared labelvector\n\n-- | make a matrix form a vector by repeating the vector n times and arranging into n rows, each corresponding to the vector\nreplicateVector :: Int -> Vector R -> Matrix R\nreplicateVector n v = fromRows $ replicate n v\n\n-- | make a squared matrix from a vector, such that each rows corresponds to the vector\nreplicateVectorSquared :: Vector R -> Matrix R\nreplicateVectorSquared v = replicateVector (size v) v\n\n-- | makes the matrix to pass to quadratix programming\nmakeQuadraticMatrix :: Matrix R -> Vector R -> Matrix R\nmakeQuadraticMatrix dataMatrix labelVector =\n multiplyByItself dataMatrix * makeLabelAgreementMatrix labelVector\n\nmakeQuadraticMatrix' :: Matrix R -> Vector R -> Matrix R\nmakeQuadraticMatrix' dataMatrix labelVector = quadMatrix + smallValtoDiag\n where\n quadMatrix = makeQuadraticMatrix dataMatrix labelVector\n smallValtoDiag = diag $ konst 0.00000000001 (size labelVector)\n\n-- | solves quadratic Programming on the input data matrix and label Vector\nalphasQuadProg ::\n Matrix R -> Vector R -> Either QuadProgPPError (Vector R, Double)\nalphasQuadProg dataMatrix labelVector =\n solveQuadProg\n (matrixA, vectorB)\n (Just (labelVecMatrix, zeros))\n (Just (idMatrix, zeros))\n where\n matrixA = makeQuadraticMatrix' dataMatrix labelVector\n vectorB = konst (-1) (size labelVector)\n labelVecMatrix = diag labelVector\n idMatrix = ident (size labelVector)\n zeros = konst 0 (size labelVector)\n\n-- | Creates the data matrix from a list of data points\ncreateDataMatrix :: [(R, R)] -> Matrix R\ncreateDataMatrix listOfPoints = matrix 2 listOfNumbers\n where\n listOfNumbers = concat [[a, b] | (a, b) <- listOfPoints]\n\nsetSmallTo0 x\n | x < (10 ** (-4)) = 0\n | otherwise = x\n\ncountSV vector = length . filter (/= 0) $ toList vector\n\n-- | trains a perceptron and SVM\ntrainPLAandSVM :: Int -> IO ()\ntrainPLAandSVM n\n --making target function, training and testing points\n -----------------------------------------------------\n = do\n target <- makeTargetFunction\n trainpoints <- createRandomPoints n\n testpoints <- createRandomPoints 1000\n let trainX = createDataMatrix trainpoints\n let trainY = createVectorY (y target) trainpoints\n let testX = createDataMatrix testpoints\n let testY = createVectorY (y target) testpoints\n --Perceptron\n ---------------------------------\n let initialWeights = (0, 0, 0)\n (finalWeights, epochs) <-\n trainPLAWithInitial initialWeights trainpoints target\n let misclassifiedTestPoints =\n length $ filter (isMisclassified target finalWeights) testpoints\n let prob = fromIntegral misclassifiedTestPoints / 1000\n --SVM\n --------------------------\n let quadmatrix = makeQuadraticMatrix trainX trainY\n let labelVecMatrix = asColumn trainY\n let alphas = alphasQuadProg trainX trainY\n let alphasModified = fmap (cmap setSmallTo0 . fst) alphas\n let numSVs = fmap countSV alphasModified\n --Printing the output\n ---------------------------\n putStrLn \"Perceptron:\"\n putStrLn \"-------------------------\"\n putStr \"Weights: \"\n print finalWeights\n putStr \"Epochs: \"\n print epochs\n putStr \"Probability f /= g: \"\n print prob\n putStrLn \"Support Vector Machine:\"\n putStrLn \"-------------------------\"\n putStr \"Alphas:\"\n print alphas\n putStr \"Alphas very small set ot 0:\"\n print alphasModified\n putStr \"number of SVs:\"\n print numSVs\n", "meta": {"hexsha": "1ac0426632ac875ad724c4c4fc5f03ae4a7660a5", "size": 5020, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/hw7/SVM.hs", "max_stars_repo_name": "AR2202/LearningFromData", "max_stars_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T06:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T06:07:24.000Z", "max_issues_repo_path": "src/hw7/SVM.hs", "max_issues_repo_name": "AR2202/LearningFromData", "max_issues_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hw7/SVM.hs", "max_forks_repo_name": "AR2202/LearningFromData", "max_forks_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6028368794, "max_line_length": 149, "alphanum_fraction": 0.6651394422, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912849, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6831572296999939}} {"text": "import Data.Complex\r\n\r\nmain :: IO ()\r\nmain = do let res = dft (map (\\x -> x :+ 0) [1..10])\r\n \t putStrLn $ show res\r\n\r\ndft :: RealFloat a => [Complex a] -> [Complex a]\r\ndft x = map (\\(_, k) -> singleDFT k idxList) idxList\r\n where idxList = zip x [0..]\r\n\r\nsingleDFT :: RealFloat a => Int -> [(Complex a, Int)] -> Complex a\r\nsingleDFT k x = sum $ map (\\(e, n) -> (e *) $ fCoeff k n $ length x) $ x\r\n\r\nfCoeff :: RealFloat a => Int -> Int -> Int -> Complex a\r\nfCoeff k n n_tot = exp (0.0 :+ ((-2.0) * pi * (fromIntegral $ k * n) / (fromIntegral n_tot)))\r\n", "meta": {"hexsha": "72d0bf49b63a9eaca9e411e6dc4d146bbadf9bae", "size": 558, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Snippets/Haskell/DFT_2.hs", "max_stars_repo_name": "fredmorcos/attic", "max_stars_repo_head_hexsha": "0da3b94aa525df59ddc977c32cb71c243ffd0dbd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-24T09:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T20:52:17.000Z", "max_issues_repo_path": "Snippets/Haskell/DFT_2.hs", "max_issues_repo_name": "fredmorcos/attic", "max_issues_repo_head_hexsha": "0da3b94aa525df59ddc977c32cb71c243ffd0dbd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-02-29T01:59:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T10:25:40.000Z", "max_forks_repo_path": "Snippets/Haskell/DFT_2.hs", "max_forks_repo_name": "fredmorcos/attic", "max_forks_repo_head_hexsha": "0da3b94aa525df59ddc977c32cb71c243ffd0dbd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-22T14:41:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-22T14:41:21.000Z", "avg_line_length": 34.875, "max_line_length": 94, "alphanum_fraction": 0.5448028674, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6826432790418363}} {"text": "\n-- | This module provides generic functionality to deal with ensembles in\n-- statistical mechanics.\n\nmodule StatisticalMechanics.Ensemble where\n\nimport Numeric.Log\n\nimport Statistics.Probability\n\n\n\n-- | The state probability functions provide conversion from some types @a@\n-- into non-normalized probabilities. For \"real\" applications, using the\n-- @logProbability@ function is preferred. This functions allows for easy\n-- abstraction when types @a@ are given as fractions of some actual value (say:\n-- deka-cal), or are discretized.\n--\n-- The returned values are not normalized, because we do not now the total\n-- evidence @Z@ until integration over all states has happened -- which is not\n-- feasible in a number of problems.\n--\n-- TODO replace @()@ with temperature and results with non-normalized @P@ or\n-- @LogP@, depending. At some point we want to have type-level physical\n-- quantities, hence the need for the second type.\n\nclass StateProbability a where\n -- | Given a temperature and a state \"energy\", return the corresponding\n -- non-normalized probability.\n stateProbability\n ∷ Double\n -- ^ this is @k*T@\n → a\n -- ^ the energy (or discretized energy)\n → Probability NotNormalized Double\n -- ^ probability of being in state @a@, but only proportional up to @1/Z@.\n stateLogProbability\n ∷ Double\n -- ^ this is @1/(k * T)@\n → a\n -- ^ the energy (or discretized energy)\n → Log (Probability NotNormalized Double)\n -- ^ resulting probability\n\ninstance StateProbability Double where\n stateProbability kT x = Prob . exp . negate $ x/kT\n {-# Inline stateProbability #-}\n --stateLogProbability kT x = Exp . log . Prob . exp . negate $ x/kT\n stateLogProbability kT x = Exp . Prob . negate $ x/kT\n {-# Inline stateLogProbability #-}\n\n", "meta": {"hexsha": "7a68dc5ba5f5aaecba8e5a9eeddc1291312b306e", "size": 1780, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "StatisticalMechanics/Ensemble.hs", "max_stars_repo_name": "choener/SciBaseTypes", "max_stars_repo_head_hexsha": "15e158339881dbdc9a21a5e386c24537f87ea5fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-12-12T18:13:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T13:30:44.000Z", "max_issues_repo_path": "StatisticalMechanics/Ensemble.hs", "max_issues_repo_name": "choener/SciBaseTypes", "max_issues_repo_head_hexsha": "15e158339881dbdc9a21a5e386c24537f87ea5fd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StatisticalMechanics/Ensemble.hs", "max_forks_repo_name": "choener/SciBaseTypes", "max_forks_repo_head_hexsha": "15e158339881dbdc9a21a5e386c24537f87ea5fd", "max_forks_repo_licenses": ["BSD-3-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.2307692308, "max_line_length": 79, "alphanum_fraction": 0.7134831461, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6817296794857213}} {"text": "import Data.Array.CArray\nimport Data.Complex\nimport Math.FFT (dft, idft) -- Binding to fftw\n\ntype Vector = CArray Int (Complex Double)\n\ncalculateEnergy :: Double -> Vector -> Vector -> Vector -> Double\ncalculateEnergy dx kin pot wfc = (* dx) . sum . map realPart $ elems total\n where\n total = liftArray2 (+) kineticE potentialE\n potentialE = wfcConj .* pot .* wfc\n kineticE = wfcConj .* idft (kin .* dft wfc)\n wfcConj = liftArray conjugate wfc\n a .* b = liftArray2 (*) a b\n", "meta": {"hexsha": "a024fd139ef4969eb92786bb136cf49580fc5091", "size": 489, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "contents/quantum_systems/code/haskell/Energy.hs", "max_stars_repo_name": "atocil/algorithm-archive", "max_stars_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-06-30T08:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T17:24:30.000Z", "max_issues_repo_path": "contents/quantum_systems/code/haskell/Energy.hs", "max_issues_repo_name": "atocil/algorithm-archive", "max_issues_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-03T20:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-03T20:52:20.000Z", "max_forks_repo_path": "contents/quantum_systems/code/haskell/Energy.hs", "max_forks_repo_name": "atocil/algorithm-archive", "max_forks_repo_head_hexsha": "2eb30cb103508c9efb91621564bd3114eb49d3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-04-28T12:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-17T20:38:46.000Z", "avg_line_length": 32.6, "max_line_length": 74, "alphanum_fraction": 0.6768916155, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6815996996864433}} {"text": "module Hw5 \n (Signal,\n Vec(..),\n rd,\n absolute,\n range,\n dft,\n idft,\n realV,\n low_pass',\n low_pass,\n fft,\n ifft,\n makeNoise)\n where\n\nimport Data.Complex\nimport Debug.Trace\nimport GHC.Base (liftA2)\nimport System.Random\n-- import Control.Monad.Reader\n\n-- {-# LANGUAGE KindSignatures #-}\n-- {-# LANGUAGE MultiParamTypeClasses #-}\n\nnewtype Vec a = Vec {runVec :: [a]}\nnewtype Reader r a = Reader { runReader :: r -> a }\ntype Signal = Vec (Complex Double)\n\nimagV :: Num a => Vec a -> Vec (Complex a)\nrealV :: Num a => Vec a -> Vec (Complex a)\nrange :: Double -> Double -> Double -> [Double]\nabsolute :: Vec (Complex Double) -> Vec Double\nrd :: Int -> Vec Double -> Vec Double\ntwiddle :: Double -> Double -> Signal\ndft :: Signal -> Signal\nidft :: Signal -> Signal\nmask :: Int -> Int -> Signal\nfft :: Signal -> Signal\nifft :: Signal -> Signal\nmakeNoise :: Random a => Int -> Int -> a -> a -> Vec a\n\nmakeNoise seed n low high =\n let x = mkStdGen seed\n genNum l h = randomR (l, h)\n genList 1 l h g = [c] where (c,y) = genNum l h g\n genList n l h g = c : genList (n-1) l h y where (c,y) = genNum l h g\n in\n Vec $ genList n low high x\n\n\nlength' (Vec x) = length x\n\nrd n = fmap (\\x -> fromIntegral (round $ c * x) / c)\n where c = 10^n\n\nabsolute = fmap (\\(r:+i) -> sqrt(r*r + i*i))\n\nrange from to count = map (\\x -> from + x * step) [0..count-1]\n where step = (to - from)/count\n\nimagV (Vec a) = Vec $ map (0:+) a\nrealV (Vec a) = Vec $ map (:+0) a\n\ninstance Show a => Show (Vec a) where\n show (Vec lst) = \"[\" ++ drop 1 lst' ++ \"]\" \n where \n lst' = mconcat $ map (\\x -> \" \" ++ show x) lst\n\ninstance Functor Vec where\n fmap f (Vec x) = Vec $ map f x\n\ninstance Applicative Vec where\n pure = Vec . repeat\n (Vec f) <*> (Vec x) = Vec $ zipWith ($) f x\n liftA2 f (Vec x) (Vec y) = Vec $ zipWith f x y\n\ninstance Foldable Vec where\n foldr f c (Vec a) = Prelude.foldr f c a\n\ninstance Semigroup (Vec a) where\n Vec a <> Vec b = Vec $ a ++ b\n\ninstance Monoid (Vec a) where\n mempty = Vec []\n \ninstance Num a => Num (Vec a) where\n (+) = liftA2 (+)\n (-) = liftA2 (-)\n (*) = liftA2 (*)\n negate = fmap negate\n abs = fmap abs\n signum = fmap signum\n fromInteger x = pure $ fromInteger x\n\ninstance (Floating a) => Fractional (Vec a) where\n (/) = liftA2 (/)\n fromRational x = pure $ fromRational x\n\ninstance (Floating a) => Floating (Vec a) where\n pi = pure pi\n exp = fmap exp\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\nmask freq n = realV $ Vec $ one ++ zero ++ one where \n one = (take freq $ repeat 1)\n zero = (take (n-freq*2) $ repeat 0)\n\n\nlow_pass' :: Int -> Signal -> Signal\n\nlow_pass' v sig =\n let\n m = mask v $ length sig\n in idft $ m * dft sig\n\ntwiddle n k = \n let a = [0.. (n - 1)]\n f x = exp (0:+ x * (-2*pi*k / n))\n in Vec $ fmap f a\n\ndft x = \n let bigN = fromIntegral $ length x -- length of x\n n = Vec [0 .. bigN-1]\n f k = sum $ x * twiddle bigN k\n in fmap f n\n\nidft x = \n let bigN = fromIntegral $ length x -- length of x\n cX = fmap conjugate x\n n = Vec [0 .. bigN-1]\n diC = (1.0 / bigN) :+ 0\n f k = sum $ cX * twiddle bigN k\n in conj diC $ fmap f n\n\nconj :: Complex Double -> Signal -> Signal\nconj b (Vec a) = fmap (\\y -> b * conjugate y) (Vec a)\n\ntwidd n k = exp( imagV $ k * pure (-2 * pi / fromIntegral n) )\ntwiddI n k = exp( imagV $ k * pure (2 * pi / fromIntegral n) )\n\ntrace_fft m x = trace (m ++ \": \" ++ (show $ rd 2 $ absolute x)) x -- debugging helper to print fft results\nfft x \n | n <= 16 = dft x\n | n <= 1 = x\n | otherwise = \n let (even, odd) = split $ runVec x \n (e, o) = (fft $ Vec even, fft $ Vec odd) \n k = Vec [0..]\n p = twidd n k\n in\n (e + p * o) <> (e - p * o)\n \n where \n n = length x\n split [] = ([], [])\n split [a] = ([a], [])\n split (a:b:c) = (a:x, b:y)\n where (x,y) = split c\n\nifft x \n | n <= 16 = idft x\n | n <= 1 = x\n | otherwise = \n let (even, odd) = split $ runVec x \n (e, o) = (fft $ Vec even, fft $ Vec odd) \n -- k = Vec [0..]\n bigN = fromIntegral n\n cE = fmap conjugate e\n cO = fmap conjugate o\n diC = (-1.0 / bigN) :+ 0\n p = twiddI n $ Vec [0..]\n in\n conj diC (e + p * o) <> conj diC (e - p * o)\n\n where \n n = length x\n split [] = ([], [])\n split [a] = ([a], [])\n split (a:b:c) = (a:x, b:y)\n where (x,y) = split c\n\n\nlow_pass :: Int -> Signal -> Signal\n\nlow_pass v sig =\n let\n m = mask v $ length sig\n in ifft $ m * fft sig", "meta": {"hexsha": "945b068ef056b23fc764e8167bc2c1e3cf75074c", "size": 4963, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Hw5.hs", "max_stars_repo_name": "NikolaPeevski/Haskell-stuff", "max_stars_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Hw5.hs", "max_issues_repo_name": "NikolaPeevski/Haskell-stuff", "max_issues_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Hw5.hs", "max_forks_repo_name": "NikolaPeevski/Haskell-stuff", "max_forks_repo_head_hexsha": "b74684bfd7df53a53f11dd4a3c6f3475f2d9bcf8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9396984925, "max_line_length": 106, "alphanum_fraction": 0.5125931896, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6812386844837572}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Finance.Hqfl.Pricer.Black\n-- Copyright : (C) 2016 Mika'il Khan\n-- License : (see the file LICENSE)\n-- Maintainer : Mika'il Khan \n-- Stability : stable\n-- Portability : portable\n--\n---------------------------------------------------------------------------- \n{-# LANGUAGE FlexibleInstances #-}\n\nmodule Finance.Hqfl.Pricer.Black where\n\nimport Finance.Hqfl.Instrument\nimport Statistics.Distribution.Normal\nimport Data.Random\n\nclass Black a where\n price :: a -> Double -> Double -> Double\n\ninstance Black (Option Future) where\n price (Option (Future f) m European k t) r v =\n case m of\n Call -> exp (-r * t) * (f * cdf normal d1 - k * cdf normal d2)\n Put -> exp (-r * t) * (k * cdf normal (-d2) - f * cdf normal (-d1))\n where d1 = (log (f / k) + ((v * v) / 2) * t) / (v * sqrt t)\n d2 = d1 - v * sqrt t\n normal = Normal (0 :: Double) 1\n", "meta": {"hexsha": "98849fdb66cbe079471188da4db87dc2f4079a7e", "size": 1009, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Finance/Hqfl/Pricer/Black.hs", "max_stars_repo_name": "co-category/hqfl", "max_stars_repo_head_hexsha": "398bd921089522c6c0e6d91893a75615a1f39a2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-02-19T14:03:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T12:44:03.000Z", "max_issues_repo_path": "src/Finance/Hqfl/Pricer/Black.hs", "max_issues_repo_name": "cokleisli/hqfl", "max_issues_repo_head_hexsha": "398bd921089522c6c0e6d91893a75615a1f39a2e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Finance/Hqfl/Pricer/Black.hs", "max_forks_repo_name": "cokleisli/hqfl", "max_forks_repo_head_hexsha": "398bd921089522c6c0e6d91893a75615a1f39a2e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-26T18:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T09:49:53.000Z", "avg_line_length": 33.6333333333, "max_line_length": 79, "alphanum_fraction": 0.5024777007, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774729, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6808547055103602}} {"text": "{-# language BangPatterns #-}\n{-|\nModule : Fitness\nDescription : Fitness Function for Genetic Algorithm for Poly Regression\nCopyright : (c) Fabricio Olivetti de Franca, 2021\nLicense : GPL-3\nMaintainer : fabricio.olivetti@gmail.com\nStability : experimental\nPortability : POSIX\n|-}\n\nmodule Fitness (evalFitness, decode) where\n\nimport GA\n\nimport Data.List (foldl')\nimport Data.List.Split hiding (split)\nimport Numeric.LinearAlgebra ((<\\>),(#>),(|||), sumElements, size, Matrix, Vector, fromRows, fromList)\n\n-- | Creates a fitness function \nevalFitness :: Int -- ^ number of terms\n -> [[Double]] -- ^ matrix X\n -> Vector Double -- ^ vector y\n -> Solution (Poly n) -- ^ solution to evaluate\n -> Solution (Poly n) \nevalFitness nTerms xss ys sol = \n case _fitness sol of\n Nothing -> sol{ _coeffs = Just betas, _fitness = Just f }\n _ -> sol \n where\n zss = decode xss (map _getPoly $ _chromo sol) \n betas = zss <\\> ys \n ysHat = zss #> betas \n f = mse ys ysHat\n\n-- | Decodes the polynomial into a transformed matrix \ndecode :: [[Double]] -> [(Bool, Int)] -> Matrix Double\ndecode xss chromo = fromRows (map (evalPoly chromo) xss)\n\n-- | Eval a single row from the dataset \nevalPoly :: [(Bool, Int)] -> [Double] -> Vector Double\nevalPoly chromo xs = fromList $ foldl' joinTerms [1.0] terms \n where\n nVars = length xs\n ix = cycle [0..nVars-1]\n xss = cycle xs\n terms = zip3 chromo xss ix \n\n joinTerms ts ((False,_), _, 0) = 1.0 : ts\n joinTerms ts ((False,_), _, _) = ts\n joinTerms ts ((True, k), x, 0) = x^k : ts\n joinTerms (t:ts) ((True,k), x, ix) = t * x^k : ts\n\n\n-- | Calculates the mean squared error\nmse :: Vector Double -> Vector Double -> Double\nmse ys ysHat = s / fromIntegral (size ys)\n where\n s = sumElements $ (ys - ysHat)^2\n", "meta": {"hexsha": "e755fa971ace641ec43f47333ee93ca41486951c", "size": 1889, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fitness.hs", "max_stars_repo_name": "folivetti/gapoly", "max_stars_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-06T11:25:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T11:25:13.000Z", "max_issues_repo_path": "src/Fitness.hs", "max_issues_repo_name": "folivetti/gapoly", "max_issues_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fitness.hs", "max_forks_repo_name": "folivetti/gapoly", "max_forks_repo_head_hexsha": "a0e2b727f046b1284353f56699b0459ed536155d", "max_forks_repo_licenses": ["BSD-3-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.4833333333, "max_line_length": 102, "alphanum_fraction": 0.6087877184, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6802684506113145}} {"text": "-- |\n-- Module : Southpaw.Picasso.Shapes\n-- Description : Various functions for creating mathematical shapes\n-- Copyright : (c) Jonatan H Sundqvist, year\n-- License : MIT\n-- Maintainer : Jonatan H Sundqvist\n-- Stability : experimental|stable\n-- Portability : POSIX (not sure)\n-- \n\n-- Created date year\n\n-- TODO | - \n-- - \n\n-- SPEC | -\n-- -\n\n\n\n---------------------------------------------------------------------------------------------------\n-- API\n---------------------------------------------------------------------------------------------------\nmodule Southpaw.Picasso.Shapes where\n\n\n\n---------------------------------------------------------------------------------------------------\n-- We'll need these\n---------------------------------------------------------------------------------------------------\nimport Data.Complex\n\nimport Southpaw.Math.Constants\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Function\n---------------------------------------------------------------------------------------------------\n-- Geometry ---------------------------------------------------------------------------------------\n-- |\n-- TODO: Start angle\n-- TODO: Invalid arguments (eg. sides < 3) (use Maybe?)\n-- TODO: Make polymorphic\n-- TODO: Move to geometry section\n-- polygon :: (Floating f, RealFloat f) => Int -> f -> Complex f -> [Complex f]\npolygon :: Integral int => int -> Double -> Complex Double -> [Complex Double]\npolygon sides radius origin = [ let θ = arg n in origin + ((radius * cos θ):+(radius * sin θ)) | n <- [1..sides]]\n where arg n = fromIntegral n * (2*π)/fromIntegral sides\n\n\n\n-- |\n-- TODO: Simplify and expound comments\narrow :: Complex Double -> Complex Double -> Double -> Double -> Double -> [Complex Double]\narrow from to sl sw hw = [from + straight (sw/2), --\n shaftEnd + straight (sw/2), --\n shaftEnd + straight (hw/2), --\n to, --\n shaftEnd - straight (hw/2), --\n shaftEnd - straight (sw/2), --\n from - straight (sw/2)] --\n where along a b distance = (a +) . mkPolar distance . snd . polar $ b-a -- Walk distance along the from a to b\n normal a b = let (mag, arg) = polar (b-a) in mkPolar mag (arg+π/2)\n shaftEnd = along from to sl --\n straight = along (0:+0) (normal from to) -- Vector perpendicular to the centre line\n\n", "meta": {"hexsha": "55e1a81a813304b1f871aa2e48f246e0c68704a8", "size": 2546, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Southpaw/Picasso/Shapes.hs", "max_stars_repo_name": "SwiftsNamesake/Southpaw", "max_stars_repo_head_hexsha": "190d2d869083ac9d5e1face165c6afb9955f305b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-07-23T09:11:10.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-23T09:11:10.000Z", "max_issues_repo_path": "lib/Southpaw/Picasso/Shapes.hs", "max_issues_repo_name": "SwiftsNamesake/Southpaw", "max_issues_repo_head_hexsha": "190d2d869083ac9d5e1face165c6afb9955f305b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Southpaw/Picasso/Shapes.hs", "max_forks_repo_name": "SwiftsNamesake/Southpaw", "max_forks_repo_head_hexsha": "190d2d869083ac9d5e1face165c6afb9955f305b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4411764706, "max_line_length": 114, "alphanum_fraction": 0.4112333071, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.679925115595514}} {"text": "module Mand where\nimport Data.List.Split\nimport Data.Scientific as Scientific\nimport Data.Complex\n\ntype CS = Complex Scientific\ntype S = Scientific\n\nmakeSci :: String -> String -> Scientific\nmakeSci a b = read (a ++ \"e\" ++ b) :: Scientific\n\ncsqrt :: (Floating a, RealFloat a) => Complex a -> Complex a\ncsqrt x = (m * cos (t) :+ m * sin(t))\n where\n p = polar x\n m = sqrt $ fst p\n t = (snd p)/2\n\n--cubed_iteration c z = c + z * cos (z ** z) \ncubed_iteration :: RealFloat a => Complex a -> Complex a -> Complex a \ncubed_iteration c z = c + z * z * z\n\nnew_iteration :: RealFloat a => Complex a -> Complex a -> Complex a -> Complex a \nnew_iteration c n_z o_z = c + n_z * o_z \n\nzzcosMask :: RealFloat a => Complex a -> Bool\nzzcosMask (x :+y) = ((x > -0.95 && x < 0.1) && (y < 0.47 && y > -0.47)) || (( x <= -0.95 && x > -1.25) && (abs y < 0.42)) || (abs y < 0.2 && x <= -1.25 && x > -1.45) || (abs y < 0.4 && x >= 0.1 && x < 0.2) || (abs y < 0.17 && (x > 0.6 && x < 0.78)) || (abs y < 0.11 && x > 0.4 && x <= 0.85)\n\nzzcos_iteration :: RealFloat a => Complex a -> Complex a -> Complex a \nzzcos_iteration c z = c + z * z * (cos z)\n\nmand_iteration :: RealFloat a => Complex a -> Complex a -> Complex a \nmand_iteration c z = c + z*z \n\nmand_pow_iteration :: RealFloat a => Int -> Complex a -> Complex a -> Complex a \nmand_pow_iteration pow c z = c + z^pow\n\nmand_iterationA :: CS -> CS -> CS \nmand_iterationA (c:+b) (z:+x) = (c + z*z - x* x) :+ (b + 2*z*x) \n\ncexp :: Floating a => Complex a -> Complex a\ncexp (a :+ b) = (s * cos b :+ s * sin b)\n where \n s = exp a\n\ncsin :: RealFloat a => Complex a -> Complex a\ncsin x = ((realPart c1 + realPart c2)/2 :+ (imagPart c1 + imagPart c2)/2)\n where\n c1 = exp x\n c2 = exp $ negate x \n\ncpow :: RealFloat a => Complex a -> Complex a -> Complex a\ncpow x y = cexp $ y * log x \n \nmand :: (RealFloat a) => Either (Complex a) CS -> Int -> Int\nmand (Left c) max = general mand_iteration (Just mandSive) c max\nmand (Right c) _ = generalA mand_iterationA c\n\nsciMagnitude :: Complex Scientific -> Scientific\nsciMagnitude (a :+b) = a * a + b * b\n\nmandSive :: RealFloat a => Complex a -> Bool\nmandSive c@(x:+y) = ( let b = c + (1:+0) in realPart(b*(conjugate b)) < 0.05) ||((x < 0) && ( realPart (c * (conjugate c)) < 0.4)) ||(x < 0.25 && x >= 0 && abs y < 0.5) -- takes 16 seconds \n\n--( let b = a + (1:+0) in realPart(b*(conjugate b)) < 0.05) ||((realPart a < 0) && ( realPart (a * (conjugate a)) < 0.4)) ||(realPart a < 0.25 && realPart a >= 0 && abs (imagPart a) < 0.5) = max -1 -- takes 16 seconds \n\ngeneral :: RealFloat a => (Complex a -> Complex a -> Complex a) -> Maybe (Complex a -> Bool) -> Complex a -> Int -> Int\ngeneral g Nothing a max = count_iterations 0 (0 :+ 0) a\n where \n count_iterations n e x \n | n == max = max -1\n | realPart (x * (conjugate x)) > 4 = n\n | otherwise = count_iterations (n +1) e $ g a x\ngeneral g (Just sive) a max \n-- | ((realPart a) < 0.25) && ((realPart a) > (-0.5)) && (abs (imagPart a) < 0.5) = 255 takes 21 secods\n-- removed real check: (imagPart a == 0 && realPart a < 0.25 && realPart a > -2) || \n | sive a = max - 1 \n | otherwise = count_iterations 0 (0 :+ 0) a \n where \n count_iterations n e x \n | n == max = max -1\n | realPart (x * (conjugate x)) > 4 = n\n | otherwise = count_iterations (n +1) e $ g a x\n\ngeneralA :: (CS -> CS -> CS) -> CS -> Int\ngeneralA g a = count_iterations 0 (0 :+ 0) a \n where \n count_iterations n e x \n -- | n >= 255 = 255\n | n >= 16581375 = 16581375 \n -- if using sci\n -- | (sciMagnitude x ) > (makeSci \"4\" \"0\") = n\n -- | otherwise = count_iterations (n + 1) e $ g a $ roundComplex x \n -- if using float\n | (realPart x)^2 + (imagPart x)^2 > 4 = n\n | otherwise = count_iterations (n +1) e $ g a $ roundComplex x\n\ngeneral_list_R :: (Complex Scientific -> Complex Scientific -> Complex Scientific) -> Complex Scientific -> [Complex Scientific]\ngeneral_list_R g a = get_list 0 a (0 :+ 0)\n where\n get_list 1000 _ _ = []\n get_list n (c :+d) (e :+ f) \n | (sciMagnitude (e :+ f)) > (scientific 2 0) = []\n | otherwise = (e:+f): (get_list (n +1) (c :+d) ( g (c :+ d) (roundComplex (e :+ f)))) \n-- takes 1:13 to do 1000 iterations using roundComplex\n\ngeneral_list :: (Complex Scientific -> Complex Scientific -> Complex Scientific) -> Complex Scientific -> [Complex Scientific]\ngeneral_list g (a :+ b) = get_list 0 (a :+ b) (0 :+ 0)\n where\n get_list 40 _ _ = []\n get_list n (c :+d) (e :+ f) \n | (sciMagnitude (e :+ f)) > (makeSci \"2\" \"2\") = []\n | otherwise = (e:+f): (get_list (n +1) (c :+d) ( g (c :+ d) (e :+ f))) \n\ngeneral_list_D :: RealFloat a => (Complex a -> Complex a -> Complex a) -> Complex a -> [Complex a]\ngeneral_list_D g x = getlist 0 x (0 :+ 0)\n where\n getlist 1000 _ _ = []\n getlist n c z \n | realPart (z * conjugate z)> 4 = []\n | otherwise = z: (getlist (n +1) c (g c z)) \n\nroundSci' :: Scientific -> Scientific \nroundSci' s = makeSci (getSign:cut) getExp\n where \n num = splitOn \"e\" $ show s\n removeSign = if s < 0 then tail (num !! 0) else (num !! 0)\n getSign = if s < 0 then '-' else ' '\n getExp = if (length num) == 1 then \"0\" else num !! 1\n cut = take 100 removeSign\n\n--rounds t 20 dp\nroundSci :: Scientific -> Scientific \nroundSci s \n | d < 0 = s\n | otherwise = scientific (div (coefficient s) (10^d)) $ d + base10Exponent s\n where \n d = (digitCount $ coefficient s) - 20 \n\ndigitCount :: Integer -> Int\ndigitCount = go 1 . abs\n where\n go ds n = if n >= 10 then go (ds + 1) (n `div` 10) else ds\n--(fromInteger $ round $ f * (10^n)) / (10.0^^n)\n--Integer \nroundComplex :: Complex Scientific -> Complex Scientific\nroundComplex (a :+ b) = (roundSci' a :+ roundSci' b)\n", "meta": {"hexsha": "d67813b5379e3072be47be6e15a9c57a1de3e91f", "size": 5777, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "source/Mand.hs", "max_stars_repo_name": "AlwinHughes/fractal", "max_stars_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Mand.hs", "max_issues_repo_name": "AlwinHughes/fractal", "max_issues_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Mand.hs", "max_forks_repo_name": "AlwinHughes/fractal", "max_forks_repo_head_hexsha": "dc99dbf9444e2a5583d5c51f29417592426c5ff4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0337837838, "max_line_length": 290, "alphanum_fraction": 0.5675956379, "num_tokens": 2072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6796324797666463}} {"text": "-- file: Astro/Kepler.hs\n-- Various forms of Kepler's equation with efficient solvers\n\nmodule Astro.Kepler ( eKepler\n\t\t , gKepler\n\t\t , solveEKepler\n\t\t , solveGKepler\n\t\t , keplerPropagate\n\t\t )\n\twhere\n\nimport Astro.Stumpff\nimport Astro.Misc\n\nimport Complex\nimport Debug.Trace\nimport Numeric.GSL\nimport Numeric.LinearAlgebra\nimport Text.Printf (printf)\n\n-- Shorthands and such\ntype CD = Complex Double\ntype VD = Vector Double\n\n-- Elliptic Kepler's equation\neKepler :: (Floating a) => a -> a -> a\neKepler e ea = ea - e * sin ea\n\n-- General Variable Formulation of Kepler's eq\ngKepler :: Double -> Double -> Double -> Double -> Double -> Double\ngKepler r0 eta0 zeta0 beta x = \n\tr0 * x + eta0 * stumpff_G 2 beta x + zeta0 * stumpff_G 3 beta x\n\n-- Solve Elliptic Kepler's equation iteratively\nsolveEKepler :: (Floating a) => a -> a -> a\nsolveEKepler e m =\n\titerate 0 m m\n\twhere \n\t--iterate n ea m | trace (\"n,E: \" ++ show n ++ \" \" ++ show ea) False = undefined\n\titerate n ea m \n\t\t| ea' == ea || n > maxit = ea'\n\t\t| otherwise = iterate (n+1) ea' m\n\t\twhere\n\t\t fd = 1.0 - e * cos ea\n\t\t fdd = e * sin ea\n\t\t f = eKepler e ea - m\n\t\t ea' = ea - f / sqrt (fd^2 - f * fdd)\n\tmaxit = 10\n\n-- Solve General Kepler's eq iteratively\n--solveGKepler :: Double -> Double -> Double -> Double -> Double -> Double -> Double\nsolveGKepler r0 eta0 zeta0 beta x0 t (tol,maxIt) = \n\tif abs lastErr > tol\n\t\tthen head sol `debug` \n\t\t\t(\"solveGKepler: iter. incomp., error: \"\n\t\t\t\t++(show lastErr))\n\t\telse head sol\n\twhere\n\t\t(sol,path) = root Hybrids tol maxIt f [x0]\n\t\tlastErr = (last.last) $ toLists path\n\t\tf vx = [gKepler r0 eta0 zeta0 beta (head vx) - t]\n\n-- Solve r, v given r0, v0, gravitational parameter, delta_t\n--keplerPropagate :: VD -> VD -> Double -> (Double, Int) -> (VD,VD)\nkeplerPropagate dt (tol,maxIt) rv vv =\n\t(scale f rv + scale g vv , scale fd rv + scale gd vv)\n\twhere (r0, v0) = (norm rv, norm vv) \n\t tau = dt -- working in units where G(m_1+m_2) = 1\n\t eta0 = rv <.> vv\n\t beta = 2/r0 - v0^2\n\t zeta0 = 1 - beta * r0\n\t x = solveGKepler r0 eta0 zeta0 beta 0.0 tau (tol,maxIt)\n\t r = r0 + eta0 * stumpff_G 1 beta x + zeta0 * stumpff_G 2 beta x\n\t f = 1 - stumpff_G 2 beta x / r0\n\t g = tau - stumpff_G 3 beta x\n\t fd = - stumpff_G 1 beta x / (r * r0)\n\t gd = 1 - stumpff_G 2 beta x / r\n", "meta": {"hexsha": "70e1df5875a1810cfddbac3c3806f1e039b10c0d", "size": 2337, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Kepler.hs", "max_stars_repo_name": "sageh/AstroHaskell", "max_stars_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Kepler.hs", "max_issues_repo_name": "sageh/AstroHaskell", "max_issues_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Kepler.hs", "max_forks_repo_name": "sageh/AstroHaskell", "max_forks_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9615384615, "max_line_length": 84, "alphanum_fraction": 0.6200256739, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6789639089447712}} {"text": "import Data.Complex\n\nmandelbrot a = iterate (\\z -> z^2 + a) 0 !! 50\n\nmain = mapM_ putStrLn [[if magnitude (mandelbrot (x :+ y)) < 2 then '*' else ' '\n | x <- [-2, -1.9685 .. 0.5]]\n | y <- [1, 0.95 .. -1]]\n", "meta": {"hexsha": "b343193359fb9b930dfc0f357c636e635e3e48d0", "size": 253, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Task/Mandelbrot-set/Haskell/mandelbrot-set.hs", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Mandelbrot-set/Haskell/mandelbrot-set.hs", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Mandelbrot-set/Haskell/mandelbrot-set.hs", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 31.625, "max_line_length": 80, "alphanum_fraction": 0.418972332, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172601537142, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6788781779270758}} {"text": "module Main where\n\nimport Data.Complex\n\nmain :: IO ()\nmain = do\n putStrLn \"hello world\"\n\nmaxIter :: Int\nmaxIter = 10000\n\n-- data Scale = {\n-- ULCorner :: Point\n-- DRCorner :: Point\n-- XScale :: Double\n-- YScale :: Double\n-- }\n\n-- Simple boolean test to see if a point is in the set\nisInSet :: RealFloat a => a -> a -> Bool\nisInSet r i = case escapeTime r i of\n Nothing -> True\n Just _ -> False\n\n-- Escape Time of Nothing means the point never escaped\nescapeTime :: RealFloat a => a -> a -> Maybe Int\nescapeTime r i\n | numIter == maxIter = Nothing\n | otherwise = Just numIter\n where numIter = mandel r i\n\n-- Figures out how many iterations a point takes to escape\n-- Or stops after maxIter iterations\nmandel :: RealFloat a => a -> a -> Int\nmandel r i = length . takeWhile ((<= 2) . magnitude) .\n take maxIter $ iterate (\\z -> z^2 + (r :+ i)) 0\n", "meta": {"hexsha": "a54e25a890d29b30304c2214d69ea7045407d5c1", "size": 955, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "IQubic/mandelbrot", "max_stars_repo_head_hexsha": "f605f360552750659d2e4ddef45c18d0b6c239be", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "IQubic/mandelbrot", "max_issues_repo_head_hexsha": "f605f360552750659d2e4ddef45c18d0b6c239be", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "IQubic/mandelbrot", "max_forks_repo_head_hexsha": "f605f360552750659d2e4ddef45c18d0b6c239be", "max_forks_repo_licenses": ["BSD-3-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.8108108108, "max_line_length": 58, "alphanum_fraction": 0.580104712, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6786653826849899}} {"text": "import Data.Complex (cis, phase)\n\nmeanAngle = (/ pi) . (* 180) . phase . sum . map (cis . (/ 180) . (* pi))\n\nmain = mapM_ (\\angles -> putStrLn $ \"The mean angle of \" ++ show angles ++ \" is: \" ++ show (meanAngle angles) ++ \" degrees\")\n [[350, 10], [90, 180, 270, 360], [10, 20, 30]]\n", "meta": {"hexsha": "c387b57855ea92f3c6fa00bceef2884ad3cdbc76", "size": 288, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1428571429, "max_line_length": 124, "alphanum_fraction": 0.5381944444, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6784539461366544}} {"text": "{-# LANGUAGE Rank2Types, BangPatterns, ScopedTypeVariables #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.AD.Newton\n-- Copyright : (c) Edward Kmett 2010\n-- License : BSD3\n-- Maintainer : ekmett@gmail.com\n-- Stability : experimental\n-- Portability : GHC only\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.AD.Newton\n (\n -- * Newton's Method (Forward AD)\n findZero\n , inverse\n , fixedPoint\n , extremum\n -- * Gradient Ascent/Descent (Reverse AD)\n , gradientDescent\n , gradientAscent\n , conjugateGradientDescent\n , conjugateGradientAscent\n ) where\n\nimport Prelude hiding (all, mapM, sum)\nimport Data.Functor\nimport Data.Foldable (all, sum)\nimport Data.Traversable\nimport Numeric.AD.Types\nimport Numeric.AD.Mode.Forward (diff, diff')\nimport Numeric.AD.Mode.Reverse (grad, gradWith')\nimport Numeric.AD.Internal.Combinators\nimport Numeric.AD.Internal.Composition\n\n-- | The 'findZero' function finds a zero of a scalar function using\n-- Newton's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes constant\n-- (\"it converges\"), no further elements are returned.\n--\n-- Examples:\n--\n-- >>> take 10 $ findZero (\\x->x^2-4) 1\n-- [1.0,2.5,2.05,2.000609756097561,2.0000000929222947,2.000000000000002,2.0]\n--\n-- >>> import Data.Complex\n-- >>> last $ take 10 $ findZero ((+1).(^2)) (1 :+ 1)\n-- 0.0 :+ 1.0\nfindZero :: (Fractional a, Eq a) => (forall s. Mode s => AD s a -> AD s a) -> a -> [a]\nfindZero f = go where\n go x = x : if x == xn then [] else go xn where\n (y,y') = diff' f x\n xn = x - y/y'\n{-# INLINE findZero #-}\n\n-- | The 'inverse' function inverts a scalar function using\n-- Newton's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes\n-- constant (\"it converges\"), no further elements are returned.\n--\n-- Example:\n--\n-- >>> last $ take 10 $ inverse sqrt 1 (sqrt 10)\n-- 10.0\ninverse :: (Fractional a, Eq a) => (forall s. Mode s => AD s a -> AD s a) -> a -> a -> [a]\ninverse f x0 y = findZero (\\x -> f x - lift y) x0\n{-# INLINE inverse #-}\n\n-- | The 'fixedPoint' function find a fixedpoint of a scalar\n-- function using Newton's method; its output is a stream of\n-- increasingly accurate results. (Modulo the usual caveats.)\n--\n-- If the stream becomes constant (\"it converges\"), no further\n-- elements are returned.\n--\n-- >>> last $ take 10 $ fixedPoint cos 1\n-- 0.7390851332151607\nfixedPoint :: (Fractional a, Eq a) => (forall s. Mode s => AD s a -> AD s a) -> a -> [a]\nfixedPoint f = findZero (\\x -> f x - x)\n{-# INLINE fixedPoint #-}\n\n-- | The 'extremum' function finds an extremum of a scalar\n-- function using Newton's method; produces a stream of increasingly\n-- accurate results. (Modulo the usual caveats.) If the stream\n-- becomes constant (\"it converges\"), no further elements are returned.\n--\n-- >>> last $ take 10 $ extremum cos 1\n-- 0.0\nextremum :: (Fractional a, Eq a) => (forall s. Mode s => AD s a -> AD s a) -> a -> [a]\nextremum f = findZero (diff (decomposeMode . f . composeMode))\n{-# INLINE extremum #-}\n\n-- | The 'gradientDescent' function performs a multivariate\n-- optimization, based on the naive-gradient-descent in the file\n-- @stalingrad\\/examples\\/flow-tests\\/pre-saddle-1a.vlad@ from the\n-- VLAD compiler Stalingrad sources. Its output is a stream of\n-- increasingly accurate results. (Modulo the usual caveats.)\n--\n-- It uses reverse mode automatic differentiation to compute the gradient.\ngradientDescent :: (Traversable f, Fractional a, Ord a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> [f a]\ngradientDescent f x0 = go x0 fx0 xgx0 0.1 (0 :: Int)\n where\n (fx0, xgx0) = gradWith' (,) f x0\n go x fx xgx !eta !i\n | eta == 0 = [] -- step size is 0\n | fx1 > fx = go x fx xgx (eta/2) 0 -- we stepped too far\n | zeroGrad xgx = [] -- gradient is 0\n | otherwise = x1 : if i == 10\n then go x1 fx1 xgx1 (eta*2) 0\n else go x1 fx1 xgx1 eta (i+1)\n where\n zeroGrad = all (\\(_,g) -> g == 0)\n x1 = fmap (\\(xi,gxi) -> xi - eta * gxi) xgx\n (fx1, xgx1) = gradWith' (,) f x1\n{-# INLINE gradientDescent #-}\n\n-- | Perform a gradient descent using reverse mode automatic differentiation to compute the gradient.\ngradientAscent :: (Traversable f, Fractional a, Ord a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> [f a]\ngradientAscent f = gradientDescent (negate . f)\n{-# INLINE gradientAscent #-}\n\n-- | Perform a conjugate gradient descent using reverse mode automatic differentiation to compute the gradient.\nconjugateGradientDescent :: (Traversable f, Fractional a, Ord a) =>\n (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> [f a]\nconjugateGradientDescent f x0 = go x0 d0 d0\n where\n dot x y = sum $ zipWithT (*) x y\n d0 = negate <$> grad f x0\n go xi ri di = xi : go xi1 ri1 di1\n where\n ai = last $ take 20 $ extremum (\\a -> f $ zipWithT (\\x d -> lift x + a * lift d) xi di) 0\n xi1 = zipWithT (\\x d -> x + ai*d) xi di\n ri1 = negate <$> grad f xi1\n bi1 = max 0 $ dot ri1 (zipWithT (-) ri1 ri) / dot ri1 ri1\n -- bi1 = max 0 $ sum (zipWithT (\\a b -> a * (a - b)) ri1 ri) / dot ri1 ri1\n di1 = zipWithT (\\r d -> r * bi1*d) ri1 di\n{-# INLINE conjugateGradientDescent #-}\n\n-- | Perform a conjugate gradient ascent using reverse mode automatic differentiation to compute the gradient.\nconjugateGradientAscent :: (Traversable f, Fractional a, Ord a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> [f a]\nconjugateGradientAscent f = conjugateGradientDescent (negate . f)\n{-# INLINE conjugateGradientAscent #-}\n", "meta": {"hexsha": "52b40ca07119eb316f411b532ef4a8dcde69f4fa", "size": 5918, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Newton.hs", "max_stars_repo_name": "yairchu/ad", "max_stars_repo_head_hexsha": "490c1d0f3adca67a310dbfcdf9350a5ff47eea5d", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/AD/Newton.hs", "max_issues_repo_name": "yairchu/ad", "max_issues_repo_head_hexsha": "490c1d0f3adca67a310dbfcdf9350a5ff47eea5d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/AD/Newton.hs", "max_forks_repo_name": "yairchu/ad", "max_forks_repo_head_hexsha": "490c1d0f3adca67a310dbfcdf9350a5ff47eea5d", "max_forks_repo_licenses": ["BSD-3-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.0972222222, "max_line_length": 125, "alphanum_fraction": 0.6083136195, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6780664187622577}} {"text": "-- figure 2.1\n\nimport qualified Data.Vector as V\n\nimport Statistics.Sample\nimport Statistics.Sample.Histogram (histogram)\n\ndice :: V.Vector Double\ndice = V.fromList [1,2,3,4,5,6]\n\nmain = do\n putStrLn $ \"the range: \" ++ show (range dice)\n putStrLn $ \"the mean: \" ++ show (mean dice)\n putStrLn $ \"the harmonic mean, which is defined by 6 / (sum $ map (1/) [1..6]): \" ++ show (harmonicMean dice)\n putStrLn $ \"the standard deviation: \" ++ show (stdDev dice)\n\n\n let (bs,hs) = histogram 6 dice\n putStrLn $ \"the histogram is of course uniform: \" ++ show (hs :: V.Vector Int)\n putStrLn $ \"the (lower) boundaries: \" ++ show bs\n", "meta": {"hexsha": "4694a7d2d9b601eb9a807adebce2c482ee716b2a", "size": 626, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ch02/uniform.hs", "max_stars_repo_name": "raydsameshima/Stat", "max_stars_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch02/uniform.hs", "max_issues_repo_name": "raydsameshima/Stat", "max_issues_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch02/uniform.hs", "max_forks_repo_name": "raydsameshima/Stat", "max_forks_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": 29.8095238095, "max_line_length": 111, "alphanum_fraction": 0.6597444089, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6773663090848261}} {"text": "module BuckinghamPi\n (\n FundamentalUnit(..),\n DimensionalVariable(..),\n DimensionlessVariable(..),\n Exponent(..),\n generatePiGroups,\n numFundamentalUnits\n ) where\n\nimport Control.Applicative\nimport Data.List (nub, (\\\\))\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra.HMatrix\nimport Text.Printf (printf)\n\n-- Define sum type for fundamental units (M,L,T,Theta).\ndata FundamentalUnit = Mass | Length | Time | Temperature deriving (Eq,Show)\n\n-- Define type synonym for Exponent.\ntype Exponent = Double\n\n-- A variable is defined by the name, along with units, which is a list of tuples which contains\n-- the FundamentalUnit along with an exponent.\ndata DimensionalVariable = DimensionalVariable {name :: String, units :: [(FundamentalUnit, Exponent)]} deriving (Eq,Show)\n\n-- Define data type for a dimensionless variable.\ndata DimensionlessVariable = DimensionlessVariable {dimensionalVariables :: [DimensionalVariable], exponents :: [Exponent]} deriving (Eq)\n\n-- Define function which normalizes exponents so that the smallest value is +/- 1.\nnormalizeExponents :: [Exponent] -> [Exponent]\nnormalizeExponents exps = map (/factor) exps\n where\n minExp = minimum exps\n factor = minExp * signum minExp\n\n-- Define show instance for a dimensionless variable.\ninstance Show DimensionlessVariable where\n show (DimensionlessVariable dimVars exps) = concatMap (uncurry (printf \"%s^(%.4f) \")) $ filter (\\t -> abs (snd t) > 1.0e-6) $ zip (map name dimVars) (normalizeExponents exps)\n\ngetFundamentalUnits :: DimensionalVariable -> [FundamentalUnit]\ngetFundamentalUnits dimVar = map fst $ units dimVar\n\ngetUniqueFundamentalUnits :: [DimensionalVariable] -> [FundamentalUnit]\ngetUniqueFundamentalUnits = nub . concatMap getFundamentalUnits\n\nnumFundamentalUnits :: [DimensionalVariable] -> Int\nnumFundamentalUnits = length . getUniqueFundamentalUnits\n\n-- Define function that computes the number of dimensionless groups given a list of dimensional variables.\ncomputeNumberOfGroups :: [DimensionalVariable] -> Int\ncomputeNumberOfGroups dimensionalVars = length dimensionalVars - numFundamentalUnits dimensionalVars\n\n-- Define function that returns nonrepeating variables.\ngetNonrepeatingVars :: [DimensionalVariable] -> [Int] -> [DimensionalVariable]\ngetNonrepeatingVars dimVars repeatedIndices = [dimVars !! i | i <- [0..(length dimVars - 1)], i `notElem` repeatedIndices]\n\n-- Define a function that returns the exponent on a given unit in the given dimensional variable.\ngetExponent :: FundamentalUnit -> DimensionalVariable -> Exponent\ngetExponent unit dimVar\n | unit `elem` map fst (units dimVar) = snd $ head $ filter (\\u -> fst u == unit) $ units dimVar\n | otherwise = 0.0\n\n-- Define a function that returns the equation that must be solved.\ngetEquation :: [DimensionalVariable] -> FundamentalUnit -> [Exponent]\ngetEquation varCombination funUnit = map (getExponent funUnit) varCombination\n\ngetVariableCombinations :: [DimensionalVariable] -> [DimensionalVariable] -> [[DimensionalVariable]]\ngetVariableCombinations repeatingVars = map (\\x -> repeatingVars ++ [x])\n\nbuildMatrix :: [DimensionalVariable] -> [FundamentalUnit] -> Matrix Double\nbuildMatrix varCombination funUnits = fromLists $ map (getEquation varCombination) funUnits\n\nfindDimensionlessGroup :: [FundamentalUnit] -> [DimensionalVariable] -> DimensionlessVariable\nfindDimensionlessGroup funUnits dimVars = DimensionlessVariable dimVars (concat . toLists $ nullspace $ buildMatrix dimVars funUnits)\n\n-- Define function which takes a list of dimensional variables along with a list of integers\n-- that identifies which are the repeated variables, and returns a list of dimensionless variables.\ngeneratePiGroups :: [DimensionalVariable] -> [Int] -> [DimensionlessVariable]\ngeneratePiGroups dimVars repeatingVarInds = map (findDimensionlessGroup funUnits) (getVariableCombinations repeatingVars nonrepeatingVars)\n where\n repeatingVars = [dimVars !! i | i <- repeatingVarInds]\n nonrepeatingVars = dimVars \\\\ repeatingVars\n funUnits = getUniqueFundamentalUnits dimVars\n", "meta": {"hexsha": "1aec33dc2fc46a8719529c103f3156ce501668e1", "size": 4161, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BuckinghamPi.hs", "max_stars_repo_name": "jgrisham4/buckingham-pi", "max_stars_repo_head_hexsha": "897fab1d4392c59aa8a1905cb971ba43de05bc7d", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/BuckinghamPi.hs", "max_issues_repo_name": "jgrisham4/buckingham-pi", "max_issues_repo_head_hexsha": "897fab1d4392c59aa8a1905cb971ba43de05bc7d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BuckinghamPi.hs", "max_forks_repo_name": "jgrisham4/buckingham-pi", "max_forks_repo_head_hexsha": "897fab1d4392c59aa8a1905cb971ba43de05bc7d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9529411765, "max_line_length": 176, "alphanum_fraction": 0.7575102139, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6772028789415526}} {"text": "import Numeric.LinearAlgebra\nimport Graphics.Plot\nimport Numeric.GSL.Special(erf_Z, erf)\n\nsombrero n = f x y where \n (x,y) = meshdom range range\n range = linspace n (-2,2)\n f x y = exp (-r2) * cos (2*r2) where \n r2 = x*x+y*y\n\nf x = sin x + 0.5 * sin (5*x)\n\ngaussianPDF = erf_Z\ncumdist x = 0.5 * (1+ erf (x/sqrt 2))\n\nmain = do\n let x = linspace 1000 (-4,4)\n mplot [f x]\n mplot [x, mapVector cumdist x, mapVector gaussianPDF x]\n mesh (sombrero 40)", "meta": {"hexsha": "f950aa59770016e11b834e5ebbabdbf5a6a03d7d", "size": 474, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/plot.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/plot.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/plot.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": 23.7, "max_line_length": 59, "alphanum_fraction": 0.611814346, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6771822839864404}} {"text": "#!/usr/bin/env runhaskell\n{-# LANGUAGE OverloadedStrings, NoImplicitPrelude #-}\nimport ClassyPrelude hiding ((<>)) -- this <> is for semigroups (usually better)\nimport Data.Monoid ((<>)) -- ... but HMatrix only has Monoid\nimport Numeric.LinearAlgebra (tr) -- transpose\nimport qualified Numeric.LinearAlgebra as HMatrix\nimport qualified Data.Text.Format as Format\n\nmain = do\n -- Load the term-document matrix\n putStrLn \"Loading\"\n matrix <- HMatrix.loadMatrix \"termdoc.txt\"\n (u, sigma, vt) <- stochasticTruncatedSVD 50 2 matrix\n\n print $ HMatrix.size u\n print $ HMatrix.size sigma\n print $ HMatrix.size vt\n\n-- Stochastic SVD. See Halko, Martinsson, and Tropp, 2010 for an explanation\nstochasticTruncatedSVD :: Int -> Int -> HMatrix.Matrix Double -> IO (HMatrix.Matrix Double, HMatrix.Vector Double, HMatrix.Matrix Double)\nstochasticTruncatedSVD top_vectors num_iterations original = do\n let (m, n) = HMatrix.size original\n let k = top_vectors + 10\n -- Stage A\n putStrLn \"Stage A\\n\\tPower Iteration\"\n omega <- HMatrix.randn n k\n let\n y 0 = original <> omega\n y n = seq (y (n-1)) $ original <> tr original <> y (n-1)\n bigY <- return $! y num_iterations -- Force evaluation here\n putStrLn \"\\tOrthogonalizing\"\n q <- return $! HMatrix.orth bigY\n\n -- Stage B\n putStrLn \"Stage B\"\n let b = tr q <> original\n (uhat, sigma, vt) = HMatrix.thinSVD b\n u = q <> uhat\n\n return $! (HMatrix.takeColumns top_vectors u,\n HMatrix.subVector 0 top_vectors sigma,\n HMatrix.takeRows top_vectors $ tr vt)\n --putStrLn \"Checking\"\n --let ahat = u <> HMatrix.diag sigma <> tr vt\n\n --Format.print \"MSE of approximation {}\\n\" [HMatrix.sumElements ((a-ahat)^2) / (fromIntegral $ m*n)]\n", "meta": {"hexsha": "77e1567af5409e94a1a49637e9363def81005b68", "size": 1696, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "sketches/02-randomized-svd.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": "sketches/02-randomized-svd.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": "sketches/02-randomized-svd.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": 36.085106383, "max_line_length": 137, "alphanum_fraction": 0.6969339623, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6769448424486297}} {"text": "module Main where\n\nimport Lib\nimport Data.Complex\nimport Graphics.Image\n\nwidth = 750\nheight = 500\nscaleDivisor = 250\n\nxOffset = 2\nyOffset = 1\n\nisInMandelbrotSet :: Complex Double -> Complex Double -> Int -> Int\nisInMandelbrotSet c z 0 = 0\nisInMandelbrotSet c z itterations | (Data.Complex.magnitude z) < 4 = isInMandelbrotSet c (z**2 + c) (itterations - 1)\n | (Data.Complex.magnitude z) >= 4 = itterations\n\ncalculatePixel :: Int -> Int -> Pixel RGB Double\ncalculatePixel y x = PixelRGB 0 0 value where\n real = (fromIntegral x / scaleDivisor) - xOffset\n imag = (fromIntegral y / scaleDivisor) - yOffset\n value = ((fromIntegral (isInMandelbrotSet (real :+ imag) 0 1000)) / 1000)\n\nmain = do\n let image = makeImageR VS (height, width) (\\(y, x) -> calculatePixel y x)\n writeImageExact PNG [] \"output.png\" image", "meta": {"hexsha": "0932e31e6a85b3883f7e62c8f6af70fcafb35d37", "size": 855, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "badnames/haskellbrot", "max_stars_repo_head_hexsha": "fe8e67acd1ce0763df370a7544360598e3ec8b02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "badnames/haskellbrot", "max_issues_repo_head_hexsha": "fe8e67acd1ce0763df370a7544360598e3ec8b02", "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": "badnames/haskellbrot", "max_forks_repo_head_hexsha": "fe8e67acd1ce0763df370a7544360598e3ec8b02", "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.6666666667, "max_line_length": 118, "alphanum_fraction": 0.6736842105, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6768008212427373}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- | Chi-Squared test for uniformity.\nmodule Uniformity (testUniformity) where\n\nimport Data.List (intercalate)\nimport Data.List (foldl')\nimport Numeric (showFFloat)\nimport Numeric.SpecFunctions (incompleteGamma)\nimport Test.Framework.Providers.API (Test, TestName)\n\nimport qualified Data.Map as Map\n\nimport MiniQC as QC\n\n-- | \\( \\lim_{n\\to\\infty} \\mathrm{Pr}(V \\le v) = \\ldots \\)\nchiDist\n :: Int -- ^ k, categories\n -> Double -- ^ v, value\n -> Double\nchiDist k x = incompleteGamma (0.5 * v) (0.5 * x) where\n v = fromIntegral (k - 1)\n\n-- | When the distribution is uniform,\n--\n-- \\[\n-- \\frac{1}{n} \\sum_{s = 1}^k \\frac{Y_s^2}{p_s} - n\n-- \\]\n--\n-- simplifies to\n--\n-- \\[\n-- \\frac{k}{n} \\sum_{s=1}^k Y_s^2 - n\n-- \\]\n--\n-- when \\(p_s = \\frac{1}{k} \\), i.e. \\(k\\) is the number of buckets.\n--\ncalculateV :: Int -> Map.Map k Int -> Double\ncalculateV k data_ = chiDist k v\n where\n v = fromIntegral k * fromIntegral sumY2 / fromIntegral n - fromIntegral n\n V2 n sumY2 = foldl' sumF (V2 0 0) (Map.elems data_) where\n sumF (V2 m m2) x = V2 (m + x) (m2 + x * x)\n\n-- Strict pair of 'Int's, used as an accumulator.\ndata V2 = V2 !Int !Int\n\ncountStream :: Ord a => Stream a -> Int -> Map.Map a Int\ncountStream = go Map.empty where\n go !acc s n\n | n <= 0 = acc\n | otherwise = case s of\n x :> xs -> go (Map.insertWith (+) x 1 acc) xs (pred n)\n\ntestUniformityRaw :: forall a. (Ord a, Show a) => Int -> Stream a -> Either String Double\ntestUniformityRaw k s\n | Map.size m > k = Left $ \"Got more elements (\" ++ show (Map.size m, take 5 $ Map.keys m) ++ \" than expected (\" ++ show k ++ \")\"\n | p > 0.999999 = Left $\n \"Too impropabable p-value: \" ++ show p ++ \"\\n\" ++ table\n [ [ show x, showFFloat (Just 3) (fromIntegral y / fromIntegral n :: Double) \"\" ]\n | (x, y) <- take 20 $ Map.toList m\n ]\n | otherwise = Right p\n where\n -- each bucket to have roughly 128 elements\n n :: Int\n n = k * 128\n\n -- buckets from the stream\n m :: Map.Map a Int\n m = countStream s n\n\n -- calculate chi-squared value\n p :: Double\n p = calculateV k m\n\ntestUniformityQC :: (Ord a, Show a) => Int -> Stream a -> QC.Property\ntestUniformityQC k s = case testUniformityRaw k s of\n Left err -> QC.counterexample err False\n Right _ -> QC.property True\n\n-- | Test that generator produces values uniformly.\n--\n-- The size is scaled to be at least 20.\n--\ntestUniformity\n :: forall a b. (Ord b, Show b)\n => TestName\n -> QC.Gen a -- ^ Generator to test\n -> (a -> b) -- ^ Partitioning function\n -> Int -- ^ Number of partittions\n -> Test\ntestUniformity name gen f k = QC.testMiniProperty name\n $ QC.forAllBlind (streamGen gen)\n $ testUniformityQC k . fmap f\n\n-------------------------------------------------------------------------------\n-- Infinite stream\n-------------------------------------------------------------------------------\n\ndata Stream a = a :> Stream a deriving (Functor)\ninfixr 5 :>\n\nstreamGen :: QC.Gen a -> QC.Gen (Stream a)\nstreamGen g = gs where\n gs = do\n x <- g\n xs <- gs\n return (x :> xs)\n\n-------------------------------------------------------------------------------\n-- Table\n-------------------------------------------------------------------------------\n\ntable :: [[String]] -> String\ntable cells = unlines rows\n where\n cols :: Int\n rowWidths :: [Int]\n rows :: [String]\n\n (cols, rowWidths, rows) = foldr go (0, repeat 0, []) cells\n\n go :: [String] -> (Int, [Int], [String]) -> (Int, [Int], [String])\n go xs (c, w, yss) =\n ( max c (length xs)\n , zipWith max w (map length xs ++ repeat 0)\n , intercalate \" \" (take cols (zipWith fill xs rowWidths))\n : yss\n )\n\n fill :: String -> Int -> String\n fill s n = s ++ replicate (n - length s) ' '\n", "meta": {"hexsha": "0f442c66fdeeb339820fd4acb0a2798dc815bb12", "size": 4065, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tests/Uniformity.hs", "max_stars_repo_name": "Mikolaj/splitmix", "max_stars_repo_head_hexsha": "664a1e063a5f0cf03c4874ed9abac5ac9e0993f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2017-06-30T16:20:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-26T05:17:21.000Z", "max_issues_repo_path": "tests/Uniformity.hs", "max_issues_repo_name": "Mikolaj/splitmix", "max_issues_repo_head_hexsha": "664a1e063a5f0cf03c4874ed9abac5ac9e0993f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2018-04-15T20:29:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T17:56:29.000Z", "max_forks_repo_path": "tests/Uniformity.hs", "max_forks_repo_name": "Mikolaj/splitmix", "max_forks_repo_head_hexsha": "664a1e063a5f0cf03c4874ed9abac5ac9e0993f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-04-15T19:56:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T17:06:42.000Z", "avg_line_length": 30.1111111111, "max_line_length": 132, "alphanum_fraction": 0.52300123, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6766098021049611}} {"text": "module Math.Probably.Circular where\n\nimport Math.Probably.FoldingStats\nimport Numeric.LinearAlgebra\nimport Control.Applicative\n\n--approximate method first mentioned http://en.wikipedia.org/wiki/Mean_of_circular_quantities\ncircularMean :: Fold Double Double\ncircularMean = before (after vmean getAngle) toCartesian where\n vmean = pure (scale) <*> after realLengthF recip <*> sumF\n getAngle v = atan2 (v@>1) (v@>0)\n toCartesian alpha = fromList [cos alpha, sin alpha]\n\n--http://webspace.ship.edu/pgmarr/Geo441/Lectures/Lec%2016%20-%20Directional%20Statistics.pdf\ncircularDispersion :: Fold Double Double\ncircularDispersion = after (both xs ys) getR where\n xs = before sumF cos\n ys = before sumF sin\n getR (x,y) = sqrt (x*x + y*y)\n\n\n--example for running statistic\n\nrunCircularMean :: [Double] -> Double\nrunCircularMean = runStat circularMean\n", "meta": {"hexsha": "888f24dd68d5051e1085be8ebc43c62931c80a0c", "size": 846, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/Circular.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/Circular.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/Circular.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 32.5384615385, "max_line_length": 93, "alphanum_fraction": 0.7671394799, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6766097966197103}} {"text": "module ActivationFunction\n ( step'\n , sigmoid\n , relu\n , softMax'\n ) where\n\nimport Numeric.LinearAlgebra\n\nstep' :: (Element b, Container c a, Ord a, Num a, Num b) => c a -> c b\nstep' = cmap (\\x -> if x>0 then 1 else 0)\n\nsigmoid :: (Container c b, Floating b) => c b -> c b\nsigmoid = cmap (\\x -> 1 / (1 + exp(-x)))\n\nrelu :: (Container c b, Ord b, Num b) => c b -> c b\nrelu = cmap (max 0)\n\n-- This function is deprecated, causes overflow.\nsoftMax :: (Container c b, Floating b) => c b -> c b\nsoftMax xs = cmap (/sumCexp) $ cexp xs\n where sumCexp = (sumElements . cexp) xs\n\nsoftMax' :: (Container c b, Floating b) => c b -> c b\nsoftMax' xs = cmap (/sumCexp) $ cexp' xs\n where sumCexp = (sumElements . cexp') xs\n\ncexp :: (Container c b, Floating b) => c b -> c b\ncexp = cmap exp\n\ncexp' :: (Container c b, Floating b) => c b -> c b\ncexp' xs = cexp $ cmap (subtract $ maxElement xs) xs\n", "meta": {"hexsha": "8d05b5ae7699a234e7fe1f227366513c8011c159", "size": 901, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ActivationFunction.hs", "max_stars_repo_name": "ku00/deep-learning-practice", "max_stars_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-03T05:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T05:32:58.000Z", "max_issues_repo_path": "src/ActivationFunction.hs", "max_issues_repo_name": "ku00/deep-learning-practice", "max_issues_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ActivationFunction.hs", "max_forks_repo_name": "ku00/deep-learning-practice", "max_forks_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.303030303, "max_line_length": 70, "alphanum_fraction": 0.5993340733, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.676198866886354}} {"text": "module Math(hamming, preemphasis, sliding, toMesh, spectrogram) where\n\nimport RIO\nimport RIO.List (mapAccumL, zipWith)\nimport Control.Parallel.Strategies\nimport Data.Complex\nimport qualified Numeric.FFT as NF\n\nsliding :: Int -> Int -> a -> [a] -> [[a]]\nsliding step size padding xs\n | len < size = [xs ++ replicate (size - len) padding]\n | otherwise = take size xs : sliding step size padding (drop step xs)\n where len = length xs\n\npreemphasis :: Complex Double -> [Complex Double] -> [Complex Double]\npreemphasis emph = snd . mapAccumL (\\prev y -> (y, y - emph * prev)) 0.0\n\nhamming :: [Complex Double] -> [Complex Double]\nhamming signal = let len = length signal\n in zipWith (*) signal $ hamming' len 0.53\n\nhamming' :: Int -> Complex Double -> [Complex Double]\nhamming' n alpha =\n let beta = 1 - alpha\n in [alpha - beta * cos(2 * pi * fromIntegral i / (fromIntegral n - 1)) | i <- [0..n - 1]]\n\ntoMesh :: (Num c) => [[c]] -> [[(c, c, c)]]\ntoMesh dd = do\n (x, fs) <- zip ([1..] :: [Integer]) dd\n return $ do\n (y, p) <- zip ([0..] :: [Integer]) fs\n return (fromIntegral x, fromIntegral y, p)\n\nspectrogram :: Int -> Int -> [Complex Double] -> [[Complex Double]]\nspectrogram step len signal = let ft = take (len `div` 2) . NF.fft . hamming\n windows = sliding step len 0 signal\n nWindows = length windows\n strat = parListChunk (nWindows `div` 4) rdeepseq\n in ft <$> windows `using` strat\n", "meta": {"hexsha": "e2615f510f5c0de0c6c842c4e96a34261e72c541", "size": 1566, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math.hs", "max_stars_repo_name": "kaffepanna/genderhs", "max_stars_repo_head_hexsha": "9648212c57c32d45cd67a078587f52691a4f8755", "max_stars_repo_licenses": ["BSD-3-Clause"], "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.hs", "max_issues_repo_name": "kaffepanna/genderhs", "max_issues_repo_head_hexsha": "9648212c57c32d45cd67a078587f52691a4f8755", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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.hs", "max_forks_repo_name": "kaffepanna/genderhs", "max_forks_repo_head_hexsha": "9648212c57c32d45cd67a078587f52691a4f8755", "max_forks_repo_licenses": ["BSD-3-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.15, "max_line_length": 94, "alphanum_fraction": 0.5779054917, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6761971464476884}} {"text": "module Main where\n\nimport qualified Data.Attoparsec.Text as P\nimport Exercise\nimport Numeric.LinearAlgebra hiding ((<>))\nimport qualified Data.Map as M\nimport Data.List\nimport Text.Printf ( printf )\n\n-- Parsing\n--------------------------------------------------\n\ntype Input = [Int]\n\nfishParser :: P.Parser [Int]\nfishParser =\n P.decimal `P.sepBy` P.char ','\n\ninputParser :: P.Parser Input\ninputParser =\n fishParser <* P.skipSpace <* P.endOfInput\n\n-- Linear Algebra\n--------------------------------------------------\n\n-- | Simple matrix powers.\n-- Does not use repeated squaring.\npow :: Matrix R -> Int -> Matrix R\npow m n\n | n <= 0 = ident (rows m)\n | n == 1 = m\n | even n = pow (m <> m) (n `div` 2)\n | otherwise = m <> pow m (n - 1)\n\n-- | Convert a list of numbers to a vector of counts\n-- This could be more efficient by accumulating counts, but this is good enough.\ntoCounts :: [Int] -> Vector R\ntoCounts = fromList . toFrequencies . M.fromListWith (+) . flip zip (repeat 1)\n where\n toFrequencies m =\n map (maybe 0 id . flip M.lookup m) [0..8]\n\n-- Main\n--------------------------------------------------\n\nmain :: IO ()\nmain = do\n input <- parseInput inputParser\n numFish1 <- runExercise \"Part 1\" (countFish 7 2 80) input\n printf \"Number of fish: %d\\n\" numFish1\n numFish2 <- runExercise \"Part 2\" (countFish 7 2 256) input\n printf \"Number of fish: %d\\n\" numFish2\n\n-- numFish2 <- runExercise \"Part 2\" part2 input\n-- printf \"Losing Score: %d\\n\" score2\n\ncountFish :: Int -> Int -> Int -> Input -> Int\ncountFish gestation adolescence generations fish =\n let fishVector = toCounts fish\n generationMatrix = makeGenerationMatrix gestation adolescence\n in truncate . sumElements $ pow generationMatrix generations #> fishVector\n\nmakeGenerationMatrix :: Int -> Int -> Matrix R\nmakeGenerationMatrix gestation adolescence =\n let size = gestation + adolescence\n modifyNth n f xs =\n let (a, b : c) = splitAt n xs\n in a ++ f b : c\n emptyRow = replicate size 0\n row n = modifyNth n (+ 1) emptyRow\n basic = map row [1 .. (size - 1)] ++ [row 0]\n withGestation = modifyNth (gestation - 1) (modifyNth 0 (+ 1)) basic\n in fromLists withGestation", "meta": {"hexsha": "89b0d6e331b70defea114a47383a043baa4a7147", "size": 2195, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Day06/Main.hs", "max_stars_repo_name": "periodic/AdventOfCode2021", "max_stars_repo_head_hexsha": "b182b8b32cb58d0db646a85aa306e40ecbb95943", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-07T23:26:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T23:26:03.000Z", "max_issues_repo_path": "src/Day06/Main.hs", "max_issues_repo_name": "periodic/AdventOfCode2021", "max_issues_repo_head_hexsha": "b182b8b32cb58d0db646a85aa306e40ecbb95943", "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/Day06/Main.hs", "max_forks_repo_name": "periodic/AdventOfCode2021", "max_forks_repo_head_hexsha": "b182b8b32cb58d0db646a85aa306e40ecbb95943", "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.0684931507, "max_line_length": 80, "alphanum_fraction": 0.6218678815, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6759076819735027}} {"text": "-- File created: 2009-07-15 21:15:44\n\n{-# LANGUAGE Rank2Types #-}\n\nmodule Haschoo.Evaluator.Standard.Numeric\n (procedures, isNumeric, isExact, numEq, asInt) where\n\nimport Control.Arrow ((&&&), (***))\nimport Control.Monad (ap, foldM)\nimport Data.Array.IArray (elems)\nimport Data.Array.MArray (getElems)\nimport Data.Char (intToDigit)\nimport Data.Complex ( Complex((:+)), mkPolar\n , imagPart, realPart, phase, magnitude)\nimport Data.Ratio (numerator, denominator, approxRational)\nimport Data.Function (on)\nimport Numeric (showIntAtBase, showSigned)\n\nimport qualified Haschoo.Parser as Parser\nimport Haschoo.Types (ScmValue(..), toScmMString)\nimport Haschoo.Utils (ErrOr, allM, ($<), (.:))\nimport Haschoo.Evaluator.Utils (tooFewArgs, tooManyArgs, notInt)\n\nprocedures :: [(String, ScmValue)]\nprocedures = map (\\(a,b) -> (a, ScmFunc a (return . b)))\n [ (\"number?\", fmap ScmBool . scmIsNumber)\n , (\"complex?\", fmap ScmBool . scmIsNumber)\n , (\"real?\", fmap ScmBool . scmIsReal)\n , (\"rational?\", fmap ScmBool . scmIsRational)\n , (\"integer?\", fmap ScmBool . scmIsInteger)\n\n , \"exact?\" $< id &&& fmap ScmBool .: scmIsExact\n , \"inexact?\" $< id &&& fmap (ScmBool . not) .: scmIsExact\n\n , (\"=\", fmap ScmBool . scmNumEq)\n , \"<\" $< id &&& fmap ScmBool .: scmCompare (<)\n , \">\" $< id &&& fmap ScmBool .: scmCompare (>)\n , \"<=\" $< id &&& fmap ScmBool .: scmCompare (<=)\n , \">=\" $< id &&& fmap ScmBool .: scmCompare (>=)\n\n , (\"zero?\", fmap ScmBool . scmIsZero)\n , (\"positive?\", fmap ScmBool . scmIsPos)\n , (\"negative?\", fmap ScmBool . scmIsNeg)\n , \"even?\" $< id &&& fmap ScmBool .: scmIsEven\n , \"odd?\" $< id &&& fmap (ScmBool . not) .: scmIsEven\n\n , (\"max\", scmMax)\n , (\"min\", scmMin)\n\n , (\"+\", scmPlus)\n , (\"-\", scmMinus)\n , (\"*\", scmMul)\n , (\"/\", scmDiv)\n\n , (\"abs\", scmAbs)\n\n , (\"quotient\", scmQuot)\n , (\"remainder\", scmRem)\n , (\"modulo\", scmMod)\n\n , (\"gcd\", scmGcd)\n , (\"lcm\", scmLcm)\n\n , (\"numerator\", scmNumerator)\n , (\"denominator\", scmDenominator)\n\n , (\"floor\", scmFloor)\n , (\"ceiling\", scmCeil)\n , (\"truncate\", scmTrunc)\n , (\"round\", scmRound)\n\n , (\"rationalize\", scmRationalize)\n\n , (\"exp\", scmExp)\n , (\"log\", scmLog)\n , (\"sin\", scmSin)\n , (\"cos\", scmCos)\n , (\"tan\", scmTan)\n , (\"asin\", scmAsin)\n , (\"acos\", scmAcos)\n , (\"atan\", scmAtan)\n\n , (\"sqrt\", scmSqrt)\n , (\"expt\", scmExpt)\n\n , (\"make-rectangular\", scmMakeRectangular)\n , (\"make-polar\", scmMakePolar)\n , (\"real-part\", scmRealPart)\n , (\"imag-part\", scmImagPart)\n , (\"magnitude\", scmNorm)\n , (\"angle\", scmAngle)\n\n , (\"exact->inexact\", scmToInexact)\n , (\"inexact->exact\", scmToExact) ]\n\n ++ map (\\(a,b) -> (a, ScmFunc a b))\n [ (\"number->string\", scmToString)\n , (\"string->number\", scmToNumber) ]\n\n---- Predicates\n\nscmIsNumber, scmIsReal, scmIsRational, scmIsInteger :: [ScmValue] -> ErrOr Bool\nscmIsNumber [x] = Right $ isNumeric x\nscmIsNumber [] = tooFewArgs \"number?\"\nscmIsNumber _ = tooManyArgs \"number?\"\n\nscmIsReal [x] = Right $ isReal x\nscmIsReal [] = tooFewArgs \"real?\"\nscmIsReal _ = tooManyArgs \"real?\"\n\nscmIsRational [ScmRat _] = Right True\nscmIsRational [x] = Right $ isInteger x\nscmIsRational [] = tooFewArgs \"rational?\"\nscmIsRational _ = tooManyArgs \"rational?\"\n\nscmIsInteger [x] = Right $ isInteger x\nscmIsInteger [] = tooFewArgs \"integer?\"\nscmIsInteger _ = tooManyArgs \"integer?\"\n\nscmIsExact :: String -> [ScmValue] -> ErrOr Bool\nscmIsExact _ [x] | isNumeric x = Right $ isExact x\nscmIsExact s [_] = notNum s\nscmIsExact s [] = tooFewArgs s\nscmIsExact s _ = tooManyArgs s\n\nisExact :: ScmValue -> Bool\nisExact (ScmInt _) = True\nisExact (ScmRat _) = True\nisExact _ = False\n\n---- Comparison\n\nscmNumEq :: [ScmValue] -> ErrOr Bool\nscmNumEq [] = tooFewArgs \"=\"\nscmNumEq xs = allM f . (zip`ap`tail) $ xs\n where\n f (a,b) = if isNumeric a && isNumeric b\n then Right $ numEq a b\n else notNum \"=\"\n\nnumEq :: ScmValue -> ScmValue -> Bool\nnumEq x y =\n case pairScmComplex x y of\n Right (ScmInt a, ScmInt b) -> a == b\n Right (ScmRat a, ScmRat b) -> a == b\n Right (ScmReal a, ScmReal b) -> a == b\n Right (ScmComplex a, ScmComplex b) -> a == b\n _ -> error \"numEq :: the impossible happened\"\n\nscmCompare :: (forall a. Real a => a -> a -> Bool)\n -> String -> [ScmValue] -> ErrOr Bool\nscmCompare p s xs@(_:_:_) = allM f . (zip`ap`tail) $ xs\n where\n f (a,b) = case liftScmRealA2 p a b of\n Left _ -> notReal s\n x -> x\n\nscmCompare _ s _ = tooFewArgs s\n\nscmIsZero :: [ScmValue] -> ErrOr Bool\nscmIsZero [ScmInt 0] = Right True\nscmIsZero [ScmRat 0] = Right True\nscmIsZero [ScmReal 0] = Right True\nscmIsZero [ScmComplex 0] = Right True\nscmIsZero [x] | isNumeric x = Right False\nscmIsZero [_] = notNum \"zero?\"\nscmIsZero _ = tooManyArgs \"zero?\"\n\nscmIsPos, scmIsNeg :: [ScmValue] -> ErrOr Bool\nscmIsPos [x] = scmCompare (>) \"positive?\" [x, ScmInt 0]\nscmIsPos _ = tooManyArgs \"positive?\"\n\nscmIsNeg [x] = scmCompare (<) \"negative?\" [x, ScmInt 0]\nscmIsNeg _ = tooManyArgs \"negative?\"\n\nscmIsEven :: String -> [ScmValue] -> ErrOr Bool\nscmIsEven s [x] = if isInteger x\n then (scmIsZero.return) =<< scmMod [x, ScmInt 2]\n else notInt s\nscmIsEven s _ = tooManyArgs s\n\nscmMax, scmMin :: [ScmValue] -> ErrOr ScmValue\nscmMax = scmMinMax max \"max\"\nscmMin = scmMinMax min \"min\"\n\nscmMinMax :: (forall a. Real a => a -> a -> a) -> String\n -> [ScmValue] -> ErrOr ScmValue\nscmMinMax _ s [] = tooFewArgs s\nscmMinMax f s (x:xs) = if isNumeric x then foldM go x xs else notNum s\n where\n go n a = if isNumeric a\n then case liftScmReal2 f n a of\n Left _ -> notReal s\n m -> m\n else notNum s\n\n---- +-*/\n\nscmPlus, scmMinus, scmMul, scmDiv :: [ScmValue] -> ErrOr ScmValue\nscmPlus [] = Right $ ScmInt 0\nscmPlus xs = foldM go (ScmInt 0) xs\n where\n go n x = if isNumeric x then liftScmNum2 (+) n x else notNum \"+\"\n\nscmMinus [] = tooFewArgs \"-\"\nscmMinus (x:_) | not (isNumeric x) = notNum \"-\"\nscmMinus [x] = liftScmNum negate x\nscmMinus (x:xs) = foldM go x xs\n where\n go n a = if isNumeric a then liftScmNum2 (-) n a else notNum \"-\"\n\nscmMul [] = Right $ ScmInt 1\nscmMul xs = foldM go (ScmInt 1) xs\n where\n go n x = if isNumeric x then liftScmNum2 (*) n x else notNum \"*\"\n\nscmDiv [] = tooFewArgs \"/\"\nscmDiv (x:xs) =\n unint x >>= case xs of\n [] -> liftScmFrac recip\n _:_ -> flip (foldM go) xs\n where\n go n a = unint a >>= liftScmFrac2 (/) n\n\n unint (ScmInt n) = Right $ ScmRat (fromInteger n)\n unint n = if isNumeric x then Right n else notNum \"/\"\n\n---- abs\n\nscmAbs :: [ScmValue] -> ErrOr ScmValue\nscmAbs [x] =\n if isReal x\n then liftScmNum abs x\n else notReal \"abs\"\nscmAbs [] = tooFewArgs \"abs\"\nscmAbs _ = tooManyArgs \"abs\"\n\n---- quot rem mod\n\nscmQuot, scmRem, scmMod :: [ScmValue] -> ErrOr ScmValue\nscmQuot = scmQuotRemMod quot \"quotient\"\nscmRem = scmQuotRemMod rem \"remainder\"\nscmMod = scmQuotRemMod mod \"modulo\"\n\nscmQuotRemMod :: (Integer -> Integer -> Integer) -> String\n -> [ScmValue] -> ErrOr ScmValue\nscmQuotRemMod f s [x,y] = do\n (e1,a) <- asInt s x\n (e2,b) <- asInt s y\n return . (if e1 && e2 then ScmInt else ScmReal . fromInteger) $ f a b\nscmQuotRemMod _ s (_:_:_) = tooManyArgs s\nscmQuotRemMod _ s _ = tooFewArgs s\n\n---- gcd lcm\n\nscmGcd, scmLcm :: [ScmValue] -> ErrOr ScmValue\nscmGcd = scmGcdLcm (\\a b -> if a == 0 && b == 0 then 0 else gcd a b) 0 \"gcd\"\nscmLcm = scmGcdLcm lcm 1 \"lcm\"\n\nscmGcdLcm :: (Integer -> Integer -> Integer) -> Integer -> String\n -> [ScmValue] -> ErrOr ScmValue\nscmGcdLcm f i s = fmap fin . foldM go (True,i)\n where\n go (exact, n) = fmap ((exact &&) *** f n) . asInt s\n fin (exact, n) = if exact then ScmInt n else ScmReal (fromInteger n)\n\n---- numerator denominator\n\nscmNumerator, scmDenominator :: [ScmValue] -> ErrOr ScmValue\nscmNumerator = scmNumerDenom numerator \"numerator\"\nscmDenominator = scmNumerDenom denominator \"denominator\"\n\nscmNumerDenom :: (Rational -> Integer) -> String\n -> [ScmValue] -> ErrOr ScmValue\nscmNumerDenom f s [n] =\n case n of\n ScmInt x -> Right . ScmInt $ f (fromInteger x)\n ScmRat x -> Right . ScmInt $ f x\n ScmReal x -> Right . ScmReal . fromInteger $ f (realToFrac x)\n ScmComplex (x :+ 0) -> Right . ScmReal . fromInteger $ f (realToFrac x)\n _ -> notRat s\n\nscmNumerDenom _ s [] = tooFewArgs s\nscmNumerDenom _ s _ = tooManyArgs s\n\n---- floor ceil trunc round\n\nscmFloor, scmCeil, scmTrunc, scmRound :: [ScmValue] -> ErrOr ScmValue\nscmFloor = scmGenericRound floor \"floor\"\nscmCeil = scmGenericRound ceiling \"ceiling\"\nscmTrunc = scmGenericRound truncate \"truncate\"\nscmRound = scmGenericRound round \"round\"\n\nscmGenericRound :: (forall a. RealFrac a => a -> Integer) -> String\n -> [ScmValue] -> ErrOr ScmValue\nscmGenericRound _ _ [ ScmInt x] = Right . ScmInt $ x\nscmGenericRound f _ [ ScmRat x] = Right . ScmInt $ f x\nscmGenericRound f _ [ ScmReal x] = Right . ScmReal . fromInteger $ f x\nscmGenericRound _ s [n@(ScmComplex _)] =\n case asInt s n of\n Right (_,x) -> Right . ScmInt $ x\n Left _ -> notReal s\nscmGenericRound _ s [_] = notNum s\nscmGenericRound _ s [] = tooFewArgs s\nscmGenericRound _ s _ = tooManyArgs s\n\n---- rationalize\n\nscmRationalize :: [ScmValue] -> ErrOr ScmValue\nscmRationalize (_:_:_:_) = tooManyArgs \"rationalize\"\nscmRationalize [x,y] =\n case liftScmRealFracB2 approxRational x y of\n Left _ -> notReal \"rationalize\"\n Right (True , n) -> Right (ScmRat n)\n Right (False, n) -> Right (ScmReal (fromRational n))\n\nscmRationalize _ = tooFewArgs \"rationalize\"\n\n---- exp log sin cos tan asin acos atan sqrt\n\nscmExp, scmLog,\n scmSin, scmCos, scmTan,\n scmAsin, scmAcos, scmAtan,\n scmSqrt :: [ScmValue] -> ErrOr ScmValue\n\nscmExp = scmComplex1 exp \"exp\"\nscmLog = scmComplex1 log \"log\"\nscmSin = scmComplex1 sin \"sin\"\nscmCos = scmComplex1 cos \"cos\"\nscmTan = scmComplex1 tan \"tan\"\nscmAsin = scmComplex1 asin \"asin\"\nscmAcos = scmComplex1 acos \"acos\"\n\nscmAtan [y,x] =\n case pairScmReal x y of\n Left _ -> notReal \"atan\"\n Right (ScmReal a, ScmReal b) -> Right (ScmReal $ phase $ a :+ b)\n Right (ScmInt a, ScmInt b) ->\n Right (ScmReal $ phase $ fromInteger a :+ fromInteger b)\n Right (ScmRat a, ScmRat b) ->\n Right (ScmReal $ phase $ fromRational a :+ fromRational b)\n Right _ -> error \"scmAtan :: internal error\"\n\nscmAtan xs = scmComplex1 atan \"atan\" xs\n\nscmSqrt = scmComplex1 sqrt \"sqrt\"\n\nscmComplex1 :: (Complex Double -> Complex Double) -> String\n -> [ScmValue] -> ErrOr ScmValue\nscmComplex1 f _ [ScmInt x] = Right . fromComplex $ f (fromInteger x :+ 0)\nscmComplex1 f _ [ScmRat x] = Right . fromComplex $ f (fromRational x :+ 0)\nscmComplex1 f _ [ScmReal x] = Right . fromComplex $ f (x :+ 0)\nscmComplex1 f _ [ScmComplex x] = Right . fromComplex $ f x\nscmComplex1 _ s [_] = notNum s\nscmComplex1 _ s [] = tooFewArgs s\nscmComplex1 _ s _ = tooManyArgs s\n\n---- expt\n\nscmExpt :: [ScmValue] -> ErrOr ScmValue\nscmExpt [x,y] =\n case pairScmComplex x y of\n Left _ -> notNum \"expt\"\n Right (ScmInt a, ScmInt b) ->\n if b < 0\n then Right . ScmReal $ fromInteger a ^^ b\n else Right . ScmInt $ a ^ b\n Right (ScmReal a, ScmReal b) -> Right . ScmReal $ a ** b\n Right (ScmComplex a, ScmComplex b) -> Right . ScmComplex $ a ** b\n Right (ScmRat a, ScmRat b) ->\n Right . ScmReal $ fromRational a ** fromRational b\n Right _ -> error \"expt :: internal error\"\n\nscmExpt (_:_:_) = tooManyArgs \"expt\"\nscmExpt _ = tooFewArgs \"expt\"\n\n---- make-rectangular make-polar real-part imag-part magnitude angle\n\nscmMakeRectangular, scmMakePolar :: [ScmValue] -> ErrOr ScmValue\nscmMakeRectangular = scmMakeComplex (:+) \"make-rectangular\"\nscmMakePolar = scmMakeComplex mkPolar \"make-polar\"\n\nscmMakeComplex :: (Double -> Double -> Complex Double) -> String\n -> [ScmValue] -> ErrOr ScmValue\nscmMakeComplex f s [x,y] =\n case pairScmReal x y of\n Left _ -> notReal s\n Right (ScmReal a, ScmReal b) -> Right . ScmComplex $ f a b\n Right (ScmRat a, ScmRat b) ->\n Right . ScmComplex $ (f `on` fromRational) a b\n Right (ScmInt a, ScmInt b) ->\n Right . ScmComplex $ (f `on` fromInteger) a b\n Right _ ->\n error $ s ++ \" :: internal error\"\n\nscmMakeComplex _ s (_:_:_) = tooManyArgs s\nscmMakeComplex _ s _ = tooFewArgs s\n\nscmRealPart, scmImagPart, scmNorm, scmAngle :: [ScmValue] -> ErrOr ScmValue\nscmRealPart = scmComplexPart realPart Right \"real-part\"\nscmImagPart = scmComplexPart imagPart (liftScmNum $ const 0) \"imag-part\"\nscmNorm = scmComplexPart magnitude (liftScmNum abs) \"magnitude\"\nscmAngle = scmComplexPart phase (Right . angle) \"angle\"\n where\n angle (ScmReal n) = f ScmReal n\n angle (ScmRat n) = f ScmRat n\n angle (ScmInt n) = f ScmInt n\n angle _ = error \"angle :: the impossible happened\"\n\n f c n = if n >= 0 then c 0 else ScmReal pi\n\nscmComplexPart :: (Complex Double -> Double)\n -> (ScmValue -> ErrOr ScmValue)\n -> String\n -> [ScmValue] -> ErrOr ScmValue\nscmComplexPart f _ _ [ScmComplex x] = Right $ ScmReal (f x)\nscmComplexPart _ g _ [x] | isNumeric x = g x\nscmComplexPart _ _ s [_] = notNum s\nscmComplexPart _ _ s [] = tooFewArgs s\nscmComplexPart _ _ s _ = tooManyArgs s\n\n---- exact->inexact inexact->exact\n\nscmToInexact, scmToExact :: [ScmValue] -> ErrOr ScmValue\nscmToInexact [ScmInt x] = Right $ ScmReal (fromInteger x)\nscmToInexact [ScmRat x] = Right $ ScmReal (fromRational x)\nscmToInexact [x] | isNumeric x = Right x\nscmToInexact [_] = notNum \"exact->inexact\"\nscmToInexact [] = tooFewArgs \"exact->inexact\"\nscmToInexact _ = tooManyArgs \"exact->inexact\"\n\nscmToExact [ScmReal x] =\n let r = toRational x\n in Right $ if denominator r == 1\n then ScmInt (numerator r)\n else ScmRat r\nscmToExact [ScmComplex x] =\n case imagPart x of\n 0 -> Right $ ScmReal (realPart x)\n _ -> fail $ \"inexact->exact :: implementation restriction: \" ++\n \"can't exactify complex numbers\"\nscmToExact [x] | isNumeric x = Right x\nscmToExact [_] = notNum \"exact->inexact\"\nscmToExact [] = tooFewArgs \"exact->inexact\"\nscmToExact _ = tooManyArgs \"exact->inexact\"\n\n---- number->string string->number\n\nscmToString, scmToNumber :: [ScmValue] -> IO (ErrOr ScmValue)\n\n-- TODO: scmShow should use this or vice versa\nscmToString (x:xs) | isNumeric x =\n case xs of\n [] -> g x 10\n [ScmInt radix] ->\n if radix `elem` [2,8,10,16]\n then g x (fromInteger radix)\n else return. fail $\n \"number->string :: invalid radix \" ++ show radix\n\n [_] -> return$ notInt \"number->string\"\n _ -> return$ tooManyArgs \"number->string\"\n where\n g n radix = case f n radix of\n Left err -> return$ fail err\n Right s -> fmap Right $ toScmMString s\n\n f (ScmInt i) radix = Right $ showInt radix i\n f (ScmRat r) radix = Right $\n if denominator r == 1\n then showInt radix (numerator r)\n else concat [ showInt radix (numerator r)\n , \"/\"\n , showInt radix (denominator r) ]\n\n f (ScmReal r) radix =\n if radix == 10\n then Right $\n case () of\n _| isNaN r -> \"+nan.#\"\n | isInfinite r -> (if r < 0 then '-' else '+') : \"inf.#\"\n\n -- R5RS 6.2.6 specifies that \"the result contains a\n -- decimal point\" if inexact and a decimal-point\n -- containing result can make it work\n | otherwise -> show r\n else fail \"number->string :: nondecimal radix for inexact real\"\n\n f (ScmComplex (a :+ b)) radix =\n -- As in the ScmReal case\n if radix == 10\n then Right . concat $ let bs = either undefined id $ f (ScmReal b) 10\n in [ either undefined id $ f (ScmReal a) 10\n , if head bs `elem` \"-+\" then [] else \"+\"\n , bs\n , \"i\" ]\n\n else fail \"number->string :: nondecimal radix for inexact complex\"\n\n f _ _ = error \"number->string :: the impossible happened\"\n\n showInt radix i = showSigned (showIntAtBase radix intToDigit) 0 i \"\"\n\nscmToString [] = return$ tooFewArgs \"number->string\"\nscmToString _ = return$ notNum \"number->string\"\n\nscmToNumber (ScmString s : xs) = return$ toNumHelper xs (elems s)\nscmToNumber (ScmMString s : xs) = fmap (toNumHelper xs) (getElems s)\nscmToNumber [] = return$ tooFewArgs \"string->number\"\nscmToNumber _ = return$ fail \"Nonstring argument to string->number\"\n\ntoNumHelper :: [ScmValue] -> String -> ErrOr ScmValue\ntoNumHelper xs s =\n case xs of\n [] -> Right $ f s 10\n [ScmInt radix] ->\n if radix `elem` [2,8,10,16]\n then Right $ f s (fromInteger radix)\n else fail $ \"string->number :: invalid radix \" ++ show radix\n\n [_] -> notInt \"string->number\"\n _ -> tooManyArgs \"string->number\"\n where\n f str radix =\n case Parser.runParser (Parser.number radix) \"\" str of\n Right n | isNumeric n -> n\n _ -> ScmBool False\n\n-------------\n\nnotNum, notReal, notRat :: String -> ErrOr a\nnotNum = fail . (\"Nonnumeric argument to \" ++)\nnotReal = fail . (\"Nonreal argument to \" ++)\nnotRat = fail . (\"Nonrational argument to \" ++)\n\nisNumeric, isInteger, isReal :: ScmValue -> Bool\nisNumeric (ScmInt _) = True\nisNumeric (ScmRat _) = True\nisNumeric (ScmReal _) = True\nisNumeric (ScmComplex _) = True\nisNumeric _ = False\n\nisInteger (ScmInt _) = True\nisInteger (ScmRat x) = denominator x == 1\nisInteger (ScmReal x) = x == fromInteger (round x)\nisInteger (ScmComplex (a:+b)) = b == 0 && a == fromInteger (round a)\nisInteger _ = False\n\nisReal (ScmComplex (_ :+ b)) = b == 0\nisReal x = isNumeric x\n\nasInt :: String -> ScmValue -> ErrOr (Bool, Integer)\nasInt s x | not (isInteger x) = notInt s\nasInt _ (ScmInt x) = Right (True, x)\nasInt _ (ScmRat x) = Right (True, numerator x)\nasInt _ (ScmReal x) = Right (False, round x)\nasInt _ (ScmComplex (x:+0)) = Right (False, round x)\nasInt _ _ = error \"This can't happen\"\n\nfromComplex :: Complex Double -> ScmValue\nfromComplex (x :+ 0) = ScmReal x\nfromComplex x = ScmComplex x\n\n-- Lift ScmValue's numeric types to a common type\n--\n-- Versions without 'A' at the end also return results in the correct\n-- constructor of the two given. Versions with 'B' just return whether the\n-- result should be exact or not.\n--\n-- Ugly and verbose... too lazy to metaize these {{{\n\n--- Num\nliftScmNum :: (forall a. Num a => a -> a) -> ScmValue -> ErrOr ScmValue\nliftScmNum f (ScmInt a) = Right . ScmInt $ f a\nliftScmNum f (ScmRat a) = Right . ScmRat $ f a\nliftScmNum f (ScmReal a) = Right . ScmReal $ f a\nliftScmNum f (ScmComplex a) = Right . ScmComplex $ f a\nliftScmNum _ _ = fail \"liftScmNum :: internal error\"\n\nliftScmNum2 :: (forall a. Num a => a -> a -> a)\n -> (ScmValue -> ScmValue -> ErrOr ScmValue)\nliftScmNum2 f (ScmInt a) (ScmInt b) = Right . ScmInt $ f a b\nliftScmNum2 f (ScmRat a) (ScmRat b) = Right . ScmRat $ f a b\nliftScmNum2 f (ScmReal a) (ScmReal b) = Right . ScmReal $ f a b\nliftScmNum2 f (ScmComplex a) (ScmComplex b) = Right . ScmComplex$ f a b\n\n-- Int+{Rat,Real,Complex}\nliftScmNum2 f (ScmInt a) (ScmRat b) = Right . ScmRat $ f (fInt a) b\nliftScmNum2 f (ScmRat a) (ScmInt b) = Right . ScmRat $ f a (fInt b)\nliftScmNum2 f (ScmInt a) (ScmReal b) = Right . ScmReal $ f (fInt a) b\nliftScmNum2 f (ScmReal a) (ScmInt b) = Right . ScmReal $ f a (fInt b)\nliftScmNum2 f (ScmInt a) (ScmComplex b) = Right . ScmComplex$ f (fInt a) b\nliftScmNum2 f (ScmComplex a) (ScmInt b) = Right . ScmComplex$ f a (fInt b)\n\n-- Rat+{Real,Complex}\nliftScmNum2 f (ScmRat a) (ScmReal b) = Right . ScmReal $ f (fRat a) b\nliftScmNum2 f (ScmReal a) (ScmRat b) = Right . ScmReal $ f a (fRat b)\nliftScmNum2 f (ScmRat a) (ScmComplex b) = Right . ScmComplex$ f (fRat a) b\nliftScmNum2 f (ScmComplex a) (ScmRat b) = Right . ScmComplex$ f a (fRat b)\n\n-- Real+Complex\nliftScmNum2 f (ScmReal a) (ScmComplex b) = Right . ScmComplex$ f (a :+ 0) b\nliftScmNum2 f (ScmComplex a) (ScmReal b) = Right . ScmComplex$ f a (b :+ 0)\n\nliftScmNum2 _ _ _ = fail \"liftScmNum2 :: internal error\"\n\n--- Frac\nliftScmFrac :: (forall a. Fractional a => a -> a) -> ScmValue -> ErrOr ScmValue\nliftScmFrac f (ScmRat a) = Right . ScmRat $ f a\nliftScmFrac f (ScmReal a) = Right . ScmReal $ f a\nliftScmFrac f (ScmComplex a) = Right . ScmComplex $ f a\nliftScmFrac _ _ = fail \"liftScmFrac :: internal error\"\n\nliftScmFrac2 :: (forall a. Fractional a => a -> a -> a)\n -> (ScmValue -> ScmValue -> ErrOr ScmValue)\nliftScmFrac2 f (ScmRat a) (ScmRat b) = Right . ScmRat $ f a b\nliftScmFrac2 f (ScmReal a) (ScmReal b) = Right . ScmReal $ f a b\nliftScmFrac2 f (ScmComplex a) (ScmComplex b) = Right . ScmComplex$ f a b\n\n-- Rat+{Real,Complex}\nliftScmFrac2 f (ScmRat a) (ScmReal b) = Right . ScmReal $ f (fRat a) b\nliftScmFrac2 f (ScmReal a) (ScmRat b) = Right . ScmReal $ f a (fRat b)\nliftScmFrac2 f (ScmRat a) (ScmComplex b) = Right . ScmComplex$ f (fRat a) b\nliftScmFrac2 f (ScmComplex a) (ScmRat b) = Right . ScmComplex$ f a (fRat b)\n\n-- Real+Complex\nliftScmFrac2 f (ScmReal a) (ScmComplex b) = Right . ScmComplex$ f (a :+ 0) b\nliftScmFrac2 f (ScmComplex a) (ScmReal b) = Right . ScmComplex$ f a (b :+ 0)\n\nliftScmFrac2 _ _ _ = fail \"liftScmFrac2 :: internal error\"\n\n--- Real\nliftScmReal2 :: (forall a. Real a => a -> a -> a)\n -> (ScmValue -> ScmValue -> ErrOr ScmValue)\nliftScmReal2 f x y =\n case pairScmReal x y of\n Right (ScmReal a, ScmReal b) -> Right . ScmReal $ f a b\n Right (ScmRat a, ScmRat b) -> Right . ScmRat $ f a b\n Right (ScmInt a, ScmInt b) -> Right . ScmInt $ f a b\n Left s -> Left s\n Right _ -> fail \"liftScmReal2 :: internal error\"\n\nliftScmRealA2 :: (forall a. Real a => a -> a -> b)\n -> (ScmValue -> ScmValue -> ErrOr b)\nliftScmRealA2 f x y =\n case pairScmReal x y of\n Right (ScmReal a, ScmReal b) -> Right $ f a b\n Right (ScmRat a, ScmRat b) -> Right $ f a b\n Right (ScmInt a, ScmInt b) -> Right $ f a b\n Left s -> Left s\n Right _ -> fail \"liftScmRealA2 :: internal error\"\n\n--- RealFrac\nliftScmRealFracB2 :: (forall a. RealFrac a => a -> a -> b)\n -> (ScmValue -> ScmValue -> ErrOr (Bool, b))\nliftScmRealFracB2 f x y =\n case pairScmReal x y of\n Right (ScmReal a, ScmReal b) -> Right (False, f a b)\n Right (ScmRat a, ScmRat b) -> Right (True, f a b)\n Right (ScmInt a, ScmInt b) ->\n Right (True, f (fInt a) (fInt b :: Rational))\n Left s -> Left s\n Right _ ->\n fail \"liftScmRealFracB2 :: internal error\"\n\npairScmReal :: ScmValue -> ScmValue -> ErrOr (ScmValue, ScmValue)\npairScmReal (ScmComplex a) _ | imagPart a /= 0 = fail \"pairScmReal :: complex\"\npairScmReal _ (ScmComplex b) | imagPart b /= 0 = fail \"pairScmReal :: complex\"\n\npairScmReal a@(ScmInt _) b@(ScmInt _) = Right (a,b)\npairScmReal a@(ScmRat _) b@(ScmRat _) = Right (a,b)\npairScmReal a@(ScmReal _) b@(ScmReal _) = Right (a,b)\npairScmReal (ScmComplex a) (ScmComplex b) =\n Right $ ((,) `on` ScmReal . realPart) a b\n\n-- Int+{Rat,Real,Complex}\npairScmReal (ScmInt a) (ScmRat b) = Right $ ((,)`on`ScmRat) (fInt a) b\npairScmReal (ScmRat a) (ScmInt b) = Right $ ((,)`on`ScmRat) a (fInt b)\npairScmReal (ScmInt a) (ScmReal b) = Right $ ((,)`on`ScmReal) (fInt a) b\npairScmReal (ScmReal a) (ScmInt b) = Right $ ((,)`on`ScmReal) a (fInt b)\npairScmReal (ScmInt a) (ScmComplex b) =\n Right $ ((,)`on`ScmReal) (fInt a) (realPart b)\npairScmReal (ScmComplex a) (ScmInt b) =\n Right $ ((,)`on`ScmReal) (realPart a) (fInt b)\n\n-- Rat+{Real,Complex}\npairScmReal (ScmRat a) (ScmReal b) = Right $ ((,)`on`ScmReal) (fRat a) b\npairScmReal (ScmReal a) (ScmRat b) = Right $ ((,)`on`ScmReal) a (fRat b)\npairScmReal (ScmRat a) (ScmComplex b) =\n Right $ ((,)`on`ScmReal) (fRat a) (realPart b)\npairScmReal (ScmComplex a) (ScmRat b) =\n Right $ ((,)`on`ScmReal) (realPart a) (fRat b)\n\n-- Real+Complex\npairScmReal (ScmReal a) (ScmComplex b) =\n Right $ ((,)`on`ScmReal) a (realPart b)\npairScmReal (ScmComplex a) (ScmReal b) =\n Right $ ((,)`on`ScmReal) (realPart a) b\n\npairScmReal _ _ = fail \"pairScmReal :: internal error\"\n\npairScmComplex :: ScmValue -> ScmValue -> ErrOr (ScmValue, ScmValue)\npairScmComplex a@(ScmInt _) b@(ScmInt _) = Right (a,b)\npairScmComplex a@(ScmRat _) b@(ScmRat _) = Right (a,b)\npairScmComplex a@(ScmReal _) b@(ScmReal _) = Right (a,b)\npairScmComplex a@(ScmComplex _) b@(ScmComplex _) = Right (a,b)\n\n-- Int+{Rat,Real,Complex}\npairScmComplex (ScmInt a) (ScmRat b) = Right$((,)`on`ScmRat) (fInt a) b\npairScmComplex (ScmRat a) (ScmInt b) = Right$((,)`on`ScmRat) a (fInt b)\npairScmComplex (ScmInt a) (ScmReal b) =\n Right $ ((,)`on`ScmReal) (fInt a) b\npairScmComplex (ScmReal a) (ScmInt b) =\n Right $ ((,)`on`ScmReal) a (fInt b)\npairScmComplex (ScmInt a) (ScmComplex b) =\n Right $ ((,)`on`ScmComplex) (fInt a) b\npairScmComplex (ScmComplex a) (ScmInt b) =\n Right $ ((,)`on`ScmComplex) a (fInt b)\n\n-- Rat+{Real,Complex}\npairScmComplex (ScmRat a) (ScmReal b) =\n Right $ ((,)`on`ScmReal) (fRat a) b\npairScmComplex (ScmReal a) (ScmRat b) =\n Right $ ((,)`on`ScmReal) a (fRat b)\npairScmComplex (ScmRat a) (ScmComplex b) =\n Right $ ((,)`on`ScmComplex) (fRat a) b\npairScmComplex (ScmComplex a) (ScmRat b) =\n Right $ ((,)`on`ScmComplex) a (fRat b)\n\n-- Real+Complex\npairScmComplex (ScmReal a) (ScmComplex b) =\n Right $ ((,)`on`ScmComplex) (a:+0) b\npairScmComplex (ScmComplex a) (ScmReal b) =\n Right $ ((,)`on`ScmComplex) a (b:+0)\n\npairScmComplex _ _ = fail \"pairScmComplex :: internal error\"\n\nfInt :: Num a => Integer -> a\nfInt = fromInteger\n\nfRat :: Fractional a => Rational -> a\nfRat = fromRational\n\n-- }}}\n", "meta": {"hexsha": "f6b483ff65f7007001f9ab8e840e4859a9e14654", "size": 27977, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Haschoo/Evaluator/Standard/Numeric.hs", "max_stars_repo_name": "Deewiant/haschoo", "max_stars_repo_head_hexsha": "378d8e3361fc2cedd54f3428da1eceae75560631", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Haschoo/Evaluator/Standard/Numeric.hs", "max_issues_repo_name": "Deewiant/haschoo", "max_issues_repo_head_hexsha": "378d8e3361fc2cedd54f3428da1eceae75560631", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Haschoo/Evaluator/Standard/Numeric.hs", "max_forks_repo_name": "Deewiant/haschoo", "max_forks_repo_head_hexsha": "378d8e3361fc2cedd54f3428da1eceae75560631", "max_forks_repo_licenses": ["BSD-3-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.5530201342, "max_line_length": 79, "alphanum_fraction": 0.5786181506, "num_tokens": 9543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6753389156701309}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MonoLocalBinds #-}\n\nmodule Synapse\n ( sigmoid\n , sigmoidm\n , sigmoidBackward\n , relu\n , relum\n , relumBackward\n , softmax\n , softmaxm\n , softmaxWithCross\n , softmaxWithCrossBackward\n , crossEntropy\n , crossEntropym\n , affinem\n , affinemBackward\n ) where\n\nimport Debug.Trace\nimport Numeric.LinearAlgebra\nimport Prelude hiding ((<>))\n\nsigmoid :: (Floating a) => a -> a\nsigmoid a = 1 / (1 + exp (-a))\n\nsigmoidm :: (Floating a, Container Matrix a) => Matrix a -> Matrix a\nsigmoidm = cmap sigmoid\n\nsigmoidBackward ::\n (Floating a, Num (Vector a), Container Matrix a)\n => Matrix a\n -> Matrix a\n -> Matrix a\nsigmoidBackward y d = d * (1 - y) * y\n\nrelu :: (Ord a, Num a) => a -> a\nrelu = max 0\n\nrelum :: (Ord a, Num a, Container Matrix a) => Matrix a -> Matrix a\nrelum = cmap relu\n\nrelumBackward ::\n (Ord a, Num a, Num (Matrix a), Container Vector a, Container Matrix a)\n => Matrix a\n -> Matrix a\n -> Matrix a\nrelumBackward x d = d * mask\n where\n mask = cmap (fromIntegral . onoff) x\n onoff a\n | 0 < a = 1\n | otherwise = 0\n\nsoftmax :: (Floating a, Container Vector a) => Vector a -> Vector a\nsoftmax v = cmap (/ s) v'\n where\n m = maxElement v\n v' = cmap (\\a -> exp (a - m)) v\n s = sumElements v'\n\nsoftmaxm :: (Floating a, Container Vector a) => Matrix a -> Matrix a\nsoftmaxm m = fromRows $ map softmax $ toRows m\n\ncrossEntropy ::\n (Floating a, Num (Vector a), Container Vector a)\n => Vector a\n -> Vector a\n -> a\ncrossEntropy t y = -(sumElements $ cmap log (y + d) * t)\n where\n d = 1e-10\n\ncrossEntropym ::\n (Floating a, Num (Vector a), Container Vector a)\n => Matrix a\n -> Matrix a\n -> a\ncrossEntropym t m = sum vs / batchSize\n where\n vs = zipWith crossEntropy (toRows t) (toRows m)\n batchSize = fromIntegral $ rows t\n\nsoftmaxWithCross ::\n (Floating a, Num (Vector a), Container Vector a)\n => Matrix a\n -> Matrix a\n -> (Matrix a, a)\nsoftmaxWithCross t x = (y, crossEntropym t y)\n where\n y = softmaxm x\n\nsoftmaxWithCrossBackward ::\n (Floating a, Num (Vector a), Container Vector a)\n => Matrix a\n -> Matrix a\n -> Matrix a\nsoftmaxWithCrossBackward t y = cmap (/ batchSize) $ y - t\n where\n batchSize = fromIntegral $ rows t\n\naffinem ::\n (Floating a, Numeric a, Num (Vector a))\n => Matrix a\n -> Vector a\n -> Matrix a\n -> Matrix a\naffinem w b x = (x <> w) + b'\n where\n b' = fromRows $ replicate (rows x) b\n\naffinemBackward ::\n (Floating a, Numeric a)\n => Matrix a\n -> Matrix a\n -> Matrix a\n -> (Matrix a, Matrix a, Vector a)\naffinemBackward w x d = (dx, dw, db)\n where\n dx = d <> tr w\n dw = tr x <> d\n db = fromList $ sumElements `map` toColumns d\n", "meta": {"hexsha": "de01f24ecf844d1181dc5fc1576cd1cee1ebdd54", "size": 2759, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Synapse.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/Synapse.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/Synapse.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": 22.25, "max_line_length": 75, "alphanum_fraction": 0.6074664734, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6752557604091936}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra.Packed.Cholesky\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Cholesky factorizations of symmetric (Hermitian) positive-definite\n-- matrices.\n--\n\nmodule Numeric.LinearAlgebra.Packed.Cholesky (\n -- * Immutable interface\n cholFactor,\n cholSolveVector,\n cholSolveMatrix,\n\n -- * Mutable interface\n cholFactorM,\n cholSolveVectorM_,\n cholSolveMatrixM_,\n ) where\n\nimport Control.Monad( when )\nimport Control.Monad.ST( ST, runST, unsafeIOToST )\nimport Text.Printf( printf )\n\nimport qualified Foreign.LAPACK as LAPACK\n\nimport Numeric.LinearAlgebra.Types\n\nimport Numeric.LinearAlgebra.Packed.Base( Packed, RPacked, STPacked )\nimport qualified Numeric.LinearAlgebra.Packed.Base as P\n\nimport Numeric.LinearAlgebra.Matrix( Matrix, STMatrix )\nimport qualified Numeric.LinearAlgebra.Matrix as M\n\nimport Numeric.LinearAlgebra.Vector( Vector, STVector )\nimport qualified Numeric.LinearAlgebra.Vector as V\n\n-- | @cholFactor a@ tries to compute the Cholesky\n-- factorization of @a@. If @a@ is positive-definite then the routine\n-- returns @Right@ with the factorization. If the leading minor of order @i@\n-- is not positive-definite then the routine returns @Left i@.\ncholFactor :: (LAPACK e)\n => Herm Packed e\n -> Either Int (Chol Packed e)\ncholFactor (Herm uplo a) = runST $ do\n ma <- P.newCopy a\n cholFactorM (Herm uplo ma)\n >>= either (return . Left) (\\(Chol uplo' ma') -> do\n a' <- P.unsafeFreeze ma'\n return $ Right (Chol uplo' a')\n )\n\n-- | @cholSolveVector a x@ returns @a \\\\ x@.\ncholSolveVector :: (LAPACK e)\n => Chol Packed e\n -> Vector e\n -> Vector e\ncholSolveVector a x = V.create $ do\n x' <- V.newCopy x\n cholSolveVectorM_ a x'\n return x'\n\n-- | @cholSolveMatrix a b@ returns @a \\\\ b@.\ncholSolveMatrix :: (LAPACK e)\n => Chol Packed e\n -> Matrix e\n -> Matrix e\ncholSolveMatrix a c = M.create $ do\n c' <- M.newCopy c\n cholSolveMatrixM_ a c'\n return c'\n\n-- | @cholFactorM a@ tries to compute the Cholesky\n-- factorization of @a@ in place. If @a@ is positive-definite then the\n-- routine returns @Right@ with the factorization, stored in the same\n-- memory as @a@. If the leading minor of order @i@ is not\n-- positive-definite then the routine returns @Left i@.\n-- In either case, the original storage of @a@ is destroyed.\ncholFactorM :: (LAPACK e)\n => Herm (STPacked s) e\n -> ST s (Either Int (Chol (STPacked s) e))\ncholFactorM (Herm uplo a) = do\n n <- P.getDim a\n unsafeIOToST $\n P.unsafeWith a $ \\pa -> do\n info <- LAPACK.pptrf uplo n pa\n return $ if info > 0 then Left info\n else Right (Chol uplo a)\n\n-- | @cholSolveVectorM_ a x@ sets @x := a \\\\ x@.\ncholSolveVectorM_ :: (LAPACK e, RPacked p)\n => Chol p e\n -> STVector s e\n -> ST s ()\ncholSolveVectorM_ a x =\n M.withFromColM x $ \\x' ->\n cholSolveMatrixM_ a x'\n\n-- | @cholSolveMatrixM_ a b@ sets @b := a \\\\ b@.\ncholSolveMatrixM_ :: (LAPACK e, RPacked p)\n => Chol p e\n -> STMatrix s e\n -> ST s ()\ncholSolveMatrixM_ (Chol uplo a) b = do\n na <- P.getDim a\n (mb,nb) <- M.getDim b\n let (n,nrhs) = (mb,nb)\n\n when ((not . and) [ na == n\n , (mb,nb) == (n,nrhs)\n ]) $ error $\n printf (\"cholSolveMatrixM_\"\n ++ \" (Chol _ )\"\n ++ \" \"\n ++ \": dimension mismatch\")\n na mb nb\n\n unsafeIOToST $\n P.unsafeWith a $ \\pa ->\n M.unsafeWith b $ \\pb ldb ->\n LAPACK.pptrs uplo n nrhs pa pb ldb\n", "meta": {"hexsha": "18234f1464b781e6dc7975602bb61b286d6f00d5", "size": 4128, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Packed/Cholesky.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Packed/Cholesky.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Packed/Cholesky.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": 32.7619047619, "max_line_length": 77, "alphanum_fraction": 0.5714631783, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582995, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6752557460457043}} {"text": "{-# LANGUAGE OverloadedLists\n , TypeFamilies\n , FlexibleContexts #-}\n\nmodule Utils.Quaternions where\n\nimport Number.Quaternion hiding (normalize,norm)\nimport qualified Number.Quaternion as Q\nimport Numeric.LinearAlgebra (Matrix, Vector, tr, cmap,(<>), inv,single,double)\nimport qualified Data.Vector.Storable as VS\nimport qualified Numeric.LinearAlgebra.Data as LD\n\nimport Utils (mat3ToMat4)\n\nqvMul :: VS.Vector Float -> T Float -> T Float\nqvMul v = quatConcat (0 +:: (VS.unsafeIndex v 0,VS.unsafeIndex v 1,VS.unsafeIndex v 2))\n\nquatToLInv inertiaDiag quat =\n let orientation = quatToMat3 quat\n in tr orientation\n <> (single . inv . double) inertiaDiag\n <> orientation\n\nrotateWithQuat :: T Float -> VS.Vector Float -> VS.Vector Float\nrotateWithQuat quat [a,b,c] =\n (\\(a,b,c) -> [a,b,c]) .\n imag .\n flip quatConcat (qInverse quat) $\n quatConcat quat (0 +:: (a,b,c))\n\naddQuat q1 q2 =\n let r1 = real q1\n r2 = real q2\n i1 = imag q1\n i2 = imag q2\n in (r1 + r2) +:: sum3 i1 i2\n\n\nquatToMatV :: T Float -> VS.Vector Float\nquatToMatV q =\n let r = real q\n (i,j,k) = imag q\n r2 = r*r\n i2 = i*i; j2 = j*j; k2 = k*k;\n ri = 2*r*i; rj = 2*r*j; rk = 2*r*k;\n ij = 2*i*j; ki = 2*k*i; kj = 2*k*j;\n in [ r2+i2-j2-k2, ij-rk, ki+rj, 0\n , ij+rk, r2-i2+j2-k2, kj-ri, 0\n , ki-rj, kj+ri, r2-i2-j2+k2, 0\n , 0, 0, 0, 1]\n\nquatToMat = tr . LD.reshape 4 . quatToMatV\n\nquatToMat3 :: T Float -> Matrix Float\nquatToMat3 = LD.fromArray2D . toRotationMatrix\n\n\n\nsum3 (a,b,c) (d,e,f) = (a+d,b+e,c+f)\n\nscale3 n (a,b,c) = (n*a,n*b,n*c)\n\nquatConcat q0 q1 =\n let w0 = real q0\n w1 = real q1\n v0 = imag q0\n v1 = imag q1\n wr = w1 * w0 - scalarProduct v1 v0\n vr = scale3 w1 v0 `sum3` scale3 w0 v1 `sum3` crossProduct v1 v0\n in wr +:: vr\n\nqInverse :: T Float -> T Float\nqInverse q =\n let w = real q\n v = (\\(a,b,c) -> (negate a, negate b, negate c)) $ imag q\n in w +:: v\n\nqZero :: T Float\nqZero = 1 +:: (0,0,0)\n", "meta": {"hexsha": "547e45356110bcdc7f16bf8a59d89219ac51ce79", "size": 2073, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Utils/Quaternions.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/Utils/Quaternions.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/Utils/Quaternions.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": 25.9125, "max_line_length": 89, "alphanum_fraction": 0.5769416305, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6751275473711104}} {"text": "module Main where\n\nimport Linear (\n V2(V2), V3(V3), (^+^), (^-^), (*^))\nimport Data.Complex (\n Complex((:+)))\nimport Codec.Picture (\n Image, Pixel8, generateImage, writePng)\n\n\ndata Edge2 a = Edge2 (V2 a) (V2 a)\n deriving (Show, Eq, Ord)\n\n\ntype ScalarField2 a = V2 a -> a\n\nrenderE0 :: Floating a => Ord a => ScalarField2 a\nrenderE0 (V2 x1 x2)\n | x1 < 0 = 0\n | x1 > 1 = 0\n | otherwise = x2 * exp (negate (sqr x2))\n\nsqr :: Num a => a -> a\nsqr x = x * x\n\n\ncotransformScalarField2 :: (V2 a -> V2 a) -> ScalarField2 a -> ScalarField2 a\ncotransformScalarField2 g f = \\x -> f (g x)\n\ntranslate2 :: Num a => V2 a -> V2 a -> V2 a\ntranslate2 = (^+^)\n\nrotate2 :: RealFloat a => Complex a -> V2 a -> V2 a\nrotate2 r (V2 x1 x2) = do\n let y1 :+ y2 = r * (x1 :+ x2)\n V2 y1 y2\n\nscale22 :: Num a => a -> V2 a -> V2 a\nscale22 s (V2 x1 x2) = V2 x1 (s * x2)\n\n\nrenderEdge2 :: RealFloat a => Ord a => Edge2 a -> ScalarField2 a\nrenderEdge2 (Edge2 a b) = do\n let w = 0.1\n let V2 c1 c2 = b ^-^ a\n let r = c1 :+ c2\n cotransformScalarField2 (\n scale22 (recip w) . rotate2 (recip r) . translate2 (negate a)) renderE0\n\n\n-- Write image\n\nresolution :: Int\nresolution = 600\n\nimageToCameraSpace :: V2 Int -> V2 Double\nimageToCameraSpace (V2 i1 i2) = do\n let x1 = fromIntegral i1 / fromIntegral resolution * 2 - 1\n let x2 = 1 - fromIntegral i2 / fromIntegral resolution * 2\n V2 x1 x2\n\ndiscreteGrey :: Double -> Pixel8\ndiscreteGrey a\n | a < -1 = 0\n | a > 1 = 255\n | otherwise = round ((0.5 + 0.5 * a) * 255)\n\nmanifestImage :: ScalarField2 Double -> Image Pixel8\nmanifestImage rendering = do\n let imageFunction i1 i2 = discreteGrey (rendering (imageToCameraSpace (V2 i1 i2)))\n generateImage imageFunction resolution resolution\n\nmain :: IO ()\nmain = do\n\n let testImage = renderEdge2 (Edge2 (V2 (-0.8) 0.3) (V2 0.4 0.8))\n\n writePng \"out/testImage.png\" (manifestImage testImage)\n", "meta": {"hexsha": "68895bdca5d4f794561c782eaf550c6548dff67c", "size": 1863, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "phischu/stereo-vision", "max_stars_repo_head_hexsha": "11572dfbbad88aa8c006ba32dff5f7e0840e4a81", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "phischu/stereo-vision", "max_issues_repo_head_hexsha": "11572dfbbad88aa8c006ba32dff5f7e0840e4a81", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "phischu/stereo-vision", "max_forks_repo_head_hexsha": "11572dfbbad88aa8c006ba32dff5f7e0840e4a81", "max_forks_repo_licenses": ["BSD-3-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.582278481, "max_line_length": 84, "alphanum_fraction": 0.6301663983, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6751275387878534}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule LinearRegression\n ( trainLinReg\n , trainAndTestLinReg\n , trainLinRegWNoise\n , avError\n , linRegAsInitialForPLA\n , createVectorY\n , createRandomPoints\n , flipLabels\n , linearRegressionWeight\n , linRegClassificationError\n , testLinRegWNoise\n , createMatrixX\n , makeTargetFunction\n , y\n ) where\n\nimport Control.Monad (replicateM)\nimport Data.Maybe\nimport Data.Traversable (for)\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra.HMatrix\nimport PLA\nimport System.Random\n\n--------------------------------------------------------------\n-- Solutions to homework 2 of \"Learning from data\" question 5-6\n--------------------------------------------------------------\n---------------------------------------------\n-- Creating the line for the target function\n--------------------------------------------\n-- | takes 2 points and returns the slope of the line connecting them\nm :: (R, R) -> (R, R) -> R\nm (x1, x2) (z1, z2) = (x2 - z2) / (x1 - z1)\n\n-- | takes 2 points and returns the y-intercept of the line connecting them\nb :: (R, R) -> (R, R) -> R\nb (x1, x2) (z1, z2) = x2 - x1 * (x2 - z2) / (x1 - z1)\n\n-- | Takes 2 Points and returns the function of a line connecting them\nline point1 point2 = \\x -> m point1 point2 * x + b point1 point2\n\n-----------------------------------\n-- Creating random data points\n------------------------------------\n-- |Creates a random Point between (-1,-1) and (1,1)\ncreateRandomPoint :: IO (R, R)\ncreateRandomPoint = do\n rand1 <- randomRIO (-1, 1)\n rand2 <- randomRIO (-1, 1)\n return (rand1, rand2)\n\n-- |Creates a list of n random Points between (-1,-1) and (1,1)\ncreateRandomPoints :: Int -> IO [(R, R)]\ncreateRandomPoints n = do\n randList1 <- for [1 .. n] $ \\_ -> randomRIO (-1, 1)\n randList2 <- for [1 .. n] $ \\_ -> randomRIO (-1, 1)\n return $ zip randList1 randList2\n\n-----------------------------------------------------\n-- Preparing data for processing by Linear Regression\n------------------------------------------------------\n-- | looks up the label of the point by applying the target function\ny :: (R -> R) -> (R, R) -> R\ny yLine (x1, x2) =\n if yLine x1 < x2\n then (-1)\n else 1\n\n-- | Creates the vector of labels using the target function 'yLine' and a list of data points\ncreateVectorY :: ((R, R) -> R) -> [(R, R)] -> Vector R\ncreateVectorY target listOfPoints = vector $ map target listOfPoints\n\n-- | Creates the matrix X from a list of data points\ncreateMatrixX :: [(R, R)] -> Matrix R\ncreateMatrixX listOfPoints = matrix 3 listOfNumbers\n where\n listOfNumbers = concat [[1, a, b] | (a, b) <- listOfPoints]\n\nflipLabels :: Float -> Vector R -> IO (Vector R)\nflipLabels noiselevel labelvector = do\n gen <- getStdGen\n let numLabels = size labelvector\n let randnums :: [Int] = randomRs (1, numLabels) gen\n let toFlip = take (floor (noiselevel * fromIntegral numLabels)) randnums\n let flipVector =\n vector\n [ if x `elem` toFlip\n then (-1)\n else 1\n | x <- [1 .. numLabels]\n ]\n let flippedLabels = labelvector * flipVector\n return flippedLabels\n\n--------------------------------------------------------\n-- Linear Regression algorithm\n--------------------------------------------------------\n-- | returns the weights determined by linear regression on the training data\nlinearRegressionWeight :: Matrix R -> Vector R -> Vector R\nlinearRegressionWeight matrixOfInputData vectorOfLabels =\n pinv matrixOfInputData #> vectorOfLabels\n\n-- | Squared error\nsquaredError :: Matrix R -> Vector R -> Vector R -> R\nsquaredError matrixOfInputData vectorOfLabels weight =\n 1 / fromIntegral n * dot v v\n where\n v = signum (matrixOfInputData #> weight) - vectorOfLabels\n n = size vectorOfLabels\n\n-- | Classification error for linear Regression (i.e. fraction of misclassified points)\nlinRegClassificationError :: Matrix R -> Vector R -> Vector R -> R\nlinRegClassificationError matrixOfInputData vectorOfLabels weight =\n numberMisclassified / totalDatapoints\n where\n numberMisclassified =\n norm_0 $ signum (matrixOfInputData #> weight) - vectorOfLabels\n totalDatapoints = fromIntegral $ size vectorOfLabels\n\n--------------------------------------------------\n-- training and testing the Linear Regression model\n--------------------------------------------------\n-- | create the target function\nmakeTargetFunction :: IO (R -> R)\nmakeTargetFunction = do\n point1 <- createRandomPoint\n point2 <- createRandomPoint\n let target = line point1 point2\n return target\n\n-- | training linear Regression on random dataset of n noisy points and returning (weights, in-Sample error, trainingpoints)\ntrainLinRegWNoise ::\n ((R, R) -> R)\n -> Int\n -> Float\n -> ([(R, R)] -> Matrix R)\n -> IO (Vector R, R, [(R, R)])\ntrainLinRegWNoise target n noiselevel transformFunction = do\n trainpoints <- createRandomPoints n\n let trainX = transformFunction trainpoints\n let trainY = createVectorY target trainpoints\n trainYNoisy <- flipLabels noiselevel trainY\n let weights = linearRegressionWeight trainX trainYNoisy\n let inSampleError = linRegClassificationError trainX trainYNoisy weights\n return (weights, inSampleError, trainpoints)\n\n-- | training linear Regression on random dataset of n noiseless points and returning (weights, in-Sample error, trainingpoints)\ntrainLinReg ::\n (R -> R) -> Int -> ([(R, R)] -> Matrix R) -> IO (Vector R, R, [(R, R)])\ntrainLinReg target n transformFunction =\n trainLinRegWNoise (y target) n 0 transformFunction\n\n-- | evaluates linear Regression result on test data\ntestLinReg :: (R -> R) -> Int -> ([(R, R)] -> Matrix R) -> Vector R -> IO R\ntestLinReg target n transformFunction weights =\n testLinRegWNoise (y target) n 0 transformFunction weights\n\n-- | training linear Regression on random dataset of n noisy points and returning (weights, in-Sample error, trainingpoints)\ntestLinRegWNoise ::\n ((R, R) -> R) -> Int -> Float -> ([(R, R)] -> Matrix R) -> Vector R -> IO R\ntestLinRegWNoise target n noiselevel transformFunction weights = do\n testpoints <- createRandomPoints n\n let testX = transformFunction testpoints\n let testY = createVectorY target testpoints\n testYNoisy <- flipLabels noiselevel testY\n let outOfSampleError = linRegClassificationError testX testYNoisy weights\n return outOfSampleError\n\n-- | performs training and testing\ntrainAndTestLinReg :: IO (R, R)\ntrainAndTestLinReg = do\n target <- makeTargetFunction\n (weights, inSampleError, _) <- trainLinReg target 100 createMatrixX\n outOfSampleError <- testLinReg target 1000 createMatrixX weights\n return (inSampleError, outOfSampleError)\n\n---------------------------------------------------------\n-- averaging several runs of the algorithm\n---------------------------------------------------------\n-- | average in a list of numbers\naverage :: [R] -> R\naverage xs = sum xs / fromIntegral (length xs)\n\n-- | average of in-sample and out-of-sample error, calculated from a list of pairs and returned as a pair.\naverageErrors :: [(R, R)] -> (R, R)\naverageErrors pairs = (avFst, avSnd)\n where\n avFst = average $ map fst pairs\n avSnd = average $ map snd pairs\n\n-- |pair of average in-sample and out-of-sample error in n runs of linear Regression on n different sets of points\navError :: Int -> IO ()\navError n =\n putStrLn . (\"In-sample error, out-of-sample error: \" ++) . show =<<\n fmap averageErrors (replicateM n trainAndTestLinReg)\n\n----------------------------------------------\n-- Using linear regression to obtain initial weights for perceptron\n--------------------------------------------------\nlistToTuple :: [a] -> Maybe (a, a, a)\nlistToTuple (x:y:z:xs) = Just (x, y, z)\nlistToTuple _ = Nothing\n\n-- | trains a perceptron wiht initial weights obtained by linear Regression\nlinRegAsInitialForPLA :: IO ()\nlinRegAsInitialForPLA = do\n target <- makeTargetFunction\n (initialweightsVec, _, trainPoints) <- trainLinReg target 10 createMatrixX\n let maybeInitialWeights = listToTuple $ toList initialweightsVec\n let initialWeights = fromMaybe (0, 0, 0) maybeInitialWeights\n (finalWeights, epochs) <-\n trainPLAWithInitial initialWeights trainPoints target\n putStr \"Weights: \"\n print finalWeights\n putStr \"Epochs: \"\n print epochs\n", "meta": {"hexsha": "3de7b4c7808ae46b94199a3d75f2ac025e9676ed", "size": 8382, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/hw2/LinearRegression.hs", "max_stars_repo_name": "AR2202/LearningFromData", "max_stars_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T06:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T06:07:24.000Z", "max_issues_repo_path": "src/hw2/LinearRegression.hs", "max_issues_repo_name": "AR2202/LearningFromData", "max_issues_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hw2/LinearRegression.hs", "max_forks_repo_name": "AR2202/LearningFromData", "max_forks_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.92760181, "max_line_length": 128, "alphanum_fraction": 0.6329038416, "num_tokens": 2128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6751275308231236}} {"text": "import Numeric.LinearAlgebra\nimport ActivationFunction\nimport Mnist\nimport SampleWeight\n\nbatchSize = 100\n\npredict :: SampleWeight -> Vector R -> Vector R\npredict ([w1,w2,w3],[b1,b2,b3]) x =\n softMax' . (\\x'' -> sumInput x'' w3 b3) . sigmoid . (\\x' -> sumInput x' w2 b2) . sigmoid $ sumInput x w1 b1\n\nsumInput :: Vector R -> Weight -> Bias -> Vector R\nsumInput x w b = (x <# w) + b\n\nmaxIndexPredict :: SampleWeight -> Vector R -> Double\nmaxIndexPredict sw x = fromIntegral . maxIndex $ predict sw x\n\ntake' :: Indexable c t => Int -> Int -> c -> [t]\ntake' n1 n2 x\n | n1 >= n2 = []\n | otherwise = (x ! n1) : take' (n1+1) n2 x\n\nincrement :: [Double] -> [Double] -> Double\nincrement ps l = fromIntegral . length . filter id $ zipWith (==) ps l\n\ncountAccuracy :: Double -> Int -> SampleWeight -> DataSet -> Double\ncountAccuracy a n sw ds@(i,l)\n | n <= 0 = a\n | otherwise =\n if maxIndexPredict sw (i ! (n-1)) == l ! (n-1)\n then countAccuracy (a+1) (n-1) sw ds\n else countAccuracy a (n-1) sw ds\n\n-- For batch\ncountAccuracy' :: Double -> Int -> SampleWeight -> DataSet -> Double\ncountAccuracy' a n sw ds@(i,l)\n | n <= 0 = a\n | otherwise = countAccuracy' (a+cnt) (n-batchSize) sw ds\n where ps = maxIndexPredict sw <$> take' (n-batchSize) n i\n ls = take' (n-batchSize) n l\n cnt = increment ps ls\n\nmain = do\n [_, ds] <- loadMnist True\n sw <- loadSW\n let r = rows $ fst ds\n cnt = countAccuracy' 0 r sw ds\n\n putStrLn $ \"Accuracy: \" ++ show (cnt / fromIntegral r)\n", "meta": {"hexsha": "f115b3f49e09ce344248c4d0d2711fbc58176424", "size": 1548, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NeuralnetMnist.hs", "max_stars_repo_name": "ku00/deep-learning-practice", "max_stars_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-03T05:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T05:32:58.000Z", "max_issues_repo_path": "src/NeuralnetMnist.hs", "max_issues_repo_name": "ku00/deep-learning-practice", "max_issues_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NeuralnetMnist.hs", "max_forks_repo_name": "ku00/deep-learning-practice", "max_forks_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.96, "max_line_length": 111, "alphanum_fraction": 0.5949612403, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6749492063096248}} {"text": "{-# LANGUAGE ViewPatterns #-}\n-- |\n-- Module : Statistics.Test.WilcoxonT\n-- Copyright : (c) 2010 Neil Brown\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The Wilcoxon matched-pairs signed-rank test is non-parametric test\n-- which could be used to test whether two related samples have\n-- different means.\nmodule Statistics.Test.WilcoxonT (\n -- * Wilcoxon signed-rank matched-pair test\n -- ** Test\n wilcoxonMatchedPairTest\n -- ** Building blocks\n , wilcoxonMatchedPairSignedRank\n , wilcoxonMatchedPairSignificant\n , wilcoxonMatchedPairSignificance\n , wilcoxonMatchedPairCriticalValue\n , module Statistics.Test.Types\n -- * References\n -- $references\n ) where\n\n\n\n--\n--\n--\n-- Note that: wilcoxonMatchedPairSignedRank == (\\(x, y) -> (y, x)) . flip wilcoxonMatchedPairSignedRank\n-- The samples are zipped together: if one is longer than the other, both are truncated\n-- The value returned is the pair (T+, T-). T+ is the sum of positive ranks (the\n-- These values mean little by themselves, and should be combined with the 'wilcoxonSignificant'\n-- function in this module to get a meaningful result.\n-- ranks of the differences where the first parameter is higher) whereas T- is\n-- the sum of negative ranks (the ranks of the differences where the second parameter is higher).\n-- to the length of the shorter sample.\n\nimport Data.Function (on)\nimport Data.List (findIndex)\nimport Data.Ord (comparing)\nimport qualified Data.Vector.Unboxed as U\nimport Prelude hiding (sum)\nimport Statistics.Function (sortBy)\nimport Statistics.Sample.Internal (sum)\nimport Statistics.Test.Internal (rank, splitByTags)\nimport Statistics.Test.Types\nimport Statistics.Types -- (CL,pValue,getPValue)\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\n\n\n-- | Calculate (n,T⁺,T⁻) values for both samples. Where /n/ is reduced\n-- sample where equal pairs are removed.\nwilcoxonMatchedPairSignedRank :: (Ord a, Num a, U.Unbox a) => U.Vector (a,a) -> (Int, Double, Double)\nwilcoxonMatchedPairSignedRank ab\n = (nRed, sum ranks1, negate (sum ranks2))\n where\n -- Positive and negative ranks\n (ranks1, ranks2) = splitByTags\n $ U.zip tags (rank ((==) `on` abs) diffs)\n -- Sorted list of differences\n diffsSorted = sortBy (comparing abs) -- Sort the differences by absolute difference\n $ U.filter (/= 0) -- Remove equal elements\n $ U.map (uncurry (-)) ab -- Work out differences\n nRed = U.length diffsSorted\n -- Sign tags and differences\n (tags,diffs) = U.unzip\n $ U.map (\\x -> (x>0 , x)) -- Attach tags to distribution elements\n $ diffsSorted\n\n\n\n-- | The coefficients for x^0, x^1, x^2, etc, in the expression\n-- \\prod_{r=1}^s (1 + x^r). See the Mitic paper for details.\n--\n-- We can define:\n-- f(1) = 1 + x\n-- f(r) = (1 + x^r)*f(r-1)\n-- = f(r-1) + x^r * f(r-1)\n-- The effect of multiplying the equation by x^r is to shift\n-- all the coefficients by r down the list.\n--\n-- This list will be processed lazily from the head.\ncoefficients :: Int -> [Integer]\ncoefficients 1 = [1, 1] -- 1 + x\ncoefficients r = let coeffs = coefficients (r-1)\n (firstR, rest) = splitAt r coeffs\n in firstR ++ add rest coeffs\n where\n add (x:xs) (y:ys) = x + y : add xs ys\n add xs [] = xs\n add [] ys = ys\n\n-- This list will be processed lazily from the head.\nsummedCoefficients :: Int -> [Double]\nsummedCoefficients n\n | n < 1 = error \"Statistics.Test.WilcoxonT.summedCoefficients: nonpositive sample size\"\n | n > 1023 = error \"Statistics.Test.WilcoxonT.summedCoefficients: sample is too large (see bug #18)\"\n | otherwise = map fromIntegral $ scanl1 (+) $ coefficients n\n\n\n\n-- | Tests whether a given result from a Wilcoxon signed-rank matched-pairs test\n-- is significant at the given level.\n--\n-- This function can perform a one-tailed or two-tailed test. If the first\n-- parameter to this function is 'TwoTailed', the test is performed two-tailed to\n-- check if the two samples differ significantly. If the first parameter is\n-- 'OneTailed', the check is performed one-tailed to decide whether the first sample\n-- (i.e. the first sample you passed to 'wilcoxonMatchedPairSignedRank') is\n-- greater than the second sample (i.e. the second sample you passed to\n-- 'wilcoxonMatchedPairSignedRank'). If you wish to perform a one-tailed test\n-- in the opposite direction, you can either pass the parameters in a different\n-- order to 'wilcoxonMatchedPairSignedRank', or simply swap the values in the resulting\n-- pair before passing them to this function.\nwilcoxonMatchedPairSignificant\n :: PositionTest -- ^ How to compare two samples\n -> PValue Double -- ^ The p-value at which to test (e.g. @mkPValue 0.05@)\n -> (Int, Double, Double) -- ^ The (n,T⁺, T⁻) values from 'wilcoxonMatchedPairSignedRank'.\n -> Maybe TestResult -- ^ Return 'Nothing' if the sample was too\n -- small to make a decision.\nwilcoxonMatchedPairSignificant test pVal (sampleSize, tPlus, tMinus) =\n case test of\n -- According to my nearest book (Understanding Research Methods and Statistics\n -- by Gary W. Heiman, p590), to check that the first sample is bigger you must\n -- use the absolute value of T- for a one-tailed check:\n AGreater -> do crit <- wilcoxonMatchedPairCriticalValue sampleSize pVal\n return $ significant $ abs tMinus <= fromIntegral crit\n BGreater -> do crit <- wilcoxonMatchedPairCriticalValue sampleSize pVal\n return $ significant $ abs tPlus <= fromIntegral crit\n -- Otherwise you must use the value of T+ and T- with the smallest absolute value:\n --\n -- Note that in absence of ties sum of |T+| and |T-| is constant\n -- so by selecting minimal we are performing two-tailed test and\n -- look and both tails of distribution of T.\n SamplesDiffer -> do crit <- wilcoxonMatchedPairCriticalValue sampleSize (mkPValue $ p/2)\n return $ significant $ t <= fromIntegral crit\n where\n t = min (abs tPlus) (abs tMinus)\n p = pValue pVal\n\n\n-- | Obtains the critical value of T to compare against, given a sample size\n-- and a p-value (significance level). Your T value must be less than or\n-- equal to the return of this function in order for the test to work out\n-- significant. If there is a Nothing return, the sample size is too small to\n-- make a decision.\n--\n-- 'wilcoxonSignificant' tests the return value of 'wilcoxonMatchedPairSignedRank'\n-- for you, so you should use 'wilcoxonSignificant' for determining test results.\n-- However, this function is useful, for example, for generating lookup tables\n-- for Wilcoxon signed rank critical values.\n--\n-- The return values of this function are generated using the method\n-- detailed in the Mitic's paper. According to that paper, the results\n-- may differ from other published lookup tables, but (Mitic claims)\n-- the values obtained by this function will be the correct ones.\nwilcoxonMatchedPairCriticalValue ::\n Int -- ^ The sample size\n -> PValue Double -- ^ The p-value (e.g. @mkPValue 0.05@) for which you want the critical value.\n -> Maybe Int -- ^ The critical value (of T), or Nothing if\n -- the sample is too small to make a decision.\nwilcoxonMatchedPairCriticalValue n pVal\n | n < 100 =\n case subtract 1 <$> findIndex (> m) (summedCoefficients n) of\n Just k | k < 0 -> Nothing\n | otherwise -> Just k\n Nothing -> error \"Statistics.Test.WilcoxonT.wilcoxonMatchedPairCriticalValue: impossible happened\"\n | otherwise =\n case quantile (normalApprox n) p of\n z | z < 0 -> Nothing\n | otherwise -> Just (round z)\n where\n p = pValue pVal\n m = (2 ** fromIntegral n) * p\n\n\n-- | Works out the significance level (p-value) of a T value, given a sample\n-- size and a T value from the Wilcoxon signed-rank matched-pairs test.\n--\n-- See the notes on 'wilcoxonCriticalValue' for how this is calculated.\nwilcoxonMatchedPairSignificance\n :: Int -- ^ The sample size\n -> Double -- ^ The value of T for which you want the significance.\n -> PValue Double -- ^ The significance (p-value).\nwilcoxonMatchedPairSignificance n t\n = mkPValue p\n where\n p | n < 100 = (summedCoefficients n !! floor t) / 2 ** fromIntegral n\n | otherwise = cumulative (normalApprox n) t\n\n\n-- | Normal approximation for Wilcoxon T statistics\nnormalApprox :: Int -> NormalDistribution\nnormalApprox ni\n = normalDistr m s\n where\n m = n * (n + 1) / 4\n s = sqrt $ (n * (n + 1) * (2*n + 1)) / 24\n n = fromIntegral ni\n\n\n-- | The Wilcoxon matched-pairs signed-rank test. The samples are\n-- zipped together: if one is longer than the other, both are\n-- truncated to the length of the shorter sample.\n--\n-- For one-tailed test it tests whether first sample is significantly\n-- greater than the second. For two-tailed it checks whether they\n-- significantly differ\n--\n-- Check 'wilcoxonMatchedPairSignedRank' and\n-- 'wilcoxonMatchedPairSignificant' for additional information.\nwilcoxonMatchedPairTest\n :: (Ord a, Num a, U.Unbox a)\n => PositionTest -- ^ Perform one-tailed test.\n -> U.Vector (a,a) -- ^ Sample of pairs\n -> Test () -- ^ Return 'Nothing' if the sample was too\n -- small to make a decision.\nwilcoxonMatchedPairTest test pairs =\n Test { testSignificance = pVal\n , testStatistics = t\n , testDistribution = ()\n }\n where\n (n,tPlus,tMinus) = wilcoxonMatchedPairSignedRank pairs\n (t,pVal) = case test of\n AGreater -> (abs tMinus, wilcoxonMatchedPairSignificance n (abs tMinus))\n BGreater -> (abs tPlus, wilcoxonMatchedPairSignificance n (abs tPlus ))\n -- Since we take minimum of T+,T- we can't get more\n -- that p=0.5 and can multiply it by 2 without risk\n -- of error.\n SamplesDiffer -> let t' = min (abs tMinus) (abs tPlus)\n p = wilcoxonMatchedPairSignificance n t'\n in (t', mkPValue $ min 1 $ 2 * pValue p)\n\n\n-- $references\n--\n-- * \\\"Critical Values for the Wilcoxon Signed Rank Statistic\\\", Peter\n-- Mitic, The Mathematica Journal, volume 6, issue 3, 1996\n-- ()\n", "meta": {"hexsha": "b2bf6e5233f2db4db80d159694cc3e49f705f598", "size": 10571, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Test/WilcoxonT.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/Test/WilcoxonT.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/Test/WilcoxonT.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": 42.9715447154, "max_line_length": 107, "alphanum_fraction": 0.6699460789, "num_tokens": 2810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6746508305711589}} {"text": "module Grid\n ( Grid\n , standardInterval\n , makeInterval\n , startOfInterval\n , endOfInterval\n , elementSize\n , nElements\n ) where\n\nimport Numeric.LinearAlgebra (R)\n\ndata Grid = Grid R R R Int\n deriving (Eq, Show)\n\nstandardInterval :: Grid\nstandardInterval = makeInterval 0.0 1.0 10\n\n-- | Specify a 1D Intervall [start, end]\nmakeInterval :: R -> R -> Int -> Grid\nmakeInterval start end n\n | start < end && n > 0 = Grid start end ((end - start) / fromIntegral n) n\n | otherwise = undefined\n\nstartOfInterval :: Grid -> R\nstartOfInterval (Grid start _ _ _) = start\n\nendOfInterval :: Grid -> R\nendOfInterval (Grid _ end _ _) = end\n\nelementSize :: Grid -> R\nelementSize (Grid _ _ h _) = h\n\nnElements :: Grid -> Int\nnElements (Grid _ _ _ n) = n\n", "meta": {"hexsha": "ab364aa881a3a9419a8f78972d7dbc793c099ef9", "size": 764, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grid.hs", "max_stars_repo_name": "bschwb/haskfem", "max_stars_repo_head_hexsha": "2f32413ddbbc95e30f6df7fce005c29618eeb528", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-08-26T23:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T01:23:11.000Z", "max_issues_repo_path": "src/Grid.hs", "max_issues_repo_name": "bschwb/haskfem", "max_issues_repo_head_hexsha": "2f32413ddbbc95e30f6df7fce005c29618eeb528", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grid.hs", "max_forks_repo_name": "bschwb/haskfem", "max_forks_repo_head_hexsha": "2f32413ddbbc95e30f6df7fce005c29618eeb528", "max_forks_repo_licenses": ["BSD-3-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.2222222222, "max_line_length": 76, "alphanum_fraction": 0.6609947644, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.673684576855708}} {"text": "{-# OPTIONS_GHC -Wall #-}\n\n-- | A magma heirarchy for multiplication. The basic magma structure is repeated and prefixed with 'Multiplicative-'.\nmodule Plankton.Multiplicative\n ( MultiplicativeMagma(..)\n , MultiplicativeUnital(..)\n , MultiplicativeAssociative\n , MultiplicativeCommutative\n , MultiplicativeInvertible(..)\n , product\n , Multiplicative(..)\n , MultiplicativeRightCancellative(..)\n , MultiplicativeLeftCancellative(..)\n , MultiplicativeGroup(..)\n ) where\n\nimport Data.Complex (Complex(..))\nimport Plankton.Additive\nimport qualified Protolude as P\nimport Protolude (Bool(..), Double, Float, Int, Integer)\n\n-- | 'times' is used as the operator for the multiplicative magam to distinguish from '*' which, by convention, implies commutativity\n--\n-- > ∀ a,b ∈ A: a `times` b ∈ A\n--\n-- law is true by construction in Haskell\nclass MultiplicativeMagma a where\n times :: a -> a -> a\n\ninstance MultiplicativeMagma Double where\n times = (P.*)\n\ninstance MultiplicativeMagma Float where\n times = (P.*)\n\ninstance MultiplicativeMagma Int where\n times = (P.*)\n\ninstance MultiplicativeMagma Integer where\n times = (P.*)\n\ninstance MultiplicativeMagma Bool where\n times = (P.&&)\n\ninstance (MultiplicativeMagma a, AdditiveGroup a) =>\n MultiplicativeMagma (Complex a) where\n (rx :+ ix) `times` (ry :+ iy) =\n (rx `times` ry - ix `times` iy) :+ (ix `times` ry + iy `times` rx)\n\n-- | Unital magma for multiplication.\n--\n-- > one `times` a == a\n-- > a `times` one == a\nclass MultiplicativeMagma a =>\n MultiplicativeUnital a where\n one :: a\n\ninstance MultiplicativeUnital Double where\n one = 1\n\ninstance MultiplicativeUnital Float where\n one = 1\n\ninstance MultiplicativeUnital Int where\n one = 1\n\ninstance MultiplicativeUnital Integer where\n one = 1\n\ninstance MultiplicativeUnital Bool where\n one = True\n\ninstance (AdditiveUnital a, AdditiveGroup a, MultiplicativeUnital a) =>\n MultiplicativeUnital (Complex a) where\n one = one :+ zero\n\n-- | Associative magma for multiplication.\n--\n-- > (a `times` b) `times` c == a `times` (b `times` c)\nclass MultiplicativeMagma a =>\n MultiplicativeAssociative a\n\ninstance MultiplicativeAssociative Double\n\ninstance MultiplicativeAssociative Float\n\ninstance MultiplicativeAssociative Int\n\ninstance MultiplicativeAssociative Integer\n\ninstance MultiplicativeAssociative Bool\n\ninstance (AdditiveGroup a, MultiplicativeAssociative a) =>\n MultiplicativeAssociative (Complex a)\n\n-- | Commutative magma for multiplication.\n--\n-- > a `times` b == b `times` a\nclass MultiplicativeMagma a =>\n MultiplicativeCommutative a\n\ninstance MultiplicativeCommutative Double\n\ninstance MultiplicativeCommutative Float\n\ninstance MultiplicativeCommutative Int\n\ninstance MultiplicativeCommutative Integer\n\ninstance MultiplicativeCommutative Bool\n\ninstance (AdditiveGroup a, MultiplicativeCommutative a) =>\n MultiplicativeCommutative (Complex a)\n\n-- | Invertible magma for multiplication.\n--\n-- > ∀ a ∈ A: recip a ∈ A\n--\n-- law is true by construction in Haskell\nclass MultiplicativeMagma a =>\n MultiplicativeInvertible a where\n recip :: a -> a\n\ninstance MultiplicativeInvertible Double where\n recip = P.recip\n\ninstance MultiplicativeInvertible Float where\n recip = P.recip\n\ninstance (AdditiveGroup a, MultiplicativeInvertible a) =>\n MultiplicativeInvertible (Complex a) where\n recip (rx :+ ix) = (rx `times` d) :+ (negate ix `times` d)\n where\n d = recip ((rx `times` rx) `plus` (ix `times` ix))\n\n-- | Idempotent magma for multiplication.\n--\n-- > a `times` a == a\nclass MultiplicativeMagma a =>\n MultiplicativeIdempotent a\n\ninstance MultiplicativeIdempotent Bool\n\n-- | product definition avoiding a clash with the Product monoid in base\n--\nproduct :: (Multiplicative a, P.Foldable f) => f a -> a\nproduct = P.foldr (*) one\n\n-- | Multiplicative is commutative, associative and unital under multiplication\n--\n-- > one * a == a\n-- > a * one == a\n-- > (a * b) * c == a * (b * c)\n-- > a * b == b * a\nclass ( MultiplicativeCommutative a\n , MultiplicativeUnital a\n , MultiplicativeAssociative a\n ) =>\n Multiplicative a where\n infixl 7 *\n (*) :: a -> a -> a\n a * b = times a b\n\ninstance Multiplicative Double\n\ninstance Multiplicative Float\n\ninstance Multiplicative Int\n\ninstance Multiplicative Integer\n\ninstance Multiplicative Bool\n\ninstance (AdditiveGroup a, Multiplicative a) => Multiplicative (Complex a)\n\n-- | Non-commutative left divide\n--\n-- > recip a `times` a = one\nclass ( MultiplicativeUnital a\n , MultiplicativeAssociative a\n , MultiplicativeInvertible a\n ) =>\n MultiplicativeLeftCancellative a where\n infixl 7 ~/\n (~/) :: a -> a -> a\n a ~/ b = recip b `times` a\n\n-- | Non-commutative right divide\n--\n-- > a `times` recip a = one\nclass ( MultiplicativeUnital a\n , MultiplicativeAssociative a\n , MultiplicativeInvertible a\n ) =>\n MultiplicativeRightCancellative a where\n infixl 7 /~\n (/~) :: a -> a -> a\n a /~ b = a `times` recip b\n\n-- | Divide ('/') is reserved for where both the left and right cancellative laws hold. This then implies that the MultiplicativeGroup is also Abelian.\n--\n-- > a / a = one\n-- > recip a = one / a\n-- > recip a * a = one\n-- > a * recip a = one\nclass (Multiplicative a, MultiplicativeInvertible a) =>\n MultiplicativeGroup a where\n infixl 7 /\n (/) :: a -> a -> a\n (/) a b = a `times` recip b\n\ninstance MultiplicativeGroup Double\n\ninstance MultiplicativeGroup Float\n\ninstance (AdditiveGroup a, MultiplicativeGroup a) =>\n MultiplicativeGroup (Complex a)\n", "meta": {"hexsha": "b7d88442f37d1a5b6310b90d818b01b24579d164", "size": 5569, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Plankton/Multiplicative.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/Multiplicative.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/Multiplicative.hs", "max_forks_repo_name": "chessai/plankton", "max_forks_repo_head_hexsha": "01cf52cf962aa24c42bd0065903902cc19686fb4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5458715596, "max_line_length": 152, "alphanum_fraction": 0.7024600467, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6736845601920485}} {"text": "{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE TypeFamilies #-}\n\n-----------------------------------------------------------------------------\n{- |\nModule : Numeric.LinearAlgebra.Algorithms\nCopyright : (c) Alberto Ruiz 2006-9\nLicense : GPL-style\n\nMaintainer : Alberto Ruiz (aruiz at um dot es)\nStability : provisional\nPortability : uses ffi\n\nHigh level generic interface to common matrix computations.\n\nSpecific functions for particular base types can also be explicitly\nimported from \"Numeric.LinearAlgebra.LAPACK\".\n\n-}\n-----------------------------------------------------------------------------\n\nmodule Numeric.LinearAlgebra.Algorithms (\n-- * Supported types\n Field(),\n-- * Linear Systems\n linearSolve,\n luSolve,\n cholSolve,\n linearSolveLS,\n linearSolveSVD,\n inv, pinv,\n det, invlndet,\n rank, rcond,\n-- * Matrix factorizations\n-- ** Singular value decomposition\n svd,\n fullSVD,\n thinSVD,\n compactSVD,\n singularValues,\n leftSV, rightSV,\n-- ** Eigensystems\n eig, eigSH, eigSH',\n eigenvalues, eigenvaluesSH, eigenvaluesSH',\n geigSH',\n-- ** QR\n qr, rq,\n-- ** Cholesky\n chol, cholSH, mbCholSH,\n-- ** Hessenberg\n hess,\n-- ** Schur\n schur,\n-- ** LU\n lu, luPacked,\n-- * Matrix functions\n expm,\n sqrtm,\n matFunc,\n-- * Nullspace\n nullspacePrec,\n nullVector,\n nullspaceSVD,\n orth,\n-- * Norms\n Normed(..), NormType(..),\n relativeError,\n-- * Misc\n eps, peps, i,\n-- * Util\n haussholder,\n unpackQR, unpackHess,\n pinvTol,\n ranksv\n) where\n\n\nimport Data.Packed.Internal hiding ((//))\nimport Data.Packed.Matrix\nimport Numeric.LinearAlgebra.LAPACK as LAPACK\nimport Data.List(foldl1')\nimport Data.Array\nimport Numeric.ContainerBoot\n\n\n{- | Class used to define generic linear algebra computations for both real and complex matrices. Only double precision is supported in this version (we can\ntransform single precision objects using 'single' and 'double').\n\n-}\nclass (Product t,\n Convert t,\n Container Vector t,\n Container Matrix t,\n Normed Matrix t,\n Normed Vector t) => Field t where\n svd' :: Matrix t -> (Matrix t, Vector Double, Matrix t)\n thinSVD' :: Matrix t -> (Matrix t, Vector Double, Matrix t)\n sv' :: Matrix t -> Vector Double\n luPacked' :: Matrix t -> (Matrix t, [Int])\n luSolve' :: (Matrix t, [Int]) -> Matrix t -> Matrix t\n linearSolve' :: Matrix t -> Matrix t -> Matrix t\n cholSolve' :: Matrix t -> Matrix t -> Matrix t\n linearSolveSVD' :: Matrix t -> Matrix t -> Matrix t\n linearSolveLS' :: Matrix t -> Matrix t -> Matrix t\n eig' :: Matrix t -> (Vector (Complex Double), Matrix (Complex Double))\n eigSH'' :: Matrix t -> (Vector Double, Matrix t)\n eigOnly :: Matrix t -> Vector (Complex Double)\n eigOnlySH :: Matrix t -> Vector Double\n cholSH' :: Matrix t -> Matrix t\n mbCholSH' :: Matrix t -> Maybe (Matrix t)\n qr' :: Matrix t -> (Matrix t, Matrix t)\n hess' :: Matrix t -> (Matrix t, Matrix t)\n schur' :: Matrix t -> (Matrix t, Matrix t)\n\n\ninstance Field Double where\n svd' = svdRd\n thinSVD' = thinSVDRd\n sv' = svR\n luPacked' = luR\n luSolve' (l_u,perm) = lusR l_u perm\n linearSolve' = linearSolveR -- (luSolve . luPacked) ??\n cholSolve' = cholSolveR\n linearSolveLS' = linearSolveLSR\n linearSolveSVD' = linearSolveSVDR Nothing\n eig' = eigR\n eigSH'' = eigS\n eigOnly = eigOnlyR\n eigOnlySH = eigOnlyS\n cholSH' = cholS\n mbCholSH' = mbCholS\n qr' = unpackQR . qrR\n hess' = unpackHess hessR\n schur' = schurR\n\ninstance Field (Complex Double) where\n#ifdef NOZGESDD\n svd' = svdC\n thinSVD' = thinSVDC\n#else\n svd' = svdCd\n thinSVD' = thinSVDCd\n#endif\n sv' = svC\n luPacked' = luC\n luSolve' (l_u,perm) = lusC l_u perm\n linearSolve' = linearSolveC\n cholSolve' = cholSolveC\n linearSolveLS' = linearSolveLSC\n linearSolveSVD' = linearSolveSVDC Nothing\n eig' = eigC\n eigOnly = eigOnlyC\n eigSH'' = eigH\n eigOnlySH = eigOnlyH\n cholSH' = cholH\n mbCholSH' = mbCholH\n qr' = unpackQR . qrC\n hess' = unpackHess hessC\n schur' = schurC\n\n--------------------------------------------------------------\n\nsquare m = rows m == cols m\n\nvertical m = rows m >= cols m\n\nexactHermitian m = m `equal` ctrans m\n\n--------------------------------------------------------------\n\n-- | Full singular value decomposition.\nsvd :: Field t => Matrix t -> (Matrix t, Vector Double, Matrix t)\nsvd = {-# SCC \"svd\" #-} svd'\n\n-- | A version of 'svd' which returns only the @min (rows m) (cols m)@ singular vectors of @m@.\n--\n-- If @(u,s,v) = thinSVD m@ then @m == u \\<> diag s \\<> trans v@.\nthinSVD :: Field t => Matrix t -> (Matrix t, Vector Double, Matrix t)\nthinSVD = {-# SCC \"thinSVD\" #-} thinSVD'\n\n-- | Singular values only.\nsingularValues :: Field t => Matrix t -> Vector Double\nsingularValues = {-# SCC \"singularValues\" #-} sv'\n\n-- | A version of 'svd' which returns an appropriate diagonal matrix with the singular values.\n--\n-- If @(u,d,v) = fullSVD m@ then @m == u \\<> d \\<> trans v@.\nfullSVD :: Field t => Matrix t -> (Matrix t, Matrix Double, Matrix t)\nfullSVD m = (u,d,v) where\n (u,s,v) = svd m\n d = diagRect 0 s r c\n r = rows m\n c = cols m\n\n-- | Similar to 'thinSVD', returning only the nonzero singular values and the corresponding singular vectors.\ncompactSVD :: Field t => Matrix t -> (Matrix t, Vector Double, Matrix t)\ncompactSVD m = (u', subVector 0 d s, v') where\n (u,s,v) = thinSVD m\n d = rankSVD (1*eps) m s `max` 1\n u' = takeColumns d u\n v' = takeColumns d v\n\n\n-- | Singular values and all right singular vectors.\nrightSV :: Field t => Matrix t -> (Vector Double, Matrix t)\nrightSV m | vertical m = let (_,s,v) = thinSVD m in (s,v)\n | otherwise = let (_,s,v) = svd m in (s,v)\n\n-- | Singular values and all left singular vectors.\nleftSV :: Field t => Matrix t -> (Matrix t, Vector Double)\nleftSV m | vertical m = let (u,s,_) = svd m in (u,s)\n | otherwise = let (u,s,_) = thinSVD m in (u,s)\n\n\n--------------------------------------------------------------\n\n-- | Obtains the LU decomposition of a matrix in a compact data structure suitable for 'luSolve'.\nluPacked :: Field t => Matrix t -> (Matrix t, [Int])\nluPacked = {-# SCC \"luPacked\" #-} luPacked'\n\n-- | Solution of a linear system (for several right hand sides) from the precomputed LU factorization obtained by 'luPacked'.\nluSolve :: Field t => (Matrix t, [Int]) -> Matrix t -> Matrix t\nluSolve = {-# SCC \"luSolve\" #-} luSolve'\n\n-- | Solve a linear system (for square coefficient matrix and several right-hand sides) using the LU decomposition. For underconstrained or overconstrained systems use 'linearSolveLS' or 'linearSolveSVD'.\n-- It is similar to 'luSolve' . 'luPacked', but @linearSolve@ raises an error if called on a singular system.\nlinearSolve :: Field t => Matrix t -> Matrix t -> Matrix t\nlinearSolve = {-# SCC \"linearSolve\" #-} linearSolve'\n\n-- | Solve a symmetric or Hermitian positive definite linear system using a precomputed Cholesky decomposition obtained by 'chol'.\ncholSolve :: Field t => Matrix t -> Matrix t -> Matrix t\ncholSolve = {-# SCC \"cholSolve\" #-} cholSolve'\n\n-- | Minimum norm solution of a general linear least squares problem Ax=B using the SVD. Admits rank-deficient systems but it is slower than 'linearSolveLS'. The effective rank of A is determined by treating as zero those singular valures which are less than 'eps' times the largest singular value.\nlinearSolveSVD :: Field t => Matrix t -> Matrix t -> Matrix t\nlinearSolveSVD = {-# SCC \"linearSolveSVD\" #-} linearSolveSVD'\n\n\n-- | Least squared error solution of an overconstrained linear system, or the minimum norm solution of an underconstrained system. For rank-deficient systems use 'linearSolveSVD'.\nlinearSolveLS :: Field t => Matrix t -> Matrix t -> Matrix t\nlinearSolveLS = {-# SCC \"linearSolveLS\" #-} linearSolveLS'\n\n--------------------------------------------------------------\n\n-- | Eigenvalues and eigenvectors of a general square matrix.\n--\n-- If @(s,v) = eig m@ then @m \\<> v == v \\<> diag s@\neig :: Field t => Matrix t -> (Vector (Complex Double), Matrix (Complex Double))\neig = {-# SCC \"eig\" #-} eig'\n\n-- | Eigenvalues of a general square matrix.\neigenvalues :: Field t => Matrix t -> Vector (Complex Double)\neigenvalues = {-# SCC \"eigenvalues\" #-} eigOnly\n\n-- | Similar to 'eigSH' without checking that the input matrix is hermitian or symmetric. It works with the upper triangular part.\neigSH' :: Field t => Matrix t -> (Vector Double, Matrix t)\neigSH' = {-# SCC \"eigSH'\" #-} eigSH''\n\n-- | Similar to 'eigenvaluesSH' without checking that the input matrix is hermitian or symmetric. It works with the upper triangular part.\neigenvaluesSH' :: Field t => Matrix t -> Vector Double\neigenvaluesSH' = {-# SCC \"eigenvaluesSH'\" #-} eigOnlySH\n\n-- | Eigenvalues and Eigenvectors of a complex hermitian or real symmetric matrix.\n--\n-- If @(s,v) = eigSH m@ then @m == v \\<> diag s \\<> ctrans v@\neigSH :: Field t => Matrix t -> (Vector Double, Matrix t)\neigSH m | exactHermitian m = eigSH' m\n | otherwise = error \"eigSH requires complex hermitian or real symmetric matrix\"\n\n-- | Eigenvalues of a complex hermitian or real symmetric matrix.\neigenvaluesSH :: Field t => Matrix t -> Vector Double\neigenvaluesSH m | exactHermitian m = eigenvaluesSH' m\n | otherwise = error \"eigenvaluesSH requires complex hermitian or real symmetric matrix\"\n\n--------------------------------------------------------------\n\n-- | QR factorization.\n--\n-- If @(q,r) = qr m@ then @m == q \\<> r@, where q is unitary and r is upper triangular.\nqr :: Field t => Matrix t -> (Matrix t, Matrix t)\nqr = {-# SCC \"qr\" #-} qr'\n\n-- | RQ factorization.\n--\n-- If @(r,q) = rq m@ then @m == r \\<> q@, where q is unitary and r is upper triangular.\nrq :: Field t => Matrix t -> (Matrix t, Matrix t)\nrq m = {-# SCC \"rq\" #-} (r,q) where\n (q',r') = qr $ trans $ rev1 m\n r = rev2 (trans r')\n q = rev2 (trans q')\n rev1 = flipud . fliprl\n rev2 = fliprl . flipud\n\n-- | Hessenberg factorization.\n--\n-- If @(p,h) = hess m@ then @m == p \\<> h \\<> ctrans p@, where p is unitary\n-- and h is in upper Hessenberg form (it has zero entries below the first subdiagonal).\nhess :: Field t => Matrix t -> (Matrix t, Matrix t)\nhess = hess'\n\n-- | Schur factorization.\n--\n-- If @(u,s) = schur m@ then @m == u \\<> s \\<> ctrans u@, where u is unitary\n-- and s is a Shur matrix. A complex Schur matrix is upper triangular. A real Schur matrix is\n-- upper triangular in 2x2 blocks.\n--\n-- \\\"Anything that the Jordan decomposition can do, the Schur decomposition\n-- can do better!\\\" (Van Loan)\nschur :: Field t => Matrix t -> (Matrix t, Matrix t)\nschur = schur'\n\n\n-- | Similar to 'cholSH', but instead of an error (e.g., caused by a matrix not positive definite) it returns 'Nothing'.\nmbCholSH :: Field t => Matrix t -> Maybe (Matrix t)\nmbCholSH = {-# SCC \"mbCholSH\" #-} mbCholSH'\n\n-- | Similar to 'chol', without checking that the input matrix is hermitian or symmetric. It works with the upper triangular part.\ncholSH :: Field t => Matrix t -> Matrix t\ncholSH = {-# SCC \"cholSH\" #-} cholSH'\n\n-- | Cholesky factorization of a positive definite hermitian or symmetric matrix.\n--\n-- If @c = chol m@ then @c@ is upper triangular and @m == ctrans c \\<> c@.\nchol :: Field t => Matrix t -> Matrix t\nchol m | exactHermitian m = cholSH m\n | otherwise = error \"chol requires positive definite complex hermitian or real symmetric matrix\"\n\n\n-- | Joint computation of inverse and logarithm of determinant of a square matrix.\ninvlndet :: (Floating t, Field t)\n => Matrix t\n -> (Matrix t, (t, t)) -- ^ (inverse, (log abs det, sign or phase of det)) \ninvlndet m | square m = (im,(ladm,sdm))\n | otherwise = error $ \"invlndet of nonsquare \"++ shSize m ++ \" matrix\"\n where\n lp@(lup,perm) = luPacked m\n s = signlp (rows m) perm\n dg = toList $ takeDiag $ lup\n ladm = sum $ map (log.abs) dg\n sdm = s* product (map signum dg)\n im = luSolve lp (ident (rows m))\n\n\n-- | Determinant of a square matrix. To avoid possible overflow or underflow use 'invlndet'.\ndet :: Field t => Matrix t -> t\ndet m | square m = {-# SCC \"det\" #-} s * (product $ toList $ takeDiag $ lup)\n | otherwise = error $ \"det of nonsquare \"++ shSize m ++ \" matrix\"\n where (lup,perm) = luPacked m\n s = signlp (rows m) perm\n\n-- | Explicit LU factorization of a general matrix.\n--\n-- If @(l,u,p,s) = lu m@ then @m == p \\<> l \\<> u@, where l is lower triangular,\n-- u is upper triangular, p is a permutation matrix and s is the signature of the permutation.\nlu :: Field t => Matrix t -> (Matrix t, Matrix t, Matrix t, t)\nlu = luFact . luPacked\n\n-- | Inverse of a square matrix. See also 'invlndet'.\ninv :: Field t => Matrix t -> Matrix t\ninv m | square m = m `linearSolve` ident (rows m)\n | otherwise = error $ \"inv of nonsquare \"++ shSize m ++ \" matrix\"\n\n-- | Pseudoinverse of a general matrix.\npinv :: Field t => Matrix t -> Matrix t\npinv m = linearSolveSVD m (ident (rows m))\n\n-- | Numeric rank of a matrix from the SVD decomposition.\nrankSVD :: Element t\n => Double -- ^ numeric zero (e.g. 1*'eps')\n -> Matrix t -- ^ input matrix m\n -> Vector Double -- ^ 'sv' of m\n -> Int -- ^ rank of m\nrankSVD teps m s = ranksv teps (max (rows m) (cols m)) (toList s)\n\n-- | Numeric rank of a matrix from its singular values.\nranksv :: Double -- ^ numeric zero (e.g. 1*'eps')\n -> Int -- ^ maximum dimension of the matrix\n -> [Double] -- ^ singular values\n -> Int -- ^ rank of m\nranksv teps maxdim s = k where\n g = maximum s\n tol = fromIntegral maxdim * g * teps\n s' = filter (>tol) s\n k = if g > teps then length s' else 0\n\n-- | The machine precision of a Double: @eps = 2.22044604925031e-16@ (the value used by GNU-Octave).\neps :: Double\neps = 2.22044604925031e-16\n\n\n-- | 1 + 0.5*peps == 1, 1 + 0.6*peps /= 1\npeps :: RealFloat x => x\npeps = x where x = 2.0 ** fromIntegral (1 - floatDigits x)\n\n\n-- | The imaginary unit: @i = 0.0 :+ 1.0@\ni :: Complex Double\ni = 0:+1\n\n-----------------------------------------------------------------------\n\n-- | The nullspace of a matrix from its SVD decomposition.\nnullspaceSVD :: Field t\n => Either Double Int -- ^ Left \\\"numeric\\\" zero (eg. 1*'eps'),\n -- or Right \\\"theoretical\\\" matrix rank.\n -> Matrix t -- ^ input matrix m\n -> (Vector Double, Matrix t) -- ^ 'rightSV' of m\n -> [Vector t] -- ^ list of unitary vectors spanning the nullspace\nnullspaceSVD hint a (s,v) = vs where\n tol = case hint of\n Left t -> t\n _ -> eps\n k = case hint of\n Right t -> t\n _ -> rankSVD tol a s\n vs = drop k $ toRows $ ctrans v\n\n\n-- | The nullspace of a matrix. See also 'nullspaceSVD'.\nnullspacePrec :: Field t\n => Double -- ^ relative tolerance in 'eps' units (e.g., use 3 to get 3*'eps')\n -> Matrix t -- ^ input matrix\n -> [Vector t] -- ^ list of unitary vectors spanning the nullspace\nnullspacePrec t m = nullspaceSVD (Left (t*eps)) m (rightSV m)\n\n-- | The nullspace of a matrix, assumed to be one-dimensional, with machine precision.\nnullVector :: Field t => Matrix t -> Vector t\nnullVector = last . nullspacePrec 1\n\north :: Field t => Matrix t -> [Vector t]\n-- ^ Return an orthonormal basis of the range space of a matrix\north m = take r $ toColumns u\n where\n (u,s,_) = compactSVD m\n r = ranksv eps (max (rows m) (cols m)) (toList s)\n\n------------------------------------------------------------------------\n\n{- Pseudoinverse of a real matrix with the desired tolerance, expressed as a\nmultiplicative factor of the default tolerance used by GNU-Octave (see 'pinv').\n\n@\\> let m = 'fromLists' [[1,0, 0]\n ,[0,1, 0]\n ,[0,0,1e-10]]\n\\ --\n\\> 'pinv' m \n1. 0. 0.\n0. 1. 0.\n0. 0. 10000000000.\n\\ --\n\\> pinvTol 1E8 m\n1. 0. 0.\n0. 1. 0.\n0. 0. 1.@\n\n-}\n--pinvTol :: Double -> Matrix Double -> Matrix Double\npinvTol t m = v' `mXm` diag s' `mXm` trans u' where\n (u,s,v) = thinSVDRd m\n sl@(g:_) = toList s\n s' = fromList . map rec $ sl\n rec x = if x < g*tol then 1 else 1/x\n tol = (fromIntegral (max r c) * g * t * eps)\n r = rows m\n c = cols m\n d = dim s\n u' = takeColumns d u\n v' = takeColumns d v\n\n---------------------------------------------------------------------\n\n-- many thanks, quickcheck!\n\nhaussholder :: (Field a) => a -> Vector a -> Matrix a\nhaussholder tau v = ident (dim v) `sub` (tau `scale` (w `mXm` ctrans w))\n where w = asColumn v\n\n\nzh k v = fromList $ replicate (k-1) 0 ++ (1:drop k xs)\n where xs = toList v\n\nzt 0 v = v\nzt k v = join [subVector 0 (dim v - k) v, konst 0 k]\n\n\nunpackQR :: (Field t) => (Matrix t, Vector t) -> (Matrix t, Matrix t)\nunpackQR (pq, tau) = {-# SCC \"unpackQR\" #-} (q,r)\n where cs = toColumns pq\n m = rows pq\n n = cols pq\n mn = min m n\n r = fromColumns $ zipWith zt ([m-1, m-2 .. 1] ++ repeat 0) cs\n vs = zipWith zh [1..mn] cs\n hs = zipWith haussholder (toList tau) vs\n q = foldl1' mXm hs\n\nunpackHess :: (Field t) => (Matrix t -> (Matrix t,Vector t)) -> Matrix t -> (Matrix t, Matrix t)\nunpackHess hf m\n | rows m == 1 = ((1><1)[1],m)\n | otherwise = (uH . hf) m\n\nuH (pq, tau) = (p,h)\n where cs = toColumns pq\n m = rows pq\n n = cols pq\n mn = min m n\n h = fromColumns $ zipWith zt ([m-2, m-3 .. 1] ++ repeat 0) cs\n vs = zipWith zh [2..mn] cs\n hs = zipWith haussholder (toList tau) vs\n p = foldl1' mXm hs\n\n--------------------------------------------------------------------------\n\n-- | Reciprocal of the 2-norm condition number of a matrix, computed from the singular values.\nrcond :: Field t => Matrix t -> Double\nrcond m = last s / head s\n where s = toList (singularValues m)\n\n-- | Number of linearly independent rows or columns.\nrank :: Field t => Matrix t -> Int\nrank m = rankSVD eps m (singularValues m)\n\n{-\nexpm' m = case diagonalize (complex m) of\n Just (l,v) -> v `mXm` diag (exp l) `mXm` inv v\n Nothing -> error \"Sorry, expm not yet implemented for non-diagonalizable matrices\"\n where exp = vectorMapC Exp\n-}\n\ndiagonalize m = if rank v == n\n then Just (l,v)\n else Nothing\n where n = rows m\n (l,v) = if exactHermitian m\n then let (l',v') = eigSH m in (real l', v')\n else eig m\n\n-- | Generic matrix functions for diagonalizable matrices. For instance:\n--\n-- @logm = matFunc log@\n--\nmatFunc :: (Complex Double -> Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double)\nmatFunc f m = case diagonalize m of\n Just (l,v) -> v `mXm` diag (mapVector f l) `mXm` inv v\n Nothing -> error \"Sorry, matFunc requires a diagonalizable matrix\" \n\n--------------------------------------------------------------\n\ngolubeps :: Integer -> Integer -> Double\ngolubeps p q = a * fromIntegral b / fromIntegral c where\n a = 2^^(3-p-q)\n b = fact p * fact q\n c = fact (p+q) * fact (p+q+1)\n fact n = product [1..n]\n\nepslist = [ (fromIntegral k, golubeps k k) | k <- [1..]]\n\ngeps delta = head [ k | (k,g) <- epslist, g Matrix t -> Matrix t\nexpm = expGolub\n\nexpGolub :: ( Fractional t, Element t, Field t\n , Normed Matrix t\n , RealFrac (RealOf t)\n , Floating (RealOf t)\n ) => Matrix t -> Matrix t\nexpGolub m = iterate msq f !! j\n where j = max 0 $ floor $ logBase 2 $ pnorm Infinity m\n a = m */ fromIntegral ((2::Int)^j)\n q = geps eps -- 7 steps\n eye = ident (rows m)\n work (k,c,x,n,d) = (k',c',x',n',d')\n where k' = k+1\n c' = c * fromIntegral (q-k+1) / fromIntegral ((2*q-k+1)*k)\n x' = a <> x\n n' = n |+| (c' .* x')\n d' = d |+| (((-1)^k * c') .* x')\n (_,_,_,nf,df) = iterate work (1,1,eye,eye,eye) !! q\n f = linearSolve df nf\n msq x = x <> x\n\n (<>) = multiply\n v */ x = scale (recip x) v\n (.*) = scale\n (|+|) = add\n\n--------------------------------------------------------------\n\n{- | Matrix square root. Currently it uses a simple iterative algorithm described in Wikipedia.\nIt only works with invertible matrices that have a real solution. For diagonalizable matrices you can try @matFunc sqrt@.\n\n@m = (2><2) [4,9\n ,0,4] :: Matrix Double@\n\n@\\>sqrtm m\n(2><2)\n [ 2.0, 2.25\n , 0.0, 2.0 ]@\n-}\nsqrtm :: Field t => Matrix t -> Matrix t\nsqrtm = sqrtmInv\n\nsqrtmInv x = fst $ fixedPoint $ iterate f (x, ident (rows x))\n where fixedPoint (a:b:rest) | pnorm PNorm1 (fst a |-| fst b) < peps = a\n | otherwise = fixedPoint (b:rest)\n fixedPoint _ = error \"fixedpoint with impossible inputs\"\n f (y,z) = (0.5 .* (y |+| inv z),\n 0.5 .* (inv y |+| z))\n (.*) = scale\n (|+|) = add\n (|-|) = sub\n\n------------------------------------------------------------------\n\nsignlp r vals = foldl f 1 (zip [0..r-1] vals)\n where f s (a,b) | a /= b = -s\n | otherwise = s\n\nswap (arr,s) (a,b) | a /= b = (arr // [(a, arr!b),(b,arr!a)],-s)\n | otherwise = (arr,s)\n\nfixPerm r vals = (fromColumns $ elems res, sign)\n where v = [0..r-1]\n s = toColumns (ident r)\n (res,sign) = foldl swap (listArray (0,r-1) s, 1) (zip v vals)\n\ntriang r c h v = (r>=h then v else 1 - v\n\nluFact (l_u,perm) | r <= c = (l ,u ,p, s)\n | otherwise = (l',u',p, s)\n where\n r = rows l_u\n c = cols l_u\n tu = triang r c 0 1\n tl = triang r c 0 0\n l = takeColumns r (l_u |*| tl) |+| diagRect 0 (konst 1 r) r r\n u = l_u |*| tu\n (p,s) = fixPerm r perm\n l' = (l_u |*| tl) |+| diagRect 0 (konst 1 c) r c\n u' = takeRows c (l_u |*| tu)\n (|+|) = add\n (|*|) = mul\n\n---------------------------------------------------------------------------\n\ndata NormType = Infinity | PNorm1 | PNorm2 | Frobenius\n\nclass (RealFloat (RealOf t)) => Normed c t where\n pnorm :: NormType -> c t -> RealOf t\n\ninstance Normed Vector Double where\n pnorm PNorm1 = norm1\n pnorm PNorm2 = norm2\n pnorm Infinity = normInf\n pnorm Frobenius = norm2\n\ninstance Normed Vector (Complex Double) where\n pnorm PNorm1 = norm1\n pnorm PNorm2 = norm2\n pnorm Infinity = normInf\n pnorm Frobenius = pnorm PNorm2\n\ninstance Normed Vector Float where\n pnorm PNorm1 = norm1\n pnorm PNorm2 = norm2\n pnorm Infinity = normInf\n pnorm Frobenius = pnorm PNorm2\n\ninstance Normed Vector (Complex Float) where\n pnorm PNorm1 = norm1\n pnorm PNorm2 = norm2\n pnorm Infinity = normInf\n pnorm Frobenius = pnorm PNorm2\n\n\ninstance Normed Matrix Double where\n pnorm PNorm1 = maximum . map (pnorm PNorm1) . toColumns\n pnorm PNorm2 = (@>0) . singularValues\n pnorm Infinity = pnorm PNorm1 . trans\n pnorm Frobenius = pnorm PNorm2 . flatten\n\ninstance Normed Matrix (Complex Double) where\n pnorm PNorm1 = maximum . map (pnorm PNorm1) . toColumns\n pnorm PNorm2 = (@>0) . singularValues\n pnorm Infinity = pnorm PNorm1 . trans\n pnorm Frobenius = pnorm PNorm2 . flatten\n\ninstance Normed Matrix Float where\n pnorm PNorm1 = maximum . map (pnorm PNorm1) . toColumns\n pnorm PNorm2 = realToFrac . (@>0) . singularValues . double\n pnorm Infinity = pnorm PNorm1 . trans\n pnorm Frobenius = pnorm PNorm2 . flatten\n\ninstance Normed Matrix (Complex Float) where\n pnorm PNorm1 = maximum . map (pnorm PNorm1) . toColumns\n pnorm PNorm2 = realToFrac . (@>0) . singularValues . double\n pnorm Infinity = pnorm PNorm1 . trans\n pnorm Frobenius = pnorm PNorm2 . flatten\n\n-- | Approximate number of common digits in the maximum element.\nrelativeError :: (Normed c t, Container c t) => c t -> c t -> Int\nrelativeError x y = dig (norm (x `sub` y) / norm x)\n where norm = pnorm Infinity\n dig r = round $ -logBase 10 (realToFrac r :: Double)\n\n----------------------------------------------------------------------\n\n-- | Generalized symmetric positive definite eigensystem Av = lBv,\n-- for A and B symmetric, B positive definite (conditions not checked).\ngeigSH' :: Field t\n => Matrix t -- ^ A\n -> Matrix t -- ^ B\n -> (Vector Double, Matrix t)\ngeigSH' a b = (l,v')\n where\n u = cholSH b\n iu = inv u\n c = ctrans iu <> a <> iu\n (l,v) = eigSH' c\n v' = iu <> v\n (<>) = mXm\n\n", "meta": {"hexsha": "6500e0b0430d604cd981d0586024a7945a5269ff", "size": 25190, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/LinearAlgebra/Algorithms.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/LinearAlgebra/Algorithms.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/LinearAlgebra/Algorithms.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.412568306, "max_line_length": 298, "alphanum_fraction": 0.5776101628, "num_tokens": 7592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6735241247193973}} {"text": "import Data.Complex\nimport Data.List (partition)\nimport Data.Map ((!))\nimport qualified Data.Map as M\nimport Data.Ratio\n\ndft :: [Complex Double] -> [Complex Double]\ndft x = matMult dftMat x\n where\n n = length x\n w = exp $ (-2) * pi * (0 :+ 1) / fromIntegral n\n dftMat = [[w ^ (j * k) | j <- [0 .. n - 1]] | k <- [0 .. n - 1]]\n matMult m x = map (sum . zipWith (*) x) m\n\nfft :: [Complex Double] -> [Complex Double]\nfft x = fft' x\n where\n n = length x\n w0 = exp ((-2) * pi * (0 :+ 1) / fromIntegral n)\n w = M.fromList [(k % n, w0 ^ k) | k <- [0 .. n - 1]]\n fft' [x] = [x]\n fft' x =\n let (evens, odds) = partition (even . fst) $ zip [0 ..] x\n e = fft' $ map snd evens\n o = fft' $ map snd odds\n x1 = zipWith3 (\\e o k -> e + o * w ! (k %n)) e o [0 ..]\n x2 = zipWith3 (\\e o k -> e - o * w ! (k %n)) e o [0 ..]\n in x1 ++ x2\n\nmain = do\n print $ dft [0, 1, 2, 3]\n print $ fft [0, 1, 2, 3]\n", "meta": {"hexsha": "579e56e6d74ca6562134567b38b04cbffc519c6a", "size": 958, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "contents/cooley_tukey/code/haskell/fft.hs", "max_stars_repo_name": "Iinguistics/algorithm-archivists.github.io", "max_stars_repo_head_hexsha": "3759b22a9c21b8b7a9bf075ca880e02ec524abc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1975, "max_stars_repo_stars_event_min_datetime": "2018-04-28T13:46:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:14:47.000Z", "max_issues_repo_path": "contents/cooley_tukey/code/haskell/fft.hs", "max_issues_repo_name": "Iinguistics/algorithm-archivists.github.io", "max_issues_repo_head_hexsha": "3759b22a9c21b8b7a9bf075ca880e02ec524abc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 632, "max_issues_repo_issues_event_min_datetime": "2018-04-28T10:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T20:38:53.000Z", "max_forks_repo_path": "contents/cooley_tukey/code/haskell/fft.hs", "max_forks_repo_name": "Iinguistics/algorithm-archivists.github.io", "max_forks_repo_head_hexsha": "3759b22a9c21b8b7a9bf075ca880e02ec524abc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 433, "max_forks_repo_forks_event_min_datetime": "2018-04-27T22:50:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T06:16:03.000Z", "avg_line_length": 29.0303030303, "max_line_length": 68, "alphanum_fraction": 0.4770354906, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.673055647613007}} {"text": "{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n-- | This module defines the Syntax of the Quantum IO Monad, which is\n-- an embedded language for writing quantum computations. It is an\n-- alternative definition using the approach of defining F-Algebras.\nmodule QIO.QioSynAlt where\n\nimport Data.Monoid as Monoid\nimport Data.Complex\nimport Control.Applicative (Applicative(..))\nimport Control.Monad (liftM, ap)\n\n-- | For Real numbers, we simply use the built in Double type\ntype RR = Double\n\n-- | For Complex numbers, we use the built in Complex numbers, over our Real\n-- number type (i.e. Double)\ntype CC = Complex RR\n\n-- | The amplitude of a complex number is the magnitude squared.\namp :: CC -> RR\namp k = (magnitude k)*(magnitude k)\n\n-- | The type of Qubits in QIO are simply integer references.\nnewtype Qbit = Qbit Int deriving (Num, Enum, Eq, Ord)\n\n-- | We can display a qubit reference\ninstance Show Qbit where\n show (Qbit q) = \"(Qbit:\" ++ show q ++ \")\"\n\n-- | A rotation is in essence a two-by-two complex valued matrix\ntype Rotation = ((Bool,Bool) -> CC)\n\n-- | We can display the matrix representation of a rotation\ninstance Show Rotation where\n show f = \"(\" ++ (show (f (False,False))) ++ \",\" ++ (show (f (False,True))) ++ \",\" ++ (show (f (True,False))) ++ \",\" ++ (show (f (True,True))) ++ \")\"\n\n-- | The identity rotation\nrid :: Rotation\nrid (x,y) = if x==y then 1 else 0\n\n-- | The not rotation\nrnot :: Rotation\nrnot (x,y) = if x==y then 0 else 1\n\n-- | The hadamard rotation\nrhad :: Rotation\nrhad (x,y) = if x && y then -h else h where h = (1/sqrt 2)\n\n-- | The phase rotation\nrphase :: RR -> Rotation\nrphase _ (False,False) = 1\nrphase r (True,True) = exp(0:+r)\nrphase _ (_,_) = 0\n\n-- | Returns the inverse (or reverse) of the given rotation\nrrev :: Rotation -> Rotation\nrrev r (False,True) = conjugate (r (True,False))\nrrev r (True,False) = conjugate (r (False,True))\nrrev r xy = conjugate (r xy)\n\n-- | Rotations can be compared for equality.\n-- They are equal if the define the same matrix.\ninstance Eq Rotation where\n f == g = (f (False,False) == g (False,False))\n && (f (False,True) == g (False,True))\n && (f (True,False) == g (True,False))\n && (f (True,True) == g (True,True))\n f /= g = (f (False,False) /= g (False,False))\n || (f (False,True) /= g (False,True))\n || (f (True,False) /= g (True,False))\n || (f (True,True) /= g (True,True))\n\n-- | The non-recursive data type definition of a unitary operation\ndata UFunctor u = UReturn\n | Rot Qbit Rotation u\n | Swap Qbit Qbit u\n | Cond Qbit (Bool -> u) u\n | Ulet Bool (Qbit -> u) u\n\n-- | In order to define an F-Algebra, 'UFunctor' must be a functor.\ninstance Functor UFunctor where\n fmap eval UReturn = UReturn\n fmap eval (Rot q r u) = Rot q r (eval u)\n fmap eval (Swap q1 q2 u) = Swap q1 q2 (eval u)\n fmap eval (Cond q f u) = Cond q (eval . f) (eval u)\n fmap eval (Ulet b f u) = Ulet b (eval . f) (eval u)\n\n-- | The fix point type construtor.\nnewtype Fix f = Fx (f (Fix f))\n\n-- | We can define the inverse of Fx\nunFix :: Fix f -> f (Fix f)\nunFix (Fx x) = x\n\n-- | We fix the non-recursice data-type in order to get our type 'U'\n-- of unitary operations.\ntype U = Fix UFunctor\n\n-- | The type of an F-Algebra.\ntype Algebra f a = f a -> a\n\n-- | The type of the initial algebra for UFunctor\ntype UInitialAlgebra = Algebra UFunctor U\n\n-- | We can now define the initial algebra for U\nuInitialAlgebra :: UInitialAlgebra\nuInitialAlgebra = Fx\n\n-- | We can use a catamorphism to abstract evaluation over a given\n-- algebra\ncata :: Functor f => Algebra f a -> Fix f -> a\ncata algebra = algebra . fmap (cata algebra) . unFix\n\n-- | The type \"U\" forms a Monoid.\ninstance Semigroup U where\n (Fx UReturn) <> u = u\n (Fx (Rot x a u)) <> u' = Fx $ Rot x a (u <> u')\n (Fx (Swap x y u)) <> u' = Fx $ Swap x y (u <> u')\n (Fx (Cond x br u')) <> u'' = Fx $ Cond x br (u' <> u'')\n (Fx (Ulet b f u)) <> u' = Fx $ Ulet b f (u <> u')\n\ninstance Monoid U where\n mempty = Fx UReturn\n\n-- | Apply the given rotation to the given qubit\nrot :: Qbit -> Rotation -> U\nrot x r = Fx $ Rot x r mempty\n\n-- | Swap the state of the two given qubits\nswap :: Qbit -> Qbit -> U\nswap x y = Fx $ Swap x y mempty\n\n-- | Apply the conditional unitary, depending on the value of the given qubit\ncond :: Qbit -> (Bool -> U) -> U\ncond x br = Fx $ Cond x br mempty\n\n-- | Introduce an Ancilla qubit in the given state, for use in the sub-unitary\nulet :: Bool -> (Qbit -> U) -> U\nulet b ux = Fx $ Ulet b ux mempty\n\n-- | Apply a not rotation to the given qubit\nunot :: Qbit -> U\nunot x = rot x rnot\n\n-- | Apply a hadamard rotation to the given qubit\nuhad :: Qbit -> U\nuhad x = rot x rhad\n\n-- | Apply a phase rotation (of the given angle) to the given qubit\nuphase :: Qbit -> RR -> U\nuphase x r = rot x (rphase r)\n\n-- | Returns the inverse (or reverse) of the given unitary operation,\n-- using an F-Algebra\nurev :: U -> U\nurev = cata urev_algebra\n where\n urev_algebra :: UFunctor U -> U\n urev_algebra UReturn = Fx UReturn\n urev_algebra (Rot x r u) = u `mappend` rot x (rrev r)\n urev_algebra (Swap x y u) = u `mappend` swap x y\n urev_algebra (Cond x br u) = u `mappend` cond x br\n urev_algebra (Ulet b xu u) = u `mappend` ulet b xu\n\n-- | We can display a representation of a unitary, using an F-Algebra\ninstance Show U where\n show = cata showU_algebra\n where\n showU_algebra :: UFunctor String -> String\n showU_algebra UReturn = \"\"\n showU_algebra (Rot q r u) =\n \"Rotate \" ++ show q ++ \":\" ++ show r ++ \"\\n\" ++ u\n showU_algebra (Swap q1 q2 u) =\n \"Swap \" ++ show q1 ++ \" and \" ++ show q2 ++ \"\\n\" ++ u\n showU_algebra (Cond q br u) =\n \"Cond \" ++ show q ++ \" \\\\b -> if b then (\\n\"\n ++ unlines (map (' ':) (lines $ br True))\n ++ \") else (\\n\"\n ++ unlines (map (' ':) (lines $ br False))\n ++ \")\\n\" ++ u\n showU_algebra (Ulet b xu u) =\n let fv = find_fv xu in\n \"Ulet \" ++ show fv ++ \" = \" ++ (if b then \"1\" else \"0\") ++ \" in (\\n\"\n ++ unlines (map (' ':) (lines $ xu fv))\n ++ \")\\n\" ++ u\n -- this is currently a dummy function\n find_fv :: (Qbit -> String) -> Qbit\n find_fv _ = -1\n\n-- | The non-recursive data type definition of a QIO computation\ndata QIOFunctor a q = QReturn a\n | MkQbit Bool (Qbit -> q)\n | ApplyU U q\n | Meas Qbit (Bool -> q)\n\n-- | In order to define an F-Algebra, 'UF' must be a functor.\ninstance Functor (QIOFunctor a) where\n fmap eval (QReturn a) = QReturn a\n fmap eval (MkQbit b f) = MkQbit b (eval . f)\n fmap eval (ApplyU u q) = ApplyU u (eval q)\n fmap eval (Meas q f) = Meas q (eval . f)\n\n-- | We fix the non-recursice data-type in order to get our type 'U'\n-- of unitary operations.\ntype QIOprim a = Fix (QIOFunctor a)\n\n-- | The type of the initial algebra for UFunctor\ntype QIOInitialAlgebra a = Algebra (QIOFunctor a) (QIOprim a)\n\n-- | We can now define the initial algebra for U\nqioInitialAlgebra :: QIOInitialAlgebra a\nqioInitialAlgebra = Fx\n\n-- | The \"QIO\" type forms a Monad, by wrapping 'QIOprim'\ndata QIO a = Apply (Fix (QIOFunctor a))\n\n-- | We can remove the wrapper.\nprimQIO :: QIO a -> QIOprim a\nprimQIO (Apply q) = q\n\ninstance Functor QIO where\n fmap = liftM\n\ninstance Applicative QIO where\n pure = Apply . Fx . QReturn\n (<*>) = ap\n\n-- | The wrapper type 'ApplyFix' forms a Monad\ninstance Monad QIO where\n return = pure\n (Apply (Fx (QReturn a))) >>= f = f a\n (Apply (Fx (MkQbit b g))) >>= f = Apply . Fx $\n MkQbit b (\\q -> primQIO $ (Apply (g q)) >>= f)\n (Apply (Fx (ApplyU u q))) >>= f = Apply . Fx $\n ApplyU u $ primQIO (Apply q >>= f)\n (Apply (Fx (Meas x g))) >>= f = Apply . Fx $\n Meas x (\\b -> primQIO $ (Apply (g b)) >>= f)\n\n-- | Initialise a qubit in the given state (adding it to the overall quantum state)\nmkQbit :: Bool -> QIO Qbit\nmkQbit b = Apply . Fx $ MkQbit b (\\q -> primQIO (return q))\n\n-- | Apply the given unitary operation to the current quantum state\napplyU :: U -> QIO ()\napplyU u = Apply . Fx $ ApplyU u $ primQIO (return ())\n\n-- | Measure the given qubit, and return the measurement outcome (note that this\n-- operation may affect the overall quantum state, as a measurement is destructive)\nmeasQbit :: Qbit -> QIO Bool\nmeasQbit x = Apply . Fx $ Meas x (\\b -> primQIO (return b))\n\n-- | We can show a QIO computation, using an F-Algebra\ninstance (Show a) => Show (QIO a) where\n show = (cata showQIO_algebra) . primQIO\n where\n showQIO_algebra :: (Show a) => Algebra (QIOFunctor a) String\n showQIO_algebra (QReturn a) =\n \"Return: \" ++ show a ++ \"\\n\"\n showQIO_algebra (MkQbit b f) =\n \"Init\" ++ (if b then \"1\" else \"0\") ++ \"\\n\"\n ++ f 0\n showQIO_algebra (ApplyU u qio) =\n \"Apply Unitary: (\\n\"\n ++ unlines (map (' ':) (lines $ show u))\n ++ \")\\n\" ++ qio\n showQIO_algebra (Meas q f) =\n \"Measure \" ++ show q ++ \" \\\\b -> if b then (\\n\"\n ++ unlines (map (' ':) (lines $ f True))\n ++ \") else (\\n\"\n ++ unlines (map (' ':) (lines $ f False))\n ++ \")\\n\"\n\n-- | We can count the number of each primitive operation using an F-Algebra\ncount :: QIO a -> (Int,Int,Int)\ncount = (cata count_algebra) . primQIO\n where\n count_algebra :: Algebra (QIOFunctor a) (Int,Int,Int)\n count_algebra (QReturn _) = (0,0,0)\n count_algebra (MkQbit b f) = let (mk,ap,ms) = f 0 in\n (mk+1,ap,ms)\n count_algebra (ApplyU _ (mk,ap,ms)) = (mk,ap+1,ms)\n count_algebra (Meas q f) = let (mk,ap,ms) = f False in\n (mk,ap,ms+1)\n\ntoffoli :: Qbit -> Qbit -> Qbit -> U\ntoffoli q1 q2 q3 =\n cond q1 (\\b1 -> if b1 then (\n cond q2 (\\b2 -> if b2 then (unot q3)\n else mempty)) else mempty)\n\nand :: Bool -> Bool -> QIO Bool\nand a b = do\n q1 <- mkQbit a\n q2 <- mkQbit b\n q3 <- mkQbit False\n applyU (toffoli q1 q2 q3)\n measQbit q3\n", "meta": {"hexsha": "bdcbe422f1d5cf9ebedff695b2e0889b7dfcd5e6", "size": 10109, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "QIO/QioSynAlt.hs", "max_stars_repo_name": "probprob/qio-haskell", "max_stars_repo_head_hexsha": "e48151a335dc3ddde4cbda440ed68ca80dc95b15", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-11T15:26:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-11T15:26:05.000Z", "max_issues_repo_path": "QIO/QioSynAlt.hs", "max_issues_repo_name": "probprob/qio-haskell", "max_issues_repo_head_hexsha": "e48151a335dc3ddde4cbda440ed68ca80dc95b15", "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/QioSynAlt.hs", "max_forks_repo_name": "probprob/qio-haskell", "max_forks_repo_head_hexsha": "e48151a335dc3ddde4cbda440ed68ca80dc95b15", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-02-12T22:41:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T09:25:43.000Z", "avg_line_length": 33.584717608, "max_line_length": 152, "alphanum_fraction": 0.5990701355, "num_tokens": 3235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6725356581208877}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n-- |\n-- Module : Statistics.Sample\n-- Copyright : (c) 2008 Don Stewart, 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Commonly used sample statistics, also known as descriptive\n-- statistics.\n\nmodule Statistics.Sample\n (\n -- * Statistics of location\n mean\n\n -- ** Two-pass functions (numerically robust)\n -- $robust\n , variance\n , varianceUnbiased\n , stdDev\n\n -- * References\n -- $references\n ) where\n\nimport Statistics.Sample.Internal (robustSumVar, sum)\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\n\n-- Operator ^ will be overriden\nimport Prelude hiding ((^), sum)\n\n-- | /O(n)/ Arithmetic mean. This uses Kahan-Babuška-Neumaier\n-- summation, so is more accurate than 'welfordMean' unless the input\n-- values are very large.\nmean :: (G.Vector v Double) => v Double -> Double\nmean xs = sum xs / fromIntegral (G.length xs)\n{-# SPECIALIZE mean :: U.Vector Double -> Double #-}\n{-# SPECIALIZE mean :: V.Vector Double -> Double #-}\n\n-- $variance\n--\n-- The variance—and hence the standard deviation—of a\n-- sample of fewer than two elements are both defined to be zero.\n\n-- $robust\n--\n-- These functions use the compensated summation algorithm of Chan et\n-- al. for numerical robustness, but require two passes over the\n-- sample data as a result.\n--\n-- Because of the need for two passes, these functions are /not/\n-- subject to stream fusion.\n\n-- | Maximum likelihood estimate of a sample's variance. Also known\n-- as the population variance, where the denominator is /n/.\nvariance :: (G.Vector v Double) => v Double -> Double\nvariance samp\n | n > 1 = robustSumVar (mean samp) samp / fromIntegral n\n | otherwise = 0\n where\n n = G.length samp\n{-# SPECIALIZE variance :: U.Vector Double -> Double #-}\n{-# SPECIALIZE variance :: V.Vector Double -> Double #-}\n\n\n-- | Unbiased estimate of a sample's variance. Also known as the\n-- sample variance, where the denominator is /n/-1.\nvarianceUnbiased :: (G.Vector v Double) => v Double -> Double\nvarianceUnbiased samp\n | n > 1 = robustSumVar (mean samp) samp / fromIntegral (n-1)\n | otherwise = 0\n where\n n = G.length samp\n{-# SPECIALIZE varianceUnbiased :: U.Vector Double -> Double #-}\n{-# SPECIALIZE varianceUnbiased :: V.Vector Double -> Double #-}\n\n-- | Standard deviation. This is simply the square root of the\n-- unbiased estimate of the variance.\nstdDev :: (G.Vector v Double) => v Double -> Double\nstdDev = sqrt . varianceUnbiased\n{-# SPECIALIZE stdDev :: U.Vector Double -> Double #-}\n{-# SPECIALIZE stdDev :: V.Vector Double -> Double #-}\n\n-- $cancellation\n--\n-- The functions prefixed with the name @fast@ below perform a single\n-- pass over the sample data using Knuth's algorithm. They usually\n-- work well, but see below for caveats. These functions are subject\n-- to array fusion.\n--\n-- /Note/: in cases where most sample data is close to the sample's\n-- mean, Knuth's algorithm gives inaccurate results due to\n-- catastrophic cancellation.\n\n-- $references\n--\n-- * Chan, T. F.; Golub, G.H.; LeVeque, R.J. (1979) Updating formulae\n-- and a pairwise algorithm for computing sample\n-- variances. Technical Report STAN-CS-79-773, Department of\n-- Computer Science, Stanford\n-- University. \n--\n-- * Knuth, D.E. (1998) The art of computer programming, volume 2:\n-- seminumerical algorithms, 3rd ed., p. 232.\n--\n-- * Welford, B.P. (1962) Note on a method for calculating corrected\n-- sums of squares and products. /Technometrics/\n-- 4(3):419–420. \n--\n-- * West, D.H.D. (1979) Updating mean and variance estimates: an\n-- improved method. /Communications of the ACM/\n-- 22(9):532–535. \n", "meta": {"hexsha": "6dc1a75f79c9e0a746da4fe1c7f70c3e11568d14", "size": 4009, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "statistics/Statistics/Sample.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/Sample.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/Sample.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": 33.9745762712, "max_line_length": 92, "alphanum_fraction": 0.6882015465, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6724742656331962}} {"text": "module RandomExtra where\n\nimport Data.Complex (Complex(..))\nimport qualified Control.Monad.Random.Strict as R\nimport Numeric (log)\n\n-- | Yield two randomly selected values which follow standard\n-- normal distribution.\n-- code stolen from https://hackage.haskell.org/package/moo-1.2/docs/src/Moo.GeneticAlgorithm.Random.html#getNormal2\ngetNormal2 :: (R.Random a, RealFloat a, R.MonadRandom m) => m (a, a)\ngetNormal2 = do\n -- Box-Muller method\n u <- R.getRandom\n v <- R.getRandom\n let (c :+ s) = exp (0 :+ (2 * pi * v))\n let r = sqrt $ (-2) * log u\n return (r * c, r * s)\n\n-- | Yield one randomly selected value from standard normal distribution.\n-- code stolen from https://hackage.haskell.org/package/moo-1.2/docs/src/Moo.GeneticAlgorithm.Random.html#getNormal2\n-- code stolen from https://hackage.haskell.org/package/moo-1.2/docs/src/Moo.GeneticAlgorithm.Random.html#getNormal2\ngetNormal :: (R.Random a, RealFloat a, R.MonadRandom m) => m a\ngetNormal = fst <$> getNormal2\n\nnewtype Mu a = Mu a\n\nnewtype Sigma a = Sigma a\n\ngetScaledNormal\n :: (R.Random a, RealFloat a, R.MonadRandom m) => Mu a -> Sigma a -> m a\ngetScaledNormal (Mu mu) (Sigma sigma) = (\\x -> x * sigma + mu) <$> getNormal\n\nrandomAngle :: (Floating a, R.Random a, R.MonadRandom m) => m a\nrandomAngle = R.getRandomR (0, 2 * pi)\n\n", "meta": {"hexsha": "c2447e01856fc295c9739e79d7b5d1d5b5ec26d5", "size": 1314, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/RandomExtra.hs", "max_stars_repo_name": "SandiCat/colorblind-test", "max_stars_repo_head_hexsha": "6c2167d98025b8d071627e846c5a8e4b5ace4005", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/RandomExtra.hs", "max_issues_repo_name": "SandiCat/colorblind-test", "max_issues_repo_head_hexsha": "6c2167d98025b8d071627e846c5a8e4b5ace4005", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RandomExtra.hs", "max_forks_repo_name": "SandiCat/colorblind-test", "max_forks_repo_head_hexsha": "6c2167d98025b8d071627e846c5a8e4b5ace4005", "max_forks_repo_licenses": ["BSD-3-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.5, "max_line_length": 116, "alphanum_fraction": 0.6925418569, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6722355322842416}} {"text": "{-# LANGUAGE CPP #-}\n-----------------------------------------------------------------------------\n-- |\n-- Copyright : (c) Edward Kmett 2010-2015\n-- License : BSD3\n-- Maintainer : ekmett@gmail.com\n-- Stability : experimental\n-- Portability : GHC only\n--\n-- Root finding using Halley's rational method (the second in\n-- the class of Householder methods). Assumes the function is three\n-- times continuously differentiable and converges cubically when\n-- progress can be made.\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.AD.Rank1.Halley\n (\n -- * Halley's Method (Tower AD)\n findZero\n , findZeroNoEq\n , inverse\n , inverseNoEq\n , fixedPoint\n , fixedPointNoEq\n , extremum\n , extremumNoEq\n ) where\n\nimport Prelude hiding (all)\nimport Numeric.AD.Internal.Forward (Forward)\nimport Numeric.AD.Internal.On\nimport Numeric.AD.Internal.Tower (Tower)\nimport Numeric.AD.Mode\nimport Numeric.AD.Rank1.Tower (diffs0)\nimport Numeric.AD.Rank1.Forward (diff)\nimport Numeric.AD.Internal.Combinators (takeWhileDifferent)\n\n-- $setup\n-- >>> import Data.Complex\n\n-- | The 'findZero' function finds a zero of a scalar function using\n-- Halley's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes constant\n-- (\"it converges\"), no further elements are returned.\n--\n-- Examples:\n--\n-- >>> take 10 $ findZero (\\x->x^2-4) 1\n-- [1.0,1.8571428571428572,1.9997967892704736,1.9999999999994755,2.0]\n--\n-- >>> last $ take 10 $ findZero ((+1).(^2)) (1 :+ 1)\n-- 0.0 :+ 1.0\nfindZero :: (Fractional a, Eq a) => (Tower a -> Tower a) -> a -> [a]\nfindZero f = takeWhileDifferent . findZeroNoEq f\n{-# INLINE findZero #-}\n\n-- | The 'findZeroNoEq' function behaves the same as 'findZero' except that it\n-- doesn't truncate the list once the results become constant. This means it\n-- can be used with types without an 'Eq' instance.\nfindZeroNoEq :: Fractional a => (Tower a -> Tower a) -> a -> [a]\nfindZeroNoEq f = iterate go where\n go x = xn where\n (y:y':y'':_) = diffs0 f x\n xn = x - 2*y*y'/(2*y'*y'-y*y'') -- 9.606671960457536 bits error\n -- = x - recip (y'/y - y''/ y') -- \"improved error\" = 6.640625e-2 bits\n -- = x - y' / (y'/y/y' - y''/2) -- \"improved error\" = 1.4\n#ifdef HERBIE\n{-# ANN findZeroNoEq \"NoHerbie\" #-}\n#endif\n{-# INLINE findZeroNoEq #-}\n\n-- | The 'inverse' function inverts a scalar function using\n-- Halley's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes constant\n-- (\"it converges\"), no further elements are returned.\n--\n-- Note: the @take 10 $ inverse sqrt 1 (sqrt 10)@ example that works for Newton's method\n-- fails with Halley's method because the preconditions do not hold!\ninverse :: (Fractional a, Eq a) => (Tower a -> Tower a) -> a -> a -> [a]\ninverse f x0 = takeWhileDifferent . inverseNoEq f x0\n{-# INLINE inverse #-}\n\n-- | The 'inverseNoEq' function behaves the same as 'inverse' except that it\n-- doesn't truncate the list once the results become constant. This means it\n-- can be used with types without an 'Eq' instance.\ninverseNoEq :: Fractional a => (Tower a -> Tower a) -> a -> a -> [a]\ninverseNoEq f x0 y = findZeroNoEq (\\x -> f x - auto y) x0\n{-# INLINE inverseNoEq #-}\n\n-- | The 'fixedPoint' function find a fixedpoint of a scalar\n-- function using Halley's method; its output is a stream of\n-- increasingly accurate results. (Modulo the usual caveats.)\n--\n-- If the stream becomes constant (\"it converges\"), no further\n-- elements are returned.\n--\n-- >>> last $ take 10 $ fixedPoint cos 1\n-- 0.7390851332151607\nfixedPoint :: (Fractional a, Eq a) => (Tower a -> Tower a) -> a -> [a]\nfixedPoint f = takeWhileDifferent . fixedPointNoEq f\n{-# INLINE fixedPoint #-}\n\n-- | The 'fixedPointNoEq' function behaves the same as 'fixedPoint' except that\n-- it doesn't truncate the list once the results become constant. This means it\n-- can be used with types without an 'Eq' instance.\nfixedPointNoEq :: Fractional a => (Tower a -> Tower a) -> a -> [a]\nfixedPointNoEq f = findZeroNoEq (\\x -> f x - x)\n{-# INLINE fixedPointNoEq #-}\n\n-- | The 'extremum' function finds an extremum of a scalar\n-- function using Halley's method; produces a stream of increasingly\n-- accurate results. (Modulo the usual caveats.) If the stream becomes\n-- constant (\"it converges\"), no further elements are returned.\n--\n-- >>> take 10 $ extremum cos 1\n-- [1.0,0.29616942658570555,4.59979519460002e-3,1.6220740159042513e-8,0.0]\nextremum :: (Fractional a, Eq a) => (On (Forward (Tower a)) -> On (Forward (Tower a))) -> a -> [a]\nextremum f = takeWhileDifferent . extremumNoEq f\n{-# INLINE extremum #-}\n\n-- | The 'extremumNoEq' function behaves the same as 'extremum' except that it\n-- doesn't truncate the list once the results become constant. This means it\n-- can be used with types without an 'Eq' instance.\nextremumNoEq :: Fractional a => (On (Forward (Tower a)) -> On (Forward (Tower a))) -> a -> [a]\nextremumNoEq f = findZeroNoEq (diff (off . f . On))\n{-# INLINE extremumNoEq #-}\n", "meta": {"hexsha": "781cdd52137d28444ab43acf2a61e69795d552fe", "size": 5086, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Rank1/Halley.hs", "max_stars_repo_name": "wavewave/ad", "max_stars_repo_head_hexsha": "e6e05124fa283adcc1ac6ea415a5d590023d9c92", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/AD/Rank1/Halley.hs", "max_issues_repo_name": "wavewave/ad", "max_issues_repo_head_hexsha": "e6e05124fa283adcc1ac6ea415a5d590023d9c92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-01-16T12:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T12:39:50.000Z", "max_forks_repo_path": "src/Numeric/AD/Rank1/Halley.hs", "max_forks_repo_name": "wavewave/ad", "max_forks_repo_head_hexsha": "e6e05124fa283adcc1ac6ea415a5d590023d9c92", "max_forks_repo_licenses": ["BSD-3-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.734375, "max_line_length": 98, "alphanum_fraction": 0.6616201337, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6719648499956284}} {"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.Uniform\n-- Copyright : (c) 2011 Aleksey Khudyakov\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Variate distributed uniformly in the interval.\nmodule Statistics.Distribution.Uniform\n (\n UniformDistribution\n -- * Constructors\n , uniformDistr\n , uniformDistrE\n -- ** Accessors\n , uniformA\n , uniformB\n ) where\n\nimport Control.Applicative\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport qualified System.Random.MWC as MWC\n\nimport qualified Statistics.Distribution as D\nimport Statistics.Internal\n\n\n\n-- | Uniform distribution from A to B\ndata UniformDistribution = UniformDistribution {\n uniformA :: {-# UNPACK #-} !Double -- ^ Low boundary of distribution\n , uniformB :: {-# UNPACK #-} !Double -- ^ Upper boundary of distribution\n } deriving (Eq, Typeable, Data, Generic)\n\ninstance Show UniformDistribution where\n showsPrec i (UniformDistribution a b) = defaultShow2 \"uniformDistr\" a b i\ninstance Read UniformDistribution where\n readPrec = defaultReadPrecM2 \"uniformDistr\" uniformDistrE\n\n-- | Create uniform distribution.\nuniformDistr :: Double -> Double -> UniformDistribution\nuniformDistr a b = maybe (error errMsg) id $ uniformDistrE a b\n\n-- | Create uniform distribution.\nuniformDistrE :: Double -> Double -> Maybe UniformDistribution\nuniformDistrE a b\n | b < a = Just $ UniformDistribution b a\n | a < b = Just $ UniformDistribution a b\n | otherwise = Nothing\n-- NOTE: failure is in default branch to guard against NaNs.\n\nerrMsg :: String\nerrMsg = \"Statistics.Distribution.Uniform.uniform: wrong parameters\"\n\n\ninstance D.Distribution UniformDistribution where\n cumulative (UniformDistribution a b) x\n | x < a = 0\n | x > b = 1\n | otherwise = (x - a) / (b - a)\n\ninstance D.ContDistr UniformDistribution where\n density (UniformDistribution a b) x\n | x < a = 0\n | x > b = 0\n | otherwise = 1 / (b - a)\n quantile (UniformDistribution a b) p\n | p >= 0 && p <= 1 = a + (b - a) * p\n | otherwise =\n error $ \"Statistics.Distribution.Uniform.quantile: p must be in [0,1] range. Got: \"++show p\n complQuantile (UniformDistribution a b) p\n | p >= 0 && p <= 1 = b + (a - b) * p\n | otherwise =\n error $ \"Statistics.Distribution.Uniform.complQuantile: p must be in [0,1] range. Got: \"++show p\n\ninstance D.Mean UniformDistribution where\n mean (UniformDistribution a b) = 0.5 * (a + b)\n\ninstance D.Variance UniformDistribution where\n -- NOTE: 1/sqrt 12 is not constant folded (#4101) so it's written as\n -- numerical constant. (Also FIXME!)\n stdDev (UniformDistribution a b) = 0.2886751345948129 * (b - a)\n variance (UniformDistribution a b) = d * d / 12 where d = b - a\n\ninstance D.MaybeMean UniformDistribution where\n maybeMean = Just . D.mean\n\ninstance D.MaybeVariance UniformDistribution where\n maybeStdDev = Just . D.stdDev\n\ninstance D.Entropy UniformDistribution where\n entropy (UniformDistribution a b) = log (b - a)\n\ninstance D.MaybeEntropy UniformDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContGen UniformDistribution where\n genContVar (UniformDistribution a b) gen = MWC.uniformR (a,b) gen\n", "meta": {"hexsha": "2e1eea98aa4ad46a170686566def1df7368de585", "size": 3406, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Uniform.hs", "max_stars_repo_name": "vmchale/statistics", "max_stars_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/Distribution/Uniform.hs", "max_issues_repo_name": "vmchale/statistics", "max_issues_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/Uniform.hs", "max_forks_repo_name": "vmchale/statistics", "max_forks_repo_head_hexsha": "7f19ba0569ff34891c3ec18293a23ffb7eac8edf", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.75, "max_line_length": 102, "alphanum_fraction": 0.689371697, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6719648454265409}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra.Packed.Statistics\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Basic multivariate statistics.\n--\n\nmodule Numeric.LinearAlgebra.Packed.Statistics (\n defaultCovUplo,\n\n -- * Immutable interface\n cov,\n covWithMean,\n weightedCov,\n weightedCovWithMean,\n\n -- * Mutable interface\n covTo,\n covWithMeanTo,\n weightedCovTo,\n weightedCovWithMeanTo,\n\n ) where\n\nimport Control.Monad( when )\nimport Control.Monad.ST( ST )\nimport Data.List( foldl' )\nimport Text.Printf( printf )\n\nimport Numeric.LinearAlgebra.Types\nimport Numeric.LinearAlgebra.Packed.Base( Packed, STPacked )\nimport qualified Numeric.LinearAlgebra.Packed.Base as P\n\nimport Numeric.LinearAlgebra.Vector( Vector, RVector )\nimport qualified Numeric.LinearAlgebra.Vector as V\n\nimport qualified Numeric.LinearAlgebra.Matrix as M\n\n\n-- | Returns the default storage scheme for covariance matrices.\ndefaultCovUplo :: Uplo\ndefaultCovUplo = Lower\n\n-- | Returns the sample covariance matrix hermitian matrix (in packed form)\n-- with storage scheme equal to 'defaultCovUplo'. The first argument gives\n-- the dimension of the vectors.\ncov :: (BLAS2 e)\n => Int -> CovMethod -> [Vector e] -> Herm Packed e\ncov p t xs = P.hermCreate $ do\n c <- Herm uplo `fmap` P.new_ p\n covTo c t xs\n return c\n where\n uplo = defaultCovUplo\n\n-- | Given the pre-computed mean, returns the sample covariance matrix\n-- (in packed form) with storage scheme equal to 'defaultCovUplo'.\ncovWithMean :: (BLAS2 e)\n => Vector e -> CovMethod -> [Vector e] -> Herm Packed e\ncovWithMean mu t xs = P.hermCreate $ do\n c <- Herm uplo `fmap` P.new_ p\n covWithMeanTo c mu t xs\n return c\n where\n p = V.dim mu\n uplo = defaultCovUplo\n\n-- | Returns the weighed sample covariance matrix (in packed form) with\n-- storage scheme equal to 'defaultCovUplo'. The first argument gives the\n-- dimension of the vectors.\nweightedCov :: (BLAS2 e)\n => Int -> CovMethod -> [(Double, Vector e)] -> Herm Packed e\nweightedCov p t wxs = P.hermCreate $ do\n c <- Herm uplo `fmap` P.new_ p\n weightedCovTo c t wxs\n return c\n where\n uplo = defaultCovUplo\n\n-- | Given the pre-computed mean, returns the weighed sample covariance matrix\n-- (in packed form) with storage scheme equal to 'defaultCovUplo'.\nweightedCovWithMean :: (BLAS2 e)\n => Vector e -> CovMethod -> [(Double, Vector e)]\n -> Herm Packed e\nweightedCovWithMean mu t wxs = P.hermCreate $ do\n c <- Herm uplo `fmap` P.new_ p\n weightedCovWithMeanTo c mu t wxs\n return c\n where\n p = V.dim mu\n uplo = defaultCovUplo\n\n-- | Computes and copies the sample covariance matrix (in packed form)\n-- to the given destination.\ncovTo :: (RVector v, BLAS2 e)\n => Herm (STPacked s) e -> CovMethod -> [v e] -> ST s ()\ncovTo c@(Herm _ a) t xs = do\n p <- P.getDim a\n mu <- V.new p 1\n V.meanTo mu xs\n covWithMeanTo c mu t xs\n\n\n-- | Given the pre-computed mean, computes and copies the sample covariance\n-- matrix (in packed form) to the given destination.\ncovWithMeanTo :: (RVector v1, RVector v2, BLAS2 e)\n => Herm (STPacked s) e\n -> v1 e -> CovMethod -> [v2 e]\n -> ST s ()\ncovWithMeanTo c@(Herm _ a) mu t xs = do\n pa <- P.getDim a\n p <- V.getDim mu \n \n when (pa /= p) $ error $\n printf (\"covWithMeanTo\"\n ++ \" (Herm _ )\"\n ++ \" \"\n ++ \" _ _\"\n ++ \": dimension mismatch\")\n pa p\n\n xt <- M.new_ (p,n)\n M.withColsM xt $ \\xs' ->\n sequence_ [ V.subTo x' mu x\n | (x,x') <- zip xs xs'\n ]\n P.withVectorM a V.clear\n M.withColsM xt $ \\xs' ->\n sequence_ [ P.hermRank1UpdateM_ scale x' c | x' <- xs' ]\n where\n n = length xs\n df = fromIntegral $ case t of { MLCov -> n ; UnbiasedCov -> n - 1 }\n scale = 1/df\n\n\n-- | Computes and copies the weighed sample covariance matrix (in packed\n-- form) to the given destination.\nweightedCovTo :: (RVector v, BLAS2 e)\n => Herm (STPacked s) e\n -> CovMethod -> [(Double, v e)] \n -> ST s ()\nweightedCovTo c@(Herm _ a) t wxs = do\n p <- P.getDim a\n mu <- V.new p 1\n V.weightedMeanTo mu wxs\n weightedCovWithMeanTo c mu t wxs\n\n\n-- | Given the pre-computed mean, computes and copies the weighed sample\n-- covariance matrix (in packed form) to the given destination.\nweightedCovWithMeanTo :: (RVector v1, RVector v2, BLAS2 e)\n => Herm (STPacked s) e\n -> v1 e -> CovMethod -> [(Double, v2 e)]\n -> ST s ()\nweightedCovWithMeanTo c@(Herm _ a) mu t wxs = do\n pa <- P.getDim a\n p <- V.getDim mu\n \n when (pa /= p) $ error $\n printf (\"weightedCovWithMeanTo\"\n ++ \" (Herm _ )\"\n ++ \" \"\n ++ \" _ _\"\n ++ \": dimension mismatch\")\n pa p\n\n xt <- M.new_ (p,n)\n M.withColsM xt $ \\xs' ->\n sequence_ [ V.subTo x' mu x\n >> V.scaleM_ (realToFrac $ sqrt (w / invscale)) x'\n | (w,x,x') <- zip3 ws xs xs'\n ]\n P.withVectorM a V.clear \n M.withCols xt $ \\xs' ->\n sequence_ [ P.hermRank1UpdateM_ 1 x' c | x' <- xs' ]\n where\n (ws0,xs) = unzip wxs\n w_sum = foldl' (+) 0 ws0\n ws = if w_sum == 0 then ws0 else map (/w_sum) ws0\n w2s_sum = foldl' (+) 0 $ map (^^(2::Int)) ws\n invscale = case t of \n MLCov -> 1\n UnbiasedCov -> (1 - w2s_sum)\n n = length ws0\n", "meta": {"hexsha": "c6f1186c3b7c60ef6f52036c3189cf5e7bf8c64b", "size": 5934, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Packed/Statistics.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Packed/Statistics.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Packed/Statistics.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": 31.3968253968, "max_line_length": 78, "alphanum_fraction": 0.582743512, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.671569226795001}} {"text": "module Fractal.Math.Mandelbrot(\n mandel,\n mandel'\n)where\n{-\n\nMath packet kommt alles mathe bezogene rein\n\n-}\n\nimport Data.Complex\nimport Fractal.Math.Kernel (evaluateFractal)\n\ntype Point = Complex Double\ntype Limit = Double\ntype Iteration = Complex Double\ntype Magnitude = Double\ntype MaxIter = Int\n\n\nmandelEquation :: Point -> Iteration -> Iteration\nmandelEquation c (0.0 :+ 0.0) = c\nmandelEquation c (0.0 :+ 1) = 0\nmandelEquation c (0.0 :+ (-1)) = 0\nmandelEquation c z = z * z + c\n\nmandel :: MaxIter -> Limit -> [Point] -> [Int]\nmandel maxIter l field = map mandelEvaluator field\n where mandelEvaluator = evaluateFractal mandelEquation l maxIter\n\nmandel' :: MaxIter -> Limit -> Point -> Int\nmandel' maxIter l field = mandelEvaluator field\n where mandelEvaluator = evaluateFractal mandelEquation l maxIter\n", "meta": {"hexsha": "53b76b1b99903affa75d73c62b322c28020aa24a", "size": 811, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fractal/Math/Mandelbrot.hs", "max_stars_repo_name": "sigmaticsMUC/FractalHaskell", "max_stars_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Fractal/Math/Mandelbrot.hs", "max_issues_repo_name": "sigmaticsMUC/FractalHaskell", "max_issues_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fractal/Math/Mandelbrot.hs", "max_forks_repo_name": "sigmaticsMUC/FractalHaskell", "max_forks_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_forks_repo_licenses": ["BSD-3-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.8529411765, "max_line_length": 66, "alphanum_fraction": 0.7311960543, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6711364724665841}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\nmodule Numeric.Matrix.SVD\n ( MatrixSVD (..), SVD (..)\n , svd1, svd2, svd3, svd3q\n ) where\n\nimport Control.Monad\nimport Control.Monad.ST\nimport Data.Kind\nimport Numeric.Basics\nimport Numeric.DataFrame.Internal.PrimArray\nimport Numeric.DataFrame.ST\nimport Numeric.DataFrame.SubSpace\nimport Numeric.DataFrame.Type\nimport Numeric.Dimensions\nimport Numeric.Matrix.Bidiagonal\nimport Numeric.Matrix.Internal\nimport Numeric.Quaternion.Internal\nimport Numeric.Scalar.Internal\nimport Numeric.Subroutine.Sort\nimport Numeric.Tuple\nimport Numeric.Vector.Internal\n\n-- | Result of SVD factorization\n-- @ M = svdU %* asDiag svdS %* transpose svdV @.\n--\n-- Invariants:\n--\n-- * Singular values `svdS` are in non-increasing order and are non-negative.\n-- * svdU and svdV are orthogonal matrices\n-- * det svdU == 1\n--\n-- NB: \ndata SVD (t :: Type) (n :: Nat) (m :: Nat)\n = SVD\n { svdU :: Matrix t n n\n -- ^ Left-singular basis matrix\n , svdS :: Vector t (Min n m)\n -- ^ Vector of singular values\n , svdV :: Matrix t m m\n -- ^ Right-singular basis matrix\n }\n\nderiving instance ( Show t, PrimBytes t\n , KnownDim n, KnownDim m, KnownDim (Min n m))\n => Show (SVD t n m)\nderiving instance ( Eq (Matrix t n n)\n , Eq (Matrix t m m)\n , Eq (Vector t (Min n m)))\n => Eq (SVD t n m)\n\nclass RealFloatExtras t\n => MatrixSVD (t :: Type) (n :: Nat) (m :: Nat) where\n -- | Compute SVD factorization of a matrix\n svd :: IterativeMethod => Matrix t n m -> SVD t n m\n\n-- | Obvious dummy implementation of SVD for 1x1 matrices\nsvd1 :: (PrimBytes t, Num t, Eq t) => Matrix t 1 1 -> SVD t 1 1\nsvd1 m = SVD\n { svdU = 1\n , svdS = broadcast $ abs x\n , svdV = broadcast $ if x == 0 then 1 else signum x\n }\n where\n x = ixOff 0 m\n\n-- | SVD of a 2x2 matrix can be computed analytically\n--\n-- Related discussion:\n--\n-- https://scicomp.stackexchange.com/questions/8899/robust-algorithm-for-2-times-2-svd/\n--\n-- https://ieeexplore.ieee.org/document/486688\nsvd2 :: forall t . RealFloatExtras t => Matrix t 2 2 -> SVD t 2 2\nsvd2 (DF2 (DF2 m00 m01) (DF2 m10 m11)) =\n SVD\n { svdU = DF2 (DF2 uc us)\n (DF2 (negate us) uc)\n , svdS = DF2 sigma1 (abs sigma2)\n , svdV = DF2 (DF2 vc (sg2 (negate vs)))\n (DF2 vs (sg2 vc ))\n }\n where\n x1 = m00 - m11 -- 2F\n x2 = m00 + m11 -- 2E\n y1 = m01 + m10 -- 2G\n y2 = m01 - m10 -- 2H\n yy = y1*y2\n h1 = hypot x1 y1 -- h1 >= abs x1\n h2 = hypot x2 y2 -- h2 >= abs x2\n sigma1 = 0.5 * (h2 + h1) -- sigma1 >= abs sigma2\n sigma2 = 0.5 * (h2 - h1) -- can be negative, which is accounted by sg2\n sg2 = negateUnless (sigma2 >= 0)\n hx1 = h1 + x1\n hx2 = h2 + x2\n hxhx = hx1*hx2\n hxy = hx1*y2\n yhx = y1*hx2\n (uc', us', vc', vs') = case (x1 > 0 || y1 /= 0, x2 > 0 || y2 /= 0) of\n (True , True ) -> (hxhx + yy, hxy - yhx, hxhx - yy, hxy + yhx)\n (True , False) -> (y1, hx1, -y1, hx1)\n (False, True ) -> (y2, -hx2, -y2, hx2)\n (False, False) -> (1, 0, -1, 0)\n ru = recip $ hypot uc' us'\n rv = recip $ hypot vc' vs'\n uc = uc' * ru\n us = us' * ru\n vc = vc' * rv\n vs = vs' * rv\n\n-- | Get SVD decomposition of a 3x3 matrix using `svd3q` function.\n--\n-- This function reorders the singular components under the hood to make sure\n-- @s1 >= s2 >= s3 >= 0@.\n-- Thus, it has some overhead on top of `svd3q`.\nsvd3 :: forall t . (Quaternion t, RealFloatExtras t) => Matrix t 3 3 -> SVD t 3 3\nsvd3 m = SVD\n { svdU = toMatrix33 u\n , svdS = DF3 s1 s2 s3'\n , svdV = neg3If (s3 < 0) (toMatrix33 v)\n }\n where\n (u, (DF3 s1 s2 s3), v) = svd3q m\n s3' = abs s3\n neg3If :: Bool -> Matrix t 3 3 -> Matrix t 3 3\n neg3If False = id\n neg3If True = ewmap @t @'[3] neg3\n neg3 :: Vector t 3 -> Vector t 3\n neg3 (DF3 a b c) = DF3 a b (negate c)\n\n\n-- | Get SVD decomposition of a 3x3 matrix, with orthogonal matrices U and V\n-- represented as quaternions.\n-- Important: U and V are bound to be rotations at the expense of the last\n-- singular value being possibly negative.\n--\n-- This is an adoptation of a specialized 3x3 SVD algorithm described in\n-- \"Computing the Singular Value Decomposition of 3x3 matrices\n-- with minimal branching and elementary floating point operations\",\n-- by A. McAdams, A. Selle, R. Tamstorf, J. Teran, E. Sifakis.\n--\n-- http://pages.cs.wisc.edu/~sifakis/papers/SVD_TR1690.pdf\nsvd3q :: forall t . (Quaternion t, RealFloatExtras t)\n => Matrix t 3 3 -> (Quater t, Vector t 3, Quater t)\nsvd3q m = (u, s, v)\n where\n v = jacobiEigenQ (transpose m %* m)\n (s, u) = uncurry fixSigns $ qrDecomposition3 (m %* toMatrix33 v)\n -- last bit: make sure s1 >= s2 >= 0\n fixSigns :: Vector t 3 -> Quater t -> (Vector t 3, Quater t)\n fixSigns (DF3 s1 s2 s3) q@(Quater a b c d) = case (s1 >= 0, s2 >= 0) of\n (True , True ) -> (mk3 s1 s2 s3, q)\n (False, True ) -> (mk3 (negate s1) s2 (negate s3), Quater (-c) d a (-b))\n (True , False) -> (mk3 s1 (negate s2) (negate s3), Quater d c (-b) (-a))\n (False, False) -> (mk3 (negate s1) (negate s2) s3, Quater b (-a) d (-c))\n -- one more thing:\n -- the singular values are ordered, but may have small errors;\n -- as a result adjacent values may seem to be out of order by a very small number\n mk3 :: Scalar t -> Scalar t -> Scalar t -> Vector t 3\n mk3 s1 s2 s3' = case (s1 >= s2, s1 >= abs s3, s2 >= abs s3) of\n (True , True , True ) -> DF3 s1 s2 s3' -- s1 >= s2 >= s3\n (True , True , False) -> DF3 s1 s3 (cs s2) -- s1 >= s3 > s2\n (True , False, _ ) -> DF3 s3 s1 (cs s2) -- s3 > s1 >= s2\n (False, True , True ) -> DF3 s2 s1 s3' -- s2 > s1 >= s3\n (False, _ , False) -> DF3 s3 s2 (cs s1) -- s3 > s2 > s1\n (False, False, True ) -> DF3 s2 s3 (cs s1) -- s2 >= s3 > s1\n where\n s3 = abs s3'\n cs = negateUnless (s3' >= 0)\n\n\n-- | Approximate values for cos (a/2) and sin (a/2) of a Givens rotation for\n-- a 2x2 symmetric matrix. (Algorithm 2)\njacobiGivensQ :: forall t . RealFloatExtras t => t -> t -> t -> (t, t)\njacobiGivensQ aii aij ajj\n | g*sh*sh < ch*ch = (w * ch, w * sh)\n | otherwise = (c', s')\n where\n ch = 2 * (aii-ajj)\n sh = aij\n w = recip $ hypot ch sh\n g = 5.82842712474619 :: t -- 3 + sqrt 8\n c' = 0.9238795325112867 :: t -- cos (pi/8)\n s' = 0.3826834323650898 :: t -- sin (pi/8)\n\n\n-- | A quaternion for a QR Givens iteration\nqrGivensQ :: forall t . RealFloatExtras t => t -> t -> (t, t)\nqrGivensQ a1 a2\n | a1 < 0 = (sh * w, ch * w)\n | otherwise = (ch * w, sh * w)\n where\n rho2 = a1*a1 + a2*a2\n sh = if rho2 > M_EPS then a2 else 0\n ch = abs a1 + sqrt (max rho2 M_EPS)\n w = recip $ hypot ch sh -- TODO: consider something like a hypot\n\n\n-- | One iteration of the Jacobi algorithm on a symmetric 3x3 matrix\n--\n-- The three words arguments are indices:\n-- 0 <= i /= j /= k <= 2\njacobiEigen3Iteration :: (Quaternion t, RealFloatExtras t)\n => Int -> Int -> Int\n -> STDataFrame s t '[3,3]\n -> ST s (Quater t)\njacobiEigen3Iteration i j k sPtr = do\n sii <- readDataFrameOff sPtr ii\n sij <- readDataFrameOff sPtr ij\n sjj <- readDataFrameOff sPtr jj\n sik <- readDataFrameOff sPtr ik\n sjk <- readDataFrameOff sPtr jk\n -- Coefficients for a quaternion corresponding to a Givens rotation\n let (ch, sh) = jacobiGivensQ sii sij sjj\n a = ch*ch - sh*sh\n b = 2 * sh*ch\n aa = a * a\n ab = a * b\n bb = b * b\n -- update the matrix\n writeDataFrameOff sPtr ii $\n aa * sii + 2 * ab * sij + bb * sjj\n writeDataFrameOff sPtr ij $\n ab * (sjj - sii) + (aa - bb) * sij\n writeDataFrameOff sPtr jj $\n bb * sii - 2 * ab * sij + aa * sjj\n writeDataFrameOff sPtr ik $ a * sik + b * sjk\n writeDataFrameOff sPtr jk $ a * sjk - b * sik\n\n -- write the quaternion\n qPtr <- unsafeThawDataFrame 0\n writeDataFrameOff qPtr k (negate sh)\n writeDataFrameOff qPtr 3 ch\n fromVec4 <$> unsafeFreezeDataFrame qPtr\n where\n ii = i*3 + i\n ij = if i < j then i*3 + j else j*3 + i\n jj = j*3 + j\n ik = if i < k then i*3 + k else k*3 + i\n jk = if j < k then j*3 + k else k*3 + j\n\n\n-- | Total number of the Givens rotations during the Jacobi eigendecomposition\n-- part of the 3x3 SVD equals eigenItersX3*3.\n-- Value `eigenItersX3 = 6` corresponds to 18 iterations and gives a good precision.\neigenItersX3 :: Int\neigenItersX3 = 12\n\n-- | Run a few iterations of the Jacobi algorithm on a real-valued 3x3 symmetric matrix.\n-- The eigenvectors basis of such matrix is orthogonal, and can be represented as\n-- a quaternion.\njacobiEigenQ :: forall t\n . (Quaternion t, RealFloatExtras t)\n => Matrix t 3 3 -> Quater t\njacobiEigenQ m = runST $ do\n mPtr <- thawDataFrame m\n q <- go eigenItersX3 mPtr 1\n s1 <- readDataFrameOff mPtr 0\n s2 <- readDataFrameOff mPtr 4\n s3 <- readDataFrameOff mPtr 8\n return $ sortQ s1 s2 s3 * q\n where\n go :: Int -> STDataFrame s t '[3,3] -> Quater t -> ST s (Quater t)\n go 0 _ q = pure q\n\n -- -- primitive cyclic iteration;\n -- -- fast, but the convergence is not perfect\n -- --\n -- -- set eigenItersX3 = 6 for good precision\n -- go n p q = do\n -- q1 <- jacobiEigen3Iteration 0 1 2 p\n -- q2 <- jacobiEigen3Iteration 1 2 0 p\n -- q3 <- jacobiEigen3Iteration 2 0 1 p\n -- go (n - 1) p (q3 * q2 * q1 * q)\n\n -- Pick the largest element on lower triangle;\n -- slow because of branching, but has a better convergence\n --\n -- set eigenItersX3 = 12 for good precision\n -- (slightly faster than the cyclic version with -O0)\n go n p q = do\n a10 <- abs <$> readDataFrameOff p 1\n a20 <- abs <$> readDataFrameOff p 2\n a21 <- abs <$> readDataFrameOff p 5\n q' <- jiter n p a10 a20 a21\n go (n - 1) p (q' * q)\n jiter :: Int -> STDataFrame s t '[3,3]\n -> Scalar t -> Scalar t -> Scalar t -> ST s (Quater t)\n jiter n p a10 a20 a21\n | gt2 a10 a20 a21\n = jacobiEigen3Iteration 0 1 2 p\n | gt2 a20 a10 a21\n = jacobiEigen3Iteration 2 0 1 p\n | gt2 a21 a10 a20\n = jacobiEigen3Iteration 1 2 0 p\n | otherwise\n = case mod n 3 of\n 0 -> jacobiEigen3Iteration 0 1 2 p\n 1 -> jacobiEigen3Iteration 2 0 1 p\n _ -> jacobiEigen3Iteration 1 2 0 p\n gt2 :: Scalar t -> Scalar t -> Scalar t -> Bool\n gt2 a b c = case compare a b of\n GT -> a >= c\n EQ -> a > c\n LT -> False\n\n -- Make such a quaternion that rotates the matrix so that:\n -- abs s1 >= abs s2 >= abs s3\n -- Note, the corresponding singular values may be negative, which must be\n -- taken into account later.\n sortQ :: Scalar t -> Scalar t -> Scalar t -> Quater t\n sortQ s1 s2 s3 = sortQ' (s1 >= s2) (s1 >= s3) (s2 >= s3)\n sortQ' :: Bool -> Bool -> Bool -> Quater t\n sortQ' True True True = Quater 0 0 0 1 -- s1 >= s2 >= s3\n sortQ' True True False = Quater M_SQRT1_2 0 0 (-M_SQRT1_2) -- s1 >= s3 > s2\n sortQ' True False _ = Quater 0.5 0.5 0.5 0.5 -- s3 > s1 >= s2\n sortQ' False True True = Quater 0 0 M_SQRT1_2 (-M_SQRT1_2) -- s2 > s1 >= s3\n sortQ' False _ False = Quater 0 M_SQRT1_2 0 (-M_SQRT1_2) -- s3 > s2 > s1\n sortQ' False False True = Quater 0.5 0.5 0.5 (-0.5) -- s2 >= s3 > s1\n\n\n-- | One Givens rotation for a QR algorithm on a 3x3 matrix\n--\n-- The three words arguments are indices:\n-- 0 <= i /= j /= k <= 2\n--\n-- if i < j then the eigen values are already sorted!\nqrDecomp3Iteration :: (Quaternion t, RealFloatExtras t)\n => Int -> Int -> Int\n -> STDataFrame s t '[3,3]\n -> ST s (Quater t)\nqrDecomp3Iteration i j k sPtr = do\n sii <- readDataFrameOff sPtr ii\n sij <- readDataFrameOff sPtr ij\n sji <- readDataFrameOff sPtr ji\n sjj <- readDataFrameOff sPtr jj\n sik <- readDataFrameOff sPtr ik\n sjk <- readDataFrameOff sPtr jk\n -- Coefficients for a quaternion corresponding to a Givens rotation\n let (ch, sh) = qrGivensQ sii sji\n a = ch*ch - sh*sh\n b = 2 * sh*ch\n -- update the matrix\n writeDataFrameOff sPtr ii $ a * sii + b * sji\n writeDataFrameOff sPtr ij $ a * sij + b * sjj\n writeDataFrameOff sPtr ik $ a * sik + b * sjk\n writeDataFrameOff sPtr ji 0 -- a * sji - b * sii\n writeDataFrameOff sPtr jj $ a * sjj - b * sij\n writeDataFrameOff sPtr jk $ a * sjk - b * sik\n\n -- write the quaternion\n qPtr <- unsafeThawDataFrame 0\n writeDataFrameOff qPtr k (negateUnless leftTriple sh)\n writeDataFrameOff qPtr 3 ch\n fromVec4 <$> unsafeFreezeDataFrame qPtr\n where\n leftTriple = (j - i) /= 1 && (k - j) /= 1\n i3 = i*3\n j3 = j*3\n ii = i3 + i\n ij = i3 + j\n ik = i3 + k\n ji = j3 + i\n jj = j3 + j\n jk = j3 + k\n\n-- | Run QR decomposition in context of 3x3 svd: AV = US = QR\n-- The input here is matrix AV\n-- The R upper-triangular matrix here is in fact a diagonal matrix Sigma;\n-- The Q orthogonal matrix is matrix U in the svd decomposition,\n-- represented here as a quaternion.\nqrDecomposition3 :: (Quaternion t, RealFloatExtras t)\n => Matrix t 3 3 -> (Vector t 3, Quater t)\nqrDecomposition3 m = runST $ do\n mPtr <- thawDataFrame m\n q1 <- qrDecomp3Iteration 0 1 2 mPtr\n q2 <- qrDecomp3Iteration 0 2 1 mPtr\n q3 <- qrDecomp3Iteration 1 2 0 mPtr\n sig0 <- readDataFrameOff mPtr 0\n sig1 <- readDataFrameOff mPtr 4\n sig2 <- readDataFrameOff mPtr 8\n return (DF3 sig0 sig1 sig2, q3 * q2 * q1)\n\n\ninstance RealFloatExtras t => MatrixSVD t 1 1 where\n svd = svd1\n\ninstance RealFloatExtras t => MatrixSVD t 2 2 where\n svd = svd2\n\ninstance (RealFloatExtras t, Quaternion t) => MatrixSVD t 3 3 where\n svd = svd3\n\ninstance {-# INCOHERENT #-}\n ( RealFloatExtras t, KnownDim n, KnownDim m)\n => MatrixSVD t n m where\n svd a = runST $ do\n D <- pure dnm\n Dict <- pure $ minIsSmaller dn dm -- GHC is not convinced :(\n alphas <- unsafeThawDataFrame bdAlpha\n betas <- unsafeThawDataFrame bdBeta\n uPtr <- unsafeThawDataFrame bdU\n vPtr <- unsafeThawDataFrame bdV\n\n -- remove last beta if m > n\n bLast <- readDataFrameOff betas nm1\n when (abs bLast > M_EPS) $\n svdGolubKahanZeroCol alphas betas vPtr nm1\n\n -- main routine for a bidiagonal matrix\n let maxIter = 3*nm -- number of tries\n withinIters <- svdBidiagonalInplace alphas betas uPtr vPtr nm maxIter\n unless withinIters . tooManyIterations\n $ \"SVD - Givens rotation sweeps for a bidiagonal matrix (\"\n ++ show maxIter ++ \" sweeps max).\"\n\n -- sort singular values\n sUnsorted <- unsafeFreezeDataFrame alphas\n let sSorted :: Vector (Tuple '[t, Word]) (Min n m)\n sSorted = sortBy (\\(S (x :! _)) (S (y :! _)) -> compare y x)\n $ iwmap @_ @_ @'[] (\\(Idx i :* U) (S x) -> S (abs x :! i :! U) ) sUnsorted\n svdS = ewmap @t @_ @'[] (\\(S (x :! _)) -> S x) sSorted\n perm = ewmap @Word @_ @'[] (\\(S (_ :! i :! U)) -> S i) sSorted\n pCount =\n if nm < 2\n then 0 :: Word\n else foldl (\\s (i, j) -> if perm!i > perm!j then succ s else s)\n 0 [(i, j) | i <- [0..nm2w], j <- [i+1..nm2w+1]]\n pPositive = even pCount\n\n -- alphas and svdS are now out of sync, but that is not a problem\n\n -- make sure det U == 1\n when ((bdUDet < 0) == pPositive) $ do\n readDataFrameOff alphas 0 >>= writeDataFrameOff alphas 0 . negate\n forM_ [0..n - 1] $ \\i ->\n readDataFrameOff uPtr (i*n) >>= writeDataFrameOff uPtr (i*n) . negate\n\n -- negate negative singular values\n forM_ [0..nm1] $ \\i -> do\n s <- readDataFrameOff alphas i\n when (s < 0) $ do\n writeDataFrameOff alphas i $ negate s\n forM_ [0..m - 1] $ \\j ->\n readDataFrameOff vPtr (j*m + i)\n >>= writeDataFrameOff vPtr (j*m + i) . negate\n\n -- apply permutations if necessary\n if pCount == 0\n then do\n svdU <- unsafeFreezeDataFrame uPtr\n svdV <- unsafeFreezeDataFrame vPtr\n return SVD {..}\n else do\n svdU' <- unsafeFreezeDataFrame uPtr\n svdV' <- unsafeFreezeDataFrame vPtr\n let svdU = iwgen @_ @_ @'[] $ \\(i :* Idx j :* U) ->\n if j >= dimVal dnm\n then index (i :* Idx j :* U) svdU'\n else index (i :* Idx (unScalar $ perm!j) :* U) svdU'\n svdV = iwgen @_ @_ @'[] $ \\(i :* Idx j :* U) ->\n if j >= dimVal dnm\n then index (i :* Idx j :* U) svdV'\n else index (i :* Idx (unScalar $ perm!j) :* U) svdV'\n return SVD {..}\n where\n n = fromIntegral $ dimVal dn :: Int\n m = fromIntegral $ dimVal dm :: Int\n dn = dim @n\n dm = dim @m\n dnm = minDim dn dm\n nm1 = nm - 1\n nm = fromIntegral (dimVal dnm) :: Int\n nm2w = fromIntegral (max (nm - 2) 0) :: Word\n -- compute the bidiagonal form b first, solve svd for b.\n BiDiag {..} = bidiagonalHouseholder a\n\n\n\n{- Compute svd for a square bidiagonal matrix inplace\n \\( B = U S V^\\intercal \\)\n\n@\n B = | a1 b1 0 ... 0 |\n | 0 a2 b2 0 ... 0 |\n | 0 0 a3 b3 ... 0 |\n | ................. |\n | 0 0 ... an1 bn1 |\n | 0 0 ... 0 an | bn? (in case if n > m)\n@\n -}\nsvdBidiagonalInplace ::\n forall (s :: Type) (t :: Type) (n :: Nat) (m :: Nat) (nm :: Nat)\n . ( IterativeMethod, RealFloatExtras t\n , KnownDim n, KnownDim m, KnownDim nm, nm ~ Min n m)\n => STDataFrame s t '[nm] -- ^ the main diagonal of B and then the singular values.\n -> STDataFrame s t '[nm] -- ^ first upper diagonal of B\n -> STDataFrame s t '[n,n] -- ^ U\n -> STDataFrame s t '[m,m] -- ^ V\n -> Int -- ^ 0 < q <= nm -- size of a reduced matrix, such that leftover is diagonal\n -> Int -- iters\n -> ST s Bool -- whether the algorithm succeeds within the maxIter\nsvdBidiagonalInplace _ _ _ _ 0 _ = pure True\nsvdBidiagonalInplace _ _ _ _ 1 _ = pure True\nsvdBidiagonalInplace _ _ _ _ _ 0 = pure False\nsvdBidiagonalInplace aPtr bPtr uPtr vPtr q' iter = do\n Dict <- pure $ minIsSmaller (dim @n) (dim @m)\n (p, q) <- findCounters q'\n if (q /= 0)\n then do\n findZeroDiagonal p q >>= \\case\n Just k\n | k == q-1 -> svdGolubKahanZeroCol aPtr bPtr vPtr (k-1)\n | otherwise -> svdGolubKahanZeroRow aPtr bPtr uPtr k\n Nothing -> svdGolubKahanStep aPtr bPtr uPtr vPtr p q\n svdBidiagonalInplace aPtr bPtr uPtr vPtr q (iter - 1)\n else return True\n where\n -- nm = fromIntegral $ dimVal' @nm :: Int\n\n -- Check if off-diagonal elements are close to zero and nullify them\n -- if they are small along the way.\n -- And find such indices p and q that satisfy condition in alg. 8.6.2\n -- on p. 492. of \"Matrix Computations \" (4-th edition).\n -- Except these are inverted:\n -- p -- is the starting index of B22 (last submatrix with non-zero superdiagonal)\n -- q -- is the starting index of B33 (diagonal submatrix)\n --\n -- that is, p and q determine the index and the size of next work piece.\n findCounters :: Int -> ST s (Int, Int)\n findCounters = goQ\n where\n checkEps :: Int -> ST s Bool\n checkEps k = do\n b <- abs <$> readDataFrameOff bPtr (k-1)\n if b == 0\n then return True\n else do\n a1 <- abs <$> readDataFrameOff aPtr (k-1)\n a2 <- abs <$> readDataFrameOff aPtr k\n if b <= M_EPS * (max (a1 + a2) 1)\n then True <$ writeDataFrameOff bPtr (k-1) 0\n else return False\n goQ :: Int -> ST s (Int, Int)\n goQ 0 = pure (0, 0) -- guard against calling with q == 0\n goQ 1 = pure (0, 0) -- 1x1 matrix is always diagonal\n goQ k = checkEps (k-1) >>= \\case\n True -> goQ (k-1)\n False -> flip (,) k <$> goP (k-2)\n goP :: Int -> ST s Int\n goP 0 = pure 0\n goP k = checkEps k >>= \\case\n True -> return k\n False -> goP (k-1)\n\n -- For indices p and q (p < q), find the biggest index (< q) such that\n -- a[p] == 0\n findZeroDiagonal :: Int -> Int -> ST s (Maybe Int)\n findZeroDiagonal p q\n | k < p = pure Nothing\n | otherwise = do\n ak <- readDataFrameOff aPtr k\n if ak == 0\n then pure $ Just k\n else if abs ak <= M_EPS\n then Just k <$ writeDataFrameOff aPtr k 0\n else findZeroDiagonal p k\n where\n k = q - 1\n\n\n-- | Apply a series of column transformations to make b[k] (and whole column k+1) zero\n-- (page 491, 1st paragraph) when a[k+1] == 0.\n-- To make this element zero, I apply a series of Givens transforms on columns\n-- (multiply on the right).\n--\n-- Prerequisites:\n-- * a[k+1] == 0\n-- * 0 <= k < min n (m-1)\n-- Invariants:\n-- * matrix \\(B :: n \\times m \\) is bidiagonal, represented by two diagonals;\n-- * matrix V is orthogonal\n-- * \\( B = A V^\\intercal \\), where \\(A :: n \\times m\\) is an implicit original matrix\n-- Results:\n-- * Same bidiagonal matrix with b[k] == 0; i.e. (k+1)-th column is zero.\n-- * matrix V is updated (multiplied on the right)\n--\n-- NB: All changes are made inplace.\n--\nsvdGolubKahanZeroCol ::\n forall (s :: Type) (t :: Type) (n :: Nat) (m :: Nat)\n . (RealFloatExtras t, KnownDim n, KnownDim m, n <= m)\n => STDataFrame s t '[n] -- ^ the main diagonal of \\(B\\)\n -> STDataFrame s t '[n] -- ^ first upper diagonal of \\(B\\)\n -> STDataFrame s t '[m,m] -- ^ \\(V\\)\n -> Int -- ^ 0 <= k < min (n+1) m\n -> ST s ()\nsvdGolubKahanZeroCol aPtr bPtr vPtr k\n | k < 0 || k >= lim = error $ unwords\n [ \"svdGolubKahanZeroCol: k =\", show k\n , \"is outside of a valid range 0 <= k <\", show lim]\n -- this trick is to convince GHC that constraint (n <= m) is not redundant\n | Dict <- Dict @(n <= m) = do\n b <- readDataFrameOff bPtr k\n writeDataFrameOff bPtr k 0\n foldM_ goGivens b [k, k-1 .. 0]\n where\n n = fromIntegral $ dimVal' @n :: Int\n m = fromIntegral $ dimVal' @m :: Int\n lim = min n (m-1)\n goGivens :: Scalar t -> Int -> ST s (Scalar t)\n goGivens 0 _ = return 0 -- non-diagonal element is nullified prematurely\n goGivens b i = do\n ai <- readDataFrameOff aPtr i\n let rab = recip $ hypot b ai\n c = ai*rab\n s = b *rab\n updateGivensMat vPtr i (k+1) c s\n writeDataFrameOff aPtr i $ ai*c + b*s -- B[i,i]\n if i == 0\n then return 0\n else do\n bi1 <- readDataFrameOff bPtr (i - 1) -- B[i,i-1]\n writeDataFrameOff bPtr (i - 1) $ bi1 * c\n return $ negate (bi1 * s)\n\n-- | Apply a series of row transformations to make b[k] (and whole column k) zero\n-- (page 490, last paragraph) when a[k] == 0.\n-- To make this element zero, I apply a series of Givens transforms on rows\n-- (multiply on the left).\n--\n-- Prerequisites:\n-- * a[k] == 0\n-- * 0 <= k < n - 1\n-- Invariants:\n-- * matrix \\(B :: m \\times n \\) is bidiagonal, represented by two diagonals;\n-- * matrix U is orthogonal\n-- * \\( B = U A \\), where \\(A :: m \\times n \\) is an implicit original matrix\n-- Results:\n-- * Same bidiagonal matrix with b[k] == 0; i.e. k-th column is zero.\n-- * matrix U is updated (multiplied on the right)\n--\n-- NB: All changes are made inplace.\n--\nsvdGolubKahanZeroRow ::\n forall (s :: Type) (t :: Type) (n :: Nat) (m :: Nat)\n . (RealFloatExtras t, KnownDim n, KnownDim m, n <= m)\n => STDataFrame s t '[n] -- ^ the main diagonal of B\n -> STDataFrame s t '[n] -- ^ first upper diagonal of B\n -> STDataFrame s t '[m,m] -- ^ U\n -> Int -- ^ 0 <= k < n - 1\n -> ST s ()\nsvdGolubKahanZeroRow aPtr bPtr uPtr k\n | k < 0 || k >= n1 = error $ unwords\n [ \"svdGolubKahanZeroRow: k =\", show k\n , \"is outside of a valid range 0 <= k <\", show n1]\n -- this trick is to convince GHC that constraint (n <= m) is not redundant\n | Dict <- Dict @(n <= m) = do\n b <- readDataFrameOff bPtr k\n writeDataFrameOff bPtr k 0\n foldM_ goGivens b [k+1..n1]\n where\n n = fromIntegral $ dimVal' @n :: Int\n n1 = n - 1\n goGivens :: Scalar t -> Int -> ST s (Scalar t)\n goGivens 0 _ = return 0 -- non-diagonal element is nullified prematurely\n goGivens b j = do\n aj <- readDataFrameOff aPtr j\n bj <- readDataFrameOff bPtr j\n let rab = recip $ hypot b aj\n c = aj*rab\n s = b*rab\n updateGivensMat uPtr k j c (negate s)\n writeDataFrameOff aPtr j $ b*s + aj*c\n writeDataFrameOff bPtr j $ bj*c\n return $ negate (bj * s)\n\n-- | A Golub-Kahan bidiagonal SVD step on an unreduced matrix\nsvdGolubKahanStep ::\n forall (s :: Type) (t :: Type) (n :: Nat) (m :: Nat) (nm :: Nat)\n . ( RealFloatExtras t\n , KnownDim n, KnownDim m, KnownDim nm, nm ~ Min n m)\n => STDataFrame s t '[nm] -- ^ the main diagonal of B and then the singular values.\n -> STDataFrame s t '[nm] -- ^ first upper diagonal of B\n -> STDataFrame s t '[n,n] -- ^ U\n -> STDataFrame s t '[m,m] -- ^ V\n -> Int -- ^ p : 0 <= p < q <= nm; p <= q - 2\n -> Int -- ^ q : 0 <= p < q <= nm; p <= q - 2\n -> ST s ()\nsvdGolubKahanStep aPtr bPtr uPtr vPtr p q\n | p > q - 2 || p < 0 || q > nm\n = error $ unwords\n [ \"svdGolubKahanStep: p =\", show p, \"and q =\", show q\n , \"do not satisfy p <= q - 2 or 0 <= p < q <=\", show nm]\n | Dict <- Dict @(nm ~ Min n m) = do\n (y,z) <- getWilkinsonShiftYZ\n goGivens2 y z p\n where\n nm = fromIntegral $ dimVal' @nm :: Int\n\n -- get initial values for one recursion sweep.\n -- Note, input must satisfy: q >= p+2\n getWilkinsonShiftYZ :: ST s (Scalar t, Scalar t)\n getWilkinsonShiftYZ = do\n a1 <- readDataFrameOff aPtr p\n b1 <- readDataFrameOff bPtr p\n am <- readDataFrameOff aPtr (q-2)\n an <- readDataFrameOff aPtr (q-1)\n bm <- if q >= p + 3\n then readDataFrameOff bPtr (q-3)\n else pure 0\n bn <- readDataFrameOff bPtr (q-2)\n let t11 = a1*a1\n t12 = a1*b1\n tmm = am*am + bm*bm\n tnn = an*an + bn*bn\n tnm = am*bn\n d = 0.5*(tmm - tnn)\n mu = tnn + d - negateUnless (d >= 0) (hypot d tnm)\n return (t11 - mu, t12)\n\n -- yv = b[k-1]; zv = B[k-1,k+1] -- to be eliminated by 1st Givens r\n -- yu = a[k]; zu = B[k+1,k-1] -- to be eliminated by 2nd Givens r\n goGivens2 :: Scalar t -> Scalar t -> Int -> ST s ()\n goGivens2 yv zv k = do\n a1 <- readDataFrameOff aPtr k -- B[k,k]\n a2 <- readDataFrameOff aPtr (k+1) -- B[k+1,k+1]\n b1 <- readDataFrameOff bPtr k -- B[k,k+1]\n let a1' = a1*cv + b1*sv -- B[k,k] == yu\n a2' = a2*cv -- B[k+1,k+1]\n b0' = yv*cv + zv*sv -- B[k-1,k]\n b1' = b1*cv - a1*sv -- B[k,k+1]\n yu = a1' -- B[k,k]\n zu = a2*sv -- B[k+1,k]\n ryzu = recip $ hypot yu zu\n cu = yu * ryzu\n su = zu * ryzu\n a1'' = yu *cu + zu *su\n a2'' = a2'*cu - b1'*su\n b1'' = b1'*cu + a2'*su\n updateGivensMat vPtr k (k+1) cv sv\n updateGivensMat uPtr k (k+1) cu su\n\n when (k > p) $ writeDataFrameOff bPtr (k-1) b0'\n writeDataFrameOff bPtr k b1''\n writeDataFrameOff aPtr k a1''\n writeDataFrameOff aPtr (k+1) a2''\n when (k < q - 2) $ do\n b2 <- readDataFrameOff bPtr (k+1) -- B[k+1,k+2]\n let b2'' = b2*cu\n zvn = b2*su\n writeDataFrameOff bPtr (k+1) b2''\n goGivens2 b1'' zvn (k+1)\n where\n ryzv = recip $ hypot yv zv\n cv = yv * ryzv\n sv = zv * ryzv\n\n-- | Update a transformation matrix with a Givens transform (on the right)\nupdateGivensMat ::\n forall (s :: Type) (t :: Type) (n :: Nat)\n . (PrimBytes t, Num t, KnownDim n)\n => STDataFrame s t '[n,n]\n -> Int -> Int\n -> Scalar t -> Scalar t -> ST s ()\nupdateGivensMat p i j c s = forM_ [0..n-1] $ \\k -> do\n let nk = n*k\n ioff = nk + i\n joff = nk + j\n uki <- readDataFrameOff p ioff\n ukj <- readDataFrameOff p joff\n writeDataFrameOff p ioff $ uki*c + ukj*s\n writeDataFrameOff p joff $ ukj*c - uki*s\n where\n n = fromIntegral $ dimVal' @n :: Int\n\n\nminIsSmaller :: forall (n :: Nat) (m :: Nat)\n . Dim n -> Dim m -> Dict (Min n m <= n, Min n m <= m)\nminIsSmaller dn dm\n | Just Dict <- lessOrEqDim dnm dn\n , Just Dict <- lessOrEqDim dnm dm\n = Dict\n | otherwise\n = error \"minIsSmaller: impossible type-level comparison\"\n where\n dnm = minDim dn dm\n", "meta": {"hexsha": "eaf706cf575a37247a8a5496f06569c06122c0c1", "size": 29643, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "easytensor/src/Numeric/Matrix/SVD.hs", "max_stars_repo_name": "achirkin/fasttensor", "max_stars_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 46, "max_stars_repo_stars_event_min_datetime": "2017-06-30T04:51:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:46:17.000Z", "max_issues_repo_path": "easytensor/src/Numeric/Matrix/SVD.hs", "max_issues_repo_name": "achirkin/fasttensor", "max_issues_repo_head_hexsha": "a2efcb0b918ad5f5f113f68290d9d25fcc89990b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-07-17T18:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T06:31:42.000Z", "max_forks_repo_path": "easytensor/src/Numeric/Matrix/SVD.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": 37.05375, "max_line_length": 92, "alphanum_fraction": 0.5577708059, "num_tokens": 10114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6709373373664922}} {"text": "module Gates where\n\nimport Protolude\n\nimport Control.Exception (assert)\nimport Data.Complex (Complex (..), magnitude)\nimport Data.List ((!!))\nimport qualified Data.Matrix as M\nimport qualified Data.Vector as V\nimport System.Random (randomIO)\n\nimport Instruction (Operation, Qubit, Qubits)\nimport State (QuantumState)\n\n-- Dimension in qubits by taking the log base 2\ndimensionQubits :: Integral a => a -> Int\ndimensionQubits = ceiling . logBase 2 . fromIntegral\n\ni :: Operation\ni = M.identity 2\n\nx :: Operation\nx = M.fromLists [[0, 1], [1, 0]]\n\nh :: Operation\nh = M.scaleMatrix (1 / sqrt 2) $ M.fromLists [[1, 1], [1, -1]]\n\ncnot :: Operation\ncnot = M.fromLists [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]\n\nswap :: Operation\nswap = M.fromLists [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]\n\n-- Apply an operation to a quantum state by matrix multiplication\napplyOperation :: Operation -> QuantumState -> QuantumState\napplyOperation g s = M.getCol 1 $ g * M.colVector s\n\n-- Compose operators by doing matrix multiplication\n-- NOTE: (*) operator chosen over multStd for possible speed improvements for larger matrices\ncomposeOperations :: Operation -> Operation -> Operation\ncomposeOperations = (*)\n\n-- Sample quantum state, randomly selecting a state, weighted by |phi_i|^2\nsample :: MonadIO m => QuantumState -> m Int\nsample s = do\n r <- liftIO $ randomIO\n return $ sampleIter r 0\n where\n sampleIter :: Double -> Int -> Int\n sampleIter r t =\n let newR = r - (magnitude (s V.! t)) ** 2\n in if newR < 0\n then t\n else sampleIter newR (t + 1)\n\n-- Collapse the quantum state into the state at the given index\ncollapse :: QuantumState -> Int -> QuantumState\ncollapse s i =\n V.generate\n (V.length s)\n (\\x ->\n if x == i\n then (1 :+ 0)\n else (0 :+ 0))\n\n-- Observe the quantum state and collapse into that state\nobserve :: MonadIO m => QuantumState -> m QuantumState\nobserve s = do\n i <- sample s\n return $ collapse s i\n\n-- Oh, to have dependent types\nkroneckerMultiply :: (Num a) => M.Matrix a -> M.Matrix a -> M.Matrix a\nkroneckerMultiply a b = M.flatten $ M.mapPos (\\_ -> flip M.scaleMatrix b) a\n\n-- TODO: re-eval constraints\nkroneckerExpt :: (Num a) => M.Matrix a -> Int -> M.Matrix a\nkroneckerExpt a n\n | n < 1 = M.fromLists [[1]]\n | n == 1 = a\n | otherwise = kroneckerMultiply (kroneckerExpt a (n - 1)) a\n\n-- Lift an operation by padding with identity\nliftOperation :: Operation -> Qubit -> Int -> Operation\nliftOperation a index n =\n assert (index < n) kroneckerMultiply left (kroneckerMultiply a right)\n where\n left = kroneckerExpt i (n - index - (dimensionQubits $ M.nrows a))\n right = kroneckerExpt i index\n\n-- Calculate needed transpositions from given permutation\npermutationToTranspositions :: [Int] -> [(Int, Int)]\npermutationToTranspositions p = permutationToTranspositionsIter 0\n where\n permutationToTranspositionsIter dest\n | dest == (length p) = []\n | otherwise =\n (case compare src dest of\n LT -> [(src, dest)]\n GT -> [(dest, src)]\n _ -> []) ++\n permutationToTranspositionsIter (dest + 1)\n where\n src = nextSrc (p !! dest) dest\n nextSrc s d\n | s < d = nextSrc (p !! s) d\n | otherwise = s\n\n-- Convert transpositions to list of adjacent transpositions\ntranspositionToAdjacentTranspositions :: [(Int, Int)] -> [Int]\ntranspositionToAdjacentTranspositions ts = foldMap expandCons ts\n where\n expandCons (x, y)\n | y - x == 1 = [x]\n | otherwise =\n let trans = [x .. y - 1]\n in trans ++ (reverse (initSafe trans))\n\n-- Apply 1 qubit gate\napply1QGate :: QuantumState -> Operation -> Qubit -> QuantumState\napply1QGate s a q =\n applyOperation (liftOperation a q (dimensionQubits (length s))) s\n\n-- Apply multiple qubit gate\napplynQGate :: QuantumState -> Operation -> Qubits -> QuantumState\napplynQGate s a qubits = do\n applyOperation upq s\n where\n n :: Int\n n = dimensionQubits (length s)\n transpositionsToOperation :: [Int] -> Operation\n transpositionsToOperation ts =\n foldr composeOperations (M.identity (2 ^ n)) $\n map (\\x -> liftOperation Gates.swap x n) ts\n u01 :: Operation\n u01 = liftOperation a 0 n\n fromSpace :: [Int]\n fromSpace =\n (reverse qubits) ++ (filter (\\x -> not (elem x qubits)) [0 .. n - 1])\n trans :: [Int]\n trans =\n transpositionToAdjacentTranspositions . permutationToTranspositions $\n fromSpace\n toFrom :: Operation\n toFrom = transpositionsToOperation trans\n fromTo :: Operation\n fromTo = transpositionsToOperation (reverse trans)\n upq :: Operation\n upq = composeOperations toFrom (composeOperations u01 fromTo)\n\n-- Apply gate, picking apply1QGate or applynQGate based on size\napplyGate :: QuantumState -> Operation -> [Int] -> QuantumState\napplyGate s a qubits =\n assert\n (length qubits == dimensionQubits (M.nrows a))\n (if length qubits == 1\n then apply1QGate s a (qubits !! 0)\n else applynQGate s a qubits)\n", "meta": {"hexsha": "f7401e366e960577c2fee364e2be1598cfe5b189", "size": 5162, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Gates.hs", "max_stars_repo_name": "colescott/quantum-interpreter", "max_stars_repo_head_hexsha": "e67bfe3a57080f84333b172c25ae8ade3c7a9e40", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-04T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:06:33.000Z", "max_issues_repo_path": "src/Gates.hs", "max_issues_repo_name": "colescott/quantum-interpreter", "max_issues_repo_head_hexsha": "e67bfe3a57080f84333b172c25ae8ade3c7a9e40", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Gates.hs", "max_forks_repo_name": "colescott/quantum-interpreter", "max_forks_repo_head_hexsha": "e67bfe3a57080f84333b172c25ae8ade3c7a9e40", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.465408805, "max_line_length": 93, "alphanum_fraction": 0.6418055017, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6708173110573312}} {"text": "{-\n An attempt to implement a basic case of Cooley-Tukey FFT algorithm.\n -}\n{-# LANGUAGE ViewPatterns #-}\nmodule Main\n ( main\n ) where\n\nimport Control.DeepSeq\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Bits\nimport Data.Complex\nimport Data.Time.Clock\nimport Statistics.Sample\nimport System.Random\nimport Text.Printf\n\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as VM\n\ntype Cpx = Complex Double\n\n-- e^((c pi i) * (k / N))\nexpAuxCommon :: Int -> Int -> Int -> Cpx\nexpAuxCommon c k n = cis theta\n where\n theta = pi * fromIntegral (c * k) / fromIntegral n\n\n-- Computes e^((-2 pi i) * (k / N))\nexpFft :: Int -> Int -> Cpx\nexpFft = expAuxCommon (-2)\n\n-- Computes e^((2 pi i) * (k / N))\nexpIfft :: Int -> Int -> Cpx\nexpIfft = expAuxCommon 2\n\nsplitByParity :: V.Vector Cpx -> (V.Vector Cpx, V.Vector Cpx)\nsplitByParity vs = (evens, odds)\n where\n l = V.length vs\n oddCount = (l + 1) `quot` 2\n evenCount = l - oddCount\n evens =\n V.fromListN evenCount $ (vs V.!) <$> [0,2..]\n odds =\n V.fromListN oddCount $ (vs V.!) <$> [1,3..]\n\n-- TODO: For now we assume that vector length is a power of two,\n-- this can be easily extended to any length, by pretending out-of-range\n-- values are 0.\ngDitFft :: (Int -> Int -> Cpx) -> V.Vector Cpx -> V.Vector Cpx\ngDitFft expF = fix $\n \\impl vs ->\n let l = V.length vs\n in if l <= 1\n then vs\n else V.create $ do\n let (impl -> es, impl -> os) = splitByParity vs\n hf = l `quot` 2\n vec <- VM.unsafeNew l\n forM_ [0 .. hf - 1] $ \\k -> do\n let a = es V.! k\n b = expF k l * os V.! k\n VM.unsafeWrite vec k (a + b)\n VM.unsafeWrite vec (hf + k) (a - b)\n pure vec\n\nditFft :: V.Vector Cpx -> V.Vector Cpx\nditFft = gDitFft expFft . rightPadZeros\n\niditFft :: V.Vector Cpx -> V.Vector Cpx\niditFft (rightPadZeros -> vs) = V.map (/ fromIntegral l) (iditFftAux vs)\n where\n l = V.length vs\n iditFftAux :: V.Vector Cpx -> V.Vector Cpx\n iditFftAux = gDitFft expIfft\n\n{-\n right padding zeros in the end of a matrix to make the length of the vector\n a power of 2.\n\n special case: returns empty vector when the input is empty.\n -}\nrightPadZeros :: V.Vector Cpx -> V.Vector Cpx\nrightPadZeros vs\n | l <= 1 = vs\n | isPowerOf2 = vs\n | otherwise =\n let closestPowOf2Gt =\n {-\n Find the closest power of two that is greater or equal to input v.\n only works when v > 1 and v is not a power of two.\n -}\n unsafeShiftL 1 (finiteBitSize l - countLeadingZeros l)\n in vs <> V.fromListN (closestPowOf2Gt - l) (repeat 0)\n where\n l = V.length vs\n isPowerOf2 =\n countLeadingZeros l + countTrailingZeros l + 1 == finiteBitSize l\n\nevaluateOnVector :: V.Vector Cpx -> IO ()\nevaluateOnVector vs = do\n let result = iditFft (ditFft vs)\n diffs :: V.Vector Double\n diffs = V.zipWith (\\x y -> magnitude (x - y)) vs result\n printf \"StdDev: %.9f\\n\" (stdDev diffs)\n\ntype M = StateT StdGen IO\n\ngenRandomR :: Random a => (a, a) -> M a\ngenRandomR = state . randomR\n\ngenCpxVector :: M (V.Vector Cpx)\ngenCpxVector =\n genRandomR (1024, 8192) >>= genCpxVectorOfSize\n\ngenCpxVectorOfSize :: Int -> M (V.Vector Cpx)\ngenCpxVectorOfSize l = do\n let rDouble = genRandomR (-100,100)\n xs <- replicateM l $ (:+) <$> rDouble <*> rDouble\n pure $ V.fromListN l xs\n\nevalRandomVector :: M ()\nevalRandomVector = do\n vs <- genCpxVector\n liftIO $ do\n printf \"Vector length: %d\\n\" (V.length vs)\n evaluateOnVector vs\n\ndirectConvolve :: V.Vector Cpx -> V.Vector Cpx -> V.Vector Cpx\ndirectConvolve xs ys = V.create $ do\n let lX = V.length xs\n lY = V.length ys\n lZ = lX + lY - 1\n vec <- VM.replicate lZ 0\n forM_ [0 .. lX - 1] $ \\i -> do\n let x = V.unsafeIndex xs i\n forM_ [0 .. lY - 1] $ \\j -> do\n let y = V.unsafeIndex ys j\n k = i + j\n v <- VM.unsafeRead vec k\n VM.unsafeWrite vec k $! v + x * y\n pure vec\n\nfftConvolve :: V.Vector Cpx -> V.Vector Cpx -> V.Vector Cpx\nfftConvolve xsPre ysPre = V.fromListN lZ (V.toList (iditFft rs))\n where\n lX = V.length xsPre\n lY = V.length ysPre\n lZ = lX + lY - 1\n -- TOOD: admittedly this is a bit wasteful...\n xs = V.fromListN lZ (V.toList xsPre <> repeat 0)\n ys = V.fromListN lZ (V.toList ysPre <> repeat 0)\n xs' = ditFft xs\n ys' = ditFft ys\n rs = V.zipWith (*) xs' ys'\n\nevalRandomConvolve :: M ()\nevalRandomConvolve = do\n xs <- genCpxVector\n ys <- genCpxVector\n let lX = V.length xs\n lY = V.length ys\n lZ = lX + lY - 1\n zsDirect = directConvolve xs ys\n zsFft = fftConvolve xs ys\n diffs :: V.Vector Double\n diffs = V.zipWith (\\x y -> magnitude (x - y)) zsDirect zsFft\n liftIO $ do\n putStrLn $ \"Vector lengths (xs,ys,xs * ys): \" <> show (lX, lY, lZ)\n _ <- forceAndMeasure \"Direct\" zsDirect\n _ <- forceAndMeasure \"FFT\" zsFft\n printf \"StdDev: %.9f\\n\" (stdDev diffs)\n\nforceAndMeasure :: NFData a => String -> a -> IO a\nforceAndMeasure tag r = do\n tBefore <- getCurrentTime\n tAfter <- r `deepseq` getCurrentTime\n printf \"Time (%s): %.6f\\n\" tag ((realToFrac $ diffUTCTime tAfter tBefore) :: Double)\n pure r\n\nmain :: IO ()\nmain = do\n let cs = (\\x -> x*2 :+ (x*2 + 1)) <$> [0..19]\n vs = V.fromList cs\n evaluateOnVector vs\n g <- newStdGen\n evalStateT (evalRandomVector >> evalRandomConvolve) g\n", "meta": {"hexsha": "64c8047710d3093250cf3c970d3a9f6edb633c82", "size": 5415, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "fft-playground/src/Main.hs", "max_stars_repo_name": "Javran/misc", "max_stars_repo_head_hexsha": "736d657fead5143c26f3e3b9b85039bf8185e824", "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": "fft-playground/src/Main.hs", "max_issues_repo_name": "Javran/misc", "max_issues_repo_head_hexsha": "736d657fead5143c26f3e3b9b85039bf8185e824", "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": "fft-playground/src/Main.hs", "max_forks_repo_name": "Javran/misc", "max_forks_repo_head_hexsha": "736d657fead5143c26f3e3b9b85039bf8185e824", "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.5, "max_line_length": 86, "alphanum_fraction": 0.6127423823, "num_tokens": 1800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297141, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6707858349621705}} {"text": "{-|\nModule : kMeans\nDescription : k-Means\nCopyright : (c) Fabrício Olivetti, 2017\nLicense : GPL-3\nMaintainer : fabricio.olivetti@gmail.com\n\nk-Means Clustering algorithm\n-}\n\nmodule KMeans where\n\nimport Data.List\nimport Data.Ord\n--import qualified Numeric.LinearAlgebra as H \n\nimport Vector\nimport Dados\n\n-- |'parseFile' parses a space separated file \n-- to a list of lists of Double\nparseFile :: String -> [[Double]]\nparseFile file = map parseLine (lines file)\n where\n parseLine l = map toDouble (words l)\n toDouble w = read w :: Double\n\nfirstClusters idxs points = [ points !! i | i <- idxs ]\n\nkmeans it points clusters\n | it == 0 = clusters\n | clusters' == clusters = clusters\n | otherwise = kmeans (it-1) points clusters'\n where\n clusters' = emStep points clusters\n\nemStep points clusters = maximizationStep $ estimationStep points clusters\n\nestimationStep :: [[Double]] -> [[Double]] -> [[[Double]]]\nestimationStep points clusters = map unTuple\n $ groupByValue\n $ sortByValue\n $ zip points \n $ assign points clusters\n where\n unTuple = map fst\n\nmaximizationStep :: [[[Double]]] -> [[Double]]\nmaximizationStep candidates = map mean candidates\n where\n mean xs = (foldl' (.+.) (head xs) (tail xs)) ./ (fromIntegral $ length xs)\n\nassign :: [[Double]] -> [[Double]] -> [Integer]\nassign points clusters = map closestTo points\n where\n closestTo p = argmin $ map (euclid p) clusters\n euclid pi ci = sum $ map (^2) $ zipWith (-) pi ci\n argmin xs = fst $ head $ sortByValue $ zip [0..] xs\n\n\n", "meta": {"hexsha": "d2c69b6034ce27b6278b417a73d769c0cce0a589", "size": 1674, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "09 - Agrupamento de Dados/KMeans.hs", "max_stars_repo_name": "douggribeiro/bigdata", "max_stars_repo_head_hexsha": "5f923b4f21bce48a1a202d5f8d984ac076059b5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-19T01:49:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-19T01:49:40.000Z", "max_issues_repo_path": "09 - Agrupamento de Dados/KMeans.hs", "max_issues_repo_name": "douggribeiro/bigdata", "max_issues_repo_head_hexsha": "5f923b4f21bce48a1a202d5f8d984ac076059b5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "09 - Agrupamento de Dados/KMeans.hs", "max_forks_repo_name": "douggribeiro/bigdata", "max_forks_repo_head_hexsha": "5f923b4f21bce48a1a202d5f8d984ac076059b5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-10-28T00:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-29T14:03:54.000Z", "avg_line_length": 27.4426229508, "max_line_length": 78, "alphanum_fraction": 0.6206690562, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7718435083355188, "lm_q1q2_score": 0.6705983018644236}} {"text": "\n{-|\n\n Module : HF.Gauss\n Copyright : Copyright (c) David Schlegel\n License : BSD\n Maintainer : David Schlegel\n Stability : experimental\n Portability : Haskell\n\nGaussian Integral evaluation plays an important role in quantum chemistry. Here functions will be provided to compute the most important integrals involving gaussian-type orbitals (GTOs).\n\nAn unnormalized primitive cartesian Gaussian Orbital has the form\n\n<> \n\nwhere /A/ denotes the center of the orbital.\n\nAn unnormalized contracted Gaussian Orbital is a linear combination of primitive Gaussian:\n\n<>\n\n\"Gauss\" uses the datatype contstructors 'PG' (Primitive Gaussian) and 'Ctr' (Contraction), defined in \"HF.Data\".\n\nNotice: Formulas of Gaussian Integrals are taken from:\n\tFundamentals of Molecular Integral Evaluation\n\tby Justin T. Fermann and Edward F. Valeev\n\n-}\n\n\n\nmodule HF.Gauss (\n-- * Basic functions\ndistance, frac, center, itersum, erf, f, factorial2, general_erf,\n-- * Normalization\nnormCtr, normPG,\n-- * Integral Evaluation\ns_12, t_12,\n-- * Contraction operations\nzipContractionWith, constr_matrix\n\n\n) where\n\nimport HF.Data\nimport Numeric.Container hiding (linspace)\nimport Numeric.LinearAlgebra.Data hiding (linspace)\nimport Data.Maybe\nimport Control.DeepSeq\nimport Debug.Trace\n\n\n\n---------------------\n---------------------\n--Helper Functions---\n---------------------\n---------------------\n\n\nitersum function range\n\t| range == [] = 0\n\t| otherwise = (function $ head range) + itersum function (tail range)\n\n\n\n-- |Calculates the factorial f(x) = x!\nfactorial n\n | n < 0 = 0\n | otherwise = product [1..n]\n\n-- |Calculates the Doublefactorial f(x) = x!!\nfactorial2 :: (Show a, Eq a, Num a) => a -> a\nfactorial2 0 = 1\nfactorial2 1 = 1\nfactorial2 (-1) = 1\nfactorial2 n = n * factorial2 (n-2)\n\n-- |Calculates the binomialcoefficient n over k\n--binom :: Integer -> Integer -> Double\nbinom n 0 = 1\nbinom 0 k = 0\nbinom n k = binom (n-1) (k-1) * n `div` k \n\n-- |Computes the distance between to vectors:\n--\n-- <>\ndistance :: Vector Double -> Vector Double -> Double\ndistance rA rB = norm2(rA - rB)\n\n-- | Calculates effective coefficient:\n--\n-- >>> frac alpha beta = alpha*beta/(alpha + beta)\nfrac :: Double -> Double -> Double\nfrac alpha beta = alpha*beta/(alpha + beta)\n\n-- | Calculates weighted radius of two gaussians\ncenter :: Double -- ^ alpha\n\t\t\t-> Vector Double -- ^ rA\n\t\t\t-> Double -- ^ beta\n\t\t\t-> Vector Double -- ^ rB\n\t\t\t-> Vector Double\ncenter a rA b rB = ((scalar b * rB) * (scalar a * rA))/scalar (a+b)\n\n-- |error function calculation\nerf :: Double -> Double\nerf x = 2/sqrt pi * sum [x/(2*n+1) * product [-x^2/k | k <- [1..n] ] | n <- [0..100]]\n\n--error function calculation\nf_0 :: Double -> Double\nf_0 = erf \n\n-- | General error function. See Eq. 4.118 Thijssen.\ngeneral_erf nu u\n\t| nu == 0 = sqrt pi * erf (sqrt u) * 1/(2*sqrt u)\n\t| otherwise = 1/(2*u) * (2*nu - 1) * (general_erf (nu-1) u ) - exp (-u)\n\n\n\n\n\n\n--------------------------\n---Important Functions----\n--------------------------\n\n\n-- |Calculates normalization factor of contracted Gaussian with arbitrary angular momentum\nnormCtr :: Ctr -> Double\nnormCtr contr = (prefactor * summation)**(-1.0/2.0)\n\t--See also Eq. 2.11\n\twhere\n\t\t(l, m, n) = lmncontract contr\n\t\t--(l,m,n) = (fromIntegral l_, fromIntegral m_, fromIntegral n_) --This looks quite dirty\n\t\tn_sum = lengthcontract contr -1\n\t\ta = toList $ coefflist contr\n\t\talp = [alpha prim | prim <- (gaussians contr)]\n\t\tmom = fromIntegral $ momentumctr contr\n\t\tprefactor = 1.0/(2.0**mom)*pi**(3.0/2.0)* factorial2 (2*l-1) * factorial2 (2*m-1)* factorial2 (2*n-1)\n\t\tsummation = sum $ concat $ [[(a !! i)*(a !! j)/((alp !! i +alp !! j)**(mom + 3.0/2.0)) | i <-[0..n_sum]]| j <- [0..n_sum]]\n\n\n-- |Calculates normalization factor of primitive Gaussian with arbitrary angular momentum\nnormPG :: PG -> Double\nnormPG (PG lmn alpha pos) = (2*alpha/pi)**(3/4) * (a/b)**(1/2)\n\twhere\n\t\t(l, m, n) = (fromIntegral $ lmn !! 0, fromIntegral $ lmn !! 1, fromIntegral $ lmn !! 2)\n\t\ta = (8*alpha)**(l+m+n) * factorial l * factorial m * factorial n\n\t\tb = factorial (2*l) * factorial (2*m) * factorial (2*n)\n\n\n-- |Calculates f_k (l1 l2 pa_x pb_x) used in Gaussian Product Theorem\nf :: Int -> Int -> Int -> Double -> Double -> Double\n--trace (\"f\" ++ \" \" ++ show k ++ \" \" ++ show l1_ ++ \" \" ++ show l2_ ++ \" \" ++ show pa_x ++ \" \" ++ show pb_x) $ \nf k l1_ l2_ pa_x pb_x = sum $ concat $ [[pa_x**(fromIntegral (l1_-i)) * pb_x**(fromIntegral(l2_-j)) * fromIntegral ((binom l1_ i) * (binom l2_ j))| i <- [0..l1_], i+j <= k]| j <-[0..l2_]]\n--See also Eq. 2.45\n\n\n-- |Evaluates a given function for two contractions. The operation is symmetric in contraction arguments.\nzipContractionWith :: (PG -> PG -> Double) -- ^ Function of two primitive Gaussians \n\t\t\t\t\t\t\t-> Ctr -- ^ Contraction\n\t\t\t\t\t\t\t-> Ctr -- ^ Contraction \n\t\t\t\t\t\t\t-> Double\nzipContractionWith zipfunction (Ctr pglist1 coeffs1) (Ctr pglist2 coeffs2) = pr1 * pr2 * value\n\twhere\n\t\tcoefflist1 = toList coeffs1\n\t\tcoefflist2 = toList coeffs2\n\t\tn1 = length coefflist1 -1\n\t\tn2 = length coefflist2 -1\n\t\tpr1 = normCtr (Ctr pglist1 coeffs1) --I am not so sure about this\n\t\tpr2 = normCtr (Ctr pglist2 coeffs2) --I am not so sure about this\n\t\tvalue = sum $ [(coefflist1 !! i)* (coefflist2 !! j)* (zipfunction (pglist1 !! i) (pglist2 !! j)) | i <- [0..n1], j <- [0..n2]]\n\n\n\n-- |Construct a matrix out of a list of Contractions and a function for two primitive gaussians\nconstr_matrix :: [Ctr] -- ^ List of Contraction\n\t\t\t\t\t\t-> (PG -> PG -> Double) -- ^ Function of two primitive Gaussians\n\t\t\t\t\t\t-> Matrix Double -- ^ Matrix of dimensions (length [Ctr]) x (length [Ctr])\nconstr_matrix contractionlist function = buildMatrix (length contractionlist) (length contractionlist) (\\(i,j) -> zipContractionWith function (contractionlist !! i) (contractionlist !! j) )\n\n\n\n-- |Calculates overlap integral of two primitive gaussians\n\n-- | <>\ns_12 :: PG -> PG -> Double\ns_12 (PG lmn1 alpha1 pos1) (PG lmn2 alpha2 pos2) = trace (\"s_12: range \" ++ show range ++ \" f 0 =\" ++ show (factor 0) ++ \" f 1 = \" ++ show (factor 1)++ \" f 2 =\" ++ show (factor 2)) $ prefactor * (factor 0) * (factor 1) * (factor 2) --pref * I_x * I_y * I_z\n\twhere\n\t\t(l1, m1, n1) = (lmn1 !! 0, lmn1 !! 1, lmn1 !! 2)\n\t\t(l2, m2, n2) = (lmn2 !! 0, lmn2 !! 1, lmn2 !! 2)\n\t\tg = alpha1 + alpha2\n\t\tprefactor = exp (-alpha1*alpha2 * (distance pos1 pos2) /g)\n\t\tp = center alpha1 pos1 alpha2 pos2\n\t\tpa = toList $ p - pos1\n\t\tpb = toList $ p - pos2\n\t\trange = [0..(fromIntegral (l1+l2) /2)] :: (Enum a, Fractional a) => [a]\n\t\t-- See also Eq. 3.15\n\t\tfunction k i = force $ f (round (2*i)) l1 l2 (pa !! k) (pb !! k) * (factorial2 (2.0* i -1.0)) * ((2*g)** (- i)) * (pi/g)**(1/2)\n\t\tfactor k = itersum (function k) range\n\t\t--i k = sum $ [f (round (2*i)) l1 l2 (pa !! k) (pb !! k) * factorial2 (2.0* i -1.0) * ((2*g)** (- i)) * (pi/g)**(1/2) | i <- range ]\n\n\n\n-- |Calculates kinetic energy integral of two primitive gaussians\n\n-- | <>\nt_12 :: PG -> PG -> Double\nt_12 (PG lmn1 alpha1 pos1) (PG lmn2 alpha2 pos2) = (i 0) + (i 1) + (i 2) -- I_x + I_y + I_z\n\twhere\n\t\t--lifts or lowers l, m or n, indicated by index k for a lmn-list, respectively\n\t\tpp1 list k = [if i == k then list !! i + 1 else list !! i | i<-[0..2]]\t--lifts\n\t\tmm1 list k = [if i == k then list !! i - 1 else list !! i | i<-[0..2]]\t--lowers\n\t\t--overlaps where parts of l, m or n ar lifted +1 or lowered -1\n\t\tm1m1 k = s_12 (PG (mm1 lmn1 k) alpha1 pos1) (PG (mm1 lmn2 k) alpha2 pos2) -- <-1|-1>_k\n\t\tp1p1 k = s_12 (PG (pp1 lmn1 k) alpha1 pos1) (PG (pp1 lmn2 k) alpha2 pos2) -- <+1|+1>_k\n\t\tp1m1 k = s_12 (PG (pp1 lmn1 k) alpha1 pos1) (PG (mm1 lmn2 k) alpha2 pos2) -- <+1|-1>_k\n\t\tm1p1 k = s_12 (PG (mm1 lmn1 k) alpha1 pos1) (PG (pp1 lmn2 k) alpha2 pos2) -- <-1|+1>_k\n\t\t--See also Eq.4.13\n\t\ti k = 1/2 * (fromIntegral (lmn1 !! k)) * (fromIntegral (lmn2 !! k)) * (m1m1 k) \n\t\t\t+ 2 * alpha1 * alpha2 * (p1p1 k)\n\t\t\t- alpha1 * (fromIntegral (lmn2 !! k)) * (p1m1 k) \n\t\t\t- alpha2 * (fromIntegral (lmn1 !! k)) * (m1p1 k)\n\n{-\n-- |Calculates nuclear attraction integral of two primitive gaussians\nv_12 :: Double -> Vecotr Double -> PG -> PG -> Double\nv_12 z r_c (PG lmn1 alpha1 pos1) (PG lmn2 alpha2 pos2) = z*pi*pre/g * 2* summation\n\twhere\n\t\tax, ay, az = (fromList pos1) !! 0, (fromList pos1) !! 1, (fromList pos1) !! 2\n\t\tbx, by, bz = (fromList pos2) !! 0, (fromList pos2) !! 1, (fromList pos2) !! 2\n\t\tr_cx, r_cy, r_cz = (fromList r_c) !! 0, (fromList r_c) !! 1, (fromList r_c) !! 2\n\t\tpref = exp (-alpha1*alpha2 * (distance pos1 pos2) /g)\n\t\tg = alpha1 + alpha2\n\t\tp = 1/g * (alpha1*pos1 + alpha2*pos2)\n\t\tpx, py, pz = (fromList p) !! 0, (fromList p) !! 1, (fromList p) !! 2\n\t\teta = (alpha1 + alpha2)/g\n\t\tmu_x = l1 + l2 - 2*(ijk1 + ijk2) - (opq1 + opq2)\n\t\tmu_y = l1 + l2 - 2*(j1 + j2) - (p1 + p2)\n\t\tmu_z = l1 + l2 - 2*(k1 + k2) - (q1 + q2)\n\t\tnu = mu_x + mu_y + mu_z - (u + v + w)\n\t\tsummation = general_erf nu (g * distance p r_c) * a_x * a_y * a_z\n\n\t\t--ranges:\n\t\tijk1_range = [0..floor $ (fromIntegral l1 /2)] :: (Integral a, Enum a) => [a]\n\t\tijk2_range = [0..floor $ (fromIntegral l2 /2)] :: (Integral a, Enum a) => [a]\n\t\topq1_range ijk1 = [0..floor $ (fromIntegral l1 - 2*ijk1)] :: (Integral a, Enum a) => [a]\n\t\topq2_range ijk2 = [0..floor $ (fromIntegral l2 - 2*ijk2)] :: (Integral a, Enum a) => [a]\n\t\trst_range opq1 opq2 = [0..floor $ fromIntegral (opq1+l2) /2] :: (Integral a, Enum a) => [a]\n\t\tu_range mu_x = [0..floor $ (fromIntegral mu_x /2)] :: (Integral a, Enum a) => [a]\n\n\n\n\t\ta_x = (-1)**(l1+l2) * (factorial l1) * (factorial l2) * \n\t\t(-1)**(opq2 + r) * factorial (opq1 + opq2) * 1/(4**(ijk1+ijk2+r) * factorial ijk1 * factorial ijk2 * factorial opq1 * factorial opq2 * factorial r) * \n\t\talpha1**(opq2-ijk1-r) * alpha2**(opq1-ijk2-r) * (ax-bx)**(opq1+opq2-2*r) * 1/(factorial (l1-2*ijk1-opq1) * factorial (l2-2*ijk2-opq2) * factorial (opq1-2*opq2-2*r)) * \n\t\t* [ (-1)**u * factorial mu_x * (px -r_cx)**(mu_x - 2*u) * 1/ ((4)**u * factorial u * factorial (mu_x-2*u) * g**(opq1 + opq2 - r + u)) | u <- [0..1/2 * mu_x]]\n-}\n\n--v_12_test :: Double -> Vector Double -> PG -> PG -> [Double]\n{- v_12_test z r_c (PG lmn1 alpha1 pos1) (PG lmn2 alpha2 pos2) = summation 0\n\twhere\n\t\t--(ax, ay, az) = ((toList pos1) !! 0, (toList pos1) !! 1, (toList pos1) !! 2)\n\t\t--(bx, by, bz) = ((toList pos2) !! 0, (toList pos2) !! 1, (toList pos2) !! 2)\n\t\t--(r_cx, r_cy, r_cz) = ((toList r_c) !! 0, (toList r_c) !! 1, (toList r_c) !! 2)\n\t\t--lmn1_ = fromList lmn1\n\t\t--lmn2_ = fromList lmn2\n\t\t\n\t\tpref = exp (-alpha1*alpha2 * (distance pos1 pos2) /g)\n\t\tg = alpha1 + alpha2\n\t\tp = scale (1/g) (add (scale alpha1 pos1) (scale alpha2 pos2))\n\t\t--(px, py, pz) = ((toList p) !! 0, (toList p) !! 1, (toList p) !! 2)\n\n\t\t--f_nu ijk1 ijk2 opq1 opq2 = general_erf (nu ijk1 ijk2 opq1 opq2) (g * distance p r_c)\n\t\t\n\t\teta = (alpha1 + alpha2)/g\n\t\tmu ijk1 ijk2 opq1 opq2 s = fromIntegral (atIndex lmn1 s) + fromIntegral (atIndex lmn2 s) - 2*(ijk1 + ijk2) - (opq1 + opq2)\n\t\t--nu ijk1 ijk2 opq1 opq2 = (mu ijk1 ijk2 opq1 opq2 s) + (mu ijk1 ijk2 opq1 opq2 s) + (mu ijk1 ijk2 opq1 opq2 s) - (u v q)\n\n\t\t--ranges alle ranges (X,Y,Z) mit einer klappe schlagen, dafür index s:\n\t\tijk1_range s = [0..fromIntegral $ floor $ fromIntegral (lmn1 !! s) /2] :: [Double]\n\t\tijk2_range s = [0..fromIntegral $ floor $ fromIntegral (lmn2 !! s) /2] :: [Double]\n\t\topq1_range ijk1 s = [0..fromIntegral $ floor $ (fromIntegral (lmn1 !! s) - 2*ijk1)] :: [Double]\n\t\topq2_range ijk2 s = [0..fromIntegral $ floor $ (fromIntegral (lmn2 !! s) - 2*ijk2)] :: [Double]\n\t\trst_range opq1 opq2 s = [0..fromIntegral $ floor $ (opq1+opq2) /2] :: [Double]\n\t\tuvw_range ijk1 ijk2 opq1 opq2 s = [0..fromIntegral $ floor $ ((mu ijk1 ijk2 opq1 opq2 s) /2)] :: [Double]\n\n\t\n\t\t--a_x :: Num a => a -> a -> a -> a -> a -> Double\n\n\t\t--(-1)**(l1+l2) * (factorial fromIntegral (lmn1 !! s)) * (factorial fromIntegral (lmn2 !! s)) *\n\t\tfunction ijk1 ijk2 opq1 opq2 rst s = (-1)**(opq2 + rst) * factorial (opq1 + opq2) * 1/(4**(ijk1+ijk2+rst) * factorial ijk1 * factorial ijk2 * factorial opq1 * factorial opq2 * factorial rst) * alpha1**(opq2-ijk1-rst) * alpha2**(opq1-ijk2-rst) * (atIndex pos1 s - atIndex pos2 s)**(opq1+opq2-2*rst) * 1/(factorial ((lmn1 !! s)-2*ijk1-opq1) * factorial ((lmn2 !! s)-2*ijk2-opq2) * factorial (opq1-2*opq2-2*rst)) * sum $ [ (-1)**uvw * factorial (mu ijk1 ijk2 opq1 opq2 s) * ((atIndex p s) - (atIndex r_c s))**((mu ijk1 ijk2 opq1 opq2 s) - 2*uvw) * 1/ ((4)**uvw * factorial uvw * factorial ((mu ijk1 ijk2 opq1 opq2 s)-2*uvw) * g**(opq1 + opq2 - rst + uvw)) | uvw <- (uvw_range ijk1 ijk2 opq1 opq2 s)] \n\n\t\tsummation s = (-1)**(lmn1 !! s + lmn2 !! s) * (factorial fromIntegral (lmn1 !! s)) * (factorial fromIntegral (lmn2 !! s)) * sum $ concat $ concat $ [[[function ijk1 ijk2 opq1 opq2 rst s | rst <- (rst_range opq1 opq2 s)] | opq1 <- (opq1_range ijk1 s), opq2 <- (opq2_range ijk2 s)]| ijk1 <- ijk1_range s, ijk2 <- ijk2_range s]\n-}\n\n\n\n\n\n\n\n\n\n\n\n\n-----------------\n--Deprecated-----\n-----------------\n\n\t \n\n-- Here all importand integrals involving gaussian functions will be evaluated.\n\n--Overlap integral for s orbitals\n--calculates <1s,alpha, A | 1s, beta, B>\noverlaps :: Double -> Double -> Vector Double -> Vector Double -> Double\noverlaps alpha beta rA rB = prefactor * exp exponent\n\twhere \tprefactor = (pi/(alpha + beta))**(3/2)\n\t\texponent = - (frac alpha beta * distance rA rB)\n\n--Kinetic integral\n--calculates <1s,alpha, A | - Laplace | 1s, beta, B>\nkinetic :: Double -> Double -> Vector Double -> Vector Double -> Double\nkinetic alpha beta rA rB = prefactor * exp(exponent)\n\twhere \tprefactor = (frac alpha beta)\n\t\t\t *(6 -4 *(frac alpha beta) * distance rA rB)\n\t\t\t *(pi/(alpha + beta))**(3/2)\n\t\texponent = - ((frac alpha beta) * distance rA rB)\n\n\n\n--Nuclear interaction integral\n--calculates <1s,alpha, A | - Z/r_C | 1s, beta, B>\nnuclear :: Double -> Double -> Vector Double -> Vector Double -> Vector Double -> Double -> Double\nnuclear alpha beta rA rB rC z = pref1 * pref2 * exp(exponent)\n\twhere \tpref1 = -2*pi*z/(alpha + beta)\n\t\tpref2 = f_0 arg\n\t\targ = (distance (center alpha rA beta rB) rC ) * (alpha*beta)\n\t\texponent = - ((frac alpha beta) * (distance rA rB))\n\n--two-electron integral\n--important!\n--calculates <1s,alpha, A ; 1s, beta, B | 1s,gamma, C ; 1s, delta, D >\ntwoelectron :: Double -> Double -> Double -> Double -> Vector Double -> Vector Double -> Vector Double -> Vector Double -> Double\ntwoelectron a b g d rA rB rC rD = pref * exp(exponent) * (f_0 arg)\n\twhere\tpref = \t\t\t(2*pi**(5/2))/\n\t\t\t\t( (a+g)*(b+d)*(a+b+g+d)**(1/2) )\n\t\texponent = \t-a*g/(a+g) * (distance rA rC)\n\t\t\t\t-b*d/(b+d) * (distance rB rD)\n\t\targ = (a+g)*(b+d)/(a+b+g+d) * ( distance (center a rA g rC) (center b rB d rD) )\n\n\n\n\n--Overlap Matrix S_pq = \n--overlap p q = t\n--where\n--\tt = buildMatrix (n*n) (n*n) (\\(i,j) -> overlaps alpha beta rA rB )\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "152bb3078deb7d4c1ffd054824e57f585731beac", "size": 14882, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "dist/build/autogen/HF/gauss.hs", "max_stars_repo_name": "davidschlegel/hartree-fock", "max_stars_repo_head_hexsha": "381fc9c40e8d8f63c540b092ce51fca173149de9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dist/build/autogen/HF/gauss.hs", "max_issues_repo_name": "davidschlegel/hartree-fock", "max_issues_repo_head_hexsha": "381fc9c40e8d8f63c540b092ce51fca173149de9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dist/build/autogen/HF/gauss.hs", "max_forks_repo_name": "davidschlegel/hartree-fock", "max_forks_repo_head_hexsha": "381fc9c40e8d8f63c540b092ce51fca173149de9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7914438503, "max_line_length": 700, "alphanum_fraction": 0.6116113426, "num_tokens": 5583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6702785852660047}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Data.Random.Distribution.Static.MultivariateNormal\n-- Copyright : (c) 2016 FP Complete Corporation\n-- License : MIT (see LICENSE)\n-- Maintainer : dominic@steinitz.org\n--\n-- Sample from the multivariate normal distribution with a given\n-- vector-valued \\(\\mu\\) and covariance matrix \\(\\Sigma\\). For\n-- example, the chart below shows samples from the bivariate normal\n-- distribution. The dimension of the mean \\(n\\) is statically checked\n-- to be compatible with the dimension of the covariance matrix \\(n \\times n\\).\n--\n-- <>\n--\n-- Example code to generate the chart:\n--\n-- > {-# LANGUAGE DataKinds #-}\n-- >\n-- > import qualified Graphics.Rendering.Chart as C\n-- > import Graphics.Rendering.Chart.Backend.Diagrams\n-- >\n-- > import Data.Random.Distribution.Static.MultivariateNormal\n-- >\n-- > import qualified Data.Random as R\n-- > import Data.Random.Source.PureMT\n-- > import Control.Monad.State\n-- > import Numeric.LinearAlgebra.Static\n-- >\n-- > nSamples :: Int\n-- > nSamples = 10000\n-- >\n-- > sigma1, sigma2, rho :: Double\n-- > sigma1 = 3.0\n-- > sigma2 = 1.0\n-- > rho = 0.5\n-- >\n-- > singleSample :: R.RVarT (State PureMT) (R 2)\n-- > singleSample = R.sample $ Normal (vector [0.0, 0.0])\n-- > (sym $ matrix [ sigma1, rho * sigma1 * sigma2\n-- > , rho * sigma1 * sigma2, sigma2])\n-- >\n-- > multiSamples :: [R 2]\n-- > multiSamples = evalState (replicateM nSamples $ R.sample singleSample) (pureMT 3)\n-- >\n-- > pts = map f multiSamples\n-- > where\n-- > f z = (x, y)\n-- > where\n-- > (x, t) = headTail z\n-- > (y, _) = headTail t\n-- >\n-- > chartPoint pointVals n = C.toRenderable layout\n-- > where\n-- >\n-- > fitted = C.plot_points_values .~ pointVals\n-- > $ C.plot_points_style . C.point_color .~ opaque red\n-- > $ C.plot_points_title .~ \"Sample\"\n-- > $ def\n-- >\n-- > layout = C.layout_title .~ \"Sampling Bivariate Normal (\" ++ (show n) ++ \" samples)\"\n-- > $ C.layout_y_axis . C.laxis_generate .~ C.scaledAxis def (-3,3)\n-- > $ C.layout_x_axis . C.laxis_generate .~ C.scaledAxis def (-3,3)\n-- >\n-- > $ C.layout_plots .~ [C.toPlot fitted]\n-- > $ def\n-- >\n-- > diagMS = do\n-- > denv <- defaultEnv C.vectorAlignmentFns 600 500\n-- > return $ fst $ runBackend denv (C.render (chartPoint pts nSamples) (500, 500))\n--\n-----------------------------------------------------------------------------\n\n{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -fno-warn-name-shadowing #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}\n{-# OPTIONS_GHC -fno-warn-missing-methods #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DataKinds #-}\n\nmodule Data.Random.Distribution.Static.MultivariateNormal\n ( Normal(..)\n ) where\n\nimport Data.Random hiding ( StdNormal, Normal )\nimport qualified Data.Random as R\nimport Control.Monad.State ( replicateM )\nimport qualified Numeric.LinearAlgebra.HMatrix as H\nimport Numeric.LinearAlgebra.Static as S\n ( R, vector, extract, Sq, Sym, col,\n tr, linSolve, uncol, chol, (<.>),\n ℝ, (<>), diag, (#>), eigensystem\n )\nimport GHC.TypeLits ( KnownNat, natVal )\nimport Data.Maybe ( fromJust )\n\n\nnormalMultivariate :: KnownNat n =>\n R n -> Sym n -> RVarT m (R n)\nnormalMultivariate mu bigSigma = do\n z <- replicateM (fromIntegral $ natVal mu) (rvarT R.StdNormal)\n return $ mu + bigA #> (vector z)\n where\n (vals, bigU) = eigensystem bigSigma\n lSqrt = diag $ mapVector sqrt vals\n bigA = bigU S.<> lSqrt\n\nmapVector :: KnownNat n => (ℝ -> ℝ) -> R n -> R n\nmapVector f = vector . H.toList . H.cmap f . extract\n\nsumVector :: KnownNat n => R n -> ℝ\nsumVector x = x <.> 1\n\ndata family Normal k :: *\n\ndata instance Normal (R n) = Normal (R n) (Sym n)\n\ninstance KnownNat n => Distribution Normal (R n) where\n rvar (Normal m s) = normalMultivariate m s\n\nnormalLogPdf :: KnownNat n =>\n R n -> Sym n -> R n -> Double\nnormalLogPdf mu bigSigma x = - sumVector (mapVector log (diagonals dec))\n - 0.5 * (fromIntegral $ natVal mu) * log (2 * pi)\n - 0.5 * s\n where\n dec = chol bigSigma\n t = uncol $ fromJust $ linSolve (tr dec) (col $ x - mu)\n u = mapVector (\\x -> x * x) t\n s = sumVector u\n\nnormalPdf :: KnownNat n =>\n R n -> Sym n -> R n -> Double\nnormalPdf mu sigma x = exp $ normalLogPdf mu sigma x\n\ndiagonals :: KnownNat n => Sq n -> R n\ndiagonals = vector . H.toList . H.takeDiag . extract\n\ninstance KnownNat n => PDF Normal (R n) where\n pdf (Normal m s) = normalPdf m s\n logPdf (Normal m s) = normalLogPdf m s\n", "meta": {"hexsha": "6b83857b406e10292de9108d5924c37ae986a48e", "size": 5179, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Random/Distribution/Static/MultivariateNormal.hs", "max_stars_repo_name": "steinitznavican/random-fu-multivariate", "max_stars_repo_head_hexsha": "4f704757d0119b8c4f8ea5c2390277b775825a6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Random/Distribution/Static/MultivariateNormal.hs", "max_issues_repo_name": "steinitznavican/random-fu-multivariate", "max_issues_repo_head_hexsha": "4f704757d0119b8c4f8ea5c2390277b775825a6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Random/Distribution/Static/MultivariateNormal.hs", "max_forks_repo_name": "steinitznavican/random-fu-multivariate", "max_forks_repo_head_hexsha": "4f704757d0119b8c4f8ea5c2390277b775825a6e", "max_forks_repo_licenses": ["BSD-3-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.231292517, "max_line_length": 117, "alphanum_fraction": 0.5742421317, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.669882930216803}} {"text": "{- |\nThis module provides normalized versions of the transforms in @fftw@.\n\nAll of the transforms are normalized so that\n\n - Each transform is unitary, i.e., preserves the inner product and the sum-of-squares norm of its input.\n\n - Each backwards transform is the inverse of the corresponding forwards transform.\n\n(Both conditions only hold approximately, due to floating point precision.)\n\nFor more information on the underlying transforms, see\n.\n--\n-- @since 0.2\n-}\n\nmodule Numeric.FFT.Vector.Unitary.Multi\n (\n -- * Creating and executing 'Plan's\n run,\n plan,\n execute,\n -- * Complex-to-complex transforms\n dft,\n idft,\n -- * Real-to-complex transforms\n dftR2C,\n dftC2R,\n ) where\n\nimport Control.Exception (assert)\nimport Control.Monad (forM_)\nimport Numeric.FFT.Vector.Base\nimport qualified Numeric.FFT.Vector.Unnormalized.Multi as U\nimport Data.Complex\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Storable.Mutable as MS\nimport Control.Monad.Primitive(RealWorld)\n\n-- | A discrete Fourier transform. The output and input sizes are the same (@n@).\n--\n-- @y_k = (1\\/sqrt n) sum_(j=0)^(n-1) x_j e^(-2pi i j k\\/n)@\ndft :: TransformND (Complex Double) (Complex Double)\ndft = U.dft {normalizationND = \\ns -> constMultOutput $ 1 / sqrt (toEnum (VS.product ns))}\n\n-- | An inverse discrete Fourier transform. The output and input sizes are the same (@n@).\n--\n-- @y_k = (1\\/sqrt n) sum_(j=0)^(n-1) x_j e^(2pi i j k\\/n)@\nidft :: TransformND (Complex Double) (Complex Double)\nidft = U.idft {normalizationND = \\ns -> constMultOutput $ 1 / sqrt (toEnum (VS.product ns))}\n\n-- | A forward discrete Fourier transform with real data. If the input size is @n@,\n-- the output size will be @n \\`div\\` 2 + 1@.\ndftR2C :: TransformND Double (Complex Double)\ndftR2C = U.dftR2C {normalizationND = \\ns -> modifyOutput $\n complexR2CScaling (sqrt 2) ns (outputSizeND U.dftR2C $ VS.last ns)\n }\n\n-- | A normalized backward discrete Fourier transform which is the left inverse of\n-- 'U.dftR2C'. (Specifically, @run dftC2R . run dftR2C == id@.)\n--\n-- This 'Transform' behaves differently than the others:\n--\n-- - Calling @plan dftC2R n@ creates a 'Plan' whose /output/ size is @n@, and whose\n-- /input/ size is @n \\`div\\` 2 + 1@.\n--\n-- - If @length v == n@, then @length (run dftC2R v) == 2*(n-1)@.\n--\ndftC2R :: TransformND (Complex Double) Double\ndftC2R = U.dftC2R {normalizationND = \\ns -> modifyInput $\n complexR2CScaling (sqrt 0.5) ns (inputSizeND U.dftC2R $ VS.last ns)\n }\n\ncomplexR2CScaling :: Double -> VS.Vector Int -> Int -> MS.MVector RealWorld (Complex Double) -> IO ()\ncomplexR2CScaling !t !ns !len !a = assert (MS.length a == VS.product (VS.init ns) * len) $ do\n let !s1 = sqrt (1/toEnum (VS.product ns))\n let !s2 = t * s1\n -- Justification for the use of unsafeModify:\n -- The output size is 2n+1; so if n>0 then the output size is >=1;\n -- and if n even then the output size is >=3.\n forM_ [0.. VS.product (VS.init ns) - 1] $ \\idx -> do\n unsafeModify a (idx * len) $ scaleByD s1\n if odd (VS.last ns)\n then multC s2 (MS.unsafeSlice (idx * len + 1) (len-1) a)\n else do\n unsafeModify a (idx * len + len - 1) $ scaleByD s1\n multC s2 (MS.unsafeSlice (idx * len + 1) (len-2) a)\n\n", "meta": {"hexsha": "ffeb3165bc54a71c02baf40a549310f3a5622c44", "size": 3443, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/FFT/Vector/Unitary/Multi.hs", "max_stars_repo_name": "TravisWhitaker/vector-fftw", "max_stars_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-12-02T12:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T17:52:00.000Z", "max_issues_repo_path": "Numeric/FFT/Vector/Unitary/Multi.hs", "max_issues_repo_name": "TravisWhitaker/vector-fftw", "max_issues_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-06-16T18:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-14T19:29:13.000Z", "max_forks_repo_path": "Numeric/FFT/Vector/Unitary/Multi.hs", "max_forks_repo_name": "TravisWhitaker/vector-fftw", "max_forks_repo_head_hexsha": "e5d3eba36ba52fbb564a02aa4e7e116a87c86845", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-08-29T13:35:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T23:04:18.000Z", "avg_line_length": 38.2555555556, "max_line_length": 105, "alphanum_fraction": 0.6540807435, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6697998242078391}} {"text": "{-# LANGUAGE RankNTypes #-}\n\n-- |\n-- Author: Benedikt Spies\n--\n-- Utility functions to generate simple Images\n-- Image rows are generated in parallel\nmodule Utils.ImageGenerator (generateRainbowImage, generateMandelbrotImage) where\n\nimport Codec.Picture\n ( Image,\n Pixel8,\n PixelRGB8 (PixelRGB8),\n )\nimport Data.Complex (Complex ((:+)), magnitude)\nimport Utils.ParallelImageUtils (parGenerateImage)\n\ngenerateRainbowImage :: Image PixelRGB8\ngenerateRainbowImage = parGenerateImage f 256 256\n where\n f :: Int -> Int -> PixelRGB8\n f x y = PixelRGB8 r g b\n where\n r = fromIntegral $ 255 - x\n g = fromIntegral $ 255 - y\n b = fromIntegral x\n\ngenerateMandelbrotImage :: Int -> Int -> Image PixelRGB8\ngenerateMandelbrotImage width height = parGenerateImage (generateMandelbrotPixel width height) width height\n\ngenerateMandelbrotPixel :: Int -> Int -> Int -> Int -> PixelRGB8\ngenerateMandelbrotPixel imageWidth imageHeight x y = color $ mandelbrot (x' / w' * 3 - 2) (y' / h' * 3 - 1.5)\n where\n x' = fromIntegral x\n y' = fromIntegral y\n w' = fromIntegral imageWidth\n h' = fromIntegral imageHeight\n maxIter = 300\n color :: Int -> PixelRGB8\n color iter = PixelRGB8 colorVal colorVal colorVal\n where\n colorVal = floor $ 255 - amt * 255 :: Pixel8\n amt = fromIntegral iter / fromIntegral maxIter :: Float\n mandelbrot :: Float -> Float -> Int\n mandelbrot r i =\n length . takeWhile (\\z -> magnitude z <= 2)\n . take maxIter\n $ iterate (\\z -> z ^ (2 :: Int) + (r :+ i)) 0\n", "meta": {"hexsha": "630ea5a168d6464416cdf5acab0350693e0dfcf7", "size": 1563, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Utils/ImageGenerator.hs", "max_stars_repo_name": "birneee/haskell-spotify-tui", "max_stars_repo_head_hexsha": "6702030015001437252c6d7822c0b41b2dd26c66", "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/ImageGenerator.hs", "max_issues_repo_name": "birneee/haskell-spotify-tui", "max_issues_repo_head_hexsha": "6702030015001437252c6d7822c0b41b2dd26c66", "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/Utils/ImageGenerator.hs", "max_forks_repo_name": "birneee/haskell-spotify-tui", "max_forks_repo_head_hexsha": "6702030015001437252c6d7822c0b41b2dd26c66", "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.8979591837, "max_line_length": 109, "alphanum_fraction": 0.6628278951, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.6697998188185146}} {"text": "-- | Dynamic Programming module.\nmodule DP where\n\nimport Data.Map (Map)\nimport qualified Data.Map.Strict as M\nimport qualified Data.Set as S\nimport Numeric.LinearAlgebra.Data\n (Matrix, Vector, (!), (¿), (><), maxIndex)\nimport Numeric.LinearAlgebra.HMatrix as H\n\nimport MDP\nimport Planning\n\nimport Debug.Trace\n\n\ndata MDPM s a = MDPM\n { statesm :: Map s Int\n , actionsm :: Map a Int\n , transitionm :: Map a (Matrix Double)\n , rewardm :: Matrix Double\n , gammam :: Double -- discount\n , sizeStates :: Int -- S\n , sizeActions :: Int -- A\n , actionsr :: Map Int a\n }\n\n\nprepareMDP :: (Ord s, Ord a) => MDP s a -> MDPM s a\nprepareMDP mdp =\n MDPM\n { statesm = statesM\n , actionsm = actionsM\n , transitionm = transitionM\n , rewardm = rewardM\n , gammam = gamma mdp\n , sizeStates = S.size (states mdp)\n , sizeActions = S.size (actions mdp)\n , actionsr = M.fromList (zip [0..] (S.toList (actions mdp)))\n }\n where\n statesM = M.fromList (zip (S.toList (states mdp)) [0 ..])\n actionsM = M.fromList (zip (S.toList (actions mdp)) [0 ..])\n transitionM = transitionMap\n transitionMap =\n M.fromList\n (map\n (\\a ->\n (a, createMatrix a))\n (S.toList (actions mdp)))\n createMatrix a =\n H.fromLists\n (map\n (\\s ->\n map (transition mdp a s) (S.toList (states mdp)))\n (S.toList (states mdp)))\n rewardM = createRewardMatrix\n createRewardMatrix =\n H.fromLists\n (map\n (\\s ->\n map\n (\\a ->\n reward mdp a s)\n (S.toList (actions mdp)))\n (S.toList (states mdp)))\n\n\nvalueIterationM :: (Ord a) => MDPM s a -> Int -> Matrix Double -> Matrix Double\nvalueIterationM mdpm k v\n | k == 0 = v\n | otherwise = valueIterationM mdpm (k - 1) (calc v)\n where\n calc v' =\n rewardm mdpm +\n gammam mdpm `H.scale`\n fromColumns\n (map\n (\\a ->\n flatten\n (transitionm mdpm M.! a H.<>\n (v' ¿ [actionsm mdpm M.! a])))\n (M.keys (actionsm mdpm)))\n\n\nvalueIteration :: (Ord a, Ord s) => MDP s a -> Int -> s -> a\nvalueIteration mdp k s = actionsr mdpm M.! maxIndex (vk ! (statesm mdpm M.! s))\n where\n mdpm = prepareMDP mdp\n v0 = (sizeStates mdpm >< sizeActions mdpm) [0,0 ..]\n vk = valueIterationM mdpm k v0\n", "meta": {"hexsha": "34c183b350922e01b5e49fe4c2175812e837eb48", "size": 2611, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/DP.hs", "max_stars_repo_name": "DbIHbKA/hmdp", "max_stars_repo_head_hexsha": "515acbda34e9b43b6ae9a2d10d854fd9070c14ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-02T01:17:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-02T01:17:49.000Z", "max_issues_repo_path": "src/DP.hs", "max_issues_repo_name": "DbIHbKA/hmdp", "max_issues_repo_head_hexsha": "515acbda34e9b43b6ae9a2d10d854fd9070c14ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DP.hs", "max_forks_repo_name": "DbIHbKA/hmdp", "max_forks_repo_head_hexsha": "515acbda34e9b43b6ae9a2d10d854fd9070c14ee", "max_forks_repo_licenses": ["BSD-3-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.3804347826, "max_line_length": 79, "alphanum_fraction": 0.509000383, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6692159098002021}} {"text": "{- |\nDescription : Convenience functions to simulate Gamma rate heterogeneity\nCopyright : (c) Dominik Schrempf 2017\nLicense : GPLv3\n\nMaintainer : dominik.schrempf@gmail.com\nStability : unstable\nPortability : non-portable (not tested)\n\nSites evolve at different speeds. One way to model this phenomenon is to use\nGamma rate heterogeneity. This module provides the necessary definitions.\n\n* Changelog\n\n-}\n\nmodule GammaRate where\n\nimport Numeric.Integration.TanhSinh\nimport Statistics.Distribution\nimport Statistics.Distribution.Gamma\n\n-- | For a given number of rate categories 'n' and a shape parameter 'alpha'\n-- (the rate or scale is set such that the mean is 1.0), return a list of rates\n-- that represent the respective categories. Use the mean rate for each\n-- category.\ngetMeans :: Int -> Double -> [Double]\ngetMeans n alpha = means ++ lastMean\n where gamma = gammaDistr alpha (1.0/alpha)\n quantiles = [ quantile gamma (fromIntegral i / fromIntegral n) | i <- [0..n] ]\n -- Calculate the mean rate. Multiplication with the number of rate\n -- categories 'n' is necessary because in each n-quantile the\n -- probability mass is 1/n.\n meanFunc x = fromIntegral n * x * density gamma x\n -- Only calculate the first (n-1) categories with normal integration.\n means = [ intAToB meanFunc (quantiles !! i) (quantiles !! (i+1)) | i <- [0..n-2] ]\n -- The last category has to be calculated with an improper integration.\n lastMean = [intAToInf meanFunc (quantiles !! (n-1))]\n\n-- | The error of integration.\neps :: Double\neps = 1e-6\n\n-- | The integration method to use\nmethod :: (Double -> Double ) -> Double -> Double -> [Result]\nmethod = parSimpson\n\n-- | Helper function for a normal integral from 'a' to 'b'.\nintAToB :: (Double -> Double) -> Double -> Double -> Double\nintAToB f a b = result . absolute eps $ method f a b\n\n-- | Helper function for an improper integral from 'a' to infinity.\nintAToInf :: (Double -> Double) -> Double -> Double\nintAToInf f a = (result . absolute eps $ nonNegative method f) - intAToB f 0 a\n", "meta": {"hexsha": "cf400e8704ffac5c27d299b1ad97d4dfc4ffdd07", "size": 2125, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GammaRate.hs", "max_stars_repo_name": "dschrempf/bmm-simulate", "max_stars_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-14T15:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T15:53:08.000Z", "max_issues_repo_path": "src/GammaRate.hs", "max_issues_repo_name": "pomo-dev/bmm-simulate", "max_issues_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GammaRate.hs", "max_forks_repo_name": "pomo-dev/bmm-simulate", "max_forks_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6363636364, "max_line_length": 90, "alphanum_fraction": 0.6837647059, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6687687986531413}} {"text": "{-# LANGUAGE BangPatterns #-}\n-- file: Astro/Misc.hs\n-- Miscellaneous utilities\n\nmodule Astro.Misc where\n\nimport Data.List\nimport Debug.Trace\nimport Numeric.LinearAlgebra\nimport Numeric (showEFloat)\nimport Text.Printf\n\n{-\n - General math\n -}\n\ntype Polynomial = [Double]\n\n-- Evaluate real polynomial given as list of coefficients [a0,a1,...]\nevalPoly :: Polynomial->Double->Double\nevalPoly p x = sum $ zipWith (*) p $ map (x^) [0..]\n\n-- Derivative of a (real) polynomial\ndiffPoly :: Polynomial->Polynomial\ndiffPoly [] = []\ndiffPoly (a0:[]) = []\ndiffPoly (a0:as) = zipWith (*) as [1..]\n\n-- Degree of a polynomial\ndegPoly :: Polynomial->Int\ndegPoly [] = 0\ndegPoly (a:[]) = if a /= 0 then 1 else 0\ndegPoly p = if l == [] then 0 else last l\n\twhere\n\tl = Data.List.findIndices (/= 0) p\n\n-- Laguerre polynomial root finder\n-- Returns Nothing if fails to converge to a real root within maxIt\nrootLaguerre (tol,maxIt) p x0 = result\n\twhere\n\tresult = helper x0 0\n\tp' = diffPoly p\n\tp'' = diffPoly p'\n\tdeg = fromIntegral $ degPoly p\n\thelper x n\n\t\t| isNaN x = Nothing\n\t\t| abs (evalPoly p x) <= tol = Just x\n\t\t| n >= maxIt = Nothing -- `debug` (\"maxit x,nx:\"++show(x,nx))\n\t\t| otherwise = helper nx (n+1) \n {-\n `debug` (printf (\"g:n %g h: %g sqa: %g sq: %g x:\"\n ++\"%g y: %g\") g h sqarg sq nx y)\n -}\n\t\twhere\n\t\tg = evalPoly p' x / evalPoly p x\n\t\th = g^2 - evalPoly p'' x / evalPoly p x\n\t\tsqarg = (deg-1)*(deg*h-g^2)\n\t\tsq = sqrt sqarg\n\t\tdenom = if g>0 then g+sq else g-sq\n\t\tnx = x - deg/denom -- `debug` (\"n,denom:\"++show(n,denom))\n y = evalPoly p nx\n\n{-\n - Vector Math\n -}\n\n-- Standard vector norms\nnorm :: Vector Double -> Double\n--norm v = pnorm PNorm2 v\n-- XXX: For 3-vectors this is quite a bit faster\nnorm !v = sqrt $ v@>0*v@>0 + v@>1*v@>1 + v@>2*v@>2 \n\nnorm3D :: Vector Double -> Double\nnorm3D = sqrt . sqrNorm3D\n\nsqrNorm3D :: Vector Double -> Double\nsqrNorm3D v = v@>0*v@>0 + v@>1*v@>1 + v@>2*v@>2 \n\n-- Normalize vector\nunitV v = scale (recip $ norm v) v\n\n-- 3-vector cross product\ncross :: Vector Double->Vector Double->Vector Double\ncross !a !b = 3|>[a@>1 * b@>2 - a@>2 * b@>1 \n\t\t,-a@>0 * b@>2 + a@>2 * b@>0 \n\t\t,a@>0 * b@>1 - a@>1 * b@>0] \n\n-- Rodrigues' rotation formula\nrodr :: Vector Double->Double->Vector Double->Vector Double\nrodr z th vec = scale (cos th) vec + scale (sin th) (cross z vec)\n\t\t+ scale ((z<.>vec)*(1-cos th)) z\n\n{-\n - List and tuple manipulations\n -}\n\nthrd (_,_,a) = a\nfrth (_,_,_,a) = a\n\n-- Give all pairings, excluding (p,p) and when (p1,p2) excluding (p2,p1)\n-- Courtesy of Jussi Knuuttila\nchooseTwo :: [a] -> [(a,a)]\nchooseTwo as = concatMap pairs (tails as)\n where pairs [] = []\n pairs (a:as) = zip (repeat a) as\n\n-- Take every nth of list\ntakenth 0 _ = []\ntakenth _ [] = []\ntakenth n list = \n\titer list []\n\twhere\n\titer [] acc = acc\n\titer list acc =\n\t\titer (tail newList) (acc ++ [head newList])\n\t\twhere newList = drop (n-1) list\n\n-- Debugging and printing functions\ndebug = flip trace\nshowFloat f = showEFloat (Just 4) f \"\"\n", "meta": {"hexsha": "5eba5ab180565b2c135f6a908885666fa727206b", "size": 3071, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Misc.hs", "max_stars_repo_name": "sageh/AstroHaskell", "max_stars_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Misc.hs", "max_issues_repo_name": "sageh/AstroHaskell", "max_issues_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Misc.hs", "max_forks_repo_name": "sageh/AstroHaskell", "max_forks_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3801652893, "max_line_length": 73, "alphanum_fraction": 0.5985021166, "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064587, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6687687968831171}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.Statistics.Information\n-- Copyright : (c) A. V. H. McPhail 2010, 2014\n-- License : BSD3\n--\n-- Maintainer : haskell.vivian.mcphail gmail com\n-- Stability : provisional\n-- Portability : portable\n--\n-- Shannon entropy\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.Statistics.Information (\n entropy\n , mutual_information\n ) where\n\n\n-----------------------------------------------------------------------------\n\nimport Numeric.Statistics.PDF\n\nimport qualified Numeric.LinearAlgebra as LA\n--import Numeric.LinearAlgebra.Data hiding(Vector)\n\n--import qualified Data.Vector as DV\nimport qualified Data.Vector.Storable as V\n\nimport Prelude hiding(map,zip)\n\n-----------------------------------------------------------------------------\n\nzeroToOne x\n | x == 0.0 = 1.0\n | otherwise = x\n\nlogE = V.map (log . zeroToOne)\n\n\n-----------------------------------------------------------------------------\n\n-- | the entropy \\sum p_i l\\ln{p_i} of a sequence\nentropy :: PDF a Double \n => a -- ^ the underlying distribution\n -> LA.Vector Double -- ^ the sequence\n -> Double -- ^ the entropy\nentropy p x = let ps = probability p x\n in negate $ (LA.dot ps (logE ps))\n\n-- | the mutual information \\sum_x \\sum_y p(x,y) \\ln{\\frac{p(x,y)}{p(x)p(y)}}\nmutual_information :: (PDF a Double, PDF b (Double,Double)) \n => b -- ^ the underlying distribution\n -> a -- ^ the first dimension distribution\n -> a -- ^ the second dimension distribution\n -> (LA.Vector Double, LA.Vector Double) -- ^ the sequence\n -> Double -- ^ the mutual information\nmutual_information p px py (x,y) = let ps = probability p $ V.zipWith (,) x y\n xs = probability px x\n ys = probability py y\n in (LA.dot ps (logE ps - logE (xs*ys)))\n\n-----------------------------------------------------------------------------\n", "meta": {"hexsha": "7e4e718f1e7222839f704d6b218d902c40835f59", "size": 2505, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/Statistics/Information.hs", "max_stars_repo_name": "amcphail/hstatistics", "max_stars_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2015-05-14T19:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T15:23:53.000Z", "max_issues_repo_path": "lib/Numeric/Statistics/Information.hs", "max_issues_repo_name": "amcphail/hstatistics", "max_issues_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-12-14T23:36:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-06T23:18:48.000Z", "max_forks_repo_path": "lib/Numeric/Statistics/Information.hs", "max_forks_repo_name": "amcphail/hstatistics", "max_forks_repo_head_hexsha": "13d2bfa3280865cd8269ed5131b20f34d762e77b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-05-24T22:51:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T19:12:30.000Z", "avg_line_length": 37.9545454545, "max_line_length": 103, "alphanum_fraction": 0.4043912176, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.668631063082302}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra.Vector.Statistics\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Basic multivariate statistics.\n--\n\nmodule Numeric.LinearAlgebra.Vector.Statistics (\n -- * Immutable interface\n sum,\n mean,\n weightedSum,\n weightedMean,\n\n -- * Mutable interface\n addSumTo,\n meanTo,\n addWeightedSumTo,\n weightedMeanTo,\n\n ) where\n\nimport Prelude hiding ( sum )\n\nimport Control.Monad( forM_ )\nimport Control.Monad.ST( ST )\n\nimport Numeric.LinearAlgebra.Types\n\nimport Numeric.LinearAlgebra.Vector.Base( Vector )\nimport Numeric.LinearAlgebra.Vector.STBase( RVector, STVector )\nimport qualified Numeric.LinearAlgebra.Vector.STBase as V\n\n\n-- | Returns the sum of the vectors. The first argument gives the dimension\n-- of the vectors.\nsum :: (BLAS1 e) => Int -> [Vector e] -> Vector e\nsum p xs = V.create $ do\n s <- V.new_ p\n V.clear s\n addSumTo s xs\n return s\n\n-- | Returns the mean of the vectors. The first argument gives the dimension\n-- of the vectors.\nmean :: (BLAS1 e) => Int -> [Vector e] -> Vector e\nmean p xs = V.create $ do\n m <- V.new_ p\n meanTo m xs\n return m\n\n-- | Returns the weighted sum of the vectors. The first argument gives the\n-- dimension of the vectors.\nweightedSum :: (BLAS1 e) => Int -> [(e, Vector e)] -> Vector e\nweightedSum p wxs = V.create $ do\n s <- V.new_ p\n V.clear s\n addWeightedSumTo s wxs\n return s\n\n-- | Returns the weighted mean of the vectors. The first argument gives the\n-- dimension of the vectors.\nweightedMean :: (BLAS1 e)\n => Int -> [(Double, Vector e)] -> Vector e\nweightedMean p wxs = V.create $ do\n m <- V.new_ p\n weightedMeanTo m wxs\n return m\n\n-- | Adds the sum of the vectors to the target vector.\naddSumTo :: (RVector v, BLAS1 e) => STVector s e -> [v e] -> ST s ()\naddSumTo dst = addWeightedSumTo dst . zip (repeat 1)\n\n-- | Sets the target vector to the mean of the vectors.\nmeanTo :: (RVector v, BLAS1 e)\n => STVector s e -> [v e] -> ST s()\nmeanTo dst = weightedMeanTo dst . zip (repeat 1)\n\n-- | Adds the weigthed sum of the vectors to the target vector.\naddWeightedSumTo :: (RVector v, BLAS1 e)\n => STVector s e -> [(e, v e)] -> ST s ()\naddWeightedSumTo s wxs = do\n n <- V.getDim s\n err <- V.new n 0\n old_s <- V.new_ n\n diff <- V.new_ n\n val <- V.new_ n\n \n forM_ wxs $ \\(w,x) -> do\n V.unsafeCopyTo old_s s -- old_s := s\n \n V.unsafeCopyTo val x -- val := w * x\n V.scaleM_ w val\n\n V.addTo err err val -- err := err + val\n V.addTo s s err -- s := s + err\n \n V.subTo diff old_s s -- diff := old_s - s\n V.addTo err diff val -- err := diff + val\n\n-- | Sets the target vector to the weighted mean of the vectors.\nweightedMeanTo :: (RVector v, BLAS1 e)\n => STVector s e -> [(Double, v e)] -> ST s ()\nweightedMeanTo m wxs = let\n go _ _ [] = return ()\n go diff w_sum ((w,x):wxs') | w == 0 = go diff w_sum wxs'\n | otherwise = let w_sum' = w_sum + w\n in do\n V.subTo diff x m\n V.addWithScaleM_ \n (realToFrac $ w/w_sum') diff m\n go diff w_sum' wxs'\n in do\n n <- V.getDim m\n diff <- V.new_ n\n V.clear m\n go diff 0 wxs\n", "meta": {"hexsha": "903a1e1fd572374445775ed57c04ff9d4e8228ed", "size": 3675, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Vector/Statistics.hs", "max_stars_repo_name": "patperry/hs-linear-algebra", "max_stars_repo_head_hexsha": "887939175e03687b12eabe2fce5904b494242a1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-03-22T17:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-21T17:56:00.000Z", "max_issues_repo_path": "lib/Numeric/LinearAlgebra/Vector/Statistics.hs", "max_issues_repo_name": "cartazio/hs-cblas", "max_issues_repo_head_hexsha": "eb0ad6bee7fa65900c25ebe4dfe831e7b7aa800b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Numeric/LinearAlgebra/Vector/Statistics.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": 30.1229508197, "max_line_length": 77, "alphanum_fraction": 0.5619047619, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6683577926854807}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nmodule PLA\n ( Weight(..)\n , Point'(..)\n , viewX\n , trainPLA\n , trainPLAWithInitial\n , isMisclassified\n ) where\n\nimport Control.Lens\nimport Control.Lens.Combinators\nimport Control.Lens.Operators\nimport Control.Monad.Reader\nimport Data.List\nimport Data.Traversable (for)\nimport Numeric.LinearAlgebra.Data\nimport System.Random\n\n--------------------------------\n-- Solutions to homework 1, problems 7-10 of\n-- the 'Learning from Data' course\n-- http://work.caltech.edu/homeworks.html\n-------------------------------------\n-------------------------------\n-- Types and Typeclass Instances\n--------------------------------\ntype Weight = (R, R, R)\n\ntype Point = (R, R)\n\n-- | To be used at a later stage - currently just a test\ndata Point' =\n Point'\n { _x :: R\n , _y :: R\n }\n\nmakeLenses ''Point'\n\ninstance Num Weight where\n (+) (x0, x1, x2) (w0, w1, w2) = (w0 + x0, w1 + x1, w2 + x2)\n (-) (x0, x1, x2) (w0, w1, w2) = (x0 - w0, x1 - w1, x2 - w2)\n (*) (x0, x1, x2) (w0, w1, w2) =\n (w2 * x1 - w1 * x2, w2 * x0 - w0 * x2, w1 * x0 - w0 * x1)\n negate (w0, w1, w2) = (negate w0, negate w1, negate w2)\n abs (w0, w1, w2) = (abs w0, abs w1, abs w2)\n fromInteger x = (fromInteger x, 0.0, 0.0)\n signum (w0, w1, w2) = signum (w0, w1, w2)\n\n--------------------------------------------\n-- Creating the line for the target function\n--------------------------------------------\nm :: Point -> Point -> R\nm (x1, x2) (z1, z2) = (x2 - z2) / (x1 - z1)\n\nb :: Point -> Point -> R\nb (x1, x2) (z1, z2) = x2 - x1 * (x2 - z2) / (x1 - z1)\n\n-- | Takes 2 Points and returns the function of a line connecting them\nline :: Point -> Point -> (R -> R)\nline point1 point2 = \\x -> m point1 point2 * x + b point1 point2\n\n-----------------------------------\n-- functions for the Weight type\n-----------------------------------\n-- | The dot product\ndotProd :: Weight -> Weight -> R\ndotProd (x0, x1, x2) (w0, w1, w2) = w0 * x0 + w1 * x1 + w2 * x2\n\n-- | Scalar multiplication of the weight vecotr\nprod :: R -> Weight -> Weight\nprod lambda (x0, x1, x2) = (x0 * lambda, x1 * lambda, x2 * lambda)\n\n-- | Converting a point to a weight by adding the first coordinate (1)\npoint2weight :: Point -> Weight\npoint2weight (x1, x2) = (1, x1, x2)\n\n-- | looks up the label of the point by applying the target function\nyn :: (R -> R) -> Point -> R\nyn yLine (x1, x2) =\n if yLine x1 < x2\n then (-1)\n else 1\n\n-- | Checking if a point is misclassified\nisMisclassified yLine weight point = classified /= label\n where\n classified = signum $ dotProd (point2weight point) weight\n label = yn yLine point\n\nupdateWeight' yLine w xn = w + prod (yn yLine xn) (point2weight xn)\n\n-- | Performs 1 training epoch (one run through all training points)\n-- | performs the perceptron learning algorithm\npla yLine w niter gen xs\n | misclassifiedXs == [] = (w, niter)\n | otherwise = pla yLine wUpdated (niter + 1) nextRandom xs\n where\n wUpdated = updateWeight' yLine w $ misclassifiedXs !! number\n misclassifiedXs = filter (isMisclassified yLine w) xs\n randomRange = (0, length misclassifiedXs - 1)\n (number, nextRandom) = randomR randomRange gen\n\n-- | stores the target function and performs training, returning the weight and the number of epochs performed before convergence\nweightReader' :: [Point] -> StdGen -> Reader (R -> R) (Weight, Int)\nweightReader' points gen = do\n targetFunc <- ask\n let weightsEpochs = pla targetFunc (0, 0, 0) 0 gen points\n return weightsEpochs\n\n-- | stores the target function and performs training, returning the weight and the number of epochs performed before convergence\nweightReader :: [Point] -> StdGen -> Weight -> Reader (R -> R) (Weight, Int)\nweightReader points gen initialWeights = do\n targetFunc <- ask\n let weightsEpochs = pla targetFunc initialWeights 0 gen points\n return weightsEpochs\n\n-- |Creates a random Point between (-1,-1) and (1,1)\ncreateRandomPoint = do\n rand1 :: R <- randomRIO (-1, 1)\n rand2 :: R <- randomRIO (-1, 1)\n return (rand1, rand2)\n\n-- |Creates a list of n random Points between (-1,-1) and (1,1)\ncreateRandomPoints n = do\n randList1 :: [R] <- for [1 .. n] $ \\_ -> randomRIO (-1, 1)\n randList2 :: [R] <- for [1 .. n] $ \\_ -> randomRIO (-1, 1)\n return $ zip randList1 randList2-- | creates an infinite list of permutations of the list provided as an argument\n\npointPermutations = cycle . permutations\n\n-- | Just a test for the point lens\nviewX point = view x point\n\n---------------------------------------------------------------\n-- The final loop that creates the target function and training and testing data,\n-- performs training and testing\n-------------------------------------------------------------------\n-- | performs the PLA\ntrainPLA :: Int -> IO ()\ntrainPLA nPoints = do\n point1 <- createRandomPoint\n point2 <- createRandomPoint\n stdgen <- getStdGen\n let target = line point1 point2\n trainpoints <- createRandomPoints nPoints\n let (weights, epochs) = runReader (weightReader' trainpoints stdgen) target\n putStr \"Weights: \"\n print weights\n putStr \"Epochs: \"\n print epochs\n testpoints <- createRandomPoints 1000\n let misclassifiedTestPoints =\n length $ filter (isMisclassified target weights) testpoints\n let prob = fromIntegral misclassifiedTestPoints / 1000\n putStr \"Probability f /= g: \"\n print prob\n\n-- | performs the PLA with a set of initial weights, training points and a target function\ntrainPLAWithInitial :: (R, R, R) -> [Point] -> (R -> R) -> IO (Weight, Int)\ntrainPLAWithInitial initialWeights trainPoints target = do\n stdgen <- getStdGen\n let (weights, epochs) =\n runReader (weightReader trainPoints stdgen initialWeights) target\n return (weights, epochs)\n", "meta": {"hexsha": "d28c9a9e59d83bef1693535cbf813d374ee37a1e", "size": 5900, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/hw1/PLA.hs", "max_stars_repo_name": "AR2202/LearningFromData", "max_stars_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-18T06:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T06:07:24.000Z", "max_issues_repo_path": "src/hw1/PLA.hs", "max_issues_repo_name": "AR2202/LearningFromData", "max_issues_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hw1/PLA.hs", "max_forks_repo_name": "AR2202/LearningFromData", "max_forks_repo_head_hexsha": "3bc789e122f14430a906044424d4bce212beb938", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5029239766, "max_line_length": 129, "alphanum_fraction": 0.6144067797, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6682165039039065}} {"text": "{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveFoldable #-}\n{-# LANGUAGE DeriveTraversable #-}\n{-# LANGUAGE ParallelListComp #-}\n-----------------------------------------------------------------------------\n-- |\n-- Copyright : (c) Edward Kmett 2010-2021\n-- License : BSD3\n-- Maintainer : ekmett@gmail.com\n-- Stability : experimental\n-- Portability : GHC only\n--\n-----------------------------------------------------------------------------\n\nmodule Numeric.AD.Newton\n (\n -- * Newton's Method (Forward AD)\n findZero\n , findZeroNoEq\n , inverse\n , inverseNoEq\n , fixedPoint\n , fixedPointNoEq\n , extremum\n , extremumNoEq\n -- * Gradient Ascent/Descent (Reverse AD)\n , gradientDescent, constrainedDescent, CC(..), eval\n , gradientAscent\n , conjugateGradientDescent\n , conjugateGradientAscent\n , stochasticGradientDescent\n ) where\n\nimport Data.Foldable (all, sum)\nimport Data.Reflection (Reifies)\nimport Data.Traversable\nimport Numeric.AD.Internal.Combinators\nimport Numeric.AD.Internal.Forward (Forward)\nimport Numeric.AD.Internal.On\nimport Numeric.AD.Internal.Or\nimport Numeric.AD.Internal.Reverse (Reverse, Tape)\nimport Numeric.AD.Internal.Type (AD(..))\nimport Numeric.AD.Mode\nimport Numeric.AD.Mode.Reverse as Reverse (gradWith, gradWith', grad')\nimport Numeric.AD.Rank1.Kahn as Kahn (Kahn, grad)\nimport qualified Numeric.AD.Rank1.Newton as Rank1\nimport Prelude hiding (all, mapM, sum)\n\n-- $setup\n-- >>> import Data.Complex\n\n-- | The 'findZero' function finds a zero of a scalar function using\n-- Newton's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes constant\n-- (\"it converges\"), no further elements are returned.\n--\n-- Examples:\n--\n-- >>> take 10 $ findZero (\\x->x^2-4) 1\n-- [1.0,2.5,2.05,2.000609756097561,2.0000000929222947,2.000000000000002,2.0]\n--\n-- >>> last $ take 10 $ findZero ((+1).(^2)) (1 :+ 1)\n-- 0.0 :+ 1.0\nfindZero :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> [a]\nfindZero f = Rank1.findZero (runAD.f.AD)\n{-# INLINE findZero #-}\n\n-- | The 'findZeroNoEq' function behaves the same as 'findZero' except that it\n-- doesn't truncate the list once the results become constant. This means it\n-- can be used with types without an 'Eq' instance.\nfindZeroNoEq :: Fractional a => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> [a]\nfindZeroNoEq f = Rank1.findZeroNoEq (runAD.f.AD)\n{-# INLINE findZeroNoEq #-}\n\n-- | The 'inverse' function inverts a scalar function using\n-- Newton's method; its output is a stream of increasingly accurate\n-- results. (Modulo the usual caveats.) If the stream becomes\n-- constant (\"it converges\"), no further elements are returned.\n--\n-- Example:\n--\n-- >>> last $ take 10 $ inverse sqrt 1 (sqrt 10)\n-- 10.0\ninverse :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> a -> [a]\ninverse f = Rank1.inverse (runAD.f.AD)\n{-# INLINE inverse #-}\n\n-- | The 'inverseNoEq' function behaves the same as 'inverse' except that it\n-- doesn't truncate the list once the results become constant. This means it\n-- can be used with types without an 'Eq' instance.\ninverseNoEq :: Fractional a => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> a -> [a]\ninverseNoEq f = Rank1.inverseNoEq (runAD.f.AD)\n{-# INLINE inverseNoEq #-}\n\n-- | The 'fixedPoint' function find a fixedpoint of a scalar\n-- function using Newton's method; its output is a stream of\n-- increasingly accurate results. (Modulo the usual caveats.)\n--\n-- If the stream becomes constant (\"it converges\"), no further\n-- elements are returned.\n--\n-- >>> last $ take 10 $ fixedPoint cos 1\n-- 0.7390851332151607\nfixedPoint :: (Fractional a, Eq a) => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> [a]\nfixedPoint f = Rank1.fixedPoint (runAD.f.AD)\n{-# INLINE fixedPoint #-}\n\n-- | The 'fixedPointNoEq' function behaves the same as 'fixedPoint' except that\n-- it doesn't truncate the list once the results become constant. This means it\n-- can be used with types without an 'Eq' instance.\nfixedPointNoEq :: Fractional a => (forall s. AD s (Forward a) -> AD s (Forward a)) -> a -> [a]\nfixedPointNoEq f = Rank1.fixedPointNoEq (runAD.f.AD)\n{-# INLINE fixedPointNoEq #-}\n\n-- | The 'extremum' function finds an extremum of a scalar\n-- function using Newton's method; produces a stream of increasingly\n-- accurate results. (Modulo the usual caveats.) If the stream\n-- becomes constant (\"it converges\"), no further elements are returned.\n--\n-- >>> last $ take 10 $ extremum cos 1\n-- 0.0\nextremum :: (Fractional a, Eq a) => (forall s. AD s (On (Forward (Forward a))) -> AD s (On (Forward (Forward a)))) -> a -> [a]\nextremum f = Rank1.extremum (runAD.f.AD)\n{-# INLINE extremum #-}\n\n-- | The 'extremumNoEq' function behaves the same as 'extremum' except that it\n-- doesn't truncate the list once the results become constant. This means it\n-- can be used with types without an 'Eq' instance.\nextremumNoEq :: Fractional a => (forall s. AD s (On (Forward (Forward a))) -> AD s (On (Forward (Forward a)))) -> a -> [a]\nextremumNoEq f = Rank1.extremumNoEq (runAD.f.AD)\n{-# INLINE extremumNoEq #-}\n\n-- | The 'gradientDescent' function performs a multivariate\n-- optimization, based on the naive-gradient-descent in the file\n-- @stalingrad\\/examples\\/flow-tests\\/pre-saddle-1a.vlad@ from the\n-- VLAD compiler Stalingrad sources. Its output is a stream of\n-- increasingly accurate results. (Modulo the usual caveats.)\n--\n-- It uses reverse mode automatic differentiation to compute the gradient.\ngradientDescent :: (Traversable f, Fractional a, Ord a) => (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a) -> f a -> [f a]\ngradientDescent f x0 = go x0 fx0 xgx0 0.1 (0 :: Int)\n where\n (fx0, xgx0) = Reverse.gradWith' (,) f x0\n go x fx xgx !eta !i\n | eta == 0 = [] -- step size is 0\n | fx1 > fx = go x fx xgx (eta/2) 0 -- we stepped too far\n | zeroGrad xgx = [] -- gradient is 0\n | otherwise = x1 : if i == 10\n then go x1 fx1 xgx1 (eta*2) 0\n else go x1 fx1 xgx1 eta (i+1)\n where\n zeroGrad = all (\\(_,g) -> g == 0)\n x1 = fmap (\\(xi,gxi) -> xi - eta * gxi) xgx\n (fx1, xgx1) = Reverse.gradWith' (,) f x1\n{-# INLINE gradientDescent #-}\n\ndata SEnv (f :: * -> *) a = SEnv { sValue :: a, origEnv :: f a }\n deriving (Functor, Foldable, Traversable)\n\n-- | Convex constraint, CC, is a GADT wrapper that hides the existential\n-- ('s') which is so prevalent in the rest of the API. This is an\n-- engineering convenience for managing the skolems.\ndata CC f a where\n CC :: forall f a. (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a) -> CC f a\n\n-- |@constrainedDescent obj fs env@ optimizes the convex function @obj@\n-- subject to the convex constraints @f <= 0@ where @f `elem` fs@. This is\n-- done using a log barrier to model constraints (i.e. Boyd, Chapter 11.3).\n-- The returned optimal point for the objective function must satisfy @fs@,\n-- but the initial environment, @env@, needn't be feasible.\nconstrainedDescent :: forall f a. (Traversable f, RealFloat a, Floating a, Ord a)\n => (forall s. Reifies s Tape => f (Reverse s a)\n -> Reverse s a)\n -> [CC f a]\n -> f a\n -> [(a,f a)]\nconstrainedDescent objF [] env =\n map (\\x -> (eval objF x, x)) (gradientDescent objF env)\nconstrainedDescent objF cs env =\n let s0 = 1 + maximum [eval c env | CC c <- cs]\n -- ^ s0 = max ( f_i(0) )\n cs' = [CC (\\(SEnv sVal rest) -> c rest - sVal) | CC c <- cs]\n -- ^ f_i' = f_i - s0 and thus f_i' <= 0\n envS = SEnv s0 env\n -- feasible point for f_i', use gd to find feasiblity for f_i\n cc = constrainedConvex' (CC sValue) cs' envS ((<=0) . sValue)\n in case dropWhile ((0 <) . fst) (take (2^(20::Int)) cc) of\n [] -> []\n (_,envFeasible) : _ ->\n constrainedConvex' (CC objF) cs (origEnv envFeasible) (const True)\n{-# INLINE constrainedDescent #-}\n\neval :: (Traversable f, Fractional a, Ord a) => (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a) -> f a -> a\neval f e = fst (grad' f e)\n{-# INLINE eval #-}\n\n-- | Like 'constrainedDescent' except the initial point must be feasible.\nconstrainedConvex' :: forall f a. (Traversable f, RealFloat a, Floating a, Ord a)\n => CC f a\n -> [CC f a]\n -> f a\n -> (f a -> Bool)\n -> [(a,f a)]\nconstrainedConvex' objF cs env term =\n -- 1. Transform cs using a log barrier with increasing t values.\n let os = map (mkOpt objF cs) tValues\n -- 2. Iteratively run gradientDescent on each os.\n envs = [(undefined,env)] :\n [gD (snd $ last e) o\n | o <- os\n | e <- limEnvs\n ]\n -- Obtain a finite number of elements from the initial len tValues - 1 lists.\n limEnvs = zipWith id nrSteps envs\n in dropWhile (not . term . snd) (concat $ drop 1 limEnvs)\n where\n tValues = map realToFrac $ take 64 $ iterate (*2) (2 :: a)\n nrSteps = [take 20 | _ <- [1..length tValues]] ++ [id]\n -- | `gD f e` is gradient descent with the evaulated result\n gD e (CC f) = (eval f e, e) :\n map (\\x -> (eval f x, x)) (gradientDescent f e)\n{-# INLINE constrainedConvex' #-}\n\n-- @mkOpt u fs t@ converts an inequality convex problem (@u,fs@) into an\n-- unconstrained convex problem using log barrier @u + -(1/t)log(-f_i)@.\n-- As @t@ increases the approximation is more accurate but the gradient\n-- decreases, making the gradient descent more expensive.\nmkOpt :: forall f a. (Traversable f, RealFloat a, Floating a, Ord a)\n => CC f a -> [CC f a]\n -> a -> CC f a\nmkOpt (CC o) xs t = CC (\\e -> o e + sum (map (\\(CC c) -> iHat t c e) xs))\n{-# INLINE mkOpt #-}\n\niHat :: forall a f. (Traversable f, RealFloat a, Floating a, Ord a)\n => a\n -> (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a)\n -> (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a)\niHat t c e =\n let r = c e\n in if r >= 0 || isNaN r\n then 1 / 0\n else (-1 / auto t) * log( - (c e))\n{-# INLINE iHat #-}\n\n-- | The 'stochasticGradientDescent' function approximates\n-- the true gradient of the constFunction by a gradient at\n-- a single example. As the algorithm sweeps through the training\n-- set, it performs the update for each training example.\n--\n-- It uses reverse mode automatic differentiation to compute the gradient\n-- The learning rate is constant through out, and is set to 0.001\nstochasticGradientDescent :: (Traversable f, Fractional a, Ord a)\n => (forall s. Reifies s Tape => e -> f (Reverse s a) -> Reverse s a)\n -> [e]\n -> f a\n -> [f a]\nstochasticGradientDescent errorSingle d0 x0 = go xgx0 0.001 dLeft\n where\n dLeft = tail $ cycle d0\n xgx0 = Reverse.gradWith (,) (errorSingle (head d0)) x0\n go xgx !eta d\n | eta ==0 = []\n | otherwise = x1 : go xgx1 eta (tail d)\n where\n x1 = fmap (\\(xi, gxi) -> xi - eta * gxi) xgx\n (_, xgx1) = Reverse.gradWith' (,) (errorSingle (head d)) x1\n{-# INLINE stochasticGradientDescent #-}\n\n-- | Perform a gradient descent using reverse mode automatic differentiation to compute the gradient.\ngradientAscent :: (Traversable f, Fractional a, Ord a) => (forall s. Reifies s Tape => f (Reverse s a) -> Reverse s a) -> f a -> [f a]\ngradientAscent f = gradientDescent (negate . f)\n{-# INLINE gradientAscent #-}\n\n-- | Perform a conjugate gradient descent using reverse mode automatic differentiation to compute the gradient, and using forward-on-forward mode for computing extrema.\n--\n-- >>> let sq x = x * x\n-- >>> let rosenbrock [x,y] = sq (1 - x) + 100 * sq (y - sq x)\n-- >>> rosenbrock [0,0]\n-- 1\n-- >>> rosenbrock (conjugateGradientDescent rosenbrock [0, 0] !! 5) < 0.1\n-- True\nconjugateGradientDescent\n :: (Traversable f, Ord a, Fractional a)\n => (forall s. Chosen s => f (Or s (On (Forward (Forward a))) (Kahn a)) -> Or s (On (Forward (Forward a))) (Kahn a))\n -> f a -> [f a]\nconjugateGradientDescent f = conjugateGradientAscent (negate . f)\n{-# INLINE conjugateGradientDescent #-}\n\nlfu :: Functor f => (f (Or F a b) -> Or F a b) -> f a -> a\nlfu f = runL . f . fmap L\n\nrfu :: Functor f => (f (Or T a b) -> Or T a b) -> f b -> b\nrfu f = runR . f . fmap R\n\n-- | Perform a conjugate gradient ascent using reverse mode automatic differentiation to compute the gradient.\nconjugateGradientAscent\n :: (Traversable f, Ord a, Fractional a)\n => (forall s. Chosen s => f (Or s (On (Forward (Forward a))) (Kahn a)) -> Or s (On (Forward (Forward a))) (Kahn a))\n -> f a -> [f a]\nconjugateGradientAscent f x0 = takeWhile (all (\\a -> a == a)) (go x0 d0 d0 delta0)\n where\n dot x y = sum $ zipWithT (*) x y\n d0 = Kahn.grad (rfu f) x0\n delta0 = dot d0 d0\n go xi _ri di deltai = xi : go xi1 ri1 di1 deltai1\n where\n ai = last $ take 20 $ Rank1.extremum (\\a -> lfu f $ zipWithT (\\x d -> auto x + a * auto d) xi di) 0\n xi1 = zipWithT (\\x d -> x + ai*d) xi di\n ri1 = Kahn.grad (rfu f) xi1\n deltai1 = dot ri1 ri1\n bi1 = deltai1 / deltai\n di1 = zipWithT (\\r d -> r + bi1 * d) ri1 di\n{-# INLINE conjugateGradientAscent #-}\n", "meta": {"hexsha": "fd920a65cbf3d8d4770d29a9f70fc0d6f7e0e68d", "size": 13591, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Newton.hs", "max_stars_repo_name": "msakai/ad", "max_stars_repo_head_hexsha": "85aee3c6b4b621bab24c4379a88da1b5f0494d97", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 286, "max_stars_repo_stars_event_min_datetime": "2015-01-13T12:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T19:11:54.000Z", "max_issues_repo_path": "src/Numeric/AD/Newton.hs", "max_issues_repo_name": "msakai/ad", "max_issues_repo_head_hexsha": "85aee3c6b4b621bab24c4379a88da1b5f0494d97", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 42, "max_issues_repo_issues_event_min_datetime": "2015-03-15T02:22:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-19T18:26:25.000Z", "max_forks_repo_path": "src/Numeric/AD/Newton.hs", "max_forks_repo_name": "msakai/ad", "max_forks_repo_head_hexsha": "85aee3c6b4b621bab24c4379a88da1b5f0494d97", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2015-01-22T12:26:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T09:28:35.000Z", "avg_line_length": 42.471875, "max_line_length": 168, "alphanum_fraction": 0.6195276286, "num_tokens": 4027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6681982392442305}} {"text": "module Numeric.Layer.Sigmoid where\nimport Numeric.Layer\nimport Dependent.Size\nimport Numeric.Vector.Sized\nimport qualified Numeric.Vector.Sized as Sized\nimport GHC.TypeLits(KnownNat,Nat)\n\nnewtype Sigmoid (n :: Nat) = Sigmoid ()\n\ninstance Show (Sigmoid n) where\n showsPrec d (Sigmoid _) = showString \"Sigmoid\"\n\nsigmoid :: Floating x => x -> x\nsigmoid x = 1 / (1 + exp (-x))\n\nsigmoid' :: Num a => a -> a\nsigmoid' y = (1 - y) * y\n\ninstance KnownNat n => Layer (Sigmoid n) where\n type Inputs (Sigmoid n) = ZZ ::. n\n type Outputs (Sigmoid n) = ZZ ::. n\n type Tape (Sigmoid n) = SizedArray (ZZ ::. n)\n type Gradient (Sigmoid n) = ()\n forward _ x = (y, tape)\n where\n y = Sized.map sigmoid x\n tape = y\n backward _ tape dy = (gradient, dx)\n where\n gradient = ()\n dx = Sized.zipWith (*) dy (Sized.map sigmoid' tape)\n applyGradient layer _ = layer\n\n", "meta": {"hexsha": "cf700a7350de766ac5cb1648e01aec9a192acd1e", "size": 872, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Layer/Sigmoid.hs", "max_stars_repo_name": "mixed-signals/mixed-signals", "max_stars_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Layer/Sigmoid.hs", "max_issues_repo_name": "mixed-signals/mixed-signals", "max_issues_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Layer/Sigmoid.hs", "max_forks_repo_name": "mixed-signals/mixed-signals", "max_forks_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6470588235, "max_line_length": 57, "alphanum_fraction": 0.6479357798, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6679510641697284}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\nmodule Numeric.Layer.Affine where\n\nimport Dependent.Size\nimport Numeric.Layer\nimport Numeric.Vector.Sized\nimport qualified Numeric.Vector.Sized as Sized\nimport GHC.TypeLits\nimport Data.Array.Accelerate.LLVM.Native\n\ndata Affine (n :: Nat) (m :: Nat) = Affine (SizedMatrix' n m) (SizedVector' m)\n deriving (Show)\n\ninstance (KnownNat n, KnownNat m) => Layer (Affine n m) where\n type Inputs (Affine n m) = ZZ '::. n\n type Outputs (Affine n m) = ZZ '::. m\n type Tape (Affine n m) = SizedArray (ZZ ::. n)\n type Gradient (Affine n m) = Affine n m\n forward (Affine ws b) x = (affine (use ws) (use b) x, x)\n backward (Affine ws b) x dy = (Affine dw db, dx)\n where\n dx = use ws #> dy\n dw = runSized run (dy `outer` x)\n db = runSized run (dy)\n applyGradient (Affine ws b) (Affine dw db)\n = Affine\n (runSized run $ Sized.zipWith (-) (use ws) (use dw))\n (runSized run $ Sized.zipWith (-) (use b) (use db))\n\naffine\n :: (KnownNat n, KnownNat m)\n => SizedMatrix n m\n -> SizedVector m\n -> SizedVector n\n -> SizedVector m\naffine ws b x = (x <# ws) .+. b\n\n-- affine_dw dedy = dedw\n-- affine_db dedy = dedb\n-- affine_dx dedy = dedx\n", "meta": {"hexsha": "0faca4287ae45ab7c7f9c2da92545a1d89ce7c33", "size": 1276, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Layer/Affine.hs", "max_stars_repo_name": "mixed-signals/mixed-signals", "max_stars_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Layer/Affine.hs", "max_issues_repo_name": "mixed-signals/mixed-signals", "max_issues_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Layer/Affine.hs", "max_forks_repo_name": "mixed-signals/mixed-signals", "max_forks_repo_head_hexsha": "90cdd54bf2aae44f7e40e1dbdebc0d3ebc69fe2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 78, "alphanum_fraction": 0.6457680251, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6678577838695315}} {"text": "-----------------------------------------------------------------------------\n-- |\n-- Module : Data.Random.Distribution.MultivariateNormal\n-- Copyright : (c) 2016 FP Complete Corporation\n-- License : MIT (see LICENSE)\n-- Maintainer : dominic@steinitz.org\n--\n-- Sample from the multivariate normal distribution with a given\n-- vector-valued \\(\\mu\\) and covariance matrix \\(\\Sigma\\). For example,\n-- the chart below shows samples from the bivariate normal\n-- distribution.\n--\n-- <>\n--\n-- Example code to generate the chart:\n--\n-- > import qualified Graphics.Rendering.Chart as C\n-- > import Graphics.Rendering.Chart.Backend.Diagrams\n-- >\n-- > import Data.Random.Distribution.MultivariateNormal\n-- >\n-- > import qualified Data.Random as R\n-- > import Data.Random.Source.PureMT\n-- > import Control.Monad.State\n-- > import qualified Numeric.LinearAlgebra.HMatrix as LA\n-- >\n-- > nSamples :: Int\n-- > nSamples = 10000\n-- >\n-- > sigma1, sigma2, rho :: Double\n-- > sigma1 = 3.0\n-- > sigma2 = 1.0\n-- > rho = 0.5\n-- >\n-- > singleSample :: R.RVarT (State PureMT) (LA.Vector Double)\n-- > singleSample = R.sample $ Normal (LA.fromList [0.0, 0.0])\n-- > (LA.sym $ (2 LA.>< 2) [ sigma1, rho * sigma1 * sigma2\n-- > , rho * sigma1 * sigma2, sigma2])\n-- >\n-- > multiSamples :: [LA.Vector Double]\n-- > multiSamples = evalState (replicateM nSamples $ R.sample singleSample) (pureMT 3)\n-- > pts = map (f . LA.toList) multiSamples\n-- > where\n-- > f [x, y] = (x, y)\n-- > f _ = error \"Only pairs for this chart\"\n-- >\n-- >\n-- > chartPoint pointVals n = C.toRenderable layout\n-- > where\n-- >\n-- > fitted = C.plot_points_values .~ pointVals\n-- > $ C.plot_points_style . C.point_color .~ opaque red\n-- > $ C.plot_points_title .~ \"Sample\"\n-- > $ def\n-- >\n-- > layout = C.layout_title .~ \"Sampling Bivariate Normal (\" ++ (show n) ++ \" samples)\"\n-- > $ C.layout_y_axis . C.laxis_generate .~ C.scaledAxis def (-3,3)\n-- > $ C.layout_x_axis . C.laxis_generate .~ C.scaledAxis def (-3,3)\n-- >\n-- > $ C.layout_plots .~ [C.toPlot fitted]\n-- > $ def\n-- >\n-- > diagM = do\n-- > denv <- defaultEnv C.vectorAlignmentFns 600 500\n-- > return $ fst $ runBackend denv (C.render (chartPoint pts nSamples) (500, 500))\n--\n-----------------------------------------------------------------------------\n\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule Data.Random.Distribution.MultivariateNormal\n ( Normal(..)\n ) where\n\nimport Data.Random.Distribution\nimport qualified Numeric.LinearAlgebra.HMatrix as H\nimport Control.Monad\nimport qualified Data.Random as R\nimport Foreign.Storable ( Storable )\nimport Data.Maybe ( fromJust )\n\nnormalMultivariate :: H.Vector Double -> H.Herm Double -> R.RVarT m (H.Vector Double)\nnormalMultivariate mu bigSigma = do\n z <- replicateM (H.size mu) (rvarT R.StdNormal)\n return $ mu + bigA H.#> (H.fromList z)\n where\n (vals, bigU) = H.eigSH bigSigma\n lSqrt = H.diag $ H.cmap sqrt vals\n bigA = bigU H.<> lSqrt\n\ndata family Normal k :: *\n\ndata instance Normal (H.Vector Double) = Normal (H.Vector Double) (H.Herm Double)\n\ninstance Distribution Normal (H.Vector Double) where\n rvar (Normal m s) = normalMultivariate m s\n\nnormalPdf :: (H.Numeric a, H.Field a, H.Indexable (H.Vector a) a, Num (H.Vector a)) =>\n H.Vector a -> H.Herm a -> H.Vector a -> a\nnormalPdf mu sigma x = exp $ normalLogPdf mu sigma x\n\nnormalLogPdf :: (H.Numeric a, H.Field a, H.Indexable (H.Vector a) a, Num (H.Vector a)) =>\n H.Vector a -> H.Herm a -> H.Vector a -> a\nnormalLogPdf mu bigSigma x = - H.sumElements (H.cmap log (diagonals dec))\n - 0.5 * (fromIntegral (H.size mu)) * log (2 * pi)\n - 0.5 * s\n where\n dec = fromJust $ H.mbChol bigSigma\n t = fromJust $ H.linearSolve (H.tr dec) (H.asColumn $ x - mu)\n u = H.cmap (\\v -> v * v) t\n s = H.sumElements u\n\ndiagonals :: (Storable a, H.Element t, H.Indexable (H.Vector t) a) =>\n H.Matrix t -> H.Vector a\ndiagonals m = H.fromList (map (\\i -> m H.! i H.! i) [0..n-1])\n where\n n = max (H.rows m) (H.cols m)\n\ninstance PDF Normal (H.Vector Double) where\n pdf (Normal m s) = normalPdf m s\n logPdf (Normal m s) = normalLogPdf m s\n", "meta": {"hexsha": "56bebb3da5121ffc047df457e0ee4dfeadbdea74", "size": 4597, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Random/Distribution/MultivariateNormal.hs", "max_stars_repo_name": "steinitznavican/random-fu-multivariate", "max_stars_repo_head_hexsha": "4f704757d0119b8c4f8ea5c2390277b775825a6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Random/Distribution/MultivariateNormal.hs", "max_issues_repo_name": "steinitznavican/random-fu-multivariate", "max_issues_repo_head_hexsha": "4f704757d0119b8c4f8ea5c2390277b775825a6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Random/Distribution/MultivariateNormal.hs", "max_forks_repo_name": "steinitznavican/random-fu-multivariate", "max_forks_repo_head_hexsha": "4f704757d0119b8c4f8ea5c2390277b775825a6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-13T19:27:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:27:24.000Z", "avg_line_length": 36.776, "max_line_length": 108, "alphanum_fraction": 0.5892973678, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6677784232308014}} {"text": "-- ch03 example 3.7\n\nimport Statistics.Distribution\nimport Statistics.Distribution.Binomial\n\nb :: BinomialDistribution\nb = binomial 5 0.05\n\nmain = do\n putStrLn $ \"If 5 samples is tested, the probabiliy of observing at least one defective: \" \n ++ show (1 - probability b 0)\n", "meta": {"hexsha": "f10af2a8ab2603716e4152d7d895da950d43d111", "size": 283, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "ch03/ex3_07.hs", "max_stars_repo_name": "raydsameshima/Stat", "max_stars_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch03/ex3_07.hs", "max_issues_repo_name": "raydsameshima/Stat", "max_issues_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": "ch03/ex3_07.hs", "max_forks_repo_name": "raydsameshima/Stat", "max_forks_repo_head_hexsha": "333bc36287530b7520100d040cb7e6177dea70cf", "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": 23.5833333333, "max_line_length": 92, "alphanum_fraction": 0.7208480565, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6675785652627032}} {"text": "module Fractals\n( order\n, floatOrder\n, mandelbrot\n, bmp\n, tangentPoint\n, mandelbrotCardioid\n, mag2\n, toBitmap\n) where\n\nimport Data.Complex (Complex(..), mkPolar)\nimport Graphics.Gloss\nimport qualified Data.ByteString as B\nimport Data.Word\nimport Control.Parallel.Strategies\n\nimport Palette\n\nmag2:: Complex Double -> Double\nmag2 (a:+b) = a^(2::Int) + b^(2::Int)\n\n-- | Compute the order of a given complex function.\norder :: (Complex Double -> Complex Double) -- ^ a function on the complex plane\n -> Double -- ^ the escape radius squared\n -> Int -- ^ the maximum order\n -> Complex Double -- ^ a starting point\n -> (Int, Complex Double) -- ^ the order\norder f radius2 nMax z0 = let f' = \\ (i, z) -> (i+1, f z)\n fs = dropWhile (\\ (i, z) -> i Complex Double) -- ^ a function on the complex plane\n -> Double -- ^ the escape radius squared\n -> Int -- ^ the maximum order\n -> Complex Double -- ^ a starting point\n -> Double -- ^ the order\nfloatOrder f radius2 nMax z0 = let (nu, z) = order f radius2 nMax z0\n in fromIntegral nu - log (0.5 * (log $ mag2 z)) / log 2.0\n\n-- | the Mandelbrot function: z^2 + c.\nmandelbrot :: Complex Double -- ^ the c parameter\n -> Complex Double -- ^ the z variable\n -> Complex Double -- ^ the resulting value\nmandelbrot (cr:+ci) (zr:+zi) = (cr + zr^(2::Int) - zi^(2::Int)) :+ (ci + 2*zr*zi)\n--mandelbrot c z = z**2 + c\n\n-- | Yield the point tangent to the main cardioid and to the bulb with period q\n-- and combinatorial rotation number r=p/q.\ntangentPoint :: Rational -> Complex Double\ntangentPoint r = mandelbrotCardioid $ mkPolar 1.0 (2.0 * pi * fromRational r)\n\n-- | The equation of the main cardioid.\nmandelbrotCardioid :: Complex Double -> Complex Double\nmandelbrotCardioid mu = 0.5 * mu * (1.0 - 0.5 * mu)\n\nbitmapFormat :: BitmapFormat\nbitmapFormat = BitmapFormat BottomToTop PxRGBA\n\nescapeRadius2 :: Double\nescapeRadius2 = 100000.0\n\nmaxIter :: Int\nmaxIter = 255\n\nbmpValues :: Int -> Int -> Double -> Double -> Double -> [Double]\nbmpValues w h xc yc picScale =\n let wf = fromIntegral w * picScale\n hf = fromIntegral h * picScale\n floatOrderFromIJ :: (Int, Int) -> Double\n floatOrderFromIJ (i,j) = let x0 = xc - 0.5*wf + (fromIntegral j)*wf/(fromIntegral (w-1))\n y0 = yc - 0.5*hf + (fromIntegral i)*hf/(fromIntegral (h-1))\n z0 = x0 :+ y0\n in floatOrder (mandelbrot z0) escapeRadius2 maxIter z0\n indices = (,) <$> [0..h-1] <*> [0..w-1]\n vals = map floatOrderFromIJ indices\n in vals `using` parListChunk h rseq\n\ntoBitmap :: Palette -> [Double] -> [Word8]\ntoBitmap _ [] = []\ntoBitmap palette l = let maxL = maximum l\n toBitmap' _ [] = []\n toBitmap' maxX (x:xs) = let (r,g,b) = palette (x/maxX)\n in r:g:b:255:(toBitmap' maxX xs)\n in toBitmap' maxL l\n\nbmpByteString :: Int -> Int -> Double -> Double -> Double -> B.ByteString\nbmpByteString w h xc yc picScale = B.pack vals\n where vals = toBitmap hsv $ bmpValues w h xc yc picScale\n\nbmp :: Int -> Int -> Complex Double -> Double -> Picture\nbmp w h (xc :+ yc) picScale = bitmapOfByteString w h bitmapFormat (bmpByteString w h xc yc picScale) False\n", "meta": {"hexsha": "e1566dfee59746ba40affae3ac8a34670621b581", "size": 3813, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fractals.hs", "max_stars_repo_name": "arekfu/fractals-haskell", "max_stars_repo_head_hexsha": "7e71fafa64738e7382f459adea79d9fb1f54a3f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Fractals.hs", "max_issues_repo_name": "arekfu/fractals-haskell", "max_issues_repo_head_hexsha": "7e71fafa64738e7382f459adea79d9fb1f54a3f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fractals.hs", "max_forks_repo_name": "arekfu/fractals-haskell", "max_forks_repo_head_hexsha": "7e71fafa64738e7382f459adea79d9fb1f54a3f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5638297872, "max_line_length": 106, "alphanum_fraction": 0.5609756098, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6675785626267298}} {"text": "{-# LANGUAGE NoMonomorphismRestriction, ScopedTypeVariables, FlexibleContexts, TypeFamilies #-}\n\nmodule Math.Probably.PCA where\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra.HMatrix ((#>))\nimport Math.Probably.FoldingStats\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as VS\nimport Foreign.Storable.Tuple ()\nimport Control.Spoon\nimport qualified Data.Map.Strict as M\nimport Data.Maybe (fromJust)\nimport Data.List\nimport Data.Ord\nimport Data.Number.Erf\nimport Debug.Trace\n\n\nempiricalCovariance :: [Vector Double] -> Matrix Double\nempiricalCovariance xs\n = let k = length xs\n --barxk = L.scale (recip $ realToFrac $ k+1) $ sum xs\n --m1 = sum $ map (\\xv-> L.outer xv xv) xs\n --m2 = L.scale (realToFrac $ k+1) $ L.outer barxk barxk\n xmn = empiricalMean xs\n f xi = outerSame $ xi - xmn\n-- in L.scale (recip $ realToFrac k) $ m1 - m2\n in scale (recip $ realToFrac k - 1 ) $ sum $ map f xs\n\nempiricalCovariance' :: Vector Double -> [Vector Double] -> Matrix Double\nempiricalCovariance' xmn xs\n = let k = length xs\n --barxk = L.scale (recip $ realToFrac $ k+1) $ sum xs\n --m1 = sum $ map (\\xv-> L.outer xv xv) xs\n --m2 = L.scale (realToFrac $ k+1) $ L.outer barxk barxk\n f xi = outerSame $ xi - xmn\n-- in L.scale (recip $ realToFrac k) $ m1 - m2\n in scale (recip $ realToFrac k - 1 ) $ sumWith f xs\n\n\nouterSame v = outer v v\n\n--sumWithVs :: (Vector Double -> Vector Double) -> [Vector Double] -> Vector Double\n--sumWithVs f = foldl1' (\\acc v -> acc + f v)\n\nsumWith :: Num a => (Vector Double -> a) -> [Vector Double] -> a\nsumWith f (v:vs) = foldl' (\\acc v -> acc + f v) (f v) vs\n\nempiricalMean :: [Vector Double] -> Vector Double\nempiricalMean vecs = scale (recip $ realToFrac $ length vecs) $ sumWith id vecs\n\n-- copied from https://github.com/albertoruiz/hmatrix/blob/master/examples/pca2.hs\n\ntype Vec = Vector Double\ntype Mat = Matrix Double\n\n-- Vector with the mean value of the columns of a matrix\nmean :: Mat -> Vec\nmean a = constant (recip . fromIntegral . rows $ a) (rows a) <> a\n\n-- covariance matrix of a list of observations stored as rows\ncov :: Mat -> Mat\ncov x = (trans xc <> xc) / fromIntegral (rows x - 1)\n where xc = x - asRow (mean x)\n\ncovN :: Mat -> Mat\ncovN x = (trans x <> x) / fromIntegral (rows x)\n\ncov0 :: Mat -> Mat\ncov0 x = (trans x <> x) / fromIntegral (rows x - 1)\n --where xc = x - asRow (mean x)\n\n\ntype Stat = (Vec, [Double], Mat)\n-- 1st and 2nd order statistics of a dataset (mean, eigenvalues and eigenvectors of cov)\nstat :: Mat -> Stat\nstat x = (m, toList s, trans v) where\n m = mean x\n (s,v) = eigSH' (cov x)\n\nstat0 :: Mat -> Stat\nstat0 x = (m, toList s, trans v) where\n m = VS.map (const 0) s\n c = cov0 x\n (s,v) = eigSH' $ trace (\"cov00=\"++(show (c!0!0))) $ c\n\nstatSVD :: Mat -> Stat\nstatSVD x = (m, [], evecs) where\n m = mean x\n c = cov x\n (_, evals, evecCols) = svd c\n evecs = fromRows $ map evecSigns $ toColumns evecCols\n evecSigns ev = let maxelidx = maxIndex $ cmap abs ev\n sign = signum (ev ! maxelidx)\n in cmap (sign *) ev\n\nstatThinSVD :: Mat -> Stat\nstatThinSVD x = (m, [], evecs) where\n m = mean x\n c = cov x\n (_, evals, evecCols) = thinSVD c\n evecs = fromRows $ map evecSigns $ toColumns evecCols\n evecSigns ev = let maxelidx = maxIndex $ cmap abs ev\n sign = signum (ev ! maxelidx)\n in cmap (sign *) ev\n\npcaNSVD :: Int -> Stat -> (Vec -> Vec , Vec -> Vec)\npcaNSVD n (m,_,evecs) = (encode,decode)\n where\n encode x = VS.take n $ evecs #> (x - m)\n decode x = error \"not sure right now\"\n\nstatVs :: [Vector Double] -> Stat\nstatVs vs = (m, toList s, trans v) where\n m = empiricalMean vs\n (s,v) = eigSH' (empiricalCovariance' m vs)\n\nmbStat :: Mat -> Maybe Stat\nmbStat = spoon . stat\n\npca :: Double -> Stat -> (Vec -> Vec , Vec -> Vec)\npca prec (m,s,v) = (encode,decode)\n where\n encode x = vp <> (x - m)\n decode x = x <> vp + m\n vp = takeRows n v\n n = 1 + (length $ fst $ span (< (prec'*sum s)) $ cumSum s)\n cumSum = tail . scanl (+) 0.0\n prec' = if prec <=0.0 || prec >= 1.0\n then error \"the precision in pca must be 0 Stat -> (Vec -> Vec , Vec -> Vec)\npcaN n (m,s,v) = (encode,decode)\n where\n encode x = vp <> (x - m)\n decode x = x <> vp + m\n vp = takeRows n v\n\ntype Lens a b = ( (a->b), (a-> b -> a) )\n\nget :: Lens a b -> a -> b\nget (f,_) x = f x\n\nset :: Lens a b -> a -> b -> a\nset (_,f) x y = f x y\n\nidlens :: Lens a a\nidlens = (id, (\\_ x -> x))\n\n--, pcaFeatures\nnormaliseBy :: (Eq b, Ord b) => Lens a Vec -> Lens a b -> Int -> [a] -> [a]\nnormaliseBy veclens idlens ncomponents = equaliseVars veclens\n . rankTransform veclens idlens\n . pcaFeatures veclens ncomponents\n . equaliseVars veclens\n\nnormaliseNoRank :: Lens a Vec -> Int -> [a] -> [a]\nnormaliseNoRank veclens ncomponents = equaliseVars veclens\n . pcaFeatures veclens ncomponents\n . equaliseVars veclens\n\n\nequaliseVars ::Lens a Vec -> [a] -> [a]\nequaliseVars veclens xs = equal_vars where\n decorr_vars :: VS.Vector (Double,Double)\n decorr_vars = uncurry (VS.zipWith (,)) $ runStat meanSDF $ map (get veclens) xs\n\n equal_vars = map (\\x -> set veclens x (g $ get veclens x)) xs\n\n g :: Vec -> Vec\n g fl = VS.zipWith (\\x (mn,sd) -> (x-mn)/sd) fl decorr_vars\n\nvecMeanSds :: [Vector Double] -> Vector (Double, Double)\nvecMeanSds xs = uncurry (VS.zipWith (,)) $ runStat meanSDF xs\n\nvecMeans :: [Vector Double] -> Vector Double\nvecMeans xs = scale (recip $ realToFrac $ length xs) $ sumWith id xs\n\n\n\nrankTransform :: (Eq b, Ord b) => Lens a Vec -> Lens a b -> [a] -> [a]\nrankTransform veclens idlens nmfeatures = rankTransformed where\n nfeatures = VS.length $ get veclens $ head $ nmfeatures\n nposters = realToFrac $ length nmfeatures\n sortations = flip map [0..(nfeatures-1)] $ \\ix -> toRankMap $ map (get idlens) $ sortBy (comparing ((VS.! ix) . get veclens)) nmfeatures -- decorrelated\n rankTransformed = flip map nmfeatures $ \\x ->\n let nm = get idlens x\n f sortation = invnormcdf $ realToFrac ((getRank sortation nm)+1) / (nposters+1)\n newv = VS.fromList $ map f sortations\n in set veclens x newv\n\npcaFeatures :: Lens a Vec -> Int -> [a] -> [a]\npcaFeatures veclens ncomp nmfeatures = pca'd where\n input_data = map (get veclens ) nmfeatures\n pcaStats@(_,eigVals,_) = stat $ fromRows input_data\n (enc,_) = trace (\"eigenVals =\"++show eigVals ) $ pcaN ncomp pcaStats\n-- pca_red = PCA.pcaReduceN input_data 5\n setFeatures x =\n let oldv = get veclens x\n newNormV = enc oldv\n in set veclens x newNormV\n pca'd = map setFeatures nmfeatures\n\ntype RankMap a = M.Map a Int\n\ntoRankMap :: (Ord a, Eq a) => [a] -> RankMap a\ntoRankMap = M.fromList . (`zip` [0..])\n\ngetRank :: (Ord a, Eq a) => RankMap a -> a -> Int\ngetRank m x = fromJust $ M.lookup x m\n\n\nnewtype NumUV a = NumUV { unNumUV :: U.Vector a } deriving (Eq, Ord)\n\nnumUmap f = NumUV . U.map f . unNumUV\nnumUlength = U.length . unNumUV\n\ninstance (U.Unbox a, Num a) => Num (NumUV a) where\n (+) = binvop (+)\n (-) = binvop (-)\n (*) = binvop (*)\n abs = numUmap abs\n signum = numUmap signum\n fromInteger x = NumUV $ U.fromList [fromInteger x]\n\ninstance (U.Unbox a, Fractional a) => Fractional (NumUV a) where\n (/) = binvop (/)\n fromRational x = NumUV $ U.fromList [fromRational x]\ninstance (U.Unbox a, Floating a) => Floating (NumUV a) where\n pi = NumUV $ U.fromList [pi]\n sqrt = numUmap sqrt\n log = numUmap log\n exp = numUmap exp\n sin = numUmap sin\n cos = numUmap cos\n tan = numUmap tan\n asin = numUmap asin\n acos = numUmap acos\n atan = numUmap atan\n sinh = numUmap sinh\n cosh = numUmap cosh\n tanh = numUmap tanh\n asinh = numUmap asinh\n acosh = numUmap acosh\n atanh = numUmap atanh\n\nbinvop f xs ys\n | numUlength ys == 1 = let y = (unNumUV ys) U.! 0 in numUmap (\\x-> f x y) xs\n | numUlength xs == 1 = let x = (unNumUV xs) U.! 0 in numUmap (\\y-> f x y) ys\n | otherwise = NumUV $ U.zipWith f (unNumUV xs) (unNumUV ys)\n", "meta": {"hexsha": "a126b322947cb12517aea01ba06db9e3c96d79ed", "size": 8503, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Probably/PCA.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/PCA.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/PCA.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": 33.4763779528, "max_line_length": 154, "alphanum_fraction": 0.5988474656, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6673744909760662}} {"text": "module Rotation where\n\nimport Control.Monad\nimport Numeric.LinearAlgebra ((<>), (#>), Z, Vector, Matrix)\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Data.List as List\nimport qualified Data.Maybe as Maybe\n\nimport Cube (Cube, cubeToVector, vectorToCube)\nimport qualified Cube as Cube\n\ntype CubeRotation = Cube -> Cube\n\ntoCubeRotation :: VectorRotation -> CubeRotation\ntoCubeRotation rotation = vectorToCube . rotation . cubeToVector\n\ntype VectorRotation = Vector Z -> Vector Z\n\ntoVectorRotation :: MatrixRotation -> VectorRotation\ntoVectorRotation = (#>)\n\nrotate :: MatrixRotation -> Cube -> Cube\nrotate rotation = toCubeRotation $ toVectorRotation rotation\n\ntype MatrixRotation = Matrix Z\n\nshowMatrixRotation :: MatrixRotation -> String\nshowMatrixRotation = show . fmap (go 0 . LA.toList) . LA.toColumns\n where\n go i [] = i\n go i (v:vs)\n | v == 1 = i\n | otherwise = go (i + 1) vs\n\nidentity :: MatrixRotation\nidentity = LA.ident $ 9 * 6\n\ntopToFront :: MatrixRotation\ntopToFront =\n let vs = LA.toColumns identity\n mapping = [ 9, 10, 11, 12, 13, 14, 15, 16, 17\n , 45, 46, 47, 48, 49, 50, 51, 52, 53\n , 24, 21, 18, 25, 22, 19, 26, 23, 20\n , 8, 7, 6, 5, 4, 3, 2, 1, 0\n , 38, 41, 44, 37, 40, 43, 36, 39, 42\n , 35, 34, 33, 32, 31, 30, 29, 28, 27 ]\n in LA.fromColumns $ fmap (vs !!) mapping\n\ntopToBack :: MatrixRotation\ntopToBack = topToFront <> topToFront <> topToFront\n\ntopToRight :: MatrixRotation\ntopToRight =\n let vs = LA.toColumns identity\n mapping = [ 20, 23, 26, 19, 22, 25, 18, 21, 24\n , 11, 14, 17, 10, 13, 16, 9, 12, 15\n , 47, 50, 53, 46, 49, 52, 45, 48, 51\n , 33, 30, 27, 34, 31, 28, 35, 32, 29\n , 2, 5, 8, 1, 4, 7, 0, 3, 6\n , 38, 41, 44, 37, 40, 43, 36, 39, 42 ]\n in LA.fromColumns $ fmap (vs !!) mapping\n\ntopToLeft :: MatrixRotation\ntopToLeft = topToRight <> topToRight <> topToRight\n\ntopTwistRight :: MatrixRotation\ntopTwistRight = topToBack <> topToRight <> topToFront\n\ntopTwistLeft :: MatrixRotation\ntopTwistLeft = topTwistRight <> topTwistRight <> topTwistRight\n\nrightL :: MatrixRotation\nrightL =\n let vs = LA.toColumns identity\n mapping = [ 0, 1, 11, 3, 4, 14, 6, 7, 17\n , 9, 10, 47, 12, 13, 50, 15, 16, 53\n , 24, 21, 18, 25, 22, 19, 26, 23, 20\n , 8, 28, 29, 5, 31, 32, 2, 34, 35\n , 36, 37, 38, 39, 40, 41, 42, 43, 44\n , 45, 46, 33, 48, 49, 30, 51, 52, 27 ]\n in LA.fromColumns $ fmap (vs !!) mapping\n\nrightR :: MatrixRotation\nrightR = rightL <> rightL <> rightL\n\nleftL :: MatrixRotation\nleftL =\n let twist = topTwistRight <> topTwistRight\n in twist <> rightL <> twist\n\nleftR :: MatrixRotation\nleftR = leftL <> leftL <> leftL\n\ntopL :: MatrixRotation\ntopL = topToLeft <> rightL <> topToRight\n\ntopR :: MatrixRotation\ntopR = topL <> topL <> topL\n\nbottomL :: MatrixRotation\nbottomL =\n let twist = topToRight <> topToRight\n in twist <> topL <> twist\n\nbottomR :: MatrixRotation\nbottomR = bottomL <> bottomL <> bottomL\n\nfrontL :: MatrixRotation\nfrontL = topTwistRight <> rightL <> topTwistLeft\n\nfrontR :: MatrixRotation\nfrontR = frontL <> frontL <> frontL\n\nbackL :: MatrixRotation\nbackL =\n let twist = topTwistLeft <> topTwistLeft\n in twist <> frontL <> twist\n\nbackR :: MatrixRotation\nbackR = backL <> backL <> backL\n\nrotations :: [(MatrixRotation, String)]\nrotations = [\n (identity, \"identity\")\n , (topToFront, \"topToFront\")\n , (topToBack, \"topToBack\")\n , (topToRight, \"topToRight\")\n , (topToLeft, \"topToLeft\")\n , (topTwistRight, \"topTwistRight\")\n , (topTwistLeft, \"topTwistLeft\")\n , (rightL, \"rightL\")\n , (rightR, \"rightR\")\n , (leftL, \"leftL\")\n , (leftR, \"leftR\")\n , (topL, \"topL\")\n , (topR, \"topR\")\n , (bottomL, \"bottomL\")\n , (bottomR, \"bottomR\")\n , (frontL, \"frontL\")\n , (frontR, \"frontR\")\n , (backL, \"backL\")\n , (backR, \"backR\")\n ]\n\nnameMatrixRotation :: MatrixRotation -> String\nnameMatrixRotation = Maybe.fromMaybe \"unknown\" . flip List.lookup rotations\n\ninverse :: MatrixRotation -> Maybe MatrixRotation\ninverse r = Maybe.listToMaybe $ do\n r' <- map fst rotations\n guard $ r <> r' == identity\n return r'\n", "meta": {"hexsha": "d4d3e28cb44a141dec86184120ef6febeef3ac1a", "size": 4256, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Rotation.hs", "max_stars_repo_name": "runjak/hRubiks", "max_stars_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rotation.hs", "max_issues_repo_name": "runjak/hRubiks", "max_issues_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rotation.hs", "max_forks_repo_name": "runjak/hRubiks", "max_forks_repo_head_hexsha": "28798a2a07871c81843490ed95eb5377921c1be5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8169934641, "max_line_length": 75, "alphanum_fraction": 0.6195958647, "num_tokens": 1509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6670442984838845}} {"text": "module Main where\n\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified MachineLearning.Types as T\nimport qualified MachineLearning as ML\nimport qualified MachineLearning.Classification.Binary as CB\nimport qualified MachineLearning.Classification.OneVsAll as OVA\nimport qualified MachineLearning.TerminalProgress as TP\n\nprocessFeatures :: T.Matrix -> T.Matrix\nprocessFeatures = ML.addBiasDimension . (ML.mapFeatures 2)\n\ncalcAccuracy :: T.Matrix -> T.Vector -> [T.Vector] -> Double\ncalcAccuracy x y thetas = OVA.calcAccuracy y yPredicted\n where yPredicted = OVA.predict x thetas\n\nmain = do\n putStrLn \"\\n=== Optical Recognition of Handwritten Digits Data Set ===\\n\"\n -- Step 1. Data loading.\n -- Step 1.1 Training Data loading.\n (x, y) <- pure ML.splitToXY <*> LA.loadMatrix \"digits_classification/optdigits.tra\"\n -- Step 1.1 Testing Data loading.\n (xTest, yTest) <- pure ML.splitToXY <*> LA.loadMatrix \"digits_classification/optdigits.tes\"\n\n -- Step 2. Outputs and features preprocessing.\n let numLabels = 10\n x1 = processFeatures x\n initialTheta = LA.konst 0 (LA.cols x1)\n initialThetas = replicate numLabels initialTheta\n -- Step 3. Learning.\n (thetas, optPath) <- TP.learnOneVsAllWithProgressBar (CB.learn (OVA.BFGS2 0.01 0.1) 0.001 30 (CB.L2 30) x1) y initialThetas 1\n\n -- Step 4. Prediction and checking accuracy\n let accuracyTrain = calcAccuracy x1 y thetas\n accuracyTest = calcAccuracy (processFeatures xTest) yTest thetas\n\n -- Step 5. Printing results.\n putStrLn $ \"\\nNumber of iterations to learn: \" ++ show (map LA.rows optPath)\n\n putStrLn $ \"Accuracy on train set (%): \" ++ show (accuracyTrain*100)\n putStrLn $ \"Accuracy on test set (%): \" ++ show (accuracyTest*100)\n", "meta": {"hexsha": "cba8738b666693d74cdfdf44f5bd6d34b60e95a7", "size": 1723, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/digits_classification/Main.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "examples/digits_classification/Main.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "examples/digits_classification/Main.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 41.0238095238, "max_line_length": 127, "alphanum_fraction": 0.7376668601, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6669080300457718}} {"text": "\nmodule Trade.Statistics.Algorithm where\n\nimport Data.Time.Clock (NominalDiffTime)\n\nimport qualified Data.Vector as Vec\nimport Data.Vector (Vector)\n\nimport qualified Statistics.Sample as Stat\n\nimport Trade.Type.Equity (Equity(..))\nimport Trade.Type.Percent (Percent(..))\nimport Trade.Type.Price (Price(..))\n\n\nclass Statistics a where\n mean :: Vector a -> a\n stdDev :: Vector a -> a\n skewness :: Vector a -> Double\n kurtosis :: Vector a -> Double\n volatility :: Vector a -> Percent\n\n \ninstance Statistics Double where\n mean = Stat.mean\n stdDev = Stat.stdDev\n skewness = Stat.skewness\n kurtosis = Stat.kurtosis\n\n volatility xs =\n let as = Vec.zipWith (\\a b -> log (a/b)) (Vec.tail xs) xs\n s = sqrt (fromIntegral (Vec.length as))\n in Percent (Stat.stdDev as * s)\n\n\n\ninstance Statistics Price where\n mean = Price . Stat.mean . Vec.map unPrice\n stdDev = Price . Stat.stdDev . Vec.map unPrice\n skewness = Stat.skewness . Vec.map unPrice\n kurtosis = Stat.kurtosis . Vec.map unPrice\n volatility = volatility . Vec.map unPrice\n\ninstance Statistics Equity where\n mean = Equity . Stat.mean . Vec.map unEquity\n stdDev = Equity . Stat.stdDev . Vec.map unEquity\n skewness = Stat.skewness . Vec.map unEquity\n kurtosis = Stat.kurtosis . Vec.map unEquity\n volatility = volatility . Vec.map unEquity\n\ninstance Statistics NominalDiffTime where\n mean = realToFrac . Stat.mean . Vec.map realToFrac\n stdDev = realToFrac . Stat.stdDev . Vec.map realToFrac\n skewness = Stat.skewness . Vec.map realToFrac\n kurtosis = Stat.kurtosis . Vec.map realToFrac\n volatility = volatility . Vec.map (realToFrac :: NominalDiffTime -> Double)\n", "meta": {"hexsha": "253b95b4576653ba1a4177845d330605ef0c877c", "size": 1643, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Trade/Statistics/Algorithm.hs", "max_stars_repo_name": "fphh/trade", "max_stars_repo_head_hexsha": "4957fe6c5a709f6f7df01dc56c77a015fb69b298", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-09T10:41:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-09T10:41:11.000Z", "max_issues_repo_path": "src/Trade/Statistics/Algorithm.hs", "max_issues_repo_name": "fphh/trade", "max_issues_repo_head_hexsha": "4957fe6c5a709f6f7df01dc56c77a015fb69b298", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Trade/Statistics/Algorithm.hs", "max_forks_repo_name": "fphh/trade", "max_forks_repo_head_hexsha": "4957fe6c5a709f6f7df01dc56c77a015fb69b298", "max_forks_repo_licenses": ["BSD-3-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.8245614035, "max_line_length": 77, "alphanum_fraction": 0.7188070603, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6665329748514357}} {"text": "import Data.Complex\nimport Data.Maybe\nimport Data.Word\nimport qualified Data.Array.Repa as R\nimport Data.Array.Repa hiding (map,zip,foldr)\n\nf :: Complex Double -> Complex Double -> Complex Double\nf c z = z*z + c\n\nisMandelbrot :: Int -> Complex Double -> Int\nisMandelbrot n c = case (n' < n) of\n True -> n'\n False -> (-1)\n where\n m = iterate (f c) 0\n n' = length. take n . takeWhile (\\z -> magnitude z <2) $ m\n\n\narray :: Double -> Complex Double -> Int -> Array D DIM2 (Complex Double)\narray size centre n = R.fromFunction (Z:.n:.n) posToVal\n where\n dx = size / (fromIntegral n)\n posToVal (Z:.i:.j) = (((fromIntegral i)*dx - size/2) :+ ((fromIntegral j)*dx - size/2)) + centre \n\ngenMandelbrot :: Int -> Int -> Double -> Complex Double -> Array D DIM2 (Word8,Word8,Word8)\ngenMandelbrot res n size centre = cs\n where\n zs = array size centre res\n cs = R.map (toColor . isMandelbrot n) zs\n\ntoColor :: Int -> (Word8,Word8,Word8)\ntoColor n = case (n<0) of\n True = (0,0,0)\n False = (255 - (fromIntegral n),fromIntegral n,50)\n\nmain :: IO ()\nmain = do\n [i',j',size',res',n',filename] <- getArgs\n let res = read res' :: Int\n n = read n' :: Int\n size = read size' :: Double\n i = read i' :: Double\n j = read j' :: Double\n centre = i :+ j\n cs' = genMandelbrot res n size centre\n cs <- computeP cs' :: IO (Array U DIM2 (Word8,Word8,Word8))\n writeImageToBMP filename cs\n", "meta": {"hexsha": "98d2ca002a99fdc47e445253a82bdf030c27f02d", "size": 1527, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MWE.hs", "max_stars_repo_name": "ahgibbons/HaskMandelbrot", "max_stars_repo_head_hexsha": "339a34a6e513ac26b0b9ad1364437dddc19d3e5e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/MWE.hs", "max_issues_repo_name": "ahgibbons/HaskMandelbrot", "max_issues_repo_head_hexsha": "339a34a6e513ac26b0b9ad1364437dddc19d3e5e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MWE.hs", "max_forks_repo_name": "ahgibbons/HaskMandelbrot", "max_forks_repo_head_hexsha": "339a34a6e513ac26b0b9ad1364437dddc19d3e5e", "max_forks_repo_licenses": ["BSD-3-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.8125, "max_line_length": 102, "alphanum_fraction": 0.574983628, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6660756242157393}} {"text": "-- | Planning by Dynamic Programming (Matrix Version)\n\nmodule PlanningM where\n\nimport Data.Map (Map)\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Numeric.LinearAlgebra.Data (Matrix, Vector, (!))\nimport Numeric.LinearAlgebra.HMatrix as H\n\nimport MDP\nimport Planning\n\ndata MDPM s a = MDPM\n { statesm :: Map s Int\n , actionsm :: Map a Int\n , transitionm :: Matrix Double -- matrix S x S\n , rewardm :: Vector Double -- vector 1 x S\n , gammam :: Double -- discount\n , sizeStates :: Int -- S\n , sizeActions :: Int -- A\n }\n\ntype PolicyM = Matrix Double\n\n\npolicyEvaluationM :: (Ord s, Ord a) => MDP s a -> ValueFunction s a\npolicyEvaluationM mdp policy k s =\n matrixPolicyEvaluation mdpm k ! (M.!) (statesm mdpm) s\n where\n mdpm = prepareMDP mdp (preparePolicy mdp policy)\n\n\npreparePolicy :: MDP s a -> Policy s a -> PolicyM\npreparePolicy mdp policy = H.fromLists (\n map (\n \\s -> map (policy s) (S.toList (actions mdp)))\n (S.toList (states mdp)))\n\n\nprepareMDP :: (Ord s, Ord a) => MDP s a -> PolicyM -> MDPM s a\nprepareMDP mdp policy =\n MDPM\n { statesm = statesM\n , actionsm = actionsM\n , transitionm = transitionM\n , rewardm = rewardM\n , gammam = gamma mdp\n , sizeStates = S.size (states mdp)\n , sizeActions = S.size (actions mdp)\n }\n where\n statesM = M.fromList (zip (S.toList (states mdp)) [0 ..])\n actionsM = M.fromList (zip (S.toList (actions mdp)) [0 ..])\n transitionM =\n H.fromRows\n (map\n (\\s ->\n takeDiag (policy H.<> (transitionMap M.! s)))\n (S.toList (states mdp)))\n transitionMap =\n M.fromList\n (map\n (\\s ->\n (s, createMatrix s))\n (S.toList (states mdp)))\n createMatrix s' =\n H.fromLists\n (map\n (\\a ->\n map\n (\\s ->\n transition mdp a s s')\n (S.toList (states mdp)))\n (S.toList (actions mdp)))\n rewardM = takeDiag (policy H.<> createRewardMatrix)\n createRewardMatrix =\n H.fromLists\n (map\n (\\a ->\n map\n (\n reward mdp a)\n (S.toList (states mdp)))\n (S.toList (actions mdp)))\n\n\nmatrixPolicyEvaluation :: MDPM s a -> Int -> Vector Double\nmatrixPolicyEvaluation mdpm = evalVF (konst 0.0 (sizeStates mdpm))\n where\n evalVF v 0 = v\n evalVF v k =\n evalVF\n (rewardm mdpm + gammam mdpm `scale` (transitionm mdpm H.#> v))\n (k - 1)\n\n\nmatrixPolicyImprove :: MDPM s a -> Vector Double -> Matrix Double\nmatrixPolicyImprove mdpm vf = undefined\n", "meta": {"hexsha": "f034fbdfc7fc89acef773f36506a659b4268ceb1", "size": 2995, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PlanningM.hs", "max_stars_repo_name": "DbIHbKA/hmdp", "max_stars_repo_head_hexsha": "515acbda34e9b43b6ae9a2d10d854fd9070c14ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-02T01:17:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-02T01:17:49.000Z", "max_issues_repo_path": "src/PlanningM.hs", "max_issues_repo_name": "DbIHbKA/hmdp", "max_issues_repo_head_hexsha": "515acbda34e9b43b6ae9a2d10d854fd9070c14ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PlanningM.hs", "max_forks_repo_name": "DbIHbKA/hmdp", "max_forks_repo_head_hexsha": "515acbda34e9b43b6ae9a2d10d854fd9070c14ee", "max_forks_repo_licenses": ["BSD-3-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.95, "max_line_length": 74, "alphanum_fraction": 0.5061769616, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6660756223758315}} {"text": "\nmodule Measurable.Measures where\n\nimport Measurable.Core\nimport Numeric.SpecFunctions (choose)\nimport Statistics.Distribution\nimport qualified Statistics.Distribution.Beta as Statistics\nimport qualified Statistics.Distribution.Binomial as Statistics\nimport qualified Statistics.Distribution.ChiSquared as Statistics\nimport qualified Statistics.Distribution.Gamma as Statistics\nimport qualified Statistics.Distribution.Exponential as Statistics\nimport qualified Statistics.Distribution.Normal as Statistics\n\nstandard :: Measure Double\nstandard = fromDensityFunction pdf where\n pdf = density Statistics.standard\n\nnormal :: Double -> Double -> Measure Double\nnormal m s = fromDensityFunction pdf where\n pdf = density $ Statistics.normalDistr m s\n\nlogNormal :: Double -> Double -> Measure Double\nlogNormal m s = fmap exp (normal m s)\n\nexponential :: Double -> Measure Double\nexponential r = fromDensityFunction pdf where\n pdf = density $ Statistics.exponential r\n\ngamma :: Double -> Double -> Measure Double\ngamma a b = fromDensityFunction pdf where\n pdf = density $ Statistics.gammaDistr a b\n\ninverseGamma :: Double -> Double -> Measure Double\ninverseGamma a b = fmap recip (gamma a b)\n\nchiSquare :: Int -> Measure Double\nchiSquare k = fromDensityFunction pdf where\n pdf = density $ Statistics.chiSquared k\n\nbeta :: Double -> Double -> Measure Double\nbeta a b = fromDensityFunction pdf where\n pdf = density $ Statistics.betaDistr a b\n\nbinomial :: Int -> Double -> Measure Int\nbinomial n p = fromMassFunction pmf [0..n] where\n pmf = binomialMass n p\n\nbernoulli :: Double -> Measure Int\nbernoulli = binomial 1\n\nbinomialMass :: Int -> Double -> Int -> Double\nbinomialMass n p k = bc * p ^ k * (1 - p) ^ (n - k) where\n bc = n `choose` k\n\n", "meta": {"hexsha": "8060d26e8bc13993fad07f982a3d431c410d57d9", "size": 1740, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Measurable/Measures.hs", "max_stars_repo_name": "jtobin/measurable", "max_stars_repo_head_hexsha": "ac09f996fac0ca05eedc67f41664f9f5db68891f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2015-09-22T10:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-15T06:45:04.000Z", "max_issues_repo_path": "src/Measurable/Measures.hs", "max_issues_repo_name": "jtobin/measurable", "max_issues_repo_head_hexsha": "ac09f996fac0ca05eedc67f41664f9f5db68891f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Measurable/Measures.hs", "max_forks_repo_name": "jtobin/measurable", "max_forks_repo_head_hexsha": "ac09f996fac0ca05eedc67f41664f9f5db68891f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-09-22T10:58:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T05:02:08.000Z", "avg_line_length": 31.6363636364, "max_line_length": 66, "alphanum_fraction": 0.7649425287, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480668, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6660756150161994}} {"text": "-- perceptron simulation code \n-- created by Tomohiro KIDA 2018/05/08/Tue \n\nmodule Main \n ( main\n , linearFunc\n , linearFunc'\n , lossFunc\n , gradientDescent \n , plotDataPng\n , simPerceptron\n ) where\n\nimport Graphics.Gnuplot.Simple\nimport System.Random \nimport Numeric.LinearAlgebra \n\nxxs :: [[Double]]\nxxs = [[1,4,6],[1,1,4],[1,3,2],[1,7,3]]\nts :: [Int]\nts = [-1,-1,1,1]\na :: (Fractional frac) => frac\na = 0.1\n\n-- f (x) = w (tr x)\nlinearFunc :: Matrix R -> Matrix R -> Double\nlinearFunc w x \n | fst (size w) == 1 && fst (size x) == 1 = head . head . toLists $ w <> (tr x)\n | otherwise = -1 -- error\n\n-- linear function for plot \n-- the left hand side is x2\nlinearFunc' :: Matrix R -> Double -> Double\nlinearFunc' ws x = \n let w = (toLists ws)!!0\n in (-x)*(w!!1)/(w!!2) - ((w!!0)/(w!!2))\n\nlossFunc :: Double -> Double -> Double\nlossFunc t f = max 0.0 (-t*f)\n\n\n-- return one itaration of gradientDescent\ngradientDescent :: Int -> Matrix R -> Matrix R\ngradientDescent rn ws =\n let ti = realToFrac $ ts !! rn\n xi = fromLists [xxs!!rn] :: Matrix R\n li = lossFunc ti $ linearFunc ws xi\n wsn = if li > 0 then ws - ( a*(realToFrac (-ti))*xi ) else ws\n in wsn\n\n-- plot data and png\nplotDataPng :: Matrix R -> IO ()\nplotDataPng ws = do \n plotPathsStyle atribute plotstyle\n where \n lines = map (\\x->(x,(linearFunc' ws x))) [0..10]\n points_t = map ((\\[x,y]->(x,y)).tail) $ (\\xs->[(xs!!0),(xs!!1)]) xxs\n points_f = map ((\\[x,y]->(x,y)).tail) $ (\\xs->[(xs!!2),(xs!!3)]) xxs\n label = [(XLabel \"x\"), (YLabel \"y\")]\n range = [(XRange (0,8)), (YRange (0,8))]\n size = [Aspect (Ratio 0.7)]\n title = [(Title \"simPerceptron\")]\n png = [(PNG \"simPerceptron.png\")]\n atribute = (label++range++title++png)\n plotstyle = [(defaultStyle {plotType = Points }, points_t),\n (defaultStyle {plotType = Points }, points_f),\n (defaultStyle {plotType = Lines }, lines )]\n\n\n-- simulation perceptron by grandient descent \nsimPerceptron :: StdGen -> Matrix R -> Int -> IO () \nsimPerceptron gen ws count = do\n let (rn,ng) = randomR (0,3) gen :: (Int, StdGen) -- get one rand data of 4\n let wsn = gradientDescent rn ws -- update ws\n putStrLn $ show count ++ show wsn\n if (count > 0) \n then simPerceptron ng wsn (count-1) -- return recursion\n else plotDataPng wsn -- plot\n\nmain :: IO ()\nmain = do\n gen <- getStdGen\n let ws = (1><3) [-1,2,3] :: Matrix R\n simPerceptron gen ws 100 -- gradientDescent simulation\n", "meta": {"hexsha": "0b039295814a468c4427156acc1fc6e406d863bf", "size": 2671, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "TomohiroKida/perceptron", "max_stars_repo_head_hexsha": "f48f5f55ffbb35fb3b8f7fde13f2f61bfb5d5320", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-08T09:54:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T09:54:42.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "TomohiroKida/perceptron", "max_issues_repo_head_hexsha": "f48f5f55ffbb35fb3b8f7fde13f2f61bfb5d5320", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "TomohiroKida/perceptron", "max_forks_repo_head_hexsha": "f48f5f55ffbb35fb3b8f7fde13f2f61bfb5d5320", "max_forks_repo_licenses": ["BSD-3-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.4235294118, "max_line_length": 82, "alphanum_fraction": 0.5526020217, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6657790406851749}} {"text": "module Section_3_4_3 where\n\nimport Numeric.LinearAlgebra\n\ntype Network = [(Matrix Double, Vector Double, Double -> Double)]\n\nsigmoid :: Double -> Double\nsigmoid x = 1 / (1 + exp (-x))\n\ninitNetwork :: Network\ninitNetwork =\n [ ( (2><3) [0.1, 0.3, 0.5, 0.2, 0.4, 0.6]\n , vector [0.1, 0.2, 0.3]\n , sigmoid\n )\n , ( (3><2) [0.1, 0.4, 0.2, 0.5, 0.3, 0.6]\n , vector [0.1, 0.2]\n , sigmoid\n )\n , ( (2><2) [0.1, 0.3, 0.2, 0.4]\n , vector [0.1, 0.2]\n , id\n )\n ]\n\nforward :: Network -> Vector Double -> Vector Double\nforward nw x = foldl (\\x (w, b, h) -> cmap h (x <# w + b)) x nw\n", "meta": {"hexsha": "8616b21fe299e2c83d1a47373bad00e4c71ec58d", "size": 598, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Section_3_4_3.hs", "max_stars_repo_name": "lotz84/deep-learning-from-scratch", "max_stars_repo_head_hexsha": "7f58f3c637da0fcbf1981af5f058af5015740383", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-16T13:39:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T19:27:32.000Z", "max_issues_repo_path": "src/Section_3_4_3.hs", "max_issues_repo_name": "lotz84/deep-learning-from-scratch", "max_issues_repo_head_hexsha": "7f58f3c637da0fcbf1981af5f058af5015740383", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Section_3_4_3.hs", "max_forks_repo_name": "lotz84/deep-learning-from-scratch", "max_forks_repo_head_hexsha": "7f58f3c637da0fcbf1981af5f058af5015740383", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3571428571, "max_line_length": 65, "alphanum_fraction": 0.5234113712, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6656366707925535}} {"text": "-- root finding examples\nimport Numeric.GSL\nimport Numeric.LinearAlgebra\nimport Text.Printf(printf)\n\nrosenbrock a b [x,y] = [ a*(1-x), b*(y-x^2) ]\n\ntest method = do\n print method\n let (s,p) = root method 1E-7 30 (rosenbrock 1 10) [-10,-5]\n print s -- solution\n disp p -- evolution of the algorithm\n\njacobian a b [x,y] = [ [-a , 0]\n , [-2*b*x, b] ]\n\ntestJ method = do\n print method\n let (s,p) = rootJ method 1E-7 30 (rosenbrock 1 10) (jacobian 1 10) [-10,-5]\n print s\n disp p\n\ndisp = putStrLn . format \" \" (printf \"%.3f\")\n\nmain = do\n test Hybrids\n test Hybrid\n test DNewton\n test Broyden\n\n mapM_ testJ [HybridsJ .. GNewton]\n", "meta": {"hexsha": "8546ff52aee9bdf2135e994ec45020ecde18caf1", "size": 686, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/root.hs", "max_stars_repo_name": "curiousleo/liquidhaskell", "max_stars_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 941, "max_stars_repo_stars_event_min_datetime": "2015-01-13T10:51:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:32:32.000Z", "max_issues_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/root.hs", "max_issues_repo_name": "curiousleo/liquidhaskell", "max_issues_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 1300, "max_issues_repo_issues_event_min_datetime": "2015-01-01T05:41:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:11:03.000Z", "max_forks_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/root.hs", "max_forks_repo_name": "curiousleo/liquidhaskell", "max_forks_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 145, "max_forks_repo_forks_event_min_datetime": "2015-01-12T08:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:29:30.000Z", "avg_line_length": 21.4375, "max_line_length": 79, "alphanum_fraction": 0.5918367347, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6654150025965392}} {"text": "-- |\n-- Module : Spiral.RootOfUnity\n-- Copyright : (c) 2016-2017 Drexel University\n-- License : BSD-style\n-- Maintainer : mainland@drexel.edu\n\nmodule Spiral.RootOfUnity (\n RootOfUnity(..)\n ) where\n\nimport Data.Complex\nimport Data.Complex.Cyclotomic\n\n-- | Types that have primitive roots of unity.\nclass Fractional a => RootOfUnity a where\n -- | @rootOfUnity n k@ computes the primitive @n@th root of unity raised to\n -- the @k@th power.\n rootOfUnity :: Int -> Int -> a\n rootOfUnity n k = omega n ^^ k\n\n -- | Computes the primitive @n@th root of unity.\n omega :: Int -> a\n omega n = rootOfUnity n 1\n\ninstance RealFloat a => RootOfUnity (Complex a) where\n -- | $e^{-2 \\pi i \\frac{k}{n}$\n rootOfUnity n k = exp (-2*pi*i/fromIntegral n)^^k\n where\n i = 0:+1\n\ninstance RootOfUnity Cyclotomic where\n -- 'Data.Complex.Cyclotomic.e' computes $e^{2 \\pi i/n}$, so we need to take\n -- the reciprocal.\n rootOfUnity n k = (1/e (fromIntegral n))^^k\n", "meta": {"hexsha": "aac7fa7095c4d2fabe1b73b1c2d6d5bac98a64d0", "size": 1002, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Spiral/RootOfUnity.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/RootOfUnity.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/RootOfUnity.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6285714286, "max_line_length": 79, "alphanum_fraction": 0.6347305389, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6649789098209584}} {"text": "-- | This module implements the Fast Fourier Transformation purely in Haskell.\r\nmodule Sound.Hommage.FFT\r\n ( \r\n -- * FFT\r\n fft\r\n , fft'\r\n , fftt \r\n\r\n -- * FFT\r\n , fftc\r\n , fftc' \r\n\r\n , ffttv \r\n\r\n , fftco \r\n , fftco'\r\n\r\n , rect_transform \r\n , rect_filter \r\n , rect_filter' \r\n\r\n , i \r\n , w \r\n , ws \r\n , map2 \r\n , zip2 \r\n , evens \r\n , odds \r\n , drop_odds \r\n , appendpair\r\n-- , fitlastlength \r\n , reorder \r\n , reorder_init \r\n , reorder_init'\r\n-- , reorder_overlap \r\n , butterfly \r\n , butterfly'\r\n , fft_level \r\n , fft_merge \r\n , fft_init_overlap \r\n , fft_level' \r\n , fft_merge' \r\n , fft_init \r\n , fft_overlap_loop \r\n , expandComplex \r\n , overlap_curve \r\n , mix_overlap \r\n\r\n )\r\n where\r\nimport Data.Complex\r\nimport Sound.Hommage.Misc\r\n-------------------------------------------------------------------------------\r\n-- | The complex value 'i' = @(0 :+ 1)@\r\ni :: Complex Double\r\ni = 0.0 :+ 1.0\r\n\r\n-- | The n-th root of 1\r\nw :: Int -> Complex Double\r\nw n = exp (-2 * i * pi / fromIntegral n)\r\n\r\n-- | the 2n-th root with exponents 0, 1, .. n. False=inverse (exponents are negated)\r\nws :: Bool -> Int -> [Complex Double]\r\nws b n = take n $ map (w1^^) ix \r\n where\r\n w1 = exp (-i * pi / fromIntegral n)\r\n ix | b = [0, 1 ..]\r\n | otherwise = [0, (-1) ..]\r\n-------------------------------------------------------------------------------\r\nmap2 :: (a -> a -> b) -> [a] -> [b]\r\nmap2 f (x:y:r) = f x y : map2 f r\r\nmap2 _ _ = []\r\n\r\nmap2opt :: (a -> a -> b) -> a -> [a] -> [b]\r\nmap2opt f a = loop \r\n where\r\n loop (x:y:r) = f x y : loop r\r\n loop [x] = [f x a]\r\n loop _ = []\r\n\r\nzip2 :: [a] -> [a] -> [a]\r\nzip2 (x:xs) (y:ys) = x : y : zip2 xs ys\r\nzip2 _ _ = []\r\n\r\nevens (x:xs) = x : odds xs\r\nevens [] = []\r\n\r\nodds (_:xs) = evens xs\r\nodds [] = []\r\n\r\n-- | returns [] if argument has zero or one element.\r\ndrop_odds (x:y:r) = x : evens r\r\ndrop_odds _ = []\r\n\r\nappendpair :: ([a], [a]) -> [a]\r\nappendpair (x,y) = x++y\r\n\r\n--fitlastlength :: Int -> a -> [[a]] -> [[a]]\r\n--fitlastlength n a = loop\r\n-- where\r\n-- loop (x:xs) = case loop xs of\r\n-- [] -> [take n (x ++ repeat a)]\r\n-- xs -> x : xs\r\n-- loop [] = []\r\n-------------------------------------------------------------------------------\r\n-- | list is grouped into sublists with length N (must be power of 2) and bitwise reverse order\r\nreorder :: Int -> [[a]] -> [[a]]\r\nreorder 0 = id\r\nreorder n = map2 zip2 . reorder (n-1)\r\n\r\nreorder_r2 :: Int -> a -> [[a]] -> [[a]]\r\nreorder_r2 n a = loop n\r\n where\r\n loop 0 = id\r\n loop n = map2opt zip2 (repeat a) . loop (n-1)\r\n\r\nreorder_init (x1:x2:x3:x4:xs) = [x1 :+ x2, x3 :+ x4] : reorder_init xs\r\nreorder_init [x1,x2,x3] = [[x1 :+ x2, x3 :+ 0]]\r\nreorder_init [x1,x2] = [[x1 :+ x2, 0]]\r\nreorder_init [x1] = [[x1 :+ 0, 0]]\r\nreorder_init _ = []\r\n\r\nreorder_init' :: [a] -> [[a]]\r\nreorder_init' (x:y:r) = [x,y] : reorder_init' r\r\nreorder_init' _ = []\r\n\r\nreorder_init_r2' :: a -> [a] -> [[a]]\r\nreorder_init_r2' a = loop\r\n where\r\n loop (x:y:r) = [x,y] : loop r\r\n loop [x] = [[x,a]]\r\n loop _ = []\r\n \r\n--reorder_overlap :: [[a]] -> [a]\r\n--reorder_overlap (xs:ys:r) = (zip2 xs ys) ++ reorder_overlap (ys:r)\r\n--reorder_overlap _ = []\r\n-------------------------------------------------------------------------------\r\nbutterfly :: Complex Double -> Complex Double -> Complex Double -> (Complex Double, Complex Double)\r\nbutterfly (wr :+ wi) (xr :+ xi) (yr :+ yi) = (a, b)\r\n where\r\n wyr = wr*yr-wi*yi \r\n wyi = wr*yi+yr*wi\r\n a = ( (xr + wyr) * 0.5 :+ (xi + wyi) * 0.5 )\r\n b = ( (xr - wyr) * 0.5 :+ (xi - wyi) * 0.5 )\r\n\r\nbutterfly' :: Complex Double -> Complex Double -> Complex Double -> (Complex Double, Complex Double)\r\nbutterfly' (wr :+ wi) (xr :+ xi) (yr :+ yi) = (a, b)\r\n where\r\n wyr = wr*yr-wi*yi \r\n wyi = wr*yi+yr*wi\r\n a = ( (xr + wyr) :+ (xi + wyi) )\r\n b = ( (xr - wyr) :+ (xi - wyi) )\r\n-------------------------------------------------------------------------------\r\n-- | FFT transformation. Input is grouped into overlapping parts of 2^(N+2) reals and mapped to sublists \r\n-- with 2^(N+1) complex numbers. \r\nfft :: Int -> [Double] -> [[Complex Double]]\r\nfft n = fft_level (ws True (2^n)) . fft_init_overlap . reorder_r2 (n-1) 0 . reorder_init\r\n\r\nfft_level :: [Complex Double] -> [[Complex Double]] -> [[Complex Double]] \r\nfft_level [_] = id\r\nfft_level ws = map2 (\\x -> appendpair . fft_merge ws x) . fft_level (drop_odds ws)\r\n\r\nfft_merge :: [Complex Double] -> [Complex Double] -> [Complex Double] -> ([Complex Double], [Complex Double])\r\nfft_merge (w:ws) (x:xs) (y:ys) = let (xs', ys') = fft_merge ws xs ys\r\n (x', y') = butterfly w x y\r\n in (x' : xs', y' : ys')\r\nfft_merge _ _ _ = ([], [])\r\n\r\nfft_init_overlap (x:y:r) = (zipWith (\\x y -> [(x + y)*0.5, (x - y)*0.5]) x y) ++ fft_init_overlap (y:r)\r\nfft_init_overlap _ = []\r\n\r\nfft_init (x:y:r) = (zipWith (\\x y -> [(x + y)*0.5, (x - y)*0.5]) x y) ++ fft_init r\r\nfft_init _ = []\r\n-------------------------------------------------------------------------------\r\n-- | Inverse FFT transformation. Complex input is grouped into parts with length 2^(N+1) and mapped to \r\n-- sublists with 2^(N+2) reals, which are overlapped and mixed.\r\nfft' :: Int -> [Complex Double] -> [Double]\r\nfft' n = mix_overlap (2^(n+2)) . map expandComplex . fft_level' (ws False (2^n)) . fft_init' . reorder (n-1) . reorder_init'\r\n\r\nfft_level' :: [Complex Double] -> [[Complex Double]] -> [[Complex Double]] \r\nfft_level' [_] = id\r\nfft_level' ws = map2 (\\x -> appendpair . fft_merge' ws x) . fft_level' (drop_odds ws)\r\n\r\nfft_merge' :: [Complex Double] -> [Complex Double] -> [Complex Double] -> ([Complex Double], [Complex Double])\r\nfft_merge' (w:ws) (x:xs) (y:ys) = let (xs', ys') = fft_merge' ws xs ys\r\n (x', y') = butterfly' w x y\r\n in (x' : xs', y' : ys')\r\nfft_merge' _ _ _ = ([], [])\r\n\r\nfft_init' (x:y:r) = (zipWith (\\x y -> [x + y, x - y]) x y) ++ fft_init' r\r\nfft_init' _ = []\r\n\r\nfft_overlap_loop (x:r@(y:_)) = (concat $ zipWith (\\x y -> [x + y, x - y]) x y) : fft_overlap_loop r\r\nfft_overlap_loop _ = []\r\n\r\nexpandComplex ((x:+y):r) = x : y : expandComplex r\r\nexpandComplex _ = []\r\n-------------------------------------------------------------------------------\r\n-- | Creates a fade with length N\r\noverlap_curve :: Int -> [Double]\r\noverlap_curve n = take n $ map (\\k -> 0.5 - 0.5 * cos (fromIntegral k * 2 * pi / fromIntegral n )) [0..]\r\n\r\n-- | Overlaps a sequence of parts of length N (overlaps by N\\/2).\r\nmix_overlap :: Int -> [[Double]] -> [Double]\r\nmix_overlap n xs = merge (+) l r\r\n where \r\n c = cycle $ overlap_curve n\r\n l = zipWith (*) c $ concat $ evens xs\r\n r = replicate (div n 2) 0.0 ++ (zipWith (*) c $ concat $ odds xs)\r\n-------------------------------------------------------------------------------\r\n-- | FFT transformation with overlapping and windowing. \r\n-- Argument function maps the coefficients. Windowsize: 2^(N+2), i. e. 2^(N+1) coefficients\r\nfftt :: Int -> ([[Complex Double]] -> [Complex Double]) -> [Double] -> [Double]\r\nfftt n f = \r\n mix_overlap (2^(n+2)) . \r\n map expandComplex . \r\n fft_level' (ws False (2^n)) . \r\n fft_init' . \r\n reorder (n-1) . \r\n reorder_init' .\r\n f .\r\n fft_level (ws True (2^n)) . \r\n fft_init_overlap . \r\n reorder_r2 (n-1) 0 . \r\n reorder_init\r\n\r\nffttv :: Int -> [Double] -> [Double] -> [Double]\r\nffttv n vs = fftt n (zipWith (\\v (x:+y) -> (v*x) :+ (v*y)) vs . concat . map (\\((a:+_):r) -> (a:+0):r))\r\n-------------------------------------------------------------------------------\r\n-- | FFT transformation for complex input (segments of length 2^n). \r\n-- No overlapping or windowing.\r\nfftc :: Int -> [Complex Double] -> [[Complex Double]]\r\nfftc n = fft_level (ws True (2^n)) . fft_init . reorder_r2 (n-1) 0 . reorder_init_r2' 0\r\n\r\n-- | Inverse FFT transformation for complex input (segments of length 2^n). \r\n-- No overlapping or windowing.\r\nfftc' :: Int -> [Complex Double] -> [[Complex Double]]\r\nfftc' n = fft_level' (ws False (2^n)) . fft_init' . reorder (n-1) . reorder_init'\r\n-------------------------------------------------------------------------------\r\n-- | FFT for complex input with overlapping. Segment-size: 2^(n+1)\r\nfftco :: Int -> [Complex Double] -> [[Complex Double]]\r\nfftco n = fft_level (ws True (2^n)) . fft_init_overlap . reorder_r2 (n-1) 0 . reorder_init_r2' 0\r\n\r\nfftco' :: Int -> [Complex Double] -> [Complex Double]\r\nfftco' n = mix_overlapc (2^(n+1)) . fft_level' (ws False (2^n)) . fft_init' . reorder (n-1) . reorder_init'\r\n\r\n-- | Overlaps a sequence of parts of length N (overlaps by N\\/2).\r\nmix_overlapc :: Int -> [[Complex Double]] -> [Complex Double]\r\nmix_overlapc n xs = merge (+) l r\r\n where \r\n c = cycle $ map (:+0) $ overlap_curve n\r\n l = zipWith (*) c $ concat $ evens xs\r\n r = replicate (div n 2) 0.0 ++ (zipWith (*) c $ concat $ odds xs)\r\n-------------------------------------------------------------------------------\r\n\r\n-- | A self-inverse transformation similar to FFT but with a simple butterfly\r\n-- operation that uses always W=1. Modifying the data between application\r\n-- and inverse is similar to filtering but the result will be built up from\r\n-- rectangle waves instead of sinus waves.\r\nrect_transform :: Floating a => Int -> [a] -> [[a]]\r\nrect_transform n = run n . map (:[])\r\n where\r\n sq = 1 / sqrt 2\r\n add x y = (x+y) * sq\r\n sub x y = (x-y) * sq\r\n run 0 = id\r\n run n = loop . run (n-1)\r\n loop (x:y:r) = iter True x y : loop r\r\n loop [x] = [iter True x (repeat 0)]\r\n loop _ = []\r\n iter True (x:xs) (y:ys) = add x y : sub x y : iter False xs ys\r\n iter False (x:xs) (y:ys) = sub x y : add x y : iter True xs ys\r\n iter _ _ _ = []\r\n\r\nrect_filter :: Floating a => Int -> ([[a]] -> [[a]]) -> [a] -> [a]\r\nrect_filter n f = concat . rect_transform n . concat . f . rect_transform n\r\n\r\nrect_filter' :: Floating a => Int -> [[a]] -> [a] -> [a]\r\nrect_filter' n vs = concat . rect_transform n . concat . zipWith f vs . rect_transform n\r\n where\r\n f v c = zipWith (*) (v ++ repeat 0) c\r\n\r\n\r\n", "meta": {"hexsha": "5bb5464148d2eb18b08ecd1f2287e44a474bb500", "size": 10154, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Sound/Hommage/FFT.hs", "max_stars_repo_name": "aische/hommage", "max_stars_repo_head_hexsha": "5285b0b3ce347b90ed9cafb517cd1917b0733c4f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-06-23T12:17:56.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-23T12:17:56.000Z", "max_issues_repo_path": "src/Sound/Hommage/FFT.hs", "max_issues_repo_name": "aische/hommage", "max_issues_repo_head_hexsha": "5285b0b3ce347b90ed9cafb517cd1917b0733c4f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Sound/Hommage/FFT.hs", "max_forks_repo_name": "aische/hommage", "max_forks_repo_head_hexsha": "5285b0b3ce347b90ed9cafb517cd1917b0733c4f", "max_forks_repo_licenses": ["BSD-3-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.7535211268, "max_line_length": 125, "alphanum_fraction": 0.504136301, "num_tokens": 3097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6648581861818663}} {"text": "import Numeric.LinearAlgebra\n\nand' x1 x2 =\n let w1 = 0.5; w2 = 0.5\n theta = 0.7\n tmp = x1*w1 + x2*w2\n in if tmp > theta then 1 else 0\n\nand'' :: Num t => Vector R -> t\nand'' x =\n let w = vector [0.5, 0.5]\n b = (-0.7)\n tmp = (x <.> w) + b\n in if tmp > 0 then 1 else 0\n\nnand :: Num t => Vector R -> t\nnand x =\n let w = vector [(-0.5), (-0.5)]\n b = 0.7\n tmp = (x <.> w) + b\n in if tmp > 0 then 1 else 0\n\nor' :: Num t => Vector R -> t\nor' x =\n let w = vector [0.5, 0.5]\n b = (-0.2)\n tmp = (x <.> w) + b\n in if tmp > 0 then 1 else 0\n\nxor :: Num t => Vector R -> t\nxor x =\n let s1 = nand x\n s2 = or' x\n in and'' $ vector [s1, s2]\n", "meta": {"hexsha": "457f23ec1487ba56591ce1be889775da2dabd442", "size": 716, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Gate.hs", "max_stars_repo_name": "ku00/deep-learning-practice", "max_stars_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-03T05:32:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-03T05:32:58.000Z", "max_issues_repo_path": "src/Gate.hs", "max_issues_repo_name": "ku00/deep-learning-practice", "max_issues_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Gate.hs", "max_forks_repo_name": "ku00/deep-learning-practice", "max_forks_repo_head_hexsha": "50ed3fc142e23fad865cca90b0331af7b819d5b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4571428571, "max_line_length": 35, "alphanum_fraction": 0.437150838, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443461, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6644510370217253}} {"text": "-- file:Astro/AccretionDisk.hs\n-- Numerical tools for accretion disk analysis\n\nmodule Astro.AccretionDisk\n\twhere\n\nimport Control.Monad\nimport System.IO.Unsafe\nimport System.Random\nimport Numeric.LinearAlgebra\n\nimport Astro.Misc\n\nseed = 1337\n\nrndDoubles :: Int -> (Double,Double) -> IO [Double]\nrndDoubles n (min,max) = replicateM n $ randomRIO (min,max)\n\nrndDouble :: (Double, Double) -> IO Double\nrndDouble (min, max) = randomRIO (min,max) :: IO Double\n\n-- Random position and corresponding velocity in a flat xy-plane Keplerian disk\n-- with CCW rotation when viewed towards negative z-axis\nrndDiskPosVel :: (Double, Double) -> Double -> IO (Vector Double, Vector Double)\nrndDiskPosVel (minR,maxR) gpar = \n\tdo\n\tr <- rndDouble (minR,maxR)\n\tth <- rndDouble (0, 2*pi)\n\tlet rv = fromList [ r * cos th, r * sin th, 0]\n\t vv = fromList [-rv@>1, rv@>0, 0.0]\n\t vv' = scale (sqrt gpar/norm rv) vv\n\treturn (rv, vv')\n\n-- Create a flat disk (planar), rotating in a CCW sense when viewed\n-- towards negative z-axis\nflatDisk :: (Double, Double) -> Double -> Int \n\t\t-> [(Vector Double, Vector Double)]\nflatDisk (minR, maxR) gpar nparts = unsafePerformIO $\n\tdo \n\t\tsetStdGen $ mkStdGen seed\n\t\treplicateM nparts $ rndDiskPosVel (minR,maxR) gpar\n\n\t\n", "meta": {"hexsha": "ca9d68c843dd79f9980073dfd38a0906108f35f1", "size": 1236, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AccretionDisk.hs", "max_stars_repo_name": "sageh/AstroHaskell", "max_stars_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AccretionDisk.hs", "max_issues_repo_name": "sageh/AstroHaskell", "max_issues_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AccretionDisk.hs", "max_forks_repo_name": "sageh/AstroHaskell", "max_forks_repo_head_hexsha": "9431a0b5045716ee5fc1395232f2689b07002a5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0909090909, "max_line_length": 80, "alphanum_fraction": 0.7046925566, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6642529101615606}} {"text": "{-# LANGUAGE ViewPatterns #-}\nimport Numeric.GSL.ODE\nimport Numeric.LinearAlgebra\nimport Graphics.Plot\nimport Debug.Trace(trace)\ndebug x = trace (show x) x\n\nvanderpol mu = do\n let xdot mu t [x,v] = [v, -x + mu * v * (1-x^2)]\n ts = linspace 1000 (0,50)\n sol = toColumns $ odeSolve (xdot mu) [1,0] ts\n mplot (ts : sol)\n mplot sol\n\n\nharmonic w d = do\n let xdot w d t [x,v] = [v, a*x + b*v] where a = -w^2; b = -2*d*w\n ts = linspace 100 (0,20)\n sol = odeSolve (xdot w d) [1,0] ts\n mplot (ts : toColumns sol)\n\n\nkepler v a = mplot (take 2 $ toColumns sol) where\n xdot t [x,y,vx,vy] = [vx,vy,x*k,y*k]\n where g=1\n k=(-g)*(x*x+y*y)**(-1.5)\n ts = linspace 100 (0,30)\n sol = odeSolve xdot [4, 0, v * cos (a*degree), v * sin (a*degree)] ts\n degree = pi/180\n\n\nmain = do\n vanderpol 2\n harmonic 1 0\n harmonic 1 0.1\n kepler 0.3 60\n kepler 0.4 70\n vanderpol' 2\n\n-- example of odeSolveV with jacobian\nvanderpol' mu = do\n let xdot mu t (toList->[x,v]) = fromList [v, -x + mu * v * (1-x^2)]\n jac t (toList->[x,v]) = (2><2) [ 0 , 1\n , -1-2*x*v*mu, mu*(1-x**2) ]\n ts = linspace 1000 (0,50)\n hi = (ts@>1 - ts@>0)/100\n sol = toColumns $ odeSolveV (MSBDF jac) hi 1E-8 1E-8 (xdot mu) (fromList [1,0]) ts\n mplot sol\n\n\n", "meta": {"hexsha": "dc6e0ec7199463405737d42b57cd4cee1a498161", "size": 1374, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/ode.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/ode.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/ode.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": 26.9411764706, "max_line_length": 90, "alphanum_fraction": 0.5203784571, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6640174149440495}} {"text": "module Nnaskell ( NN(..)\n , randomNN\n , activateNN\n , cost\n , optimizeCost\n , loadNN\n , saveNN\n ) where\n\nimport Data.Function\nimport Data.List\nimport Control.Monad\nimport System.Random\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra.HMatrix\n\ndata NN = NN { nnWs :: [Matrix R]\n , nnBs :: [Vector R]\n } deriving (Show, Read)\n\nrandomVec :: Int -> IO (Vector R)\nrandomVec n = vector <$> (replicateM n $ randomRIO (-1.0, 1.0))\n\nrandomMatrix :: Int -> Int -> IO (Matrix R)\nrandomMatrix n m = matrix m <$> (replicateM ((*) n m) $ randomRIO (-1.0, 1.0))\n\nrandomLayer :: Int -> Int -> IO (Matrix R, Vector R)\nrandomLayer n m = liftM2 (\\ws bs -> (ws, bs)) (randomMatrix m n) (randomVec m)\n\nrandomNN :: [Int] -> IO NN\nrandomNN ns = do (ws, bs) <- unzip <$> (sequence $ map (uncurry randomLayer) $ pairScan ns)\n return $ NN { nnWs = ws\n , nnBs = bs\n }\n\nsigmoid :: R -> R\nsigmoid t = 1 / (1 + exp (-1 * t))\n\nsigmoidVec :: Vector R -> Vector R\nsigmoidVec = fromList . map sigmoid . toList\n\nactivateLayer :: Vector R -> (Matrix R, Vector R) -> Vector R\nactivateLayer as (ws, bs) = sigmoidVec (ws #> as + bs)\n\nactivateNN :: NN -> Vector R -> Vector R\nactivateNN nn as = foldl activateLayer as $ zip ws bs\n where ws = nnWs nn\n bs = nnBs nn\n\npairScan :: [a] -> [(a, a)]\npairScan (x:y:rest) = (x, y) : pairScan (y:rest)\npairScan _ = []\n\ncost :: [(Vector R, Vector R)] -> NN -> R\ncost td nn = (sum $ map inputCost td) / n\n where inputCost (input, output) = sumElements $ cmap (** 2) (activateNN nn input - output)\n n = fromIntegral $ length td\n\nstepBias :: NN -> Int -> R -> NN\nstepBias nn updateIdx s = nn { nnBs = map (\\(v, idx) -> if idx <= updateIdx && updateIdx < idx + size v\n then accum v (+) [(updateIdx - idx, s)]\n else v)\n $ zip bs\n $ scanl (\\idx v -> idx + size v) 0 bs\n }\n where bs = nnBs nn\n\nstepWeight :: NN -> Int -> R -> NN\nstepWeight nn updateIdx s = nn { nnWs = map (\\(mx, idx) -> let (n, m) = size mx\n effIdx = updateIdx - idx\n in if idx <= updateIdx && updateIdx < idx + (n * m)\n then accum mx (+) [((effIdx `div` m, effIdx `mod` m), s)]\n else mx)\n $ zip ws\n $ scanl (\\idx m -> idx + uncurry (*) (size m)) 0 ws\n }\n where ws = nnWs nn\n\nclass Domain d where\n countArgs :: d -> Int\n stepArg :: d -> Int -> R -> d\n\ninstance Domain NN where\n countArgs nn = bsCount + wsCount\n where bsCount = sum $ map (length . toList) $ nnBs nn\n wsCount = sum $ map length $ concatMap toLists $ nnWs nn\n stepArg nn idx s = if idx < bsCount\n then stepBias nn idx s\n else stepWeight nn (idx - bsCount) s\n where bsCount = sum $ map (length . toList) $ nnBs nn\n\noptimizeCost :: Domain d => (d -> R) -> d -> [d]\noptimizeCost cost d = scanl optimizeStep d $ cycle [0 .. n - 1]\n where n = countArgs d\n optimizeStep d idx = minimumBy (compare `on` cost) $ map (stepArg d idx) [-step, 0, step]\n step = 0.1\n\nloadNN :: FilePath -> IO NN\nloadNN filePath = read <$> readFile filePath\n\nsaveNN :: FilePath -> NN -> IO ()\nsaveNN filePath nn = writeFile filePath $ show nn\n", "meta": {"hexsha": "587f446681c5dbbc5c2b6ead6c87bd1c2b40629e", "size": 3848, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Nnaskell.hs", "max_stars_repo_name": "tsoding/nnaskell", "max_stars_repo_head_hexsha": "241c0a568a6eda967c1221f9a72706e75da09d2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-10-31T19:58:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T14:52:00.000Z", "max_issues_repo_path": "src/Nnaskell.hs", "max_issues_repo_name": "tsoding/nnaskell", "max_issues_repo_head_hexsha": "241c0a568a6eda967c1221f9a72706e75da09d2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2017-11-01T16:54:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-16T22:14:59.000Z", "max_forks_repo_path": "src/Nnaskell.hs", "max_forks_repo_name": "tsoding/nnaskell", "max_forks_repo_head_hexsha": "241c0a568a6eda967c1221f9a72706e75da09d2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.359223301, "max_line_length": 119, "alphanum_fraction": 0.4823284823, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059267, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6636664502495802}} {"text": "{- |\nDescription : Some handy (mathematical, string manipulation, and so on) tools\nCopyright : (c) Dominik Schrempf 2017\nLicense : GPLv3\n\nMaintainer : dominik.schrempf@gmail.com\nStability : unstable\nPortability : non-portable (not tested)\n\nPlease see function definitions and documentations.\n\n* Changelog\n\n-}\n\nmodule Tools\n ( allValues\n , harmonic\n , matrixSeparateSymSkew\n , matrixSetDiagToZero\n , nearlyEq\n , left\n , right\n ) where\n\nimport Numeric.LinearAlgebra\n\n-- | Get all values of a bounded enumerated type.\nallValues :: (Bounded a, Enum a) => [a]\nallValues = [minBound..]\n\n-- | Calculate the nth harmonic number.\nharmonic :: Int -> Double\nharmonic 1 = 1.0\nharmonic n = 1.0 / fromIntegral n + harmonic (n-1)\n\n-- | Separate a square matrix into a symmetric and a skew-symmetric matrix.\nmatrixSeparateSymSkew :: Matrix R -> (Matrix R, Matrix R)\nmatrixSeparateSymSkew m = (mSym, mSkew)\n where trM = tr m\n mSym = scale 0.5 $ m + trM\n mSkew = scale 0.5 $ m - trM\n\n-- | Set the diagonal entries of a matrix to zero.\nmatrixSetDiagToZero :: Matrix R -> Matrix R\nmatrixSetDiagToZero m = m - diag (takeDiag m)\n\n-- | Test for equality with tolerance (needed because of machine precision).\nnearlyEq :: Double -> Double -> Double -> Bool\nnearlyEq tol a b = tol > abs (a-b)\n\n-- Functions that fill a string 's' to a given width 'n' by adding a pad\n-- character 'c' (c) to align right.\nfillDiff :: Int -> String -> Int\nfillDiff width entry =\n if l >= width then 0 else width - l\n where l = length entry\n\nfillLeft :: Char -> Int -> String -> String\nfillLeft c n s = s ++ replicate (fillDiff n s) c\n\nfillRight :: Char -> Int -> String -> String\nfillRight c n s = replicate (fillDiff n s) c ++ s\n\n-- | Fill a string to a given width by adding spaces. Align left.\nleft :: Int -> String -> String\nleft = fillLeft ' '\n\n-- | Fill a string to a given width by adding spaces. Align right.\nright :: Int -> String -> String\nright = fillRight ' '\n", "meta": {"hexsha": "804f4d769757e353ceb95f5c45bdfdfada1fe50e", "size": 1968, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Tools.hs", "max_stars_repo_name": "dschrempf/bmm-simulate", "max_stars_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-14T15:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T15:53:08.000Z", "max_issues_repo_path": "src/Tools.hs", "max_issues_repo_name": "pomo-dev/bmm-simulate", "max_issues_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tools.hs", "max_forks_repo_name": "pomo-dev/bmm-simulate", "max_forks_repo_head_hexsha": "219a4f8b7bb08a2b2bc9920a94c67fd319b0b9f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3333333333, "max_line_length": 78, "alphanum_fraction": 0.6803861789, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.6634073965845235}} {"text": "module Lib.Utility.Differentiation (\n numericalGradient\n ) where\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Devel\n\nh = 1e-4\n\ntype F = X -> Double\ntype X = Matrix Double\nnumericalGradient :: F -> X -> X\nnumericalGradient f xs = runSTMatrix $ do\n xs' <- thawMatrix xs\n let (rows, columns) = size xs\n let grad = newMatrix 0 rows columns\n let allIndex = [(r,c) | r <- [0..rows-1], c <- [0..columns-1]]\n foldr (\\(r, c) grad -> do\n x <- readMatrix xs' r c\n grad' <- grad\n writeMatrix xs' r c $ x+h\n xs'' <- freezeMatrix xs'\n let fxHPlus = f xs''\n writeMatrix xs' r c $ x-h\n xs'' <- freezeMatrix xs'\n let fxHMinus = f xs''\n let delta = (fxHPlus - fxHMinus) / (2 * h)\n writeMatrix xs' r c x\n writeMatrix grad' r c delta\n return grad'\n ) grad allIndex\n", "meta": {"hexsha": "df13271df1d96a816891ff9e583696c049c93e66", "size": 868, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib/Utility/Differentiation.hs", "max_stars_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_stars_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T06:16:37.000Z", "max_issues_repo_path": "src/Lib/Utility/Differentiation.hs", "max_issues_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_issues_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-01-04T02:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-09T12:39:40.000Z", "max_forks_repo_path": "src/Lib/Utility/Differentiation.hs", "max_forks_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_forks_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T03:39:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T03:39:47.000Z", "avg_line_length": 27.125, "max_line_length": 66, "alphanum_fraction": 0.5783410138, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6633164604056755}} {"text": "module Main where\n\nimport Numeric.LinearAlgebra\nimport Common\nimport Forward\nimport BackProp\nimport AutoEncoder\nimport ActivFunc\nimport Other\n\nmain :: IO ()\nmain = do\n regression\n classification\n\nregression :: IO ()\nregression = do\n ws <- genWeights [2, 4, 8, 1]\n let x = matrix 4 [0, 0, 1, 1,\n 0, 1, 0, 1]\n let y = matrix 4 [0, 1, 1, 0]\n let i = matrix 4 [0, 0, 1, 1,\n 0, 1, 0, 1] -- example\n -- let nws = last . take 500 $ iterate (backPropRegression sigmoids (x, y)) ws\n nws <- last . take 500 $ iterateM (sgdMethod 2 (x, y) $ backPropRegression 0.1 sigmoids) ws\n let pws = preTrains 0.1 500 sigmoids x ws\n npws <- last . take 500 $ iterateM (sgdMethod 2 (x, y) $ backPropRegression 0.1 sigmoids) pws\n putStrLn \"training inputs\"\n print x\n putStrLn \"training outputs\"\n print y\n putStrLn \"inputs\"\n print i\n putStrLn \"not trained outputs\"\n print $ forwardRegression sigmoidC ws i\n putStrLn \"trainined outputs\"\n print $ forwardRegression sigmoidC nws i\n putStrLn \"pretrainined outputs\"\n print $ forwardRegression sigmoidC npws i\n\nclassification :: IO ()\nclassification = do\n ws <- genWeights [2, 4, 8, 3]\n let x = matrix 4 [0, 0, 1, 1,\n 0, 1, 0, 1]\n let y = matrix 4 [1, 0, 0, 0,\n 0, 1, 1, 0,\n 0, 0, 0, 1]\n let i = matrix 4 [0, 0, 1, 1,\n 0, 1, 0, 1] -- example\n -- let nws = last . take 500 $ iterate (backPropClassification sigmoids (x, y)) ws\n nws <- last . take 500 $ iterateM (sgdMethod 2 (x, y) $ backPropClassification 0.1 sigmoids) ws\n let pws = preTrains 0.1 500 sigmoids x ws\n npws <- last . take 500 $ iterateM (sgdMethod 2 (x, y) $ backPropClassification 0.1 sigmoids) pws\n putStrLn \"training inputs\"\n print x\n putStrLn \"training outputs\"\n print y\n putStrLn \"inputs\"\n print i\n putStrLn \"not trained outputs\"\n print $ forwardClassification sigmoidC ws i\n putStrLn \"trainined outputs\"\n print $ forwardClassification sigmoidC nws i\n putStrLn \"pretrainined outputs\"\n print $ forwardClassification sigmoidC npws i\n", "meta": {"hexsha": "714483e645e3ecdbe3d15dd5a5a2c44ca4af0268", "size": 2075, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.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": "app/Main.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": "app/Main.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": 30.9701492537, "max_line_length": 99, "alphanum_fraction": 0.6453012048, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7461390043208004, "lm_q1q2_score": 0.663137594662424}} {"text": "module Perceptron where\n\nimport Numeric.LinearAlgebra\n\nv00 = vector [0.0,0.0]\nv01 = vector [0.0,1.0]\nv10 = vector [1.0,0.0]\nv11 = vector [1.0,1.0]\n\np_and :: Vector Double -> Double\np_and x\n | tmp <= 0.0 = 0.0\n | otherwise = 1.0\n where\n tmp = w <.> x + b\n b = -0.7\n w = vector [0.5,0.5]\n\np_nand :: Vector Double -> Double\np_nand x\n | tmp <= 0.0 = 0.0\n | otherwise = 1.0\n where\n tmp = w <.> x + b\n b = 0.7\n w = vector [-0.5,-0.5]\n\np_or :: Vector Double -> Double\np_or x\n | tmp <= 0.0 = 0.0\n | otherwise = 1.0\n where\n tmp = w <.> x + b\n b = -0.2\n w = vector [0.5,0.5]\n\np_xor :: Vector Double -> Double\np_xor x = p_and $ vector [s1,s2]\n where\n s1 = p_nand x\n s2 = p_or x\n", "meta": {"hexsha": "4ae52ec1aa3ebfb47ffc756b8cbe444281f88d2a", "size": 710, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Perceptron.hs", "max_stars_repo_name": "chupaaaaaaan/nn-with-haskell", "max_stars_repo_head_hexsha": "c1a8c303e0ca8d23781fe1279cbc5e439efbde39", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Perceptron.hs", "max_issues_repo_name": "chupaaaaaaan/nn-with-haskell", "max_issues_repo_head_hexsha": "c1a8c303e0ca8d23781fe1279cbc5e439efbde39", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Perceptron.hs", "max_forks_repo_name": "chupaaaaaaan/nn-with-haskell", "max_forks_repo_head_hexsha": "c1a8c303e0ca8d23781fe1279cbc5e439efbde39", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9047619048, "max_line_length": 33, "alphanum_fraction": 0.5352112676, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6629068824068269}} {"text": "{-# LANGUAGE CPP #-}\n-- |\n-- Module : Numeric.SpecFunctions\n-- Copyright : (c) 2009, 2011, 2012 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Special functions and factorials.\nmodule Numeric.SpecFunctions (\n -- * Error function\n erf\n , erfc\n , invErf\n , invErfc\n -- * Gamma function\n , logGamma\n , logGammaL\n , incompleteGamma\n , invIncompleteGamma\n , digamma\n -- * Beta function\n , logBeta\n , incompleteBeta\n , incompleteBeta_\n , invIncompleteBeta\n -- * Sinc\n , sinc\n -- * Logarithm\n -- $log1p\n , log1p\n , log1pmx\n , log2\n -- * Exponent\n , expm1\n -- * Factorial\n , factorial\n , logFactorial\n , stirlingError\n -- * Combinatorics\n , choose\n , logChoose\n -- * References\n -- $references\n ) where\n\nimport Numeric.SpecFunctions.Internal\n\n-- $log1p\n--\n-- Base starting from @4.9.0@ (GHC 8.0) provides 'log1p' and 'expm1'\n-- as method of class 'Floating'. In this case we simply reexport\n-- these function. Otherwise we provide our own with more restrictive\n-- signature @Double → Double@.\n\n-- $references\n--\n-- * Bernardo, J. (1976) Algorithm AS 103: Psi (digamma)\n-- function. /Journal of the Royal Statistical Society. Series C\n-- (Applied Statistics)/ 25(3):315-317.\n-- \n--\n-- * Cran, G.W., Martin, K.J., Thomas, G.E. (1977) Remark AS R19\n-- and Algorithm AS 109: A Remark on Algorithms: AS 63: The\n-- Incomplete Beta Integral AS 64: Inverse of the Incomplete Beta\n-- Function Ratio. /Journal of the Royal Statistical Society. Series\n-- C (Applied Statistics)/ Vol. 26, No. 1 (1977), pp. 111-114\n-- \n--\n-- * Lanczos, C. (1964) A precision approximation of the gamma\n-- function. /SIAM Journal on Numerical Analysis B/\n-- 1:86–96. \n--\n-- * Loader, C. (2000) Fast and Accurate Computation of Binomial\n-- Probabilities. \n--\n-- * Macleod, A.J. (1989) Algorithm AS 245: A robust and reliable\n-- algorithm for the logarithm of the gamma function.\n-- /Journal of the Royal Statistical Society, Series C (Applied Statistics)/\n-- 38(2):397–402. \n--\n-- * Majumder, K.L., Bhattacharjee, G.P. (1973) Algorithm AS 63: The\n-- Incomplete Beta Integral. /Journal of the Royal Statistical\n-- Society. Series C (Applied Statistics)/ Vol. 22, No. 3 (1973),\n-- pp. 409-411. \n--\n-- * Majumder, K.L., Bhattacharjee, G.P. (1973) Algorithm AS 64:\n-- Inverse of the Incomplete Beta Function Ratio. /Journal of the\n-- Royal Statistical Society. Series C (Applied Statistics)/\n-- Vol. 22, No. 3 (1973), pp. 411-414\n-- \n--\n-- * Temme, N.M. (1992) Asymptotic inversion of the incomplete beta\n-- function. /Journal of Computational and Applied Mathematics\n-- 41(1992) 145-157.\n--\n-- * Temme, N.M. (1994) A set of algorithms for the incomplete gamma\n-- functions. /Probability in the Engineering and Informational\n-- Sciences/, 8, 1994, 291-307. Printed in the U.S.A.\n\n", "meta": {"hexsha": "204dd4d86834b984a4a1ac7979c84ef373736afc", "size": 3244, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Numeric/SpecFunctions.hs", "max_stars_repo_name": "Shimuuar/math-functions", "max_stars_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2015-06-05T09:06:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T17:18:01.000Z", "max_issues_repo_path": "Numeric/SpecFunctions.hs", "max_issues_repo_name": "Shimuuar/math-functions", "max_issues_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2015-08-23T21:28:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-31T11:52:32.000Z", "max_forks_repo_path": "Numeric/SpecFunctions.hs", "max_forks_repo_name": "Shimuuar/math-functions", "max_forks_repo_head_hexsha": "fa607079fd821d00d4b7c3bbdf38a9320e2b4471", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2015-03-29T03:36:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-25T16:40:04.000Z", "avg_line_length": 31.4951456311, "max_line_length": 98, "alphanum_fraction": 0.6670776819, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6624203702413038}} {"text": "module Main where\n\nimport BuckinghamPi\nimport FileOperations\nimport Numeric.LinearAlgebra.HMatrix\n\nrho = DimensionalVariable \"rho\" [(Mass , 1.0) , (Length , -3.0)]\nvel = DimensionalVariable \"v\" [(Length , 1.0) , (Time , -1.0)]\nl = DimensionalVariable \"l\" [(Length , 1.0)]\nmu = DimensionalVariable \"mu\" [(Mass , 1.0) , (Length , -1.0) , (Time , -1.0)]\na = DimensionalVariable \"a\" [(Length , 1.0) , (Time , -1.0)]\n\ndimVars = [rho, vel, l, mu, a]\nfunUnits = [Mass, Length, Time]\n\n--writeDimensionlessGroups :: [DimensionlessVariable] -> FilePath -> IO ()\nmain :: IO ()\nmain = fmap (\\d -> generatePiGroups d [0..(numFundamentalUnits dimVars - 1)]) (readVariablesFromFile \"./app/dimensional_variables\") >>= (\\v -> writeDimensionlessGroups v \"dimensionless_groups\")\n", "meta": {"hexsha": "795d0cbdfff9e1ebe7771a1aebc2f16b2217c8c6", "size": 815, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "jgrisham4/buckingham-pi", "max_stars_repo_head_hexsha": "897fab1d4392c59aa8a1905cb971ba43de05bc7d", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "jgrisham4/buckingham-pi", "max_issues_repo_head_hexsha": "897fab1d4392c59aa8a1905cb971ba43de05bc7d", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "jgrisham4/buckingham-pi", "max_forks_repo_head_hexsha": "897fab1d4392c59aa8a1905cb971ba43de05bc7d", "max_forks_repo_licenses": ["BSD-3-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.8947368421, "max_line_length": 193, "alphanum_fraction": 0.6306748466, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6622969538631913}} {"text": "{-|\nModule : Marvin.API.Algorithms.Internal.GradientDescent\nDescription : Optimization algorithm.\n-}\nmodule Marvin.API.Algorithms.Internal.GradientDescent where\n\nimport Marvin.API.Table.Internal as Table\nimport Marvin.API.Fallible\n\nimport Numeric.LinearAlgebra.HMatrix\nimport Numeric.LinearAlgebra.Data as LA\n\nimport qualified Data.Vector as Vec\nimport qualified Data.Vector.Unboxed as UVec\n\nimport Control.Arrow\nimport Control.Monad.Except\nimport Data.List (intercalate)\n\n-- | Resulting model\ndata LinearModel = LM {\n featureColumnNames :: [Fallible ColumnName]\n , targetVariableName :: Fallible ColumnName\n , coefs :: LA.Vector Double\n , intercept_ :: Double\n} deriving Eq\n\ninstance Show LinearModel where\n show model = intercalate \" +\\n\" $ map ((++) \"\\t\") $ show (intercept_ model) : columnStrings\n where\n columnStrings = map (\\(idx, (coef, fallibleName)) ->\n let name = case fallibleName of\n Right n -> n\n Left _ -> \"column #\" ++ show idx\n in show coef ++ \" * \" ++ name) $\n zip [0..] $ zip (LA.toList (coefs model)) (featureColumnNames model)\n\nfit' :: GradientDescent -> (NumericTable, NumericColumn) -> LinearModel\nfit' gradDesc (nt, nc) = LM {\n featureColumnNames = columnNames nt\n , targetVariableName = columnName nc\n , intercept_ = intercept'\n , coefs = theta'\n }\n where\n featureMtx = tableToMatrix nt\n targetVar = columnToVector nc\n modelParams = gradientDescent gradDesc featureMtx targetVar\n theta = modelParams\n (intercept', theta') = if (addIntercept gradDesc)\n then (theta ! 0, LA.subVector 1 (LA.size theta - 1) theta)\n else (0, theta)\n\npredict' :: LinearModel -> NumericTable -> Fallible NumericColumn\npredict' model test = do\n dimCheck\n return $ unsafePredict model test\n where\n modelDim = LA.size $ coefs model\n testDim = numberOfColumns test\n dimCheck = if modelDim == testDim\n then return ()\n else throwError $\n RowLengthMismatch $\n \"When attempting to make predictions based on a linear model. \" ++\n \"coefficients: \" ++ (show modelDim) ++\n \", columns: \" ++ (show testDim) ++ \".\"\n\n-- | Predicts without checks.\nunsafePredict :: LinearModel -> NumericTable -> NumericColumn\nunsafePredict model nt = pred\n where\n pred = unsafeFromVector $ fromLinAlgVector $ batchPredict theta c x\n x = tableToMatrix nt\n theta = coefs model\n c = intercept_ model\n\n-- | Predicts with hmatrix types.\nbatchPredict :: LA.Vector R -> R -> FeatureMatrix -> TargetVariable\nbatchPredict theta intercept x = cmap (+ intercept) (x #> theta)\n\n-- * Type aliases\ntype TargetVariable = Vector R\ntype FeatureVector = Vector R\n\ntype FeatureMatrix = Matrix R\ntype ModelParameters = Vector R\n\ntype CostFunction = FeatureMatrix -> TargetVariable -> ModelParameters -> (R, Vector R)\ntype Regularization = R -> ModelParameters -> (R, Vector R)\n\n-- * Parameters\ndata GradientDescent = GradientDescent {\n learningRate :: Double\n , addIntercept :: Bool\n , lambda :: Double\n , cost :: CostFunction\n , initModelParams :: FeatureMatrix -> TargetVariable -> ModelParameters\n , numIter :: Int\n}\n\ndefaultGradientDescent = GradientDescent {\n learningRate = 0.1\n , initModelParams = \\x y -> cols x |> [1,1..]\n , numIter = 10\n , lambda = 0.1\n , addIntercept = True\n , cost = linearRegressionCost\n}\n-- * Cost functions\n\nlogisticRegressionCost :: FeatureMatrix -> TargetVariable -> ModelParameters\n -> (R, Vector R)\nlogisticRegressionCost x@features y@targetVariable theta@modelParameters =\n (cost, gradient)\n where\n cost = (1 / m) * sumElements (-y * log h - (1-y) * log(1-h))\n gradient = scale (1 / m) $ tr x #> error\n m = fromIntegral (rows x) :: R\n error = h - y\n h@hypothesis = cmap sigmoid $ x #> theta\n\nlinearRegressionCost :: FeatureMatrix -> TargetVariable -> ModelParameters -> (R, Vector R)\nlinearRegressionCost x@features y@targetVariable theta@modelParameters =\n (cost, gradient)\n where\n cost = (1 / (2 * m)) * sumElements (error ^ 2)\n gradient = scale (1 / m) $ tr x #> error\n m = fromIntegral (rows x) :: R\n error = h - y\n h@hypothesis = x #> theta\n\naddRegularization :: R -> CostFunction -> Regularization -> CostFunction\naddRegularization lambda costFunction regularization x y theta =\n (cost + regCost, gradient + regGradient)\n where\n (cost, gradient) = costFunction x y theta\n (regCost, regGradient) = regularization lambda theta\n\nl2 :: R -> ModelParameters -> (R, Vector R)\nl2 lambda@regularizationCoefficient theta@modelParameters =\n (cost, gradient)\n where\n cost = lambda * (norm_2 modelParameters)^2\n gradient = scale (2 * lambda) modelParameters\n\n-- * Algorithm\n\ngradientDescent :: GradientDescent -> FeatureMatrix -> TargetVariable ->\n ModelParameters\ngradientDescent params featureMtx targetVariable =\n runIteration (numIter params) modelUpdater initModel\n where\n features = if addIntercept params\n then addInterceptFeature featureMtx\n else featureMtx\n lambda' = lambda params\n cost' = cost params\n costFunction = if lambda' /= 0\n then addRegularization lambda' cost' l2\n else cost'\n alpha = learningRate params\n initModel = initModelParams params features targetVariable\n gradient model = snd $ costFunction features targetVariable model\n modelUpdater theta = theta - scale alpha (gradient theta)\n\n-- * Helpers\n\naddInterceptFeature :: FeatureMatrix -> FeatureMatrix\naddInterceptFeature features = LA.fromColumns $ constantFeature:toColumns x\n where\n x = features\n (m,_) = size x\n constantFeature = m |> repeat 1\n\nsigmoid :: R -> R\nsigmoid z = 1 / (1 + exp(-z))\n\nrunIteration :: Int -> (a -> a) -> a -> a\nrunIteration n f init = iterate f init !! n\n\n-- * Conversions\n\ncolumnToVector :: NumericColumn -> LA.Vector R\ncolumnToVector = LA.fromList . UVec.toList . values\n\ntableToMatrix :: NumericTable -> LA.Matrix R\ntableToMatrix =\n columnsVec >>>\n Vec.toList >>>\n map columnToVector >>>\n LA.fromColumns\n\nfromLinAlgVector :: LA.Vector R -> UVec.Vector R\nfromLinAlgVector = LA.toList >>> UVec.fromList\n\ntoLinAlgVector :: Vec.Vector R -> LA.Vector R\ntoLinAlgVector = Vec.toList >>> LA.fromList", "meta": {"hexsha": "81065e4456cea2e7371fe4b5fc6021ede5806f7c", "size": 6492, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Marvin/API/Algorithms/Internal/GradientDescent.hs", "max_stars_repo_name": "gaborhermann/marvin", "max_stars_repo_head_hexsha": "5c616709f0645d4b1f13caa20820a39ee31774de", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-18T09:46:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-18T09:46:00.000Z", "max_issues_repo_path": "src/Marvin/API/Algorithms/Internal/GradientDescent.hs", "max_issues_repo_name": "gaborhermann/marvin", "max_issues_repo_head_hexsha": "5c616709f0645d4b1f13caa20820a39ee31774de", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Marvin/API/Algorithms/Internal/GradientDescent.hs", "max_forks_repo_name": "gaborhermann/marvin", "max_forks_repo_head_hexsha": "5c616709f0645d4b1f13caa20820a39ee31774de", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-02T11:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T11:45:45.000Z", "avg_line_length": 32.7878787879, "max_line_length": 93, "alphanum_fraction": 0.6598890943, "num_tokens": 1626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.662117580355359}} {"text": "-- Gaussian primes\n-- http://www.codewars.com/kata/54d6abf84a35017d30000b26/\n\nmodule Data.Complex.Gaussian.Prime where\n\nimport Control.Arrow ((&&&))\nimport Data.Complex.Gaussian (Gaussian (..), norm)\n\nisGaussianPrime :: Gaussian -> Bool\nisGaussianPrime g@(Gaussian a b) | a == 0 = f b\n | b == 0 = f a\n | otherwise = isPrime . norm $ g\n where f = uncurry (&&) . ((==3) . (`mod` 4) &&& isPrime) . abs\n isPrime n | n `elem` [2, 3, 5] = True\n | n `mod` 2 == 0 || n `mod` 3 == 0 = False\n | otherwise = notElem 0 . map (n `mod`) $ [5, 7 .. floor . sqrt . fromIntegral $ n]\n", "meta": {"hexsha": "7fa6be0c20c8aa4d9af2482d982fed64609531a8", "size": 797, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Beta/Prime.hs", "max_stars_repo_name": "gafiatulin/codewars", "max_stars_repo_head_hexsha": "535db608333e854be93ecfc165686a2162264fef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-01-14T20:12:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T06:16:58.000Z", "max_issues_repo_path": "src/Beta/Prime.hs", "max_issues_repo_name": "gafiatulin/codewars", "max_issues_repo_head_hexsha": "535db608333e854be93ecfc165686a2162264fef", "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/Beta/Prime.hs", "max_forks_repo_name": "gafiatulin/codewars", "max_forks_repo_head_hexsha": "535db608333e854be93ecfc165686a2162264fef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8823529412, "max_line_length": 132, "alphanum_fraction": 0.4328732748, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.661955352292927}} {"text": "-----------------------------------------------------------------------------\n{- |\nThis module defines the monad of sampling functions. See Park, Pfenning and Thrun:\nA probabilistic language based upon sampling functions, Principles of programming languages 2005\n \nSampling functions allow the composition of both discrete and continuous \nprobability distributions. \n\nThe implementation and interface are similar to those in the random-fu, monte-carlo \nand monad-mersenne-random packages.\n\nExample -- a biased coin:\n\n@\ndata Throw = Head | Tail\n\nthrow bias = do\n b <- bernoulli bias\n return $ if b then Head else Tail\n\ntenThrowsCrooked = replicateM 10 $ throw 0.3\n\ncountHeads = do \n throws <- tenThrowsCrooked\n return $ length [ () | Head <- throws]\n\nmain = do \n print =<< sampleIO tenThrowsCrooked\n print =<< eval ((\\<4) \\`fmap\\` countHeads)\n@\n\n-}\n\n{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}\n\nmodule Math.Probably.Sampler where\n\nimport Control.Monad\nimport Control.Applicative\nimport qualified Math.Probably.PDF as PDF\nimport Numeric.LinearAlgebra hiding (find)\nimport System.Random.Mersenne.Pure64\nimport System.Environment\nimport Data.List\nimport Data.Maybe\nimport Data.Ord\nimport Control.Spoon\n\n--import Debug.Trace\n\ntype Seed = PureMT\n\n\ndata Sampler a = Sam {unSam :: Seed -> (a, Seed) }\n | Samples [a]\n\ninstance Functor Sampler where\n fmap f (Sam sf) = Sam $ \\rs -> let (x,rs') = sf rs in\n (f x, rs')\n fmap f (Samples xs) = Samples $ map f xs\n \ninstance Applicative Sampler where\n pure x = Sam (\\rs-> (x, rs))\n (Sam sff) <*> (Sam sfx) = Sam $ \\rs-> let (f ,rs') = sff rs \n (x, rs'') = sfx rs' in\n (f x, rs'')\n\ninstance Monad Sampler where\n return = pure\n (Sam sf) >>= f = Sam $ \\rs-> let (x, rs'::Seed) = sf rs \n nextProb = f x\n in case nextProb of\n Sam g -> g rs'\n Samples xs -> primOneOf xs rs'\n (Samples xs) >>= f = Sam $ \\rs-> let (x, rs'::Seed) = primOneOf xs rs\n nextProb = f x\n in case nextProb of\n Sam g -> g rs'\n Samples ys -> primOneOf ys rs'\n\n-- | given a seed, return an infinite list of draws from sampling function\nrunSampler :: Seed -> Sampler a -> [a]\nrunSampler pmt s@(Sam sf) \n = let (x, pmt') = sf pmt\n in x : runSampler pmt' s\nrunSampler _ (Samples xs) = xs\n\n-- | Get a seed\ngetSeedIO :: IO Seed\ngetSeedIO = do\n args <- getArgs\n case mapMaybe (stripPrefix \"--seed=\") args of \n [] -> newPureMT\n sdStr:_ -> return $ pureMT $ read sdStr\n\n-- | Return an infinite list of draws from sampling function in the IO monad\nrunSamplerIO :: Sampler a -> IO [a]\nrunSamplerIO s = \n fmap (`runSampler` s) $ getSeedIO\n\n-- | Return a singe draw from sampling function\nsampleIO :: Sampler a -> IO a\nsampleIO s = head `fmap` runSamplerIO s\n\n-- | Return a list of n draws from sampling function\nsampleNIO :: Int -> Sampler a -> IO [a]\nsampleNIO n s = take n `fmap` runSamplerIO s\n\n-- | Estimate the probability that a hypothesis is true (in the IO monad)\neval :: Sampler Bool -> Sampler Double\neval s = do\n bs <- replicateM 1000 s \n return $ realToFrac (length (filter id bs)) / 1000\n \n\n\n{-mu :: Vector Double\nsigma :: Matrix Double\n\nmystery = -1\nmu = fromList [0,0,0]\nsigma = (3><3) [ 1, 1, 0,\n 1, 1, mystery,\n 0, mystery, 1]\n \n\nsamIt = sampleNIO 2 $ multiNormal mu sigma\n -}\n-- | The joint distribution of two independent distributions\njoint :: Sampler a -> Sampler b -> Sampler (a,b)\njoint sf1 sf2 = liftM2 (,) sf1 sf2\n\n-- | The joint distribution of two distributions where one depends on the other\njointConditional :: Sampler a -> (a-> Sampler b) -> Sampler (a,b)\njointConditional sf1 condsf \n = do x <- sf1\n y <- condsf x\n return (x,y)\n\n--replicateM :: Monad m => Int -> m a -> m [a]\n--replicateM n ma = forM [1..n] $ const ma\n\n \n-- * Uniform distributions\n \n-- | The unit interval U(0,1)\nunitSample :: Sampler Double\nunitSample = Sam randomDouble \n\n-- | for x and y, the uniform distribution between x and y \nuniform :: (Fractional a) => a -> a -> Sampler a\nuniform a b = (\\x->(realToFrac x)*(b-a)+a) `fmap` unitSample\n \n-- * Normally distributed sampling function\n\n--http://en.wikipedia.org/wiki/Box-Muller_transform\n-- | The univariate gaussian (normal) distribution defined by mean and standard deviation\ngauss :: (Floating b) => b -> b -> Sampler b\ngauss m sd = \n do (u1,u2) <- (mapPair realToFrac) `fmap` joint unitSample unitSample\n return $ sqrt(-2*log(u1))*cos(2*pi*u2)*sd+m\n where mapPair f (x,y) = (f x, f y)\n\n-- | Gaussians specialised for doubles\ngaussD :: Double -> Double -> Sampler Double\ngaussD m sd = \n do (u1,u2) <- joint unitSample unitSample\n return $ sqrt(-2*log(u1))*cos(2*pi*u2)*sd+m\n\n\ngaussMany :: Floating b => [(b,b)] -> Sampler [b]\ngaussMany means_sds = do gus <- gaussManyUnit (length means_sds)\n return $ map f $ zip gus means_sds\n where f (gu, (mean, sd)) = gu*sd+mean\n\ngaussManyD :: [(Double,Double)] -> Sampler [Double]\ngaussManyD means_sds = do gus <- gaussManyUnitD (length means_sds)\n return $ zipWith f gus means_sds\n where f gu (mean, sd) = gu*sd+mean\n\ngaussManyUnit :: Floating b => Int -> Sampler [b]\ngaussManyUnit 0 = return []\ngaussManyUnit n | odd n = liftM2 (:) (gauss 0 1) (gaussManyUnit (n-1))\n | otherwise = do us <- forM [1..n] $ const $ unitSample\n return $ gaussTwoAtATime $ map realToFrac us\n where \n gaussTwoAtATime :: Floating a => [a] -> [a]\n gaussTwoAtATime (u1:u2:rest) = sqrt(-2*log(u1))*cos(2*pi*u2) : sqrt(-2*log(u1))*sin(2*pi*u2) : gaussTwoAtATime rest\n gaussTwoAtATime _ = []\n\ngaussManyUnitD :: Int -> Sampler [Double]\ngaussManyUnitD 0 = return []\ngaussManyUnitD n | odd n = liftM2 (:) (gauss 0 1) (gaussManyUnit (n-1))\n | otherwise = do us <- forM [1..n] $ const $ unitSample\n return $ gaussTwoAtATimeD us\n where\n gaussTwoAtATimeD :: [Double] -> [Double]\n gaussTwoAtATimeD (u1:u2:rest) = sqrt(-2*log(u1))*cos(2*pi*u2) : sqrt(-2*log(u1))*sin(2*pi*u2) : gaussTwoAtATimeD rest\n gaussTwoAtATimeD _ = []\n\n\n\n-- | Multivariate normal distribution\nmultiNormal :: Vector Double -> Matrix Double -> Sampler (Vector Double)\nmultiNormal mu sigma =\n let c = cholSH sigma\n a = trans c\n k = dim mu\n in do z <- fromList `fmap` gaussManyUnitD k\n-- return $ mu + (head $ toColumns $ a*asRow z)\n let c = asColumn z\n let r = asRow z\n return $ (mu + (head $ toColumns $ a `multiply` asColumn z))\n\nmultiNormalByChol :: Vector Double -> Matrix Double -> Sampler (Vector Double)\nmultiNormalByChol mu cholSigma =\n let a = trans $ cholSigma\n k = dim mu\n in do z <- fromList `fmap` gaussManyUnitD k\n-- return $ mu + (head $ toColumns $ a*asRow z)\n let c = asColumn z\n let r = asRow z\n return $ (mu + (head $ toColumns $ a `multiply` asColumn z))\n\nmultiNormalIndep :: Vector Double -> Vector Double -> Sampler (Vector Double)\nmultiNormalIndep vars mus = do\n let k = dim mus\n gs <- gaussManyUnitD k\n return $ fromList $ zipWith3 (\\var mu g -> g*sqrt(var) + mu) (toList vars) (toList mus) gs\n\n\n\n--http://en.wikipedia.org/wiki/Log-normal_distribution#Generating_log-normally-distributed_random_variates\n\n-- | log-normal distribution \nlogNormal :: (Floating b) => b -> b -> Sampler b\nlogNormal m sd = \n do n <- gauss 0 1\n return $ exp $ m + sd * n\n\n\n-- * Other distribution\n\n-- | Bernoulli distribution. Returns a Boolean that is 'True' with probability 'p'\nbernoulli :: Double -> Sampler Bool\nbernoulli p = ( Sampler a\ndiscrete weightedSamples = \n let sumWeights = sum $ map fst weightedSamples\n cummWeightedSamples = scanl (\\(csum,_) (w,x) -> (csum+w,x)) (0,undefined) $ sortBy (comparing fst) weightedSamples\n in do u <- unitSample\n return . snd . fromJust $ find ((>=u*sumWeights) . fst) cummWeightedSamples\n\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\noneOf :: [a] -> Sampler a\noneOf xs = do idx <- floor `fmap` uniform (0::Double) (realToFrac $ length xs )\n return $ xs !! idx\n\nnOf :: Int -> [a] -> Sampler [a]\nnOf n xs = sequence $ replicate n $ oneOf xs\n\n{-main = do \n rnds <- take 1000 `fmap` runSamplerSysRan (oneOf [1,2,3])\n let diff = sort $ nub rnds\n print $ map (\\x->(x, length $ filter (==x) rnds )) $ diff -}\n\n-- | Bayesian inference from likelihood and prior using rejection sampling. \nbayesRejection :: (PDF.PDF a) -> Double -> Sampler a -> Sampler a\nbayesRejection p c q = bayes\n where bayes = do x <- q\n u <- unitSample\n if u < p x / c \n then return x\n else bayes \n\n \n{-\nexpectation :: Fractional a => Int -> Sampler a -> IO a\nexpectation n sf = \n (mean . take n) `fmap` runSamplerIO sf\n \nexpectSD :: Floating a => Int -> Sampler a -> IO (a,a)\nexpectSD n sf = \n (meanSD . take n) `fmap` runSamplerIO sf\n-} \n\n--mapPair :: (a->b) -> (a,a) -> (b,b)\n\n\n{-\n--http://cgi.cse.unsw.edu.au/~dons/blog/2008/05/16#fast\nmean :: Fractional a => [a] -> a\nmean = go 0 0\n where\n -- go :: -> Int -> [Double] -> Double\n go s n [] = s / fromIntegral n\n go !s !n (x:xs) = go (s+x) (n+1) xs\n\nmeanSD :: Floating a => [a] -> (a,a)\nmeanSD = go 0 0 0\n where go sq s n [] = let len = fromIntegral n in\n (s/len, (recip len)*sqrt (len*sq-s*s))\n go !sq !s !n (x:xs) = go (sq+x*x) (s+x) (n+1) xs\n\n\n\ntest_mean = mean [0..1e8]\ntest_meanVar = meanSD [0..1e8]\n\nmain = do u <- expectSD 1000000 $ gauss 0 1\n print u\n\n-}\n\n\n--poisson :: :: Double -> [Double] -> IO Double\n-- | Exponential distribution\nexpDist rate = (\\u-> negate $ (log(1-u))/rate) `fmap` unitSample\n\n-- | Homogeneous poisson process defined by rate and duration\npoissonMany :: Double -> Double -> Sampler [Double]\npoissonMany rate tmax = aux 0 \n where aux last = do\n next <- (+last) `fmap` expDist rate\n if next > tmax\n then return []\n else liftM2 (:) (return next) $ aux next\n\n-- | binomial distribution \nbinomial :: Int -> Double -> Sampler Int\nbinomial n p = do\n bools <- forM [1..n] $ const $ fmap ( Double -> Sampler Double\ngamma a b \n | a < 1 \n = do\n u <- unitSample\n x <- gamma (1 + a) b\n return (x * u ** recip a)\n | otherwise\n = go\n where\n d = a - (1 / 3)\n c = recip (3 * sqrt d) -- (1 / 3) / sqrt d\n \n go = do\n x <- gaussD 0 1\n \n let cx = c * x\n v = (1 + cx) ^ 3\n \n x_2 = x * x\n x_4 = x_2 * x_2\n \n if cx <= (-1)\n then go\n else do\n u <- unitSample\n \n if u < 1 - 0.0331 * x_4\n || log u < 0.5 * x_2 + d * (1 - v + log v)\n then return (b * d * v)\n else go\n\n-- | inverse gamma distribution\ninvGamma :: Double -> Double -> Sampler Double\ninvGamma a b = recip `fmap` gamma a b\n\n--http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Drawing_values_from_the_distribution\n--multiNormal :: Vector Double -> Matrix Double -> Sampler (Vector Double)\n\n--http://www.xycoon.com/beta_randomnumbers.htm\n-- | beta distribution\nbeta :: Int -> Int -> Sampler Double\nbeta a b = \n let gam n = do us <- forM [1..n] $ const unitSample\n return $ log $ product us\n in do gama1 <- gamma (realToFrac a) 1\n-- gama2 <- gamma (realToFrac a) 1\n\n\n gamb <- gamma (realToFrac b) 1\n return $ gama1/(gama1+gamb)\n\ntbeta = sampleNIO 100 $ beta 1 1", "meta": {"hexsha": "f0776031fe3788e7fd69dd223057829d5a408113", "size": 12708, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Math/Probably/Sampler.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/Sampler.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/Sampler.hs", "max_forks_repo_name": "glutamate/probably", "max_forks_repo_head_hexsha": "efe7ea91c4b3b363ee9444560766bf03408c1a17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0100755668, "max_line_length": 121, "alphanum_fraction": 0.567516525, "num_tokens": 3627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6610154263142393}} {"text": "module NumberParser\n ( parseNumber\n , parseFloat\n , parseComplex\n ) where\n\nimport Data.Complex\nimport LispVal\nimport Numeric\nimport Text.ParserCombinators.Parsec\n\nparseNumber :: Parser LispVal\nparseNumber = parseDecimal1 <|> parseDecimal2 <|> parseHex <|> parseOct <|> parseBin\n\nparseDecimal1 :: Parser LispVal\nparseDecimal1 = Number . read <$> many1 digit\n\nparseDecimal2 :: Parser LispVal\nparseDecimal2 = 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 (hex2dig x)\n\nparseOct :: Parser LispVal\nparseOct = do\n try $ string \"#o\"\n x <- many1 octDigit\n return $ Number (oct2dig 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\n\nbin2dig' digint \"\" = digint\nbin2dig' digint (x:xs) =\n let old =\n 2 * digint +\n (if x == '0'\n then 0\n else 1)\n in bin2dig' old xs\n\ntoDouble :: LispVal -> Double\ntoDouble (Float f) = realToFrac f\ntoDouble (Number n) = fromIntegral n\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\nparseComplex :: Parser LispVal\nparseComplex = do\n x <- try parseFloat <|> parseDecimal1 <|> parseDecimal2\n char '+'\n y <- try parseFloat <|> parseDecimal1 <|> parseDecimal2\n char 'i'\n return $ Complex (toDouble x :+ toDouble y)\n", "meta": {"hexsha": "ab79be29e21050c431d01a13f071e28f4dec07e6", "size": 1576, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/NumberParser.hs", "max_stars_repo_name": "anushriadhia/haskellScheme", "max_stars_repo_head_hexsha": "af5699685e7a02e3222c5e147778df07b7c564dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/NumberParser.hs", "max_issues_repo_name": "anushriadhia/haskellScheme", "max_issues_repo_head_hexsha": "af5699685e7a02e3222c5e147778df07b7c564dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/NumberParser.hs", "max_forks_repo_name": "anushriadhia/haskellScheme", "max_forks_repo_head_hexsha": "af5699685e7a02e3222c5e147778df07b7c564dd", "max_forks_repo_licenses": ["BSD-3-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.0133333333, "max_line_length": 84, "alphanum_fraction": 0.6592639594, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6601912531626628}} {"text": "module Main where\n\nimport Numeric.LinearAlgebra\nimport LeastSquares\n\nmain :: IO ()\nmain = do\n let a = Mat $ (3><2) [1.0, 1.0, 1.0, 4.0, 2.0, -1.0]\n let b = Vec $ vector [13, 27, 1]\n let x = Var \"x\" 2\n print $ minimize (SumSquares (a * x - b)) []\n -- let a1 = Mat $ (3><1) [1.0, 1.0, 1.0]\n -- let a2 = Mat $ (3><1) [2.0, 4.0, -1.0]\n -- let x1 = Var \"x1\" 1\n -- let x2 = Var \"x2\" 1\n print $ minimize (SumSquares (a * x - b) + 2 * SumSquares x) []\n let c = Mat $ (1><2) [1.0, -1]\n let d = Vec $ vector [2]\n print $ minimize (SumSquares (a * x - b)) [c * x :==: d]\n", "meta": {"hexsha": "002f9ab74ee1d1294548fa41bb30906f7039d202", "size": 572, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Main.hs", "max_stars_repo_name": "tridao/leastsquares", "max_stars_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T05:14:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T05:14:02.000Z", "max_issues_repo_path": "app/Main.hs", "max_issues_repo_name": "tridao/leastsquares", "max_issues_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Main.hs", "max_forks_repo_name": "tridao/leastsquares", "max_forks_repo_head_hexsha": "05847fd78e68892b5af3e12b04200e4ff3ad17e4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-12-13T22:03:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T05:14:09.000Z", "avg_line_length": 28.6, "max_line_length": 65, "alphanum_fraction": 0.5104895105, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6600147507154206}} {"text": "{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule Fields (C, Field (..), Fp, Prime (..), Q, R, Val (..), modInv) where\n\nimport Data.Complex (Complex (..))\nimport Data.Ratio (denominator, numerator)\n\n------------------------------------------------------------------------------\n-- Fields\n\n-- Value information\ndata Val = None | NumDen Integer Integer | ReIm Double Double\n\n-- Field type class\nclass (Eq f, Fractional f, Show f) => Field f where\n {-# MINIMAL char, val #-}\n char :: f -> Integer\n val :: f -> Val\n\n------------------------------------------------------------------------------\n-- Characteristic zero\n\n-- Rational numbers Q\nnewtype Q = Q Rational deriving (Eq, Fractional, Num, Ord)\ninstance Show Q where\n show q = show n ++ if d == 1 then \"\" else \"/\" ++ show d\n where\n NumDen n d = val q\ninstance Field Q where\n char = const 0\n val (Q q) = NumDen (numerator q) (denominator q)\n\n-- Real numbers R\nnewtype R = R Double deriving (Eq, Fractional, Num, Ord)\ninstance Show R where\n show (R r) = if r == fromIntegral r' then show r' else show r\n where\n r' = floor r\ninstance Field R where\n char = const 0\n val = const None\n\n-- Complex numbers C\nnewtype C = C (Complex Double) deriving (Eq, Fractional, Num)\ninstance Show C where\n show (C (r :+ i))\n | signum i == -1 = \"(\" ++ show (R r) ++ \"-\" ++ show (R (abs i)) ++ \"i)\"\n | signum i == 1 = \"(\" ++ show (R r) ++ \"+\" ++ show (R i) ++ \"i)\"\n | otherwise = show (R r)\ninstance Field C where\n char = const 0\n val (C (r :+ i)) = ReIm r i\n\n------------------------------------------------------------------------------\n-- Characteristic prime\n\n-- Prime numbers\nclass (Enum p, Show p) => Prime p where\n prime :: p -> Integer\n prime _ = read . tail . show $ (toEnum 0 :: p)\n\n-- Prime subfields Fp\nnewtype Fp p = Fp Integer\n\n-- Fp field instance\ninstance Prime p => Field (Fp p) where\n char = const $ prime (undefined :: p)\n val = const None\n\n-- Fp standard instances\ninstance Prime p => Bounded (Fp p) where\n minBound = 0\n maxBound = -1\ninstance Prime p => Enum (Fp p) where\n toEnum = fromIntegral\n fromEnum (Fp n) = fromInteger n\ninstance Eq (Fp p) where\n Fp n == Fp n' = fromInteger n == fromInteger n'\ninstance Prime p => Fractional (Fp p) where\n fromRational n = fromInteger (numerator n) / fromInteger (denominator n)\n recip (Fp n) = case modInv n $ prime (undefined :: p) of\n Right m -> fromIntegral m\n Left m -> error $ show m\ninstance Prime p => Integral (Fp p) where\n quotRem (Fp n) (Fp n') = (fromInteger q, fromInteger r)\n where\n (q, r) = quotRem n n'\n toInteger (Fp n) = fromInteger n\ninstance Prime p => Num (Fp p) where\n Fp n + Fp n' = fromInteger $ n + n'\n Fp n * Fp n' = fromInteger $ n * n'\n abs n = n\n signum n = if n == 0 then 0 else 1\n fromInteger n = Fp . mod n $ prime (undefined :: p)\n negate (Fp n) = fromInteger $ (-n)\ninstance Ord (Fp p) where\n Fp n <= Fp n' = n <= n'\ninstance Prime p => Real (Fp p) where\n toRational (Fp n) = fromInteger n\ninstance Show (Fp p) where\n show (Fp n) = show n\n\n-- Extended Euclidean algorithm\nextGCD :: Integral a => a -> a -> ((a, a), a)\nextGCD 0 y = ((0, 1), y)\nextGCD x y = ((t - s * q, s), g)\n where\n (q, r) = quotRem y x\n ((s, t), g) = extGCD r x\n\n-- Modular inverse\nmodInv :: Integral a => a -> a -> Either a a\nmodInv x p = if g == 1 then return (mod y p) else Left g\n where\n ((y, _), g) = extGCD x p", "meta": {"hexsha": "965571cc19e0e916bb58a9e058b4cf6e988d5d5b", "size": 3433, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "urop/hs/Fields.hs", "max_stars_repo_name": "Multramate/EllipticCurves", "max_stars_repo_head_hexsha": "f46652e975c1d7af5977fc0f2b5b845972eec63d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-19T17:04:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T08:58:48.000Z", "max_issues_repo_path": "urop/hs/Fields.hs", "max_issues_repo_name": "Multramate/EllipticCurves", "max_issues_repo_head_hexsha": "f46652e975c1d7af5977fc0f2b5b845972eec63d", "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": "urop/hs/Fields.hs", "max_forks_repo_name": "Multramate/EllipticCurves", "max_forks_repo_head_hexsha": "f46652e975c1d7af5977fc0f2b5b845972eec63d", "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.5948275862, "max_line_length": 78, "alphanum_fraction": 0.5709292164, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6594398142868971}} {"text": "module Main where\n\nimport Graphics.Rendering.Chart.Easy\nimport Graphics.Rendering.Chart.Backend.Cairo\n\nimport Statistics.Distribution.Normal\nimport Statistics.Distribution\n\n-- pOak = class1\n-- pBeech = class2\n\nstdDevOak :: NormalDistribution\nstdDevOak = normalDistr (- 2.25) 1\n\nstdDevBeech :: NormalDistribution\nstdDevBeech = normalDistr 1.596 1\n\ntype Priori = Double\n\npOak :: Priori\npOak = 0.25\n\npBeech :: Priori\npBeech = 0.75\n\noak :: [Double] -> [(Double,Double)]\noak xs = [ (x,(density stdDevOak x) * pOak) | x <- xs ]\n\nbeech :: [Double] -> [(Double, Double)]\nbeech xs = [ (x,(density stdDevBeech x) * pBeech) | x <- xs ]\n\nidentit :: [Double] -> [(Double, Double)]\nidentit xs = [(x, x) | x <- xs]\n\nincrements :: Double -> Double -> Double -> [Double]\nincrements from to inc\n | from > to = []\n | otherwise = (from):(increments (from + inc) to inc)\n\n--main = print $ (increments (-5) 5 0.1)\n\nmain = toFile def \"output.png\" $ do\n layout_title .= \"KMeans\"\n setShapes [PointShapeCircle, PointShapePlus, PointShapeStar]\n setColors [opaque blue, opaque red]\n plot (points \"class2\" $ beech (increments (-5) 5 0.1))\n plot (line \"class1\" [oak (increments (-5) 5 0.1)])", "meta": {"hexsha": "a48cae5c183c1348f2da4431ae6f37b5a3797bf9", "size": 1182, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "paper/utils/plot.hs", "max_stars_repo_name": "Parrows/Parrows", "max_stars_repo_head_hexsha": "163964988c07a37f19a805816ea71efab9970616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-25T17:08:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T15:07:57.000Z", "max_issues_repo_path": "paper/utils/plot.hs", "max_issues_repo_name": "Parrows/Parrows", "max_issues_repo_head_hexsha": "163964988c07a37f19a805816ea71efab9970616", "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": "paper/utils/plot.hs", "max_forks_repo_name": "Parrows/Parrows", "max_forks_repo_head_hexsha": "163964988c07a37f19a805816ea71efab9970616", "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.1489361702, "max_line_length": 64, "alphanum_fraction": 0.665820643, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384595, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6593568483177842}} {"text": "{-# OPTIONS_GHC -Wall #-}\n\nmodule Numeric.FFT.HMatrix.Vector (\n -- * Complex-to-complex transforms\n dft\n , idft\n -- * Real-to-complex transforms\n , dftR2C\n , dftC2R\n -- * Real-to-real transforms\n -- ** Discrete cosine transforms\n , dct1\n , dct2\n , dct3\n , dct4\n -- ** Discrete sine transforms\n , dst1\n , dst2\n , dst3\n , dst4\n ) where\n\nimport Foreign.Storable ( Storable )\nimport Numeric.LinearAlgebra.Data ( Vector, Complex )\nimport Numeric.LinearAlgebra ( Element )\nimport qualified Numeric.LinearAlgebra.Data as M\nimport qualified Numeric.FFT.Vector.Unnormalized as FFT\n\ndft :: Vector (Complex Double) -> Vector (Complex Double)\ndft = FFT.run FFT.dft\n\nidft :: Vector (Complex Double) -> Vector (Complex Double)\nidft = FFT.run FFT.idft\n\ndftR2C :: Vector Double -> Vector (Complex Double)\ndftR2C = FFT.run FFT.dftR2C\n\ndftC2R :: Vector (Complex Double) -> Vector Double\ndftC2R = FFT.run FFT.dftC2R\n\ndct1 :: Vector Double -> Vector Double\ndct1 = FFT.run FFT.dct1\n\ndct2 :: Vector Double -> Vector Double\ndct2 = FFT.run FFT.dct2\n\ndct3 :: Vector Double -> Vector Double\ndct3 = FFT.run FFT.dct3\n\ndct4 :: Vector Double -> Vector Double\ndct4 = FFT.run FFT.dct4\n\ndst1 :: Vector Double -> Vector Double\ndst1 = FFT.run FFT.dst1\n\ndst2 :: Vector Double -> Vector Double\ndst2 = FFT.run FFT.dst2\n\ndst3 :: Vector Double -> Vector Double\ndst3 = FFT.run FFT.dst3\n\ndst4 :: Vector Double -> Vector Double\ndst4 = FFT.run FFT.dst4\n", "meta": {"hexsha": "6ac5bf625392f750958a4102d8c09d70e647d38e", "size": 1435, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/FFT/HMatrix/Vector.hs", "max_stars_repo_name": "peddie/hmatrix-fftw", "max_stars_repo_head_hexsha": "53a8033b605ede41ec7b41a05b5ad63775c84bdb", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/FFT/HMatrix/Vector.hs", "max_issues_repo_name": "peddie/hmatrix-fftw", "max_issues_repo_head_hexsha": "53a8033b605ede41ec7b41a05b5ad63775c84bdb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/FFT/HMatrix/Vector.hs", "max_forks_repo_name": "peddie/hmatrix-fftw", "max_forks_repo_head_hexsha": "53a8033b605ede41ec7b41a05b5ad63775c84bdb", "max_forks_repo_licenses": ["BSD-3-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.421875, "max_line_length": 58, "alphanum_fraction": 0.6975609756, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6593568406086062}} {"text": "-- | authors: Connor Ford, Jake Hauser\n\nmodule Persistence where \n\nimport Data.List (intercalate)\nimport Numeric.LinearAlgebra\nimport Data.List.HT (mapAdjacent)\nimport ExplicitSimplexStream\n\n-- Betti Vector\n-- This data type is equivalent to a list of Ints. It represents the betti vector.\n-- For a betti vector of length n, all betti numbers b_i such that i >= n are assumed to be 0.\ndata BettiVector = BettiVector [Int] deriving (Eq)\n\ninstance Show BettiVector where\n show (BettiVector []) = \"()\"\n show (BettiVector vs) = \"(\" ++ intercalate \", \" (map show vs) ++ \")\"\n\n-- getBoundaryMapHelper (see: getBoundaryMap)\n-- First argument is SimplexListByDegree representing C_k\n-- Second argument is SimplexListByDegree representing C_k+1\n-- Third argument should initially be the length of the x in (x:xs) for C_k+1. It it a counter for removing elements from x.\n-- Fourth argument should initially be zero. It is a counter for the index of x in (x:xs).\n-- Fifth argument should be the zero matrix for _correct_ boundary map calculations.\ngetBoundaryMapHelper :: (Ord a) => SimplexListByDegree a -> SimplexListByDegree a -> Int -> Int -> Matrix Double -> Matrix Double\ngetBoundaryMapHelper _ (SimplexListByDegree _ []) _ _ mat = mat\ngetBoundaryMapHelper list1 (SimplexListByDegree n (_:xs)) 0 k mat = getBoundaryMapHelper list1 (SimplexListByDegree n (xs)) n (k+1) mat\ngetBoundaryMapHelper list1 (SimplexListByDegree n (x:xs)) m k mat = \n let \n x_dim = indexOfSimplex (Simplex (removeSimplexElement x (m-1))) list1\n y_dim = k\n val = (-1)^(m-1)\n updatedMatrix = accum mat (\\a _ -> a) [((x_dim,y_dim), val)] -- use accumulator to change values of matrix\n in \n getBoundaryMapHelper list1 (SimplexListByDegree n (x:xs)) (m-1) k updatedMatrix\n\n-- getBoundaryMap\n-- First argument C_k\n-- Second argument C_k+1\n-- return matrix dimensions: len(C_k) = num rows, len(C_k+1) = num cols\n-- algorithm: \n-- Given element of C_k+1, y, remove i'th element from y (starting with index zero) to get element in C_k called x. \n-- Then the value in the matrix at row idxOf(x) and column idxOf(y) is (-1)^i.\ngetBoundaryMap :: (Ord a) => SimplexListByDegree a -> SimplexListByDegree a -> Matrix Double\ngetBoundaryMap list1@(SimplexListByDegree _ simps1) list2@(SimplexListByDegree n simps2) = \n let \n zero_matrix = matrix (length simps2) (replicate ((length simps1)*(length simps2)) 0)\n in\n getBoundaryMapHelper list1 list2 n 0 zero_matrix\n\n-- getHomologyDimension\n-- first arg is D_i+1\n-- second arg is D_i \n-- third argument k (or i in the below illustration)\n-- want to find: dim ker D_i - dim im D_i+1\n-- algorithm to find ker and im:\n-- (i) rref matrix \n-- (ii) # of non-zero rows correspond to rnk of original matrix.\n-- (iii) # of columns with leading 1’s correspond to the columns of original matrix that span image.\n-- (iv) dim ker = (ii) - (iii)\ngetHomologyDimension :: Matrix Double -> Matrix Double -> Int -> Int \ngetHomologyDimension m1 m2 k = \n let \n m1_rank = rank m1 \n m2_columns = cols m2 \n m2_rank = rank m2 \n m2_nullity = m2_columns - m2_rank\n in \n if k > 0 then \n m2_nullity - m1_rank \n else \n m2_columns - m1_rank\n\n-- persistenceHelper (see: persistence)\n-- First argument is a list of matrices representing a sequence of boundary maps.\n-- Second argument is k representing the k'th homology.\npersistenceHelper :: [Matrix Double] -> Int -> [Int]\npersistenceHelper [] _ = []\npersistenceHelper [x] k = [getHomologyDimension ((ident 1) - (ident 1)) x k] -- base case for last boundary map\npersistenceHelper (x:y:xs) k = (getHomologyDimension y x k):(persistenceHelper (y:xs) (k+1))\n\n-- persistence\n-- The persistence algorithm computes the BettiVector for s simplex stream. The algorithm is as follows: \n-- Given a simplex stream, and a field coefficient p corresponding to Z/pZ we will return betti numbers (b_0, b_1, ..., b_n) where n+1 equals the degree of the highest order simplex in the stream. \n-- (1) Get simplex lists ordered by the degree of simplices\n-- (2) Get boundary maps D_0, ..., D_{n-1} such that:\n-- 0 <-- C_0 <-- C_1 <-- ... <-- C_{n-1} <-- C_n <-- 0\n-- D_{-1} D_0 D_1 D_{n-1}\n-- (3) Compute dimensions of the Homologies:\n-- dim H_0 = dim Ker 0 - dim Im D_0\n-- dim H_1 = dim Ker D_0 - dim Im D_1 \n-- ...\n-- dim H_n = dim Ker D_{n-1} - dim Im 0\n-- (4) return betti profile (dim H_0, dim H_1, ..., dim H_n)\n-- TODO: implement with rref mod p where Field = Z/pZ.\npersistence :: (Ord a) => Stream a -> Int -> BettiVector\npersistence stream field = \n let \n (OrderedSimplexList l) = streamToOrderedSimplexList stream \n in \n BettiVector $ persistenceHelper (mapAdjacent getBoundaryMap l) 0", "meta": {"hexsha": "c6872ea3058ac8046d7162a5b1409af7801286c8", "size": 4793, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "library/Persistence.hs", "max_stars_repo_name": "Pomona-College-CS181-SP2020/HaskellPlex", "max_stars_repo_head_hexsha": "b609edd689d34eae013bc67257f75d4213dcc5aa", "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/Persistence.hs", "max_issues_repo_name": "Pomona-College-CS181-SP2020/HaskellPlex", "max_issues_repo_head_hexsha": "b609edd689d34eae013bc67257f75d4213dcc5aa", "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/Persistence.hs", "max_forks_repo_name": "Pomona-College-CS181-SP2020/HaskellPlex", "max_forks_repo_head_hexsha": "b609edd689d34eae013bc67257f75d4213dcc5aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4554455446, "max_line_length": 197, "alphanum_fraction": 0.6880867932, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6590870019606817}} {"text": "{-|\nModule : ControlSystems.DynamicSystems.Conversion\nDescription : Converts continuous time systems to discrete time\nCopyright : (c) Ryan Orendorff, 2020\nLicense : BSD3\nStability : experimental\n-}\nmodule ControlSystems.DynamicSystems.Conversions (\n c2d\n)\n\nwhere\n\nimport Numeric.LinearAlgebra\n\n-- | Convert a continuous time linear differential system to a discrete form,\n-- using state space models.\nc2d :: Double -- ^ The sampling time\n -> Matrix Double -- ^ The state transition matrix, aka A\n -> Matrix Double -- ^ The state input matrix, aka B\n -> (Matrix Double, Matrix Double) -- ^ The discretized A & B system\nc2d t a b = (a_d, b_d)\n where\n -- First we have to extract the sizes of all the matrices at run time.\n (m_a, n_a) = (rows a, cols a)\n (_ , n_b) = (rows b, cols b)\n\n -- Then manually make the correct block. This must be a square matrix\n -- because the matrix exponential function (`expm`) expects to only have\n -- square inputs (given that it is a series expansion of matrix to higher\n -- powers). We need to form this matrix\n -- ⌈ A B ⌉\n -- ⌊ 0 0 ⌋\n block = a ||| b\n ===\n konst 0 (m_a, n_a + n_b) -- I left in a bug here! ;-D\n\n -- Calculate the discrete time block matrix, which is the following\n -- ⌈ A_d B_d ⌉\n -- ⌊ 0 I ⌋\n exp_block = expm (scale t block)\n\n -- Finally we can extract the correct submatrices assuming we pull out the\n -- right pieces.\n a_d = subMatrix (0, 0) (m_a, n_a) exp_block\n b_d = subMatrix (0, n_a) (m_a, n_b) exp_block\n", "meta": {"hexsha": "d9884edb61a1b87efa3284d97c454890494dda83", "size": 1630, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ControlSystems/DynamicSystems/Conversions.hs", "max_stars_repo_name": "ryanorendorff/convex", "max_stars_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-06-13T21:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T15:53:28.000Z", "max_issues_repo_path": "src/ControlSystems/DynamicSystems/Conversions.hs", "max_issues_repo_name": "ryanorendorff/convex", "max_issues_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ControlSystems/DynamicSystems/Conversions.hs", "max_forks_repo_name": "ryanorendorff/convex", "max_forks_repo_head_hexsha": "e92ad63061efcce417b8c684c55cf8191e6dceae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6808510638, "max_line_length": 78, "alphanum_fraction": 0.6239263804, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6585576067363975}} {"text": "\n-- | RVM regression model\nmodule Numeric.BMML.RVMR\n ( fit\n , predict\n ) where\n\nimport Numeric.LinearAlgebra.Data (Matrix, Vector)\nimport qualified Numeric.LinearAlgebra.HMatrix as H\n\ndata RVMRModel = RVMRModel\n { mean :: Vector Double\n , covariance :: Matrix Double\n , optbeta :: Double\n }\n\ninitAlpha :: Int -> Vector Double\ninitAlpha m = H.konst 1.0e-3 m\n\ninitBeta :: Double\ninitBeta = 1.0e-3\n\nfit :: Matrix Double -> Vector Double -> RVMRModel\nfit x t =\n let (_,d) = H.size x\n alpha = initAlpha d\n beta = initBeta\n sigma = calcSigma alpha beta x\n m = calcMean beta sigma x t\n in go 10000 alpha beta sigma m\n where\n go 0 _ beta sigma m =\n RVMRModel\n { mean = m\n , covariance = sigma\n , optbeta = beta\n }\n go k alpha beta sigma m = if sNorm alpha na < 0.01\n then go 0 na nb ns nm\n else go (k - 1) na nb ns nm\n where\n (n,d) = H.size x\n gamma :: Vector Double\n gamma = (H.konst 1 d) - (alpha * (H.takeDiag sigma))\n na :: Vector Double\n na =\n H.fromList\n (zipWith\n (\\gi mi ->\n gi / (mi * mi))\n (H.toList gamma)\n (H.toList m))\n nb :: Double\n nb = normSq (t - x H.#> m) / (fromIntegral n - H.sumElements gamma)\n ns = calcSigma na nb x\n nm = calcMean nb ns x t\n\nsNorm :: Vector Double -> Vector Double -> Double\nsNorm x y =\n sqrt\n (foldr\n (\\(xi,yi) res ->\n res + (yi - xi) * (yi - xi))\n 0\n (filter\n (\\(xi,yi) ->\n xi < 10000 && yi < 10000)\n (zip (H.toList x) (H.toList y))))\n{-# INLINE sNorm #-}\n\ncalcSigma :: Vector Double -> Double -> Matrix Double -> Matrix Double\ncalcSigma a b x = H.inv (H.diag a + b `H.scale` (H.tr x H.<> x))\n{-# INLINE calcSigma #-}\n\ncalcMean :: Double\n -> Matrix Double\n -> Matrix Double\n -> Vector Double\n -> Vector Double\ncalcMean b s x t = b `H.scale` ((s H.<> H.tr x) H.#> t)\n{-# INLINE calcMean #-}\n\nnormSq :: Vector Double -> Double\nnormSq v = v `H.dot` v\n{-# INLINE normSq #-}\n\npredict :: RVMRModel -> Vector Double -> (Double, Double)\npredict (RVMRModel m sigma ob) v =\n (m `H.dot` v, 1 / ob + v `H.dot` (sigma H.#> v))\n", "meta": {"hexsha": "0fef767e6fa8ce2bc4c65129dbf616283b788c2b", "size": 2444, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/BMML/RVMR.hs", "max_stars_repo_name": "DbIHbKA/BMML", "max_stars_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/BMML/RVMR.hs", "max_issues_repo_name": "DbIHbKA/BMML", "max_issues_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/BMML/RVMR.hs", "max_forks_repo_name": "DbIHbKA/BMML", "max_forks_repo_head_hexsha": "1ed44258bacf91a1319a34f50d0ebcc6e5bbaef9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1555555556, "max_line_length": 75, "alphanum_fraction": 0.5016366612, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.658340025453329}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}\n-- |\n-- Module : Statistics.Distribution.Exponential\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The exponential distribution. This is the continuous probability\n-- distribution of the times between events in a poisson process, in\n-- which events occur continuously and independently at a constant\n-- average rate.\n\nmodule Statistics.Distribution.Exponential\n (\n ExponentialDistribution\n -- * Constructors\n , exponential\n , exponentialE\n -- * Accessors\n , edLambda\n ) where\n\nimport Control.Applicative\nimport Data.Aeson (FromJSON(..),ToJSON,Value(..),(.:))\nimport Data.Binary (Binary, put, get)\nimport Data.Data (Data, Typeable)\nimport GHC.Generics (Generic)\nimport Numeric.SpecFunctions (log1p)\nimport Numeric.MathFunctions.Constants (m_neg_inf)\nimport qualified System.Random.MWC.Distributions as MWC\nimport qualified Data.Vector.Generic as G\n\nimport qualified Statistics.Distribution as D\nimport qualified Statistics.Sample as S\nimport Statistics.Internal\n\n\n\nnewtype ExponentialDistribution = ED {\n edLambda :: Double\n } deriving (Eq, Typeable, Data, Generic)\n\ninstance Show ExponentialDistribution where\n showsPrec n (ED l) = defaultShow1 \"exponential\" l n\ninstance Read ExponentialDistribution where\n readPrec = defaultReadPrecM1 \"exponential\" exponentialE\n\ninstance ToJSON ExponentialDistribution\ninstance FromJSON ExponentialDistribution where\n parseJSON (Object v) = do\n l <- v .: \"edLambda\"\n maybe (fail $ errMsg l) return $ exponentialE l\n parseJSON _ = empty\n\ninstance Binary ExponentialDistribution where\n put = put . edLambda\n get = do\n l <- get\n maybe (fail $ errMsg l) return $ exponentialE l\n\ninstance D.Distribution ExponentialDistribution where\n cumulative = cumulative\n complCumulative = complCumulative\n\ninstance D.ContDistr ExponentialDistribution where\n density (ED l) x\n | x < 0 = 0\n | otherwise = l * exp (-l * x)\n logDensity (ED l) x\n | x < 0 = m_neg_inf\n | otherwise = log l + (-l * x)\n quantile = quantile\n complQuantile = complQuantile\n\ninstance D.Mean ExponentialDistribution where\n mean (ED l) = 1 / l\n\ninstance D.Variance ExponentialDistribution where\n variance (ED l) = 1 / (l * l)\n\ninstance D.MaybeMean ExponentialDistribution where\n maybeMean = Just . D.mean\n\ninstance D.MaybeVariance ExponentialDistribution where\n maybeStdDev = Just . D.stdDev\n maybeVariance = Just . D.variance\n\ninstance D.Entropy ExponentialDistribution where\n entropy (ED l) = 1 - log l\n\ninstance D.MaybeEntropy ExponentialDistribution where\n maybeEntropy = Just . D.entropy\n\ninstance D.ContGen ExponentialDistribution where\n genContVar = MWC.exponential . edLambda\n\ncumulative :: ExponentialDistribution -> Double -> Double\ncumulative (ED l) x | x <= 0 = 0\n | otherwise = 1 - exp (-l * x)\n\ncomplCumulative :: ExponentialDistribution -> Double -> Double\ncomplCumulative (ED l) x | x <= 0 = 1\n | otherwise = exp (-l * x)\n\n\nquantile :: ExponentialDistribution -> Double -> Double\nquantile (ED l) p\n | p >= 0 && p <= 1 = - log1p(-p) / l\n | otherwise =\n error $ \"Statistics.Distribution.Exponential.quantile: p must be in [0,1] range. Got: \"++show p\n\ncomplQuantile :: ExponentialDistribution -> Double -> Double\ncomplQuantile (ED l) p\n | p == 0 = 0\n | p >= 0 && p < 1 = -log p / l\n | otherwise =\n error $ \"Statistics.Distribution.Exponential.quantile: p must be in [0,1] range. Got: \"++show p\n\n-- | Create an exponential distribution.\nexponential :: Double -- ^ Rate parameter.\n -> ExponentialDistribution\nexponential l = maybe (error $ errMsg l) id $ exponentialE l\n\n-- | Create an exponential distribution.\nexponentialE :: Double -- ^ Rate parameter.\n -> Maybe ExponentialDistribution\nexponentialE l\n | l > 0 = Just (ED l)\n | otherwise = Nothing\n\nerrMsg :: Double -> String\nerrMsg l = \"Statistics.Distribution.Exponential.exponential: scale parameter must be positive. Got \" ++ show l\n\n-- | Create exponential distribution from sample. Returns @Nothing@ if\n-- sample is empty or contains negative elements. No other tests are\n-- made to check whether it truly is exponential.\ninstance D.FromSample ExponentialDistribution Double where\n fromSample xs\n | G.null xs = Nothing\n | G.all (>= 0) xs = Nothing\n | otherwise = Just $! ED (S.mean xs)\n", "meta": {"hexsha": "357e5ff744f85061fe9c6490b360e4570b1e66df", "size": 4792, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution/Exponential.hs", "max_stars_repo_name": "intricate/statistics", "max_stars_repo_head_hexsha": "7ac06d597eefb2c42dd3b726c8f5cb17e54f72d7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Statistics/Distribution/Exponential.hs", "max_issues_repo_name": "intricate/statistics", "max_issues_repo_head_hexsha": "7ac06d597eefb2c42dd3b726c8f5cb17e54f72d7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Distribution/Exponential.hs", "max_forks_repo_name": "intricate/statistics", "max_forks_repo_head_hexsha": "7ac06d597eefb2c42dd3b726c8f5cb17e54f72d7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5986394558, "max_line_length": 110, "alphanum_fraction": 0.6773789649, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6581729933242572}} {"text": "{-|\nModule: MachineLearning.Optimization.GradientDescent\nDescription: Gradient Descent\nCopyright: (c) Alexander Ignatyev, 2016\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\n-}\n\nmodule MachineLearning.Optimization.GradientDescent\n(\n gradientDescent\n)\n\nwhere\n\nimport MachineLearning.Types (R, Vector, Matrix)\nimport MachineLearning.Regularization (Regularization)\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as LA\n\nimport qualified MachineLearning.Model as Model\n\n-- | Gradient Descent method implementation. See \"MachineLearning.Regression\" for usage details.\ngradientDescent :: Model.Model a => R-> a -> R -> Int -> Regularization -> Matrix -> Vector -> Vector -> (Vector, Matrix)\ngradientDescent alpha model eps maxIters lambda x y theta = helper theta maxIters []\n where gradient = Model.gradient model lambda\n cost = Model.cost model lambda\n helper theta nIters optPath =\n let theta' = theta - (LA.scale alpha (gradient x y theta))\n j = cost x y theta'\n gradientTest = LA.norm_2 (theta' - theta) < eps\n optPathRow = V.concat [LA.vector [(fromIntegral $ maxIters - nIters), j], theta']\n optPath' = optPathRow : optPath\n in if gradientTest || nIters <= 1\n then (theta, LA.fromRows $ reverse optPath')\n else helper theta' (nIters - 1) optPath'\n", "meta": {"hexsha": "120ff74b48ebbd0e75e2df8ff39b79da9ed3c27b", "size": 1405, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/Optimization/GradientDescent.hs", "max_stars_repo_name": "aligusnet/mltool", "max_stars_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2018-08-20T16:39:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T08:06:10.000Z", "max_issues_repo_path": "src/MachineLearning/Optimization/GradientDescent.hs", "max_issues_repo_name": "aligusnet/mltool", "max_issues_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-08T11:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-08T11:16:23.000Z", "max_forks_repo_path": "src/MachineLearning/Optimization/GradientDescent.hs", "max_forks_repo_name": "aligusnet/mltool", "max_forks_repo_head_hexsha": "92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-01-04T00:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T18:01:57.000Z", "avg_line_length": 36.0256410256, "max_line_length": 121, "alphanum_fraction": 0.7003558719, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.657934339927602}} {"text": "module Lib.Practice.P3 where\n\nimport Control.Monad\nimport Numeric.LinearAlgebra\n\nf3 = do\n let gates = [(\"AND\", gAnd), (\"NAND\", gNand), (\"OR\", gOr)]\n mapM_ showOutput gates\n\ngAnd = Neuron { weight = vector [0.5, 0.5], bias = -0.7 }\ngNand = Neuron { weight = vector [-0.5, -0.5], bias = 0.7 }\ngOr = Neuron { weight = vector [0.5, 0.5], bias = -0.2 }\n\ninputs = replicateM 2 [NotFire, Fire]\nshowOutput (name, gate) = do\n putStrLn $ name ++ \"ゲート\"\n mapM_ (showOutput' gate) inputs\n putStrLn \"\"\n where\n showOutput' gate input = do\n let result = input --> gate\n putStrLn $ show input ++ \" -> \" ++ show result\n\ndata Neuron = Neuron {\n weight :: Vector R,\n bias :: R\n} deriving Show\n\ndata Input = Fire | NotFire deriving Show\ninput2Int Fire = 1\ninput2Int NotFire = 0\n\n(-->) = output\noutput :: [Input] -> Neuron -> Input\noutput inputs Neuron { weight = w, bias = b } = result\n where inputV = fromList $ map input2Int inputs\n sum' = sumElements $ inputV * w\n result' = b + sum'\n result = case () of\n _ | result' >= 0 -> Fire \n otherwise -> NotFire\n", "meta": {"hexsha": "1d4520db7dca511efa10c873aca61eab0d334e8b", "size": 1167, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib/Practice/P3.hs", "max_stars_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_stars_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-25T06:16:37.000Z", "max_issues_repo_path": "src/Lib/Practice/P3.hs", "max_issues_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_issues_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-01-04T02:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-09T12:39:40.000Z", "max_forks_repo_path": "src/Lib/Practice/P3.hs", "max_forks_repo_name": "spinylobster/my-deep-learning-from-scratch-in-haskell", "max_forks_repo_head_hexsha": "a8396281033926ef6f3794c490c6674f349fc206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-20T03:39:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T03:39:47.000Z", "avg_line_length": 27.7857142857, "max_line_length": 61, "alphanum_fraction": 0.5698371894, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6573103927905718}} {"text": "module Quantum where\n\nimport Data.AdditiveGroup\nimport Data.Complex hiding ((:+))\nimport qualified Data.Complex as C (Complex ((:+)))\nimport Data.Foldable (foldl')\nimport Data.VectorSpace hiding (magnitude)\nimport Lib\nimport Matrix\nimport Vector\n\n-- base type for qubits\ntype CDouble = Complex Double\n\ntype CVVec n = VVec n CDouble\n\ntype Qubit = CVVec Two\n\ntype NQubits n = CVVec (Exp Two n)\n\n-- for ease of use\nsqtwo :: Floating a => a\nsqtwo = 1 / sqrt 2\n\ni :: Num a => Complex a\ni = 0 C.:+ 1\n\n-- define some basic qubits/vectors, and qubit collections\nbasisVec :: forall n a. (Num a, KnownNat n) => Fin n -> VVec n a\nbasisVec f = generateMat (\\x _ -> fromIntegral $ fromEnum $ x == f)\n\nzero' :: forall n a. (Num a, KnownNat n) => VVec n a\nzero' = basisVec FZero\n\nzero :: Qubit\nzero = zero'\n\none' :: forall n a m. (Num a, KnownNat n, n ~ 'Succ m) => VVec n a\none' = basisVec (FSucc FZero)\n\none :: Qubit\none = one'\n\nplus :: Qubit\nplus = sqtwo *^ zero ^+^ sqtwo *^ one\n\nminus :: Qubit\nminus = sqtwo *^ zero ^-^ sqtwo *^ one\n\nqubits :: [Qubit]\nqubits = [zero, one, plus, minus]\n\nmakeTwoQubits :: [Qubit] -> [NQubits Two]\nmakeTwoQubits qs = (.*.) <$> qs <*> qs\n\ntwoQubits :: [NQubits Two]\ntwoQubits = makeTwoQubits [zero, one]\n\nconsQubit :: CDouble -> CDouble -> Qubit\nconsQubit a b = numMatFromList [[a], [b]]\n\nconsVVec :: forall n a. (KnownNat n, Num a) => [a] -> VVec n a\nconsVVec ns = numMatFromList @n @One (fmap (: []) ns)\n\n-- define some transformation matrices\npauliX :: Num a => Matrix Two Two a\npauliX = numMatFromList [[0, 1], [1, 0]]\n\npauliY :: RealFloat a => Matrix Two Two (Complex a)\npauliY = numMatFromList [[0, - i], [i, 0]]\n\npauliZ :: Num a => Matrix Two Two a\npauliZ = numMatFromList [[1, 0], [0, -1]]\n\nhadamard :: Floating a => Matrix Two Two a\nhadamard = (* sqtwo) <$> numMatFromList [[1, 1], [1, -1]]\n\n-- a rotation matrix. produces a matrix which rotates by n radians\nrotation :: Floating a => a -> Matrix Two Two a\nrotation n = numMatFromList [[c, - s], [s, c]]\n where\n c = cos n\n s = sin n\n\ncnot :: Num a => Matrix Four Four a\ncnot = numMatFromList [[1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]\n\ncnot' :: Num a => Matrix Four Four a\ncnot' = numMatFromList [[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]\n\niden2 :: Num a => Matrix Two Two a\niden2 = identity\n\nswap :: Num a => Matrix Four Four a\nswap = numMatFromList [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]\n\n-- define the tensor product\ntensorProd ::\n (Num a) => Matrix n m a -> Matrix i j a -> Matrix (Mul n i) (Mul m j) a\ntensorProd n m = expandNested $ fmap (\\a -> fmap (a *) m) n\n\n-- ease of use function for the tensor product\n(.*.) :: (Num a) => Matrix n m a -> Matrix i j a -> Matrix (Mul n i) (Mul m j) a\n(.*.) = tensorProd\n\ninfixr 8 .*.\n\n-- apply the tensor product a number of times.\n-- to use this function, use `tensorPower @(type number) matrix`\n-- for example, to tensor product matrix `a` gate three times, do `tensorPower @Three a`\n-- If used in relation to other matrices, tensorPower can infer\n-- the `i` value, which is pretty neat\n-- Only works on non-vector matrices - see tensorPowerVVec for column vec variant\ntensorPower ::\n forall i a n m.\n (Num a, KnownNat i, i ~ GetExp ('Succ n) i, i ~ GetExp ('Succ m) i) =>\n Matrix ('Succ n) ('Succ m) a ->\n Matrix (Exp ('Succ n) i) (Exp ('Succ m) i) a\ntensorPower m = tensorPower' @i m natSing\n\n-- apply the tensor product a number of times on a column vector\n-- very similar to tensorPower, but only works on column vectors\ntensorPowerVVec ::\n forall i a n.\n (Num a, KnownNat i, i ~ GetExp ('Succ n) i) =>\n Matrix ('Succ n) 'One a ->\n Matrix (Exp ('Succ n) i) (Exp 'One i) a\ntensorPowerVVec m = tensorPower' @i m natSing\n\n-- helper function for tensorPower\ntensorPower' ::\n forall i n m a.\n Num a =>\n Matrix n m a ->\n NatS i ->\n Matrix (Exp n i) (Exp m i) a\ntensorPower' m OneS = m\ntensorPower' m (SuccS s) = m .*. tensorPower' m s\n\n-- transpose and get the conjugate of the given qubit\n-- effectively, find the bra\nconjTrans :: CVVec n -> HVec n CDouble\nconjTrans v = conjugate <$> Matrix.transpose v\n\n-- using conjTrans, find the inner product of two qubits\ninnerProduct :: CVVec n -> CVVec n -> CDouble\ninnerProduct v v' = getVal $ conjTrans v *.* v'\n\n-- generate all basis vectors for a given dimension\ncompBasis' :: forall n a. (Num a, KnownNat n) => Vector n (VVec n a)\ncompBasis' = generateVec basisVec\n\n-- define the computational basis\ncompBasis :: Vector Two Qubit\ncompBasis = compBasis'\n\n-- apply a transformation matrix to the computational basis\ntransformBasis ::\n forall n a. (Num a, KnownNat n) => Matrix n n a -> Vector n (VVec n a)\ntransformBasis m = fmap (m *.*) compBasis'\n\n-- measure in a given basis, returning probabilities for each\n-- basis vector\nmeasureIn :: CVVec m -> Vector n (CVVec m) -> Vector n Double\nmeasureIn v = fmap ((** 2) . magnitude . Quantum.innerProduct v)\n\n-- measure in the computational basis, returning probabilities\n-- for each basis vector\nmeasure :: Qubit -> Vector Two Double\nmeasure v = measureIn v compBasis\n\n-- given a list of vector-probability pairs, return Just the density matrix\n-- if the probabilities sum up to 1; else return Nothing\ngetDensityMatrix ::\n (KnownNat m) => [(CVVec m, CDouble)] -> Maybe (Matrix m m CDouble)\ngetDensityMatrix qs\n | sum (map snd qs) == 1 =\n Just $\n foldr (^+^) zeroed [p *^ f tq | (tq, p) <- qs]\n | otherwise = Nothing\n where\n zeroed = generateMat (\\_ _ -> 0)\n f m = m *.* conjTrans m\n\n-- given a density matrix (as seen in previous function),\n-- and a complex number vector, return the probability of\n-- seeing that vector\ncalcProbability :: Matrix m m CDouble -> CVVec m -> CDouble\ncalcProbability densityMatrix base =\n getVal $ conjTrans base *.* densityMatrix *.* base\n\nchi_f :: CVVec m -> CVVec m -> CDouble\nchi_f s x = (-1) ** Quantum.innerProduct s x\n\n-- vecToFunc :: (KnownNat m) => CVVec m -> Matrix m m CDouble\n-- vecToFunc v =\n-- generateMat (\\f f' -> if f == f' then getAtMatrix f FZero v else 0)\n\n-- fhat :: (KnownNat n) => (CVVec n -> CDouble) -> CVVec n -> CDouble\n-- fhat f s =\n-- (foldl' (\\b a -> b + (apply a)) 0 compBasis') / (2 ** (fst $ Matrix.size s))\n-- where\n-- chi_s = chi s\n-- apply x = (f x) * chi_s x\n\ncreateInput :: Num a => Vector n (VVec m a) -> VVec (Exp m n) a\ncreateInput (VecSing v) = v\ncreateInput (v :+ vs) = v .*. createInput vs\n\nfourierBasis :: (KnownNat n) => Vector n (CVVec n)\nfourierBasis = fmap chi compBasis'\n\nchi :: (KnownNat n) => CVVec n -> CVVec n\nchi s = normalise $ toVVec $ fmap (chi_f s) compBasis'\n\nfhat_f :: (KnownNat n) => CVVec n -> CVVec n -> CDouble\nfhat_f = Quantum.innerProduct\n\nfhat :: (KnownNat n) => CVVec n -> CVVec n\nfhat f = toVVec $ fmap (fhat_f f) fourierBasis\n\nnormalise :: (KnownNat n) => CVVec n -> CVVec n\nnormalise v = v ^/ sqrt (sum $ fmap (abs) v)\n\ngroverDiffusion ::\n forall i a.\n (KnownNat (Exp Two i), KnownNat i, i ~ GetExp Two i, Floating a) =>\n Matrix (Exp Two i) (Exp Two i) a\ngroverDiffusion =\n tensorPower hadamard *.* generateMat f *.* tensorPower hadamard\n where\n f a b\n | a == b && a == FZero = 1\n | a == b = -1\n | otherwise = 0\n\n-- fhat :: (KnownNat n) => CVVec n -> CVVec n -> CDouble\n-- fhat f s\n", "meta": {"hexsha": "68df57adca39cc2e092970bf0e48f7f287720f59", "size": 7225, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Quantum.hs", "max_stars_repo_name": "L0neGamer/matrix-pkg", "max_stars_repo_head_hexsha": "3286cc34b742753142ef698ddac6919c07ec1ed0", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Quantum.hs", "max_issues_repo_name": "L0neGamer/matrix-pkg", "max_issues_repo_head_hexsha": "3286cc34b742753142ef698ddac6919c07ec1ed0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Quantum.hs", "max_forks_repo_name": "L0neGamer/matrix-pkg", "max_forks_repo_head_hexsha": "3286cc34b742753142ef698ddac6919c07ec1ed0", "max_forks_repo_licenses": ["BSD-3-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.230125523, "max_line_length": 88, "alphanum_fraction": 0.6438754325, "num_tokens": 2410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6569897226078554}} {"text": "{-# LANGUAGE Strict #-}\n\nmodule HEP.Util.Polynomial (quarticEqSol, quadEqSol) where\n\nimport Numeric.GSL.Polynomials (polySolve)\n\nimport Data.Complex (imagPart, realPart)\nimport Data.List (nub, sort)\n\n-- | returns the real roots of quartic polynomial equation in ascending order.\n--\n-- It does not return zero roots. Thus, if the roots are empty, it implies\n-- that the polynomial has only zero roots.\nquarticEqSol :: (Double -> Double)\n -> [Double] -- ^ four distinct nonzero inputs\n -> Double -- ^ the cut value for complex roots\n -> Maybe (Int, [Double]) -- ^ (the number of real roots, roots)\nquarticEqSol f xs eps\n | length (filter (/= 0) xs) /= 4 || xs /= nub xs = Nothing\n | otherwise = do\n let roots = filter (\\r -> abs (imagPart r) < eps) $\n polySolve (coeffQuartic f xs)\n realroots = (sort . filter ((> eps) . abs)) $ realPart <$> roots\n return (length realroots, realroots)\n\n-- | returns the coefficients of quartic polynomial\n-- using four distinct nonzero inputs.\n--\n-- a * x^4 + b * x^3 + c * x^2 + d * x + e\n--\n-- the output is the list of the coefficients [e, d, c, b, a].\ncoeffQuartic :: (Double -> Double) -> [Double] -> [Double]\ncoeffQuartic f xs =\n let [x1, x2, x3, x4] = xs\n [f1, f2, f3, f4] = f <$> xs\n\n d1 = x1 * (x2 - x1) * (x3 - x1) * (x4 - x1)\n d2 = x2 * (x2 - x1) * (x3 - x2) * (x4 - x2)\n d3 = x3 * (x3 - x1) * (x3 - x2) * (x4 - x3)\n d4 = x4 * (x4 - x1) * (x4 - x2) * (x4 - x3)\n\n p12 = x1 * x2\n p13 = x1 * x3\n p14 = x1 * x4\n p23 = x2 * x3\n p24 = x2 * x4\n p34 = x3 * x4\n p1234 = p12 * p34\n\n e = f 0\n\n a = - f1 / d1 + f2 / d2 - f3 / d3 + f4 / d4 + e / p1234\n\n b = f1 * (x2 + x3 + x4) / d1\n - f2 * (x4 + x3 + x1) / d2\n + f3 * (x4 + x2 + x1) / d3\n - f4 * (x3 + x2 + x1) / d4\n - e * (x1 + x2 + x3 + x4) / p1234\n\n c = - f1 * (p34 + p24 + p23) / d1\n + f2 * (p34 + p14 + p13) / d2\n - f3 * (p24 + p14 + p12) / d3\n + f4 * (p23 + p13 + p12) / d4\n + e * (p34 + p24 + p14 + p23 + p13 + p12) / p1234\n\n d = f1 * x2 * p34 / d1\n - f2 * x3 * p14 / d2\n + f3 * x4 * p12 / d3\n - f4 * x1 * p23 / d4\n - e * (x2 * p34 + x3 * p14 + x4 * p12 + x1 * p23) / p1234\n in\n [e, d, c, b, a]\n\n-- | the real roots of quadratic equation: a x^2 + b x + c = 0.\n--\n-- If the root x0 is complex and |Im(x0)| < cut, it returns Re(x0).\nquadEqSol :: Double -- ^ the coefficient a\n -> Double -- ^ the coefficient b\n -> Double -- ^ the coefficient c\n -> Double -- ^ the cut value for complex roots\n -> Maybe (Double, Double)\nquadEqSol a b c epsScale = do\n let d = b * b - 4 * a * c\n eps = 1.0e-12\n if d >= 0\n -- then return ((-b + sqrt d) / (2*a), (-b - sqrt d) / (2*a))\n then do let q = -0.5 * (b + signum b * sqrt d)\n return (q / (a + eps), c / (q + eps))\n else do let r = sqrt $ c / (a + eps)\n th = acos $ - b / (2 * sqrt (a * c) + eps)\n x = r * cos th\n if abs (r * sin th) < epsScale\n then return (x, x)\n else Nothing\n", "meta": {"hexsha": "c935f8754f7d2b0a2bf9492d7595a93766881090", "size": 3407, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HEP/Util/Polynomial.hs", "max_stars_repo_name": "cbpark/hep-vector", "max_stars_repo_head_hexsha": "cbf4697a64507e791f756955ab4e621a2c02e0d0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-01T15:39:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T15:39:37.000Z", "max_issues_repo_path": "src/HEP/Util/Polynomial.hs", "max_issues_repo_name": "cbpark/hep-vector", "max_issues_repo_head_hexsha": "cbf4697a64507e791f756955ab4e621a2c02e0d0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HEP/Util/Polynomial.hs", "max_forks_repo_name": "cbpark/hep-vector", "max_forks_repo_head_hexsha": "cbf4697a64507e791f756955ab4e621a2c02e0d0", "max_forks_repo_licenses": ["BSD-3-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.8631578947, "max_line_length": 78, "alphanum_fraction": 0.4549457, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.656719203497105}} {"text": "-- might not work if module is not installed, possible fix is to place the file in \n-- hnn-master root folder\n\nimport AI.HNN.FF.ComplexNetwork\nimport Numeric.LinearAlgebra\nimport Data.Complex\nimport System.Random.MWC\nimport Foreign.Storable (Storable)\n\n\nsamplesXOR :: Samples (Complex Double)\nsamplesXOR = [ (fromList [(-1):+ (-1)], fromList [1:+0])\n , (fromList [(-1):+1], fromList [0:+0])\n , (fromList [1:+(-1)], fromList [1:+1])\n , (fromList [1:+1], fromList [0:+1])\n ]\n\nreal' :: (Floating a) => Complex a -> Complex a\nreal' (x :+ y) = x :+ 0\n\nmapComplex :: (Complex a -> a) -> (Complex a -> a) -> Complex a -> Complex a\nmapComplex f g z = (f z) :+ (g z)\n\nquarters :: (Floating a, Ord a, RealFloat a) => Complex a -> Complex a\nquarters (x :+ y) = (if x > 0 then 1 else 0) :+ (if y > 0 then 1 else 0)\n\nmakeSamples :: (Floating a, Variate a, Storable a) => Int -> (Complex a -> Complex a) -> IO (Samples (Complex a))\nmakeSamples 0 _ = return []\nmakeSamples n f = do\n z <- randComplex\n lst <- makeSamples (n-1) f\n return ((fromList [z], fromList [f(z)]) : lst)\n\n\n-- uncomment relevant sections for different tests\nmain :: IO ()\nmain = do\n -- Complex XOR:\n --mapM_ (putStrLn . show ) samplesXOR\n --n <- createComplexNetwork 1 [2] 1 :: IO (ComplexNetwork (Complex Double))\n --putStrLn $ show n\n --putStrLn \"------------------\"\n --let n' = trainNTimes 1000 0.8 complexSigmoid complexSigmoid' n samplesXOR\n --mapM_ (putStrLn . show . output n' complexSigmoid . fst) samplesXOR\n --putStrLn \"------------\"\n --putStrLn $ show n'\n\n -- Quarters on plane:\n --samples <- makeSamples 50 quarters\n --test <- makeSamples 10 quarters\n --mapM_ (putStrLn . show ) test\n --n <- createComplexNetwork 1 [2] 1 :: IO (ComplexNetwork (Complex Double))\n --putStrLn $ show n\n --putStrLn \"------------------\"\n --let n' = trainNTimes 1000 0.8 complexSigmoid complexSigmoid' n samples\n --mapM_ (putStrLn . show . output n' complexSigmoid . fst) test\n --putStrLn \"------------\"\n --putStrLn $ show n'\n\n -- Parabolas on plane: \n let h1 (x :+ y) = if x > 0.5*x^2 -0.5 then 1 else 0\n let h2 (x :+ y) = if y > -0.5*x^2 +0.5 then 1 else 0\n \n samples <- makeSamples 1000 (mapComplex h1 h2)\n test <- makeSamples 10 (mapComplex h1 h2 )\n\n mapM_ (putStrLn . show ) test\n n <- createComplexNetwork 1 [20] 1 :: IO (ComplexNetwork (Complex Double))\n let n' = trainNTimes 1 0.5 complexSigmoid complexSigmoid' n samples\n\n mapM_ (putStrLn . show . output n' complexSigmoid . fst) test\n", "meta": {"hexsha": "6a51bf184e0e7431f7bddbb2aee0b992eaa68afa", "size": 2519, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/cff/TestComplex.hs", "max_stars_repo_name": "EditResearch/HsANN", "max_stars_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 98, "max_stars_repo_stars_event_min_datetime": "2015-01-15T08:32:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T07:31:55.000Z", "max_issues_repo_path": "examples/cff/TestComplex.hs", "max_issues_repo_name": "EditResearch/HsANN", "max_issues_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-03-13T05:01:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-15T19:26:01.000Z", "max_forks_repo_path": "examples/cff/TestComplex.hs", "max_forks_repo_name": "EditResearch/HsANN", "max_forks_repo_head_hexsha": "5715560bfb289390dc7d3af5357bf11349e9a7e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-01-30T16:48:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T07:45:31.000Z", "avg_line_length": 34.9861111111, "max_line_length": 113, "alphanum_fraction": 0.6196903533, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6567191983634099}} {"text": "{-# LANGUAGE FlexibleInstances #-}\n{-|\nModule : Algorithm.ShapeConstraint\nDescription : evaluation of shape-constraints for symbolic regression\nCopyright : (c) Fabricio Olivetti de Franca, 2022\nLicense : GPL-3\nMaintainer : fabricio.olivetti@gmail.com\nStability : experimental\nPortability : POSIX\n\nThis package provides support functions to evaluate different \nshape-constraints for symbolic regression using modal arithmetic.\n\nSee https://direct.mit.edu/evco/article/30/1/75/99840 for more details.\n\n@\n@article{kronberger2022shape,\n title={Shape-Constrained Symbolic Regression—Improving Extrapolation with Prior Knowledge},\n author={Kronberger, Gabriel and de Fran{\\c{c}}a, Fabricio Olivetti and Burlacu, Bogdan and Haider, Christian and Kommenda, Michael},\n journal={Evolutionary computation},\n volume={30},\n number={1},\n pages={75--98},\n year={2022},\n publisher={MIT Press One Rogers Street, Cambridge, MA 02142-1209, USA journals-info~…}\n}\n@\n\n-}\nmodule Algorithm.ShapeConstraint\n ( getViolationFun\n , Evaluator(..)\n , Shape(..)\n )\n where\n\nimport Numeric.ModalInterval\nimport Numeric.ModalInterval.Algorithms\nimport Data.SRTree\n\nimport Data.Map.Strict (Map(..))\nimport qualified Data.Map.Strict as M\nimport qualified Data.Vector as V\nimport Data.Bool (bool)\nimport Data.Maybe (fromMaybe)\nimport qualified Numeric.LinearAlgebra.Data as LA\n\n-- | Data type describing the type of constraint:\n--\n-- * Range of the function\n-- * Range of a partial derivative\n-- * Monotonicity (non-increasing and non-decreasing)\n-- * Partial monotonicity\n-- * Inflection, Convex or Concave\n--\n-- The monotonicity constraints require the index of the\n-- variable, the ranges require a tuple of the minimum and\n-- maximum values, the partial monotonicity also requires\n-- the range of the domain that has this property,\n-- inflection, convexity and concavity requires the first\n-- and second index of the partial derivatives.\ndata Shape = Range (Double, Double) -- ^ f(x) \\in [a, b]\n | DiffRng Int (Double, Double) -- ^ d f(x) / dx \\in [a, b]\n | NonIncreasing Int -- ^ d f(x) / dx \\in [-inf, 0]\n | NonDecreasing Int -- ^ d f(x) / dx \\in [0, inf]\n | PartialNonIncreasing Int (Double, Double) -- ^ d f(x) / dx \\in [-inf, 0], a <= x <= b\n | PartialNonDecreasing Int (Double, Double) -- ^ d f(x) / dx \\in [0, inf], a <= x <= b\n | Inflection Int Int -- ^ d^2 f(x)/dx^2 == 0\n | Convex Int Int -- ^ d^2 f(x)/dx^2 \\in (0, Infinity)\n | Concave Int Int -- ^ d^2 f(x)/dx^2 \\in (-Infinitiy,0)\n deriving (Show, Read)\n\n-- inner (a, b) no sharper than that\n-- outer (a, b) no wider than that\n\n-- | The `Evaluator` indicates the algorithm used to calculate the constraint:\n--\n-- * InnerInterval can result in false positives (i.e., it says it is feasible but it is not)\n-- * OuterInterval can result in false negatives (i.e., it says it is infeasible but it is not)\n-- * Sampling can result in false positives and usually requires a lot of samples\n-- * Hybrid - not yet implemented\n-- * Bisection can improve the results of OuterInterval\ndata Evaluator = InnerInterval | OuterInterval | Sampling Int | Hybrid | Bisection Int\n deriving (Show, Read)\n\n-- | Function that calculates how much of the constraints a symbolic tree vioaltes\ntype ConstraintFun = SRTree Int Double -> Double\n\n-- | A list of domains of the variables\ntype Domains = [(Double, Double)]\n\n-- | A list of domains using Modal Arithmetic\ntype KDomains = Map (Kaucher Double)\n\n-- | Calculates the partial derivatives of a tree when needed.\nofShape :: (Floating a, Eq a, OptIntPow a) => SRTree Int a -> Shape -> SRTree Int a\nt `ofShape` Range _ = t\nt `ofShape` DiffRng ix _ = simplify $ deriveBy ix t\nt `ofShape` NonIncreasing ix = simplify $ deriveBy ix t\nt `ofShape` NonDecreasing ix = simplify $ deriveBy ix t\nt `ofShape` PartialNonIncreasing ix _ = simplify $ deriveBy ix t\nt `ofShape` PartialNonDecreasing ix _ = simplify $ deriveBy ix t\nt `ofShape` Inflection ix iy = simplify $ deriveBy iy $ simplify $ deriveBy ix t\nt `ofShape` Convex ix iy = simplify $ deriveBy iy $ simplify $ deriveBy ix t\nt `ofShape` Concave ix iy = simplify $ deriveBy iy $ simplify $ deriveBy ix t\n{-# INLINE ofShape #-}\n\ntoTuple :: Kaucher Double -> (Double, Double)\ntoTuple k = (fromMaybe (-1/0) $ inf k, fromMaybe (1/0) $ sup k)\n{-# INLINE toTuple #-}\n\neps :: Double\neps = 1e-6\n{-# INLINE eps #-}\n\ncalcPenalty :: Bool -> Double -> Double\ncalcPenalty b pnlty = bool 0 pnlty b\n{-# INLINE calcPenalty #-}\n\ninRng (a, b) (x, y) = calcPenalty (x < a - eps) (a - x) + calcPenalty (y > b + eps) (y - b)\n{-# INLINE inRng #-}\nisPositive (x, y) = calcPenalty (x <= -eps) (abs x) + calcPenalty (y <= -eps) (abs y)\n{-# INLINE isPositive #-}\nisNegative (x, y) = calcPenalty (x >= eps) (abs x) + calcPenalty (y >= eps) (abs y)\n{-# INLINE isNegative #-}\nisZero (x, y) = calcPenalty (x <= -eps) (abs x) + calcPenalty (y >= eps) y\n{-# INLINE isZero #-}\n\n-- | Evaluates the constraint\nevalConstraints :: Shape -> (Double, Double) -> Double\nevalConstraints (Range ab) xy = inRng ab xy\nevalConstraints (DiffRng _ ab) xy = inRng ab xy\nevalConstraints (NonIncreasing _) xy = isNegative xy\nevalConstraints (NonDecreasing _) xy = isPositive xy\nevalConstraints (PartialNonIncreasing _ _) xy = isNegative xy\nevalConstraints (PartialNonDecreasing _ _) xy = isPositive xy\nevalConstraints (Inflection _ _) xy = isZero xy\nevalConstraints (Convex _ _) xy = isPositive xy\nevalConstraints (Concave _ _) xy = isNegative xy\n{-# INLINE evalConstraints #-}\n\n-- | Convert the domains for the partial monotonicity constraint\nconvertDomains :: Shape -> Map Int (Kaucher Double) -> Map Int (Kaucher Double)\nconvertDomains (PartialNonIncreasing ix (a, b)) ds = M.insert ix (a <.< b) ds\nconvertDomains (PartialNonDecreasing ix (a, b)) ds = M.insert ix (a <.< b) ds \nconvertDomains _ ds = ds\n{-# INLINE convertDomains #-}\n\n-- | Sum a list of constraint violations\nsumCnstr :: (SRTree Int (Kaucher Double) -> Map Int (Kaucher Double) -> Kaucher Double) -> Map Int (Kaucher Double) -> [SRTree Int (Kaucher Double)] -> [Shape] -> Double -> Double\nsumCnstr f ds [] [] acc = acc\nsumCnstr f ds (x:xs) (z:zs) acc = sumCnstr f ds xs zs (acc + cnstr)\n where \n cnstr = evalConstraints z $ toTuple $ f x $ convertDomains z ds\n{-# INLINE sumCnstr #-}\n\ntoMap :: Domains -> Map Int (Kaucher Double)\ntoMap = M.fromList . zip [0..] . map (uncurry (<.<))\n{-# INLINE toMap #-}\n\n-- | Returns a constraint function given an `Evaluator` a list of `Shape` and the\n-- `Domains` of the input variables.\ngetViolationFun :: Evaluator -> [Shape] -> Domains -> ConstraintFun\ngetViolationFun InnerInterval shapes domains t = sumCnstr innerApprox ds ts shapes 0.0 \n where\n t' = fmap singleton t\n ts = map (t' `ofShape`) shapes\n ds = toMap domains\n\ngetViolationFun OuterInterval shapes domains t = sumCnstr outerApprox ds ts shapes 0.0\n where\n t' = fmap singleton t\n ts = map (t' `ofShape`) shapes\n ds = toMap domains\n\ngetViolationFun (Sampling nSamples) shapes domains t = go shapes ts samples 0.0\n where\n ds = toMap domains \n samples = map (M.fromList . zip [0..] . makeSamples nSamples . (`convertDomains` ds)) shapes\n getSize s = LA.size $ s M.! 0\n ts = map (t `ofShape`) shapes\n \n evalSamples :: Maybe (LA.Vector Double) -> (Double, Double)\n evalSamples mxs = (fromMaybe (-1/0) mmin, fromMaybe (1/0) mmax)\n where\n mmax = LA.maxElement <$> mxs\n mmin = LA.minElement <$> mxs\n \n go [] _ _ acc = acc \n go (x:xs) (y:ys) (z:zs) acc = go xs ys zs (acc + cnstr)\n where \n cnstr = evalConstraints x rng\n y' = fmap (LA.fromList . replicate (getSize z)) y\n rng = evalSamples $ evalTreeWithMap y' z\n\ngetViolationFun e shapes domains t = error $ show e <> \" evaluator not implemented\"\n\ninstance OptIntPow (LA.Vector Double) where \n (^.) = (^^)\n {-# INLINE (^.) #-}\n\n-- | Creates the samples of the `Sampling` approach\nmakeSamples :: Int -> Map Int (Kaucher Double) -> [LA.Vector Double]\nmakeSamples n domains = LA.toColumns $ LA.fromLists $ map (map midpoint) $ head $ dropWhile (\\x -> length x < n) samples\n where\n step x = let (a,b) = bisect x in [a,b]\n f = map (concatMap step)\n samples = map sequence $ iterate f $ map (pure.snd) $ M.toAscList domains\n{-# INLINE makeSamples #-}\n", "meta": {"hexsha": "f42222a635d2e66d49e141ec2939fe1cc44c0dd2", "size": 8766, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Algorithm/ShapeConstraint.hs", "max_stars_repo_name": "folivetti/shape-constraint", "max_stars_repo_head_hexsha": "1bc12f658beaca28de5eca53bbb86d3e15843628", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Algorithm/ShapeConstraint.hs", "max_issues_repo_name": "folivetti/shape-constraint", "max_issues_repo_head_hexsha": "1bc12f658beaca28de5eca53bbb86d3e15843628", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Algorithm/ShapeConstraint.hs", "max_forks_repo_name": "folivetti/shape-constraint", "max_forks_repo_head_hexsha": "1bc12f658beaca28de5eca53bbb86d3e15843628", "max_forks_repo_licenses": ["BSD-3-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.7428571429, "max_line_length": 179, "alphanum_fraction": 0.6476157883, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6566861080676039}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE TupleSections #-}\nmodule Main where\n\nimport Map\nimport Sector\n-- import RepaMap\nimport Map.PixelMap\n-- import SectorTree\n-- import SectorMap\nimport Map.Dimension\n\nimport Linear.V as L\nimport Data.Complex\nimport qualified Data.Vector as V\nimport Codec.Picture\n-- import Data.Kind\n\n-- mandelbrot :: Int -> Complex Double -> Bool\n{-# INLINE mandelbrot #-}\nmandelbrot :: (Ord t, Num t, RealFloat a) => t -> Complex a -> Bool\nmandelbrot n x = mandelbrot' x x n where\n mandelbrot' z _ _ | (sqr . magnitude $ z) > 4 = False\n mandelbrot' _ _ i | i <= 0 = True\n mandelbrot' z c i = mandelbrot' (z*z + c) c (i - 1)\n sqr a = a * a\n\n{-# INLINE toComplexCoords #-}\ntoComplexCoords :: V 2 Double -> Complex Double\ntoComplexCoords (V v) = v V.! 1 :+ v V.! 0\n\n{-# INLINE mandelMap #-}\nmandelMap :: Int -> PixelMap Double\nmandelMap n = fmap toGrayScale\n . changeCoordinates toComplexCoords\n $ getPoint >>= return . mandelbrot n\n\n{-# INLINE mandelMap' #-}\nmandelMap' :: Int -> Sector 2 Double -> Int -> PixelMap Double\nmandelMap' n = optimizeMap (mandelMap n)\n\nviewSector :: Zone -> Double -> Sector 2 Double\nviewSector (Zone x y r) ratio = V . V.fromList $ [(x - r, x + r), (y - r * ratio, y + r * ratio)]\n\ndata Zone = Zone { zoneX :: Double\n , zoneY :: Double\n , zoneR :: Double }\n\ninterestingZones :: [Zone]\ninterestingZones =\n [ Zone 0 0 2\n , Zone 0.1 (-0.7) (5e-4)\n , Zone (0.109) (-0.7443) (0.005)\n -- , Zone (0.1102) (-0.7463) (0.005)\n , Zone (0.1127) (-0.7453) (6.5e-4)\n , Zone (1.0405) (-0.16) (0.026)\n ]\n\nmain :: IO ()\nmain = do\n let resX = 1920 * resMultiplier -- x and y dimensions\n resY = 1080 * resMultiplier\n resMultiplier = 1 -- increment this to get 4k, 8k, etc.\n ratio = (fromIntegral resX) / (fromIntegral resY)\n zone = Zone 0 0 2\n depth = 400\n sec = viewSector zone ratio\n img = bakePixelMap\n sec\n (resolution resX resY)\n (mandelMap depth)\n putStrLn \"Execution started.\"\n savePngImage (\"/tmp/mandelbrot.png\") img\n putStrLn \"Execution finished\"\n", "meta": {"hexsha": "335113a0aa9e2c3748bc1ba46e0672c243fde761", "size": 2289, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "app/Mandelbrot/Main.hs", "max_stars_repo_name": "zephyrys/myworld-rewrite", "max_stars_repo_head_hexsha": "aa61a873d3580f3a53a71ee89cd84b3cae0fb2f7", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Mandelbrot/Main.hs", "max_issues_repo_name": "zephyrys/myworld-rewrite", "max_issues_repo_head_hexsha": "aa61a873d3580f3a53a71ee89cd84b3cae0fb2f7", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Mandelbrot/Main.hs", "max_forks_repo_name": "zephyrys/myworld-rewrite", "max_forks_repo_head_hexsha": "aa61a873d3580f3a53a71ee89cd84b3cae0fb2f7", "max_forks_repo_licenses": ["BSD-3-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.7272727273, "max_line_length": 97, "alphanum_fraction": 0.5915246833, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.656622399560901}} {"text": "-- |\n-- Module : Statistics.Test.WilcoxonT\n-- Copyright : (c) 2010 Neil Brown\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- The Wilcoxon matched-pairs signed-rank test is non-parametric test\n-- which could be used to whether two related samples have different\n-- means.\n--\n-- WARNING: current implementation contain serious bug and couldn't be\n-- used with samples larger than 1023.\n-- \nmodule Statistics.Test.WilcoxonT (\n -- * Wilcoxon signed-rank matched-pair test\n wilcoxonMatchedPairTest\n , wilcoxonMatchedPairSignedRank\n , wilcoxonMatchedPairSignificant\n , wilcoxonMatchedPairSignificance\n , wilcoxonMatchedPairCriticalValue\n -- * Data types\n , TestType(..)\n , TestResult(..)\n ) where\n\n\n\n--\n--\n--\n-- Note that: wilcoxonMatchedPairSignedRank == (\\(x, y) -> (y, x)) . flip wilcoxonMatchedPairSignedRank\n-- The samples are zipped together: if one is longer than the other, both are truncated\n-- The value returned is the pair (T+, T-). T+ is the sum of positive ranks (the\n-- These values mean little by themselves, and should be combined with the 'wilcoxonSignificant'\n-- function in this module to get a meaningful result.\n-- ranks of the differences where the first parameter is higher) whereas T- is\n-- the sum of negative ranks (the ranks of the differences where the second parameter is higher).\n-- to the the length of the shorter sample.\n\nimport Control.Applicative ((<$>))\nimport Data.Function (on)\nimport Data.List (findIndex)\nimport Data.Ord (comparing)\nimport Prelude hiding (sum)\nimport Statistics.Function (sortBy)\nimport Statistics.Sample.Internal (sum)\nimport Statistics.Test.Internal (rank, splitByTags)\nimport Statistics.Test.Types (TestResult(..), TestType(..), significant)\nimport Statistics.Types (Sample)\nimport qualified Data.Vector.Unboxed as U\n\nwilcoxonMatchedPairSignedRank :: Sample -> Sample -> (Double, Double)\nwilcoxonMatchedPairSignedRank a b = (sum ranks1, negate (sum ranks2))\n where\n (ranks1, ranks2) = splitByTags\n $ U.zip tags (rank ((==) `on` abs) diffs)\n (tags,diffs) = U.unzip\n $ U.map (\\x -> (x>0 , x)) -- Attack tags to distribution elements\n $ U.filter (/= 0.0) -- Remove equal elements\n $ sortBy (comparing abs) -- Sort the differences by absolute difference\n $ U.zipWith (-) a b -- Work out differences\n\n\n-- | The coefficients for x^0, x^1, x^2, etc, in the expression\n-- \\prod_{r=1}^s (1 + x^r). See the Mitic paper for details.\n--\n-- We can define:\n-- f(1) = 1 + x\n-- f(r) = (1 + x^r)*f(r-1)\n-- = f(r-1) + x^r * f(r-1)\n-- The effect of multiplying the equation by x^r is to shift\n-- all the coefficients by r down the list.\n--\n-- This list will be processed lazily from the head.\ncoefficients :: Int -> [Integer]\ncoefficients 1 = [1, 1] -- 1 + x\ncoefficients r = let coeffs = coefficients (r-1)\n (firstR, rest) = splitAt r coeffs\n in firstR ++ add rest coeffs\n where\n add (x:xs) (y:ys) = x + y : add xs ys\n add xs [] = xs\n add [] ys = ys\n\n-- This list will be processed lazily from the head.\nsummedCoefficients :: Int -> [Double]\nsummedCoefficients n\n | n < 1 = error \"Statistics.Test.WilcoxonT.summedCoefficients: nonpositive sample size\"\n | n > 1023 = error \"Statistics.Test.WilcoxonT.summedCoefficients: sample is too large (see bug #18)\"\n | otherwise = map fromIntegral $ scanl1 (+) $ coefficients n\n\n-- | Tests whether a given result from a Wilcoxon signed-rank matched-pairs test\n-- is significant at the given level.\n--\n-- This function can perform a one-tailed or two-tailed test. If the first\n-- parameter to this function is 'TwoTailed', the test is performed two-tailed to\n-- check if the two samples differ significantly. If the first parameter is\n-- 'OneTailed', the check is performed one-tailed to decide whether the first sample\n-- (i.e. the first sample you passed to 'wilcoxonMatchedPairSignedRank') is\n-- greater than the second sample (i.e. the second sample you passed to\n-- 'wilcoxonMatchedPairSignedRank'). If you wish to perform a one-tailed test\n-- in the opposite direction, you can either pass the parameters in a different\n-- order to 'wilcoxonMatchedPairSignedRank', or simply swap the values in the resulting\n-- pair before passing them to this function.\nwilcoxonMatchedPairSignificant ::\n TestType -- ^ Perform one- or two-tailed test (see description below).\n -> Int -- ^ The sample size from which the (T+,T-) values were derived.\n -> Double -- ^ The p-value at which to test (e.g. 0.05)\n -> (Double, Double) -- ^ The (T+, T-) values from 'wilcoxonMatchedPairSignedRank'.\n -> Maybe TestResult -- ^ Return 'Nothing' if the sample was too\n -- small to make a decision.\nwilcoxonMatchedPairSignificant test sampleSize p (tPlus, tMinus) =\n case test of\n -- According to my nearest book (Understanding Research Methods and Statistics\n -- by Gary W. Heiman, p590), to check that the first sample is bigger you must\n -- use the absolute value of T- for a one-tailed check:\n OneTailed -> (significant . (abs tMinus <=) . fromIntegral) <$> wilcoxonMatchedPairCriticalValue sampleSize p\n -- Otherwise you must use the value of T+ and T- with the smallest absolute value:\n TwoTailed -> (significant . (t <=) . fromIntegral) <$> wilcoxonMatchedPairCriticalValue sampleSize (p/2)\n where\n t = min (abs tPlus) (abs tMinus)\n\n-- | Obtains the critical value of T to compare against, given a sample size\n-- and a p-value (significance level). Your T value must be less than or\n-- equal to the return of this function in order for the test to work out\n-- significant. If there is a Nothing return, the sample size is too small to\n-- make a decision.\n--\n-- 'wilcoxonSignificant' tests the return value of 'wilcoxonMatchedPairSignedRank'\n-- for you, so you should use 'wilcoxonSignificant' for determining test results.\n-- However, this function is useful, for example, for generating lookup tables\n-- for Wilcoxon signed rank critical values.\n--\n-- The return values of this function are generated using the method detailed in\n-- the paper \\\"Critical Values for the Wilcoxon Signed Rank Statistic\\\", Peter\n-- Mitic, The Mathematica Journal, volume 6, issue 3, 1996, which can be found\n-- here: .\n-- According to that paper, the results may differ from other published lookup tables, but\n-- (Mitic claims) the values obtained by this function will be the correct ones.\nwilcoxonMatchedPairCriticalValue ::\n Int -- ^ The sample size\n -> Double -- ^ The p-value (e.g. 0.05) for which you want the critical value.\n -> Maybe Int -- ^ The critical value (of T), or Nothing if\n -- the sample is too small to make a decision.\nwilcoxonMatchedPairCriticalValue sampleSize p\n = case critical of\n Just n | n < 0 -> Nothing\n | otherwise -> Just n\n Nothing -> Just maxBound -- shouldn't happen: beyond end of list\n where\n m = (2 ** fromIntegral sampleSize) * p\n critical = subtract 1 <$> findIndex (> m) (summedCoefficients sampleSize)\n\n-- | Works out the significance level (p-value) of a T value, given a sample\n-- size and a T value from the Wilcoxon signed-rank matched-pairs test.\n--\n-- See the notes on 'wilcoxonCriticalValue' for how this is calculated.\nwilcoxonMatchedPairSignificance :: Int -- ^ The sample size\n -> Double -- ^ The value of T for which you want the significance.\n -> Double -- ^ The significance (p-value).\nwilcoxonMatchedPairSignificance sampleSize rnk\n = (summedCoefficients sampleSize !! floor rnk) / 2 ** fromIntegral sampleSize\n\n-- | The Wilcoxon matched-pairs signed-rank test. The samples are\n-- zipped together: if one is longer than the other, both are\n-- truncated to the the length of the shorter sample.\n--\n-- For one-tailed test it tests whether first sample is significantly\n-- greater than the second. For two-tailed it checks whether they\n-- significantly differ\n--\n-- Check 'wilcoxonMatchedPairSignedRank' and\n-- 'wilcoxonMatchedPairSignificant' for additional information.\nwilcoxonMatchedPairTest :: TestType -- ^ Perform one-tailed test.\n -> Double -- ^ The p-value at which to test (e.g. 0.05)\n -> Sample -- ^ First sample\n -> Sample -- ^ Second sample\n -> Maybe TestResult\n -- ^ Return 'Nothing' if the sample was too\n -- small to make a decision.\nwilcoxonMatchedPairTest test p smp1 smp2 =\n wilcoxonMatchedPairSignificant test (min n1 n2) p\n $ wilcoxonMatchedPairSignedRank smp1 smp2\n where\n n1 = U.length smp1\n n2 = U.length smp2\n", "meta": {"hexsha": "11fa3820e00f5d603064281c3fd80a6eb923adda", "size": 9040, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Test/WilcoxonT.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Test/WilcoxonT.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Test/WilcoxonT.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": 47.5789473684, "max_line_length": 113, "alphanum_fraction": 0.6819690265, "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6562678495508827}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n\nmodule Quadrature\n( getGaussPoints\n, numGaussPoints\n, integrate\n, integrateFunc\n) where\n\nimport qualified Numeric.LinearAlgebra.HMatrix as HMat\n\ntype FrElNuFi a = (Fractional a,HMat.Element a,HMat.Numeric a,HMat.Field a)\ntype FlElNuFi a = (Floating a,HMat.Element a,HMat.Numeric a,HMat.Field a)\n\n-- Function for computing the required number of Gauss points for a polynomial\nnumGaussPoints :: Integral a => a -> a\nnumGaussPoints order = ceiling (0.5 * (fromIntegral order + 1.0))\n\n-- Function for getting Gauss points for integration\n-- Given the number of points it returns a list of the points and the weights\ngetGaussPoints :: Floating a => Int -> ([a], [a])\ngetGaussPoints 1 = ([0.0], [2.0])\ngetGaussPoints 2 = ([-1.0/sqrt 3.0, 1.0/sqrt 3.0], [1.0, 1.0])\ngetGaussPoints 3 = ([-sqrt (3.0/5.0), 0.0, sqrt (3.0/5.0)], [5.0/9.0, 8.0/9.0, 5.0/9.0])\ngetGaussPoints 4 = ([-0.861136311594053,-0.339981043584856,0.339981043584856,0.861136311594053],[0.347854845137454,0.652145154862546,0.652145154862546,0.347854845137454])\ngetGaussPoints _ = error \"Gauss points only up to 4 point quadrature available.\"\n\n-- Function for integrating some integrand over an element\n-- Usage: integrate dim ngpts integrand\nintegrate :: FrElNuFi a => Int -> Int -> ([a] -> HMat.Matrix a) -> HMat.Matrix a\nintegrate 1 ngpts integrand = foldl1 HMat.add $ zipWith HMat.scale wts (map (\\x -> integrand [x]) xi)\n where\n gpts = getGaussPoints ngpts\n xi = fst gpts\n wts = snd gpts\nintegrate _ _ _ = error \"Integration only works in 1d for now.\"\n\n-- Function for integrating a function from -1 to 1\nintegrateFunc :: Floating a => Int -> (a -> a) -> a\nintegrateFunc ngpts func = sum $ zipWith (*) wts (map func pts)\n where\n gpts = getGaussPoints ngpts\n pts = fst gpts\n wts = snd gpts\n", "meta": {"hexsha": "d2ffd66b3f79096eb9a351584eaa9cbab637871d", "size": 1805, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Quadrature.hs", "max_stars_repo_name": "jgrisham4/hfem", "max_stars_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Quadrature.hs", "max_issues_repo_name": "jgrisham4/hfem", "max_issues_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Quadrature.hs", "max_forks_repo_name": "jgrisham4/hfem", "max_forks_repo_head_hexsha": "2bb85634f2f0753419916fd99224505b76ce8291", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1111111111, "max_line_length": 170, "alphanum_fraction": 0.7096952909, "num_tokens": 604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6558903598396031}} {"text": "import Graphics.Gloss\nimport Graphics.Gloss.Raster.Field\nimport Graphics.Gloss.Data.ViewPort\nimport Data.Complex\nimport Data.Colour.RGBSpace\nimport Data.Colour.RGBSpace.HSV\nimport qualified Graphics.Gloss.Data.Point.Arithmetic as PA\n\nmandelbrot :: Complex Float -> Complex Float -> Int -> (Complex Float, Int)\nmandelbrot z _ 0 = (z, 0)\nmandelbrot z c n\n | magnitude z > 2 = (z, n)\n | otherwise = mandelbrot (z * z + c) c (n - 1)\n \n\nrgbcolor :: Float -> Float -> Float -> Color\nrgbcolor r g b = makeColor r g b 1.0\n\nsmoothcolor :: Complex Float -> Int -> Int -> Color\nsmoothcolor _ 0 _ = black\nsmoothcolor z n max = (uncurryRGB rgbcolor) $ hsv deg 1 1 \n where deg = 360 * ((fromIntegral n) - 1.0 + (log (log (magnitude z))) / (log 2)) / (fromIntegral max)\n \ncolorof :: Int -> Point -> Color\ncolorof max (x,y) = let (z, n) = mandelbrot 0 (x :+ y) max\n in smoothcolor z n max\n\ngetpicture :: ViewPort -> Float -> (Picture,Point) -> (Picture,Point)\ngetpicture vp _ pd@(pic,pt) = let npt = invertViewPort vp (1,1)\n adjpt = (PA.- (1/300 PA.* t)).(300/scl PA.*)\n adjpic = (translate (-tx) (-ty)).(scale (300 /scl) (300/scl))\n t@(tx,ty) = viewPortTranslate vp\n scl = 300 * (viewPortScale vp)\n max = (round $ 4 * (log scl))\n in case (pt /= npt) of\n True -> (adjpic $ makePicture 600 600 5 5 ((colorof max).adjpt), npt)\n False -> pd\n\nmain :: IO ()\nmain = simulate\n (InWindow \"Mandelbrot\" (600,600) (20,20))\n black\n 1\n (Circle 0, (0,0))\n (\\(p,_ ) -> p)\n getpicture\n", "meta": {"hexsha": "8998664ceba03924f54f0e49cc9edfcd3a1d9769", "size": 1735, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "mandelbrot.hs", "max_stars_repo_name": "swarmalator/mandelbrot-zoom", "max_stars_repo_head_hexsha": "4644f66360bc1d7af994577c5fc92f24edcb658a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mandelbrot.hs", "max_issues_repo_name": "swarmalator/mandelbrot-zoom", "max_issues_repo_head_hexsha": "4644f66360bc1d7af994577c5fc92f24edcb658a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mandelbrot.hs", "max_forks_repo_name": "swarmalator/mandelbrot-zoom", "max_forks_repo_head_hexsha": "4644f66360bc1d7af994577c5fc92f24edcb658a", "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.914893617, "max_line_length": 103, "alphanum_fraction": 0.5458213256, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6557958858297206}} {"text": "-- | Module providing various functions popular in quantum calculations, but\n-- not implemented in \"Numeric.LinearAlgebra\".\nmodule Hoqus.MtxFun where\n\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra\n\n-- | Trace of a matrix. This function ignores the non-sqare part of the matrix.\ntrace :: Matrix C -> C\ntrace = sum.toList.takeDiag\n\n-- | Logarithm of a matrix. Based on 'Numeric.LinearAlgebra.matFunc' function\n-- from \"Numeric.LinearAlgebra\" package.\nlogm :: Matrix C -> Matrix C\nlogm = matFunc log\n", "meta": {"hexsha": "c74847f227e3c743af3dc3389e0583579ef1d635", "size": 514, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Hoqus/MtxFun.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/MtxFun.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/MtxFun.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": 32.125, "max_line_length": 79, "alphanum_fraction": 0.7645914397, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6557921652767023}} {"text": "module HopfieldMat ( initialWeights\n , energy\n , feed\n , train\n ) where\n\nimport Numeric.LinearAlgebra\n\ninitialWeights :: Int -> Matrix R\ninitialWeights l = (l> Matrix R -> Matrix R\ntrain p w = (outer p p) * zeroDiagonal + w\n where\n zeroDiagonal = (sp> Vector R -> Vector R\nfeed w = cmap signum . (w #>)\n\nenergy :: Matrix R -> Vector R -> Double\nenergy w p = -0.5 * (sumElements $ p * (w #> p))\n", "meta": {"hexsha": "ee0f710f32d843c9ee922eebb01c8444f4046c2c", "size": 569, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HopfieldMat.hs", "max_stars_repo_name": "mfandl/hml", "max_stars_repo_head_hexsha": "2673bf802d5806e27c17d817be33449c97cc1a3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HopfieldMat.hs", "max_issues_repo_name": "mfandl/hml", "max_issues_repo_head_hexsha": "2673bf802d5806e27c17d817be33449c97cc1a3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HopfieldMat.hs", "max_forks_repo_name": "mfandl/hml", "max_forks_repo_head_hexsha": "2673bf802d5806e27c17d817be33449c97cc1a3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7391304348, "max_line_length": 49, "alphanum_fraction": 0.546572935, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6555635607863548}} {"text": "module Math.FROG.Retrieval\n( retrieve\n, calcLoss\n) where\n\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Math.Optimization.SPSA as SPSA\n\nimport qualified Math.FROG.Tools as FR\nimport Math.FROG.Types \n\n\nretrieve :: Nonlinearity -> Trace -> IO (LA.Vector Double)\nretrieve nonlin measurement = do\n let niter = 50000\n let a = 0.2\n let c = 0.00001\n\n let sz = LA.rows measurement\n let gainA = SPSA.standardAk a (niter `quot` 10) 0.602\n let gainC = SPSA.standardCk c 0.101\n let lossFn = calcLoss nonlin measurement\n\n spsa <- SPSA.mkUnconstrainedSPSA lossFn gainA gainC (2*sz)\n initialGuess <- FR.mkInitialGuess sz\n\n return $ SPSA.optimize spsa niter initialGuess\n \n\n\n\ncalcLoss :: Nonlinearity -> Trace -> LA.Vector Double -> Double\ncalcLoss nonlin meas v = (/ (fromIntegral $ LA.rows meas)) . sqrt \n . LA.sumElements $ sqDiff\n where\n field = FR.flatPolar2Complex v\n (signal, gate) = FR.mkSigGate nonlin field field\n sqDiff = (^2) . abs $ (meas - FR.mkTrace signal gate)\n", "meta": {"hexsha": "701910c406e49c18014ecb6c19a2daac5c901c4a", "size": 1081, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/FROG/Retrieval.hs", "max_stars_repo_name": "leroix/haskell-spsa-frog", "max_stars_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-25T19:38:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-25T19:38:00.000Z", "max_issues_repo_path": "src/Math/FROG/Retrieval.hs", "max_issues_repo_name": "leroix/haskell-spsa-frog", "max_issues_repo_head_hexsha": "0ff98b2941840b317a08a0c2a8aa8d101c1503fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/FROG/Retrieval.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": 27.7179487179, "max_line_length": 84, "alphanum_fraction": 0.6632747456, "num_tokens": 312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6552342386212002}} {"text": "module Numeric.LinearAlgebra.OrthoNormalBasis where\n\nimport Numeric.LinearAlgebra.Vector\n\nepsilon :: (Ord a, Floating a) => a\nepsilon = 0.01\n\ndata ONB a = ONB\n { onbU :: Vec3 a\n , onbV :: Vec3 a\n , onbW :: Vec3 a\n } deriving (Read, Show, Eq, Ord)\n\nmkFromU :: (Ord a, Floating a) => Vec3 a -> ONB a\nmkFromU u' = ONB u v w\n where\n n = Vec3 1 0 0\n m = Vec3 0 1 0\n u = unitVector u'\n v = if len (u <%> n) < epsilon\n then u <%> m\n else u <%> n\n w = u <%> v\n\nmkFromV :: (Ord a, Floating a) => Vec3 a -> ONB a\nmkFromV v' = ONB u v w\n where\n n = Vec3 1 0 0\n m = Vec3 0 1 0\n v = unitVector v'\n u = if lenSquared (v <%> n) < epsilon\n then v <%> m\n else v <%> n\n w = u <%> v\n\nmkFromW :: (Ord a, Floating a) => Vec3 a -> ONB a\nmkFromW w' = ONB u v w\n where\n n = Vec3 1 0 0\n m = Vec3 0 1 0\n w = unitVector w'\n u = if len (w <%> n) < epsilon\n then w <%> m\n else w <%> n\n v = w <%> u\n\nmkFromUV :: Floating a => Vec3 a -> Vec3 a -> ONB a\nmkFromUV u' v' = ONB u v w\n where\n u = unitVector u'\n w = unitVector (u' <%> v')\n v = w <%> u\n\nmkFromVU :: Floating a => Vec3 a -> Vec3 a -> ONB a\nmkFromVU v' u' = ONB u v w\n where\n v = unitVector v'\n w = unitVector (u' <%> v')\n u = v <%> w\n\nmkFromUW :: Floating a => Vec3 a -> Vec3 a -> ONB a\nmkFromUW u' w' = ONB u v w\n where\n u = unitVector u'\n v = unitVector (w' <%> u')\n w = u <%> v\n\nmkFromWU :: Floating a => Vec3 a -> Vec3 a -> ONB a\nmkFromWU w' u' = ONB u v w\n where\n w = unitVector w'\n v = unitVector (w' <%> u')\n u = v <%> w\n\nmkFromVW :: Floating a => Vec3 a -> Vec3 a -> ONB a\nmkFromVW v' w' = ONB u v w\n where\n v = unitVector v'\n u = unitVector (v' <%> w')\n w = u <%> v\n\nmkFromWV :: Floating a => Vec3 a -> Vec3 a -> ONB a\nmkFromWV w' v' = ONB u v w\n where\n w = unitVector w'\n u = unitVector (v' <%> w')\n v = w <%> u \n", "meta": {"hexsha": "8671237ec6241950d61ac0e7314fc87db4cbbf6d", "size": 1840, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/LinearAlgebra/OrthoNormalBasis.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/OrthoNormalBasis.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/OrthoNormalBasis.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": 20.9090909091, "max_line_length": 51, "alphanum_fraction": 0.5293478261, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6547711194877429}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Evaluator.Numerical where\n\nimport LispTypes\nimport Environment\nimport Evaluator.Operators\n\nimport Data.Complex\nimport Data.Ratio\nimport Data.Foldable\nimport Data.Fixed \nimport Numeric\nimport Control.Monad.Except\n\nnumericalPrimitives :: [(String, [LispVal] -> ThrowsError LispVal)]\nnumericalPrimitives = \n -- Binary Numerical operations\n [(\"+\", numAdd), \n (\"-\", numSub),\n (\"*\", numMul),\n (\"/\", numDivide),\n (\"modulo\", numMod),\n (\"quotient\", numericBinop quot),\n (\"remainder\", numericBinop rem),\n (\"abs\", numAbs),\n (\"ceiling\", numCeil),\n (\"floor\", numFloor),\n (\"round\", numRound),\n (\"truncate\", numTruncate),\n -- Conversion\n (\"number->string\", numToString),\n -- Numerical Boolean operators\n (\"=\", numBoolBinop (==)),\n (\"<\", numBoolBinop (<)),\n (\">\", numBoolBinop (>)),\n (\"/=\", numBoolBinop (/=)),\n (\">=\", numBoolBinop (>=)),\n (\"<=\", numBoolBinop (<=)),\n -- Scientific functions\n (\"sqrt\", sciSqrt),\n (\"acos\", sciAcos),\n (\"asin\", sciAsin),\n (\"atan\", sciAtan),\n (\"cos\", sciCos),\n (\"sin\", sciSin),\n (\"tan\", sciTan),\n-- (\"acosh\", sciAcosh),\n-- (\"asinh\", sciAsinh),\n-- (\"atanh\", sciAtanh),\n-- (\"cosh\", sciCosh),\n-- (\"sinh\", sciSinh),\n-- (\"tanh\", sciTanh),\n (\"exp\", sciExp),\n (\"expt\", sciExpt),\n (\"log\", sciLog),\n -- Complex numbers operations\n-- (\"angle\", cAngle),\n (\"real-part\", cRealPart),\n (\"imag-part\", cImagPart),\n (\"magnitude\", cMagnitude),\n (\"make-polar\", cMakePolar),\n-- (\"make-rectangular\", cMakeRectangular),\n -- Type testing functions\n (\"number?\", unaryOp numberp),\n (\"integer?\", unaryOp integerp),\n (\"float?\", unaryOp floatp),\n (\"ratio?\", unaryOp ratiop),\n (\"complex?\", unaryOp complexp)]\n\n-- |Type testing functions\nnumberp, integerp, floatp, ratiop, complexp :: LispVal -> LispVal\nintegerp (Number _) = Bool True\nintegerp _ = Bool False\nnumberp (Number _) = Bool True\nnumberp (Float _) = Bool True\nnumberp (Ratio _) = Bool True\nnumberp (Complex _) = Bool True\nnumberp _ = Bool False\nfloatp (Float _) = Bool True\nfloatp _ = Bool False\nratiop (Ratio _) = Bool True\nratiop _ = Bool False\ncomplexp (Complex _) = Bool True\ncomplexp _ = Bool False\n\n-- |Absolute value\nnumAbs :: [LispVal] -> ThrowsError LispVal\nnumAbs [Number x] = return $ Number $ abs x\nnumAbs [Float x] = return $ Float $ abs x\nnumAbs [Complex x] = return $ Complex $ abs x -- Calculates the magnitude \nnumAbs [Ratio x] = return $ Ratio $ abs x\nnumAbs [x] = throwError $ TypeMismatch \"number\" x\nnumAbs l = throwError $ NumArgs 1 l\n\n-- |Ceiling, floor, round and truncate\nnumCeil, numFloor, numRound, numTruncate :: [LispVal] -> ThrowsError LispVal\nnumCeil [Number x] = return $ Number $ ceiling $ fromInteger x\nnumCeil [Ratio x] = return $ Number $ ceiling $ fromRational x\nnumCeil [Float x] = return $ Number $ ceiling x\nnumCeil [Complex x] = \n if imagPart x == 0 then return $ Number $ ceiling $ realPart x\n else throwError $ TypeMismatch \"integer or float\" $ Complex x\nnumCeil [x] = throwError $ TypeMismatch \"integer or float\" x\nnumCeil l = throwError $ NumArgs 1 l\n\nnumFloor [Number x] = return $ Number $ floor $ fromInteger x\nnumFloor [Ratio x] = return $ Number $ floor $ fromRational x\nnumFloor [Float x] = return $ Number $ floor x\nnumFloor [Complex x] = \n if imagPart x == 0 then return $ Number $ floor $ realPart x\n else throwError $ TypeMismatch \"integer or float\" $ Complex x\nnumFloor [x] = throwError $ TypeMismatch \"integer or float\" x\nnumFloor l = throwError $ NumArgs 1 l\n\nnumRound [Number x] = return $ Number $ round $ fromInteger x\nnumRound [Ratio x] = return $ Number $ round $ fromRational x\nnumRound [Float x] = return $ Number $ round x\nnumRound [Complex x] = \n if imagPart x == 0 then return $ Number $ round $ realPart x\n else throwError $ TypeMismatch \"integer or float\" $ Complex x\nnumRound [x] = throwError $ TypeMismatch \"integer or float\" x\nnumRound l = throwError $ NumArgs 1 l\n\nnumTruncate [Number x] = return $ Number $ truncate $ fromInteger x\nnumTruncate [Ratio x] = return $ Number $ truncate $ fromRational x\nnumTruncate [Float x] = return $ Number $ truncate x\nnumTruncate [Complex x] = \n if imagPart x == 0 then return $ Number $ truncate $ realPart x\n else throwError $ TypeMismatch \"integer or float\" $ Complex x\nnumTruncate [x] = throwError $ TypeMismatch \"integer or float\" x\nnumTruncate l = throwError $ NumArgs 1 l\n\n-- |foldl1M is like foldlM but has no base case\nfoldl1M :: Monad m => (a -> a -> m a) -> [a] -> m a \nfoldl1M f (x : xs) = foldlM f x xs\nfoldl1M _ _ = error \"unexpected error in foldl1M\"\n\n-- | Sum numbers\nnumAdd :: [LispVal] -> ThrowsError LispVal\nnumAdd [] = return $ Number 0\nnumAdd l = foldl1M (\\ x y -> numCast [x, y] >>= go) l\n where \n go (List [Number x, Number y]) = return $ Number $ x + y \n go (List [Float x, Float y]) = return $ Float $ x + y\n go (List [Ratio x, Ratio y]) = return $ Ratio $ x + y\n go (List [Complex x, Complex y]) = return $ Complex $ x + y\n go _ = throwError $ Default \"unexpected error in (+)\"\n\n-- | Subtract numbers\nnumSub :: [LispVal] -> ThrowsError LispVal\nnumSub [] = throwError $ NumArgs 1 []\nnumSub [Number x] = return $ Number $ -1 * x\nnumSub [Float x] = return $ Float $ -1 * x\nnumSub [Ratio x] = return $ Ratio $ -1 * x \nnumSub [Complex x] = return $ Complex $ -1 * x\nnumSub l = foldl1M (\\ x y -> numCast [x, y] >>= go) l\n where \n go (List [Number x, Number y]) = return $ Number $ x - y \n go (List [Float x, Float y]) = return $ Float $ x - y\n go (List [Ratio x, Ratio y]) = return $ Ratio $ x - y\n go (List [Complex x, Complex y]) = return $ Complex $ x - y\n go _ = throwError $ Default \"unexpected error in (-)\"\n\n-- | Multiply numbers\nnumMul :: [LispVal] -> ThrowsError LispVal\nnumMul [] = return $ Number 1\nnumMul l = foldl1M (\\ x y -> numCast [x, y] >>= go) l\n where \n go (List [Number x, Number y]) = return $ Number $ x * y \n go (List [Float x, Float y]) = return $ Float $ x * y\n go (List [Ratio x, Ratio y]) = return $ Ratio $ x * y\n go (List [Complex x, Complex y]) = return $ Complex $ x * y\n go _ = throwError $ Default \"unexpected error in (*)\"\n\n-- |Divide two numbers\nnumDivide :: [LispVal] -> ThrowsError LispVal\nnumDivide [] = throwError $ NumArgs 1 []\nnumDivide [Number 0] = throwError DivideByZero\nnumDivide [Ratio 0] = throwError DivideByZero\nnumDivide [Number x] = return $ Ratio $ 1 / fromInteger x\nnumDivide [Float x] = return $ Float $ 1.0 / x\nnumDivide [Ratio x] = return $ Ratio $ 1 / x \nnumDivide [Complex x] = return $ Complex $ 1 / x\nnumDivide l = foldl1M (\\ x y -> numCast [x, y] >>= go) l\n where \n go (List [Number x, Number y])\n | y == 0 = throwError DivideByZero\n | mod x y == 0 = return $ Number $ div x y -- Integer division\n | otherwise = return $ Ratio $ fromInteger x / fromInteger y \n go (List [Float x, Float y])\n | y == 0 = throwError DivideByZero\n | otherwise = return $ Float $ x / y\n go (List [Ratio x, Ratio y])\n | y == 0 = throwError DivideByZero\n | otherwise = return $ Ratio $ x / y\n go (List [Complex x, Complex y])\n | y == 0 = throwError DivideByZero\n | otherwise = return $ Complex $ x / y\n go _ = throwError $ Default \"unexpected error in (/)\"\n\n-- |Numerical modulus\nnumMod :: [LispVal] -> ThrowsError LispVal\nnumMod [] = return $ Number 1\nnumMod l = foldl1M (\\ x y -> numCast [x, y] >>= go) l\n where\n go (List [Number a, Number b]) = return $ Number $ mod' a b\n go (List [Float a, Float b]) = return $ Float $ mod' a b\n go (List [Ratio a, Ratio b]) = return $ Ratio $ mod' a b\n -- #TODO implement modulus for complex numbers\n go (List [Complex a, Complex b]) = throwError $ Default \"modulus is not yet implemented for complex numbers\"\n go _ = throwError $ Default \"unexpected error in (modulus)\"\n\n-- | Boolean operator\nnumBoolBinop :: (LispVal -> LispVal -> Bool) -> [LispVal] -> ThrowsError LispVal\nnumBoolBinop op [] = throwError $ Default \"need at least two arguments\"\nnumBoolBinop op [x] = throwError $ Default \"need at least two arguments\"\nnumBoolBinop op [x, y] = numCast [x, y] >>= go op\n where \n go op (List [x@(Number _), y@(Number _)]) = return $ Bool $ x `op` y\n go op (List [x@(Float _), y@(Float _)]) = return $ Bool $ x `op` y\n go op (List [x@(Ratio _), y@(Ratio _)]) = return $ Bool $ x `op` y\n go op (List [x@(Complex _), y@(Complex _)]) = return $ Bool $ x `op` y \n go op _ = throwError $ Default \"unexpected error in boolean operation\"\n\n-- |Accept two numbers and cast one as the appropriate type\nnumCast :: [LispVal] -> ThrowsError LispVal\n-- Same type, just return the two numbers\nnumCast [a@(Number _), b@(Number _)] = return $ List [a,b] \nnumCast [a@(Float _), b@(Float _)] = return $ List [a,b] \nnumCast [a@(Ratio _), b@(Ratio _)] = return $ List [a,b]\nnumCast [a@(Complex _), b@(Complex _)] = return $ List [a,b]\n-- First number is an integer\nnumCast [Number a, b@(Float _)] = return $ List [Float $ fromInteger a, b] \nnumCast [Number a, b@(Ratio _)] = return $ List [Ratio $ fromInteger a, b] \nnumCast [Number a, b@(Complex _)] = return $ List [Complex $ fromInteger a, b] \n-- First number is a float\nnumCast [a@(Float _), Number b] = return $ List [a, Float $ fromInteger b] \nnumCast [a@(Float _), Ratio b] = return $ List [a, Float $ fromRational b] \nnumCast [Float a, b@(Complex _)] = return $ List [Complex $ a :+ 0, b]\n-- First number is a rational\nnumCast [a@(Ratio _), Number b] = return $ List [a, Ratio $ fromInteger b] \nnumCast [Ratio a, b@(Float _)] = return $ List [Float $ fromRational a, b] \nnumCast [Ratio a, b@(Complex _)] = \n return $ List [Complex $ fromInteger (numerator a) / fromInteger (denominator a), b]\n-- First number is a complex\nnumCast [a@(Complex _), Number b] = return $ List [a, Complex $ fromInteger b] \nnumCast [a@(Complex _), Float b] = return $ List [a, Complex $ b :+ 0] \nnumCast [a@(Complex _), Ratio b] = \n return $ List [a, Complex $ fromInteger (numerator b) / fromInteger (denominator b)]\n-- Error cases\nnumCast [a, b] = case a of\n Number _ -> throwError $ TypeMismatch \"number\" b\n Float _ -> throwError $ TypeMismatch \"number\" b\n Ratio _ -> throwError $ TypeMismatch \"number\" b\n Complex _ -> throwError $ TypeMismatch \"number\" b\n _ -> throwError $ TypeMismatch \"number\" a\nnumCast _ = throwError $ Default \"unknown error in numCast\"\n\n\n-- |Take a primitive Haskell Integer function and wrap it\n-- with code to unpack an argument list, apply the function to it\n-- and return a numeric value\nnumericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal\n-- Throw an error if there's only one argument\nnumericBinop op val@[_] = throwError $ NumArgs 2 val\n-- Fold the operator leftway if there are enough args\nnumericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op \n\n-- |Convert a Number to a String\nnumToString :: [LispVal] -> ThrowsError LispVal\nnumToString [Number x] = return $ String $ show x\nnumToString [Float x] = return $ String $ show x\nnumToString [Ratio x] = return $ String $ show x\nnumToString [Complex x] = return $ String $ show x\nnumToString [x] = throwError $ TypeMismatch \"number\" x\nnumToString badArgList = throwError $ NumArgs 2 badArgList\n\n-- | Trigonometric functions\nsciCos, sciSin, sciTan, sciAcos, sciAsin, sciAtan :: [LispVal] -> ThrowsError LispVal\n-- | Cosine of a number\nsciCos [Number x] = return $ Float $ cos $ fromInteger x \nsciCos [Float x] = return $ Float $ cos x\nsciCos [Ratio x] = return $ Float $ cos $ fromRational x\nsciCos [Complex x] = return $ Complex $ cos x\nsciCos [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciCos badArgList = throwError $ NumArgs 1 badArgList\n-- | Sine of a number\nsciSin [Number x] = return $ Float $ sin $ fromInteger x \nsciSin [Float x] = return $ Float $ sin x\nsciSin [Ratio x] = return $ Float $ sin $ fromRational x\nsciSin [Complex x] = return $ Complex $ sin x\nsciSin [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciSin badArgList = throwError $ NumArgs 1 badArgList\n-- | Tangent of a number\nsciTan [Number x] = return $ Float $ tan $ fromInteger x \nsciTan [Float x] = return $ Float $ tan x\nsciTan [Ratio x] = return $ Float $ tan $ fromRational x\nsciTan [Complex x] = return $ Complex $ tan x\nsciTan [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciTan badArgList = throwError $ NumArgs 1 badArgList\n-- | Arccosine of a number\nsciAcos [Number x] = return $ Float $ acos $ fromInteger x \nsciAcos [Float x] = return $ Float $ acos x\nsciAcos [Ratio x] = return $ Float $ acos $ fromRational x\nsciAcos [Complex x] = return $ Complex $ acos x\nsciAcos [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciAcos badArgList = throwError $ NumArgs 1 badArgList\n-- | Sine of a number\nsciAsin [Number x] = return $ Float $ asin $ fromInteger x \nsciAsin [Float x] = return $ Float $ asin x\nsciAsin [Ratio x] = return $ Float $ asin $ fromRational x\nsciAsin [Complex x] = return $ Complex $ asin x\nsciAsin [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciAsin badArgList = throwError $ NumArgs 1 badArgList\n-- | Tangent of a number\nsciAtan [Number x] = return $ Float $ atan $ fromInteger x \nsciAtan [Float x] = return $ Float $ atan x\nsciAtan [Ratio x] = return $ Float $ atan $ fromRational x\nsciAtan [Complex x] = return $ Complex $ atan x\nsciAtan [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciAtan badArgList = throwError $ NumArgs 1 badArgList\n\n-- #TODO Implement hyperbolic functions\n-- Ask teacher\n-- | Hyperbolic functions\n-- sciAcosh, sciAsinh, sciAtanh, sciCosh, sciSinh, sciTanh :: [LispVal] -> ThrowsError LispVal\n\n-- Misc. Scientific primitives\nsciSqrt, sciExp, sciExpt, sciLog :: [LispVal] -> ThrowsError LispVal\n-- | Square root of a number\nsciSqrt [Number x] = return $ Float $ sqrt $ fromInteger x \nsciSqrt [Float x] = return $ Float $ sqrt x\nsciSqrt [Ratio x] = return $ Float $ sqrt $ fromRational x\nsciSqrt [Complex x] = return $ Complex $ sqrt x\nsciSqrt [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciSqrt badArgList = throwError $ NumArgs 1 badArgList\n-- | Return e to the power of x\nsciExp [Number x] = return $ Float $ exp $ fromInteger x \nsciExp [Float x] = return $ Float $ exp x\nsciExp [Ratio x] = return $ Float $ exp $ fromRational x\nsciExp [Complex x] = return $ Complex $ exp x\nsciExp [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciExp badArgList = throwError $ NumArgs 1 badArgList\n-- | Return x to the power of y\nsciExpt [x, y] = numCast [x, y] >>= go\n where \n go (List [Number x, Number y]) = return $ Number $ round $ (fromInteger x) ** (fromInteger y) \n go (List [Float x, Float y]) = return $ Float $ x ** y\n go (List [Ratio x, Ratio y]) = return $ Float $ (fromRational x) ** (fromRational y)\n go (List [Complex x, Complex y]) = return $ Complex $ x ** y\n go _ = throwError $ Default \"unexpected error in (-)\"\nsciExpt badArgList = throwError $ NumArgs 2 badArgList\n-- | Return the natural logarithm of x\nsciLog [Number x] = return $ Float $ log $ fromInteger x \nsciLog [Float x] = return $ Float $ log x\nsciLog [Ratio x] = return $ Float $ log $ fromRational x\nsciLog [Complex x] = return $ Complex $ log x\nsciLog [notnum] = throwError $ TypeMismatch \"number\" notnum\nsciLog badArgList = throwError $ NumArgs 1 badArgList\n\n-- #TODO implement phase (angle)\n-- Ask teacher how to convert phase formats from haskell to guile scheme\n-- | Complex number functions\ncRealPart, cImagPart, cMakePolar, cMagnitude :: [LispVal] -> ThrowsError LispVal\n-- | Real part of a complex number\ncRealPart [Number x] = return $ Number $ fromInteger x \ncRealPart [Float x] = return $ Float x\ncRealPart [Ratio x] = return $ Float $ fromRational x\ncRealPart [Complex x] = return $ Float $ realPart x\ncRealPart [notnum] = throwError $ TypeMismatch \"number\" notnum\ncRealPart badArgList = throwError $ NumArgs 1 badArgList\n-- | Imaginary part of a complex number\ncImagPart [Number x] = return $ Number 0 \ncImagPart [Float x] = return $ Number 0\ncImagPart [Ratio x] = return $ Number 0\ncImagPart [Complex x] = return $ Float $ imagPart x\ncImagPart [notnum] = throwError $ TypeMismatch \"number\" notnum\ncImagPart badArgList = throwError $ NumArgs 1 badArgList\n-- | Form a complex number from polar components of magnitude and phase.\ncMakePolar [mag, p] = numCast [mag, p] >>= go\n where \n go (List [Number mag, Number p]) \n | mag == 0 = return $ Number 0 \n | p == 0 = return $ Number mag\n | otherwise = return $ Complex $ mkPolar (fromInteger mag) (fromInteger p)\n go (List [Float mag, Float p]) \n | mag == 0 = return $ Number 0 \n | p == 0 = return $ Float mag\n | otherwise = return $ Complex $ mkPolar mag p\n go (List [Ratio mag, Ratio p]) \n | mag == 0 = return $ Number 0\n | p == 0 = return $ Float (fromRational mag)\n | otherwise = return $ Complex $ mkPolar (fromRational mag) (fromRational p)\n go val@(List [Complex mag, Complex p]) = throwError $ TypeMismatch \"real\" val\n go _ = throwError $ Default \"unexpected error in make-polar\"\ncMakePolar badArgList = throwError $ NumArgs 2 badArgList\n-- | Return the magnitude (length) of a complex number\ncMagnitude [Number x] = return $ Number $ fromInteger x\ncMagnitude [Float x] = return $ Float x\ncMagnitude [Ratio x] = return $ Float $ fromRational x\ncMagnitude [Complex x] = return $ Float $ magnitude x\ncMagnitude [notnum] = throwError $ TypeMismatch \"number\" notnum\ncMagnitude badArgList = throwError $ NumArgs 1 badArgList", "meta": {"hexsha": "ef5df37af45cac2ec6c15705a3b5064dc87df88b", "size": 18263, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Evaluator/Numerical.hs", "max_stars_repo_name": "zfnmxt/yasih", "max_stars_repo_head_hexsha": "f9afe967439e5ffd70437e94d62491fe5060d2ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Evaluator/Numerical.hs", "max_issues_repo_name": "zfnmxt/yasih", "max_issues_repo_head_hexsha": "f9afe967439e5ffd70437e94d62491fe5060d2ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Evaluator/Numerical.hs", "max_forks_repo_name": "zfnmxt/yasih", "max_forks_repo_head_hexsha": "f9afe967439e5ffd70437e94d62491fe5060d2ef", "max_forks_repo_licenses": ["BSD-3-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.2054455446, "max_line_length": 116, "alphanum_fraction": 0.6370804359, "num_tokens": 5401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6545191309214566}} {"text": "-- Gaussian arithmetic\n-- http://www.codewars.com/kata/55182e34a5808b90f4001335/\n\nmodule Data.Complex.Gaussian.Instances (Gaussian (..)) where\n\nimport Data.Complex.Gaussian (Gaussian (..))\n\ninstance Num Gaussian where\n (+) (Gaussian a b) (Gaussian c d) = Gaussian (a + c) (b + d)\n (*) (Gaussian a b) (Gaussian c d) = Gaussian (a*c-b*d) (a*d+b*c)\n negate (Gaussian a b) = Gaussian (negate a) (negate b)\n signum (Gaussian 0 0) = Gaussian 0 0\n signum (Gaussian a b) | a > 0 && b >= 0 = Gaussian 1 0\n | a <= 0 && b > 0 = Gaussian 0 1\n | a < 0 && b <= 0 = Gaussian (-1) 0\n | a >= 0 && b < 0 = Gaussian 0 (-1)\n abs (Gaussian 0 0) = Gaussian 0 0\n abs (Gaussian a b) | a > 0 && b >= 0 = Gaussian a b\n | a <= 0 && b > 0 = Gaussian b (-a)\n | a < 0 && b <= 0 = Gaussian (-a) (-b)\n | a >= 0 && b < 0 = Gaussian (-b) a\n fromInteger n = Gaussian n 0\n\ninstance Integral Gaussian where\n toInteger (Gaussian a b) = a*a + b*b \n quotRem (Gaussian a b) (Gaussian c d) = (q, (Gaussian a b) - q * (Gaussian c d))\n where q = Gaussian ((a*c+b*d) `quot` (c*c+d*d)) ((b*c-a*d) `quot` (c*c+d*d))\n", "meta": {"hexsha": "70121d3dd8f3945f3cf73eb98109832e10b58067", "size": 1277, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Beta/Gaussian.hs", "max_stars_repo_name": "gafiatulin/codewars", "max_stars_repo_head_hexsha": "535db608333e854be93ecfc165686a2162264fef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-01-14T20:12:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T06:16:58.000Z", "max_issues_repo_path": "src/Beta/Gaussian.hs", "max_issues_repo_name": "gafiatulin/codewars", "max_issues_repo_head_hexsha": "535db608333e854be93ecfc165686a2162264fef", "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/Beta/Gaussian.hs", "max_forks_repo_name": "gafiatulin/codewars", "max_forks_repo_head_hexsha": "535db608333e854be93ecfc165686a2162264fef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6071428571, "max_line_length": 84, "alphanum_fraction": 0.4894283477, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6545191295045911}} {"text": "{-|\nModule: Math.Ftensor.Algebra\nCopyright: (c) 2015 Michael Benfield\nLicense: ISC\n\nClasses supporting arithmetic operations. Haskell's numeric classes are too\ncoarse for our needs. Types which are instances of more than one of these\nclasses should satisfy the obvious compatibility relations between the various\noperations.\n\nFor instance, the equalities @x -. x = zero@ and @x *. (y +. z) = x *. y +. x\n*. z@ and @one *. x = x@ should hold. If the type in question implements\ninexact arithmetic, they should hold approximately.\n\nFor an instance of @Num@, these should hold whenever the type is also an\ninstance of the classes defining these functions:\n\n* @(+.) = (+)@\n\n* @(*.) = (*)@\n\n* @(-.) = (-)@\n\n* @neg = negate@\n\n* @one = fromInteger 1@\n\n* @zero = fromInteger 0@\n\nSimilarly, for an instance of @Fractional@\n\n* @(\\/.) = (\\/)@\n\n* @inv = recip@\n-}\n\n{-# LANGUAGE CPP #-}\n\nmodule Math.Ftensor.Algebra (\n Additive(..),\n WithZero(..),\n WithNegatives(..),\n Multiplicative(..),\n WithOne(..),\n WithReciprocals(..),\n WithScalars(..),\n Rg,\n Rng,\n Rig,\n Ring,\n Field,\n Module,\n VectorSpace,\n Algebra,\n UnitalAlgebra,\n) where\n\nimport Data.Complex (Complex)\nimport Data.Int\nimport Data.Ratio (Ratio)\nimport Data.Word\nimport Numeric.Natural\n\ninfixl 6 +.\n\nclass Additive a where\n (+.) :: a -> a -> a\n\n-- | Types that have an additive identity. Should satisfy:\n--\n-- * @x +. zero = zero +. x = x@\nclass Additive a => WithZero a where\n zero :: a\n\ninfixl 6 -.\n\n-- | Types that have additive inverses. Should satisfy:\n-- @neg x = zero -. x@ and @x -. x = zero@.\nclass WithZero a => WithNegatives a where\n {-# MINIMAL neg | (-.) #-}\n neg :: a -> a\n neg x = zero -. x\n (-.) :: a -> a -> a\n lhs -. rhs = lhs +. neg rhs\n\ninfixl 7 *.\n\nclass Multiplicative a where\n (*.) :: a -> a -> a\n\n-- | Types with a multiplicative identity. Should satisfy:\n--\n-- * @one *. x = x *. one = x@.\nclass Multiplicative a => WithOne a where\n one :: a\n\ninfixl 7 /.\n\n-- | Types with multiplicative inverse.\n-- @inv x@ and @y /. x@\n-- may throw an exception or behave in undefined ways if\n-- @invertible x = False@.\n--\n-- * @inv x = one ./ x@ \n--\n-- * @y *. x /. y = x@ \n--\n-- * @x /. y *. x = y@\nclass WithOne a => WithReciprocals a where\n\n {-# MINIMAL invertible, (inv | (/.)) #-}\n invertible :: a -> Bool\n\n inv :: a -> a\n inv x = one /. x\n\n (/.) :: a -> a -> a\n lhs /. rhs = lhs *. inv rhs\n\ninfixl 7 *:\n\n-- | Types like mathematical vectors that can be multiplied by another type.\nclass WithScalars a where\n type Scalar a\n (*:) :: Scalar a -> a -> a\n\n-- | A @Rg@ is a Ring without one or negatives.\ntype Rg a = (WithZero a, Multiplicative a)\n\n-- | A @Rng@ is a Ring without one.\ntype Rng a = (Rg a, WithNegatives a)\n\n-- | A @Rig@ is a Ring without negatives.\ntype Rig a = (Rg a, WithOne a)\n\ntype Ring a = (Rng a, Rig a)\n\ntype Field a = (Ring a, WithReciprocals a)\n\ntype Module a = (WithNegatives a, WithScalars a, Ring (Scalar a))\n\ntype VectorSpace a = (Module a, Field (Scalar a))\n\ntype Algebra a = (VectorSpace a, Rng a)\n\ntype UnitalAlgebra a = (Algebra a, WithOne a)\n\n#define INSTANCES_NUM(typ, ctxt) \\\ninstance ctxt Additive (typ) where { \\\n; {-# INLINE (+.) #-} \\\n; (+.) = (+) \\\n} ; instance ctxt WithZero (typ) where { \\\n; {-# INLINE zero #-} \\\n; zero = 0 \\\n} ; instance ctxt WithNegatives (typ) where { \\\n; {-# INLINE neg #-} \\\n; neg = negate \\\n; {-# INLINE (-.) #-} \\\n; (-.) = (-) \\\n} ; instance ctxt Multiplicative (typ) where { \\\n; {-# INLINE (*.) #-} \\\n; (*.) = (*) \\\n} ; instance ctxt WithOne (typ) where { \\\n; {-# INLINE one #-} \\\n; one = 1 \\\n} ; instance ctxt WithScalars (typ) where { \\\n; type Scalar (typ) = typ \\\n; {-# INLINE (*:) #-} \\\n; (*:) = (*) \\\n}\n\n#define INSTANCES_FRACTIONAL(typ, ctxt) \\\nINSTANCES_NUM(typ, ctxt) ; \\\ninstance ctxt WithReciprocals (typ) where { \\\n; {-# INLINE invertible #-} \\\n; invertible = (/= 0) \\\n; {-# INLINE inv #-} \\\n; inv = recip \\\n; {-# INLINE (/.) #-} \\\n; (/.) = (/) \\\n}\n\nINSTANCES_NUM(Natural, )\nINSTANCES_NUM(Integer, )\nINSTANCES_NUM(Int, )\nINSTANCES_NUM(Int8, )\nINSTANCES_NUM(Int16, )\nINSTANCES_NUM(Int32, )\nINSTANCES_NUM(Int64, )\nINSTANCES_NUM(Word, )\nINSTANCES_NUM(Word8, )\nINSTANCES_NUM(Word16, )\nINSTANCES_NUM(Word32, )\nINSTANCES_NUM(Word64, )\n\nINSTANCES_FRACTIONAL(Float, )\nINSTANCES_FRACTIONAL(Double, )\nINSTANCES_FRACTIONAL(Complex a, RealFloat a =>)\nINSTANCES_FRACTIONAL(Ratio a, Integral a =>)\n", "meta": {"hexsha": "7003d41e7eefe9400be2bc2174cbc0729afa7f3d", "size": 4419, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Ftensor/Algebra.hs", "max_stars_repo_name": "mikebenfield/ftensor", "max_stars_repo_head_hexsha": "312f064357632b77f5d32f276e3931094f22da6d", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-10-16T03:16:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T15:21:22.000Z", "max_issues_repo_path": "src/Math/Ftensor/Algebra.hs", "max_issues_repo_name": "mikebenfield/ftensor", "max_issues_repo_head_hexsha": "312f064357632b77f5d32f276e3931094f22da6d", "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/Math/Ftensor/Algebra.hs", "max_forks_repo_name": "mikebenfield/ftensor", "max_forks_repo_head_hexsha": "312f064357632b77f5d32f276e3931094f22da6d", "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": 22.095, "max_line_length": 78, "alphanum_fraction": 0.6053405748, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6544984006811004}} {"text": "{-- --:= Mark: find better way to construct complex number\ntype ImaginaryUnit = Integer\ntype RealNumber = Integer\ndata ComplexNumber = ComplexN {real :: RealNumber,\n imag :: ImaginaryUnit}\n--}\n\nimport Data.Complex\n\nreadComplex :: String -> Complex Double\nreadComplex = read\n\nresult :: (String, String) -> Complex Double\nresult (x,y) = (readComplex x) * (readComplex y)\n\nmain = do\n let exm1 = (\"1 :+ 1\",\"1 :+ 1\")\n let exm2 = (\"1 :+ -1\",\"1 :+ -1\")\n print $ result exm1\n print $ result exm2\n", "meta": {"hexsha": "9afa3067f3b35c550f0345a962a2a17f374ccc07", "size": 532, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Complex-Number-Multiplication/CNM.hs", "max_stars_repo_name": "ccqpein/Arithmetic-Exercises", "max_stars_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-07-11T03:07:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T06:46:10.000Z", "max_issues_repo_path": "Complex-Number-Multiplication/CNM.hs", "max_issues_repo_name": "ccqpein/Arithmetic-Exercises", "max_issues_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "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": "Complex-Number-Multiplication/CNM.hs", "max_forks_repo_name": "ccqpein/Arithmetic-Exercises", "max_forks_repo_head_hexsha": "748d7ac1313892d47eb0a66a0b7705e6d33b43ad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-06T22:19:33.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T22:19:33.000Z", "avg_line_length": 25.3333333333, "max_line_length": 58, "alphanum_fraction": 0.6109022556, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6542733028485629}} {"text": "{-# LANGUAGE RankNTypes, BangPatterns, ScopedTypeVariables #-}\n\nmodule Main where\n\nimport Math.Probably.MCMC\nimport qualified Math.Probably.PDF as PDF\nimport Math.Probably.RandIO\nimport Math.Probably.HamMC\nimport Math.Probably.MALA\nimport Math.Probably.FoldingStats\nimport Math.Probably.Sampler\nimport Control.Applicative\nimport Control.Monad\n\nimport Numeric.LinearAlgebra\nimport Numeric.AD\nimport Text.Printf\n\nimport Graphics.Gnewplot.Exec\nimport Graphics.Gnewplot.Types\nimport Graphics.Gnewplot.Style\nimport Graphics.Gnewplot.Panels\nimport Graphics.Gnewplot.Instances\nimport Graphics.Gnewplot.Histogram\nimport qualified Data.Vector.Storable as V\n\nimport Debug.Trace\n\n\nimport qualified Control.Monad.State.Strict as S\n\n\nvarf i = [10, 0.5, 1, 5, 0.1]!!(i `mod` 5)\n\ncorrf i j | i < j = corrf j i\n | otherwise = [-0.5, -0.2, 0, 0.2, 0.5]!!((i+j) `mod` 5)\n\ncovf (i,j) | i == j = varf i\n | otherwise = varf i * varf j * corrf i j\n\nd = 3\n\nmuMVN = fromList $ replicate d 10\ncovMVN = buildMatrix d d covf \n\n(invSigmaMVN, (lndetMVN, _)) = invlndet covMVN\n\npdfMVN = PDF.multiNormalByInv lndetMVN invSigmaMVN muMVN\n\n--pdfI :: [Double] -> Double\npdfI xs = sum $ map f $ zip xs (map varf [0..]) where\n f (x, var) = PDF.normal 10 var x\n\npdfI2 xs = sum $ map f $ zip xs (map varf [0..]) where\n f (x, var) = PDF.logNormal 0.1 var x\n\npdf3 [alpha, error_sd] = sum $ map f regrdata where\n f (age, height) = PDF.normalLogPdf (alpha) error_sd height\n\n\npdf2 [alpha, error_sd, beta] = sum $ map f regrdata where\n f (age, height) = PDF.normalLogPdf (alpha+(age*beta)) error_sd height\n\nregrdata :: (Real a, Floating a) => [(a,a)]\nregrdata = [ 35.1**6.3,\n 1.5**\t2.1,\n 35.2**\t5.1,\n 4.5**\t3.1,\n 10.1**\t3.9,\n 80.4**\t9.1,\n 5.2**\t3.2,\n 60.1**\t8.1,\n 70.1**\t9.1,\n 40.6**\t7] where (**) = (,)\n\n-- split HMC paper p 5\nnealCov :: Matrix Double\nneal_d = 200\n\nnealCov = buildMatrix neal_d neal_d $ \\(i,j) -> if i==j then realToFrac (i+1) / 100 else 0\n--(2><2) [1, 0.95, 0.95, 2]\n(nealCovInv, (nealLnDet,_)) = invlndet nealCov\nnealMean = fromList $ replicate neal_d 3\nnealPDF v = PDF.multiNormalByInv nealLnDet nealCovInv nealMean v\nnealPostGrad v = \n let p = nealPDF v\n tol = 0.001\n f (i,x) = let h = max (tol/10) $ tol * x\n v' = v V.// [(i,x+h)]\n v'' = v V.// [(i,x-h)]\n in (nealPDF v' - nealPDF v'')/(2*h)\n grad3 = fromList $ map f $ zip [0..] $ toList v\n in (p,grad3)\n\ncovM1 :: Matrix Double\ncovM1 = (3><3) [1, 0,0, \n 0 , 2,0, \n 0, 0, 4]\n\nmeans1, vars2 :: Vector Double\nvars2 = fromList [1,2,4]\n\nmeans1 = fromList [3,3,3]\n\n(covMinv, (covMLnDet,_)) = invlndet covM1\n\n\nmain = runRIO $ do\n --io $ print $ nealCov\n --io $ print $ nealCovInv \n{- vs1 <- sample $ sequence $ replicate 10000 $ multiNormal means1 covM1\n io $ print $ runStat meanSDF $ map (@>0) $ vs1\n io $ print $ runStat meanSDF $ map (@>1) $ vs1\n io $ print $ runStat meanSDF $ map (@>2) $ vs1\n vs1 <- sample $ sequence $ replicate 10000 $ mvnSampler means1 2 vars2\n io $ print $ runStat meanSDF $ map (@>0) $ vs1\n io $ print $ runStat meanSDF $ map (@>1) $ vs1\n io $ print $ runStat meanSDF $ map (@>2) $ vs1\n io $ print $ PDF.multiNormal means1 (scale 2 covM1) (fromList [2,2,2])\n-- io $ print $ PDF.multiNormalByInv covMLnDet covMinv means1 (fromList [2,2,2])\n-- io $ print $ PDF.multiNormalIndep vars2 means1 (fromList [2,2,2])\n io $ print $ mvnPDF means1 2 vars2 (fromList [2,2,2]) -}\n let vinit = fromList $ replicate neal_d (1)\n --io $ print $ nealPostGrad vinit\n let pinit = fst $ nealPostGrad vinit\n io $ print $ (\"pinit\", pinit)\n let hmcp0 = HMCPar vinit 100 0 0.15 0 0 True\n-- (vs') <- runMalaRioSimple (nealCov, nealCovInv, cholSH nealCov) nealPostGrad 2000 100 10 vinit\n (hmcp1, vs') <- runHMC nealPostGrad 100 hmcp0\n let vs = drop 50 $ reverse vs' \n --io $ forM (vs) $ \\v -> print (v, nealPDF v)\n io $ print $ runStat meanSDF $ map (@>20) $ vs\n io $ print $ runStat meanSDF $ map (@>80) $ vs\n let have_ess = calcESSprim $ vs\n io $ putStrLn $ \"ESS=\" ++show have_ess \n --io $ print hmcp1\n return () \n\nthin n [] = []\nthin n (x:xs) = x : thin n (drop n xs)\n\n\ncovF i j = pure (-) <*> before meanF (\\v -> v@>i * v@>j) \n <*> fmap (uncurry (*)) (both (before meanF (@>i)) (before meanF (@>j)))\n\n--cache prev, use grad'?\n", "meta": {"hexsha": "c53eb26f78e43fef101cd1ab8e110bb2f296e743", "size": 4346, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "testMCMC.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": "testMCMC.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": "testMCMC.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": 29.5646258503, "max_line_length": 98, "alphanum_fraction": 0.623561896, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6541435070577095}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n-- |\n-- Module : Statistics.Quantile\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Functions for approximating quantiles, i.e. points taken at regular\n-- intervals from the cumulative distribution function of a random\n-- variable.\n--\n-- The number of quantiles is described below by the variable /q/, so\n-- with /q/=4, a 4-quantile (also known as a /quartile/) has 4\n-- intervals, and contains 5 points. The parameter /k/ describes the\n-- desired point, where 0 ≤ /k/ ≤ /q/.\n\nmodule Statistics.Quantile\n (\n -- * Quantile estimation functions\n weightedAvg\n , ContParam(..)\n , continuousBy\n , midspread\n\n -- * Parameters for the continuous sample method\n , cadpw\n , hazen\n , s\n , spss\n , medianUnbiased\n , normalUnbiased\n\n -- * References\n -- $references\n ) where\n\nimport Data.Vector.Generic ((!))\nimport Numeric.MathFunctions.Constants (m_epsilon)\nimport Statistics.Function (partialSort)\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\n\n-- | O(/n/ log /n/). Estimate the /k/th /q/-quantile of a sample,\n-- using the weighted average method.\nweightedAvg :: G.Vector v Double =>\n Int -- ^ /k/, the desired quantile.\n -> Int -- ^ /q/, the number of quantiles.\n -> v Double -- ^ /x/, the sample data.\n -> Double\nweightedAvg k q x\n | G.any isNaN x = modErr \"weightedAvg\" \"Sample contains NaNs\"\n | n == 1 = G.head x\n | q < 2 = modErr \"weightedAvg\" \"At least 2 quantiles is needed\"\n | k < 0 || k >= q = modErr \"weightedAvg\" \"Wrong quantile number\"\n | otherwise = xj + g * (xj1 - xj)\n where\n j = floor idx\n idx = fromIntegral (n - 1) * fromIntegral k / fromIntegral q\n g = idx - fromIntegral j\n xj = sx ! j\n xj1 = sx ! (j+1)\n sx = partialSort (j+2) x\n n = G.length x\n{-# SPECIALIZE weightedAvg :: Int -> Int -> U.Vector Double -> Double #-}\n{-# SPECIALIZE weightedAvg :: Int -> Int -> V.Vector Double -> Double #-}\n\n-- | Parameters /a/ and /b/ to the 'continuousBy' function.\ndata ContParam = ContParam {-# UNPACK #-} !Double {-# UNPACK #-} !Double\n\n-- | O(/n/ log /n/). Estimate the /k/th /q/-quantile of a sample /x/,\n-- using the continuous sample method with the given parameters. This\n-- is the method used by most statistical software, such as R,\n-- Mathematica, SPSS, and S.\ncontinuousBy :: G.Vector v Double =>\n ContParam -- ^ Parameters /a/ and /b/.\n -> Int -- ^ /k/, the desired quantile.\n -> Int -- ^ /q/, the number of quantiles.\n -> v Double -- ^ /x/, the sample data.\n -> Double\ncontinuousBy (ContParam a b) k q x\n | q < 2 = modErr \"continuousBy\" \"At least 2 quantiles is needed\"\n | k < 0 || k > q = modErr \"continuousBy\" \"Wrong quantile number\"\n | G.any isNaN x = modErr \"continuousBy\" \"Sample contains NaNs\"\n | otherwise = (1-h) * item (j-1) + h * item j\n where\n j = floor (t + eps)\n t = a + p * (fromIntegral n + 1 - a - b)\n p = fromIntegral k / fromIntegral q\n h | abs r < eps = 0\n | otherwise = r\n where r = t - fromIntegral j\n eps = m_epsilon * 4\n n = G.length x\n item = (sx !) . bracket\n sx = partialSort (bracket j + 1) x\n bracket m = min (max m 0) (n - 1)\n{-# SPECIALIZE\n continuousBy :: ContParam -> Int -> Int -> U.Vector Double -> Double #-}\n{-# SPECIALIZE\n continuousBy :: ContParam -> Int -> Int -> V.Vector Double -> Double #-}\n\n-- | O(/n/ log /n/). Estimate the range between /q/-quantiles 1 and\n-- /q/-1 of a sample /x/, using the continuous sample method with the\n-- given parameters.\n--\n-- For instance, the interquartile range (IQR) can be estimated as\n-- follows:\n--\n-- > midspread medianUnbiased 4 (U.fromList [1,1,2,2,3])\n-- > ==> 1.333333\nmidspread :: G.Vector v Double =>\n ContParam -- ^ Parameters /a/ and /b/.\n -> Int -- ^ /q/, the number of quantiles.\n -> v Double -- ^ /x/, the sample data.\n -> Double\nmidspread (ContParam a b) k x\n | G.any isNaN x = modErr \"midspread\" \"Sample contains NaNs\"\n | k <= 0 = modErr \"midspread\" \"Nonpositive number of quantiles\"\n | otherwise = quantile (1-frac) - quantile frac\n where\n quantile i = (1-h i) * item (j i-1) + h i * item (j i)\n j i = floor (t i + eps) :: Int\n t i = a + i * (fromIntegral n + 1 - a - b)\n h i | abs r < eps = 0\n | otherwise = r\n where r = t i - fromIntegral (j i)\n eps = m_epsilon * 4\n n = G.length x\n item = (sx !) . bracket\n sx = partialSort (bracket (j (1-frac)) + 1) x\n bracket m = min (max m 0) (n - 1)\n frac = 1 / fromIntegral k\n{-# SPECIALIZE midspread :: ContParam -> Int -> U.Vector Double -> Double #-}\n{-# SPECIALIZE midspread :: ContParam -> Int -> V.Vector Double -> Double #-}\n\n-- | California Department of Public Works definition, /a/=0, /b/=1.\n-- Gives a linear interpolation of the empirical CDF. This\n-- corresponds to method 4 in R and Mathematica.\ncadpw :: ContParam\ncadpw = ContParam 0 1\n\n-- | Hazen's definition, /a/=0.5, /b/=0.5. This is claimed to be\n-- popular among hydrologists. This corresponds to method 5 in R and\n-- Mathematica.\nhazen :: ContParam\nhazen = ContParam 0.5 0.5\n\n-- | Definition used by the SPSS statistics application, with /a/=0,\n-- /b/=0 (also known as Weibull's definition). This corresponds to\n-- method 6 in R and Mathematica.\nspss :: ContParam\nspss = ContParam 0 0\n\n-- | Definition used by the S statistics application, with /a/=1,\n-- /b/=1. The interpolation points divide the sample range into @n-1@\n-- intervals. This corresponds to method 7 in R and Mathematica.\ns :: ContParam\ns = ContParam 1 1\n\n-- | Median unbiased definition, /a/=1\\/3, /b/=1\\/3. The resulting\n-- quantile estimates are approximately median unbiased regardless of\n-- the distribution of /x/. This corresponds to method 8 in R and\n-- Mathematica.\nmedianUnbiased :: ContParam\nmedianUnbiased = ContParam third third\n where third = 1/3\n\n-- | Normal unbiased definition, /a/=3\\/8, /b/=3\\/8. An approximately\n-- unbiased estimate if the empirical distribution approximates the\n-- normal distribution. This corresponds to method 9 in R and\n-- Mathematica.\nnormalUnbiased :: ContParam\nnormalUnbiased = ContParam ta ta\n where ta = 3/8\n\nmodErr :: String -> String -> a\nmodErr f err = error $ \"Statistics.Quantile.\" ++ f ++ \": \" ++ err\n\n-- $references\n--\n-- * Weisstein, E.W. Quantile. /MathWorld/.\n-- \n--\n-- * Hyndman, R.J.; Fan, Y. (1996) Sample quantiles in statistical\n-- packages. /American Statistician/\n-- 50(4):361–365. \n", "meta": {"hexsha": "209ee4c1d4c483b48974197043c6782a9c65e79e", "size": 7135, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Quantile.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Quantile.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Quantile.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": 37.3560209424, "max_line_length": 77, "alphanum_fraction": 0.6002803083, "num_tokens": 2064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6534642612796455}} {"text": "{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule NaiveBayes where\n\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\nimport Mnist (LabeledData, groupByLabel, dat)\nimport Data.Function (on)\nimport Numeric.LinearAlgebra (Vector, Matrix, R, size, fromList, toColumns, sumElements, fromRows, (#>), toList)\n\n-- TODO: later expand this by receiving label type and data type\ndata NaiveBayesClassifier = NBC\n { p :: !(Vector R)\n , l :: !(Matrix R)\n }\n\n-- represents a classifier that predicts the class from input sample\nclass Classifier a where\n -- given the prior and likelihood, with a sample data, predict the class\n predict :: a -> Vector R -> Int -- TODO: parameterize label type\n\ninstance Classifier NaiveBayesClassifier where\n predict nbc sample = argmax $ (p nbc) * (l nbc #> sample)\n\n-- divide two integers to make a fraction\nfractionDiv :: Fractional b => Int -> Int -> b\nfractionDiv = (/) `on` fromIntegral\n\n-- calculates the prior probability of a dataset\n-- the data are organized as rows having same label\n-- P(y)\nprior :: LabeledData -> Vector R\nprior ld = fromList $ map (flip fractionDiv totalNum) numElemsPerLabel\n where\n grouped :: [Matrix R] = groupByLabel ld\n numElemsPerLabel :: [Int] = map (fst . size) grouped\n totalNum = sum numElemsPerLabel\n\n-- used as prior distribution of likelihood\nepsilon :: R = 0.001\n\n-- conditional likelihood of each data attributes given the class\n-- P(x | y)\nlikelihood :: LabeledData -> Matrix R -- data_class * data_dimension shape\nlikelihood ld = fromRows $ map attrProb colSumByLabel\n where\n grouped :: [Matrix R] = groupByLabel ld\n colSum :: Matrix R -> [R] = map sumElements . toColumns\n colSumByLabel :: [[R]] = map colSum grouped\n totalSum :: [R] = colSum $ dat ld\n -- create a vector of size DATA_DIMENSION that contains probability of each attributes\n attrProb classSum = fromList $ map (\\ a -> fst a / (epsilon + snd a)) $ zip classSum totalSum\n\n-- find maximum index in the vector\nargmax :: Vector R -> Int\nargmax = fst . maximumBy (comparing snd) . zip [0..] . toList\n", "meta": {"hexsha": "972333ba1a69057490893999838820ba5e7a9383", "size": 2079, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/NaiveBayes.hs", "max_stars_repo_name": "deNsuh/hasml", "max_stars_repo_head_hexsha": "1890aa113b1c85797816d3c44a865990016d6d3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-28T05:16:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-28T05:16:19.000Z", "max_issues_repo_path": "src/NaiveBayes.hs", "max_issues_repo_name": "deNsuh/hasml", "max_issues_repo_head_hexsha": "1890aa113b1c85797816d3c44a865990016d6d3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NaiveBayes.hs", "max_forks_repo_name": "deNsuh/hasml", "max_forks_repo_head_hexsha": "1890aa113b1c85797816d3c44a865990016d6d3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4736842105, "max_line_length": 112, "alphanum_fraction": 0.7061087061, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6521532816907128}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE ViewPatterns #-}\n\nimport Data.Maybe\nimport Numeric.Hamilton\nimport Numeric.LinearAlgebra.Static\nimport qualified Data.Vector.Sized as V\n\ndoublePendulum :: System 4 2\ndoublePendulum = mkSystem' masses coordinates potential\n where\n masses :: R 4\n masses = vec4 1 1 2 2\n coordinates\n :: Floating a\n => V.Vector 2 a\n -> V.Vector 4 a\n coordinates (V2 θ1 θ2) = V4 (sin θ1) (-cos θ1)\n (sin θ1 + sin θ2/2) (-cos θ1 - cos θ2/2)\n potential\n :: Num a\n => V.Vector 4 a\n -> a\n potential (V4 _ y1 _ y2) = (y1 + 2 * y2) * 5 -- assuming g = 5\n\npattern V2 :: a -> a -> V.Vector 2 a\npattern V2 x y <- (V.toList->[x,y])\n where\n V2 x y = fromJust (V.fromList [x,y])\n\npattern V4 :: a -> a -> a -> a -> V.Vector 4 a\npattern V4 x y z a <- (V.toList->[x,y,z,a])\n where\n V4 x y z a = fromJust (V.fromList [x,y,z,a])\n\nconfig0 :: Config 2\nconfig0 = Cfg (vec2 1 0 ) -- initial positions\n (vec2 0 0.5) -- initial velocities\n\nphase0 :: Phase 2\nphase0 = toPhase doublePendulum config0\n\nevolution :: [Phase 2]\nevolution = evolveHam' doublePendulum phase0 [0,0.1 .. 1]\n\nevolution' :: [Phase 2]\nevolution' = iterate (stepHam 0.1 doublePendulum) phase0\n\npositions :: [R 2]\npositions = phsPositions <$> evolution'\n\npositions' :: [R 4]\npositions' = underlyingPos doublePendulum <$> positions\n\nmain :: IO ()\nmain = withRows (take 25 positions) (disp 4)\n\n", "meta": {"hexsha": "05a6fa5717d80cdd1b95bb5f5e5bb941bcffbfbd", "size": 1569, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "code-samples/hamilton/DoublePendulum.hs", "max_stars_repo_name": "mstksg/inCode", "max_stars_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 74, "max_stars_repo_stars_event_min_datetime": "2015-01-23T14:58:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:18:48.000Z", "max_issues_repo_path": "code-samples/hamilton/DoublePendulum.hs", "max_issues_repo_name": "mstksg/inCode", "max_issues_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2016-05-25T21:35:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-28T22:26:17.000Z", "max_forks_repo_path": "code-samples/hamilton/DoublePendulum.hs", "max_forks_repo_name": "mstksg/inCode", "max_forks_repo_head_hexsha": "e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2015-05-12T05:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:24.000Z", "avg_line_length": 26.593220339, "max_line_length": 72, "alphanum_fraction": 0.5844486934, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6520441364155968}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n-- | Pearson's chi squared test.\nmodule Statistics.Test.ChiSquared (\n chi2test\n , chi2testCont\n , module Statistics.Test.Types\n ) where\n\nimport Prelude hiding (sum)\n\nimport Statistics.Distribution\nimport Statistics.Distribution.ChiSquared\nimport Statistics.Function (square)\nimport Statistics.Sample.Internal (sum)\nimport Statistics.Test.Types\nimport Statistics.Types\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\n\n\n\n-- | Generic form of Pearson chi squared tests for binned data. Data\n-- sample is supplied in form of tuples (observed quantity,\n-- expected number of events). Both must be positive.\n--\n-- This test should be used only if all bins have expected values of\n-- at least 5.\nchi2test :: (G.Vector v (Int,Double), G.Vector v Double)\n => Int -- ^ Number of additional degrees of\n -- freedom. One degree of freedom\n -- is due to the fact that the are\n -- N observation in total and\n -- accounted for automatically.\n -> v (Int,Double) -- ^ Observation and expectation.\n -> Maybe (Test ChiSquared)\nchi2test ndf vec\n | ndf < 0 = error $ \"Statistics.Test.ChiSquare.chi2test: negative NDF \" ++ show ndf\n | n > 0 = Just Test\n { testSignificance = mkPValue $ complCumulative d chi2\n , testStatistics = chi2\n , testDistribution = chiSquared ndf\n }\n | otherwise = Nothing\n where\n n = G.length vec - ndf - 1\n chi2 = sum $ G.map (\\(o,e) -> square (fromIntegral o - e) / e) vec\n d = chiSquared n\n{-# INLINABLE chi2test #-}\n{-# SPECIALIZE\n chi2test :: Int -> U.Vector (Int,Double) -> Maybe (Test ChiSquared) #-}\n{-# SPECIALIZE\n chi2test :: Int -> V.Vector (Int,Double) -> Maybe (Test ChiSquared) #-}\n\n\n-- | Chi squared test for data with normal errors. Data is supplied in\n-- form of pair (observation with error, and expectation).\nchi2testCont\n :: (G.Vector v (Estimate NormalErr Double, Double), G.Vector v Double)\n => Int -- ^ Number of additional\n -- degrees of freedom.\n -> v (Estimate NormalErr Double, Double) -- ^ Observation and expectation.\n -> Maybe (Test ChiSquared)\nchi2testCont ndf vec\n | ndf < 0 = error $ \"Statistics.Test.ChiSquare.chi2testCont: negative NDF \" ++ show ndf\n | n > 0 = Just Test\n { testSignificance = mkPValue $ complCumulative d chi2\n , testStatistics = chi2\n , testDistribution = chiSquared ndf\n }\n | otherwise = Nothing\n where\n n = G.length vec - ndf - 1\n chi2 = sum $ G.map (\\(Estimate o (NormalErr s),e) -> square (o - e) / s) vec\n d = chiSquared n\n", "meta": {"hexsha": "a8df688e5bffc084f2b75d68482ee6a436784dba", "size": 2940, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Test/ChiSquared.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-11T23:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:33:10.000Z", "max_issues_repo_path": "Statistics/Test/ChiSquared.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-26T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:27:01.000Z", "max_forks_repo_path": "Statistics/Test/ChiSquared.hs", "max_forks_repo_name": "infinity0/statistics", "max_forks_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-12-14T09:59:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:04:37.000Z", "avg_line_length": 38.6842105263, "max_line_length": 91, "alphanum_fraction": 0.6017006803, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6516767771277444}} {"text": "{-# OPTIONS_GHC -Wall #-}\n{-# OPTIONS_GHC -fno-warn-name-shadowing #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}\n{-# OPTIONS_GHC -fno-warn-missing-methods #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DataKinds #-}\n\nmodule MultivariateNormal ( MultivariateNormal(..) ) where\n\nimport Data.Random hiding ( StdNormal, Normal )\nimport qualified Data.Random as R\nimport Control.Monad.State ( replicateM )\nimport qualified Numeric.LinearAlgebra.HMatrix as H\nimport Numeric.LinearAlgebra.Static\n ( R, vector, extract, Sq, Sym, col,\n tr, linSolve, uncol, chol, (<.>),\n ℝ, (<>), diag, (#>), eigensystem\n )\nimport GHC.TypeLits ( KnownNat, natVal )\nimport Data.Maybe ( fromJust )\n\n\nnormalMultivariate :: KnownNat n =>\n R n -> Sym n -> RVarT m (R n)\nnormalMultivariate mu bigSigma = do\n z <- replicateM (fromIntegral $ natVal mu) (rvarT R.StdNormal)\n return $ mu + bigA #> (vector z)\n where\n (vals, bigU) = eigensystem bigSigma\n lSqrt = diag $ mapVector sqrt vals\n bigA = bigU <> lSqrt\n\nmapVector :: KnownNat n => (ℝ -> ℝ) -> R n -> R n\nmapVector f = vector . H.toList . H.cmap f . extract\n\nsumVector :: KnownNat n => R n -> ℝ\nsumVector x = x <.> 1\n\ndata family MultivariateNormal k :: *\n\ndata instance MultivariateNormal (R n) = MultivariateNormal (R n) (Sym n)\n\ninstance KnownNat n => Distribution MultivariateNormal (R n) where\n rvar (MultivariateNormal m s) = normalMultivariate m s\n\nnormalLogPdf :: KnownNat n =>\n R n -> Sym n -> R n -> Double\nnormalLogPdf mu bigSigma x = - sumVector (mapVector log (takeDiag' dec))\n - 0.5 * (fromIntegral $ natVal mu) * log (2 * pi)\n - 0.5 * s\n where\n dec = chol bigSigma\n t = uncol $ fromJust $ linSolve (tr dec) (col $ x - mu)\n u = mapVector (\\x -> x * x) t\n s = sumVector u\n\nnormalPdf :: KnownNat n =>\n R n -> Sym n -> R n -> Double\nnormalPdf mu sigma x = exp $ normalLogPdf mu sigma x\n\ntakeDiag' :: KnownNat n => Sq n -> R n\ntakeDiag' = vector . H.toList . H.takeDiag . extract\n\ninstance KnownNat n => PDF MultivariateNormal (R n) where\n pdf (MultivariateNormal m s) = normalPdf m s\n logPdf (MultivariateNormal m s) = normalLogPdf m s\n", "meta": {"hexsha": "e6251ebe2c980dcf63d6b885237cd3177b4e1a62", "size": 2561, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/MultivariateNormal.hs", "max_stars_repo_name": "idontgetoutmuch/Kalman", "max_stars_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2015-03-13T16:16:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T00:33:51.000Z", "max_issues_repo_path": "test/MultivariateNormal.hs", "max_issues_repo_name": "f-o-a-m/Kalman", "max_issues_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-31T20:04:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-31T20:04:27.000Z", "max_forks_repo_path": "test/MultivariateNormal.hs", "max_forks_repo_name": "f-o-a-m/Kalman", "max_forks_repo_head_hexsha": "619d57e980d53c43bb1675efb17c73127fa924d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-08-23T16:00:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-02T17:40:49.000Z", "avg_line_length": 35.5694444444, "max_line_length": 78, "alphanum_fraction": 0.5939086294, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6516218933381}} {"text": "module Xor where\n\nimport Nnaskell\nimport Numeric.LinearAlgebra.Data\n\nxorNN = do nn <- randomNN [2, 2, 1]\n return $ head $ drop 5000 $ optimizeCost (cost xorTD) nn\n\nxorTD :: [(Vector R, Vector R)]\nxorTD = [ (vector [0.0, 0.0], vector [0.0])\n , (vector [1.0, 0.0], vector [1.0])\n , (vector [0.0, 1.0], vector [1.0])\n , (vector [1.0, 1.0], vector [0.0])\n ]\n", "meta": {"hexsha": "d82c662580d247f1506ffa8c0987c1ca4ec394c1", "size": 392, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Xor.hs", "max_stars_repo_name": "tsoding/nnaskell", "max_stars_repo_head_hexsha": "241c0a568a6eda967c1221f9a72706e75da09d2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-10-31T19:58:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T14:52:00.000Z", "max_issues_repo_path": "src/Xor.hs", "max_issues_repo_name": "tsoding/nnaskell", "max_issues_repo_head_hexsha": "241c0a568a6eda967c1221f9a72706e75da09d2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2017-11-01T16:54:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-16T22:14:59.000Z", "max_forks_repo_path": "src/Xor.hs", "max_forks_repo_name": "tsoding/nnaskell", "max_forks_repo_head_hexsha": "241c0a568a6eda967c1221f9a72706e75da09d2e", "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.1333333333, "max_line_length": 67, "alphanum_fraction": 0.5484693878, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6514672165606786}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n-- |\n-- Module : Statistics.Autocorrelation\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Functions for computing autocovariance and autocorrelation of a\n-- sample.\n\nmodule Statistics.Autocorrelation\n (\n autocovariance\n , autocorrelation\n ) where\n\nimport Prelude hiding (sum)\nimport Statistics.Function (square)\nimport Statistics.Sample (mean)\nimport Statistics.Sample.Internal (sum)\nimport qualified Data.Vector.Generic as G\n\n-- | Compute the autocovariance of a sample, i.e. the covariance of\n-- the sample against a shifted version of itself.\nautocovariance :: (G.Vector v Double, G.Vector v Int) => v Double -> v Double\nautocovariance a = G.map f . G.enumFromTo 0 $ l-2\n where\n f k = sum (G.zipWith (*) (G.take (l-k) c) (G.slice k (l-k) c))\n / fromIntegral l\n c = G.map (subtract (mean a)) a\n l = G.length a\n\n-- | Compute the autocorrelation function of a sample, and the upper\n-- and lower bounds of confidence intervals for each element.\n--\n-- /Note/: The calculation of the 95% confidence interval assumes a\n-- stationary Gaussian process.\nautocorrelation :: (G.Vector v Double, G.Vector v Int) => v Double -> (v Double, v Double, v Double)\nautocorrelation a = (r, ci (-), ci (+))\n where\n r = G.map (/ G.head c) c\n where c = autocovariance a\n dllse = G.map f . G.scanl1 (+) . G.map square $ r\n where f v = 1.96 * sqrt ((v * 2 + 1) / l)\n l = fromIntegral (G.length a)\n ci f = G.cons 1 . G.tail . G.map (f (-1/l)) $ dllse\n", "meta": {"hexsha": "9f7c2d15518b820acc2b580c6fe6700dfca10f80", "size": 1675, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Autocorrelation.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 182, "max_stars_repo_stars_event_min_datetime": "2015-01-04T04:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T18:39:40.000Z", "max_issues_repo_path": "Statistics/Autocorrelation.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 105, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T14:21:32.000Z", "max_forks_repo_path": "Statistics/Autocorrelation.hs", "max_forks_repo_name": "StefanHubner/statistics", "max_forks_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2015-02-13T00:40:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T11:19:16.000Z", "avg_line_length": 33.5, "max_line_length": 100, "alphanum_fraction": 0.6471641791, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6513847653047671}} {"text": "module Mandelbrot where\n\nimport Data.Complex\nimport Data.Maybe\nimport Data.Word\nimport qualified Data.Array.Repa as R\nimport Data.Array.Repa hiding (map,zip,foldr)\n\nmandelbrot :: Complex Double -> Complex Double -> Complex Double\nmandelbrot c z = z*z + c\n\nisMandelbrot :: Int -> Complex Double -> Maybe Int\nisMandelbrot n c = case (n' < n) of\n True -> Just n'\n False -> Nothing\n where\n m = iterate (mandelbrot c) 0\n n' = length . take n . takeWhile (\\z -> magnitude z < 2) $ m\n\nisMandelbrot2 :: Int -> Complex Double -> Int\nisMandelbrot2 n c = case (n' < n) of\n True -> n'\n False -> (-1)\n where\n m = iterate (mandelbrot c) 0\n n' = length. take n . takeWhile (\\z -> magnitude z <2) $ m\n\narray :: Double -> Complex Double -> Int -> Array D DIM2 (Complex Double)\narray size centre n = fromFunction (Z:.n:.n) posToVal\n where\n dx = size / (fromIntegral n)\n posToVal (Z:.i:.j) = (((fromIntegral i)*dx - size/2) :+ ((fromIntegral j)*dx - size/2)) + centre \n\ngenMandelbrot :: Int -> Int -> Double -> Complex Double -> Array D DIM2 (Word8,Word8,Word8)\ngenMandelbrot res n size centre = cs\n where\n zs = array size centre res\n cs = R.map (toColor2 . isMandelbrot2 n) zs\n --cs = R.map toColor ms\n\ntoColor2 :: Int -> (Word8,Word8,Word8)\ntoColor2 n = case (n==(-1)) of\n True -> (0,0,0)\n False -> (255 - (fromIntegral n),fromIntegral n,50)\n\n\ntoColor :: Maybe Int -> (Word8,Word8,Word8)\ntoColor (Just n) = (255-(fromIntegral n),(fromIntegral n),(fromIntegral n))\ntoColor Nothing = (0,0,0)\n\ntoBw2 :: Int -> (Word8, Word8, Word8)\ntoBw2 n = case (n==(-1)) of\n True -> (0,0,0)\n False ->(255-n', 255-n', 255-n')\n where n' = fromIntegral n\n\ntoBw :: Maybe Int -> (Word8,Word8,Word8)\ntoBw (Just n') = let n = fromIntegral n' in (255-n,255-n,255-n)\ntoBw Nothing = (0,0,0)\n\n", "meta": {"hexsha": "d056014a9174d075b36c11487c1cdd349f8de131", "size": 1918, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Mandelbrot.hs", "max_stars_repo_name": "ahgibbons/HaskMandelbrot", "max_stars_repo_head_hexsha": "339a34a6e513ac26b0b9ad1364437dddc19d3e5e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Mandelbrot.hs", "max_issues_repo_name": "ahgibbons/HaskMandelbrot", "max_issues_repo_head_hexsha": "339a34a6e513ac26b0b9ad1364437dddc19d3e5e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mandelbrot.hs", "max_forks_repo_name": "ahgibbons/HaskMandelbrot", "max_forks_repo_head_hexsha": "339a34a6e513ac26b0b9ad1364437dddc19d3e5e", "max_forks_repo_licenses": ["BSD-3-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.4426229508, "max_line_length": 102, "alphanum_fraction": 0.5948905109, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6513847547432621}} {"text": "-- |\n\nmodule Math.Algebra.Roots (zeros) where\n\nimport Data.Complex\nimport Polynomial.Roots\n\n-- roots of a polynomial --------------------------------------------------------\n-- no dealing with the complex problem of calculating roots, we will use\n-- the Polynomial.Roots module of the `dsp` package, complex roots will look a\n-- bit 'odd' to many as the output format is x :+ y for x + iy\nzeros :: RealFloat a => [Complex a]\nzeros = roots 1e-16 1000 [1,3,-10]\n-- note that this uses Laguerre's method\n-- >>> zeros\n-- [0.5 :+ 0.0,(-0.2) :+ 0.0]\n", "meta": {"hexsha": "02a61024e34b8a7793c03aa59557d9b7402b5bf8", "size": 544, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/Algebra/Roots.hs", "max_stars_repo_name": "karetsu/swh", "max_stars_repo_head_hexsha": "518e3b347e609eeae4187ab4de9f55901129e4ba", "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/Math/Algebra/Roots.hs", "max_issues_repo_name": "karetsu/swh", "max_issues_repo_head_hexsha": "518e3b347e609eeae4187ab4de9f55901129e4ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/Algebra/Roots.hs", "max_forks_repo_name": "karetsu/swh", "max_forks_repo_head_hexsha": "518e3b347e609eeae4187ab4de9f55901129e4ba", "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.0, "max_line_length": 81, "alphanum_fraction": 0.6121323529, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6507218833663856}} {"text": "module Main where\n\nimport Numeric.LinearAlgebra\n\nx1 = [ 3, 4, 5, 6, 7, 8] :: [Double]\ny1 = [150, 155, 150, 170, 160, 175] :: [Double]\n\nx2 = [-0.2, 0.2, 1] :: [Double]\ny2 = [0.49, 0.64, 1.39] :: [Double]\n\nx3 = [1,2,3,4] :: [Double]\ny3 = [6,5,7,10] :: [Double]\n\n-- | Least square estimator\n--\nlse :: Int -> [Double] -> [Double] -> Matrix Double\nlse deg x y = pinv (tx' <> x') <> tx' <> y'\n where\n\n tx' = trans x'\n\n x' :: Matrix Double \n x' = (lx> pow x (deg-1) ++ xs) [] x)\n\n y' :: Matrix Double\n y' = (ly><1) y\n\n lx = length x\n ly = length y\n\n pow x deg = go [] x deg\n where go :: [Double] -> Double -> Int -> [Double]\n go acc _ 0 = 1:acc\n go acc x deg = go (x**fromIntegral(deg):acc) x (deg-1)\n\n-- | prettify for gnuplot\n--\ntoF :: Matrix Double -> String\ntoF = concatMap (\\(i,[x]) -> show (round' x) ++ \"*\" ++ \"x**\"++ (show i) ++ \" + \") . zip [0..] . toLists \n where round' = (/100) . fromInteger . round . (*100) :: Double -> Double\n\n-- | Mean square estimator\nmse :: Matrix Double -> [(Double, Double)] -> Double\nmse m xys = nth . sum $ map (\\(x,y) -> ((f x) - y)**2) xys\n where l = toLists m :: [[Double]]\n f x = sum $ zipWith (\\(i, [w]) x -> w * x^i) (zip [0..] l) (repeat x)\n nth = (/ fromIntegral (length xys))\n\n-- | data -> fitting -> gnuplot\nplot :: Int -> [Double] -> [Double] -> String\nplot deg x y = toF $ lse deg x y", "meta": {"hexsha": "ca2f3b611c383472d154093194b138c31d0976d5", "size": 1489, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Haskell/machine-learning/lin-regression/lin-regression.hs", "max_stars_repo_name": "cirquit/random-code", "max_stars_repo_head_hexsha": "2fddf21f1d884ab51e0b5a323da81a8fb4f0c6be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-09T05:31:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T05:31:07.000Z", "max_issues_repo_path": "Haskell/machine-learning/lin-regression/lin-regression.hs", "max_issues_repo_name": "cirquit/Personal-Repository", "max_issues_repo_head_hexsha": "2fddf21f1d884ab51e0b5a323da81a8fb4f0c6be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Haskell/machine-learning/lin-regression/lin-regression.hs", "max_forks_repo_name": "cirquit/Personal-Repository", "max_forks_repo_head_hexsha": "2fddf21f1d884ab51e0b5a323da81a8fb4f0c6be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1960784314, "max_line_length": 105, "alphanum_fraction": 0.4808596373, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6503073190886292}} {"text": "-- This example uses the JuicyPixels package the generate the png.\nimport Control.Lens\nimport Data.Bool\nimport Data.Complex\nimport Data.Dense\nimport Data.Word\n\nimport Codec.Picture\n\n-- Simple example to compute the manelbrot set in parallel. Compile with\n--\n-- ghc -O2 -threaded examples/mandel\n--\n-- (add -fllvm is available) and run with\n--\n-- examples/mandel +RTS -N4\n--\n-- replacing 4 with the number of processors to use.\n\nmain :: IO ()\nmain = do\n let plane = complexPlane (V2 2000 2000) ((-2.5) :+ (-2)) (1.5 :+ 2)\n m = mandel 16 <$> plane\n img = mkImage (manifest m)\n\n savePngImage \"mandel.png\" (ImageY8 img)\n\ncomplexPlane\n :: V2 Int -- ^ total size\n -> Complex Double -- ^ lower bound\n -> Complex Double -- ^ upper bound\n -> Delayed V2 (Complex Double)\ncomplexPlane l@(V2 x y) a@(rmin :+ imin) (rmax :+ imax) =\n genDelayed l $\n \\(V2 j i) -> a + (rstep * fromIntegral i :+ istep * fromIntegral j)\n where\n rstep = (rmax - rmin) / (fromIntegral x - 1)\n istep = (imax - imin) / (fromIntegral y - 1)\n\nmandel :: Int -> Complex Double -> Word8\nmandel n = bool 0 255 . any ((>2) . magnitude) . take n . criticalOrbit\n\ncriticalOrbit :: Complex Double -> [Complex Double]\ncriticalOrbit z0 = iterate (quadratic z0) 0\n where quadratic c z = z*z + c\n\nmkImage :: SArray V2 Word8 -> Image Pixel8\nmkImage a = Image x y (a^.vector)\n where V2 x y = extent a\n\n", "meta": {"hexsha": "9292428f9a8a00aeb150f4290f086a94fdb334a5", "size": 1392, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/mandel.hs", "max_stars_repo_name": "cchalmers/shaped-vector", "max_stars_repo_head_hexsha": "a84e7e43c7efca0ddfe1a5f60ee18cf006dc04fa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-05-11T18:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-11T18:06:45.000Z", "max_issues_repo_path": "examples/mandel.hs", "max_issues_repo_name": "cchalmers/shaped-vector", "max_issues_repo_head_hexsha": "a84e7e43c7efca0ddfe1a5f60ee18cf006dc04fa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-04-11T09:35:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T14:29:07.000Z", "max_forks_repo_path": "examples/mandel.hs", "max_forks_repo_name": "cchalmers/shaped-vector", "max_forks_repo_head_hexsha": "a84e7e43c7efca0ddfe1a5f60ee18cf006dc04fa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-04-11T09:29:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T07:59:38.000Z", "avg_line_length": 27.2941176471, "max_line_length": 72, "alphanum_fraction": 0.650862069, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6501593541352513}} {"text": "\n-- | Metropolis-adjusted Langevin diffusion. See, ex: Girolami and Calderhead\n-- (2011):\n--\n-- http://onlinelibrary.wiley.com/doi/10.1111/j.1467-9868.2010.00765.x/abstract\n\nmodule Strategy.MALA (mala, adaMala) where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.State.Strict\nimport Data.Maybe\nimport Math.Probably.Sampler\nimport Math.Probably.Types\nimport Math.Probably.Utils\nimport Numeric.LinearAlgebra\n\n-- | The MALA transition operator. Takes a step size tunable parameter.\nmala :: Maybe Double -> Transition Double\nmala e = do\n Chain current@(ds, cs) target _ t <- get\n let stepSize = fromMaybe t e\n pcs <- lift $ perturb target cs stepSize\n zc <- lift unit\n\n let cMean = localMean target cs stepSize\n pMean = localMean target pcs stepSize\n next = nextState target current cMean (ds, pcs) pMean stepSize zc\n\n put $ Chain next target (logObjective target next) stepSize\n return next\n\nadaMala :: Transition (Maybe (Double,Int))\nadaMala = do\n Chain current@(ds, cs) target _ madaPars <- get\n let (stepSize, trCount) = case madaPars of\n Nothing -> (0.1, 1)\n Just st -> st\n pcs <- lift $ perturb target cs stepSize\n zc <- lift unit\n\n let cMean = localMean target cs stepSize\n pMean = localMean target pcs stepSize\n ratio = acceptProb target current cMean (ds, pcs) pMean stepSize\n pAccent | isNaN ratio = 0\n | otherwise = ratio\n\n if zc Vector Double -> Double -> Vector Double\nlocalMean target position e = position .+ scaledGradient position where\n grad = handleGradient (gradient target)\n scaledGradient p = (0.5 * e * e) .* grad p\n\nperturb\n :: Target\n -> ContinuousParams\n -> Double\n -> Prob ContinuousParams\nperturb target position e = do\n zs <- fromList <$> replicateM (dim position) unormal\n return $ localMean target position e .+ (e .* zs)\n\nnextState\n :: Target\n -> Parameters\n -> ContinuousParams\n -> Parameters\n -> ContinuousParams\n -> Double\n -> Double\n -> Parameters\nnextState target current cMean proposal pMean e z\n | z < pAccent = proposal\n | otherwise = current\n where\n ratio = acceptProb target current cMean proposal pMean e\n pAccent | isNaN ratio = 0\n | otherwise = ratio\n\nacceptProb\n :: Target\n -> Parameters\n -> ContinuousParams\n -> Parameters\n -> ContinuousParams\n -> Double\n -> Double\nacceptProb target current@(_, cs) cMean proposal@(_, pcs) pMean e =\n exp . min 0 $\n logObjective target proposal + log (sphereGauss cs pMean e)\n - logObjective target current - log (sphereGauss pcs cMean e)\n\n", "meta": {"hexsha": "38a6ad89d61fc7d1a8ff42d363e3b3478f1fb2b0", "size": 3080, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Strategy/MALA.hs", "max_stars_repo_name": "glutamate/probably-baysig", "max_stars_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2015-02-12T05:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:19:37.000Z", "max_issues_repo_path": "src/Strategy/MALA.hs", "max_issues_repo_name": "silky/probably-baysig", "max_issues_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Strategy/MALA.hs", "max_forks_repo_name": "silky/probably-baysig", "max_forks_repo_head_hexsha": "59c99bf29d6948b82243a4d778650d8e503962d9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-08-31T09:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T11:09:04.000Z", "avg_line_length": 29.6153846154, "max_line_length": 102, "alphanum_fraction": 0.6753246753, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6500470374103197}}