File size: 86,153 Bytes
5697766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{"text": "module Y2016.M12.D14.Solution where\n\nimport Data.Array (elems, listArray)\nimport Data.Complex\n\n-- import available via 1HaskellADay git repository\n\nimport Data.Matrix\n\n{--\nI'm thinking about quantum computation. IBM has released a 5-qubit computer\nfor public experimentation. So, let's experiment.\n\nOne way to go about that is to dive right in, so, yes, if you wish: dive\nright in.\n\nAnother approach is to comprehend the maths behind quantum computation.\n\nSo, let's look at that.\n\nI was going to bewail that Shor's prime factors algorithm needs 7 qubits to\nwork, but, NEWSFLASH! IBM has added Shor's algorithm to their API, so ...\n\nCANCEL BEWAILMENT.\n\n*ahem*\n\nMoving on.\n\nFirst, let's look at qubits. Qubits are 'bra-ket'ted numbers (ket numbers)\nwith the representation\n\n|0> =  | 1 |   or    |1> = | 0 |\n       | 0 |               | 1 |\n\nOOH! MATRICES!\n\nexercise 1. Represent ket0 and ket1 states as matrices in Haskell\n--}\n\ndata Qubit = Qbit (Matrix (Complex Float))  --- where Float is 1 or 0 but okay\n\ninstance Show Qubit where\n   show (Qbit mat) = '|':complexify mat ++ \">\"\n\ncomplexify :: Matrix (Complex Float) -> String\ncomplexify = showC . determinant . cross (fromLists [[0, 1]])\n\nshowC :: (Eq a, Show a, Num a) => Complex a -> String\nshowC (x :+ 0) = show x\nshowC (0 :+ x) = (if x == 1 then \"\" else show x) ++ \"i\"\nshowC c = show c\n\nket0, ket1 :: Qubit\nket0 = Qbit (fromLists [[1],[0]])\nket1 = Qbit (fromLists [[0],[1]])\n\n{--\nIt MAY be helpful to have a show-instance of a qubit that abbreviates the\ncomplex number to something more presentable. Your choice.\n\nA qubit state is most-times in a super-position of |0> or |1> and we represent\nthat as \n\n|ψ> = α|0> + β|1>\n\nAnd we KNOW that |α|² + |β|² = 1\n\nYAY! Okay. Whatever.\n\nSo, we have a qubit at |0>-state and we want to flip it to |1>-state, or vice\nversa. How do we do that?\n\nWe put it through a Pauli X gate\n\nThe Pauli X operator is =  | 0 1 |\n                           | 1 0 |\n\nThat is to say, zero goes to 1 and 1 goes to zero.\n\nexcercise 2: represent the Pauli X, Y, and Z operators\n--}\n\ndata PauliOperator = POp (Matrix (Complex Float))\n\ndata Cnum = C (Complex Float)\n\ninstance Show Cnum where show (C c) = showC c\n\nprintPauli :: PauliOperator -> IO ()\nprintPauli (POp mat) =\n   pprint (M (listArray ((1,1),(2,2)) (map C (elems (matrix mat)))))\n\npauliX, pauliY, pauliZ :: PauliOperator\npauliX = POp (fromLists [[0,1],[1,0]])\npauliY = POp (fromLists [[0,0 :+ (-1)],[0 :+ 1,0]])\npauliZ = POp (fromLists [[1,0],[0,-1]])\n\n{--\n*Y2016.M12.D14.Solution> printPauli pauliX\nMatrix 2x2\n| 0.0 1.0 |\n| 1.0 0.0 |\n--}\n\n-- exercise 3: rotate the qubits ket0 and ket1 through the pauliX operator\n-- (figure out what that means). The intended result is:\n\n-- X|0> = |1> and X|1> = |0>\n\n-- what are your results?\n\nrotate :: PauliOperator -> Qubit -> Qubit\nrotate (POp p) (Qbit q) = Qbit (cross p q)\n\n{--\n*Y2016.M12.D14.Solution> rotate pauliX ket0 ~> |1.0>\n*Y2016.M12.D14.Solution> rotate pauliX ket1 ~> |0.0> \n\nBAM!\n--}\n", "meta": {"hexsha": "69197edca53099382fcf8b0e9d9a4f62502e5b08", "size": 2970, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "exercises/HAD/Y2016/M12/D14/Solution.hs", "max_stars_repo_name": "nernstp/1had", "max_stars_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 250, "max_stars_repo_stars_event_min_datetime": "2016-06-20T19:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T06:39:38.000Z", "max_issues_repo_path": "exercises/HAD/Y2016/M12/D14/Solution.hs", "max_issues_repo_name": "nernstp/1had", "max_issues_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-08-18T16:46:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-27T11:09:26.000Z", "max_forks_repo_path": "exercises/HAD/Y2016/M12/D14/Solution.hs", "max_forks_repo_name": "nernstp/1had", "max_forks_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2016-06-28T06:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-08T01:42:30.000Z", "avg_line_length": 24.3442622951, "max_line_length": 78, "alphanum_fraction": 0.6595959596, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.8479705559017267}}
{"text": "module Y2016.M06.D21.Solution where\n\n{--\nSo what happens when things become Complex?\n\nWith the Quadratic type, enhance solver in such a way that it gives all\nsolutions, whether they be Real or Complex.\n\nThis exercise is an elaboration of yesterday's that solved quadratic equations\nwith Real roots with the quadratic formula:\n\n    -b +/- sqrt (b^2 - 4ac)\nx = -----------------------\n              2a\n\nfor the quadratic equation\n\nax^2 + bx + c = 0\n--}\n\nimport Data.Complex\n\ndata QuadraticEq = Q { a,b,c :: Float }\n\nq :: (Float, Float, Float) -> QuadraticEq\nq (a,b,c) = Q a b c\n\nsolver :: QuadraticEq -> [Complex Float]\nsolver q = [φ] <*> [(+),(-)] <*> [q]\n\nφ :: (Float -> Float -> Float) -> QuadraticEq -> Complex Float\nφ f q = let imag2 = b q ^ 2 - 4 * a q * c q\n            den   = 2 * a q\n            real  = negate (b q) / den\n            imag  = sqrt (abs imag2) / den in\n   if imag2 < 0 then real :+ f 0 imag else f real imag :+ 0\n\n-- with the new solver, solve the below quadratic equations represented by\n-- the coefficients (a,b,c):\n\neqs :: [(Float, Float, Float)]\neqs = [(1,-6,25), (1,10,29), (1,-6,13), (2,6,29)]\n\n{--\n*Y2016.M06.D21.Solution> map (solver . q) eqs ~>\n[[3.0 :+ 4.0,3.0 :+ (-4.0)],[(-5.0) :+ 2.0,(-5.0) :+ (-2.0)],\n [3.0 :+ 2.0,3.0 :+ (-2.0)],[(-1.5) :+ 3.5,(-1.5) :+ (-3.5)]]\n--}\n\n{-- BONUS ------------------------------------------------------------------\n\nThe default Show-instance for QuadraticEq 'leaves something to be desired.'\n\nWrite your own Show-instance for QuadraticEq that for (Q 2 3 4) shows:\n\n\"2x^2 + 3x + 4 = 0\"\n--}\n\ninstance Show QuadraticEq where\n   show (Q a b c) =\n      mbshow a ++ \"x^2\" ++ showSign b ++ \"x\" ++ showSign c ++ \" = 0\"\n\nshowSign :: Float -> String\nshowSign x = ' ':(if x < 0 then '-' else '+'):' ':mbshow (abs x)\n\nmbshow :: Float -> String\nmbshow x = if x == 1 then \"\" else showdec x\n\nshowdec :: Float -> String\nshowdec x = if floor x == ceiling x then show (floor x) else show x\n\n{--\n*Y2016.M06.D21.Solution> map q eqs ~>\n[x^2 - 6x + 25 = 0,x^2 + 10x + 29 = 0,x^2 - 6x + 13 = 0,2x^2 + 6x + 29 = 0]\n--}\n", "meta": {"hexsha": "583bdd6cc7086e80ac28e16158bde34a8865c9a2", "size": 2063, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "exercises/HAD/Y2016/M06/D21/Solution.hs", "max_stars_repo_name": "nernstp/1had", "max_stars_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 250, "max_stars_repo_stars_event_min_datetime": "2016-06-20T19:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T06:39:38.000Z", "max_issues_repo_path": "exercises/HAD/Y2016/M06/D21/Solution.hs", "max_issues_repo_name": "nernstp/1had", "max_issues_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-08-18T16:46:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-27T11:09:26.000Z", "max_forks_repo_path": "exercises/HAD/Y2016/M06/D21/Solution.hs", "max_forks_repo_name": "nernstp/1had", "max_forks_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2016-06-28T06:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-08T01:42:30.000Z", "avg_line_length": 27.1447368421, "max_line_length": 78, "alphanum_fraction": 0.5535627727, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308128813471, "lm_q2_score": 0.9073122244934722, "lm_q1q2_score": 0.846913187246125}}
{"text": "module Eris.Pantheon.Minkowski where\n\nimport Eris.Meta.DataTypes\nimport Numeric.LinearAlgebra hiding (Vector)\nimport qualified Data.Vector.Storable as DV\n\n-- import Numeric.LinearAlgebra.Data\n{-\n   This module contains different derivation of Minkowski distance. \n   These functions define distance between two high dimensional vectors X and Y.\n   One distance definition may have many different names .\n\n   1. sad (sub absolute difference, taxicab metric, manhattan distance, l1-norm of (X-Y) ) \n-}\n{- L1 norm family -}\n-- Sum of Absolute Difference: norm(l1) of (v1 - v2)\n-- sad , taxicab, manhattan distance are different names of the same implementation.\nsad :: Vector -> Vector -> Double\nsad v1 v2 = norm_1 (v1 - v2)\n\ntaxicab :: Vector -> Vector -> Double\ntaxicab = sad\n\nmanhattanDistance :: Vector -> Vector -> Double\nmanhattanDistance = sad\n\n-- | Mean Absolute Difference \nmad :: Vector -> Vector -> Double\nmad v1 v2 = norm1 / n\n  where\n    norm1 = sad v1 v2\n    n = fromIntegral . DV.length $ v1\n\n{- L2 norm based -}\n-- | Euclidean Distance \n--\neuclideanDistance :: Vector -> Vector -> Double\neuclideanDistance v1 v2 = norm_2 (v1 - v2)\n\n-- | (L2 norm based) Sum Suqred Difference\n-- Squred euclidean distance\nssd :: Vector -> Vector -> Double\nssd v1 v2 = v <.> v\n  where\n    v = v1 - v2\n\n-- | (L2 norm based) Mean Sqaured Error (MSE)\n--  ssd averaged over the vector\nmse :: Vector -> Vector -> Double\nmse v1 v2 = squaredL2 / n\n  where\n    squaredL2 = ssd v1 v2\n    n = fromIntegral . DV.length $ v1\n\n-- | (L2 norm based) Root mean squared Error (rmse)\n-- euclidean distance averged over the vector\nrmse :: Vector -> Vector -> Double\nrmse v1 v2 = euclideanDistance v1 v2 / sqrtN\n  where\n    sqrtN = sqrt . fromIntegral $ DV.length v1\n\n-- | Minkowski Distance\n-- This is a degenerate case of Minkowski distance \n-- in this case p is an Integral number for sure.\nminkowskiDistance :: Int -> Vector -> Vector -> Double\nminkowskiDistance p v1 v2 =\n  let vDiff = v1 - v2\n      absV = DV.map abs vDiff\n  in lpnorm p absV\n  where\n    lpnorm :: Int -> Vector -> Double\n    lpnorm 0 vec =\n      let vl = -DV.length vec\n      in norm_1 $ DV.map (f0 vl) vec\n    lpnorm p vec = nroot p $ norm_1 $ DV.map (\\n -> n ^ p) vec\n    nroot\n      :: (Integral a, Floating b)\n      => a -> b -> b\n    nroot 0 _ = 1\n    nroot n f = f ** (1 / fromIntegral n)\n    f0 :: Int -> Double -> Double\n    f0 l v = (2 ^ l) * (v / (1 + v))\n\n{- Minkowski based (p = 0, p -> infinity) -}\n-- | Chebyshev Distance \n-- The limiting case of Minkowski distance when p reaches infinity \ncbv :: Vector -> Vector -> Double\ncbv v1 v2 =\n  let absV = DV.map abs $ v1 - v2\n  in DV.maximum absV\n\n-- | Canberra Distance \n--\ncbr :: Vector -> Vector -> Double\ncbr v1 v2 =\n  let sum1 = DV.sum . (DV.map abs) $ v1\n      sum2 = DV.sum . (DV.map abs) $ v2\n  in (sad v1 v2) / (sum1 + sum2)\n", "meta": {"hexsha": "70bb5b78448239bbf859ec7d5cc50122c6a728d6", "size": 2840, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Eris/Pantheon/Minkowski.hs", "max_stars_repo_name": "emmettng/eris", "max_stars_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Eris/Pantheon/Minkowski.hs", "max_issues_repo_name": "emmettng/eris", "max_issues_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Eris/Pantheon/Minkowski.hs", "max_forks_repo_name": "emmettng/eris", "max_forks_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "max_forks_repo_licenses": ["BSD-3-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.6868686869, "max_line_length": 91, "alphanum_fraction": 0.6545774648, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632247867715, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8430000277679197}}
{"text": "module Mllib.Metrics\n    ( Metric\n    , euclideanDistance\n    , minkowskiDistance\n    , chebyshevDistance\n    , manhattanDistance\n    ) where\n\nimport Mllib.Types\n\nimport Numeric.LinearAlgebra (cmap, sumElements, maxElement)\n\ntype Metric = (Vector R) -> (Vector R) -> R\n\neuclideanDistance :: Metric\neuclideanDistance v1 v2 = (sumElements (cmap (**2) (v1 - v2))) ** (1/2)\n\nminkowskiDistance :: Int -> Metric\nminkowskiDistance p v1 v2 = (sumElements (cmap (**pc) (v1 - v2))) ** (1 / pc)\n  where\n    pc = fromIntegral p\n\nchebyshevDistance :: Metric\nchebyshevDistance v1 v2 = maxElement $ cmap (abs) (v1 - v2)\n\nmanhattanDistance :: Metric \nmanhattanDistance v1 v2 = sumElements $ cmap (abs) (v1 - v2)\n\n-- TODO test all above\n\n-- TODO more metrics\n-- -- Hamming\n-- -- cos(x,z)\n-- -- Canberra distance\n-- -- ? Levenstein\n\n\n", "meta": {"hexsha": "a10e9d3716a93671df71000de7f676c1a9c1dfd1", "size": 816, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Mllib/Metrics.hs", "max_stars_repo_name": "vsha96/mllib", "max_stars_repo_head_hexsha": "6ba1229b41ec92ddd67d5ef898f462089e9a229b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-07T09:20:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T09:20:08.000Z", "max_issues_repo_path": "src/Mllib/Metrics.hs", "max_issues_repo_name": "vsha96/mllib", "max_issues_repo_head_hexsha": "6ba1229b41ec92ddd67d5ef898f462089e9a229b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mllib/Metrics.hs", "max_forks_repo_name": "vsha96/mllib", "max_forks_repo_head_hexsha": "6ba1229b41ec92ddd67d5ef898f462089e9a229b", "max_forks_repo_licenses": ["BSD-3-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.4736842105, "max_line_length": 77, "alphanum_fraction": 0.6703431373, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102542943773, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.8334608982700007}}
{"text": "-- | Markov chain weather change simulations\nmodule Statistics.MarkovChain.MarkovChain \n  ( steadyState1\n  , steadyState2\n  , steadyState3\n  , steadyState4\n  ) where\n\n-- all modules required by the below\nimport Data.Complex                   -- base\nimport Data.Ord\nimport Numeric.LinearAlgebra.Data     -- hmatrix\nimport System.Random\n\nimport qualified Data.List as L\nimport qualified Numeric.LinearAlgebra.HMatrix as M\n\n\n-- steady state of Markov chain -------------------------------------------------\n-- we will write 4 approaches\n-- 1. raise the state matrix to a high power, the limiting distribution is the\n--    steady state\n-- 2. solve the system of eqns: pi P = pi and sum_i=1^3 pi_i = 1\n-- 3. using Perron-Frobenius theorem that eigenvector for the largest eval is\n--    proportional to pi, so we find it and normalise it\n-- 4. running a Monte Carlo simulation\n\n-- The setup:\ntransition :: Matrix R\ntransition = (3><3)[0.5, 0.4, 0.1,\n                    0.3, 0.2, 0.5,\n                    0.5, 0.3, 0.2]\n\ndata Weather = Fine | Cloudy | Rain deriving (Eq, Show)\n\n-- route 1:\nsteadyState1 :: Matrix R\nsteadyState1 = M.takeRows 1 $ foldl (M.<>) t [t | _ <- [1..n]]\n  where\n    n = 10^6\n    t = transition\n-- >>> disp 4 steadyState1\n-- 1x3\n-- 0.4375  0.3125  0.2500\n\n\n-- route 2:\nsystem :: Matrix R\nsystem = takeRows 2 (tr (transition - ident 3)) === matrix 3 [1,1,1]\n\ntarget :: Matrix R\ntarget = (3><1) [0,0,1 :: R]\n\nsteadyState2 :: Maybe (Matrix R)\nsteadyState2 = M.linearSolve system target\n-- >>> steadyState2\n-- Just (3><1)\n--  [ 0.4375\n--  , 0.3125\n--  ,   0.25 ]\n\n\n-- route 3:\nevals :: Vector (Complex Double)\nevecs :: Matrix (Complex Double)\n(evals, evecs) = M.eig (M.tr transition)\n\nsizes :: [R]\nsizes = map M.magnitude (toList evals)\n\nmaxid :: (Ord a, Num a, Enum a) => [a] -> (a, Int)\nmaxid xs = L.maximumBy (comparing fst) (zip xs [0..])\n\ngetEvec :: Matrix (Complex Double)\ngetEvec = M.dropColumns m $ M.takeColumns (m+1) evecs\n  where\n    m = snd $ maxid sizes\n\nsteadyState3 :: Matrix (Complex Double)\nsteadyState3 = getEvec / scalar (M.sumElements getEvec)\n-- >>> disp 4 steadyState3\n-- (3><1)\n--  [ 0.43749999999999994 :+ 0.0\n--  , 0.31250000000000006 :+ 0.0\n--  , 0.24999999999999997 :+ 0.0 ]\n\n\n-- route 4:\n-- this is absolutely not the best way to do it at all, but its an intuitive\n-- approach for those with little statistical training\n\n-- replicate each rain type as many times it needs to be weighted as given,\n-- this is in order to sample with the correct probability\ngenpop :: Matrix R -> Int -> [Weather]\ngenpop t s = replicate (round (10*t!s!0) :: Int) Fine ++\n             replicate (round (10*t!s!1) :: Int) Cloudy ++\n             replicate (round (10*t!s!2) :: Int) Rain\n\n-- increment a count of each weather occurrence\nincrement :: [Int] -> Weather -> [Int]\nincrement [x,y,z] w = case w of\n                        Fine   -> [x+1,   y,   z]\n                        Cloudy -> [  x, y+1,   z]\n                        Rain   -> [  x,   y, z+1]\nincrement xs _ = error $ \"Needed a [x, y, z], got: \" ++ show xs\n\n\nwToInt :: Weather -> Int\nwToInt Fine   = 0\nwToInt Cloudy = 1\nwToInt Rain   = 2\n\ngetNext :: Weather -> Int -> Weather\ngetNext w n = head . drop n . genpop transition . wToInt $ w\n\n-- our pattern now becomes like:\n-- getNext 3 (getNext 1 (getNext 4 (getNext 8 Fine)))\n\n-- because we are now dealing with random numbers we have to move to IO town\nsteadyState4' :: Int -> IO [Double]\nsteadyState4' n = do\n  g <- newStdGen\n  let scores' = [fromIntegral x / fromIntegral n | x <- scores]\n        where\n          scores = L.foldl' increment [0,0,0] states\n          states = init (L.scanl' getNext Fine steps)\n          steps = take n $ randomRs (0, 9) g\n  return scores'\n\nsteadyState4 :: IO [Double]\nsteadyState4 = steadyState4' (10^6)\n", "meta": {"hexsha": "1eeb433d392d99a414b2bbd9f52cb95c72b19820", "size": 3773, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Statistics/MarkovChain/MarkovChain.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/Statistics/MarkovChain/MarkovChain.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/Statistics/MarkovChain/MarkovChain.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": 28.5833333333, "max_line_length": 81, "alphanum_fraction": 0.6194010072, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.8308977932098273}}
{"text": "{- \n - Name: Benjamin Kostiuk\n - Date: 9/25/2018\n -}\n -- Module for computing all roots of a polynomial of the third degree\nmodule Assign_1_ExtraCredit where\nimport Data.Complex\n-- see https://www.stackage.org/haddock/lts-8.24/base-4.9.1.0/Data-Complex.html\n\n{- -----------------------------------------------------------------\n - cubicRoot\n - -----------------------------------------------------------------\n - Description: Computes the cubic root of a Double\n -}\ncubicRoot :: Double -> Double\ncubicRoot n\n    | (n < 0) = - ((abs n) ** (1/3))\n    | otherwise = n ** (1/3)\n\n{- -----------------------------------------------------------------\n - cubicQ\n - -----------------------------------------------------------------\n - Description: Calculates the value of Q from coefficients a, b and c\n -}\ncubicQ :: Double -> Double -> Double -> Double\ncubicQ a b c = (3*a*c - b^2) / (9*a^2) \n\n{- -----------------------------------------------------------------\n - cubicR\n - -----------------------------------------------------------------\n - Description: Calculates the value of R from coefficients a, b, c and d \n -}\ncubicR :: Double -> Double -> Double -> Double -> Double\ncubicR a b c d = (9*a*b*c - 27*a^2*d - 2*b^3) / (54*a^3)\n\n{- -----------------------------------------------------------------\n - cubicDisc\n - -----------------------------------------------------------------\n - Description: Calculates the value of the discriminant from R and Q\n -}\ncubicDisc :: Double -> Double -> Double\ncubicDisc q r = q^3 + r^2\n\n{- -----------------------------------------------------------------\n - cubicComplexS\n - -----------------------------------------------------------------\n - Description: Computes a complex double from the value of S from Q and R \n - The value of S is only calculated when the discriminant >= 0 because it is not needed for discriminant < 0\n -}\ncubicComplexS :: Double -> Double -> Complex Double\ncubicComplexS q r\n    | (disc >= 0) = cubicRoot(r + sqrt(disc)) :+ 0\n    | otherwise = 0 :+ 0 -- If disc < 0, not needed for calculations --\n    where\n        disc = cubicDisc q r\n       \n{- -----------------------------------------------------------------\n - cubicComplexT\n - -----------------------------------------------------------------\n - Description: Computes a complex double from the value of T from Q and R \n - The value of T is only calculated when the discriminant >= 0 because it is not needed for discriminant < 0\n -}\ncubicComplexT :: Double -> Double -> Complex Double\ncubicComplexT q r\n    | (disc >= 0) = cubicRoot(r - sqrt(disc)) :+ 0\n    | otherwise = 0 :+ 0 -- If disc < 0, not needed for calculations --\n    where\n        disc = cubicDisc q r\n\n{- -----------------------------------------------------------------\n - cmplxRealSolutions\n - -----------------------------------------------------------------\n - Description: Computes a list of real roots from the angular components of a cubic equation \n - Recursively returns the list of real roots in complex double form\n -}\ncmplxRealSolutions :: [Complex Double] -> Double -> Double -> Double -> Double -> Double -> [Complex Double]\ncmplxRealSolutions xs n a b q theta\n    | (length xs == 3) = xs\n    | otherwise = cmplxRealSolutions (xs++[x]) (n+2) a b q theta    -- n is incremented by two to compute all angular solutions --\n    where\n        x = (2 * sqrt(-q) * cos((theta / 3) + (n*pi/3)) - (b / (3*a))) :+ 0\n\n{- -----------------------------------------------------------------\n - cubicComplexSolutions\n - -----------------------------------------------------------------\n - Description: Computes a list of complex double roots of a cubic equation \n - If discriminant > 0, returns a list with one real and two imaginary roots\n - If discriminant equal to 0, returns a list with three roots, with x2 = x3\n - If discriminant < 0, returns a list with three distinct real roots\n -}\ncubicComplexSolutions :: Double -> Double -> Double -> Double -> [Complex Double]\ncubicComplexSolutions a b c d\n    | ((abs disc) < 1e-9) = [x1 :+ 0, x2 :+ 0, x2 :+ 0]\n    | (disc > 0)          = [x1 :+ 0, x2 :+ (((sqrt 3) / 2) * (s - t)), x2 :+ (-((sqrt 3) / 2) * (s - t))] \n    | otherwise           = cmplxRealSolutions [] 0 a b q theta\n    where\n        q = cubicQ a b c\n        r = cubicR a b c d\n        s = realPart (cubicComplexS q r)\n        t = realPart (cubicComplexT q r)\n        disc = cubicDisc q r\n        theta = acos(r / sqrt(-q^3)) -- Angle used in angular computation -- \n        x1 = ((s + t) - (b / (3*a)))    \n        x2 = (- ((s + t) / 2) - (b / (3*a)))\n\n{- -----------------------------------------------------------------\n - Test Cases \n - -----------------------------------------------------------------\n -}\n{-\n-- See test cases from Assign_1.hs for any other function\n\n--cubicComplexSolutions--\n    Input: 3 4 2 1      \n    Expected: [-1.0 :+ 0.0, -0.1666667 :+ 0.55277, -0.1666667 :+ (-0.55277)]     \n    Actual: [(-1.0000000000000004) :+ 0.0,(-0.1666666666666664) :+ 0.5527707983925663,(-0.1666666666666664) :+ (-0.5527707983925663)]\n\n    Input: 0.00033 0.00077 (-0.0002) 0.0001\n    Expected: [(-2.6100218) :+ 0.0, 0.1383442795 :+ 0.31138954,  0.1383442795 :+ (-0.31138954)]\n    Actual: [(-2.6100218924147884) :+ 0.0,0.1383442795407276 :+ 0.31138954838120664,0.1383442795407276 :+ (-0.31138954838120664)]\n\n    Input: 1 (-3) 3 (-1) \n    Expected: [1.0 :+ 0.0, 1.0 :+ 0.0, 1.0 :+ 0.0]\n    Actual: [1.0 :+ 0.0,1.0 :+ 0.0,1.0 :+ 0.0]\n\n    Input: 1 (-5) 8 (-4)\n    Expected: [1.0 :+ 0.0, 2.0 :+ 0.0, 2.0 :+ 0.0]\n    Actual: [1.0 :+ 0.0,2.0 :+ 0.0,2.0 :+ 0.0]\n\n    Input: 1 0 (-3) 0\n    Expected: [0.0 :+ 0.0, 1.7320508 :+ 0.0, (-1.7320508) :+ 0.0]\n    Actual: [1.7320508075688774 :+ 0.0,(-1.732050807568877) :+ 0.0,(-3.673819061467132e-16) :+ 0.0]\n\n    Input: 1 (-5) (-2) 24\n    Expected: [4.0 :+ 0.0, (-2.0) :+ 0.0, 3.0 :+ 0.0]\n    Actual: [4.000000000000001 :+ 0.0,(-1.9999999999999993) :+ 0.0,2.999999999999999 :+ 0.0]\n\n    Input: 1 0 (-7) (-6)\n    Expected: [3.0 :+ 0.0, (-2.0) :+ 0.0, (-1.0) :+ 0.0]\n    Actual: [3.0000000000000004 :+ 0.0,(-1.9999999999999993) :+ 0.0,(-1.0000000000000002) :+ 0.0]\n\n    Input: (-0.004) (-0.0122) 17 3\n    Expected: [63.774967 :+ 0.0, (-66.6485177) :+ 0.0, (-0.17644953) :+ 0.0]\n    Actual: [63.77496726734746 :+ 0.0,(-66.64851773002562) :+ 0.0,(-0.17644953732185886) :+ 0.0]\n -}", "meta": {"hexsha": "19ccb35a6444dc56d8348fbf202cdf64b17ffb0a", "size": 6311, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "CubeRoots/src/Assign_1_ExtraCredit.hs", "max_stars_repo_name": "BenjaminKostiuk/haskell-slide-rule", "max_stars_repo_head_hexsha": "fa4f71afd94ced7ff1657075bdee75e7c6ec5f53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-05T19:50:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-05T19:50:16.000Z", "max_issues_repo_path": "CubeRoots/src/Assign_1_ExtraCredit.hs", "max_issues_repo_name": "BenjaminKostiuk/Code-Booklet", "max_issues_repo_head_hexsha": "fa4f71afd94ced7ff1657075bdee75e7c6ec5f53", "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": "CubeRoots/src/Assign_1_ExtraCredit.hs", "max_forks_repo_name": "BenjaminKostiuk/Code-Booklet", "max_forks_repo_head_hexsha": "fa4f71afd94ced7ff1657075bdee75e7c6ec5f53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.524137931, "max_line_length": 133, "alphanum_fraction": 0.4832831564, "num_tokens": 2008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065794, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.8308977800728502}}
{"text": "{- Assignment 1\n - Name: Omar Alkersh\n - Date: TODO add of completion\n -}\nmodule Assign_1_ExtraCredit where\n\nimport           Data.Complex\n-- see https://www.stackage.org/haddock/lts-8.24/base-4.9.1.0/Data-Complex.html\n\nmacid = \"alkersho\"\n\n{- -----------------------------------------------------------------\n - cubicQ\n - -----------------------------------------------------------------\n - Description: Finds Q, refer to website\n -}\ncubicQ :: Double -> Double -> Double -> Double\ncubicQ a b c = ((3*a*c)-b^2)/(9*a^2)\n\n{- -----------------------------------------------------------------\n - cubicR\n - -----------------------------------------------------------------\n - Description: Finds R using\n -}\ncubicR :: Double -> Double -> Double -> Double -> Double\ncubicR a b c d = ((9*a*b*c)-(27*a^2*d)-(2*b^3))/(54*a^3)\n\n{- -----------------------------------------------------------------\n - cubicDisc\n - -----------------------------------------------------------------\n - Description: Finds the discriminant\n - when the disc > 0, there is one real solution\n - when the disc = 0, there are two real solutions\n - when the disc < 0, there are three real solutions\n -}\ncubicDisc :: Double -> Double -> Double\ncubicDisc q r = q^3 + r^2\n\n\n--Returns the cube root of a number\ncubeRoot :: Double -> Double\ncubeRoot x = signum x * abs x ** (1/3)\n\n\n\n{- -----------------------------------------------------------------\n - cubicS\n - -----------------------------------------------------------------\n - Description: Finds S using Q and R\n -}\ncubicS :: Double -> Double -> Double\ncubicS q r = cubeRoot(r+sqrt(q^3 + r^2))\n\ncubicComplexS :: Double -> Double -> Complex Double\ncubicComplexS q r = if cubicDisc q r >= 0\n then (cubicS q r :+ 0)\n else ((r + sqrt(-(q^3 + r^2))):+1)**(1/3)\n\n\n{- -----------------------------------------------------------------\n - cubicT\n - -----------------------------------------------------------------\n - Description: Finds T using Q and R\n -}\ncubicT :: Double -> Double -> Double\ncubicT q r = cubeRoot(r-sqrt(q^3 + r^2))\n\ncubicComplexT :: Double -> Double -> Complex Double\ncubicComplexT q r = if cubicDisc q r >= 0\n then (cubicT q r :+ 0)\n else ((r - sqrt(-(q^3 + r^2))):+1)**(1/3)\n\n{- -----------------------------------------------------------------\n - cubicRealSolutions\n - -----------------------------------------------------------------\n - Description: Finds the roots/solutions of the cubic equaition\n - when the disc > 0, there is one real solution\n - when the disc = 0, there are two real solutions\n - when the disc < 0, there are three real solutions\n -}\ncubicRealSolutions :: Double -> Double -> Double -> Double -> [Double]\ncubicRealSolutions a b c d =\n  let\n    q = cubicQ a b c\n    r = cubicR a b c d\n    s = cubicS q r\n    t = cubicT q r\n    x1 = s + t - (b / (3*a))\n    x2 = -((s+t)/2)-(b/3*a)+((sqrt 3 / 2)*(s-t))\n    tol = 1e-5\n    in if cubicDisc q r > 0\n     then [x1]\n     else if abs (cubicDisc q r) == 0.0\n       then [x1, x2, x2]\n       else []\n       \n       \ncubicComplexSolutions :: Double -> Double -> Double -> Double -> [Complex Double]\ncubicComplexSolutions a b c d =\n  let\n    q = cubicQ a b c\n    r = cubicR a b c d\n    s = cubicComplexS q r\n    t = cubicComplexT q r\n    x1 = (realPart s + realPart t - (b / (3*a))):+ (imagPart s + imagPart t)\n    fstTrm = (realPart s + realPart t)/2 :+ (imagPart s + imagPart t)/2 --returns a complex number\n    sndTrm = b/(3*a) -- returns a real number\n    sDt = (realPart s - realPart t) :+ (imagPart s - imagPart t)\n    trdTrm = (-(((sqrt 3)/2)*imagPart sDt)) :+ ((sqrt 3)/2)*realPart sDt-- returns a complex number\n    x2 = (-(realPart fstTrm) - sndTrm + (realPart trdTrm)):+( -(imagPart fstTrm) + (imagPart trdTrm))\n    x3 = (-realPart fstTrm - sndTrm - realPart trdTrm):+( - imagPart fstTrm - imagPart trdTrm)\n    in [x1, x2, x3]\n\n\n\n\n\n\n", "meta": {"hexsha": "3741d092a6ff99987e82451efbca285418bbf2a7", "size": 3829, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Assign_1_ExtraCredit.hs", "max_stars_repo_name": "OZoneGuy/1JC3_Assignment_1", "max_stars_repo_head_hexsha": "c829f1541627530e9e72ced1c9ff09a4b0a4136f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Assign_1_ExtraCredit.hs", "max_issues_repo_name": "OZoneGuy/1JC3_Assignment_1", "max_issues_repo_head_hexsha": "c829f1541627530e9e72ced1c9ff09a4b0a4136f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Assign_1_ExtraCredit.hs", "max_forks_repo_name": "OZoneGuy/1JC3_Assignment_1", "max_forks_repo_head_hexsha": "c829f1541627530e9e72ced1c9ff09a4b0a4136f", "max_forks_repo_licenses": ["BSD-3-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.1764705882, "max_line_length": 101, "alphanum_fraction": 0.4810655524, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782055, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.8299940792759977}}
{"text": "-- |\n-- Module         : Eris.Compute.Similarity\n-- Copyright      : (c) 2018 Emmett H. Ng\n-- License        : BSD3\n--\n-- Maintainer     : emmettng@gmail.com\n-- Stability      : experimental & educational\n-- Portability    : portable\n--\n-- Functions of computing pairwise similarity and similarity matrix.\n-- Documents:\n-- 1. https://numerics.mathdotnet.com/Distance.html \nmodule Eris.Compute.Similarity\n  ( sumAbsoluteDifference\n  , manhattanDistance\n  , taxicab\n  , meanAbsoluteDifference\n  , euclideanDistance\n  , sumSquaredDifference\n  , meanSquaredDistance\n  , minkowskiDistance\n  , chebyshevDistance\n  , canberraDistance\n  , cosineDistance\n  , cosineSimilarity\n  , angularDistance\n  , angularSimilarity\n  , pearsonCC\n  , pearsonCC'\n  , pairWiseSimilarity\n  ) where\n\nimport qualified Data.HashMap.Strict as Map\nimport Data.Maybe\nimport Numeric.LinearAlgebra\n\nimport Eris.Meta.DataStructure\n\n-- | Manhattan Distance is Absolute Value Norm(L1) of (v1-v2)\nmanhattanDistance :: RankMetric\nmanhattanDistance = sumAbsoluteDifference\n\n-- | Taxicab metric is Absolute Value Norm (L1) of (v1 - v2)\ntaxicab :: RankMetric\ntaxicab = sumAbsoluteDifference\n\n-- | SAD is Absolute Value Norm(L1) of (v1 - v2)\nsumAbsoluteDifference :: RankMetric\nsumAbsoluteDifference l1 l2 = norm_1 (v1 - v2)\n  where\n    v1 = vector l1\n    v2 = vector l2\n\n-- | Mean absolute Difference (MAD)\n-- | SAD average on all dimensions\nmeanAbsoluteDifference :: RankMetric\nmeanAbsoluteDifference l1 l2 = l1norm / n\n  where\n    l1norm = sumAbsoluteDifference l1 l2\n    n = fromIntegral . length $ l1\n\n-- | L2-normal           \neuclideanDistance :: RankMetric\neuclideanDistance l1 l2 = norm_2 v\n  where\n    v = vector l1 - vector l2\n\n-- | Squared L2-norm (SSD)\nsumSquaredDifference :: RankMetric\nsumSquaredDifference l1 l2 = v <.> v\n  where\n    v = vector l1 - vector l2\n\n-- | Mean Sqaured Error (MSE)\nmeanSquaredDistance :: RankMetric\nmeanSquaredDistance l1 l2 = squaredL2 / n\n  where\n    squaredL2 = sumSquaredDifference l1 l2\n    n = fromIntegral . length $ l1\n\n-- | Root mean squared Error (rmse)\nrootMeanSquaredError :: RankMetric\nrootMeanSquaredError xs1 xs2 = euclideanDistance xs1 xs2 / sqrtN\n  where\n    sqrtN = sqrt . fromIntegral $ length xs1\n\n-- | Minkowski Distance\n-- This is a degenerate case of Minkowski distance \n-- in this case p is an Integral number for sure.\nminkowskiDistance :: Int -> RankMetric\nminkowskiDistance p l1 l2 =\n  let ld = zipWith (-) l1 l2\n      absV = vector $! abs <$> ld\n  in nroot p $ norm_1 $ pow p absV\n  where\n    pow :: Int -> Vector Rank -> Vector Rank\n    pow 0 cv = 1\n    pow 1 cv = cv\n    pow n cv = pow (n - 1) $! cv * cv\n    nroot\n      :: (Integral a, Floating b)\n      => a -> b -> b\n    nroot 0 _ = 1\n    nroot n f = f ** (1 / fromIntegral n)\n\n-- | Chebyshev Distance\n-- \nchebyshevDistance :: RankMetric\nchebyshevDistance l1 l2 =\n  let ld = abs <$> zipWith (-) l1 l2\n  in maximum ld\n\n-- | Hanmming Distance is minkowskiDistance with p=0\nhammingDistance :: RankMetric\nhammingDistance = minkowskiDistance 0\n\n-- | Canberra Distance \n-- weighted L1 norm\ncanberraDistance :: RankMetric\ncanberraDistance l1 l2 = l1norm / (l1s + l2s)\n  where\n    l1norm = sumAbsoluteDifference l1 l2\n    l1s = sum $ abs <$> l1\n    l2s = sum $ abs <$> l2\n\n-- | Measure of similairty between two NON-ZERO vectors\n-- See note/similarities.md for more information.\n-- cosine similarity and cosine distance are not metric function.\ncosineSimilarity :: RankMetric\ncosineSimilarity l1 l2 = v1 <.> v2 / (norm_2 v1 * norm_2 v2)\n  where\n    v1 = vector l1\n    v2 = vector l2\n\n-- | Cosine Distance is not metric function \n-- as it does not have the triangle inequality property\n-- see angular similarity and angular distance (valid metric function) below.\ncosineDistance :: RankMetric\ncosineDistance l1 l2 = 1 - cosineSimilarity l1 l2\n\n-- | angular distance represent the radians between two vector\n-- it satisfies the triangle inequality \n-- in a recommendation system, it is assumed that all vectors are  positive.\nangularDistance :: RankMetric\nangularDistance l1 l2 =\n  let sim = cosineSimilarity l1 l2\n      inverSim = acos sim\n  in 2 * inverSim / pi\n\nangularSimilarity :: RankMetric\nangularSimilarity l1 l2 = 1 - angularSimilarity l1 l2\n\n-- quickcheckout doc\n-- pearsonCC and zscore relation doc\n-- | Pearson Correlation Coefficient\n-- It is cosine similarity between centered vectors.\n-- reference to : https://stats.stackexchange.com/questions/235673/is-there-any-relationship-among-cosine-similarity-pearson-correlation-and-z-sc\n-- necessity of centering : https://www.theanalysisfactor.com/center-on-the-mean/\npearsonCC :: RankMetric\npearsonCC l1 l2 = v1 <.> v2 / (norm_2 v1 * norm_2 v2)\n  where\n    len = fromIntegral . length $ l1\n    tv1 = vector l1\n    tv2 = vector l2\n    m1 = sumElements tv1 / len\n    m2 = sumElements tv2 / len\n    v1 = tv1 - vector [m1]\n    v2 = tv2 - vector [m2]\n\n-- | Test shows that this implementation is supresingly better than above.\npearsonCC' :: RankMetric\npearsonCC' l1 l2 = z1 <.> z2 / d\n  where\n    z1 = zScore l1\n    z2 = zScore l2\n    d = fromIntegral . length $ l1\n\n-- | a little bit involove actuallec\n-- n : vector \n-- std: popultaion standard deviation\n-- z-score = v / std\nzScore :: [Rank] -> Vector Rank\nzScore xs = scale (recip std) v\n  where\n    x = vector xs\n    n = fromIntegral . length $ xs\n    meanX = sumElements x / n\n    v = x - vector [meanX]\n    std = norm_2 v / sqrt n\n\n-- | A common operation is to subtracte mean \n-- For performance reason, this function may not be exported.\ncentering :: [Rank] -> Vector Rank\ncentering xs = v - vector [vmean]\n  where\n    v = vector xs\n    n = fromIntegral . length $ xs\n    vmean = sumElements v / n\n\n-- | merge two sorted list\n--sortH :: Ord a => [a] -> [a] -> [a]\n--sortH l1@(x:xs) l2@(y:ys)\n--    | x <= y = x : sortH xs l2\n--    | otherwise = y : sortH l1 ys\n--sortH [] l2 = l2\n--sortH l1 [] = l1\npairWiseSimilarity\n  :: Threshold\n  -> SimilarityMatrix -- fold cum\n  -> RankMetric -- distance func\n  -> ECount -- rating records\n  -> SimilarityMatrix\npairWiseSimilarity bar cumSM sfn ecount =\n  let target = head . Map.toList $ ecount\n      items = tail . Map.toList $ ecount\n      sVector = pairwiseAuxil target <$> items\n      sMatrix = composeMatrix target items sVector\n  in if null items\n       then Map.union cumSM sMatrix\n       else pairWiseSimilarity\n              bar\n              (Map.union cumSM sMatrix)\n              sfn\n              (Map.fromList items)\n  where\n    pairwiseAuxil :: (EID, ESMap) -> (EID, ESMap) -> Double\n    pairwiseAuxil (_, tMap) (_, iMap) = esmapSFN tMap iMap\n    esmapSFN :: ESMap -> ESMap -> Double\n    esmapSFN t i =\n      let intersect = Map.toList $ Map.intersection t i\n          tv =\n            [ snd v\n            | v <- intersect ]\n          iv =\n            catMaybes\n              [ Map.lookup (fst v) i\n              | v <- intersect ]\n      in if null intersect\n           then 0\n           else sfn tv iv\n    composeMatrix :: (EID, ESMap) -> [(EID, ESMap)] -> [Double] -> SimilarityMatrix\n    composeMatrix tt ilist slist =\n      let tid = fst tt\n          idList =\n            [ fst v\n            | v <- ilist ]\n          tidSelf = Map.fromList [(tid, 1)]\n          tmpDict = Map.union tidSelf $ Map.fromList $ zip idList slist\n      in Map.fromList [(tid, tmpDict)]\n", "meta": {"hexsha": "9a738c21deb57c973e43c2a0ca3194ff144a0749", "size": 7308, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Eris/Compute/Similarity.hs", "max_stars_repo_name": "emmettng/eris", "max_stars_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Eris/Compute/Similarity.hs", "max_issues_repo_name": "emmettng/eris", "max_issues_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Eris/Compute/Similarity.hs", "max_forks_repo_name": "emmettng/eris", "max_forks_repo_head_hexsha": "15f10774898f2d5d636641156b8c512f2b5a0006", "max_forks_repo_licenses": ["BSD-3-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.232, "max_line_length": 145, "alphanum_fraction": 0.6654351396, "num_tokens": 2168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8740772417253256, "lm_q1q2_score": 0.822322907624444}}
{"text": "module Y2016.M06.D21.Exercise where\n\n{--\nSo what happens when things become Complex?\n\nWith the Quadratic type, enhance solver in such a way that it gives all\nsolutions, whether they be Real or Complex.\n\nThis exercise is an elaboration of yesterday's that solved quadratic equations\nwith Real roots with the quadratic formula:\n\n    -b +/- sqrt (b^2 - 4ac)\nx = -----------------------\n              2a\n\nfor the quadratic equation\n\nax^2 + bx + c = 0\n--}\n\nimport Data.Complex\n\ndata QuadraticEq = Q { a,b,c :: Float }\n\nsolver :: QuadraticEq -> [Complex Float]\nsolver = undefined\n\n-- with the new solver, solve the below quadratic equations represented by\n-- the coefficients (a,b,c):\n\neqs :: [(Float, Float, Float)]\neqs = [(1,-6,25), (1,10,29), (1,-6,13), (2,6,29)]\n\n{-- BONUS ------------------------------------------------------------------\n\nThe default Show-instance for QuadraticEq 'leaves something to be desired.'\n\nWrite your own Show-instance for QuadraticEq that for (Q 2 3 4) shows:\n\n\"2x^2 + 3x + 4 = 0\"\n--}\n\ninstance Show QuadraticEq where show = undefined\n", "meta": {"hexsha": "688c3ba00b1f6d4285144f605321475b2bc8739a", "size": 1063, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "exercises/HAD/Y2016/M06/D21/Exercise.hs", "max_stars_repo_name": "nernstp/1had", "max_stars_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 250, "max_stars_repo_stars_event_min_datetime": "2016-06-20T19:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T06:39:38.000Z", "max_issues_repo_path": "exercises/HAD/Y2016/M06/D21/Exercise.hs", "max_issues_repo_name": "nernstp/1had", "max_issues_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-08-18T16:46:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-27T11:09:26.000Z", "max_forks_repo_path": "exercises/HAD/Y2016/M06/D21/Exercise.hs", "max_forks_repo_name": "nernstp/1had", "max_forks_repo_head_hexsha": "d706c1cc4fdd894498b7a03b8a8c59d43903a5dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2016-06-28T06:46:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-08T01:42:30.000Z", "avg_line_length": 24.1590909091, "max_line_length": 78, "alphanum_fraction": 0.6340545626, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.8577681049901036, "lm_q1q2_score": 0.817688928050943}}
{"text": "{-|\nModule      : ExponentialSum\nDescription : Compute the exponential sum of the day\n\nCompute the exponential sum of the day, to be plotted later.\n -}\n\nmodule ExponentialSum\n  (\n    -- * Main function\n    expSums\n    -- * Exported for convenience\n  , expVal\n  , realArg\n  ) where\n\nimport Data.Complex\n\n-- | Compute the value of the real argument of the exponential, at point n,\n-- given the initial coefficients.\n--\n-- For example, here is the third value computed where the coefficients are\n-- current date:\n--\n-- >>> realArg [12, 5, 2018] 3\n-- 2.063379583746283\n-- >>> realArg [12, 5, 18] 3\n-- 3.55\n--\n-- There are some properties which might be useful:\n--\n-- 1. If the coefficients are missing, we want to return a 0 for any index:\n--\n--     prop> realArg [] x == 0\n--\n-- 2. If the index is 0, we output 0 regardless of the coefficients, provided\n-- at least one is non-zero\n--\n--     prop> a == 0 || realArg (a:xs) 0 == 0\n--\n-- There might be a few more properties but we can ignore them for now, as\n-- some might fail due to numerical inaccuracies. We are also sidestepping\n-- NaNs and infinities at the moment.\nrealArg :: [Double] -> Double -> Double\nrealArg xs n = sum $ zipWith power xs [1..]\n  where\n    power :: Double -> Int -> Double\n    power x i = n ^ i / x\n\n-- | Computes the value of the complex exponential for a term at an index\n-- Since we need to multiply the result of `realArg` with i, we just put it in\n-- the imaginary part of the newly minted complex number.\n--\n-- Examples:\n--\n-- >>> expVal [12, 5, 2018] 3\n-- 0.9217505006686714 :+ 0.3877834634393964\n-- >>> expVal [12, 5, 18] 3\n-- (-0.9510565162951544) :+ (-0.3090169943749449)\n--\n-- Also, we have the following properties:\n--\n-- prop> x == 0 || expVal [] x == 1\n-- prop> a >= 0 || expVal (a:xs) 0 == 1\nexpVal :: [Double] -> Double -> Complex Double\nexpVal xs n = exp $ 2 * pi * (0 :+ realArg xs n)\n\n-- | Computes the partial sums of the exponential sum of the day\n--\n-- >>> take 3 $ expSums [12, 5, 18]\n-- [1.0 :+ 0.0,0.4700807357667952 :+ 0.8480480961564261,(-0.3779673603896302) :+ 1.3779673603896319]\n-- >>> take 3 $ expSums [12, 5, 2018]\n-- [1.0 :+ 0.0,0.7890437903507289 :+ 0.9774955128339019,1.7720662136902803 :+ 0.794010049617778]\n-- >>> take 3 $ expSums []\n-- [1.0 :+ 0.0,2.0 :+ 0.0,3.0 :+ 0.0]\nexpSums :: [Double] -> [Complex Double]\nexpSums xs = scanl1 (+) $ map (expVal xs) [0..]\n", "meta": {"hexsha": "52e11258e7dbe8063dcc7ae410f899cf891eb473", "size": 2371, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ExponentialSum.hs", "max_stars_repo_name": "mihaimaruseac/esotd", "max_stars_repo_head_hexsha": "411fe3c255ace04d6c56609d6961dded8c7fc186", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T06:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T06:36:26.000Z", "max_issues_repo_path": "src/ExponentialSum.hs", "max_issues_repo_name": "mihaimaruseac/esotd", "max_issues_repo_head_hexsha": "411fe3c255ace04d6c56609d6961dded8c7fc186", "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/ExponentialSum.hs", "max_forks_repo_name": "mihaimaruseac/esotd", "max_forks_repo_head_hexsha": "411fe3c255ace04d6c56609d6961dded8c7fc186", "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": 30.3974358974, "max_line_length": 100, "alphanum_fraction": 0.644453817, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.816728202544884}}
{"text": "module ComplexLab where\n\nimport Data.Complex\n\n-- 1.2 Complex numbers in ~~ Haskell ~~\n\ni :: Num a => a -> Complex a\ni n = 0 :+ n\n\n-- Haskell supports complex numbers.\n-- The square root of -9, the imaginary number 3i, is written:\n\nsquareRootOfNine :: Num a => Complex a\nsquareRootOfNine =\n  i 3 -- Written 3j in python\n\n-- Haskell allows the use of + to add a real number to an imaginary one.\n-- We can write the complex solution to `(x − 1)^2 = −9` as:\n\naddRealToImag :: RealFloat a => Complex a\naddRealToImag = \n  1 + squareRootOfNine -- 1 + 3j in python\n\n-- In fact, the operators +, -, *, /, and ^^ all work with complex numbers.\n-- When you add two complex numbers, the real parts are added and the imaginary parts are added.\n\nsupportsOperators :: RealFloat a => Complex a\nsupportsOperators = \n  (((1 + i 3) / 8) ^^ 2) * i 3\n  -- ((((1 + 3j) / 8) ** 2) * 3j) in python\n\n", "meta": {"hexsha": "7d9547df6826e3bed17688b0f0c47557db6d5096", "size": 875, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ComplexLab.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/ComplexLab.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/ComplexLab.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": 27.34375, "max_line_length": 96, "alphanum_fraction": 0.656, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169939, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.8160019748994294}}
{"text": "module Linalg where\n\n{-# LANGUAGE RankNTypes,\n             FlexibleContexts,\n             FlexibleInstances,\n             MultiParamTypeClasses,\n             UndecidableInstances,\n             AllowAmbiguousTypes,\n             DataKinds,\n             ScopedTypeVariables,\n#-}\n\n\nimport Data.Matrix\nimport Data.Bifunctor\nimport qualified Data.Vector as V\nimport qualified Data.List.Zipper as ZP\nimport Data.Complex\nimport qualified Data.List as DL\nimport qualified Data.Set as DS\nimport qualified Data.Map as DM\nimport GHC.Float\nimport Data.Maybe\nimport Data.Euclidean\n\nsubtr :: Num a => Matrix a -> Matrix a -> Matrix a\nsubtr = elementwise (-)\n \nadd :: Num a => Matrix a -> Matrix a -> Matrix a\nadd = elementwise (+)\n\nnorm2 :: Floating a => Matrix a -> a\nnorm2 v = sqrt $ foldr (\\x r -> x * x + r) 0 (toList v) \n\nnorm2C :: RealFloat a => Matrix (Complex a) -> a\nnorm2C v = sqrt $ foldr (\\x r -> realPart (x * conjugate x) + r) 0 (toList v) \n\ngetDiagonal :: Num a => Matrix a -> Matrix a\ngetDiagonal m = diagonalList (nrows m) 0 $ V.toList $ getDiag m\n\ngershgorinCircles :: Num a => Matrix a -> [(a, a)]\ngershgorinCircles m = zip cs rs\n    where\n        cs   = V.toList $ getDiag m\n        diag = getDiagonal m\n        rs   = map (foldr (\\x r -> abs x + r) 0) (toLists $ m `subtr` diag)\n\noutUnitCircle :: (Num a, Ord a) => Matrix a -> Bool\noutUnitCircle m = foldr (\\(c, r) acc -> (abs c + r >= 1) || acc) False (gershgorinCircles m)\n\n\n{- Simple iteration method of solving linear equations systems. Complexity O(n^2) per iteration. -}\nsimpleIteration :: (Floating a, Ord a) => [[a]] -> [[a]] -> a -> Either Int (Matrix a)\nsimpleIteration m b = simpleIteration' (fromLists m) (fromLists b)\n  \nsimpleIteration' :: (Floating a, Ord a) => Matrix a -> Matrix a -> a -> Either Int (Matrix a)\nsimpleIteration' m b eps = doIterations m' b (zero size 1) eps (outUnitCircle m) 0 \n    where \n          size = nrows m\n          m'   = identity size `subtr` m\n \ndoIterations m b x eps outCircle cnt\n    | outCircle \n        && cnt == 20                 = Left 0\n    | outCircle\n        && norm2 x' >= norm2 x + 1   = doIterations m b x' eps outCircle (cnt + 1) \n    | norm2 (x `subtr` x') < eps     = Right x'\n    | otherwise                      = doIterations m b x' eps outCircle 0\n    where x'                         = (m `multStd` x) `add` b\n \nlowerTriangle :: Num a => Matrix a -> Matrix a\nlowerTriangle m = mapPos (\\(i, j) e -> if (size - i + 1) + j <= size + 1 then e else 0) m\n    where\n        size = nrows m \n\nupperTriangle :: Num a => Matrix a -> Matrix a\nupperTriangle m = transpose $ m' `subtr` diag \n    where\n        m'   = lowerTriangle $ transpose m  \n        diag = getDiagonal m\n\ngaussPartial :: (Floating a, Ord a) => Matrix a -> Matrix a -> Matrix a\ngaussPartial m b = fromLists $ map (: []) (foldl gaussStep [] mlist) \n    where\n        m'                = b <|> m\n        mlist             = toLists m'\n        gaussStep ans row = ans ++ [xi]\n            where\n                coef = foldr (\\e acc -> if e /= 0 && acc == 0 then e else acc) 0 row\n                bi   = head row\n                row' = tail row\n                sm   = sum $ zipWith (*) ans row'\n                xi   = (bi - sm) / coef  \n\n{- Gauss-Zeidel method of solving linear equations systems. Complexity O(n^2) per iteration. -}\ngaussZeidel :: (Floating a, Ord a) => [[a]] -> [[a]] -> a -> Either Int (Matrix a)\ngaussZeidel m b = gaussZeidel' (fromLists m) (fromLists b)\n\ngaussZeidel' :: (Floating a, Ord a) => Matrix a -> Matrix a -> a -> Either Int (Matrix a)\ngaussZeidel' m b eps = doGaussZeidel l negu b (zero size 1) eps (outUnitCircle m) 0 \n    where\n        size = nrows m\n        l    = lowerTriangle m\n        negu = zero size size `subtr` upperTriangle m\n\ndoGaussZeidel l negu b x eps outCircle cnt\n    | outCircle \n        && cnt == 20                            = Left 0\n    | outCircle\n        && norm2 x' >= norm2 x + 1              = doGaussZeidel l negu b x' eps outCircle (cnt + 1)\n    | norm2 ((l `multStd` x) `subtr` b') < eps  = Right x\n    | otherwise                                 = doGaussZeidel l negu b x' eps outCircle 0\n    where\n        b' = (negu `multStd` x) `add` b\n        x' = gaussPartial l b'\n\n{- Givens rotation of matrix. Complexity O(n). -}\ngivensRotation :: Num a => [[a]] -> Int -> Int -> a -> a -> [[a]]\ngivensRotation m i j c s = zipWith subst [1..] m\n    where\n        ui    = m !! (i - 1)\n        uj    = m !! (j - 1)\n        uinew = zipWith (\\xi xj -> c * xi + s * xj) ui uj\n        ujnew = zipWith (\\xi xj -> (- s) * xi + c * xj) ui uj\n        subst pos row\n            | pos == i  = uinew\n            | pos == j  = ujnew\n            | otherwise = row\n\ntrans :: [[a]] -> [[a]]\ntrans = toLists . transpose . fromLists\n\nidMatrix :: Num a => Int -> [[a]]\nidMatrix sz = toLists $ identity sz\n\nfirstNonzero :: (Num a, Ord a) => [a] -> Int -> Int\nfirstNonzero v k = foldl (\\acc (j, x) -> if j >= k && x /= 0 && acc == 0 \n                                       then j \n                                       else acc) 0 (zip [1..] v) \n\nappToPair f (x, y) = (f x, f y)\n\n{- Givens rotation method of QR decomposition. Complexity O(n^3). -}\nqrDecompGivens :: (Floating a, Ord a) => [[a]] -> (Matrix a, Matrix a)\nqrDecompGivens m = appToPair fromLists $ first trans qr\n    where\n        idm                = idMatrix $ length m \n        qr                 = foldl handler (idm, m) [1..(length m - 1)]\n        handler (q, r) k \n            | i == 0    = (q, r)\n            | otherwise = (givensRotation q'' k i 0 1, givensRotation r'' k i 0 1)\n            where\n                col        = trans r !! (k - 1)\n                i          = firstNonzero col k\n                (q'', r'') = fst $ foldl handler' ((q, r), col !! (i - 1)) (zip [1..] col)\n                handler' ((q', r'), xi) (j, xj)\n                    | j <= i    = ((q', r'), xi)\n                    | otherwise = ((givensRotation q' j i c s, givensRotation r' j i c s), (- s) * xj + c * xi)\n                        where\n                            n = sqrt $ xi * xi + xj * xj\n                            c = xi / n\n                            s = (- xj) / n\n\n{- Householder matrix multiplication. Complexity O(n^2). -}\nmultHouseholder :: Num a => [[a]] -> [[a]] -> [[a]]\nmultHouseholder m' v' = toLists $ m `subtr` prod\n    where\n        m    = fromLists m'\n        v    = fromLists v'\n        vt   = transpose v\n        prod = scaleMatrix 2 v `multStd` (vt `multStd` m)\n\n{- Householder reflection method of QR decomposition. Complexity O(n^3). -}\nqrDecompHouseholder :: (Floating a, Ord a) => [[a]] -> (Matrix a, Matrix a)\nqrDecompHouseholder m = appToPair fromLists $ first trans qr\n    where\n        idm                = idMatrix $ length m\n        qr                 = foldl handler (idm, m) [1..(length m - 1)]\n        handler (q, r) k \n            | norm2 v' == 0 || u == e1 = (q, r)\n            | otherwise                = (multHouseholder q v, multHouseholder r v)\n            where\n                col = trans r !! (k - 1)\n                v'  = fromLists $ zipWith (\\j x -> if j < k then [0] else [x]) [1..length col] col\n                u   = scaleMatrix (1 / norm2 v') v'\n                e1  = mapPos (\\(j, _) _-> if j == k then 1 else 0) v'\n                v   = toLists $ scaleMatrix (1 / norm2 (u `subtr` e1)) (u `subtr` e1)\n \n{- Simple iteration method of calculation the maximum modulo eigenvalue. Complexity O(n^2) per iteration. -}\nsimpleIterationMaxEV :: RealFloat a => [[Complex a]] -> [[Complex a]] -> a -> Int\n                        -> Either Int (Complex a, Matrix (Complex a))\nsimpleIterationMaxEV m v = doItersMaxEV (fromLists m) (fromLists v)\n\ndoItersMaxEV m x eps cnt\n    | cnt == 0          = Left 0\n    | norm2C diff < eps = Right (ev, x)\n    | otherwise         = doItersMaxEV m x' eps (cnt - 1) \n    where\n        norm = norm2C (m `multStd` x) :+ 0\n        x'   = scaleMatrix (1 / norm) (m `multStd` x)\n        ev   = head $ head $ toLists $ transpose x `multStd` (m `multStd` x)\n        diff = (m `multStd` x) `subtr` scaleMatrix ev x\n\n{- QR-algorithm of calculation the matrix spectrum. Complexity O(n^3) per iteration. -}\nqrEV :: (Floating a, Ord a) => [[a]] -> a -> ([a], Matrix a)\nqrEV m eps = doItersQrEV m eps (identity $ length m)\n\ndoItersQrEV m eps qk\n    | lessEps   = (evs, qk)\n    | otherwise = doItersQrEV m' eps (qk `multStd` q)\n    where\n        (q, r)  = qrDecompGivens m\n        m'      = toLists $ r `multStd` q\n        circles = gershgorinCircles (fromLists m)\n        lessEps = foldr (\\(_, rd) acc -> (rd < eps) && acc) True circles\n        evs     = V.toList $ getDiag $ fromLists m\n\nmultHouseholderRight :: Num a => [[a]] -> [[a]] -> [[a]]\nmultHouseholderRight m' v' = toLists $ m `subtr` prod\n    where\n        m    = fromLists m'\n        v    = fromLists v'\n        vt   = transpose v\n        prod = scaleMatrix 2 ((m `multStd` v) `multStd` vt)\n\n{- Matrix transformation to tridiagonal form. Complexity O(n^3). -}\ngetTridiagonal :: (Floating a, Ord a) => [[a]] -> (Matrix a, Matrix a)\ngetTridiagonal m = appToPair fromLists $ second trans tridiag\n    where\n        idm                = idMatrix $ length m\n        tridiag            = foldl handler (m, idm) [1..(length m - 1)]\n        handler (a, q) k \n            | norm2 v' == 0 || u == e1 = (a, q)\n            | otherwise                = (newa, newq)\n            where\n                col  = trans a !! (k - 1)\n                v'   = fromLists $ zipWith (\\j x -> if j <= k then [0] else [x]) [1..length col] col\n                u    = scaleMatrix (1 / norm2 v') v'\n                e1   = mapPos (\\(j, _) _-> if j == k + 1 then 1 else 0) v'\n                v    = toLists $ scaleMatrix (1 / norm2 (u `subtr` e1)) (u `subtr` e1)\n                newa = multHouseholderRight (multHouseholder a v) v\n                newq = multHouseholder q v\n\ncursorp :: ZP.Zipper a -> Int\ncursorp (ZP.Zip l _) = length l\n\nrightn :: Int -> ZP.Zipper a -> ZP.Zipper a\nrightn 0 z = z\nrightn n z = rightn (n - 1) (ZP.right z) \n\ngivensRotationZ :: Num a => [ZP.Zipper a] -> Int -> Int -> a -> a -> [ZP.Zipper a]\ngivensRotationZ m i j c s = zipWith subst [1..] m\n    where\n        ui      = m !! (i - 1)\n        uj      = m !! (j - 1)\n        curspUi = cursorp ui\n        curspUj = cursorp uj   \n        uinew   = rightn curspUi $ ZP.fromList $ \n                   zipWith (\\xi xj -> c * xi + s * xj) (ZP.toList ui) (ZP.toList uj)\n        ujnew   = rightn curspUj $ ZP.fromList $ \n                   zipWith (\\xi xj -> (- s) * xi + c * xj) (ZP.toList ui) (ZP.toList uj)\n        subst pos row\n            | pos == i  = uinew\n            | pos == j  = ujnew\n            | otherwise = row\n\n{- QR decomposition for the tridiagonal matrices. Complexity O(n^2). -}\nqrDecompTridiagonal :: (Floating a, Ord a) => [[a]] -> ([(Int, Int, a, a)], Matrix a)\nqrDecompTridiagonal m = second (fromLists . fmap ZP.toList) $ \n                        foldl handler ([], zipped_m) [1..(length m - 1)]\n    where\n        zipped_m = fmap ZP.fromList m\n        handler (gs, r) k\n            | n == 0    = (gs, r)\n            | otherwise = ((k + 1, k, c, s) : gs, map ZP.right $ givensRotationZ r (k + 1) k c s)\n            where\n                col = map ZP.cursor r\n                xi  = col !! (k - 1)\n                xj  = col !! k\n                n   = sqrt $ xi * xi + xj * xj\n                c   = xi / n\n                s   = (- xj) / n\n\nmultGivens :: Num a => [(Int, Int, a, a)] -> [[a]] -> [[a]]\nmultGivens gs m = foldr (\\(i, j, c, s) acc -> givensRotation acc i j c s) m gs\n\n{- \nQR-algorithm of calculation the matrix spectrum for the tridiagonal matrices. \nComplexity O(n^2) per iteration. \n-}\nqrEVTridiagonal :: (Floating a, Ord a) => [[a]] -> a -> ([a], Matrix a)\nqrEVTridiagonal m eps = second (transpose . fromLists) $ doItersQrEVsTridiagonal m eps (idMatrix $ length m)\n\ndoItersQrEVsTridiagonal m eps qk\n    | lessEps   = (evs, qk)\n    | otherwise = doItersQrEVsTridiagonal m' eps q\n    where\n        (gs, r) = qrDecompTridiagonal m\n        m'      = trans $ multGivens gs (trans $ toLists r)\n        q       = multGivens gs qk\n        circles = gershgorinCircles (fromLists m)\n        lessEps = foldr (\\(_, rd) acc -> (rd < eps) && acc) True circles\n        evs     = V.toList $ getDiag $ fromLists m\n\ndoItersQrEVsTridiagonalNTimes m cnt qk\n    | cnt == 0  = (evs, qk)\n    | otherwise = doItersQrEVsTridiagonalNTimes m' (cnt - 1) q\n    where\n        (gs, r) = qrDecompTridiagonal m\n        m'      = trans $ multGivens gs (trans $ toLists r)\n        q       = multGivens gs qk\n        evs     = V.toList $ getDiag $ fromLists m\n\ndoItersQrMinEVTridiagonal m eps qk\n    | radius < eps = (qk, m)\n    | otherwise    = doItersQrMinEVTridiagonal m' eps q\n    where\n        (gs, r) = qrDecompTridiagonal m\n        m'      = trans $ multGivens gs (trans $ toLists r)\n        q       = multGivens gs qk\n        lastRow = last m\n        radius  = foldr (\\x acc -> abs x + acc) 0 lastRow - abs (last lastRow)\n \nswapMinor :: Num a => Matrix a -> Matrix a -> Matrix a\nswapMinor minor m = m' `add` minor' \n    where\n        minorSz = nrows minor\n        mSz     = nrows m    \n        m'     = mapPos (\\(i, j) x -> if i <= minorSz && j <= minorSz\n                                  then 0\n                                  else x) m\n        minor' = extendTo 0 mSz mSz minor\n\n{- \nWilkinson shifts QR-algorithm of calculation the matrix spectrum for the tridiagonal matrices. \nComplexity O(n^2) per iteration.\n-}\nqrEVShifts :: (Floating a, Ord a) => [[a]] -> a -> ([a], Matrix a)\nqrEVShifts mt eps = (evs, transpose q)\n    where\n        sz     = length mt\n        (q, d) = foldl handler (identity (length mt), fromLists mt) [0..sz - 2]\n        evs    = V.toList $ getDiag d\n        handler (qk, m) k \n               = (qt `multStd` qk, swapMinor r' m)\n               where\n                    m'       = submatrix 1 (sz - k) 1 (sz - k) m\n                    sz'      = nrows m'\n                    lowerSq  = submatrix (sz' - 1) sz' (sz' - 1) sz' m'\n                    maxIters = 20\n                    s        = head $ tail $ fst $ \n                               doItersQrEVsTridiagonalNTimes (toLists lowerSq) maxIters (idMatrix 2)\n                    m''      = m' `subtr` scaleMatrix s (identity sz')\n                    (qt, r)  = first fromLists $ doItersQrMinEVTridiagonal (toLists m'') eps (idMatrix sz)\n                    r'       = fromLists r `add` scaleMatrix s (identity sz')\n\n{- Test graphs on nonisomorphism. Complexity O(Time(qrEVShifts)). -}\nisomorphic :: (Floating a, Ord a) => [[a]] -> [[a]] -> Bool\nisomorphic g1 g2\n    | length g1 /= length g2 = False\n    | otherwise              = norm2 (g1Spec `subtr` g2Spec) <= 10 * eps\n    where\n        eps    = 0.00001\n        g1'    = toLists $ fst $ getTridiagonal g1\n        g2'    = toLists $ fst $ getTridiagonal g2\n        g1Spec = fromLists $ map (: []) $ DL.sort $ fst $ qrEVShifts g1' eps\n        g2Spec = fromLists $ map (: []) $ DL.sort $ fst $ qrEVShifts g2' eps\n\ngetAdjMap :: Num a => Int -> DM.Map Int (DM.Map Int a)\ngetAdjMap n = adjMap \n    where\n        buildRow = DM.fromList $ map (\\k -> (k, 0)) [0..n - 1]\n        adjMap   = DM.fromList $ map (\\k -> (k, buildRow)) [0..n - 1]\n\naddEdge (x, y) = DM.update (Just . DM.update (Just . (+ 1)) y) x\n\nbuildAdjMatrix :: Num a => Int -> (Int -> DM.Map Int (DM.Map Int a) -> DM.Map Int (DM.Map Int a)) -> Matrix a\nbuildAdjMatrix n genEdges = m\n    where\n        adjMap      = getAdjMap n\n        adjMap'     = foldr genEdges adjMap [0..n - 1]\n        m           = matrix n n fill\n        fill (i, j) = x\n            where\n                i' = i - 1\n                j' = j - 1\n                x  = fromJust $ DM.lookup (j - 1) $ fromJust $ DM.lookup (i - 1) adjMap'\n\nbuildGraph1 :: Int -> Matrix Double\nbuildGraph1 n = buildAdjMatrix (n * n) genEdges\n    where\n        genEdges x = foldr (\\y acc -> genEdges' (x, y) . acc) id [0..n - 1]\n        genEdges' (x, y)\n            | x >= n    = id\n            | otherwise = addEdge (v, u1) . addEdge (v, u2) . \n                          addEdge (v, u3) . addEdge (v, u4) .\n                          addEdge (v, u5) . addEdge (v, u6) . \n                          addEdge (v, u7) . addEdge (v, u8)\n            where\n                x1 = (x + 2 * y) `mod` n\n                x2 = (x - 2 * y + 3 * n) `mod` n\n                x3 = (x + 2 * y + 1) `mod` n\n                x4 = (x - 2 * y - 1 + 3 * n) `mod` n\n                y1 = (y + 2 * x) `mod` n\n                y2 = (y - 2 * x + 3 * n) `mod` n\n                y3 = (y + 2 * x + 1) `mod` n\n                y4 = (y - 2 * x - 1 + 3 * n) `mod` n\n                u1 = x1 * n + y\n                u2 = x2 * n + y\n                u3 = x3 * n + y\n                u4 = x4 * n + y\n                u5 = x * n + y1\n                u6 = x * n + y2\n                u7 = x * n + y3\n                u8 = x * n + y4\n                v  = x * n + y\n                \ninv :: Int -> Int -> Int\ninv x md = ((xinv `mod` md) + md) `mod` md\n    where \n        xinv = snd $ gcdExt x md  \n\nbuildGraph2 :: Int -> Matrix Double\nbuildGraph2 p = buildAdjMatrix (p + 1) genEdges\n    where\n        genEdges x  \n            | x == p    = addEdge (x, xInv) . addEdge (x, x) . addEdge (x, x)\n            | otherwise = addEdge (x, xInv) . addEdge (x, x1) . addEdge (x, x2)\n            where\n                xInv\n                    | x == 0    = p\n                    | x == p    = 0\n                    | otherwise = inv x p\n                x1 = (x + 1) `mod` p\n                x2 = (x - 1 + p) `mod` p\n\n{- Calculation the optimal alpha for expander. Complexity O(Time(qrEVShifts)). -}\nexpanderAlpha :: Int -> Matrix Double -> Double -> Double\nexpanderAlpha n g d = max (abs ev1) (abs ev2) / d \n    where\n        eps       = 0.00001\n        evs       = fst $ qrEVShifts (toLists $ fst $ getTridiagonal $ toLists g) eps\n        sortedEVs = reverse $ DL.sort evs\n        ev1       = head $ tail sortedEVs\n        ev2       = last sortedEVs\n\nexpanderAlpha1 :: Int -> Double \nexpanderAlpha1 n = expanderAlpha n g 8\n    where\n        g = buildGraph1 n\n\nexpanderAlpha2 :: Int -> Double\nexpanderAlpha2 n = expanderAlpha (n + 1) g 3\n    where\n        g = buildGraph2 n ", "meta": {"hexsha": "cf301ace0f459d591a4657e8c11909579d8ae129", "size": 18186, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linalg.hs", "max_stars_repo_name": "1DarkLord1/computational-linear-algebra", "max_stars_repo_head_hexsha": "a090a9547c402ce808fd3da22fce54831e046f8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-11T23:03:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T23:03:06.000Z", "max_issues_repo_path": "src/Linalg.hs", "max_issues_repo_name": "1DarkLord1/computational-linear-algebra", "max_issues_repo_head_hexsha": "a090a9547c402ce808fd3da22fce54831e046f8a", "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/Linalg.hs", "max_forks_repo_name": "1DarkLord1/computational-linear-algebra", "max_forks_repo_head_hexsha": "a090a9547c402ce808fd3da22fce54831e046f8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9692307692, "max_line_length": 111, "alphanum_fraction": 0.5030243044, "num_tokens": 5814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.8106413614632784}}
{"text": "-----------------------------------------------------------------------------\n-- |\n-- Module      :  Math.Tensor.Internal.LinearAlgebra\n-- Copyright   :  (c) 2019 Tobias Reinhart and Nils Alex\n-- License     :  MIT\n-- Maintainer  :  tobi.reinhart@fau.de, nils.alex@fau.de\n--\n-- Gaussian elimination algorithm based on hmatrix.\n-----------------------------------------------------------------------------\nmodule Math.Tensor.Internal.LinearAlgebra (\n-- * Gaussian Elimination\ngaussianST,\ngaussian,\n-- * Linearly Independent Columns\nindependentColumns,\nindependentColumnsMat,\n-- * Pivots\npivotsU,\nfindPivotMax)\n\nwhere\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Data\nimport Numeric.LinearAlgebra.Devel\n\nimport Data.List (maximumBy)\n\nimport Control.Monad\nimport Control.Monad.ST\n\n-- | Returns the pivot columns of an upper triangular matrix.\n--\n-- @\n-- &#x3BB; let mat = (3 >< 4) [1, 0, 2, -3, 0, 0, 1, 0, 0, 0, 0, 0]\n-- &#x3BB; mat\n-- (3><4)\n--  [ 1.0, 0.0, 2.0, -3.0\n--  , 0.0, 0.0, 1.0,  0.0\n--  , 0.0, 0.0, 0.0,  0.0 ]\n-- &#x3BB; pivotsU mat\n-- [0,2]\n-- @\n--\n\npivotsU :: Matrix Double -> [Int]\npivotsU mat = go (0,0)\n  where\n    go (i,j)\n      = case findPivot mat e (i,j) of\n          Nothing       -> []\n          Just (i', j') -> j' : go (i'+1, j'+1)\n    maxAbs = maximum $ map (maximum . map abs) $ toLists mat\n    e = eps * maxAbs\n\n\neps :: Double\neps = 1e-12\n\n-- find next pivot in upper triangular matrix\n\nfindPivot :: Matrix Double -> Double -> (Int, Int) -> Maybe (Int, Int)\nfindPivot mat e (i, j)\n    | n == j = Nothing\n    | m == i = Nothing\n    | otherwise = case nonZeros of\n                    []          -> if n == j+1\n                                   then Nothing\n                                   else findPivot mat e (i, j+1)\n                    (pi, pj):_  -> Just (pi, pj+j)\n    where\n        m = rows mat\n        n = cols mat\n        col = mat ¿ [j]\n        nonZeros = filter (\\(i', _) -> i' >= i) $ find (not . (< e) . abs) col\n\n-- | Find pivot element below position (i, j) with greatest absolute value in the ST monad.\n\nfindPivotMax :: Int -> Int -> Int -> Int -> STMatrix s Double -> ST s (Maybe (Int, Int))\nfindPivotMax m n i j mat\n    | n == j = return Nothing\n    | m == i = return Nothing\n    | otherwise =\n        do\n          col      <- mapM (\\i' -> do\n                                    x <- readMatrix mat i' j\n                                    return (i', abs x))\n                      [i..m-1]\n          let nonZeros = filter (not . (<eps) . abs . snd) col\n          let (pi, _) = maximumBy (\\(_, x) (_, y) -> x `compare` y) nonZeros\n          case nonZeros of\n            [] -> if n == j+1\n                  then return Nothing\n                  else findPivotMax m n i (j+1) mat\n            _  -> return $ Just (pi, j)\n\n-- gaussian elimination of sub matrix below position (i, j)\n\ngaussian' :: Int -> Int -> Int -> Int -> STMatrix s Double -> ST s ()\ngaussian' m n i j mat = do\n    iPivot' <- findPivotMax m n i j mat\n    case iPivot' of\n        Nothing     -> return ()\n        Just (r, p) -> do\n                          rowOper (SWAP i r (FromCol j)) mat\n                          pv <- readMatrix mat i p\n                          mapM_ (reduce pv p) [i+1 .. m-1]\n                          gaussian' m n (i+1) (p+1) mat\n  where\n    reduce pv p r = do\n                      rv <- readMatrix mat r p\n                      if abs rv < eps\n                        then return ()\n                        else\n                         let frac = -rv / pv\n                             op   = AXPY frac i r (FromCol p)\n                         in do\n                             rowOper op mat\n                             mapM_ (\\j' -> modifyMatrix mat r j' (\\x -> if abs x < eps then 0 else x)) [p..n-1]\n\n-- | Gaussian elimination perfomed in-place in the @'ST'@ monad.\n\ngaussianST :: Int -> Int -> STMatrix s Double -> ST s ()\ngaussianST m n = gaussian' m n 0 0\n\n\n-- | Gaussian elimination as pure function. Involves a copy of the input matrix.\n--\n-- @\n-- &#x3BB; let mat = (3 >< 4) [1, 1, -2, 0, 0, 2, -6, -4, 3, 0, 3, 1]\n-- &#x3BB; mat\n-- (3><4)\n--  [ 1.0, 1.0, -2.0,  0.0\n--  , 0.0, 2.0, -6.0, -4.0\n--  , 3.0, 0.0,  3.0,  1.0 ]\n-- &#x3BB; gaussian mat\n-- (3><4)\n--  [ 3.0, 0.0,  3.0,                1.0\n--  , 0.0, 2.0, -6.0,               -4.0\n--  , 0.0, 0.0,  0.0, 1.6666666666666667 ]\n-- @\n--\n\ngaussian :: Matrix Double -> Matrix Double\ngaussian mat = runST $ do\n    matST <- thawMatrix mat\n    gaussianST m n matST\n    freezeMatrix matST\n  where\n    m = rows mat\n    n = cols mat\n\n-- | Returns the indices of a maximal linearly independent subset of the columns\n--   in the matrix.\n--\n-- @\n-- &#x3BB; let mat = (3 >< 4) [1, 1, -2, 0, 0, 2, -6, -4, 3, 0, 3, 1]\n-- &#x3BB; mat\n-- (3><4)\n--  [ 1.0, 1.0, -2.0,  0.0\n--  , 0.0, 2.0, -6.0, -4.0\n--  , 3.0, 0.0,  3.0,  1.0 ]\n-- &#x3BB; independentColumns mat\n-- [0,1,3]\n-- @\n--\n\nindependentColumns :: Matrix Double -> [Int]\nindependentColumns mat = pivotsU mat'\n    where\n        mat' = gaussian mat\n\n-- | Returns a sub matrix containing a maximal linearly independent subset of\n--   the columns in the matrix.\n--\n-- @\n-- &#x3BB; let mat = (3 >< 4) [1, 1, -2, 0, 0, 2, -6, -4, 3, 0, 3, 1]\n-- &#x3BB; mat\n-- (3><4)\n--  [ 1.0, 1.0, -2.0,  0.0\n--  , 0.0, 2.0, -6.0, -4.0\n--  , 3.0, 0.0,  3.0,  1.0 ]\n-- &#x3BB; independentColumnsMat mat\n-- (3><3)\n--  [ 1.0, 1.0,  0.0\n--  , 0.0, 2.0, -4.0\n--  , 3.0, 0.0,  1.0 ]\n-- @\n--\n\nindependentColumnsMat :: Matrix Double -> Matrix Double\nindependentColumnsMat mat =\n  case independentColumns mat of\n    [] -> (rows mat >< 1) $ repeat 0\n    cs -> mat ¿ cs\n", "meta": {"hexsha": "ba788cb3a265f8397d2ad891f5e0ca9dbdcc7f0e", "size": 5599, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "package/src/Math/Tensor/Internal/LinearAlgebra.hs", "max_stars_repo_name": "TobiReinhart/HaskellTensor2", "max_stars_repo_head_hexsha": "1f7c8caeef3b32e6025935d2240e91dbecd0a150", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-09-07T18:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-01T09:40:39.000Z", "max_issues_repo_path": "package/src/Math/Tensor/Internal/LinearAlgebra.hs", "max_issues_repo_name": "TobiReinhart/HaskellTensor2", "max_issues_repo_head_hexsha": "1f7c8caeef3b32e6025935d2240e91dbecd0a150", "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": "package/src/Math/Tensor/Internal/LinearAlgebra.hs", "max_forks_repo_name": "TobiReinhart/HaskellTensor2", "max_forks_repo_head_hexsha": "1f7c8caeef3b32e6025935d2240e91dbecd0a150", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-06T11:18:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-06T11:18:48.000Z", "avg_line_length": 28.5663265306, "max_line_length": 111, "alphanum_fraction": 0.4824075728, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.8084327216382576}}
{"text": "\n\nmodule Trade.Algorithm.MovingAverage where\n\nimport Statistics.Sample (mean)\n\nimport qualified Data.Vector as Vec\nimport Data.Vector (Vector)\n\nimport Data.List (scanl')\n\nnewtype WindowSize = WindowSize Int deriving (Show, Eq, Ord)\n\nmovingAvgL :: WindowSize -> [Double] -> [Double]\nmovingAvgL (WindowSize k) lst =\n  let (h, t) = splitAt k lst \n  in map (/ fromIntegral k) $ scanl' (+) (sum h) $ zipWith (-) t lst\n\n\nmavgL :: WindowSize -> [Double] -> [(Double, Double)]\nmavgL w@(WindowSize k) xs =\n  let j = fromIntegral k -- / 2\n  in zip [j, j+1 ..] (movingAvgL w xs)\n\n\nmovingAvgV :: WindowSize -> Vector Double -> Vector Double\nmovingAvgV (WindowSize k) v =\n  let len = Vec.length v\n      f a = Vec.slice a k v\n      idx = Vec.generate (len-k) id\n  in Vec.map (mean . f) idx\n\nmavgV :: WindowSize -> Vector Double -> Vector (Double, Double)\nmavgV (WindowSize k) v =\n  let len = Vec.length v\n      f a = (fromIntegral (k+a), mean (Vec.slice a k v))\n  in Vec.generate (len-k) f\n\nmavg3 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg3 = mavg (WindowSize 3)\n\nmavg5 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg5 = mavg (WindowSize 5)\n\nmavg8 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg8 = mavg (WindowSize 8)\n\nmavg12 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg12 = mavg (WindowSize 12)\n\nmavg15 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg15 = mavg (WindowSize 15)\n\nmavg20 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg20 = mavg (WindowSize 20)\n\nmavg30 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg30 = mavg (WindowSize 30)\n\nmavg50 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg50 = mavg (WindowSize 50)\n\nmavg100 :: MovingAverage vec => vec Double -> vec (Double, Double)\nmavg100 = mavg (WindowSize 100)\n\n\nmavgBar :: WindowSize -> Vector (t, Double) -> Vector (t, Double)\nmavgBar w@(WindowSize k) vs =\n  let (ts, ys) = Vec.unzip vs\n      ts' = Vec.drop k ts\n      ys' = movingAverage w ys\n  in Vec.zip ts' ys'\n\n\n\nclass MovingAverage vec where\n  movingAverage :: WindowSize -> vec Double -> vec Double\n  mavg :: WindowSize -> vec Double -> vec (Double, Double)\n\ninstance MovingAverage [] where\n  movingAverage = movingAvgL\n  mavg = mavgL\n  \ninstance MovingAverage Vector where\n  movingAverage = movingAvgV\n  mavg = mavgV\n\n", "meta": {"hexsha": "49dd65b7bb25593328f345f2ff57fc6ab1308e42", "size": 2360, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Trade/Algorithm/MovingAverage.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/Algorithm/MovingAverage.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/Algorithm/MovingAverage.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": 26.8181818182, "max_line_length": 68, "alphanum_fraction": 0.6766949153, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.8062446582443982}}
{"text": "-- Principal component analysis\n\nimport Numeric.LinearAlgebra\nimport System.Directory(doesFileExist)\nimport System.Process(system)\nimport Control.Monad(when)\n\ntype Vec = Vector Double\ntype Mat = Matrix Double\n\n\n-- Vector with the mean value of the columns of a matrix\nmean a = constant (recip . fromIntegral . rows $ a) (rows a) <> a\n\n-- covariance matrix of a list of observations stored as rows\ncov x = (trans xc <> xc) / fromIntegral (rows x - 1)\n    where xc = x - asRow (mean x)\n\n\n-- creates the compression and decompression functions from the desired number of components\npca :: Int -> Mat -> (Vec -> Vec , Vec -> Vec)\npca n dataSet = (encode,decode)\n  where\n    encode x = vp <> (x - m)\n    decode x = x <> vp + m\n    m = mean dataSet\n    c = cov dataSet\n    (_,v) = eigSH' c\n    vp = takeRows n (trans v)\n\nnorm = pnorm PNorm2\n\nmain = do\n    ok <- doesFileExist (\"mnist.txt\")\n    when (not ok)  $ do\n        putStrLn \"\\nTrying to download test datafile...\"\n        system(\"wget -nv http://dis.um.es/~alberto/material/sp/mnist.txt.gz\")\n        system(\"gunzip mnist.txt.gz\")\n        return ()\n    m <- loadMatrix \"mnist.txt\" -- fromFile \"mnist.txt\" (5000,785)\n    let xs = takeColumns (cols m -1) m -- the last column is the digit type (class label)\n    let x = toRows xs !! 4  -- an arbitrary test Vec\n    let (pe,pd) = pca 10 xs\n    let y = pe x\n    print y  -- compressed version\n    print $ norm (x - pd y) / norm x --reconstruction quality\n", "meta": {"hexsha": "a11eba975142252fb8bc5c1de1835eadc59bdceb", "size": 1451, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/examples/pca1.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/pca1.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/pca1.hs", "max_forks_repo_name": "curiousleo/liquidhaskell", "max_forks_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 145, "max_forks_repo_forks_event_min_datetime": "2015-01-12T08:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:29:30.000Z", "avg_line_length": 30.8723404255, "max_line_length": 92, "alphanum_fraction": 0.6450723639, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983308, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.8046512450264642}}