{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE IncoherentInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Data.Vector.Image.FFT (\n fft1d\n, fft2d\n, fft3d\n, Direction(..)\n) where\n\nimport Prelude hiding(map)\nimport qualified Prelude as P\nimport qualified Data.List as L\nimport Data.Vector.Storable hiding(forM_,map,replicate,fromList,toList,(!?),(!))\nimport Data.Maybe\nimport Numeric.LinearAlgebra.Data hiding (fromList,toList,(!))\nimport Numeric.LinearAlgebra.HMatrix hiding (fromList,toList,(!))\nimport qualified Data.Vector.Storable as V\nimport Foreign\nimport GHC.Real\nimport Foreign.C.String\nimport Foreign.C.Types\nimport qualified Control.Monad as C\nimport Data.Vector.Image.Color.RGB\nimport System.IO.Unsafe(unsafePerformIO)\n\nforeign import ccall unsafe \"fft1d\" c_fft1d :: Ptr (Complex Double) -> CInt -> CInt -> IO (Ptr (Complex Double))\nforeign import ccall unsafe \"fft2d\" c_fft2d :: Ptr (Complex Double) -> CInt -> CInt -> CInt -> IO (Ptr (Complex Double))\nforeign import ccall unsafe \"fft3d\" c_fft3d :: Ptr (Complex Double) -> CInt -> CInt -> CInt -> CInt -> IO (Ptr (Complex Double))\nforeign import ccall unsafe \"&fftw_free\" c_p_freeComplexDouble :: FunPtr(Ptr (Complex Double) -> IO ())\n\ndata Direction = Forward | Backword\n\nfft1d :: Vector (Complex Double) -> Direction -> Vector (Complex Double)\nfft1d vec dir = unsafePerformIO $ do\n let n = V.length vec\n p <- unsafeWith vec $ \\v -> do\n case dir of\n Forward -> c_fft1d v (fromIntegral n) 1\n Backword -> c_fft1d v (fromIntegral n) 0\n fp <- newForeignPtr c_p_freeComplexDouble p\n return $ unsafeFromForeignPtr fp 0 n\n\nfft2d :: Vector (Complex Double) -> Int -> Direction -> Vector (Complex Double)\nfft2d vec m dir = unsafePerformIO $ do\n let nm = V.length vec\n let n = nm `div` m\n p <- unsafeWith vec $ \\v -> do\n case dir of\n Forward -> c_fft2d v (fromIntegral m) (fromIntegral n) 1\n Backword -> c_fft2d v (fromIntegral m) (fromIntegral n) 0\n fp <- newForeignPtr c_p_freeComplexDouble p\n return $ unsafeFromForeignPtr fp 0 nm\n\nfft3d :: Vector (Complex Double) -> Int -> Int -> Direction -> Vector (Complex Double)\nfft3d vec l m dir = unsafePerformIO $ do\n let lmn = V.length vec\n let n = lmn `div` (l*m)\n p <- unsafeWith vec $ \\v -> do\n case dir of\n Forward -> c_fft3d v (fromIntegral l) (fromIntegral m) (fromIntegral n) 1\n Backword -> c_fft3d v (fromIntegral l) (fromIntegral m) (fromIntegral n) 0\n fp <- newForeignPtr c_p_freeComplexDouble p\n return $ unsafeFromForeignPtr fp 0 lmn\n\n", "meta": {"hexsha": "763d81344997940c7246a060930d8e7f93253714", "size": 2835, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Vector/Image/FFT.hs", "max_stars_repo_name": "junjihashimoto/img-vector", "max_stars_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-29T04:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T04:04:04.000Z", "max_issues_repo_path": "Data/Vector/Image/FFT.hs", "max_issues_repo_name": "junjihashimoto/img-vector", "max_issues_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data/Vector/Image/FFT.hs", "max_forks_repo_name": "junjihashimoto/img-vector", "max_forks_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_forks_repo_licenses": ["BSD-3-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.3026315789, "max_line_length": 128, "alphanum_fraction": 0.7100529101, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.39955358145021375}} {"text": "{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}\n-- |\n-- Module : Statistics.Distribution\n-- Copyright : (c) 2009 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Type classes for probability distributions\n\nmodule Statistics.Distribution\n (\n -- * Type classes\n Distribution(..)\n , DiscreteDistr(..)\n , ContDistr(..)\n -- ** Distribution statistics\n , MaybeMean(..)\n , Mean(..)\n , MaybeVariance(..)\n , Variance(..)\n , MaybeEntropy(..)\n , Entropy(..)\n , FromSample(..)\n -- ** Random number generation\n , ContGen(..)\n , DiscreteGen(..)\n , genContinuous\n , genContinous\n -- * Helper functions\n , findRoot\n , sumProbabilities\n ) where\n\nimport Control.Applicative ((<$>), Applicative(..))\nimport Control.Monad.Primitive (PrimMonad,PrimState)\nimport Prelude hiding (sum)\nimport Statistics.Function (square)\nimport Statistics.Sample.Internal (sum)\nimport System.Random.MWC (Gen, uniform)\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Generic as G\n\n\n-- | Type class common to all distributions. Only c.d.f. could be\n-- defined for both discrete and continuous distributions.\nclass Distribution d where\n -- | Cumulative distribution function. The probability that a\n -- random variable /X/ is less or equal than /x/,\n -- i.e. P(/X/≤/x/). Cumulative should be defined for\n -- infinities as well:\n --\n -- > cumulative d +∞ = 1\n -- > cumulative d -∞ = 0\n cumulative :: d -> Double -> Double\n\n -- | One's complement of cumulative distribution:\n --\n -- > complCumulative d x = 1 - cumulative d x\n --\n -- It's useful when one is interested in P(/X/>/x/) and\n -- expression on the right side begin to lose precision. This\n -- function have default implementation but implementors are\n -- encouraged to provide more precise implementation.\n complCumulative :: d -> Double -> Double\n complCumulative d x = 1 - cumulative d x\n\n-- | Discrete probability distribution.\nclass Distribution d => DiscreteDistr d where\n -- | Probability of n-th outcome.\n probability :: d -> Int -> Double\n probability d = exp . logProbability d\n\n -- | Logarithm of probability of n-th outcome\n logProbability :: d -> Int -> Double\n logProbability d = log . probability d\n\n\n-- | Continuous probability distribution.\n--\n-- Minimal complete definition is 'quantile' and either 'density' or\n-- 'logDensity'.\nclass Distribution d => ContDistr d where\n -- | Probability density function. Probability that random\n -- variable /X/ lies in the infinitesimal interval\n -- [/x/,/x+/δ/x/) equal to /density(x)/⋅δ/x/\n density :: d -> Double -> Double\n density d = exp . logDensity d\n\n -- | Inverse of the cumulative distribution function. The value\n -- /x/ for which P(/X/≤/x/) = /p/. If probability is outside\n -- of [0,1] range function should call 'error'\n quantile :: d -> Double -> Double\n\n -- | 1-complement of @quantile@:\n --\n -- > complQuantile x ≡ quantile (1 - x)\n complQuantile :: d -> Double -> Double\n complQuantile d x = quantile d (1 - x)\n\n -- | Natural logarithm of density.\n logDensity :: d -> Double -> Double\n logDensity d = log . density d\n\n\n-- | Type class for distributions with mean. 'maybeMean' should return\n-- 'Nothing' if it's undefined for current value of data\nclass Distribution d => MaybeMean d where\n maybeMean :: d -> Maybe Double\n\n-- | Type class for distributions with mean. If a distribution has\n-- finite mean for all valid values of parameters it should be\n-- instance of this type class.\nclass MaybeMean d => Mean d where\n mean :: d -> Double\n\n\n\n-- | Type class for distributions with variance. If variance is\n-- undefined for some parameter values both 'maybeVariance' and\n-- 'maybeStdDev' should return Nothing.\n--\n-- Minimal complete definition is 'maybeVariance' or 'maybeStdDev'\nclass MaybeMean d => MaybeVariance d where\n maybeVariance :: d -> Maybe Double\n maybeVariance d = (*) <$> x <*> x where x = maybeStdDev d\n maybeStdDev :: d -> Maybe Double\n maybeStdDev = fmap sqrt . maybeVariance\n\n-- | Type class for distributions with variance. If distribution have\n-- finite variance for all valid parameter values it should be\n-- instance of this type class.\n--\n-- Minimal complete definition is 'variance' or 'stdDev'\nclass (Mean d, MaybeVariance d) => Variance d where\n variance :: d -> Double\n variance d = square (stdDev d)\n stdDev :: d -> Double\n stdDev = sqrt . variance\n\n-- | Type class for distributions with entropy, meaning Shannon entropy\n-- in the case of a discrete distribution, or differential entropy in the\n-- case of a continuous one. 'maybeEntropy' should return 'Nothing' if\n-- entropy is undefined for the chosen parameter values.\nclass (Distribution d) => MaybeEntropy d where\n -- | Returns the entropy of a distribution, in nats, if such is defined.\n maybeEntropy :: d -> Maybe Double\n\n-- | Type class for distributions with entropy, meaning Shannon\n-- entropy in the case of a discrete distribution, or differential\n-- entropy in the case of a continuous one. If the distribution has\n-- well-defined entropy for all valid parameter values then it\n-- should be an instance of this type class.\nclass (MaybeEntropy d) => Entropy d where\n -- | Returns the entropy of a distribution, in nats.\n entropy :: d -> Double\n\n-- | Generate discrete random variates which have given\n-- distribution.\nclass Distribution d => ContGen d where\n genContVar :: PrimMonad m => d -> Gen (PrimState m) -> m Double\n\n-- | Generate discrete random variates which have given\n-- distribution. 'ContGen' is superclass because it's always possible\n-- to generate real-valued variates from integer values\nclass (DiscreteDistr d, ContGen d) => DiscreteGen d where\n genDiscreteVar :: PrimMonad m => d -> Gen (PrimState m) -> m Int\n\n-- | Estimate distribution from sample. First parameter in sample is\n-- distribution type and second is element type.\nclass FromSample d a where\n -- | Estimate distribution from sample. Returns nothing is there's\n -- not enough data to estimate or sample clearly doesn't come from\n -- distribution in question. For example if there's negative\n -- samples in exponential distribution.\n fromSample :: G.Vector v a => v a -> Maybe d\n\n\n-- | Generate variates from continuous distribution using inverse\n-- transform rule.\ngenContinuous :: (ContDistr d, PrimMonad m) => d -> Gen (PrimState m) -> m Double\ngenContinuous d gen = do\n x <- uniform gen\n return $! quantile d x\n\n-- | Backwards compatibility with genContinuous.\ngenContinous :: (ContDistr d, PrimMonad m) => d -> Gen (PrimState m) -> m Double\ngenContinous = genContinuous\n{-# DEPRECATED genContinous \"Use genContinuous\" #-}\n\ndata P = P {-# UNPACK #-} !Double {-# UNPACK #-} !Double\n\n-- | Approximate the value of /X/ for which P(/x/>/X/)=/p/.\n--\n-- This method uses a combination of Newton-Raphson iteration and\n-- bisection with the given guess as a starting point. The upper and\n-- lower bounds specify the interval in which the probability\n-- distribution reaches the value /p/.\nfindRoot :: ContDistr d =>\n d -- ^ Distribution\n -> Double -- ^ Probability /p/\n -> Double -- ^ Initial guess\n -> Double -- ^ Lower bound on interval\n -> Double -- ^ Upper bound on interval\n -> Double\nfindRoot d prob = loop 0 1\n where\n loop !(i::Int) !dx !x !lo !hi\n | abs dx <= accuracy || i >= maxIters = x\n | otherwise = loop (i+1) dx'' x'' lo' hi'\n where\n err = cumulative d x - prob\n P lo' hi' | err < 0 = P x hi\n | otherwise = P lo x\n pdf = density d x\n P dx' x' | pdf /= 0 = P (err / pdf) (x - dx)\n | otherwise = P dx x\n P dx'' x''\n | x' < lo' || x' > hi' || pdf == 0 = let y = (lo' + hi') / 2\n in P (y-x) y\n | otherwise = P dx' x'\n accuracy = 1e-15\n maxIters = 150\n\n-- | Sum probabilities in inclusive interval.\nsumProbabilities :: DiscreteDistr d => d -> Int -> Int -> Double\nsumProbabilities d low hi =\n -- Return value is forced to be less than 1 to guard against roundoff errors.\n -- ATTENTION! this check should be removed for testing or it could mask bugs.\n min 1 . sum . U.map (probability d) $ U.enumFromTo low hi\n", "meta": {"hexsha": "c448d4fd04d34b88e990f90969faa54093d4a842", "size": 8743, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Distribution.hs", "max_stars_repo_name": "infinity0/statistics", "max_stars_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-11T23:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:33:10.000Z", "max_issues_repo_path": "Statistics/Distribution.hs", "max_issues_repo_name": "infinity0/statistics", "max_issues_repo_head_hexsha": "c14036be7f360f14f58270f87b8347e635a9f779", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-02-26T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:27:01.000Z", "max_forks_repo_path": "Statistics/Distribution.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": 37.3632478632, "max_line_length": 81, "alphanum_fraction": 0.6456593847, "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.39911891966567836}} {"text": "{-# LANGUAGE BangPatterns, \n ScopedTypeVariables,\n RecordWildCards,\n FlexibleContexts,\n TypeFamilies #-}\n\n-- |\n-- Module : AI.HNN.FF.Network\n-- Copyright : (c) 2012 Alp Mestanogullari\n-- License : BSD3\n-- Maintainer : alpmestan@gmail.com\n-- Stability : experimental\n-- Portability : GHC\n-- \n-- An implementation of feed-forward neural networks in pure Haskell.\n-- \n-- It uses weight matrices between each layer to represent the connections between neurons from\n-- a layer to the next and exports only the useful bits for a user of the library.\n-- \n-- Here is an example of using this module to create a feed-forward neural network with 2 inputs,\n-- 2 neurons in a hidden layer and one neuron in the output layer, with random weights, and compute\n-- its output for [1,2] using the sigmoid function for activation for all the neurons.\n-- \n-- > import AI.HNN.FF.Network\n-- > import Numeric.LinearAlgebra\n-- >\n-- > main = do\n-- > n <- createNetwork 2 [2] 1 :: IO (Network Double)\n-- > print $ output n sigmoid (fromList [1, 1])\n-- \n-- /Note/: Here, I create a @Network Double@, but you can replace 'Double' with any number type\n-- that implements the appropriate typeclasses you can see in the signatures of this module.\n-- Having your number type implement the @Floating@ typeclass too is a good idea, since that's what most of the\n-- common activation functions require.\n--\n-- /Note 2/: You can also give some precise weights to initialize the neural network with, with\n-- 'fromWeightMatrices'. You can also restore a neural network you had saved using 'loadNetwork'.\n-- \n-- Here is an example of how to train a neural network to learn the XOR function.\n-- ( for reference: XOR(0, 0) = 0, XOR(0, 1) = 1, XOR(1, 0) = 1, XOR(1, 1) = 0 )\n-- \n-- First, let's import hnn's feedforward neural net module, and hmatrix's vector types.\n-- \n-- > import AI.HNN.FF.Network\n-- > import Numeric.LinearAlgebra\n-- \n-- Now, we will specify our training set (what the net should try to learn).\n-- \n-- > samples :: Samples Double\n-- > samples = [ fromList [0, 0] --> fromList [0]\n-- > , fromList [0, 1] --> fromList [1]\n-- > , fromList [1, 0] --> fromList [1]\n-- > , fromList [1, 1] --> fromList [0] \n-- > ]\n-- \n-- You can see that this is basically a list of pairs of vectors, the first vector being\n-- the input given to the network, the second one being the expected output. Of course,\n-- this imply working on a neural network with 2 inputs, and a single neuron on the output layer. Then,\n-- let's create one!\n-- \n-- > main = do\n-- > net <- createNetwork 2 [2] 1\n-- \n-- You may have noticed we haven't specified a signature this time, unlike in the earlier snippet.\n-- Since we gave a signature to samples, specifying we're working with 'Double' numbers, and since\n-- we are going to tie 'net' and 'samples' by a call to a learning function, GHC will gladly figure out\n-- that 'net' is working with 'Double'. \n-- \n-- Now, it's time to train our champion. But first, let's see how bad he is now. The weights are most likely\n-- not close to those that will give a good result for simulating XOR. Let's compute the output of the net on\n-- the input vectors of our samples, using 'tanh' as the activation function.\n-- \n-- > mapM_ (print . output net tanh . fst) samples\n-- \n-- Ok, you've tested this, and it gives terrible results. Let's fix this by letting 'trainNTimes' teach our neural net\n-- how to behave. Since we're using 'tanh' as our activation function, we will tell it to the training function,\n-- and also specify its derivative.\n-- \n-- > let smartNet = trainNTimes 1000 0.8 tanh tanh' net samples\n-- \n-- So, this tiny piece of code will run the backpropagation algorithm on the samples 1000 times, with a learning rate\n-- of 0.8. The learning rate is basically how strongly we should modify the weights when we try to correct the error the net makes\n-- on our samples. The bigger it is, the more the weights are going to change significantly. Depending on the case, it can be good,\n-- but sometimes it can make the backprop algorithm oscillate around good weight values without actually getting to them.\n-- You usually want to test several values and see which ones get you the nicest neural net, which generalizes well to samples\n-- that are not in the training set while giving decent results on the training set.\n-- \n-- Now, let's see how that worked out for us:\n-- \n-- > mapM_ (print . output smartNet tanh . fst) samples\n-- \n-- You could even save that neural network's weights to a file, so that you don't need to train it again in the future, using 'saveNetwork':\n--\n-- > saveNetwork \"smartNet.nn\" smartNet\n--\n-- Please note that 'saveNetwork' is just a wrapper around zlib compression + serialization using the binary package.\n-- AI.HNN.FF.Network also provides a 'Data.Binary.Binary' instance for 'Network', which means you can also simply use\n-- 'Data.Binary.encode' and 'Data.Binary.decode' to have your own saving/restoring routines, or to simply get a bytestring \n-- we can send over the network, for example.\n-- \n-- Here's a run of the program we described on my machine (with the timing): first set of\n-- fromList's is the output of the initial neural network, the second one is the output of\n-- 'smartNet' :-)\n-- \n-- > fromList [0.574915179613429]\n-- > fromList [0.767589097192215]\n-- > fromList [0.7277396607146663]\n-- > fromList [0.8227114080561128]\n-- > ------------------\n-- > fromList [6.763498312099933e-2]\n-- > fromList [0.9775186355284375]\n-- > fromList [0.9350823296850516]\n-- > fromList [-4.400205702560454e-2]\n-- > \n-- > real 0m0.365s\n-- > user 0m0.072s\n-- > sys 0m0.016s\n-- \n-- Rejoyce! Feel free to play around with the library and report any bug, feature request and whatnot to us on\n-- our github repository using the appropriate tags. Also, you can\n-- see the simple program we studied here with pretty colors at \n-- and other ones at .\n\nmodule AI.HNN.FF.Network\n (\n -- * Types\n Network(..)\n , ActivationFunction\n , ActivationFunctionDerivative\n , Sample\n , Samples\n , (-->)\n\n -- * Creating a neural network\n , createNetwork\n , fromWeightMatrices\n\n -- * Computing a neural network's output\n , output\n , tanh\n , tanh'\n , sigmoid\n , sigmoid'\n\n -- * Training a neural network\n , trainUntil\n , trainNTimes\n , trainUntilErrorBelow\n , quadError\n \n -- * Loading and saving a neural network\n , loadNetwork\n , saveNetwork\n ) where\n\nimport Codec.Compression.Zlib (compress, decompress)\nimport Data.Binary (Binary(..), encode, decode)\nimport Data.List (foldl')\nimport Foreign.Storable (Storable)\nimport qualified Data.ByteString.Lazy as B\nimport qualified Data.Vector as V\n\nimport System.Random.MWC\nimport Numeric.LinearAlgebra.HMatrix hiding (corr)\nimport Data.Functor ((<$>))\n\n-- | Our feed-forward neural network type. Note the 'Binary' instance, which means you can use \n-- 'encode' and 'decode' in case you need to serialize your neural nets somewhere else than\n-- in a file (e.g over the network)\nnewtype Network a = Network\n { matrices :: V.Vector (Matrix a) -- ^ the weight matrices\n } deriving Show\n\ninstance (Element a, Binary a) => Binary (Network a) where\n put (Network ms) = put . V.toList $ ms\n get = (Network . V.fromList) `fmap` get \n\n-- | The type of an activation function, mostly used for clarity in signatures\ntype ActivationFunction a = a -> a\n\n-- | The type of an activation function's derivative, mostly used for clarity in signatures\ntype ActivationFunctionDerivative a = a -> a\n\n-- | The following creates a neural network with 'n' inputs and if 'l' is [n1, n2, ...]\n-- the net will have n1 neurons on the first layer, n2 neurons on the second, and so on\n-- ending with k neurons on the output layer, with random weight matrices as a courtesy of\n-- 'System.Random.MWC.uniformVector'.\n-- \n-- > createNetwork n l k\ncreateNetwork :: (Variate a, Storable a) => Int -> [Int] -> Int -> IO (Network a)\ncreateNetwork nInputs hiddens nOutputs =\n fmap Network $ withSystemRandom . asGenST $ \\gen -> go gen dimensions V.empty\n where\n go _ [] !ms = return ms\n go gen ((!n,!m):ds) ms = do\n !mat <- randomMat n m gen\n go gen ds (ms `V.snoc` mat)\n randomMat n m g = reshape m `fmap` uniformVector g (n*m)\n dimensions = zip (hiddens ++ [nOutputs]) $\n (nInputs+1 : hiddens)\n{-# INLINE createNetwork #-}\n\n\n-- | Creates a neural network with exactly the weight matrices given as input here.\n-- We don't check that the numbers of rows/columns are compatible, etc. \nfromWeightMatrices :: Storable a => V.Vector (Matrix a) -> Network a\nfromWeightMatrices ws = Network ws\n{-# INLINE fromWeightMatrices #-}\n\n-- The `join [input, 1]' trick below is a courtesy of Alberto Ruiz\n-- . Per his words:\n--\n-- \"The idea is that the constant input in the first layer can be automatically transferred to the following layers\n-- by the learning algorithm (by setting the weights of a neuron to 1,0,0,0,...). This allows for a simpler\n-- implementation and in my experiments those networks are able to easily solve non linearly separable problems.\"\n\n-- | Computes the output of the network on the given input vector with the given activation function\noutput :: (Floating (Vector a), Numeric a, Storable a, Num (Vector a)) => Network a -> ActivationFunction a -> Vector a -> Vector a\noutput (Network{..}) act input = V.foldl' f (vjoin [input, 1]) matrices\n where f !inp m = cmap act $ m #> inp\n{-# INLINE output #-}\n\n-- | Computes and keeps the output of all the layers of the neural network with the given activation function\noutputs :: (Floating (Vector a), Numeric a, Storable a, Num (Vector a)) => Network a -> ActivationFunction a -> Vector a -> V.Vector (Vector a)\noutputs (Network{..}) act input = V.scanl f (vjoin [input, 1]) matrices\n where f !inp m = cmap act $ m #> inp\n{-# INLINE outputs #-}\n\ndeltas :: (Floating (Vector a), Floating a, Numeric a, Container Vector a, Num (Vector a)) => Network a -> ActivationFunctionDerivative a -> V.Vector (Vector a) -> Vector a -> V.Vector (Matrix a)\ndeltas (Network{..}) act' os expected = V.zipWith outer (V.tail ds) (V.init os)\n where !dl = (V.last os - expected) * (deriv $ V.last os)\n !ds = V.scanr f dl (V.zip os matrices)\n f (!o, m) !del = deriv o * (tr m #> del)\n deriv = cmap act'\n{-# INLINE deltas #-}\n\nupdateNetwork :: (Floating (Vector a), Floating a, Numeric a, Storable a, Num (Vector a), Container Vector a) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Sample a -> Network a\nupdateNetwork alpha act act' n@(Network{..}) (input, expectedOutput) = Network $ V.zipWith (+) matrices corr\n where !xs = outputs n act input\n !ds = deltas n act' xs expectedOutput\n !corr = V.map (scale (-alpha)) ds\n{-# INLINE updateNetwork #-}\n \n-- | Input vector and expected output vector\ntype Sample a = (Vector a, Vector a)\n\n-- | List of 'Sample's\ntype Samples a = [Sample a]\n\n-- | Handy operator to describe your learning set, avoiding unnecessary parentheses. It's just a synonym for '(,)'. \n-- Generally you'll load your learning set from a file, a database or something like that, but it can be nice for \n-- quickly playing with hnn or for simple problems where you manually specify your learning set.\n-- That is, instead of writing:\n-- \n-- > samples :: Samples Double\n-- > samples = [ (fromList [0, 0], fromList [0])\n-- > , (fromList [0, 1], fromList [1])\n-- > , (fromList [1, 0], fromList [1])\n-- > , (fromList [1, 1], fromList [0]) \n-- > ]\n-- \n-- You can write:\n-- \n-- > samples :: Samples Double\n-- > samples = [ fromList [0, 0] --> fromList [0]\n-- > , fromList [0, 1] --> fromList [1]\n-- > , fromList [1, 0] --> fromList [1]\n-- > , fromList [1, 1] --> fromList [0] \n-- > ]\n(-->) :: Vector a -> Vector a -> Sample a\n(-->) = (,)\n\nbackpropOnce :: (Floating (Vector a), Floating a, Numeric a, Num (Vector a), Container Vector a) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a\nbackpropOnce rate act act' n samples = foldl' (updateNetwork rate act act') n samples\n{-# INLINE backpropOnce #-}\n\n-- | Generic training function.\n-- \n-- The first argument is a predicate that will tell the backpropagation algorithm when to stop.\n-- The first argument to the predicate is the epoch, i.e the number of times the backprop has been\n-- executed on the samples. The second argument is /the current network/, and the third is the list of samples.\n-- You can thus combine these arguments to create your own criterion.\n-- \n-- For example, if you want to stop learning either when the network's quadratic error on the samples,\n-- using the tanh function, is below 0.01, or after 1000 epochs, whichever comes first, you could\n-- use the following predicate:\n-- \n-- > pred epochs net samples = if epochs == 1000 then True else quadError tanh net samples < 0.01\n-- \n-- You could even use 'Debug.Trace.trace' to print the error, to see how the error evolves while it's learning,\n-- or redirect this to a file from your shell in order to generate a pretty graphics and what not.\n-- \n-- The second argument (after the predicate) is the learning rate. Then come the activation function you want,\n-- its derivative, the initial neural network, and your training set.\n-- Note that we provide 'trainNTimes' and 'trainUntilErrorBelow' for common use cases.\ntrainUntil :: (Floating (Vector a), Floating a, Numeric a, Num (Vector a), Container Vector a) => (Int -> Network a -> Samples a -> Bool) -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a\ntrainUntil pr learningRate act act' net samples = go net 0\n where go n !k | pr k n samples = n\n | otherwise = case backpropOnce learningRate act act' n samples of\n n' -> go n' (k+1)\n{-# INLINE trainUntil #-}\n\n-- | Trains the neural network with backpropagation the number of times specified by the 'Int' argument,\n-- using the given learning rate (second argument). \ntrainNTimes :: (Floating (Vector a), Floating a, Numeric a, Num (Vector a), Container Vector a) => Int -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a\ntrainNTimes n = trainUntil (\\k _ _ -> k > n)\n{-# INLINE trainNTimes #-}\n\n-- | Quadratic error on the given training set using the given activation function. Useful to create\n-- your own predicates for 'trainUntil'.\nquadError :: (Floating (Vector a), Floating a, Fractional (RealOf a), Normed (Vector a), Numeric a) => ActivationFunction a -> Network a -> Samples a -> RealOf a\nquadError act net samples = realToFrac $ foldl' (\\err (inp, out) -> err + (norm_2 $ output net act inp - out)) 0 samples\n{-# INLINE quadError #-}\n\n-- | Trains the neural network until the quadratic error ('quadError') comes below the given value (first argument),\n-- using the given learning rate (second argument).\n-- \n-- /Note/: this can loop pretty much forever when you're using a bad architecture for the problem, or inappropriate activation\n-- functions.\ntrainUntilErrorBelow :: (Floating (Vector a), Floating a, Numeric a, Normed (Vector a), Ord a, Container Vector a, Num (RealOf a), a ~ RealOf a, Show a) => a -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a\ntrainUntilErrorBelow x rate act = trainUntil (\\_ n s -> quadError act n s < x) rate act\n{-# INLINE trainUntilErrorBelow #-}\n\n-- | The sigmoid function: 1 / (1 + exp (-x))\nsigmoid :: Floating a => a -> a\nsigmoid !x = 1 / (1 + exp (-x))\n{-# INLINE sigmoid #-}\n\n-- | Derivative of the sigmoid function: sigmoid x * (1 - sigmoid x)\nsigmoid' :: Floating a => a -> a\nsigmoid' !x = case sigmoid x of\n s -> s * (1 - s)\n{-# INLINE sigmoid' #-}\n\n-- | Derivative of the 'tanh' function from the Prelude.\ntanh' :: Floating a => a -> a\ntanh' !x = case tanh x of\n s -> 1 - s**2\n{-# INLINE tanh' #-}\n\n-- | Loading a neural network from a file (uses zlib compression on top of serialization using the binary package).\n-- Will throw an exception if the file isn't there.\nloadNetwork :: (Storable a, Element a, Binary a) => FilePath -> IO (Network a)\nloadNetwork fp = decode . decompress <$> B.readFile fp\n{-# INLINE loadNetwork #-}\n\n-- | Saving a neural network to a file (uses zlib compression on top of serialization using the binary package).\nsaveNetwork :: (Storable a, Element a, Binary a) => FilePath -> Network a -> IO ()\nsaveNetwork fp = B.writeFile fp . compress . encode\n{-# INLINE saveNetwork #-}\n", "meta": {"hexsha": "5e29de8ea3659a968b08c6157bd02a094f6c66ab", "size": 17125, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "AI/HNN/FF/Network.hs", "max_stars_repo_name": "alpmestan/hnn", "max_stars_repo_head_hexsha": "4d803505bf8ab213d2fcda1ce9336f11b3cf40c4", "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": "AI/HNN/FF/Network.hs", "max_issues_repo_name": "alpmestan/hnn", "max_issues_repo_head_hexsha": "4d803505bf8ab213d2fcda1ce9336f11b3cf40c4", "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": "AI/HNN/FF/Network.hs", "max_forks_repo_name": "alpmestan/hnn", "max_forks_repo_head_hexsha": "4d803505bf8ab213d2fcda1ce9336f11b3cf40c4", "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": 48.7891737892, "max_line_length": 259, "alphanum_fraction": 0.6751532847, "num_tokens": 4418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3991189065753687}} {"text": "{-|\nModule: MachineLearning.NeuralNetwork.Topology\nDescription: Neural Network's Topology\nCopyright: (c) Alexander Ignatyev, 2017\nLicense: BSD-3\nStability: experimental\nPortability: POSIX\n\nNeural Network's Topology\n-}\n\nmodule MachineLearning.NeuralNetwork.Topology\n(\n Topology\n , LossFunc(..)\n , makeTopology\n , loss\n , propagateForward\n , propagateBackward\n , numberOutputs\n , initializeTheta\n , initializeThetaIO\n , initializeThetaM\n , flatten\n , unflatten\n)\n\nwhere\n\nimport Control.Monad (zipWithM)\nimport Data.List (foldl')\nimport qualified Control.Monad.Random as RndM\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as LA\nimport MachineLearning.Types (R, Vector, Matrix)\nimport MachineLearning.Utils (listOfTuplesToList)\nimport MachineLearning.NeuralNetwork.Layer (Layer(..), Cache(..))\nimport MachineLearning.NeuralNetwork.Regularization (Regularization, forwardReg, backwardReg)\n\n\n-- | Loss function's type.\n-- Takes x, weights and y.\ntype LossFunc = Matrix -> Matrix -> R\n\n\n-- | Neural network topology has at least 2 elements: numver of input and number of outputs.\n-- And sizes of hidden layers between 2 elements.\ndata Topology = Topology [(Int, Int)] [Layer] LossFunc\n\n\n-- | Makes Neural Network's Topology.\n-- Takes number of inputs, list of hidden layers, output layer and loss function.\nmakeTopology :: Int -> [Layer] -> Layer -> LossFunc -> Topology\nmakeTopology nInputs hiddenLayers outputLayer lossFunc =\n let layers = hiddenLayers ++ [outputLayer]\n layerSizes = nInputs : (map lUnits layers)\n sizes = getThetaSizes layerSizes\n in Topology sizes layers lossFunc\n \n\n-- | Calculates loss for the given topology.\n-- Takes topology, regularization, x, weights, y.\nloss :: Topology -> Regularization -> Matrix -> [(Matrix, Matrix)] -> Matrix -> R\nloss (Topology _ _ lf) reg x weights y =\n let lossValue = lf x y\n regValue = forwardReg reg weights\n in lossValue + regValue\n\n\n-- | Implementation of forward propagation algorithm.\npropagateForward :: Topology -> Matrix -> [(Matrix, Matrix)] -> (Matrix, [Cache])\npropagateForward (Topology _ layers _) x thetaList = foldl' f (x, []) $ zip thetaList layers\n where f (a, cs) (theta, hl) =\n let (a', cache) = forwardPass hl a theta\n in (a', cache:cs)\n\n\n-- | Makes one forward step for the given layer.\nforwardPass :: Layer -> Matrix -> (Matrix, Matrix) -> (Matrix, Cache)\nforwardPass layer a (b, w) = (a', Cache z a w)\n where z = lForward layer a b w\n a' = lActivation layer z\n\n\n-- | Implementation of backward propagation algorithm.\npropagateBackward :: Topology -> Regularization -> Matrix -> [Cache] -> Matrix -> [(Matrix, Matrix)]\npropagateBackward (Topology _ layers _) reg scores (cache:cacheList) y = gradientList\n where cache' = Cache scores (cacheX cache) (cacheW cache)\n cacheList' = cache':cacheList\n gradientList = snd $ foldl' f (y, []) $ zip cacheList' $ reverse layers\n f (da, grads) (cache, hl) =\n let (da', db, dw) = backwardPass hl reg da cache\n in (da', (db, dw):grads)\n\n\n-- | Makes one backward step for the given layer.\nbackwardPass :: Layer -> Regularization -> Matrix -> Cache -> (Matrix, Matrix, Matrix)\nbackwardPass layer reg da cache = (da', db, dw')\n where delta = lActivationGradient layer (cacheZ cache) da\n (da', db, dw) = lBackward layer delta cache\n dw' = dw + (backwardReg reg (cacheW cache))\n\n\n-- | Returns number of outputs of the given topology.\nnumberOutputs :: Topology -> Int\nnumberOutputs (Topology nnt _ _) = fst $ last nnt\n\n\n-- | Returns dimensions of weight matrices for given neural network topology\ngetThetaSizes :: [Int] -> [(Int, Int)]\ngetThetaSizes nn = zipWith (\\r c -> (r, c)) (tail nn) nn\n\n\n-- | Create and initialize weights vector with random values\n-- for given neural network topology.\n-- Takes a seed to initialize generator of random numbers as a first parameter.\ninitializeTheta :: Int -> Topology -> Vector\ninitializeTheta seed topology = RndM.evalRand (initializeThetaM topology) gen\n where gen = RndM.mkStdGen seed\n\n\n-- | Create and initialize weights vector with random values\n-- for given neural network topology inside IO Monad.\ninitializeThetaIO :: Topology -> IO Vector\ninitializeThetaIO = RndM.evalRandIO . initializeThetaM\n\n\n-- | Create and initialize weights vector with random values\n-- for given neural network topology inside RandomMonad.\ninitializeThetaM :: RndM.RandomGen g => Topology -> RndM.Rand g Vector\ninitializeThetaM topology = flatten <$> initializeThetaListM topology\n\n\n-- | Create and initialize list of weights matrices with random values\n-- for given neural network topology.\ninitializeThetaListM :: RndM.RandomGen g => Topology -> RndM.Rand g [(Matrix, Matrix)]\ninitializeThetaListM (Topology sizes layers _) = zipWithM lInitializeThetaM layers sizes\n\n\n-- | Flatten list of matrices into vector.\nflatten :: [(Matrix, Matrix)] -> Vector\nflatten ms = V.concat $ map LA.flatten $ listOfTuplesToList ms\n\n\n-- | Unflatten vector into list of matrices for given neural network topology.\nunflatten :: Topology -> Vector -> [(Matrix, Matrix)]\nunflatten (Topology sizes _ _) v =\n let offsets = reverse $ foldl' (\\os (r, c) -> (r+r*c + head os):os) [0] (init sizes)\n ms = zipWith (\\o (r, c) -> (LA.reshape r (slice o r), LA.reshape c (slice (o+r) (r*c)))) offsets sizes\n slice o n = V.slice o n v\n in ms\n", "meta": {"hexsha": "b9e70d1f21604f35fb1c58dbf7b1114bf256955d", "size": 5403, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/MachineLearning/NeuralNetwork/Topology.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/NeuralNetwork/Topology.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/NeuralNetwork/Topology.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": 35.5460526316, "max_line_length": 108, "alphanum_fraction": 0.7120118453, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.39775724579733196}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule STCPinwheel where\n\nimport Control.Monad as M\nimport Control.Monad.Parallel as MP\nimport qualified Data.Array.Accelerate as A\nimport Data.Array.Accelerate.LLVM.PTX\nimport Data.Array.IArray as IA\nimport Data.Array.Repa as R\nimport Data.Binary\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport Filter.Utils\nimport FokkerPlanck\nimport Foreign.CUDA.Driver as CUDA\nimport FourierMethod.BlockMatrixAcc\nimport FourierMethod.FourierSeries2D\nimport FourierPinwheel\nimport Image.IO\nimport Pinwheel.FourierSeries2D\nimport STC hiding (convolve)\nimport System.Directory\nimport System.Environment\nimport System.FilePath\nimport Text.Printf\nimport Utils.Array\nimport Utils.Time\n\nmain = do\n args@(deviceIDsStr:numPointsStr:deltaStr:thresholdStr:numPointsReconStr:deltaReconStr:numOrientationStr:numScaleStr:thetaSigmaStr:scaleSigmaStr:tauStr:numR2FreqStr:periodR2Str:phiFreqsStr:rhoFreqsStr:thetaFreqsStr:scaleFreqsStr:initDistStr:initScaleStr:histFilePath:stdR2Str:stdStr:numBatchR2Str:numBatchR2FreqsStr:numBatchOriStr:batchSizeStr:sStr:radiusStr:deltaTStr:numThreadStr:_) <-\n getArgs\n let deviceIDs = read deviceIDsStr :: [Int]\n numPoints = read numPointsStr :: Int\n delta = read deltaStr :: Double\n threshold = read thresholdStr :: Double\n numPointsRecon = read numPointsReconStr :: Int\n deltaRecon = read deltaReconStr :: Double\n numOrientation = read numOrientationStr :: Int\n numScale = read numScaleStr :: Int\n thetaSigma = read thetaSigmaStr :: Double\n scaleSigma = read scaleSigmaStr :: Double\n tau = read tauStr :: Double\n numR2Freq = read numR2FreqStr :: Int\n periodR2 = read periodR2Str :: Double\n phiFreq = read phiFreqsStr :: Int\n phiFreqs = L.map fromIntegral [-phiFreq .. phiFreq]\n rhoFreq = read rhoFreqsStr :: Int\n rhoFreqs = L.map fromIntegral [-rhoFreq .. rhoFreq]\n thetaFreq = read thetaFreqsStr :: Int\n thetaFreqs = L.map fromIntegral [-thetaFreq .. thetaFreq]\n scaleFreq = read scaleFreqsStr :: Int\n scaleFreqs = L.map fromIntegral [-scaleFreq .. scaleFreq]\n initScale = read initScaleStr :: Double\n initDist = read initDistStr :: [(Double, Double, Double, Double)]\n initPoints = L.map (\\(x, y, t, s) -> Point x y t s) initDist\n initSource = [L.head initPoints]\n initSink = [L.last initPoints]\n numThread = read numThreadStr :: Int\n folderPath = \"output/test/STCPinwheel\"\n stdR2 = read stdR2Str :: Double\n std = read stdStr :: Double\n numBatchR2 = read numBatchR2Str :: Int\n numBatchR2Freqs = read numBatchR2FreqsStr :: Int\n numBatchOri = read numBatchOriStr :: Int\n batchSize = read batchSizeStr :: Int\n s = read sStr :: Double\n radius = read radiusStr :: Double\n deltaT = read deltaTStr :: Double\n periodEnvelope = periodR2 ^ 2 * 2\n maxScale = sqrt periodEnvelope\n removePathForcibly folderPath\n createDirectoryIfMissing True folderPath\n flag <- doesFileExist histFilePath \n \n hist <-\n if flag\n then do printCurrentTime \"read from files...\"\n decodeFile histFilePath\n else do printCurrentTime \"Start computing coefficients...\"\n initialise []\n devs <- M.mapM device deviceIDs\n ctxs <- M.mapM (\\dev -> CUDA.create dev []) devs\n ptxs <- M.mapM createTargetFromContext ctxs\n runMonteCarloFourierCoefficientsGPU\n deviceIDs\n numThread\n 1000000\n 500000\n thetaSigma\n scaleSigma\n 0\n s\n tau\n deltaT\n phiFreqs\n rhoFreqs\n thetaFreqs\n scaleFreqs\n maxScale\n histFilePath\n -- else sampleCartesian\n -- histFilePath\n -- folderPath\n -- ptxs\n -- numPoints\n -- periodEnvelope\n -- delta\n -- numOrientation\n -- initScale\n -- thetaSigma\n -- tau\n -- threshold\n -- s\n -- phiFreq\n -- rhoFreq\n -- thetaFreq\n -- scaleFreq\n printCurrentTime \"Done\"\n printCurrentTime \"Start Convloution..\"\n plan <-\n makePlanDiscrete\n folderPath\n emptyPlan\n numPointsRecon\n numPointsRecon\n numR2Freq\n (2 * thetaFreq + 1)\n (2 * scaleFreq + 1)\n (2 * phiFreq + 1)\n (2 * rhoFreq + 1)\n let coefficients = getNormalizedHistogramArr $ hist\n -- coefficients <- hollowCoefficients plan radius periodEnvelope coefficients'\n -- coefficients = getNormalizedHistogramArr $ hist\n -- normalizeFreqArr' std phiFreqs rhoFreqs .\n harmonicsArray <-\n createHarmonics\n numR2Freq\n phiFreq\n rhoFreq\n thetaFreq\n scaleFreq\n (-s)\n periodR2\n periodEnvelope\n coefficients\n -- harmonicsArray1 =\n -- createHarmonics\n -- numR2Freq\n -- phiFreq\n -- rhoFreq\n -- thetaFreq\n -- scaleFreq\n -- (-1.25)\n -- periodR2\n -- periodEnvelope\n -- coefficients\n let !initialSourceDistribution =\n computeInitialDistributionFourierPinwheel\n numR2Freq\n periodR2\n periodEnvelope\n phiFreq\n rhoFreq\n thetaFreq\n scaleFreq\n initSource\n !initialSinkDistribution =\n computeInitialDistributionFourierPinwheel\n numR2Freq\n periodR2\n periodEnvelope\n phiFreq\n rhoFreq\n thetaFreq\n scaleFreq\n initSink\n -- harmonicsArray' =\n -- centerHollow numR2Freq $\n -- pinwheelFourierCoefficientsAnatical\n -- numR2Freq\n -- phiFreq\n -- rhoFreq\n -- thetaFreq\n -- scaleFreq\n -- (-s)\n -- periodR2\n -- periodEnvelope\n -- harmonicsArray1' =\n -- -- L.map (centerHollowVector numR2Freq) $\n -- pinwheelFourierCoefficientsAnaticalList1\n -- numR2Freq\n -- phiFreq\n -- rhoFreq\n -- thetaFreq\n -- scaleFreq\n -- (-s)\n -- periodR2\n -- periodEnvelope\n -- harmonicsArray2' =\n -- -- L.map (centerHollowVector numR2Freq) $\n -- pinwheelFourierCoefficientsAnaticalList2\n -- numR2Freq\n -- phiFreq\n -- rhoFreq\n -- thetaFreq\n -- scaleFreq\n -- (-s)\n -- periodR2\n -- periodEnvelope\n -- initialSourceDistribution =\n -- computeInitialDistributionFull'\n -- numR2Freq\n -- periodR2\n -- phiFreq\n -- rhoFreq\n -- initSource\n -- initialSourceDistribution =\n -- computeInitialDistributionPowerMethodPinwheelBasis'\n -- numR2Freq\n -- (-s)\n -- periodR2\n -- phiFreq\n -- rhoFreq\n -- initSource\n -- initialSinkDistribution =\n -- computeInitialDistributionFull'\n -- numR2Freq\n -- periodR2\n -- phiFreq\n -- rhoFreq\n -- initSink\n -- source <-\n -- convoluvePinhweelBasisTest'\n -- coefficients\n -- harmonicsArray1'\n -- harmonicsArray2'\n -- initialSourceDistribution\n -- sink <-\n -- timeReversal' <$>\n -- convoluvePinhweelBasisTest'\n -- coefficients\n -- harmonicsArray1'\n -- harmonicsArray2'\n -- initialSinkDistribution\n -- let source =\n -- convoluvePinhweelBasis'\n -- coefficients\n -- harmonicsArray'\n -- initialSourceDistribution\n -- sink =\n -- timeReversal' $\n -- convoluvePinhweelBasis'\n -- coefficients\n -- harmonicsArray'\n -- initialSinkDistribution\n -- sourceMat =\n -- A.transpose . A.use . fromDFTArray . getDFTArrayVector $ source\n -- sinkMat = A.transpose . A.use . fromDFTArray . getDFTArrayVector $ sink-\n source <- convolve harmonicsArray initialSourceDistribution\n -- source1 <- convolve harmonicsArray1 initialSourceDistribution\n let numLogPolarFreq = ((2 * scaleFreq + 1) * (2 * thetaFreq + 1))\n -- sourceMat = A.transpose . toMatrixAcc $ source\n -- sourceMat1 = A.transpose . toMatrixAcc $ source1\n -- sourceMat2 =\n -- A.transpose . toMatrixAcc $\n -- parZipWithFPArray (VS.zipWith (-)) source source1\n -- sourceR2 <-\n -- computeFourierSeriesR2StreamAcc\n -- ptxs\n -- numR2Freq\n -- numPointsRecon\n -- numLogPolarFreq\n -- periodR2\n -- deltaRecon\n -- numBatchR2\n -- sourceMat\n -- plotImageRepa (folderPath \"SourcePower.png\") .\n -- ImageRepa 8 .\n -- fromUnboxed (Z :. (1 :: Int) :. numPointsRecon :. numPointsRecon) .\n -- VU.map sqrt . toUnboxed . sumS . R.map (\\x -> (magnitude x) ** 2) . rotate3D $\n -- sourceR2\n sourceR2 <- plotFPArray plan (folderPath \"SourcePower.png\") source\n -- source1R2 <-\n -- computeFourierSeriesR2StreamAcc\n -- ptxs\n -- numR2Freq\n -- numPointsRecon\n -- numLogPolarFreq\n -- periodR2\n -- deltaRecon\n -- numBatchR2\n -- sourceMat1\n -- plotImageRepa (folderPath \"SourcePower1.png\") .\n -- ImageRepa 8 .\n -- fromUnboxed (Z :. (1 :: Int) :. numPointsRecon :. numPointsRecon) .\n -- VU.map sqrt . toUnboxed . sumS . R.map (\\x -> (magnitude x) ** 2) . rotate3D $\n -- source1R2\n -- source2R2 <-\n -- computeFourierSeriesR2StreamAcc\n -- ptxs\n -- numR2Freq\n -- numPointsRecon\n -- numLogPolarFreq\n -- periodR2\n -- deltaRecon\n -- numBatchR2\n -- sourceMat2\n -- plotImageRepa (folderPath \"SourcePower2.png\") .\n -- ImageRepa 8 .\n -- fromUnboxed (Z :. (1 :: Int) :. numPointsRecon :. numPointsRecon) .\n -- VU.map sqrt . toUnboxed . sumS . R.map (\\x -> (magnitude x) ** 2) . rotate3D $\n -- source2R2\n sink <- convolve harmonicsArray initialSinkDistribution\n let sinkMat = A.transpose . toMatrixAcc $ sink\n -- completion <- completionField' plan source (timeReversal' sink)\n -- let completionMat = createCuMat . getDFTArrayVector $ completion\n -- print completionMat\n sinkR2 <- plotFPArray plan (folderPath \"SinkPower.png\") sink\n -- sinkR2 <-\n -- computeFourierSeriesR2StreamAcc\n -- ptxs\n -- numR2Freq\n -- numPointsRecon\n -- numLogPolarFreq\n -- periodR2\n -- deltaRecon\n -- numBatchR2\n -- sinkMat\n -- plotImageRepa (folderPath \"SinkPower.png\") .\n -- ImageRepa 8 .\n -- fromUnboxed (Z :. (1 :: Int) :. numPointsRecon :. numPointsRecon) .\n -- VU.map sqrt . toUnboxed . sumS . R.map (\\x -> (magnitude x) ** 2) . rotate3D $\n -- sinkR2\n -- completionR2 <-\n -- computeFourierSeriesR2Stream\n -- deviceIDs\n -- ptxs\n -- numR2Freq\n -- numPointsRecon\n -- periodR2\n -- deltaRecon\n -- numBatchR2\n -- [transposeCuMat completionMat]\n printCurrentTime \"Start ploting..\"\n -- plotDFTArrayPower\n -- (folderPath \"CoefficientsPower.png\")\n -- numR2Freq\n -- numR2Freq\n -- source\n -- plotImageRepaComplex (folderPath \"Coefficients.png\") .\n -- ImageRepa 8 .\n -- fromUnboxed (Z :. (1 :: Int) :. numR2Freq :. numR2Freq) .\n -- VU.convert . L.foldl1' (VS.zipWith (+)) . getDFTArrayVector $\n -- source\n -- plotImageRepaComplex (folderPath \"Source.png\") .\n -- ImageRepa 8 .\n -- fromUnboxed (Z :. (1 :: Int) :. numPointsRecon :. numPointsRecon) .\n -- toUnboxed . sumS . rotate3D $\n -- sourceR2\n completionR2 <-\n completionFieldRepa\n plan\n (R.reshape\n (Z :. (L.length scaleFreqs) :. (L.length thetaFreqs) :. numPointsRecon :.\n numPointsRecon) $\n sourceR2)\n (timeReversalRepa thetaFreqs .\n R.reshape\n (Z :. (L.length scaleFreqs) :. (L.length thetaFreqs) :. numPointsRecon :.\n numPointsRecon) $\n sinkR2)\n plotImageRepa (folderPath \"CompletionPower.png\") .\n ImageRepa 8 .\n fromUnboxed (Z :. (1 :: Int) :. numPointsRecon :. numPointsRecon) .\n VU.map sqrt .\n toUnboxed . sumS . sumS . R.map (\\x -> (magnitude x) ** 2) . rotate4D2 $\n completionR2\n printCurrentTime \"Done\"\n -- sparse\n let harmonicsArraySparse =\n computeHarmonicsArraySparse\n numPointsRecon\n deltaRecon\n numPointsRecon\n deltaRecon\n phiFreqs\n rhoFreqs\n thetaFreqs\n scaleFreqs\n -- (2 * pi)\n (log (periodR2 / 4))\n 64\n s\n init =\n computeInitialDistribution'\n numPointsRecon\n numPointsRecon\n phiFreqs\n rhoFreqs\n 0\n initSource\n harmonicsArrayDFT <-\n fmap (listArray (bounds harmonicsArraySparse)) .\n dftExecuteBatchP\n plan\n (DFTPlanID DFT1DG [numPointsRecon, numPointsRecon] [0, 1]) .\n L.map (VS.convert . toUnboxed . computeUnboxedS . makeFilter2D) . IA.elems $\n harmonicsArraySparse\n sourceSparse <- convolve' Source plan coefficients harmonicsArrayDFT init\n plotDFTArrayPower\n (folderPath \"SourcePower_Sparse.png\")\n numPointsRecon\n numPointsRecon\n sourceSparse\n", "meta": {"hexsha": "8dc066a74ce7fc037a91ee0ed6d4dc0e526e8b06", "size": 13730, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "test/STCPinwheel/STCPinwheel.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/STCPinwheel/STCPinwheel.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "test/STCPinwheel/STCPinwheel.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 32.9256594724, "max_line_length": 388, "alphanum_fraction": 0.581427531, "num_tokens": 3864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3977211044755589}} {"text": "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}\n{-# LANGUAGE FlexibleInstances, ConstraintKinds, ExistentialQuantification, GADTs, RankNTypes, MultiParamTypeClasses, RankNTypes, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}\n\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n-- | \n-- | Module : First attempt at approximate counting\n-- | Creator: Xiao Ling\n-- | Created: 12/08/2015\n-- | TODO : test standard deviation of alpha, beta, and final version\n-- |\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n\nmodule Morris (\n\n morris\n , morris'\n\n , morris1\n , morris1'\n\n ) where\n\nimport Control.Monad.Random\nimport Control.Monad.Random.Class\n\nimport Data.Conduit\nimport Data.List.Split\nimport qualified Data.Conduit.List as Cl\n\n\nimport Core\nimport Statistics\n\n\n{-----------------------------------------------------------------------------\n I. Morris Algorithm list of counter\n------------------------------------------------------------------------------}\n\n---- * Count the number of items in `as` to within `eps` of actual\n---- * with confidence `delta`\nmorris' :: EpsDelta -> Batch a IO Counter\nmorris' ed = morris ed `using` evalRandIO\n\nmorris :: MonadRandom m => EpsDelta -> Streaming a m Counter\nmorris (ED e d) = medianOfMeans $ go cs\n where cs = replicate (t*m) 0\n t = round $ 1/(e^2*d) :: Int \n m = round . log $ 1/d \n go cs = (\\c -> 2^(round c) - 1) `ffmap` Cl.foldM (\\cs _ -> traverse incr cs) cs\n ffmap = fmap . fmap\n medianOfMeans = fmap median' . (fmap . fmap) mean' . fmap (chunksOf t) \n\n\n{-----------------------------------------------------------------------------\n II. Morris Algorithm list of list of counter\n------------------------------------------------------------------------------}\n\n---- * Count the number of items in `as` to within `eps` of actual\n---- * with confidence `delta`\nmorris1' :: EpsDelta -> Batch a IO Counter\nmorris1' ed = morris1 ed `using` evalRandIO\n\n-- * Run on stream inputs `as` for t independent trials for `t = 1/eps^2 * d`, \n-- * and `m` times in parallel, for `m = log(1/d)` and take the median\nmorris1 :: MonadRandom m => EpsDelta -> Streaming a m Counter\nmorris1 (ED e d) = medianOfMeans $ go ccs\n where\n medianOfMeans = fmap median' . (fmap . fmap) mean' \n ccs = replicate m $ replicate t 0\n t = round $ 1/(e^2*d) \n m = round . log $ 1/d \n go ccs = (\\x -> 2^(round x) - 1) `fffmap` Cl.foldM (\\xs _ -> incrs' xs) ccs\n fffmap = fmap . fmap . fmap\n\n-- * given a list of list of counters toss a coin for each counter and incr\n-- * this can be flattened\nincrs' :: MonadRandom m => [[Counter]] -> m [[Counter]]\nincrs' = sequence . fmap (sequence . fmap incr)\n\n\n{-----------------------------------------------------------------------------\n III. Utils\n------------------------------------------------------------------------------}\n\n\n-- * Increment a counter `x` with probability 1/2^x\nincr :: MonadRandom m => Counter -> m Counter\nincr x = do\n h <- toss . coin $ 0.5^(round x)\n return $ if isHead h then (seq () succ x) else seq () x\n\n\nmean', median' :: (Floating a, Ord a, RealFrac a) => [a] -> Float\nmean' = fromIntegral . round . mean\nmedian' = fromIntegral . round . median\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ca35fe6fae4a769ad9dc394279becedafceae1f0", "size": 3758, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Morris.hs", "max_stars_repo_name": "lingxiao/CIS700", "max_stars_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Morris.hs", "max_issues_repo_name": "lingxiao/CIS700", "max_issues_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Morris.hs", "max_forks_repo_name": "lingxiao/CIS700", "max_forks_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7962962963, "max_line_length": 194, "alphanum_fraction": 0.4739222991, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3976584615158062}} {"text": "{-# LANGUAGE DataKinds, NamedFieldPuns, GADTs, KindSignatures, TypeFamilies, TypeOperators, TypeApplications, ScopedTypeVariables, MultiParamTypeClasses, OverloadedLabels, InstanceSigs, FlexibleContexts, AllowAmbiguousTypes, FlexibleInstances, RankNTypes, UndecidableInstances, ConstraintKinds, OverlappingInstances, TypeFamilyDependencies #-}\n\nmodule TraceTypes where\n\nimport Data.Row.Records hiding ( Disjoint\n , sequence\n , map\n , zip\n )\nimport Data.Row.Internal ( Subset\n , type (.\\\\)\n , type (.\\/)\n )\nimport Data.Default\nimport Numeric.Log as Log\nimport qualified Data.Vector.Sized as V\nimport Data.Vector.Sized ( Vector )\nimport GHC.OverloadedLabels\nimport Data.Finite\nimport GHC.TypeLits\nimport Control.Monad\nimport Control.Monad.Bayes.Class as Bayes\nimport Statistics.Distribution (logDensity, complCumulative)\nimport Statistics.Distribution.Gamma\nimport Statistics.Distribution.Beta\nimport Statistics.Distribution.Normal\n\n-- The \"Constraint\" type is intended only\n-- for internal use, and is not user-facing.\n-- A Constraint of a certain record type is \n-- a record where each field type `a` has been\n-- replaced with the type `Maybe a`; a value of\n-- `Nothing` indicates an unconstrained value,\n-- whereas `Just x` indicates an observed (i.e. \n-- constrained) value.\ntype Constraint r = Rec (Map Maybe r)\n\n-- (ConcatTo l r s) means that l, r, and s are all\n-- valid record types, and that l .+ r = r .+ l = s.\ntype ConcatTo l r s\n = ( WellBehaved l\n , WellBehaved r\n , WellBehaved s\n , Subset l s\n , Subset r s\n , (l .+ r) ≈ s\n , (r .+ l) ≈ s\n , s .\\\\ l ≈ r\n , s .\\\\ r ≈ l\n )\n\n-- Are the label sets of l and r disjoint?\ntype Disjoint l r\n = ( ConcatTo l r (l .+ r)\n , ConcatTo (Map Maybe l) (Map Maybe r) (Map Maybe (l .+ r))\n , Forall (Map Maybe l) Default\n , Forall (Map Maybe r) Default\n )\n\n-- Three main types: probability distributions (D), unnormalized density-carrying measures (U), \n-- and probabilistic programs (P).\ndata U m a = U\n { usampler :: m a\n , udensity :: a -> Log Double\n }\ndata D m a = D\n { dsampler :: m a\n , ddensity :: a -> Log Double\n }\ndata P m t a = P\n { traced :: D m (Rec t)\n , retval :: Rec t -> a\n , constrain :: Constraint t -> U m (Rec t)\n }\n\nclass DensityCarrying f m where\n sampler :: f m a -> m a\n density :: f m a -> a -> Log Double\n\n\ninstance DensityCarrying U m where\n sampler = usampler\n density = udensity\n\ninstance DensityCarrying D m where\n sampler = dsampler\n density = ddensity\n\ndist sampler density = D { dsampler = sampler, ddensity = density }\nudist sampler density = U { usampler = sampler, udensity = density }\n\n-- DEFAULT INFERENCE\nobserve\n :: forall m a t s\n . (Disjoint t s, Monad m)\n => P m (t .+ s) a\n -> Rec t\n -> U m (Rec s)\nobserve p obs =\n let\n -- Turn the observation record `obs` of type `t` into a Constraint of \n -- type `t .+ s`, by filling in the `s` piece of the record with `Nothing`.\n constraints :: Constraint (t .+ s)\n constraints = map' Just obs .+ (default' @Default def :: Constraint s)\n\n -- Obtain a constrained distribution over traces.\n u :: U m (Rec (t .+ s))\n u = constrain p constraints\n in \n -- Modify the distribution u so that it is over only the unobserved values\n -- (Rec s), not full-but-constrained traces (Rec (t .+ s)).\n udist (fmap restrict $ sampler u) (density u . ((.+) obs))\n\ntraceSampler = sampler . traced\ntraceDensity = density . traced\n\n-- UNIT INTERVAL TYPE\n\nnewtype Unit = Sigmoid {logit :: Double}\n\nfromUnit :: Unit -> Double\nfromUnit (Sigmoid x) = 1.0 / (1.0 + exp (-x))\n\nmkUnit :: Double -> Unit\nmkUnit u = if 0 < u && u < 1\n then Sigmoid (log (u / (1.0 - u)))\n else error \"Number must be between 0 and 1.\"\n\ninstance Show Unit where\n show x = show (fromUnit x)\n\n------------------------------\n-- STPL LANGUAGE CONSTRUCTS --\n------------------------------\n\n-- RETURN\n\npReturn :: Monad m => a -> P m Empty a\npReturn x =\n let sampler = return Data.Row.Records.empty\n density _ = 1\n traced = dist sampler density\n constrain _ = udist sampler density\n retval _ = x\n in P { traced, retval, constrain }\n\n\n-- BIND\n\npBind :: (Disjoint t s, Monad m) => P m t a -> (a -> P m s b) -> P m (t .+ s) b\npBind f g =\n let\n bindSampler = do\n fTrace <- sampler $ traced f\n let x = retval f fTrace\n gTrace <- sampler $ traced (g x)\n return (fTrace .+ gTrace)\n\n bindDensity tr =\n let fDensity = density (traced f) (restrict tr)\n x = retval f (restrict tr)\n gDensity = density (traced $ g x) (restrict tr)\n in fDensity * gDensity\n\n bindTraced = dist bindSampler bindDensity\n\n bindRet tr = let x = retval f (restrict tr) in retval (g x) (restrict tr)\n\n constrainedSampler c = do\n fTrace <- sampler $ constrain f (restrict c)\n let x = retval f fTrace\n gTrace <- sampler $ constrain (g x) (restrict c)\n return (fTrace .+ gTrace)\n\n constrainedDensity c tr =\n let fDensity = density (constrain f (restrict c)) (restrict tr)\n x = retval f (restrict tr)\n gDensity = density (constrain (g x) (restrict c)) (restrict tr)\n in fDensity * gDensity\n\n bindConstrain c = udist (constrainedSampler c) (constrainedDensity c)\n in\n P { traced = bindTraced, retval = bindRet, constrain = bindConstrain }\n\n\n-- SAMPLE\n\nsingleLabelConstrain\n :: (KnownSymbol l, MonadInfer m)\n => Label l\n -> D m (Rec (l .== a))\n -> Constraint (l .== a)\n -> U m (Rec (l .== a))\nsingleLabelConstrain lbl traced c = case c .! lbl of\n Just x ->\n let t = lbl .== x\n constrainedSampler = do\n score $ density traced t\n return t\n constrainedDensity _ = density traced t\n in udist constrainedSampler constrainedDensity\n\n Nothing -> udist (sampler traced) (density traced)\n\n\nsample :: (KnownSymbol l, MonadInfer m) => Label l -> D m a -> P m (l .== a) a\nsample lbl d =\n let sampleTraced = dist\n (do\n x <- sampler d\n return (lbl .== x)\n )\n (\\t -> density d (t .! lbl))\n\n sampleRet t = t .! lbl\n\n sampleConstrain = singleLabelConstrain lbl sampleTraced\n in P { traced = sampleTraced\n , retval = sampleRet\n , constrain = sampleConstrain\n }\n\n\n-- WITH PROBABILITY\n\nwithProbability\n :: (KnownSymbol l, MonadInfer m)\n => Label l\n -> Unit\n -> P m t a\n -> P m s a\n -> P m (l .== Either (Rec t) (Rec s)) a\nwithProbability lbl logit f g =\n let p = fromUnit logit\n\n wpSampler = do\n r <- random\n if r < p\n then do\n t <- sampler $ traced f\n return (lbl .== Left t)\n else do\n t <- sampler $ traced g\n return (lbl .== Right t)\n\n wpDensity tr = case tr .! lbl of\n Left t -> Exp (log p) * density (traced f) t\n Right t -> Exp (log (1.0 - p)) * density (traced g) t\n\n wpTraced = dist wpSampler wpDensity\n\n wpRet t = case t .! lbl of\n Left t -> retval f t\n Right t -> retval g t\n\n wpConstrain = singleLabelConstrain lbl wpTraced\n in P { traced = wpTraced, retval = wpRet, constrain = wpConstrain }\n\n-- FOR EACH\n\nforEach\n :: (KnownSymbol l, KnownNat n, MonadInfer m)\n => Label l\n -> Vector n a\n -> (a -> P m t b)\n -> P m (l .== Vector n (Rec t)) (Vector n b)\nforEach lbl xs body =\n let\n forEachSampler = do\n traces <- V.mapM (sampler . traced . body) xs\n return (lbl .== traces)\n\n forEachDensity t = V.product\n (V.map (\\(x, tr) -> density (traced $ body x) tr) (V.zip xs (t .! lbl)))\n\n forEachTraced = dist forEachSampler forEachDensity\n\n forEachRet t = V.map (\\(x, tr) -> retval (body x) tr) (V.zip xs (t .! lbl))\n\n forEachConstrain = singleLabelConstrain lbl forEachTraced\n in\n P { traced = forEachTraced\n , retval = forEachRet\n , constrain = forEachConstrain\n }\n\n\n-- FOR ... IN RANDOM RANGE ...\n\nforRandomRange\n :: (KnownSymbol l, MonadInfer m)\n => Label l\n -> D m Int\n -> (Int -> P m t a)\n -> P m (l .== [Rec t]) [a]\nforRandomRange lbl d body =\n let\n -- Sample a trace of the for loop.\n forSampler = do\n n <- sampler d\n traces <- sequence $ map (sampler . traced . body) [0 .. n - 1]\n return (lbl .== traces)\n\n -- Compute the density of a trace of the for loop.\n forDensity t =\n density d (length $ t .! lbl)\n * product\n (map (\\(tr, i) -> density (traced $ body i) tr)\n (zip (t .! lbl) [0 ..])\n )\n\n -- The for loop's density-carrying distribution over traces\n forTraced = dist forSampler forDensity\n\n -- Compute the return value of the for loop, given a trace of an execution.\n -- The return value is just a list of the return values from each iteration.\n forRet t = map (\\(tr, i) -> retval (body i) tr) (zip (t .! lbl) [0 ..])\n\n -- Constrain the random choices made inside the for loop.\n forConstrain = singleLabelConstrain lbl forTraced\n in\n P { traced = forTraced, retval = forRet, constrain = forConstrain }\n\n{- WHILE:\n\n A stochastic while loop.\n Takes as input:\n - lbl : The label at which to trace the while loop's random choices.\n - init : The initial state of the while loop.\n - pi : A function computing a probability of continuing, based on the current state.\n - pi_max : An upper bound beyond which the probability of continuing is truncated.\n - body : The body of the while loop, which simulates a new state based on the current state.\n\n The resulting probabilistic program has type P m (l .== [Rec t]) a:\n - The trace contains, at the specified label, a list of subtraces, one for each iteration.\n - The return value is the final state at the finish of the while loop.\n\n -}\n\nwhile\n :: (KnownSymbol l, MonadInfer m)\n => Label l\n -> a\n -> (a -> Unit)\n -> Unit\n -> (a -> P m t a)\n -> P m (l .== [Rec t]) a\nwhile lbl init pi pi_max body =\n let \n -- Sample a trace of the while loop.\n whileSampler state = do\n shouldContinue <- bernoulli $ min (fromUnit (pi state)) (fromUnit pi_max)\n if shouldContinue\n then do\n nextTrace <- sampler (traced $ body state)\n let nextState = retval (body state) nextTrace\n restOfTraces <- whileSampler nextState\n return (lbl .== (nextTrace : (restOfTraces .! lbl)))\n else return (lbl .== [])\n\n -- Given traces from each iteration, and an initial state,\n -- compute the final state.\n retvalFromTraces init ts = case ts of\n [] -> init\n t : ts -> retvalFromTraces (retval (body init) t) ts\n\n -- Given a trace of the entire while loop, compute the final\n -- state.\n whileRet t = retvalFromTraces init (t .! lbl)\n\n -- Given an initial state and traces from each iteration,\n -- compute the density.\n densityFromTraces init ts = case ts of\n [] -> Exp (log (1.0 - (fromUnit (pi init))))\n t : ts ->\n Exp (log (fromUnit (pi init)))\n * (density (traced $ body init) t)\n * densityFromTraces (retval (body init) t) ts\n\n -- Given a trace of the entire while loop, compute the density.\n whileDensity t = densityFromTraces init (t .! lbl)\n\n -- The while loop's density-carrying distribution over traces.\n whileTraced = dist (whileSampler init) whileDensity\n\n -- Constrain the choices made inside the loop.\n whileConstrain = singleLabelConstrain lbl whileTraced\n\n in P { traced = whileTraced, retval = whileRet, constrain = whileConstrain }\n\n-------------------\n-- DISTRIBUTIONS --\n-------------------\n\nnrm :: MonadInfer m => Double -> Log Double -> D m Double\nnrm mu (Exp sigln) = dist (normal mu (exp sigln)) (normalPdf mu (exp sigln))\n\nbrn :: MonadSample m => Unit -> D m Bool\nbrn logit =\n let p = fromUnit logit\n in dist (bernoulli p) (\\b -> Exp . log $ if b then p else (1.0 - p))\n\ngmma :: MonadSample m => Log Double -> Log Double -> D m (Log Double)\ngmma shape scale =\n let toDouble (Exp l) = exp l\n toLogDouble d = Exp (log d)\n in\n dist (fmap toLogDouble (gamma (toDouble shape) (toDouble scale))) \n (Exp . (logDensity $ Statistics.Distribution.Gamma.gammaDistr \n (toDouble shape) (toDouble scale))\n . toDouble)\n\ngeom :: MonadSample m => Unit -> D m Int\ngeom p' = \n let p = fromUnit p'\n in dist (geometric p)\n (\\n -> Exp (fromIntegral n * (log p) + (log (1.0 - p))))\n\npois :: MonadSample m => Int -> D m Int\npois = undefined\n\nbta :: MonadSample m => Log Double -> Log Double -> D m Unit\nbta (Exp lna) (Exp lnb) = \n let\n a = exp lna\n b = exp lnb\n in\n dist (fmap mkUnit (beta a b))\n (Exp . (logDensity $ Statistics.Distribution.Beta.betaDistr a b)\n . fromUnit)\n\nunif :: MonadSample m => D m Unit\nunif = dist (fmap mkUnit Bayes.random) (\\x -> 1.0 :: Log Double)\n\ncat :: (KnownNat n, MonadSample m) => Vector n Unit -> D m (Finite n)\ncat probs = undefined\n\nlognormal :: forall m. MonadInfer m => Log Double -> Log Double -> D m (Log Double)\nlognormal (Exp logmu) sigma =\n dist (fmap Exp $ sampler $ nrm logmu sigma)\n (\\(Exp logx) -> density (nrm logmu sigma :: D m Double) logx / (Exp logx))\n\n\ntruncnrm :: MonadInfer m => Log Double -> Log Double -> D m (Log Double)\ntruncnrm (Exp logmu) (Exp logsigma) =\n let mu = exp logmu\n sigma = exp logsigma\n unbounded = nrm mu (Exp logsigma)\n \n truncNormSampler = do\n x <- sampler unbounded\n if x < 0 then truncNormSampler else return (Exp $ log x)\n \n truncNormPdf (Exp logy) = \n let y = exp logy\n z = complCumulative (normalDistr mu sigma) 0\n in (density unbounded y / (Exp (log z)))\n in dist truncNormSampler truncNormPdf\n\n\n\n----------------------------\n-- PROGRAMMABLE INFERENCE --\n----------------------------\n\n-- IMPORTANCE SAMPLING\n\nimportance\n :: (Disjoint t s, MonadInfer m)\n => P m (t .+ s) a\n -> Rec t\n -> P m s b\n -> m (Rec s)\nimportance p t q =\n let target = observe p t\n in do\n tr <- sampler $ traced q\n score ((density target tr) / (density (traced q) tr))\n return tr\n\n-- SMC\n\nunroll \n :: (MonadInfer m, Disjoint t s) \n => P m i a \n -> (a -> P m (t .+ s) a)\n -> [Rec t]\n -> m (Rec i, [Rec s])\nunroll init next steps = do\n tInit <- sampler $ traced init\n let processStep soFar t = do {\n (s, results) <- soFar;\n tNext <- sampler $ observe (next s) t;\n return (retval (next s) (tNext .+ t), tNext : results)\n }\n (s, l) <- foldl processStep (return (retval init tInit, [])) steps\n return (tInit, reverse l)\n\nparticleFilter\n :: (MonadInfer m, Disjoint t s, \n Disjoint Empty i, (Empty .+ i) ≈ i)\n => P m i a\n -> P m i b\n -> (a -> P m (t .+ s) a)\n -> [(Rec t, a -> P m s c)]\n -> m (Rec i, [Rec s])\nparticleFilter init qInit next steps = do\n tInit <- importance init Data.Row.Records.empty qInit\n let processStep soFar (t, q) = do {\n (s, results) <- soFar;\n tNext <- importance (next s) t (q s);\n return (retval (next s) (tNext .+ t), tNext : results)\n }\n (s, l) <- foldl processStep (return (retval init tInit, [])) steps\n return (tInit, reverse l)\n\n\n-- MCMC\n\ntype K m t (s :: Row *) = U m (Rec t) -> Rec t -> m (Rec t)\n\nmh\n :: forall s t m a\n . (Disjoint t s, MonadInfer m)\n => (Rec (t .+ s) -> P m t a)\n -> K m (t .+ s) t\nmh q p old =\n let proposal = do\n new <- sampler (traced $ q old)\n return $ new .+ (restrict old :: Rec s)\n rho (x, y) =\n ((density p y) * (density (traced $ q y) (restrict x)))\n / ((density p x) * (density (traced $ q x) (restrict y)))\n in do\n proposed <- proposal\n r <- Bayes.random\n if Exp (log r) < (min 1 (rho (old, proposed)))\n then return proposed\n else return old\n\nseqK :: Monad m => K m t s -> K m t r -> K m t (s .\\/ r)\nseqK k1 k2 p old = do\n t' <- k1 p old\n k2 p t'\n\nmixK :: MonadSample m => Double -> K m t s -> K m t r -> K m t (s .\\/ r)\nmixK p k1 k2 model old = do\n r <- Bayes.random\n if r < p then k1 model old else k2 model old\n\nrepeatK :: Monad m => Int -> K m t s -> K m t s\nrepeatK n k p old = if n == 0\n then return old\n else do\n t <- k p old\n repeatK (n - 1) k p t\n\nifK\n :: (Disjoint t s, Monad m)\n => (Rec t -> Bool)\n -> K m (t .+ s) s\n -> K m (t .+ s) s\nifK b k p old = if (b (restrict old)) then k p old else return old\n\n-- VARIATIONAL (STUBBED)\n\nsvi\n :: (Disjoint t s, Monad m)\n => P m (t .+ s) a\n -> Rec t\n -> (theta -> P m s b)\n -> theta\n -> m theta\nsvi p t q theta = undefined\n-- do tr <- traceSampler $ q theta\n-- let sco = density (observe p t) tr\n-- let gradient = grad (\\th -> traceDensity (q th) tr) theta\n-- return theta + stepSize * sco * gradient\n\ntrainAmortized\n :: (Disjoint t s, Monad m)\n => P m (t .+ s) a\n -> (theta -> Rec t -> P m s b)\n -> theta\n -> m theta\ntrainAmortized p q theta = undefined\n-- do tr <- traceSampler p\n-- let gradient = grad (\\th -> traceDensity (q th (restrict tr)) (restrict tr)) theta\n-- return theta + step * gradient\n\n\nifThenElse c t f = if c then t else f\n", "meta": {"hexsha": "1f793c748a89b1e1f745bf7160c81e95885f1eab", "size": 17599, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/TraceTypes.hs", "max_stars_repo_name": "probcomp/haskell-trace-types", "max_stars_repo_head_hexsha": "d7b209a61f31f6d77d3e285716abe1d96244e1ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-04T23:09:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T18:03:56.000Z", "max_issues_repo_path": "src/TraceTypes.hs", "max_issues_repo_name": "probcomp/haskell-trace-types", "max_issues_repo_head_hexsha": "d7b209a61f31f6d77d3e285716abe1d96244e1ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-31T02:03:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-31T02:03:20.000Z", "max_forks_repo_path": "src/TraceTypes.hs", "max_forks_repo_name": "probcomp/haskell-trace-types", "max_forks_repo_head_hexsha": "d7b209a61f31f6d77d3e285716abe1d96244e1ae", "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.6779089376, "max_line_length": 343, "alphanum_fraction": 0.5795215637, "num_tokens": 5103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3969096138787487}} {"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE OverloadedLabels #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-|\nModule : Grenade.Layers.Add\nDescription : Layer to add some constant, with shape broadcasting\nMaintainer : Theo Charalambous\nLicense : BSD2\nStability : experimental\n-}\n\nmodule Grenade.Layers.Add \n (\n -- * Layer instances\n Add (..)\n\n -- * Helper functions\n , initAdd\n ) where\n\nimport Control.DeepSeq (NFData (..))\n\nimport Data.Kind (Type)\nimport Data.Maybe (fromJust)\nimport Data.Proxy\nimport Data.Serialize\nimport GHC.TypeLits\n\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Static (R)\nimport qualified Numeric.LinearAlgebra.Static as H\n\nimport Lens.Micro ((^.))\n\nimport Grenade.Core\nimport Grenade.Layers.Internal.Add\nimport Grenade.Onnx\n\ndata Add :: Nat -- The number of channels of the bias\n -> Nat -- The number of rows of the bias\n -> Nat -- The number of columns of the bias\n -> Type where\n Add :: ( KnownNat channels\n , KnownNat rows\n , KnownNat columns )\n => R (channels * rows * columns)\n -> Add channels rows columns\n\ninstance UpdateLayer (Add c h w) where\n type Gradient (Add c h w) = ()\n runUpdate _ x _ = x\n reduceGradient _ = ()\n\ninstance (KnownNat c, KnownNat h, KnownNat w ) => RandomLayer (Add c h w) where\n createRandomWith _ _ = pure initAdd\n\n-- | Initialize an Add layer with 0 bias\ninitAdd :: forall c h w. ( KnownNat c, KnownNat h, KnownNat w )\n => Add c h w\ninitAdd =\n let c' = fromIntegral $ natVal (Proxy :: Proxy c)\n h' = fromIntegral $ natVal (Proxy :: Proxy h)\n w' = fromIntegral $ natVal (Proxy :: Proxy w)\n zeroes = replicate (c' * h' * w') 0\n bias = H.fromList zeroes :: R (c * h * w)\n in Add bias\n\ninstance ( KnownNat c, KnownNat h, KnownNat w ) => Serialize (Add c h w) where\n put (Add bias) = putListOf put . LA.toList . H.extract $ bias\n get = do\n bias <- maybe (fail \"Vector of incorrect size\") return . H.create . LA.fromList =<< getListOf get\n return $ Add bias\n\n-- | A three dimensions image can have a vector added to it with size equal to the number of channels\n-- of the image, this corresponds to adding the nth element of the bias to every pixel of the nth \n-- channel of the input image\ninstance ( KnownNat i, KnownNat j, KnownNat k ) => Layer (Add k 1 1) ('D3 i j k) ('D3 i j k) where\n type Tape (Add k 1 1) ('D3 i j k) ('D3 i j k) = ()\n\n runForwards (Add b) (S3D m)\n = let c = fromIntegral $ natVal (Proxy :: Proxy k)\n h = fromIntegral $ natVal (Proxy :: Proxy i)\n w = fromIntegral $ natVal (Proxy :: Proxy j)\n m' = H.extract m\n b' = H.extract b\n r = addPerChannel c h w m' b'\n in ((), S3D . fromJust . H.create $ r)\n\n runBackwards = undefined\n\ninstance OnnxOperator (Add c h w) where\n onnxOpTypeNames _ = [\"Add\"]\n\ninstance (KnownNat c, KnownNat h, KnownNat w) => OnnxLoadable (Add c h w) where\n loadOnnxNode inits node = case node ^. #input of\n [bias, _] -> do\n loadedBias <- readInitializerTensorIntoVector inits bias\n return $ Add loadedBias\n _ -> onnxIncorrectNumberOfInputs\n\ninstance NFData (Add c h w) where\n rnf (Add bias) = rnf bias\n", "meta": {"hexsha": "31a4c378cf9b7eeca44b2dcb8ccd9166c901df73", "size": 3988, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Add.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Add.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Add.hs", "max_forks_repo_name": "th-char/grenade", "max_forks_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0854700855, "max_line_length": 101, "alphanum_fraction": 0.603560682, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3966460941306852}} {"text": "{-# LANGUAGE GADTs, FlexibleContexts, RankNTypes #-}\n\nmodule Numeric.Trainee.Neural (\n\tNet, net, netSeed,\n\t(⭃),\n\tndup, npar, ndupWith, nsum, nfold,\n\tpad, pad2,\n\tmaxPool, maxPool2,\n\tfc, conv, conv2,\n\tdconv, dconv2,\n\n\tsigma, relu, softplus,\n\tsummator, biaser, activator, convolver, convolver2,\n\tnormVar,\n\n\tmodule Numeric.Trainee.Types,\n\tmodule Numeric.Trainee.Learnee\n\t) where\n\nimport Prelude hiding ((.), id)\nimport Prelude.Unicode\n\nimport Control.Monad (replicateM, liftM2)\nimport Data.Random\nimport qualified Data.Vector as V\nimport Numeric.LinearAlgebra hiding (conv, conv2)\nimport System.Random (newStdGen, StdGen)\n\nimport Numeric.Trainee.Types\nimport Numeric.Trainee.Gradee\nimport Numeric.Trainee.Learnee\n\ntype Net a = Learnee (Vector a) (Vector a)\n\nnet ∷ RVar a → IO a\nnet n = netSeed <$> newStdGen <*> pure n\n\nnetSeed ∷ StdGen → RVar a → a\nnetSeed g n = fst $ sampleState n g\n\n(⭃) ∷ RVar (Learnee a b) → RVar (Learnee b c) → RVar (Learnee a c)\nn ⭃ l = liftM2 (⇉) n l\n\n-- | Split layers, just wraps @vdup@\nndup ∷ Num a ⇒ Int → RVar (Learnee a (V.Vector a))\nndup = return ∘ computee ∘ vdup\n\n-- | Process vector of layers\nnpar ∷ Int → RVar (Learnee a b) → RVar (Learnee (V.Vector a) (V.Vector b))\nnpar n = fmap (parallel ∘ V.fromList) ∘ replicateM n\n\n-- | Split layers, justs wraps @vdupWith@\nndupWith ∷ (a → a → a) → Int → RVar (Learnee a (V.Vector a))\nndupWith fn = return ∘ computee ∘ vdupWith fn\n\n-- | Join layers with sum\nnsum ∷ Num a ⇒ RVar (Learnee (V.Vector a) a)\nnsum = return (computee vsum)\n\n-- | Join layers with custom sum\nnfold ∷ (a → a → a) → RVar (Learnee (V.Vector a) a)\nnfold = return ∘ computee ∘ vfold\n\n-- | Padding\npad ∷ Numeric a ⇒ Int → RVar (Learnee (Vector a) (Vector a))\npad = return ∘ computee ∘ padVec\n\n-- | 2d padding\npad2 ∷ Numeric a ⇒ Int → Int → RVar (Learnee (Matrix a) (Matrix a))\npad2 w h = return ∘ computee $ padMat w h\n\n-- | Max pool layer\nmaxPool ∷ (RealFrac a, Numeric a) ⇒ Int → RVar (Learnee (Vector a) (Vector a))\nmaxPool = return ∘ computee ∘ maxPoolVec\n\n-- | 2d max pool layer\nmaxPool2 ∷ (RealFrac a, Numeric a) ⇒ Int → Int → RVar (Learnee (Matrix a) (Matrix a))\nmaxPool2 w h = return ∘ computee $ maxPoolMat w h\n\n-- | Fully connected layer\nfc ∷ (Distribution Normal a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Unary (Vector a) → Int → Int → RVar (Net a)\nfc f inputs outputs = do\n\ts ← summator inputs outputs\n\tb ← biaser outputs\n\treturn $ s ⇉ b ⇉ activator f\n\n-- | Convolution layer 1-d\nconv ∷ (Distribution Normal a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Unary (Vector a) → Int → RVar (Net a)\nconv f w = do\n\tc ← convolver w\n\tb ← do\n\t\tbs ← normVar\n\t\treturn $ learnee biasVec bs\n\treturn $ c ⇉ b ⇉ activator f\n\n-- | Convolution layer 2-d\nconv2 ∷ (Distribution Normal a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Unary (Matrix a) → (Int, Int) → RVar (Learnee (Matrix a) (Matrix a))\nconv2 f (w, h) = do\n\tc ← convolver2 w h\n\tb ← do\n\t\tbs ← normVar\n\t\treturn $ learnee biasMat bs\n\treturn $ c ⇉ b ⇉ activator f\n\n-- | Depth (with several input and output channels) convolution 1-d\ndconv ∷ (Distribution Normal a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Unary (Vector a) → Int → Int → Int → RVar (Learnee (V.Vector (Vector a)) (V.Vector (Vector a)))\ndconv f inputs outputs width =\n\tndupWith (V.zipWith (+)) outputs ⭃\n\tnpar outputs (npar inputs (conv f width) ⭃ nsum)\n\n-- | Depth (with several input and output channels) convolution 2-d\ndconv2 ∷ (Distribution Normal a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Unary (Matrix a) → Int → Int → (Int, Int) → RVar (Learnee (V.Vector (Matrix a)) (V.Vector (Matrix a)))\ndconv2 f inputs outputs (w, h) =\n\tndupWith (V.zipWith (+)) outputs ⭃\n\tnpar outputs (npar inputs (conv2 f (w, h)) ⭃ nsum)\n\nsigma ∷ Floating a ⇒ a → a\nsigma t = 1 / (1 + exp (negate t))\n\nrelu ∷ Fractional a ⇒ a → a\nrelu t = 0.5 * (1 + signum t) * t\n\nsoftplus ∷ Floating a ⇒ a → a\nsoftplus t = log (1 + exp t)\n\nsummator ∷ (Distribution Normal a, Fractional a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Int → Int → RVar (Net a)\nsummator inputs outputs = do\n\tws ← replicateM (inputs * outputs) normVar\n\treturn $ learnee matVec ((outputs >< inputs) ws)\n\nbiaser ∷ (Distribution Normal a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Int → RVar (Net a)\nbiaser sz = do\n\tbs ← replicateM sz normVar\n\treturn $ learnee odot (fromList bs)\n\nactivator ∷ Num a ⇒ Unary a → Learnee a a\nactivator f = computee (unary f)\n\nconvolver ∷ (Distribution Normal a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Int → RVar (Net a)\nconvolver w = do\n\tws ← replicateM w normVar\n\treturn $ learnee corrVec (fromList ws)\n\nconvolver2 ∷ (Distribution Normal a, Fractional a, Numeric a, Parametric (Vector a), Parametric a) ⇒ Int → Int → RVar (Learnee (Matrix a) (Matrix a))\nconvolver2 w h = do\n\tws ← replicateM (w * h) normVar\n\treturn $ learnee corrMat ((w >< h) ws)\n\nnormVar ∷ (Distribution Normal a, Fractional a) ⇒ RVar a\nnormVar = normal 0.0 0.25", "meta": {"hexsha": "a438d0ffe313b83df23414ee0456c3b67df56220", "size": 4929, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Trainee/Neural.hs", "max_stars_repo_name": "mvoidex/trainee", "max_stars_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-25T19:54:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T03:03:26.000Z", "max_issues_repo_path": "src/Numeric/Trainee/Neural.hs", "max_issues_repo_name": "mvoidex/trainee", "max_issues_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Trainee/Neural.hs", "max_forks_repo_name": "mvoidex/trainee", "max_forks_repo_head_hexsha": "60a935e53cabcf145736716829ee1be986b0ffc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.86, "max_line_length": 185, "alphanum_fraction": 0.6780279976, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.39504434653854487}} {"text": "{-# OPTIONS_GHC -Wall -Wno-partial-type-signatures #-}\n\n{-# LANGUAGE QuasiQuotes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE MultiWayIf #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE PartialTypeSignatures #-}\n\n-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.Sundials.CVode.ODE\n-- Copyright : Dominic Steinitz 2018,\n-- Novadiscovery 2018\n-- License : BSD\n-- Maintainer : Dominic Steinitz\n-- Stability : provisional\n--\n-- Solution of ordinary differential equation (ODE) initial value problems.\n--\n-- \n--\n-- A simple example:\n--\n-- <>\n--\n-- @\n-- import Numeric.Sundials.CVode.ODE\n-- import Numeric.LinearAlgebra\n--\n-- import Plots as P\n-- import qualified Diagrams.Prelude as D\n-- import Diagrams.Backend.Rasterific\n--\n-- brusselator :: Double -> [Double] -> [Double]\n-- brusselator _t x = [ a - (w + 1) * u + v * u * u\n-- , w * u - v * u * u\n-- , (b - w) / eps - w * u\n-- ]\n-- where\n-- a = 1.0\n-- b = 3.5\n-- eps = 5.0e-6\n-- u = x !! 0\n-- v = x !! 1\n-- w = x !! 2\n--\n-- lSaxis :: [[Double]] -> P.Axis B D.V2 Double\n-- lSaxis xs = P.r2Axis &~ do\n-- let ts = xs!!0\n-- us = xs!!1\n-- vs = xs!!2\n-- ws = xs!!3\n-- P.linePlot' $ zip ts us\n-- P.linePlot' $ zip ts vs\n-- P.linePlot' $ zip ts ws\n--\n-- main = do\n-- let res1 = odeSolve brusselator [1.2, 3.1, 3.0] (fromList [0.0, 0.1 .. 10.0])\n-- renderRasterific \"diagrams/brusselator.png\"\n-- (D.dims2D 500.0 500.0)\n-- (renderAxis $ lSaxis $ [0.0, 0.1 .. 10.0]:(toLists $ tr res1))\n-- @\n--\n-----------------------------------------------------------------------------\nmodule Numeric.Sundials.CVode.ODE ( odeSolve\n , odeSolveV\n , odeSolveVWith\n , odeSolveVWith'\n , odeSolveRootVWith'\n , odeSolveWithEvents\n , ODEMethod(..)\n , StepControl(..)\n , SolverResult(..)\n , SundialsSolution(..)\n , EventSpec(..)\n , EventInfo(..)\n , CrossingDirection(..)\n ) where\n\nimport qualified Language.C.Inline as C\nimport qualified Language.C.Inline.Unsafe as CU\n\nimport Data.Monoid ((<>))\nimport Data.Maybe (isJust, fromJust)\nimport Data.List (genericLength)\n\nimport Foreign.C.Types (CDouble, CInt, CLong)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (peek, poke)\n\nimport qualified Data.Vector.Storable as V\n\nimport Data.Coerce (coerce)\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport Numeric.LinearAlgebra.Devel (createVector)\n\nimport Numeric.LinearAlgebra.HMatrix (Vector, Matrix, toList, rows,\n cols, toLists, size, reshape,\n subVector, subMatrix, toColumns)\n\nimport Numeric.Sundials.Arkode (cV_ADAMS, cV_BDF,\n vectorToC, cV_SUCCESS,\n SunVector(..))\nimport qualified Numeric.Sundials.Arkode as T\nimport Numeric.Sundials.ODEOpts\n\n\nC.context (C.baseCtx <> C.vecCtx <> C.funCtx <> T.sunCtx)\n\nC.include \"\"\nC.include \"\"\nC.include \"\"\nC.include \"\" -- prototypes for CVODE fcts., consts.\nC.include \"\" -- serial N_Vector types, fcts., macros\nC.include \"\" -- access to dense SUNMatrix\nC.include \"\" -- access to dense SUNLinearSolver\nC.include \"\" -- access to CVDls interface\nC.include \"\" -- CVDiag\nC.include \"\" -- definition of type realtype\nC.include \"\"\nC.include \"../../../helpers.h\"\nC.include \"Numeric/Sundials/Arkode_hsc.h\"\n\n\n-- | The direction in which a function should cross the x axis\ndata CrossingDirection = Upwards | Downwards | AnyDirection\n deriving (Eq, Show)\n\n-- Contrary to the documentation, it appears that CVodeGetRootInfo\n-- may use both 1 and -1 to indicate a root, depending on the\n-- direction of the sign change. See near the end of cvRootfind.\nintToDirection :: Integral d => d -> Maybe CrossingDirection\nintToDirection d =\n case d of\n 1 -> Just Upwards\n -1 -> Just Downwards\n _ -> Nothing\n\n-- | Almost inverse of 'intToDirection'. Map 'Upwards' to 1, 'Downwards' to\n-- -1, and 'AnyDirection' to 0.\ndirectionToInt :: Integral d => CrossingDirection -> d\ndirectionToInt d =\n case d of\n Upwards -> 1\n Downwards -> -1\n AnyDirection -> 0\n\ndata SundialsSolution =\n SundialsSolution\n { actualTimeGrid :: V.Vector Double -- ^ actual time grid returned by the solver (with duplicated event times)\n , solutionMatrix :: Matrix Double -- ^ matrix of solutions: each column is an unknwown (add also the time vector?)\n , eventInfo :: [EventInfo] -- ^ event infos, as many items as triggered events during the simulation\n , diagnostics :: SundialsDiagnostics -- ^ usual Sundials diagnostics\n }\n\ndata EventInfo =\n EventInfo\n { eventTime :: !Double -- ^ time at which event was triggered\n , eventIndex :: !Int -- ^ which index was triggered\n , rootDirection :: !CrossingDirection -- ^ in which direction ((+)->(-) or (-)->(+)) the root is crossed\n }\n deriving Show\n\ngetMethod :: ODEMethod -> Int\ngetMethod (ADAMS) = cV_ADAMS\ngetMethod (BDF) = cV_BDF\n\ngetJacobian :: ODEMethod -> Maybe Jacobian\ngetJacobian _ = Nothing\n\n-- | A version of 'odeSolveVWith' with reasonable default step control.\nodeSolveV\n :: ODEMethod\n -> Maybe Double -- ^ initial step size - by default, CVode\n -- estimates the initial step size to be the\n -- solution \\(h\\) of the equation\n -- \\(\\|\\frac{h^2\\ddot{y}}{2}\\| = 1\\), where\n -- \\(\\ddot{y}\\) is an estimated value of the\n -- second derivative of the solution at \\(t_0\\)\n -> Double -- ^ absolute tolerance for the state vector\n -> Double -- ^ relative tolerance for the state vector\n -> (Double -> Vector Double -> Vector Double) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> Vector Double -- ^ initial conditions\n -> Vector Double -- ^ desired solution times\n -> Matrix Double -- ^ solution\nodeSolveV meth hi epsAbs epsRel f y0 ts =\n odeSolveVWith meth (X epsAbs epsRel) hi g y0 ts\n where\n g t x0 = coerce $ f t x0\n\n-- | A version of 'odeSolveV' with reasonable default parameters and\n-- system of equations defined using lists. FIXME: we should say\n-- something about the fact we could use the Jacobian but don't for\n-- compatibility with hmatrix-gsl.\nodeSolve :: (Double -> [Double] -> [Double]) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> [Double] -- ^ initial conditions\n -> Vector Double -- ^ desired solution times\n -> Matrix Double -- ^ solution\nodeSolve f y0 ts =\n -- FIXME: These tolerances are different from the ones in GSL\n odeSolveVWith BDF (XX' 1.0e-6 1.0e-10 1 1) Nothing g (V.fromList y0) (V.fromList $ toList ts)\n where\n g t x0 = V.fromList $ f t (V.toList x0)\n\n-- | A version of 'odeSolveVWith'' with reasonable default solver\n-- options.\nodeSolveVWith ::\n ODEMethod\n -> StepControl\n -> Maybe Double -- ^ initial step size - by default, CVode\n -- estimates the initial step size to be the\n -- solution \\(h\\) of the equation\n -- \\(\\|\\frac{h^2\\ddot{y}}{2}\\| = 1\\), where\n -- \\(\\ddot{y}\\) is an estimated value of the second\n -- derivative of the solution at \\(t_0\\)\n -> (Double -> V.Vector Double -> V.Vector Double) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> V.Vector Double -- ^ Initial conditions\n -> V.Vector Double -- ^ Desired solution times\n -> Matrix Double -- ^ Error code or solution\nodeSolveVWith method control initStepSize f y0 tt =\n case odeSolveVWith' opts f y0 tt of\n Left (c, _v) -> error $ show c -- FIXME\n Right (v, _d) -> v\n where\n opts = ODEOpts { maxNumSteps = 10000\n , minStep = 1.0e-12\n , maxFail = 10\n , odeMethod = method\n , stepControl = control\n , initStep = initStepSize\n }\n\nodeSolveVWith' ::\n ODEOpts\n -> (Double -> V.Vector Double -> V.Vector Double) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> V.Vector Double -- ^ Initial conditions\n -> V.Vector Double -- ^ Desired solution times\n -> Either (Matrix Double, Int) (Matrix Double, SundialsDiagnostics) -- ^ Error code or solution\nodeSolveVWith' opts f y0 tt =\n case solveOdeC (fromIntegral $ maxFail opts)\n (fromIntegral $ maxNumSteps opts) (coerce $ minStep opts)\n (fromIntegral . getMethod . odeMethod $ opts) (coerce $ initStep opts) jacH (scise $ stepControl opts)\n (coerce f) (coerce y0)\n 0 (\\_ x -> x) [] 0 (\\_ _ y -> y) (coerce tt) of\n -- Remove the time column for backwards compatibility\n SolverError m c -> Left\n ( subMatrix (0, 1) (V.length tt, l) m\n , fromIntegral c\n )\n SolverSuccess _ m d -> Right\n ( subMatrix (0, 1) (V.length tt, l) m\n , d\n )\n where\n l = size y0\n scise (X aTol rTol) = coerce (V.replicate l aTol, rTol)\n scise (X' aTol rTol) = coerce (V.replicate l aTol, rTol)\n scise (XX' aTol rTol yScale _yDotScale) = coerce (V.replicate l aTol, yScale * rTol)\n -- FIXME; Should we check that the length of ss is correct?\n scise (ScXX' aTol rTol yScale _yDotScale ss) = coerce (V.map (* aTol) ss, yScale * rTol)\n jacH = fmap (\\g t v -> matrixToSunMatrix $ g (coerce t) (coerce v)) $\n getJacobian $ odeMethod opts\n\nmatrixToSunMatrix :: Matrix Double -> T.SunMatrix\nmatrixToSunMatrix m = T.SunMatrix { T.rows = nr, T.cols = nc, T.vals = vs }\n where\n nr = fromIntegral $ rows m\n nc = fromIntegral $ cols m\n -- FIXME: efficiency\n vs = V.fromList $ map coerce $ concat $ toLists m\n\nsolveOdeC ::\n CInt ->\n CLong ->\n CDouble ->\n CInt ->\n Maybe CDouble ->\n (Maybe (CDouble -> V.Vector CDouble -> T.SunMatrix)) ->\n (V.Vector CDouble, CDouble) ->\n (CDouble -> V.Vector CDouble -> V.Vector CDouble) -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> V.Vector CDouble -- ^ Initial conditions\n -> CInt -- ^ Number of event equations\n -> (CDouble -> V.Vector CDouble -> V.Vector CDouble) -- ^ The event equations themselves\n -> [CrossingDirection] -- ^ The required crossing direction for each event\n -> CInt -- ^ Maximum number of events\n -> (Int -> CDouble -> V.Vector CDouble -> V.Vector CDouble)\n -- ^ Function to reset/update the state when an event occurs. The\n -- 'Int' argument is the 0-based number of the event that has\n -- occurred. If multiple events have occurred at the same time, they\n -- are handled in the increasing order of the event index. The other\n -- arguments are the time and the point in the state space. Return\n -- the updated point in the state space.\n -> V.Vector CDouble -- ^ Desired solution times\n -> SolverResult\nsolveOdeC maxErrTestFails maxNumSteps_ minStep_ method initStepSize\n jacH (aTols, rTol) fun f0 nr event_fn directions max_events apply_event ts =\n unsafePerformIO $ do\n\n let isInitStepSize :: CInt\n isInitStepSize = fromIntegral $ fromEnum $ isJust initStepSize\n ss :: CDouble\n ss = case initStepSize of\n -- It would be better to put an error message here but\n -- inline-c seems to evaluate this even if it is never\n -- used :(\n Nothing -> 0.0\n Just x -> x\n\n let dim = V.length f0\n nEq :: CLong\n nEq = fromIntegral dim\n nTs :: CInt\n nTs = fromIntegral $ V.length ts\n output_mat_mut :: V.MVector _ CDouble <- V.thaw =<< createVector ((1 + fromIntegral dim) * (fromIntegral (2 * max_events) + fromIntegral nTs))\n diagMut :: V.MVector _ CLong <- V.thaw =<< createVector 10 -- FIXME\n -- We need the types that sundials expects.\n -- FIXME: The Haskell type is currently empty!\n let funIO :: CDouble -> Ptr T.SunVector -> Ptr T.SunVector -> Ptr () -> IO CInt\n funIO t y f _ptr = do\n sv <- peek y\n poke f $ SunVector { sunVecN = sunVecN sv\n , sunVecVals = fun t (sunVecVals sv)\n }\n return 0\n\n let nrPre = fromIntegral nr\n gResults :: V.Vector CInt <- createVector nrPre\n -- FIXME: Do we need to do this here? Maybe as it will get GC'd and\n -- we'd have to do a malloc in C otherwise :(\n gResMut <- V.thaw gResults\n event_index_mut :: V.MVector _ CInt <- V.thaw =<< createVector (fromIntegral max_events)\n event_time_mut :: V.MVector _ CDouble <- V.thaw =<< createVector (fromIntegral max_events)\n -- Total number of events. This is *not* directly re\n n_events_mut :: V.MVector _ CInt <- V.thaw =<< createVector 1\n -- Total number of rows in the output_mat_mut matrix. It *cannot* be\n -- inferred from n_events_mut because when an event occurs k times, it\n -- contributes k to n_events_mut but only 2 to n_rows_mut.\n n_rows_mut :: V.MVector _ CInt <- V.thaw =<< createVector 1\n actual_event_direction_mut :: V.MVector _ CInt <- V.thaw =<< createVector (fromIntegral max_events)\n\n let event_fn_c :: CDouble -> Ptr T.SunVector -> Ptr CDouble -> Ptr () -> IO CInt\n event_fn_c x y f _ptr = do\n vals <- event_fn x <$> (sunVecVals <$> peek y)\n -- FIXME: We should be able to use poke somehow\n vectorToC vals nrPre f\n return 0\n\n apply_event_c :: CInt -> CDouble -> Ptr T.SunVector -> Ptr T.SunVector -> IO CInt\n apply_event_c event_index t y y' = do\n sv <- peek y\n poke y' $ SunVector\n { sunVecN = sunVecN sv\n , sunVecVals = apply_event (fromIntegral event_index) t (sunVecVals sv)\n }\n return 0\n\n requested_event_directions :: V.Vector CInt\n requested_event_directions = V.fromList $ map directionToInt directions\n\n let isJac :: CInt\n isJac = fromIntegral $ fromEnum $ isJust jacH\n jacIO :: CDouble -> Ptr T.SunVector -> Ptr T.SunVector -> Ptr T.SunMatrix ->\n Ptr () -> Ptr T.SunVector -> Ptr T.SunVector -> Ptr T.SunVector ->\n IO CInt\n jacIO t y _fy jacS _ptr _tmp1 _tmp2 _tmp3 = do\n case jacH of\n Nothing -> error \"Numeric.Sundials.CVode.ODE: Jacobian not defined\"\n Just jacI -> do j <- jacI t <$> (sunVecVals <$> peek y)\n poke jacS j\n -- FIXME: I don't understand what this comment means\n -- Unsafe since the function will be called many times.\n [CU.exp| int{ 0 } |]\n\n res :: Int <- fromIntegral <$> [C.block| int {\n /* general problem variables */\n\n int flag; /* reusable error-checking flag */\n\n int i, j; /* reusable loop indices */\n N_Vector y = NULL; /* empty vector for storing solution */\n N_Vector tv = NULL; /* empty vector for storing absolute tolerances */\n\n SUNMatrix A = NULL; /* empty matrix for linear solver */\n SUNLinearSolver LS = NULL; /* empty linear solver object */\n void *cvode_mem = NULL; /* empty CVODE memory structure */\n realtype t;\n long int nst, nfe, nsetups, nje, nfeLS, nni, ncfn, netf, nge;\n\n realtype tout;\n\n /* input_ind tracks the current index into the ts array */\n int input_ind = 1;\n /* output_ind tracks the current row into the output_mat_mut matrix.\n If differs from input_ind because of the extra rows corresponding to events. */\n int output_ind = 1;\n /* We need to update n_rows_mut every time we update output_ind because\n of the possibility of early return (in which case we still need to assemble\n the partial results matrix). We could even work with n_rows_mut only and ditch\n output_ind, but the inline-c expression is quite verbose, and output_ind is\n more convenient to use in index calculations.\n */\n\t\t\t ($vec-ptr:(int *n_rows_mut))[0] = output_ind;\n /* event_ind tracks the current event number */\n int event_ind = 0;\n\n /* general problem parameters */\n\n realtype T0 = RCONST(($vec-ptr:(double *ts))[0]); /* initial time */\n sunindextype NEQ = $(sunindextype nEq); /* number of dependent vars. */\n\n /* Initialize data structures */\n\n y = N_VNew_Serial(NEQ); /* Create serial vector for solution */\n if (check_flag((void *)y, \"N_VNew_Serial\", 0)) return 1;\n /* Specify initial condition */\n for (i = 0; i < NEQ; i++) {\n NV_Ith_S(y,i) = ($vec-ptr:(double *f0))[i];\n };\n\n cvode_mem = CVodeCreate($(int method), CV_NEWTON);\n if (check_flag((void *)cvode_mem, \"CVodeCreate\", 0)) return(1);\n\n /* Call CVodeInit to initialize the integrator memory and specify the\n * user's right hand side function in y'=f(t,y), the inital time T0, and\n * the initial dependent variable vector y. */\n flag = CVodeInit(cvode_mem, $fun:(int (* funIO) (double t, SunVector y[], SunVector dydt[], void * params)), T0, y);\n if (check_flag(&flag, \"CVodeInit\", 1)) return(1);\n\n tv = N_VNew_Serial(NEQ); /* Create serial vector for absolute tolerances */\n if (check_flag((void *)tv, \"N_VNew_Serial\", 0)) return 1;\n /* Specify tolerances */\n for (i = 0; i < NEQ; i++) {\n NV_Ith_S(tv,i) = ($vec-ptr:(double *aTols))[i];\n };\n\n flag = CVodeSetMinStep(cvode_mem, $(double minStep_));\n if (check_flag(&flag, \"CVodeSetMinStep\", 1)) return 1;\n flag = CVodeSetMaxNumSteps(cvode_mem, $(long int maxNumSteps_));\n if (check_flag(&flag, \"CVodeSetMaxNumSteps\", 1)) return 1;\n flag = CVodeSetMaxErrTestFails(cvode_mem, $(int maxErrTestFails));\n if (check_flag(&flag, \"CVodeSetMaxErrTestFails\", 1)) return 1;\n\n /* Call CVodeSVtolerances to specify the scalar relative tolerance\n * and vector absolute tolerances */\n flag = CVodeSVtolerances(cvode_mem, $(double rTol), tv);\n if (check_flag(&flag, \"CVodeSVtolerances\", 1)) return(1);\n\n /* Call CVodeRootInit to specify the root function event_fn_c with nr components */\n flag = CVodeRootInit(cvode_mem, $(int nr), $fun:(int (* event_fn_c) (double t, SunVector y[], double gout[], void * params)));\n\n if (check_flag(&flag, \"CVodeRootInit\", 1)) return(1);\n\n /* Set the initial step size if there is one */\n if ($(int isInitStepSize)) {\n /* FIXME: We could check if the initial step size is 0 */\n /* or even NaN and then throw an error */\n flag = CVodeSetInitStep(cvode_mem, $(double ss));\n if (check_flag(&flag, \"CVodeSetInitStep\", 1)) return 1;\n }\n\n /* Set the Jacobian if there is one */\n if ($(int isJac)) {\n /* Initialize dense matrix data structure and solver */\n A = SUNDenseMatrix(NEQ, NEQ);\n if (check_flag((void *)A, \"SUNDenseMatrix\", 0)) return 1;\n LS = SUNDenseLinearSolver(y, A);\n if (check_flag((void *)LS, \"SUNDenseLinearSolver\", 0)) return 1;\n\n /* Attach matrix and linear solver */\n flag = CVDlsSetLinearSolver(cvode_mem, LS, A);\n if (check_flag(&flag, \"CVDlsSetLinearSolver\", 1)) return 1;\n\n /* Set the Jacobian */\n flag = CVDlsSetJacFn(cvode_mem, $fun:(int (* jacIO) (double t, SunVector y[], SunVector fy[], SunMatrix Jac[], void * params, SunVector tmp1[], SunVector tmp2[], SunVector tmp3[])));\n if (check_flag(&flag, \"CVDlsSetJacFn\", 1)) return 1;\n } else /* Else we use CVDiag directly */ {\n flag = CVDiag(cvode_mem);\n if (check_flag(&flag, \"CVDiag\", 1)) return 1;\n }\n\n /* Store initial conditions */\n\t\t\t ($vec-ptr:(double *output_mat_mut))[0 * (NEQ + 1) + 0] = ($vec-ptr:(double *ts))[0];\n for (j = 0; j < NEQ; j++) {\n ($vec-ptr:(double *output_mat_mut))[0 * (NEQ + 1) + (j + 1)] = NV_Ith_S(y,j);\n }\n\n while (1) {\n flag = CVode(cvode_mem, ($vec-ptr:(double *ts))[input_ind], y, &t, CV_NORMAL); /* call integrator */\n if (check_flag(&flag, \"CVode solver failure, stopping integration\", 1)) return 1;\n\n /* Store the results for Haskell */\n\t\t\t ($vec-ptr:(double *output_mat_mut))[output_ind * (NEQ + 1) + 0] = t;\n for (j = 0; j < NEQ; j++) {\n ($vec-ptr:(double *output_mat_mut))[output_ind * (NEQ + 1) + (j + 1)] = NV_Ith_S(y,j);\n }\n output_ind++;\n ($vec-ptr:(int *n_rows_mut))[0] = output_ind;\n\n if (flag == CV_ROOT_RETURN) {\n if (event_ind >= $(int max_events)) {\n /* We don't have any more space for events. Return an error. */\n return 1;\n }\n\n /* Are we interested in this event?\n If not, continue without any observable side-effects.\n */\n int good_event = 0;\n\t\t\t flag = CVodeGetRootInfo(cvode_mem, ($vec-ptr:(int *gResMut)));\n\t\t\t if (check_flag(&flag, \"CVodeGetRootInfo\", 1)) return 1;\n for (i = 0; i < $(int nr); i++) {\n int ev = ($vec-ptr:(int *gResMut))[i];\n int req_dir = ($vec-ptr:(const int *requested_event_directions))[i];\n if (ev != 0 && ev * req_dir >= 0) {\n good_event = 1;\n\n ($vec-ptr:(int *actual_event_direction_mut))[event_ind] = ev;\n ($vec-ptr:(int *event_index_mut))[event_ind] = i;\n ($vec-ptr:(double *event_time_mut))[event_ind] = t;\n event_ind++;\n\n /* Update the state with the supplied function */\n $fun:(int (* apply_event_c) (int, double, SunVector y[], SunVector z[]))(i, t, y, y);\n }\n }\n\n if (good_event) {\n ($vec-ptr:(double *output_mat_mut))[output_ind * (NEQ + 1) + 0] = t;\n for (j = 0; j < NEQ; j++) {\n ($vec-ptr:(double *output_mat_mut))[output_ind * (NEQ + 1) + (j + 1)] = NV_Ith_S(y,j);\n }\n output_ind++;\n ($vec-ptr:(int *n_rows_mut))[0] = output_ind;\n\n flag = CVodeReInit(cvode_mem, t, y);\n if (check_flag(&flag, \"CVodeReInit\", 1)) return(1);\n } else {\n /* Since this is not a wanted event, it shouldn't get a row */\n output_ind--;\n ($vec-ptr:(int *n_rows_mut))[0] = output_ind;\n }\n }\n\t\t\t else {\n\t\t\t if (++input_ind >= $(int nTs))\n break;\n\t\t\t }\n }\n\n\t\t\t /* The number of actual roots we found */\n\t\t\t ($vec-ptr:(int *n_events_mut))[0] = event_ind;\n\n /* Get some final statistics on how the solve progressed */\n flag = CVodeGetNumSteps(cvode_mem, &nst);\n check_flag(&flag, \"CVodeGetNumSteps\", 1);\n ($vec-ptr:(long int *diagMut))[0] = nst;\n\n /* FIXME */\n ($vec-ptr:(long int *diagMut))[1] = 0;\n\n flag = CVodeGetNumRhsEvals(cvode_mem, &nfe);\n check_flag(&flag, \"CVodeGetNumRhsEvals\", 1);\n ($vec-ptr:(long int *diagMut))[2] = nfe;\n /* FIXME */\n ($vec-ptr:(long int *diagMut))[3] = 0;\n\n flag = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);\n check_flag(&flag, \"CVodeGetNumLinSolvSetups\", 1);\n ($vec-ptr:(long int *diagMut))[4] = nsetups;\n\n flag = CVodeGetNumErrTestFails(cvode_mem, &netf);\n check_flag(&flag, \"CVodeGetNumErrTestFails\", 1);\n ($vec-ptr:(long int *diagMut))[5] = netf;\n\n flag = CVodeGetNumNonlinSolvIters(cvode_mem, &nni);\n check_flag(&flag, \"CVodeGetNumNonlinSolvIters\", 1);\n ($vec-ptr:(long int *diagMut))[6] = nni;\n\n flag = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);\n check_flag(&flag, \"CVodeGetNumNonlinSolvConvFails\", 1);\n ($vec-ptr:(long int *diagMut))[7] = ncfn;\n\n flag = CVDlsGetNumJacEvals(cvode_mem, &nje);\n check_flag(&flag, \"CVDlsGetNumJacEvals\", 1);\n ($vec-ptr:(long int *diagMut))[8] = ncfn;\n\n flag = CVDlsGetNumRhsEvals(cvode_mem, &nfeLS);\n check_flag(&flag, \"CVDlsGetNumRhsEvals\", 1);\n ($vec-ptr:(long int *diagMut))[9] = ncfn;\n\n /* Clean up and return */\n\n N_VDestroy(y); /* Free y vector */\n N_VDestroy(tv); /* Free tv vector */\n CVodeFree(&cvode_mem); /* Free integrator memory */\n SUNLinSolFree(LS); /* Free linear solver */\n SUNMatDestroy(A); /* Free A matrix */\n\n return CV_SUCCESS;\n } |]\n preD <- V.freeze diagMut\n let d = SundialsDiagnostics (fromIntegral $ preD V.!0)\n (fromIntegral $ preD V.!1)\n (fromIntegral $ preD V.!2)\n (fromIntegral $ preD V.!3)\n (fromIntegral $ preD V.!4)\n (fromIntegral $ preD V.!5)\n (fromIntegral $ preD V.!6)\n (fromIntegral $ preD V.!7)\n (fromIntegral $ preD V.!8)\n (fromIntegral $ preD V.!9)\n n_rows <- fromIntegral . V.head <$> V.freeze n_rows_mut\n output_mat <- coerce . reshape (dim + 1) . subVector 0 ((dim + 1) * n_rows) <$>\n V.freeze output_mat_mut\n n_events <- fromIntegral . V.head <$> V.freeze n_events_mut\n event_time :: V.Vector Double\n <- coerce . V.take n_events <$> V.freeze event_time_mut\n event_index :: V.Vector Int\n <- V.map fromIntegral . V.take n_events <$> V.freeze event_index_mut\n actual_event_direction :: V.Vector CInt\n <- V.take n_events <$> V.freeze actual_event_direction_mut\n let\n events :: [EventInfo]\n events = zipWith3 EventInfo\n (V.toList event_time)\n (V.toList event_index)\n (map (fromJust . intToDirection) $ V.toList actual_event_direction)\n return $\n if res == cV_SUCCESS\n then\n SolverSuccess events output_mat d\n else\n SolverError output_mat res\n\ndata SolverResult\n = SolverError !(Matrix Double) !Int\n -- ^ Partial results and error code\n | SolverSuccess\n [EventInfo]\n !(Matrix Double)\n !SundialsDiagnostics\n -- ^ Times at which the event was triggered, information about which root and the\n -- results and diagnostics.\n deriving Show\n\nodeSolveRootVWith' ::\n ODEOpts\n -> (Double -> V.Vector Double -> V.Vector Double)\n -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> Maybe (Double -> Vector Double -> Matrix Double)\n -- ^ The Jacobian (optional)\n -> V.Vector Double -- ^ Initial conditions\n -> [EventSpec] -- ^ Event specifications\n -> Int -- ^ Maximum number of events\n -> V.Vector Double -- ^ Desired solution times\n -> SolverResult\nodeSolveRootVWith' opts f mb_jacobian y0 event_specs nRootEvs tt =\n solveOdeC (fromIntegral $ maxFail opts)\n (fromIntegral $ maxNumSteps opts) (coerce $ minStep opts)\n (fromIntegral . getMethod . odeMethod $ opts) (coerce $ initStep opts) jacH (scise $ stepControl opts)\n (coerce f) (coerce y0)\n (genericLength event_specs) event_equations event_directions\n (fromIntegral nRootEvs) reset_state\n (coerce tt)\n where\n l = size y0\n scise (X aTol rTol) = coerce (V.replicate l aTol, rTol)\n scise (X' aTol rTol) = coerce (V.replicate l aTol, rTol)\n scise (XX' aTol rTol yScale _yDotScale) = coerce (V.replicate l aTol, yScale * rTol)\n -- FIXME; Should we check that the length of ss is correct?\n scise (ScXX' aTol rTol yScale _yDotScale ss) = coerce (V.map (* aTol) ss, yScale * rTol)\n jacH = fmap (\\g t v -> matrixToSunMatrix $ g (coerce t) (coerce v)) $ mb_jacobian\n event_equations :: CDouble -> Vector CDouble -> Vector CDouble\n event_equations t y = V.fromList $\n map (\\ev -> coerce (eventCondition ev) t y) event_specs\n event_directions :: [CrossingDirection]\n event_directions = map eventDirection event_specs\n reset_state :: Int -> CDouble -> Vector CDouble -> Vector CDouble\n reset_state n_event = coerce $ eventUpdate (event_specs !! n_event)\n\ndata EventSpec = EventSpec\n { eventCondition :: Double -> V.Vector Double -> Double\n , eventDirection :: CrossingDirection\n , eventUpdate :: Double -> V.Vector Double -> V.Vector Double\n }\n\nodeSolveWithEvents\n :: ODEOpts\n -> [EventSpec]\n -- ^ Event specifications\n -> Int\n -- ^ Maximum number of events\n -> (Double -> V.Vector Double -> V.Vector Double)\n -- ^ The RHS of the system \\(\\dot{y} = f(t,y)\\)\n -> Maybe (Double -> Vector Double -> Matrix Double)\n -- ^ The Jacobian (optional)\n -> V.Vector Double\n -- ^ Initial conditions\n -> V.Vector Double\n -- ^ Desired solution times\n -> Either Int SundialsSolution\n -- ^ Either an error code or a solution\nodeSolveWithEvents opts event_specs max_events rhs mb_jacobian initial sol_times =\n let\n result :: SolverResult\n result =\n odeSolveRootVWith' opts rhs mb_jacobian initial event_specs\n max_events sol_times\n in\n case result of\n SolverError _ code -> Left code\n SolverSuccess events mx diagn ->\n Right $ SundialsSolution\n { actualTimeGrid = extractTimeGrid mx\n , solutionMatrix = mx\n , eventInfo = events\n , diagnostics = diagn\n }\n where\n -- The time grid is the first column of the result matrix\n extractTimeGrid :: Matrix Double -> Vector Double\n extractTimeGrid = head . toColumns\n", "meta": {"hexsha": "4291bbbb6f769ee28470a0b68dc4560d4959e5da", "size": 34236, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Sundials/CVode/ODE.hs", "max_stars_repo_name": "feuerbach/hmatrix-sundials", "max_stars_repo_head_hexsha": "4bbb1375de9965a9accbe20cd2ec7ef07a9b2bf1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Numeric/Sundials/CVode/ODE.hs", "max_issues_repo_name": "feuerbach/hmatrix-sundials", "max_issues_repo_head_hexsha": "4bbb1375de9965a9accbe20cd2ec7ef07a9b2bf1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Numeric/Sundials/CVode/ODE.hs", "max_forks_repo_name": "feuerbach/hmatrix-sundials", "max_forks_repo_head_hexsha": "4bbb1375de9965a9accbe20cd2ec7ef07a9b2bf1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-11T12:33:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T12:33:55.000Z", "avg_line_length": 47.2872928177, "max_line_length": 209, "alphanum_fraction": 0.5189566538, "num_tokens": 8325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.39470387780105043}} {"text": "{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric #-}\n\n-- |\n-- Module : Statistics.Resampling\n-- Copyright : (c) 2009, 2010 Bryan O'Sullivan\n-- License : BSD3\n--\n-- Maintainer : bos@serpentine.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Resampling statistics.\n\nmodule Statistics.Resampling\n (\n Resample(..)\n , jackknife\n , jackknifeMean\n , jackknifeVariance\n , jackknifeVarianceUnb\n , jackknifeStdDev\n , resample\n , estimate\n , splitGen\n ) where\n\nimport Data.Aeson (FromJSON, ToJSON)\nimport Control.Concurrent (forkIO, newChan, readChan, writeChan)\nimport Control.Monad (forM_, liftM, replicateM, replicateM_)\nimport Data.Binary (Binary(..))\nimport Data.Data (Data, Typeable)\nimport Data.Vector.Algorithms.Intro (sort)\nimport Data.Vector.Binary ()\nimport Data.Vector.Generic (unsafeFreeze)\nimport Data.Word (Word32)\nimport GHC.Conc (numCapabilities)\nimport GHC.Generics (Generic)\nimport Numeric.Sum (Summation(..), kbn)\nimport Statistics.Function (indices)\nimport Statistics.Sample (mean, stdDev, variance, varianceUnbiased)\nimport Statistics.Types (Estimator(..), Sample)\nimport System.Random.MWC (GenIO, initialize, uniform, uniformVector)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Unboxed.Mutable as MU\n\n-- | A resample drawn randomly, with replacement, from a set of data\n-- points. Distinct from a normal array to make it harder for your\n-- humble author's brain to go wrong.\nnewtype Resample = Resample {\n fromResample :: U.Vector Double\n } deriving (Eq, Read, Show, Typeable, Data, Generic)\n\ninstance FromJSON Resample\ninstance ToJSON Resample\n\ninstance Binary Resample where\n put = put . fromResample\n get = fmap Resample get\n\n-- | /O(e*r*s)/ Resample a data set repeatedly, with replacement,\n-- computing each estimate over the resampled data.\n--\n-- This function is expensive; it has to do work proportional to\n-- /e*r*s/, where /e/ is the number of estimation functions, /r/ is\n-- the number of resamples to compute, and /s/ is the number of\n-- original samples.\n--\n-- To improve performance, this function will make use of all\n-- available CPUs. At least with GHC 7.0, parallel performance seems\n-- best if the parallel garbage collector is disabled (RTS option\n-- @-qg@).\nresample :: GenIO\n -> [Estimator] -- ^ Estimation functions.\n -> Int -- ^ Number of resamples to compute.\n -> Sample -- ^ Original sample.\n -> IO [Resample]\nresample gen ests numResamples samples = do\n let !numSamples = U.length samples\n ixs = scanl (+) 0 $\n zipWith (+) (replicate numCapabilities q)\n (replicate r 1 ++ repeat 0)\n where (q,r) = numResamples `quotRem` numCapabilities\n results <- mapM (const (MU.new numResamples)) ests\n done <- newChan\n gens <- splitGen numCapabilities gen\n forM_ (zip3 ixs (tail ixs) gens) $ \\ (start,!end,gen') -> do\n forkIO $ do\n let loop k ers | k >= end = writeChan done ()\n | otherwise = do\n re <- U.replicateM numSamples $ do\n r <- uniform gen'\n return (U.unsafeIndex samples (r `mod` numSamples))\n forM_ ers $ \\(est,arr) ->\n MU.write arr k . est $ re\n loop (k+1) ers\n loop start (zip ests' results)\n replicateM_ numCapabilities $ readChan done\n mapM_ sort results\n mapM (liftM Resample . unsafeFreeze) results\n where\n ests' = map estimate ests\n\n-- | Run an 'Estimator' over a sample.\nestimate :: Estimator -> Sample -> Double\nestimate Mean = mean\nestimate Variance = variance\nestimate VarianceUnbiased = varianceUnbiased\nestimate StdDev = stdDev\nestimate (Function est) = est\n\n-- | /O(n) or O(n^2)/ Compute a statistical estimate repeatedly over a\n-- sample, each time omitting a successive element.\njackknife :: Estimator -> Sample -> U.Vector Double\njackknife Mean sample = jackknifeMean sample\njackknife Variance sample = jackknifeVariance sample\njackknife VarianceUnbiased sample = jackknifeVarianceUnb sample\njackknife StdDev sample = jackknifeStdDev sample\njackknife (Function est) sample\n | G.length sample == 1 = singletonErr \"jackknife\"\n | otherwise = U.map f . indices $ sample\n where f i = est (dropAt i sample)\n\n-- | /O(n)/ Compute the jackknife mean of a sample.\njackknifeMean :: Sample -> U.Vector Double\njackknifeMean samp\n | len == 1 = singletonErr \"jackknifeMean\"\n | otherwise = G.map (/l) $ G.zipWith (+) (pfxSumL samp) (pfxSumR samp)\n where\n l = fromIntegral (len - 1)\n len = G.length samp\n\n-- | /O(n)/ Compute the jackknife variance of a sample with a\n-- correction factor @c@, so we can get either the regular or\n-- \\\"unbiased\\\" variance.\njackknifeVariance_ :: Double -> Sample -> U.Vector Double\njackknifeVariance_ c samp\n | len == 1 = singletonErr \"jackknifeVariance\"\n | otherwise = G.zipWith4 go als ars bls brs\n where\n als = pfxSumL . G.map goa $ samp\n ars = pfxSumR . G.map goa $ samp\n goa x = v * v where v = x - m\n bls = pfxSumL . G.map (subtract m) $ samp\n brs = pfxSumR . G.map (subtract m) $ samp\n m = mean samp\n n = fromIntegral len\n go al ar bl br = (al + ar - (b * b) / q) / (q - c)\n where b = bl + br\n q = n - 1\n len = G.length samp\n\n-- | /O(n)/ Compute the unbiased jackknife variance of a sample.\njackknifeVarianceUnb :: Sample -> U.Vector Double\njackknifeVarianceUnb = jackknifeVariance_ 1\n\n-- | /O(n)/ Compute the jackknife variance of a sample.\njackknifeVariance :: Sample -> U.Vector Double\njackknifeVariance = jackknifeVariance_ 0\n\n-- | /O(n)/ Compute the jackknife standard deviation of a sample.\njackknifeStdDev :: Sample -> U.Vector Double\njackknifeStdDev = G.map sqrt . jackknifeVarianceUnb\n\npfxSumL :: U.Vector Double -> U.Vector Double\npfxSumL = G.map kbn . G.scanl add zero\n\npfxSumR :: U.Vector Double -> U.Vector Double\npfxSumR = G.tail . G.map kbn . G.scanr (flip add) zero\n\n-- | Drop the /k/th element of a vector.\ndropAt :: U.Unbox e => Int -> U.Vector e -> U.Vector e\ndropAt n v = U.slice 0 n v U.++ U.slice (n+1) (U.length v - n - 1) v\n\nsingletonErr :: String -> a\nsingletonErr func = error $\n \"Statistics.Resampling.\" ++ func ++ \": singleton input\"\n\n-- | Split a generator into several that can run independently.\nsplitGen :: Int -> GenIO -> IO [GenIO]\nsplitGen n gen\n | n <= 0 = return []\n | otherwise =\n fmap (gen:) . replicateM (n-1) $\n initialize =<< (uniformVector gen 256 :: IO (U.Vector Word32))\n", "meta": {"hexsha": "c1c719248d8766af0f916476f5a4b1ee822410e7", "size": 6641, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Statistics/Resampling.hs", "max_stars_repo_name": "StefanHubner/statistics", "max_stars_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:18:47.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-03T06:18:47.000Z", "max_issues_repo_path": "Statistics/Resampling.hs", "max_issues_repo_name": "StefanHubner/statistics", "max_issues_repo_head_hexsha": "e98af025ef4aa0bc31a5b1fcf88bb80295aac956", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Statistics/Resampling.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": 35.7043010753, "max_line_length": 75, "alphanum_fraction": 0.6675199518, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3946045533632717}} {"text": "{-# language BangPatterns #-}\n{-# language ConstraintKinds #-}\n{-# language DefaultSignatures #-}\n{-# language FlexibleContexts #-}\n{-# language FlexibleInstances #-}\n{-# language GeneralizedNewtypeDeriving #-}\n{-# language RankNTypes #-}\n{-# language RebindableSyntax #-}\n{-# language TypeFamilies #-}\nmodule Prob where\n\nimport Prelude hiding (Functor(..), Applicative(..), Monad(..), sequence, (=<<), mapM, mapM_)\nimport qualified Prelude\n\nimport GHC.Exts (Constraint)\n\nimport Control.DeepSeq (NFData(..), force)\nimport Control.Parallel.Strategies (withStrategy, rpar, rseq, parList, parListChunk)\nimport Control.Monad.State (State)\n\nimport Data.List (groupBy, sort, sortBy)\nimport Data.List.NonEmpty (NonEmpty(..))\nimport qualified Data.Random as R\nimport qualified Data.Random.Distribution.Categorical as R\n\nimport Numeric.SpecFunctions (choose)\n\n\ntype QQ = Rational\n\ndata Event a = Event !a !QQ deriving (Eq, Ord)\n\neventToPair :: Event a -> (a, QQ)\neventToPair (Event a p) = (a, p)\n{-# inline eventToPair #-}\n\nmapEvent :: (a -> b) -> Event a -> Event b\nmapEvent f (Event a p) = Event (f a) p\n{-# inline mapEvent #-}\n\ninstance NFData a => NFData (Event a) where\n rnf (Event a _) = rnf a\n\ninstance Show a => Show (Event a) where\n show (Event a p) = show a ++ \": \" ++ show p -- (realToFrac p :: Float)\n\nnewtype Prob a = Prob { density :: [Event a] } deriving (Eq, Ord, Show, NFData)\n\nevents :: Prob a -> [Event a]\nevents (Prob es) = es\n\neventValues :: Prob a -> [a]\neventValues prob = [a | Event a _ <- events prob]\n\neventProbs :: Prob a -> [QQ]\neventProbs prob = [p | Event _ p <- events prob]\n\nclass NoConstr a\ninstance NoConstr a\n\nclass ConstrMonad m where\n type Constr m :: * -> Constraint\n type Constr m = NoConstr\n\n fmap :: Constr m b => (a -> b) -> m a -> m b\n fmap f ma = do\n a <- ma\n return (f a)\n\n return :: Constr m a => a -> m a\n (>>=) :: Constr m b => m a -> (a -> m b) -> m b\n\n (|>>=|) :: (Constr m a, Constr m b) => m a -> (a -> m b) -> m b\n (|>>=|) = (>>=)\n\n default return :: Prelude.Monad m => a -> m a\n return = Prelude.return\n default (>>=) :: Prelude.Monad m => m a -> (a -> m b) -> m b\n ma >>= f = ma Prelude.>>= f\n\ninfixl 1 >>=\n\n\nliftA2 :: (ConstrMonad m, Constr m a, Constr m b, Constr m d) => (a -> b -> d) -> m a -> m b -> m d\nliftA2 f ma mb = do\n a <- ma\n b <- mb\n return (f a b)\n{-# inline liftA2 #-}\n\nliftA3 :: (ConstrMonad m, Constr m a, Constr m b, Constr m d, Constr m e) => (a -> b -> d -> e) -> m a -> m b -> m d -> m e\nliftA3 f ma mb md = do\n a <- ma\n b <- mb\n d <- md\n return (f a b d)\n{-# inlinable liftA3 #-}\n\n(=<<) :: (ConstrMonad m, Constr m a, Constr m b) => (a -> m b) -> m a -> m b\nf =<< ma = ma >>= f\ninfixr 1 =<<\n{-# inline (=<<) #-}\n\n\ninstance ConstrMonad Maybe\ninstance ConstrMonad IO\ninstance ConstrMonad (State s)\n\ninstance Prelude.Monad m => ConstrMonad (R.RVarT m)\ninstance Prelude.Monad m => ProbMonad (R.RVarT m) where\n fromEventsSorted evts = R.categoricalT [(realToFrac p :: Double, a) | Event a p <- evts]\n\nweightedEvents :: Real b => [(a, b)] -> [Event a]\nweightedEvents es = [Event a (realToFrac w / s) | (a,w) <- es]\n where\n s = realToFrac $ sum [w | (_,w) <- es]\n\nrnfList :: [a] -> ()\nrnfList [] = ()\nrnfList (a:as) = a `seq` rnfList as\n\nforceList :: [a] -> [a]\nforceList as = rnfList as `seq` as\n\nfmapProb :: Ord b => (a -> b) -> Prob a -> Prob b\nfmapProb f (Prob [Event a p]) = Prob [Event (f a) p]\nfmapProb f (Prob evts) =\n Prob $ forceList $ group1 $ sortBy (\\(Event b _) (Event b' _) -> compare b b') [Event (f a) p | Event a p <- evts]\n where\n group1 :: Ord a => [Event a] -> [Event a]\n group1 [] = []\n group1 (e:es) = group e es\n\n group :: Ord a => Event a -> [Event a] -> [Event a]\n group e@(Event a p) ees =\n case ees of\n [] -> [e]\n e'@(Event a' p') : es\n | a == a' -> group (Event a (p + p')) es\n | otherwise -> e : group e' es\n\n{-# inlinable fmapProb #-}\n\nbindProbWithStrat :: Ord b => (forall c. [c] -> [c]) -> Prob a -> (a -> Prob b) -> Prob b\nbindProbWithStrat evalList (Prob [Event a _]) f = Prob $ evalList $ events (f a)\nbindProbWithStrat evalList (Prob evts) f =\n Prob $ forceList $ group1 $ merge1 $ evalList $ totalProb [Event (f a) p | Event a p <- evts]\n where\n totalProb :: [Event (Prob a)] -> [[Event a]]\n totalProb ess = [[Event b (p*p') | Event b p' <- es] | Event (Prob es) p <- ess]\n\n merge1 :: Ord a => [[Event a]] -> [Event a]\n merge1 [] = []\n merge1 (es:ess) = merge es ess\n\n merge :: Ord a => [Event a] -> [[Event a]] -> [Event a]\n merge es [] = es\n merge es (es':[]) = merge2 es es'\n merge es (es':es'':ess) = merge2 (merge2 es es') (merge es'' ess)\n\n merge2 :: Ord a => [Event a] -> [Event a] -> [Event a]\n merge2 as [] = as\n merge2 [] bs = bs\n merge2 aas@(a:as) bbs@(b:bs)\n | a <= b = a : merge2 as bbs\n | otherwise = b : merge2 aas bs\n\n group1 :: Ord a => [Event a] -> [Event a]\n group1 [] = []\n group1 (e:es) = group e es\n\n group :: Ord a => Event a -> [Event a] -> [Event a]\n group e@(Event a p) ees =\n case ees of\n [] -> [e]\n e'@(Event a' p') : es\n | a == a' -> group (Event a (p + p')) es\n | otherwise -> e : group e' es\n\n{-# inlinable bindProbWithStrat #-}\n\ninstance ConstrMonad Prob where\n type Constr Prob = Ord\n\n fmap = fmapProb\n {-# inline fmap #-}\n\n return a = Prob [Event a 1]\n {-# inline return #-}\n\n (>>=) = bindProbWithStrat forceList\n {-# inline (>>=) #-}\n\n -- (|>>=|) :: (Ord a, Ord b) => Prob a -> (a -> Prob b) -> Prob b\n (|>>=|) = bindProbWithStrat (withStrategy $ parList rseq)\n {-# inline (|>>=|) #-}\n\n\n(|=<<|) :: (Ord a, Ord b) => (a -> Prob b) -> Prob a -> Prob b\nf |=<<| ma = ma |>>=| f\n{-# inline (|=<<|) #-}\n\nifThenElse :: Bool -> a -> a -> a\nifThenElse True t _ = t\nifThenElse False _ f = f\n{-# inline ifThenElse #-}\n\nfail :: a\nfail = error \"fail called\"\n\n(>>) :: (ConstrMonad m, Constr m (), Constr m b) => m a -> m b -> m b\nma >> mb = fmap (\\_ -> ()) ma >>= \\() -> mb\ninfixl 1 >>\n{-# inline (>>) #-}\n\n(<<) :: (ConstrMonad m, Constr m (), Constr m b) => m b -> m a -> m b\nmb << ma = ma >> mb\ninfixr 1 <<\n{-# inline (<<) #-}\n\nsequence :: (ConstrMonad m, Constr m a, Constr m [a]) => [m a] -> m [a]\nsequence [] = return []\nsequence (ma:mas) = liftA2 (:) ma (sequence mas)\n{-# inlinable sequence #-}\n\nmapM :: (ConstrMonad m, Constr m b, Constr m [b]) => (a -> m b) -> [a] -> m [b]\nmapM f [] = return []\nmapM f (a:as) = liftA2 (:) (f a) (mapM f as)\n{-# inlinable mapM #-}\n\nmapM_ :: (ConstrMonad m, Constr m ()) => (a -> m ()) -> [a] -> m ()\nmapM_ f [] = return ()\nmapM_ f (a:as) = f a >> mapM_ f as\n{-# inlinable mapM_ #-}\n\nforM :: (ConstrMonad m, Constr m b, Constr m [b]) => [a] -> (a -> m b) -> m [b]\nforM as f = mapM f as\n{-# inline forM #-}\n\nforM_ :: (ConstrMonad m, Constr m ()) => [a] -> (a -> m ()) -> m ()\nforM_ as f = mapM_ f as\n{-# inline forM_ #-}\n\nsequence1 :: (ConstrMonad m, Constr m a, Constr m [a], Constr m (NonEmpty a)) => NonEmpty (m a) -> m (NonEmpty a)\nsequence1 (ma:|mas) = liftA2 (:|) ma (sequence mas)\n{-# inline sequence1 #-}\n\nmapM1 :: (ConstrMonad m, Constr m b, Constr m [b], Constr m (NonEmpty b)) => (a -> m b) -> NonEmpty a -> m (NonEmpty b)\nmapM1 f (a:|as) = liftA2 (:|) (f a) (mapM f as)\n{-# inline mapM1 #-}\n\nforM1 :: (ConstrMonad m, Constr m b, Constr m [b], Constr m (NonEmpty b)) => NonEmpty a -> (a -> m b) -> m (NonEmpty b)\nforM1 as f = mapM1 f as\n{-# inline forM1 #-}\n\n\nliftFoldl' :: (ConstrMonad m, Constr m a, Constr m b) => (b -> a -> b) -> m b -> [m a] -> m b\nliftFoldl' _ !z [] = z\nliftFoldl' f !z (p:ps) = liftFoldl' f (liftA2 f z p) ps\n\nliftFoldr :: (ConstrMonad m, Constr m a, Constr m b) => (a -> b -> b) -> m b -> [m a] -> m b\nliftFoldr f z = foldr (liftA2 f) z\n\nliftFold :: (ConstrMonad m, Constr m a, Monoid a) => [m a] -> m a\nliftFold = liftFoldl' mappend (return mempty)\n\nliftSum :: (ConstrMonad m, Constr m a, Num a) => [m a] -> m a\nliftSum = liftFoldl' (+) (return 0)\n\n\nclass ConstrMonad m => ProbMonad m where\n fromEventsSorted :: Constr m a => [Event a] -> m a\n\ninstance ProbMonad Prob where\n fromEventsSorted = Prob\n\nuniformly :: (ProbMonad m, Constr m a, Ord a) => [a] -> m a\nuniformly = uniformlySorted . sort\n\nuniformlySorted :: (ProbMonad m, Constr m a) => [a] -> m a\nuniformlySorted as = fromEventsSorted [Event a (1/n) | a <- as]\n where\n n = fromIntegral (length as)\n\nprobTrue :: Prob Bool -> QQ\nprobTrue prob =\n case events prob of\n [Event False _, Event True p] -> p\n [Event True p] -> p\n [Event False q] -> 1 - q\n [] -> error \"empty Prob!\"\n _ -> error \"unnormalized Prob!\"\n\nprobFalse :: Prob Bool -> QQ\nprobFalse prob = 1 - probTrue prob\n\neventProb :: Eq a => a -> Prob a -> QQ\neventProb e prob =\n case [p | Event a p <- events prob, a == e] of\n [] -> 0\n [p] -> p\n _ -> error \"eventProb: prob is not normalized\"\n\nprobOf :: (a -> Bool) -> Prob a -> QQ\nprobOf test prob = sum [p | Event a p <- events prob, test a]\n\ngiven :: (a -> Bool) -> Prob a -> Prob a\ngiven hyp prob =\n Prob [Event a (p / probHyp) | Event a p <- events prob, hyp a]\n where\n probHyp = probOf hyp prob\n\nbernoulli :: QQ -> Prob Bool\nbernoulli p = Prob [Event False (1-p), Event True p]\n\nbinomial :: Int -> QQ -> Prob Int\nbinomial 0 _ = return 0\nbinomial n p =\n case p of\n 0 -> force $ return 0\n 1 -> force $ return n\n _ -> force $ Prob [Event k (binomialProb n p k) | k <- [0..n]]\n\nbinomialProb :: Int -> QQ -> Int -> QQ\nbinomialProb n p k\n | k < 0 || k > n = 0\n | n == 0 = 1\n | otherwise = realToFrac (choose n k) * p^k * (1-p)^fromIntegral (n-k)\n\ndistribution :: Ord a => Prob a -> [Event a]\ndistribution (Prob evts) = scanl1 sumEvents evts\n where\n sumEvents (Event _ p) (Event a' p') = Event a' (p + p')\n\nrevDistribution :: Ord a => Prob a -> [Event a]\nrevDistribution (Prob evts) = scanr1 sumEvents evts\n where\n sumEvents (Event a p) (Event _ p') = Event a (p + p')\n\nsummary :: Prob QQ -> IO ()\nsummary p =\n let mu = \"µ=\" ++ show (realToFrac (mean p) :: Double)\n sigma = \"σ=\" ++ show (sqrt $ realToFrac (variance p) :: Double)\n in\n putStrLn $ mu ++ \", \" ++ sigma\n\nsummaryInt :: Prob Int -> IO ()\nsummaryInt = summary . fmap fromIntegral\n\nmean :: Prob QQ -> QQ\nmean prob = sum [k * p | Event k p <- events prob]\n\nvariance :: Prob QQ -> QQ\nvariance prob = sum [k^2 * p | Event k p <- events prob] - mean prob^2\n\nmaxEvent :: Ord a => Prob a -> a\nmaxEvent (Prob es) = maximum [a | Event a _ <- es]\n", "meta": {"hexsha": "e14aac69a49a07ffdec0f7ce29314099334df826", "size": 10775, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Prob.hs", "max_stars_repo_name": "bielr/taxo-gen", "max_stars_repo_head_hexsha": "61c4582da0dacf1f08986dad56d38df5c66e9922", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-05-23T09:04:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-23T09:04:54.000Z", "max_issues_repo_path": "src/Prob.hs", "max_issues_repo_name": "bielr/taxo-gen", "max_issues_repo_head_hexsha": "61c4582da0dacf1f08986dad56d38df5c66e9922", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Prob.hs", "max_forks_repo_name": "bielr/taxo-gen", "max_forks_repo_head_hexsha": "61c4582da0dacf1f08986dad56d38df5c66e9922", "max_forks_repo_licenses": ["BSD-3-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.0977653631, "max_line_length": 123, "alphanum_fraction": 0.5489559165, "num_tokens": 3579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3939253116929671}} {"text": "{-# LANGUAGE PackageImports,BangPatterns,StandaloneDeriving,TypeFamilies,FlexibleContexts,FlexibleInstances,TypeOperators,ExistentialQuantification,NoMonomorphismRestriction,DeriveTraversable,DeriveFunctor,DeriveFoldable #-}\nmodule Kalman where\nimport Space.Class hiding(dim)\nimport Solver.RungeKutta\nimport qualified Space.Class as M\nimport Data.Typeable\nimport Data.Distributive\nimport Data.Functor.Compose\nimport Linear.Matrix hiding(trace)\nimport qualified Linear.Metric as Metric\nimport Vectorization\nimport Control.Applicative\nimport Data.Maybe\nimport Data.Foldable (Foldable,foldl')\nimport qualified Data.Foldable as F\nimport Data.Traversable (Traversable,fmapDefault,mapAccumL)\nimport qualified Data.Traversable as T\nimport Linear.V0\nimport Linear.V1\nimport Foreign.Storable\nimport Foreign.FStorable\nimport Foreign.Cholesky\nimport qualified Numeric.LinearAlgebra as M\nimport qualified Data.Packed.Matrix as M \nimport Local\nimport Linear.Vector\nimport CartesianProduct\nimport Control.Monad.Trans.State\n\n-- Covariance Version\n\nfullM\n :: (RealFloat a, FStorable (Local b),\n Vectorize (Local b), Vectorize (Local b1), Space b,\n Space b1, Cholesky a, M.Field a) =>\n (b a -> b a)\n -> Local b (Local b a)\n -> (b a -> b1 a)\n -> Local b1 (Local b1 a)\n -> b1 a\n -> (b a, Local b (Local b a))\n -> (b a, Local b (Local b a))\nfullM f r h q m s= execState ( do \n modify (prediction f r)\n modify (measure h q m)\n --modify (smoothing f r s)\n --modify (prediction f r)\n ) s\n\n\nfull\n :: (RealFloat a, FStorable (Local b2), FStorable (Local b),\n Vectorize (Local b), Vectorize (Local b1), Space b2, Space b,\n Space b1, Cholesky a, M.Field a) =>\n (b2 a -> b a)\n -> Local b (Local b a)\n -> (b a -> b1 a)\n -> Local b1 (Local b1 a)\n -> b1 a\n -> (b2 a, Local b2 (Local b2 a))\n -> (b a, Local b (Local b a))\nfull f r h q m s= sm \n where sp = prediction f r s\n sm = measure h q m sp \n ss = smoothing f r s sm\n ssp = prediction f r ss\n ssm = measure h q m ssp \n\npredictionM f = modify . prediction f \nmeasureM h q = modify . measure h q \nsmoothingM f r = modify . smoothing f r \n\nprediction\n :: (M.Field a , Vectorize (Local b) ,RealFloat a, \n FStorable (Local b1), Space b1, Space b, Cholesky a) =>\n (b1 a -> b a)\n -> Local b (Local b a)\n -> (b1 a, Local b1 (Local b1 a))\n -> (b a, Local b (Local b a))\nprediction f r (x ,p)= (mean ,pxx )\n where\n (mean,pxx,_,_) = sigmaSamplingCovGain f r (x,p)\n\n\nmeasure\n :: (RealFloat a, FStorable (Local b),\n Vectorize (Local b1), Space b, Space b1, Cholesky a, M.Field a) =>\n (b a -> b1 a)\n -> Local b1 (Local b1 a)\n -> b1 a\n -> (b a, Local b (Local b a))\n -> (b a, Local b (Local b a))\nmeasure h q m (x ,p) = ( xb , pb )\n where\n (mmean,pxx,pxy,k) =sigmaSamplingCovGain h q (x,p)\n xb = x |+| ( k !* ( m |-| mmean ) )\n pb = p !-! ( k !*! pxx !*! distribute k )\n\nsmoothing\n :: (RealFloat a, FStorable (Local b), Vectorize (Local b1),\n Space b, Space b1, Cholesky a,\n M.Field a) =>\n (b a -> b1 a)\n -> Local b1 (Local b1 a)\n -> (b a, Local b (Local b a))\n -> (b1 a, Local b1 (Local b1 a))\n -> (b a, Local b (Local b a))\nsmoothing f r (x,p) (x1,p1) = (xb ,pb) \n where \n (xmean ,pxx,pxy,k) = sigmaSamplingCovGain f r (x,p) \n xb = x |+| (k !* ( x1 |-| xmean ) )\n pb = p !+! (k !*! ( p1 !-! pxx ) !*! distribute k )\n\nsigmaSamplingCovGain\n :: (RealFloat a,M.Field a ,Vectorize (Local b), \n FStorable (Local b1), Space b1, Space b, Cholesky a) =>\n (b1 a -> b a)\n -> (Local b (Local b a))\n -> (b1 a, Local b1 (Local b1 a))\n -> (b a, Local b (Local b a), Local b (Local b1 a),Local b1 (Local b a ))\nsigmaSamplingCovGain f r (x,p) = (mean , pxx,pxy,k) \n where\n spoints = (sigmaPoints1 x p)\n points = fmap f spoints \n mean = sigmaMean1 points\n pxx = sigmaCov mean points !+! r\n pxy = sigmaCovXY x mean spoints points\n k = distribute pxy !*! inverseM pxx\n \n\nsigmaSamplingCov\n :: (RealFloat a, Show (Local b1 (Local b1 a)),\n FStorable (Local b1), Space b1, Space b, Cholesky a) =>\n (b1 a -> b a)\n -> (Local b (Local b a))\n -> (b1 a, Local b1 (Local b1 a))\n -> (b a, Local b (Local b a), Local b (Local b1 a))\n\nsigmaSamplingCov f r (x,p) = (mean , pxx,pxy) \n where\n spoints = (sigmaPoints1 x p)\n points = fmap f spoints \n mean = sigmaMean1 points\n pxx = sigmaCov mean points !+! r\n pxy = sigmaCovXY x mean spoints points\n \n\ninverseM = fromLists . M.toLists . M.inv . M.fromLists . toLists \n\n{-\nmeasureDelayed h m (x,p) (xlag,plag) = (xnew,pxk)\n where\n -- Xlag\n sxlag = sigmaPoints1 xlag plag\n -- X\n sx = sigmaPoints1 x p\n -- XXlag\n pxxlag = sigmaCovXY x xlag sx sxlag\n -- Xk\n xk = x :|: xlag\n pxk = prodSym p plag pxxlag\n sxk = sigmaPoints1 xk pxk\n -- Y\n (sy,ym,py) = sigmaTransform h xlag plag\n pxlagy = sigmaCovXY xk ym sxk sy\n k = (distribute pxlagy) !*! (inverseM py)\n xnew = xk |+| (k !* (m |-| ym) )\n-}\n\nprodSym x y xy = prod x y xy (distribute xy)\n\nprod x y xy yx = (liftA2 (:|:) x xy ) :|: (liftA2 (:|:) yx y)\n\n\n-- Helpers\n\nsquare :: (Num a, R f) => f a -> f (f a)\nsquare v = mult v v\n\nsquareT v = (distribute v) !*! v\n\nmult x m = fmap (x ^*) m\n\nsigmaMean\n :: (RealFloat a, Traversable t, FStorable t, Space b) =>\n t (b a) -> b a -> b a\nsigmaMean p p0= case sigmaMean' p p0 of\n Just x -> x\n Nothing -> error $ \"sigmaMean nonConvergence\"\n\nsigmaMean1 (V1 p0 :|: p )= sigmaMean p p0\n\nsigmaMean'\n :: (RealFloat a, Traversable t, FStorable t, Space b) =>\n t (b a) -> b a -> Maybe (b a)\nsigmaMean' p p0 = go 1000 p0\n where\n go ! i ! mik\n | i == 0 = Nothing\n | Metric.quadrance m > 1.0e-14 = go (i-1) mik1\n | otherwise = Just mik1\n where\n mik1 = mik |+| m\n s = F.foldr1 (^+^) $ fmap (|-|mik) p\n m = s ^/ n\n n = 2 * (fromIntegral $ fsize p)\n\nsigmaCovXY xmean ymean samplex sampley = covxy\n where\n xstd = fmap (|-| xmean) samplex\n ystd = fmap (|-| ymean) sampley\n covxy = fmap (^/ 2) $ F.foldr1 (!+!) (liftA2 mult xstd ystd)\n\nsigmaCov mean sample = cov\n where\n std = fmap (|-| mean) sample\n cov = fmap (^/2) $ F.foldr1 (!+!) (fmap square std)\n\n\n\nsigmaPoints1 x p = V1 x :|: points\n where\n m = case potrf p of\n Right x -> x\n Left i -> error $ \"cholesky factorization error: sigmapoints1 : \" \n points = fmap (x|+|) $ m :|: fmap ((-1) *^) m\n\n\n\nsqrtPrediction\n :: (Applicative g1, Applicative g, Traversable g, Traversable g1,\n FStorable g, FStorable g1, FStorable (Local b1), Space b,\n Space b1) =>\n (b Double -> b1 Double)\n -> g1 (Local b1 Double)\n -> (b Double, g (Local b Double))\n -> (b1 Double, Local b1 (Local b1 Double))\nsqrtPrediction f r (x,s)= (xmean,sk'')\n where\n (y,w0m,w0c,w1) = weigthsGamma (fromIntegral $ fsize s)\n sp = fmap (x|+|) $ fmap (fmap (*y)) s :|: fmap (fmap (*(-y))) s\n sp' = fmap f sp\n x' = f x\n xmean = sigmaMean1 $ V1 x' :|: sp'\n std =fmap (|-| xmean) sp'\n sk' = dgeqrf $ distribute $ (fmap (fmap (*sqrt w1)) std):|: r\n sk'' = distribute $ ch1upJ sk' $ fmap (*sqrt w0c) $ x' |-| xmean\n\n\nweigthsGamma l = weigths 1 2 0 l\n\nweigths a b k l= (y,w0m,w0c,w1) where\n lam = a^2 * (l + k ) - l\n y = sqrt ( l + lam)\n w0m = lam /(l + lam)\n w0c = w0m + (1 - a^2 + b)\n w1 = 1 / (2*(l+ lam))\n\n\nch1dnR x = unRight . ch1dn x\nsqrtMeasure\n :: (Show (Local b Double),Show (b Double),Applicative g, Traversable g, FStorable g, FStorable (Local b),\n FStorable (Local b1), Space b1, Space b) =>\n (b1 Double -> b Double)\n -> g (Local b Double)\n -> b Double\n -> (b1 Double, Local b1 (Local b1 Double))\n -> (b1 Double, Local b1 (Local b1 Double))\nsqrtMeasure h r m (x,s) = (x'',s''')\n where\n{-\n spx = V1 x :|: (fmap (x|+|) $ fmap (fmap (*y)) s :|: fmap (fmap (*(-y))) s )\n wc = V1 w0c :|: pure w1\n --wm = V1 w0m :|: pure w1\n V1 y' :|: _ = spy\n xmean = sigmaMean1 spx\n stdx = liftA2 (*^) wc $ fmap (|-| xmean ) spx\n spy = fmap h spx\n ymean = sigmaMean1 spy\n stdy = fmap (|-| ymean) spy\n pxy = distribute stdx !*! stdy\n sk' = dgeqrf $ distribute $ fmap (fmap (*sqrt w1)) stdy :|: r\n sk''= distribute .fromJust $ ch1up sk' (fmap (*w0c) $ ymean |-| y')\n-}\n (ymean,pxx,pxy) = sigmaSampling h r (x,s) \n k = pseudoInverse pxy pxx \n -- x' = xmean |+| (k !* (m |-| y') )\n x' = x |+| (k !* (m |-| ymean) )\n u = pxx !*! distribute k\n s' = distribute $ F.foldl ch1dnR (distribute s) u\n (x'',s''',_) = sigmaSampling id V0 (x',s')\n{- spx' = fmap (x' |+| ) $ fmap (fmap (*y)) s' :|: fmap (fmap (*(-y))) s'\n x'' = sigmaMean1 $ V1 x' :|: spx'\n stdx' = fmap (|-| x'') spx'\n s'' = dgeqrf $ distribute $ fmap (fmap (*sqrt w1)) stdx'\n s''' = distribute $ fromJust $ ch1up s'' $ fmap (*sqrt w0c) $ x'' |-| x'\n-}\n\npseudoInverse\n :: (Applicative nhrs, Applicative m, Applicative m1,\n Traversable nhrs, Traversable m, Traversable m1, Distributive m1,\n FStorable nhrs, FStorable m, FStorable m1) =>\n nhrs (m1 Double) -> m (m1 Double) -> nhrs (m1 Double)\npseudoInverse y x = dgelssR (distribute x ) (dgelssR x y )\n\n\n\nsqrtBackward f p (x,s) (x1,s1) = (xb ,sb) \n where \n (xmean ,pxx,pxy) = sigmaSampling f p (x,s) \n k = pseudoInverse pxy pxx\n xb = x |+| (k !* (x1 |-| xmean ))\n s1pxx = distribute $ F.foldl (\\y-> ch1dnR y) (distribute s1 ) (distribute pxx )\n u = s1pxx !*! distribute k\n sb = distribute $ F.foldl ch1upJ (distribute s) u\n\nsigmaSampling h r (x,s) = (ymean,sxx,sxy)\n where \n (y,w0m,w0c,w1) = weigthsGamma (fromIntegral $ fsize s)\n spx = V1 x :|: (fmap (x|+|) $ fmap (fmap (*y)) s :|: fmap (fmap (*(-y))) s )\n wc = V1 w0c :|: pure w1\n --wm = V1 w0m :|: pure w1\n V1 y' :|: _ = spy\n xmean = sigmaMean1 spx\n stdx = liftA2 (*^) wc $ fmap (|-| xmean ) spx\n spy = fmap h spx\n ymean = sigmaMean1 spy\n stdy = fmap (|-| ymean) spy\n sxy = distribute stdx !*! stdy\n sk' = dgeqrf $ distribute $ fmap (fmap (*sqrt w1)) stdy :|: r\n sxx = distribute $ ch1upJ sk' (fmap (*w0c) $ ymean |-| y')\n\nch1upJ x = fromJust . ch1up x\ndgelssR x = unRight . dgelss x\n\nunRight (Right x) = x\nunRight (Left x) = error $ \"no right: \" \n\n\n\n", "meta": {"hexsha": "c465425473330d96dde34b927d5c35197efb72d1", "size": 10878, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Kalman.hs", "max_stars_repo_name": "massudaw/mtk", "max_stars_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Kalman.hs", "max_issues_repo_name": "massudaw/mtk", "max_issues_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Kalman.hs", "max_forks_repo_name": "massudaw/mtk", "max_forks_repo_head_hexsha": "c74570b02d3806f6690c57767e8e717e3d02a1ff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9002932551, "max_line_length": 224, "alphanum_fraction": 0.5471594043, "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.39373673772430473}} {"text": "module Data.SQP\n ( Problem (..)\n , optimize\n ) where\n\nimport Numeric.LinearAlgebra.HMatrix\nimport Numeric.Minimization.QuadProgPP\n\nimport Debug.Trace\n\ndata Problem = Problem\n { _cost :: Vector Double -> Double\n , _approxCost :: Vector Double\n -> (Matrix Double, Vector Double, Double)\n , _trueIneqs :: Vector Double -> Vector Double\n , _approxAffineIneqs :: Vector Double\n -> (Matrix Double, Vector Double)\n , _eqs :: Vector Double -> Vector Double\n , _approxEqs :: Vector Double -> (Matrix Double, Vector Double)\n , _numVariables :: Int\n , _numIneqs :: Int\n , _numEqs :: Int\n }\n\nstepAcceptanceThreshold :: Double\nstepAcceptanceThreshold = 0.25\n\ntrustShrinkFactor :: Double\ntrustShrinkFactor = 0.1\n\ntrustExpandFactor :: Double\ntrustExpandFactor = 1.5\n\nconstraintPenaltyScalingFactor :: Double\nconstraintPenaltyScalingFactor = 10\n\nminTrustSize :: Double\nminTrustSize = 1e-4\n\nminModelImprove :: Double\nminModelImprove = 1e-4\n\nminModelImproveRatio :: Double\nminModelImproveRatio = negate $ read \"Infinity\"\n\nconstraintSatisfactionThreshold :: Double\nconstraintSatisfactionThreshold = 1e-4\n\ninitTrustSize :: Double\ninitTrustSize = 0.1\n\ninitPenalty :: Double\ninitPenalty = 10\n\nevalMerit :: Problem -> Double -> Vector Double -> Double\nevalMerit problem penaltyParam x =\n let cost = _cost problem x\n penalty =\n penaltyParam * sum (map (max 0.0) $ toList $ _trueIneqs problem x) +\n penaltyParam * sum (map abs $ toList $ _eqs problem x)\n in cost + penalty\n\noptimize :: Problem\n -> Vector Double -- xInitial\n -> (Vector Double, Double)\noptimize problem xInit =\n findSuitableConstraintPenalty problem xInit initTrustSize initPenalty\n\nfindSuitableConstraintPenalty :: Problem\n -> Vector Double -- x\n -> Double -- trust region size\n -> Double -- constraint penalty\n -- xNew, trueMerit\n -> (Vector Double, Double)\nfindSuitableConstraintPenalty problem x trustSize penaltyParam =\n let (xNew, trueMerit, newTrustSize) =\n reconvexify problem x trustSize penaltyParam\n ineqsSatisfied = all (<= constraintSatisfactionThreshold) $\n toList $ _trueIneqs problem xNew\n eqsSatisfied = all ((<= constraintSatisfactionThreshold) . abs) $\n toList $ _eqs problem xNew\n constraintsSatisfied = ineqsSatisfied && eqsSatisfied\n in if constraintsSatisfied\n then (xNew, trueMerit)\n else let penalty' = penaltyParam * constraintPenaltyScalingFactor\n in findSuitableConstraintPenalty\n problem xNew newTrustSize penalty'\n\nevalQuadratic :: (Matrix Double, Vector Double, Double)\n -> Vector Double\n -> Double\nevalQuadratic (m, b, c) x =\n (x `dot` ((0.5 * (m #> x)) + b)) + c\n\nevalLinear :: (Matrix Double, Vector Double)\n -> Vector Double\n -> Vector Double\nevalLinear (m, b) x = (m #> x) + b\n\nreconvexify :: Problem\n -> Vector Double -- x\n -> Double -- trust region size\n -> Double -- constraint penalty\n -- xNew, newTrueMerit, newTrustSize\n -> (Vector Double, Double, Double)\nreconvexify problem x trustSize penaltyParam =\n let convexCost = _approxCost problem x\n convexIneqs = _approxAffineIneqs problem x\n convexEqs = _approxEqs problem x\n trueMerit = evalMerit problem penaltyParam x\n trustResult = findSuitableTrustStep problem x convexCost\n convexIneqs convexEqs trueMerit trustSize\n penaltyParam\n in case trustResult of\n Reconvexify xNew newMerit newTrustSize ->\n reconvexify problem xNew newTrustSize penaltyParam\n Finished xNew newMerit newTrustSize ->\n (xNew, newMerit, newTrustSize)\n\ndata TrustStepResult = -- x merit trustSize\n Reconvexify (Vector Double) Double Double\n | Finished (Vector Double) Double Double\n deriving (Show)\n\nfindSuitableTrustStep :: Problem\n -> Vector Double -- x\n -- convexified cost\n -> (Matrix Double, Vector Double, Double)\n -- convexified inequality constraints\n -> (Matrix Double, Vector Double)\n -- convexified equality constraints\n -> (Matrix Double, Vector Double)\n -> Double -- old true merit\n -> Double -- trust region size\n -> Double -- constraint penalty parameter\n -- xNew, newTrueMerit, newTrustSize\n -> TrustStepResult\nfindSuitableTrustStep\n problem x convexCost convexIneq convexEq oldTrueMerit trustSize penaltyParam =\n let trustStep =\n trustRegionStep problem x convexCost convexIneq convexEq oldTrueMerit\n trustSize penaltyParam\n in case trace (show trustStep) trustStep of\n Reject -> let newTrustSize = trustSize * trustShrinkFactor\n in findSuitableTrustStep problem x convexCost convexIneq\n convexEq oldTrueMerit newTrustSize penaltyParam\n Accept xNew newTrueMerit ->\n let newTrustSize = trustSize * trustExpandFactor\n in Reconvexify xNew newTrueMerit newTrustSize\n Converged xNew newTrueMerit ->\n let newTrustSize =\n max trustSize $ (minTrustSize / trustShrinkFactor) * 1.5\n in Finished xNew newTrueMerit newTrustSize\n\ndata IterationResult = Reject\n -- xNew newMerit\n | Accept (Vector Double) Double\n | Converged (Vector Double) Double\n deriving (Show)\n\ntrustRegionStep :: Problem\n -> Vector Double -- x\n -- convexified cost\n -> (Matrix Double, Vector Double, Double)\n -- convexified inequality constraints\n -> (Matrix Double, Vector Double)\n -- convexified equality constraints\n -> (Matrix Double, Vector Double)\n -> Double -- old true merit\n -> Double -- trust region size\n -> Double -- constraint penalty parameter\n -> IterationResult\ntrustRegionStep\n problem x convexCost convexIneq convexEq oldTrueMerit trustSize penaltyParam =\n let (xNew, modelMerit) = solveQuadraticSubproblem problem x convexCost\n convexIneq convexEq trustSize penaltyParam\n trueMerit = evalMerit problem penaltyParam xNew\n trueImprove = oldTrueMerit - trueMerit\n modelImprove = oldTrueMerit - modelMerit\n in if modelImprove < -1e-2 -- why so high? our convexification?\n then error $ \"Model improvement got worse: \" ++\n show (modelImprove, modelMerit, oldTrueMerit, trueMerit)\n else\n if trustSize < minTrustSize ||\n modelImprove < minModelImprove ||\n modelImprove / oldTrueMerit < minModelImproveRatio\n then Converged x oldTrueMerit\n else\n if trueImprove > 0.0 &&\n trueImprove / modelImprove > stepAcceptanceThreshold\n then Accept xNew trueMerit\n else Reject\n\nsolveQuadraticSubproblem :: Problem\n -> Vector Double\n -- convex cost\n -> (Matrix Double, Vector Double, Double)\n -- convexified inequality constraints\n -> (Matrix Double, Vector Double)\n -- convexified equality constraints\n -> (Matrix Double, Vector Double)\n -> Double -- trust region size\n -> Double -- constraint penalty parameter\n -> (Vector Double, Double) -- new x, model merit\nsolveQuadraticSubproblem\n problem x (costMatrix, costVector, costConstant)\n (approxIneqMatrix, approxIneqVector) (approxEqMatrix, approxEqVector)\n trustSize penaltyParam =\n -- We approximate each nonlinear inequality as |ax + b|^+. For each\n -- of these, we introduce a new optimization variable t (i.e., a\n -- slack variable) that comes with two inequalities:\n --\n -- 0 <= t\n --\n -- ax + b <= t\n --\n -- Each nonlinear equality as |ax + b|. For each of these, two new\n -- optimization variables s and t with following properties:\n --\n -- -s <= 0\n -- -t <= 0\n -- s - t = ax + b\n let numIneqs = _numIneqs problem\n numEqs = _numEqs problem\n numVariables = _numVariables problem\n\n costMatrixWithSlacks =\n diagBlock [ costMatrix\n , konst 0.0 (numIneqs, numIneqs)\n , konst 0.0 (2 * numEqs, 2 * numEqs)]\n\n -- LET'S MAKE COST SPD\n (l, v) = eigSH costMatrixWithSlacks\n positiveEigVals = cmap (max 1e-12) l\n augmentedCostMatrix = v <> diag positiveEigVals <> tr v\n\n augmentedCostVector = vjoin [costVector\n , konst 1.0 numIneqs\n , konst 1.0 $ 2 * numEqs]\n\n augmentedIneqMatrix =\n ((scalar penaltyParam * approxIneqMatrix) |||\n negate (ident numIneqs) |||\n konst 0.0 (numIneqs, 2 * numEqs)) ===\n (konst 0.0 (numIneqs + 2 * numEqs, numVariables) |||\n negate (ident $ numIneqs + 2 * numEqs))\n augmentedIneqVector =\n vjoin [ scalar penaltyParam * approxIneqVector\n , konst 0.0 $ numIneqs + 2 * numEqs ]\n\n ineqMatrixWithTrustConstraints =\n augmentedIneqMatrix ===\n (ident numVariables ||| konst 0.0 (numVariables, numIneqs + 2 * numEqs)) ===\n (negate (ident numVariables) ||| konst 0.0 (numVariables, numIneqs + 2 * numEqs))\n ineqVectorWithTrustConstraints =\n vjoin [ augmentedIneqVector\n , negate (x + scalar trustSize)\n , x - scalar trustSize ]\n\n augmentedEqMatrix =\n scalar penaltyParam * approxEqMatrix |||\n konst 0.0 (numEqs, numIneqs) |||\n negate (ident numEqs) |||\n ident numEqs\n augmentedEqVector = scalar penaltyParam * approxEqVector\n\n -- inequalities are given as ax + b <= 0, but quadprog++ wants\n -- a'x + b' >= 0\n result = solveQuadProg\n (augmentedCostMatrix, augmentedCostVector)\n (Just (augmentedEqMatrix, augmentedEqVector)) $\n Just ((-ineqMatrixWithTrustConstraints),\n (-ineqVectorWithTrustConstraints))\n\n in case result of\n Left e -> error $ show e\n Right (xNewAugmented, newMeritHomogenous) ->\n let xNew = subVector 0 numVariables xNewAugmented\n newMerit = newMeritHomogenous + costConstant\n\n -- Compute the merit of the approximation without regularization\n cost = evalQuadratic (costMatrix, costVector, costConstant) xNew\n ineqViolations =\n evalLinear (approxIneqMatrix, approxIneqVector) xNew\n ineqPenalty =\n penaltyParam * (sum $ map (max 0.0) $ toList ineqViolations)\n eqViolations = evalLinear (approxEqMatrix, approxEqVector) xNew\n eqPenalty =\n penaltyParam * (sum $ map abs $ toList eqViolations)\n meritNoReg = cost + ineqPenalty + eqPenalty\n\n -- DEBUG\n meritError = abs $ newMerit - meritNoReg\n in if meritError / (abs meritNoReg) > 0.5\n then error $ \"merits don't match!\" ++ show (meritNoReg, newMerit)\n else (xNew, meritNoReg)\n", "meta": {"hexsha": "b0f64c5c873872c938b588c967505f0b0ce0239a", "size": 11798, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib-src/Data/SQP.hs", "max_stars_repo_name": "giogadi/hs-trajopt", "max_stars_repo_head_hexsha": "3860780bb3d4d8b91f87c2c7d28e80388b66062b", "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": "lib-src/Data/SQP.hs", "max_issues_repo_name": "giogadi/hs-trajopt", "max_issues_repo_head_hexsha": "3860780bb3d4d8b91f87c2c7d28e80388b66062b", "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-src/Data/SQP.hs", "max_forks_repo_name": "giogadi/hs-trajopt", "max_forks_repo_head_hexsha": "3860780bb3d4d8b91f87c2c7d28e80388b66062b", "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.7239057239, "max_line_length": 89, "alphanum_fraction": 0.5962027462, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.39318755904606567}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# OPTIONS_GHC -Wno-deprecations #-}\nmodule BlueRipple.Model.PreferenceBayes\n (\n -- * MLE\n cgOptimize\n , cgOptimizeAD\n , invFisher\n , mleCovEigens\n , variances\n , covar\n , correlFromCov\n\n -- * MCMC\n , Sample\n , Chain\n , runMany\n -- * Re-exports\n , dispf\n , disps\n )\nwhere\n\nimport qualified Statistics.Types as S\nimport qualified Control.Foldl as FL\nimport Control.Lens.At ( IxValue\n , Index\n , Ixed\n )\nimport Control.Lens.Indexed ( FunctorWithIndex )\nimport Control.Monad ( sequence )\n\nimport qualified Numeric.AD as AD\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra ( dispf\n , disps\n )\nimport Numeric.MathFunctions.Constants\n ( m_ln_sqrt_2_pi )\nimport qualified Numeric.MCMC as MC\nimport Numeric (log)\n\nimport Math.Gamma ( gamma\n , Gamma\n )\nimport System.Random ( randomRIO )\nimport qualified Control.Concurrent as CC\nimport qualified Control.Concurrent.MVar as CC\nimport qualified Data.Vector.Unboxed as VU\nimport qualified Data.Vector.Storable as VS\nimport qualified Data.Vector.Generic as VG\nimport qualified Data.Vector as VB\n\nimport qualified Numeric.Optimization.Algorithms.HagerZhang05\n as CG\n\nimport qualified Numeric.Optimization.Algorithms.HagerZhang05.AD\n as CGAD\n\nnewtype ObservedVote = ObservedVote { dem :: Int}\n\ndata Pair a b = Pair !a !b\n\nbinomialNormalParams :: RealFrac a => VB.Vector Int -> VB.Vector a -> (a, a)\nbinomialNormalParams turnoutCounts demProbs =\n let np = VB.zip turnoutCounts demProbs\n meanVarUpdate :: RealFrac a => Pair a a -> (Int, a) -> Pair a a\n meanVarUpdate (Pair m v) (n, p) =\n let m' = realToFrac n * p in Pair (m + m') (v + m' * (1 - p))\n foldMeanVar = FL.Fold meanVarUpdate (Pair 0 0) id\n Pair m v = FL.fold foldMeanVar np\n in (m, v)\n\nlogBinomialObservedVote\n :: (RealFrac a, Floating a) => VB.Vector a -> (Int, VB.Vector Int) -> a\nlogBinomialObservedVote demProbs (demVote, turnoutCounts) =\n let (m, v) = binomialNormalParams turnoutCounts demProbs\n in negate $ log v + ((realToFrac demVote - m) ^ 2 / (2 * v))\n\ngradLogBinomialObservedVote\n :: (Floating a, RealFrac a)\n => VB.Vector a\n -> (Int, VB.Vector Int)\n -> VB.Vector a\ngradLogBinomialObservedVote demProbs (demVote, turnoutCounts) =\n let (m, v) = binomialNormalParams turnoutCounts demProbs\n np = VB.zip turnoutCounts demProbs\n dv = fmap (\\(n, p) -> let n' = realToFrac n in n' * (1 - 2 * p)) np\n dm = turnoutCounts\n dmv = VB.zip dm dv\n a1 = negate (1 / v) -- d (log v)\n a2 = (realToFrac demVote - m)\n a3 = (a2 * a2) / (2 * v * v)\n a4 = (a2 / v)\n in fmap (\\(dm, dv) -> (a1 + a3) * dv + a4 * realToFrac dm) dmv\n\nlogBinomialObservedVotes\n :: (Functor f, Foldable f, Floating a, RealFrac a)\n => f (Int, VB.Vector Int)\n -> VB.Vector a\n -> a\nlogBinomialObservedVotes votesAndTurnout demProbs =\n FL.fold FL.sum $ fmap (logBinomialObservedVote demProbs) votesAndTurnout\n\ngradLogBinomialObservedVotes\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> VB.Vector Double\ngradLogBinomialObservedVotes votesAndTurnout demProbs =\n let\n n = VG.length demProbs\n indexVector = VG.generate n id\n sumEach =\n sequenceA $ (\\n -> FL.premap (VG.! n) (FL.sum @Double)) <$> indexVector\n in\n FL.fold sumEach\n $ fmap (gradLogBinomialObservedVote demProbs) votesAndTurnout\n\ncgOptimize\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> IO (VS.Vector Double, CG.Result, CG.Statistics)\ncgOptimize votesAndVoters guess = do\n let params = CG.defaultParameters { CG.printFinal = False\n , CG.printParams = False\n , CG.verbose = CG.Quiet\n }\n grad_tol = 0.0000001\n CG.optimize\n params\n grad_tol\n guess\n (CG.VFunction (negate . logBinomialObservedVotes votesAndVoters))\n (CG.VGradient (fmap negate . gradLogBinomialObservedVotes votesAndVoters))\n Nothing\n\ncgOptimizeAD\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> IO (VB.Vector Double, CG.Result, CG.Statistics)\ncgOptimizeAD votesAndVoters guess = do\n let params = CG.defaultParameters { CG.printFinal = False\n , CG.printParams = False\n , CG.verbose = CG.Quiet\n }\n grad_tol = 0.0000001\n CGAD.optimize params\n grad_tol\n guess\n (negate . logBinomialObservedVotes votesAndVoters)\n\n-- I'm not sure about row/column order her. But it doesn't\n-- matter since the Hessian is symmetric.\nhessianLL\n :: (Foldable f, Functor f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> LA.Matrix Double\nhessianLL votesAndVoters x =\n LA.fromRows $ fmap VS.convert $ VB.toList $ AD.hessian\n (negate . logBinomialObservedVotes votesAndVoters)\n x\n\ninvFisher\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> LA.Matrix Double\ninvFisher votesAndVoters x = LA.inv $ hessianLL votesAndVoters x\n\nvariances\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> LA.Vector Double\nvariances votesAndVoters x = LA.takeDiag $ invFisher votesAndVoters x\n\ncovar\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> LA.Matrix Double\ncovar = invFisher\n\ncorrelFromCov :: LA.Matrix Double -> LA.Matrix Double\ncorrelFromCov cov =\n let vars = LA.takeDiag cov\n mISD = LA.diag $ LA.cmap (\\x -> 1 / sqrt x) vars\n in mISD LA.<> cov LA.<> mISD\n\ncorrel\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> LA.Matrix Double\ncorrel votesAndVoters x =\n let cov = invFisher votesAndVoters x\n sds = LA.cmap sqrt $ LA.takeDiag cov\n (rows, cols) = LA.size cov\n rho n m = cov `LA.atIndex` (n, m) / ((sds LA.! n) * (sds LA.! m))\n in LA.assoc\n (rows, cols)\n 0\n [ ((n, m), rho n m) | n <- [0 .. (rows - 1)], m <- [0 .. (cols - 1)] ]\n\n\nmleCovEigens\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> VB.Vector Double\n -> (LA.Vector Double, LA.Matrix Double)\nmleCovEigens votesAndVoters x =\n LA.eigSH $ LA.trustSym $ invFisher votesAndVoters x\n\n\nbetaDist :: (Floating a, RealFrac a, Gamma a) => a -> a -> a -> a\nbetaDist alpha beta x =\n let b = gamma (alpha + beta) / (gamma alpha + gamma beta)\n in if (x >= 0) && (x <= 1)\n then b * (x ** (alpha - 1)) * ((1 - x) ** (beta - 1))\n else 0\n\nlogBetaDist :: (Floating a, RealFrac a, Gamma a) => a -> a -> a -> a\nlogBetaDist alpha beta x =\n let lb = log $ gamma (alpha + beta) / (gamma alpha + gamma beta)\n in lb + (alpha - 1) * log x + (beta - 1) * log (1 - x)\n\nbetaPrior :: (Floating a, RealFrac a, Gamma a) => a -> a -> VB.Vector a -> a\nbetaPrior a b xs = FL.fold FL.product $ fmap (betaDist a b) xs\n\n{-\n--logBetaPrior :: Double -> Double -> [Double] -> Double\n--logBetaPrior = FL.fold FL.product $ fmap (logBetabDist a b) xs\n\nf :: [(Int, [Int])] -> [Double] -> Double\nf votesAndTurnout demProbs =\n let v = demProbs\n in (exp $ logProbObservedVotes votesAndTurnout v) * (betaPrior 2 2 v)\n-}\n\nlogBinomialWithPrior\n :: (Functor f, Foldable f, Floating a, RealFrac a, Gamma a)\n => f (Int, VB.Vector Int)\n -> VB.Vector a\n -> a\nlogBinomialWithPrior votesAndTurnout demProbs =\n let x = demProbs\n in logBinomialObservedVotes votesAndTurnout x + log (betaPrior 2 2 x)\n\ntype Sample = VB.Vector Double\ntype Chain = [Sample]\n\n-- TODO: withSystemRandom is deprecated in mwc-random but comes from \"declarative\" so would be a pain to fix.\nrunMCMC\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> Int\n -> Sample\n -> IO Chain\nrunMCMC votesAndTurnout numIters start =\n fmap (fmap MC.chainPosition) . MC.withSystemRandom . MC.asGenIO $ MC.chain\n numIters\n start\n (MC.frequency [(1, MC.hamiltonian 0.0001 10), (1, MC.hamiltonian 0.00001 5)]\n )\n (MC.Target (logBinomialWithPrior votesAndTurnout)\n (Just $ gradLogBinomialObservedVotes votesAndTurnout)\n )\n\n-- launch each action on its own thread, writing the result to an MVar.\n-- as each MVar is written to,\n-- place each result in the appropriate place in the structure.\n-- return the new structure when all results are available.\nsequenceConcurrently :: Traversable t => t (IO a) -> IO (t a)\nsequenceConcurrently actions = do\n let f :: IO a -> IO (CC.MVar a, CC.ThreadId)\n f action = do\n mvar <- newEmptyMVar\n threadId <- CC.forkIO (action >>= putMVar mvar)\n return (mvar, threadId)\n g :: (CC.MVar a, CC.ThreadId) -> IO a\n g (mvar, _) = takeMVar mvar\n forked <- traverse f actions -- IO (t (MVar a, ThreadId))\n traverse g forked\n\nrunMany\n :: (Functor f, Foldable f)\n => f (Int, VB.Vector Int)\n -> Int\n -> Int\n -> Int\n -> Int\n -> IO [Chain]\nrunMany votesAndTurnout nParams nChains nSamplesPerChain nBurnPerChain = do\n let\n randomStart :: Int -> IO Sample\n randomStart n = VG.fromList <$> replicateM n (randomRIO (0, 1))\n randomStarts :: Int -> Int -> IO [Sample]\n randomStarts n m = replicateM m (randomStart n)\n doEach =\n fmap (drop nBurnPerChain) . runMCMC votesAndTurnout nSamplesPerChain\n starts <- randomStarts nParams nChains\n sequenceConcurrently $ fmap doEach starts\n\n{-\ndata Normal = Normal { m :: Double, v :: Double } deriving (Show)\n\ninstance Semigroup Normal where\n (Normal m1 v1) <> (Normal m2 v2) = Normal (m1 + m2) (v1 + v2)\n\nlogNormalObservedVote :: [Normal] -> (Int, [Int]) -> Double\nlogNormalObservedVote demProbs (demVote, turnoutCounts) =\n let Normal m' v' = mconcat $ fmap (\\(t,Normal m v) -> Normal (t*m) (v*m))$ zip turnoutCounts demProbs\n in negate $ log v' + ((realToFrac demVote - m')) ^ 2 / (2 * v'))\n\n\ngradLogNormalObservedVote :: [Normal] -> (Int, [Int]) -> [Normal]\ngradLogNormalObservedVote demProbs (demVote, turnoutCounts) =\n let Normal m' v' = mconcat $ fmap (\\(t,Normal m v) -> Normal (t*m) (v*m))$ zip turnoutCounts demProbs\n np = zip turnoutCounts demProbs\n dv = fmap (\\(n, p) -> let n' = realToFrac n in n' * (1 - 2 * p)) np\n dm = turnoutCounts\n dmv = zip dm dv\n a1 = negate (1 / v) -- d (log v)\n a2 = (realToFrac demVote - m)\n a3 = (a2 * a2) / (2 * v * v)\n a4 = (a2 / v)\n in fmap (\\(dm, dv) -> (a1 + a3) * dv + a4 * realToFrac dm) dmv\n\nlogBinomialObservedVotes :: [(Int, [Int])] -> [Double] -> Double\nlogBinomialObservedVotes votesAndTurnout demProbs =\n FL.fold FL.sum $ fmap (logBinomialObservedVote demProbs) votesAndTurnout\n\ngradLogBinomialObservedVotes :: [(Int, [Int])] -> [Double] -> [Double]\ngradLogBinomialObservedVotes votesAndTurnout demProbs =\n let n = length demProbs\n sumEach =\n sequenceA\n $ fmap (\\n -> FL.premap (!! n) (FL.sum @Double))\n $ [0 .. (n - 1)]\n in FL.fold sumEach $ fmap (gradLogBinomialObservedVote demProbs) votesAndTurnout\n\n-}\n{-\n--gradLogProbObservedVotes2 :: [(Int, [Int])] -> [Double] -> [Double]\ngradLogProbObservedVotes2 votesAndTurnout =\n grad (logProbObservedVotes votesAndTurnout)\n-}\n\n\n\n{-\ndata VPSummary = VPSummary { mean :: Double, stDev :: Double, rHat :: Double } deriving (Show)\n\nsummarize :: (Sample -> Double) -> [Chain] -> VPSummary -- FL.Fold Chain VPSummary\nsummarize integrandF chains =\n -- build up the fold\n let n = (length $ head chains) `div` 2\n splitChains :: [Chain]\n splitChains =\n concat $ fmap (\\c -> let (a, b) = splitAt n c in [a, b]) chains\n meanVarF = (,) <$> FL.mean <*> FL.variance\n meanVars = fmap (FL.fold (FL.premap integrandF meanVarF)) splitChains\n bVar = FL.fold (FL.premap fst FL.variance) meanVars -- variance of the means\n wVar = FL.fold (FL.premap snd FL.mean) meanVars -- mean of the variances\n v = (realToFrac n / realToFrac (n + 1)) * wVar + bVar\n rhat = sqrt (v / wVar)\n in VPSummary (FL.fold (FL.premap fst FL.mean) meanVars)\n (FL.fold (FL.premap snd FL.mean) meanVars)\n rhat\n\n\n-- . foldTo (meanOfVariances, varianceOfMeans) . fmap (compute meanVar . fmap integrandF) . splitChains\n-}\n", "meta": {"hexsha": "3faa844b39932efdb6f3f028a43f6ceb628f82e3", "size": 13138, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/BlueRipple/Model/PreferenceBayes.hs", "max_stars_repo_name": "blueripple/preference-model", "max_stars_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T11:32:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T11:32:48.000Z", "max_issues_repo_path": "src/BlueRipple/Model/PreferenceBayes.hs", "max_issues_repo_name": "blueripple/preference-model", "max_issues_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BlueRipple/Model/PreferenceBayes.hs", "max_forks_repo_name": "blueripple/preference-model", "max_forks_repo_head_hexsha": "beae97c2d854830bc0e9027609e54166f93d976b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4829396325, "max_line_length": 109, "alphanum_fraction": 0.5989496118, "num_tokens": 3912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3926683912861458}} {"text": "{-# language FlexibleInstances #-}\n{-# language KindSignatures #-}\n{-# language FunctionalDependencies #-}\n{-# language LambdaCase #-}\n{-# language MultiParamTypeClasses #-}\n{-# language Rank2Types #-}\n{-# language TupleSections #-}\nmodule Main where\n\nimport Control.Monad.Reader\nimport Data.Complex\nimport Data.Functor.Const\nimport Data.Functor.Contravariant\nimport Data.Functor.Identity\nimport Data.Monoid (First(..))\nimport Data.Profunctor\nimport Data.Profunctor.Unsafe ((#.), (.#))\nimport Data.Tagged\nimport Data.Void (absurd, vacuous)\n\n\ntype Equality s t a b\n = forall (p :: * -> * -> *) f.\n p a (f b) -> p s (f t)\n\ntype Lens s t a b\n = forall f. Functor f\n => (a -> f b) -> s -> f t\n\ntype Traversal s t a b\n = forall f. Applicative f\n => (a -> f b) -> s -> f t\n\ntype Iso s t a b\n = forall p f. (Functor f, Profunctor p)\n => p a (f b) -> p s (f t)\n\ntype Prism s t a b\n = forall p f. (Applicative f, Choice p)\n => p a (f b) -> p s (f t)\n\ntype Getter s a\n = forall f. (Functor f, Contravariant f)\n => (a -> f a) -> s -> f s\n\ntype Fold s a\n = forall f. (Applicative f, Contravariant f)\n => (a -> f a) -> s -> f s\n\ntype Optic p f s t a b\n = p a (f b) -> p s (f t)\ntype Optic' p f t b\n = p b (f b) -> p t (f t)\n\ntype Review t b\n = Tagged b (Identity b) -> Tagged t (Identity t)\n-- in other words,\ntype Review' t b\n = Optic' Tagged Identity t b\n\n-- Traversal:\n--\n-- We strengthen `Functor` to `Applicative`. Why?\n--\n-- Clue: note that\n--\n-- traverse :: Applicative f => (a -> f b) -> t a -> f (t b)\n-- ~ Traversable f => Traversal (f a) (f b) a b\n--\n-- So, instead we can ask why does `traverse` require `Applicative`?\n--\n-- The instance for lists is informative:\n--\n-- instance Traversable [] where\n-- traverse _ [] = pure []\n-- traverse f (x:xs) = (:) <$> f x <*> traverse f xs\n--\n-- Every lens is a valid Traversal. Witness:\n\nlensToTraversal :: Lens s t a b -> Traversal s t a b\nlensToTraversal = id\n\n--\n-- Iso:\n--\n-- We generalize `->` to `(Profunctor p =>) p`. Why?\n--\n-- One answer is that using `Exchange` (a `Profunctor`) allows us to reverse\n-- the `Iso` and extract its parts.\n--\n-- Prism:\n--\n-- Here `f` is an `Applicative` and `p` is a `Choice`. Why?\n--\n-- First of all:\n-- * Every `Prism`: Applicative f, Choice p\n-- is a valid v v\n-- `Traversal`: Applicative f\n--\n-- witness:\n\nprismToTraversal :: Prism s t a b -> Traversal s t a b\nprismToTraversal = id\n\n--\n-- Here `Prism` adds `Choice p`, meaning TODO\n--\n-- * Every `Iso`: Functor f, Profunctor p\n-- is a valid v v\n-- `Prism`: Applicative f, Choice p\n--\n-- witness:\n\nisoToPrism :: Iso s t a b -> Prism s t a b\nisoToPrism = id\n\n-- Iso's are everything actually:\n\nisoToLens :: Iso s t a b -> Lens s t a b\nisoToLens = id\n\nisoToTraversal :: Iso s t a b -> Traversal s t a b\nisoToTraversal = id\n\nisoToGetter :: Iso s s a a -> Getter s a\nisoToGetter = id\n\nisoToFold :: Iso s s a a -> Fold s a\nisoToFold = id\n\nisoToReview :: Iso s s a a -> Review s a\nisoToReview = id\n\n-- Except an `Equality`, that is. An `Equality` is an `Iso`:\n\nequalityToIso :: Equality s t a b -> Iso s t a b\nequalityToIso = id\n\n-- An Equality is a witness that a ~ s and b ~ t.\n--\n--\n-- Here `Prism` strenthens the constraints:\n-- * `Functor` to `Applicative` because it doesn't touch exactly one position\n-- * `Profunctor` to `Choice` because TODO\n--\n-- Getter:\n--\n-- A getter describes how to retrieve a single value\n--\n-- > for f to be both Functor and Contravariant implies `f a` doesn't contain\n-- > any `a`s at all!\n--\n-- citation: https://www.reddit.com/r/haskell/comments/5vb6x1/how_do_i_learn_lensinternals/de0uz1v\n-- Witness:\n\ncoerceGetterF :: (Functor f, Contravariant f) => f a -> f b\ncoerceGetterF = vacuous . contramap absurd\n\n-- Fold:\n--\n-- A `Fold` describes how to retrieve multiple values\n--\n-- Note how conspicuously `Fold` and `Getter` are:\n--\n-- TODO: understand\n-- \"A `Getter` is a legal `Fold` that just ignores the supplied `Monoid`\n--\n-- * Every `Getter`: Functor f, Contravariant f\n-- is a valid v v\n-- `Fold`: Applicative f, Contravariant f\n--\n-- Witness:\n\ngetterToFold :: Getter s a -> Fold s a\ngetterToFold = id\n\n-- Like `Getter`, note that the functor used in the `Fold` can't contain any\n-- values:\n\ncoerceFoldF :: (Applicative f, Contravariant f) => f a -> f b\ncoerceFoldF = vacuous . contramap absurd\n\n-- A \"is a limited form of a `Prism` that can only be used for `re` operations.\n-- Witness:\n\nprismToReview :: Prism' t b -> Review t b\nprismToReview = id\n\ntype Simple f s a = f s s a a\ntype Equality' s a = Simple Equality s a\ntype Lens' s a = Simple Lens s a\ntype Iso' s a = Simple Iso s a\ntype Prism' s a = Simple Prism s a\ntype Getting r s a = (a -> Const r a) -> s -> Const r s\n\niso :: (s -> a) -> (b -> t) -> Iso s t a b\niso sa bt = dimap sa (fmap bt)\n\n-- used to provide access to the two parts of an iso\ndata Exchange a b s t = Exchange (s -> a) (b -> t)\n\ninstance Functor (Exchange a b s) where\n fmap g' (Exchange f g) = Exchange f (g' . g)\n\ninstance Profunctor (Exchange a b) where\n dimap f' g' (Exchange f g) = Exchange (f . f') (g' . g)\n\nwithIso :: Iso s t a b -> ((s -> a) -> (b -> t) -> r) -> r\nwithIso ai k = case ai (Exchange id Identity) of\n Exchange sa bt -> k sa (runIdentity #. bt)\n\n-- used to provide access to the two parts of a prism\ndata Market a b s t = Market (b -> t) (s -> Either t a)\n\ninstance Functor (Market a b s) where\n fmap h (Market f g) = Market (h . f) (either (Left . h) Right . g)\n\ninstance Profunctor (Market a b) where\n dimap f' g' (Market f g) = Market (g' . f) (left' g' . g . f')\n\ninstance Choice (Market a b) where\n left' (Market f g) = Market (Left . f) $ \\case\n Left x -> case g x of\n Left y -> Left (Left y)\n Right y -> Right y\n Right c -> Left (Right c)\n -- TODO: implement right'\n\nwithPrism :: Prism s t a b -> ((b -> t) -> (s -> Either t a) -> r) -> r\nwithPrism p k = case p (Market Identity Right) of\n Market bt sa -> k (runIdentity #. bt) (left' runIdentity . sa)\n\nprism :: (b -> t) -> (s -> Either t a) -> Prism s t a b\nprism bt seta = dimap seta (either pure (fmap bt)) . right'\n\nmatching :: Prism s t a b -> s -> Either t a\nmatching k = withPrism k $ \\_ seta -> seta\n\n_Left :: Prism (Either a c) (Either b c) a b\n_Left = prism Left $ either Right (Left . Right)\n\n_Right :: Prism (Either c a) (Either c b) a b\n_Right = prism Right $ either (Left . Left) Right\n\n-- TODO: rewrite / become more comfortable with this section\n\nre :: Review t b -> Getter b t\nre p = to (runIdentity #. unTagged #. p .# Tagged .# Identity)\n\nto :: (Profunctor p, Contravariant f) => (s -> a) -> Optic' p f s a\nto k = dimap k (contramap k)\n\nreviewSimple :: Prism' s a -> a -> s\nreviewSimple r = runIdentity . unTagged . r . Tagged . Identity\n\nreview :: MonadReader b m => Optic' Tagged Identity t b -> m t\nreview r = asks $ runIdentity . unTagged . r . Tagged . Identity\n\nfoldMapOf :: Getting r s a -> (a -> r) -> s -> r\nfoldMapOf l f = getConst #. l (Const #. f)\n\npreview :: Prism' s a -> s -> Maybe a\npreview p s = getFirst #. foldMapOf p (First #. Just) $ s\n\n(^?) :: s -> Prism' s a -> Maybe a\n(^?) s p = preview p s\n\n--\n\nfrom :: Iso s t a b -> Iso b a t s\nfrom l = withIso l $ \\ sa bt -> iso bt sa\n\nview :: Lens s t a b -> s -> a\nview l s = getConst (l Const s)\n\nover :: Lens s t a b -> (a -> b) -> s -> t\nover l f = runIdentity . l (Identity . f)\n\nset :: Lens s t a b -> b -> s -> t\nset l = over l . const\n\nlens :: (s -> a) -> (s -> b -> t) -> Lens s t a b\nlens get' set' f s = set' s <$> f (get' s)\n\nrealLens, realLens' :: RealFloat a => Lens' (Complex a) a\nrealLens f (r :+ i) = fmap (:+ i) (f r)\n\nimagLens, imagLens' :: RealFloat a => Lens' (Complex a) a\nimagLens f (r :+ i) = fmap (r :+) (f i)\n\nrealLens' = lens (\\(r :+ _) -> r) (\\(_ :+ i) r -> r :+ i)\nimagLens' = lens (\\(_ :+ i) -> i) (\\(r :+ _) i -> r :+ i)\n\n(<&>) :: Functor f => f a -> (a -> b) -> f b\n(<&>) = flip fmap\n\nclass Field1 s t a b | s -> a, t -> b, s b -> t, t a -> s where\n _1 :: Lens s t a b\n\ninstance Field1 (a, b) (a', b) a a' where\n _1 f ~(a, b) = f a <&> \\a' -> (a', b)\n\ninstance Field1 (a, b, c) (a', b, c) a a' where\n _1 k ~(a, b, c) = k a <&> \\a' -> (a', b, c)\n\nclass Field2 s t a b | s -> a, t -> b, s b -> t, t a -> s where\n _2 :: Lens s t a b\n\ninstance Field2 (a, b) (a, b') b b' where\n _2 f ~(a, b) = f b <&> \\b' -> (a, b')\n\ninstance Field2 (a, b, c) (a, b', c) b b' where\n _2 k ~(a, b, c) = k b <&> \\b' -> (a, b', c)\n\nmain :: IO ()\nmain = do\n print $ set realLens (1 :: Double) (0 :+ 1)\n print $ view _1 ('x', 'y', 'z')\n print $ view _2 $ set _2 False ('x', 'y', 'z')\n", "meta": {"hexsha": "1534d8ab7b6b919093e79fd010381b2f19f06693", "size": 8773, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Main.hs", "max_stars_repo_name": "joelburget/mylens", "max_stars_repo_head_hexsha": "baaa855d938bb99c5f0efc000b5e44c03c433bcb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-09-09T21:07:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-20T02:18:41.000Z", "max_issues_repo_path": "src/Main.hs", "max_issues_repo_name": "joelburget/mylens", "max_issues_repo_head_hexsha": "baaa855d938bb99c5f0efc000b5e44c03c433bcb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "joelburget/mylens", "max_forks_repo_head_hexsha": "baaa855d938bb99c5f0efc000b5e44c03c433bcb", "max_forks_repo_licenses": ["BSD-3-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.415625, "max_line_length": 98, "alphanum_fraction": 0.5793913143, "num_tokens": 2950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3920482007092462}} {"text": "-- | An attempt at writing QuickHull in quintessential Haskell.\n-- | I am just writing the simple 2D version for now.\n\nmodule QuickHull (qhull2D) where\n\nimport Control.Arrow\nimport Control.Monad\nimport Data.DList (DList)\nimport qualified Data.DList as D\nimport Data.Foldable (asum)\nimport qualified Data.List as L (splitAt)\nimport Data.Maybe\nimport Data.Ord\nimport qualified Data.Vector as V\nimport Data.Vector.Algorithms.Intro as I\nimport qualified Data.Vector.Unboxed as UV\nimport Numeric.LinearAlgebra (peps)\n\ndata Region2D\n = R021\n | R201\n | R012\n deriving (Show,Eq,Ord)\n\nqhull2D\n :: V.Vector (UV.Vector Double)\n -> [UV.Vector Double]\nqhull2D vecs\n | V.length vecs < 4 = V.toList vecs\n | otherwise =\n D.toList $ D.fromList [ax, bx, ay, by] `mappend`\n qhull2DHelper ax by regU021 `mappend`\n qhull2DHelper by bx regU201 `mappend`\n qhull2DHelper bx ay regB201 `mappend`\n qhull2DHelper ax ay regB021\n where\n ((regU021, regU201), (regB021, regB201)) =\n (assignTwoRegions *** assignTwoRegions) . splitValidQuad ax by bx ay $\n vecs\n [ax, bx, ay, by] = qhull2DInit vecs\n\nqhull2DInit :: V.Vector (UV.Vector Double) -> [UV.Vector Double]\nqhull2DInit points =\n [ V.unsafeIndex points ax\n , V.unsafeIndex points bx\n , V.unsafeIndex points ay\n , V.unsafeIndex points by\n ]\n where\n (ax, bx) = minMaxXIndexes points\n (ay, by) = minMaxYIndexes points\n\nqhull2DHelper :: UV.Vector Double -> UV.Vector Double -> V.Vector (UV.Vector Double) -> DList (UV.Vector Double)\nqhull2DHelper v w vecs\n | V.length vecs > 1 =\n D.cons maxP $\n qhull2DHelper w0 w1 r021 `mappend`\n qhull2DHelper w0 w2 r012 `mappend`\n qhull2DHelper w1 w2 r201\n | V.length vecs == 1 =\n D.singleton $\n V.unsafeHead vecs\n | otherwise = D.empty\n where\n (r021, r201, r012) = assignThreeRegions $ splitValidTri w0 w1 w2 testpts\n [w0, w1, w2] = V.toList . sortTriangle v w $ maxP\n testpts = V.ifilter (\\i _ -> i /= maxInd) vecs\n (maxInd, maxP) = maxDistPt v w vecs\n\nassignTwoRegions :: V.Vector (Region2D, UV.Vector Double)\n -> (V.Vector (UV.Vector Double), V.Vector (UV.Vector Double))\nassignTwoRegions = (,) <$> rMap R021 <*> rMap R201\n\nassignThreeRegions\n :: V.Vector (Region2D, UV.Vector Double)\n -> (V.Vector (UV.Vector Double), V.Vector (UV.Vector Double), V.Vector (UV.Vector Double))\nassignThreeRegions = (,,) <$> rMap R021 <*> rMap R201 <*> rMap R012\n\nrMap\n :: Eq b\n => b -> V.Vector (b, UV.Vector Double) -> V.Vector (UV.Vector Double)\nrMap r = V.map snd . V.filter ((== r) . fst)\n\n-- Sorts points by their x-coordinates\nsortTriangle\n :: UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> V.Vector (UV.Vector Double)\nsortTriangle u v w = V.modify (I.sortBy (comparing UV.unsafeHead)) r\n where\n r = V.fromList [u, v, w]\n\ninTriangleInterior\n :: UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> (Bool, Double, [Double])\ninTriangleInterior a b c p = (,,) <$> same' . sum <*> signum . sum <*> id $ vv\n where\n vv = [test' ab aP, test' bc bp, test' ca cp]\n ab = diff b a\n bc = diff c b\n ca = diff a c\n aP = diff p a\n bp = diff p b\n cp = diff p c\n diff = UV.zipWith (-)\n same' = (||) <$> (== 3) <*> (== -3)\n test' u v = signum $ UV.foldl1' (-) $ UV.zipWith (*) u (UV.reverse v)\n\ninQuadInterior\n :: UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> (Bool, Double, [Double])\ninQuadInterior a b c d p = (,,) <$> same' . sum <*> signum . sum <*> id $ vv\n where\n vv = [test' ab aP, test' bc bp, test' cd cp, test' da dp]\n ab = diff b a\n bc = diff c b\n cd = diff d c\n da = diff a d\n aP = diff p a\n bp = diff p b\n cp = diff p c\n dp = diff p d\n diff = UV.zipWith (-)\n same' = (||) <$> (== 4) <*> (== (-4))\n test' u v = signum $ UV.foldl1' (-) $ UV.zipWith (*) u (UV.reverse v)\n\ntestInRegionQuad\n :: UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> (Maybe Region2D, Maybe Region2D)\ntestInRegionQuad v0 v1 v2 v3 p = reg\n where\n (inQuad,signSum,regs) = inQuadInterior v0 v1 v2 v3 p\n reg =\n if inQuad\n then (Nothing, Nothing)\n else (asum *** asum) . L.splitAt 2 . zipWith ($) regAssign $ regs\n regAssign =\n [ toMaybe R021 . (/= signSum)\n , toMaybe R201 . (/= signSum)\n , toMaybe R021 . (/= signSum)\n , toMaybe R201 . (/= signSum)]\n\nsplitValidQuad\n :: UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> V.Vector (UV.Vector Double)\n -> (V.Vector (Region2D, UV.Vector Double), V.Vector (Region2D, UV.Vector Double))\nsplitValidQuad u v w x =\n (V.map fromJust . V.filter isJust *** V.map fromJust . V.filter isJust) .\n V.unzip .\n V.map\n ((\\v' (a,b) ->\n (flip (,) v' <$> a, flip (,) v' <$> b)) `ap`\n testInRegionQuad u v w x)\n\ntoMaybe :: a -> Bool -> Maybe a\ntoMaybe a pred' =\n if pred'\n then Just a\n else Nothing\n\ntestInRegionTri\n :: UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> Maybe Region2D\ntestInRegionTri v0 v1 v2 p = reg\n where\n (inTriangle,signSum,regs) = inTriangleInterior v0 v1 v2 p\n reg =\n if inTriangle\n then Nothing\n else asum . zipWith ($) regAssign $ regs\n regAssign =\n [ toMaybe R021 . (/= signSum)\n , toMaybe R201 . (/= signSum)\n , toMaybe R012 . (/= signSum)]\n\nsplitValidTri\n :: UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> V.Vector (UV.Vector Double)\n -> V.Vector (Region2D, UV.Vector Double)\nsplitValidTri u v w =\n V.map fromJust .\n V.filter isJust . V.map ((fmap . flip (,)) `ap` testInRegionTri u v w)\n\nminMaxXIndexes :: V.Vector (UV.Vector Double) -> (Int, Int)\nminMaxXIndexes = minmax . sortOnFirst . vzip . V.map UV.unsafeHead\n where\n vzip v = V.zip v (V.enumFromN 0 $ V.length v)\n\nminMaxYIndexes :: V.Vector (UV.Vector Double) -> (Int, Int)\nminMaxYIndexes = minmax . sortOnFirst . vzip . V.map UV.unsafeLast\n where\n vzip v = V.zip v (V.enumFromN 0 $ V.length v)\n\nminmax :: V.Vector (Double, Int) -> (Int, Int)\nminmax = uncurry (,) . (snd . V.unsafeHead &&& snd . V.unsafeLast)\n\nsortOnFirst\n :: Ord a\n => V.Vector (a, b) -> V.Vector (a, b)\nsortOnFirst = V.modify (I.sortBy (comparing fst))\n\nmaxDistPt\n :: UV.Vector Double\n -> UV.Vector Double\n -> V.Vector (UV.Vector Double)\n -> (Int, UV.Vector Double)\nmaxDistPt mn mx =\n getMax . ap V.zip (V.map $ internalBisect mn mx . snd) . V.indexed\n where\n getMax = fst . V.maximumBy (comparing snd)\n\ninternalBisect :: UV.Vector Double\n -> UV.Vector Double\n -> UV.Vector Double\n -> Double\ninternalBisect u v w = 2 * sqrt (b * c * s * (b + c)) / (b + c + peps)\n where\n dist' x = sqrt . UV.sum . UV.map (join (*)) . UV.zipWith (-) x\n a = dist' u v\n b = dist' v w\n c = dist' u w\n s = a + b + c\n", "meta": {"hexsha": "21770cfa4610cb1c22aac189502ab5ffb3a70c90", "size": 7381, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/QuickHull.hs", "max_stars_repo_name": "emmanueldenloye/QuickHull", "max_stars_repo_head_hexsha": "73411a840c940d538269f1129666ace8e763c22e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-02-26T05:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T18:04:59.000Z", "max_issues_repo_path": "src/QuickHull.hs", "max_issues_repo_name": "emmanueldenloye/QuickHull", "max_issues_repo_head_hexsha": "73411a840c940d538269f1129666ace8e763c22e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-02-26T05:50:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-26T05:50:32.000Z", "max_forks_repo_path": "src/QuickHull.hs", "max_forks_repo_name": "emmanueldenloye/QuickHull", "max_forks_repo_head_hexsha": "73411a840c940d538269f1129666ace8e763c22e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-02-26T05:16:26.000Z", "max_forks_repo_forks_event_max_datetime": "2016-02-26T05:16:26.000Z", "avg_line_length": 30.3744855967, "max_line_length": 112, "alphanum_fraction": 0.5835252676, "num_tokens": 2294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3906873192327603}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ViewPatterns #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\n-----------------------------------------------------------------------------\n{- |\nModule : Internal.Util\nCopyright : (c) Alberto Ruiz 2013\nLicense : BSD3\nMaintainer : Alberto Ruiz\nStability : provisional\n\n-}\n-----------------------------------------------------------------------------\n\nmodule Internal.Util(\n\n -- * Convenience functions\n vector, matrix,\n disp,\n formatSparse,\n approxInt,\n dispDots,\n dispBlanks,\n formatShort,\n dispShort,\n zeros, ones,\n diagl,\n row,\n col,\n (&), (¦), (|||), (——), (===),\n (?), (¿),\n Indexable(..), size,\n Numeric,\n rand, randn,\n cross,\n norm,\n ℕ,ℤ,ℝ,ℂ,iC,\n Normed(..), norm_Frob, norm_nuclear,\n magnit,\n normalize,\n mt,\n (~!~),\n pairwiseD2,\n rowOuters,\n null1,\n null1sym,\n -- * Convolution\n -- ** 1D\n corr, conv, corrMin,\n -- ** 2D\n corr2, conv2, separable,\n block2x2,block3x3,view1,unView1,foldMatrix,\n gaussElim_1, gaussElim_2, gaussElim,\n luST, luSolve', luSolve'', luPacked', luPacked'',\n invershur\n) where\n\nimport Control.Arrow ((&&&), (***))\nimport Control.Monad (forM_, when)\nimport Data.Complex\nimport Data.Function (on)\nimport Data.List (foldl', intercalate, sortBy)\nimport Data.List.Split (splitOn)\nimport Internal.Algorithms hiding (Normed, linearSolve', luPacked', luSolve')\nimport Internal.Container\nimport Internal.Convolution\nimport Internal.Element\nimport Internal.IO\nimport Internal.Matrix hiding (size)\nimport Internal.Numeric\nimport Internal.Random\nimport Internal.ST\nimport Internal.Vector\nimport Internal.Vectorized\nimport Numeric.Matrix ()\nimport Numeric.Vector ()\nimport Text.Printf\n#if MIN_VERSION_base(4,11,0)\nimport Prelude hiding ((<>))\n#endif\n\ntype ℝ = Float\ntype ℕ = Int\ntype ℤ = Int\ntype ℂ = Complex Float\n\n-- | imaginary unit\niC :: C\niC = 0:+1\n\n{- | Create a real vector.\n\n>>> vector [1..5]\n[1.0,2.0,3.0,4.0,5.0]\nit :: Vector R\n\n-}\nvector :: [R] -> Vector R\nvector = fromList\n\n{- | Create a real matrix.\n\n>>> matrix 5 [1..15]\n(3><5)\n [ 1.0, 2.0, 3.0, 4.0, 5.0\n , 6.0, 7.0, 8.0, 9.0, 10.0\n , 11.0, 12.0, 13.0, 14.0, 15.0 ]\n\n-}\nmatrix\n :: Int -- ^ number of columns\n -> [R] -- ^ elements in row order\n -> Matrix R\nmatrix c = reshape c . fromList\n\n\n{- | print a real matrix with given number of digits after the decimal point\n\n>>> disp 5 $ ident 2 / 3\n2x2\n0.33333 0.00000\n0.00000 0.33333\n\n-}\ndisp :: Int -> Matrix Float -> IO ()\n\ndisp n = putStr . dispf n\n\n\n{- | create a real diagonal matrix from a list\n\n>>> diagl [1,2,3]\n(3><3)\n [ 1.0, 0.0, 0.0\n , 0.0, 2.0, 0.0\n , 0.0, 0.0, 3.0 ]\n\n-}\ndiagl :: [Float] -> Matrix Float\ndiagl = diag . fromList\n\n-- | a real matrix of zeros\nzeros :: Int -- ^ rows\n -> Int -- ^ columns\n -> Matrix Float\nzeros r c = konst 0 (r,c)\n\n-- | a real matrix of ones\nones :: Int -- ^ rows\n -> Int -- ^ columns\n -> Matrix Float\nones r c = konst 1 (r,c)\n\n-- | concatenation of real vectors\ninfixl 3 &\n(&) :: Vector Float -> Vector Float -> Vector Float\na & b = vjoin [a,b]\n\n{- | horizontal concatenation\n\n>>> ident 3 ||| konst 7 (3,4)\n(3><7)\n [ 1.0, 0.0, 0.0, 7.0, 7.0, 7.0, 7.0\n , 0.0, 1.0, 0.0, 7.0, 7.0, 7.0, 7.0\n , 0.0, 0.0, 1.0, 7.0, 7.0, 7.0, 7.0 ]\n\n-}\ninfixl 3 |||\n(|||) :: Element t => Matrix t -> Matrix t -> Matrix t\na ||| b = fromBlocks [[a,b]]\n\n-- | a synonym for ('|||') (unicode 0x00a6, broken bar)\ninfixl 3 ¦\n(¦) :: Matrix Float -> Matrix Float -> Matrix Float\n(¦) = (|||)\n\n\n-- | vertical concatenation\n--\n(===) :: Element t => Matrix t -> Matrix t -> Matrix t\ninfixl 2 ===\na === b = fromBlocks [[a],[b]]\n\n-- | a synonym for ('===') (unicode 0x2014, em dash)\n(——) :: Matrix Float -> Matrix Float -> Matrix Float\ninfixl 2 ——\n(——) = (===)\n\n\n-- | create a single row real matrix from a list\n--\n-- >>> row [2,3,1,8]\n-- (1><4)\n-- [ 2.0, 3.0, 1.0, 8.0 ]\n--\nrow :: [Float] -> Matrix Float\nrow = asRow . fromList\n\n-- | create a single column real matrix from a list\n--\n-- >>> col [7,-2,4]\n-- (3><1)\n-- [ 7.0\n-- , -2.0\n-- , 4.0 ]\n--\ncol :: [Float] -> Matrix Float\ncol = asColumn . fromList\n\n{- | extract rows\n\n>>> (20><4) [1..] ? [2,1,1]\n(3><4)\n [ 9.0, 10.0, 11.0, 12.0\n , 5.0, 6.0, 7.0, 8.0\n , 5.0, 6.0, 7.0, 8.0 ]\n\n-}\ninfixl 9 ?\n(?) :: Element t => Matrix t -> [Int] -> Matrix t\n(?) = flip extractRows\n\n{- | extract columns\n\n(unicode 0x00bf, inverted question mark, Alt-Gr ?)\n\n>>> (3><4) [1..] ¿ [3,0]\n(3><2)\n [ 4.0, 1.0\n , 8.0, 5.0\n , 12.0, 9.0 ]\n\n-}\ninfixl 9 ¿\n(¿) :: Element t => Matrix t -> [Int] -> Matrix t\n(¿)= flip extractColumns\n\n\ncross :: Product t => Vector t -> Vector t -> Vector t\n-- ^ cross product (for three-element vectors)\ncross x y | dim x == 3 && dim y == 3 = fromList [z1,z2,z3]\n | otherwise = error $ \"the cross product requires 3-element vectors (sizes given: \"\n ++show (dim x)++\" and \"++show (dim y)++\")\"\n where\n [x1,x2,x3] = toList x\n [y1,y2,y3] = toList y\n z1 = x2*y3-x3*y2\n z2 = x3*y1-x1*y3\n z3 = x1*y2-x2*y1\n\n{-# SPECIALIZE cross :: Vector Float -> Vector Float -> Vector Float #-}\n{-# SPECIALIZE cross :: Vector (Complex Float) -> Vector (Complex Float) -> Vector (Complex Float) #-}\n\nnorm :: Vector Float -> Float\n-- ^ 2-norm of real vector\nnorm = pnorm PNorm2\n\n-- | p-norm for vectors, operator norm for matrices\nclass Normed a\n where\n norm_0 :: a -> R\n norm_1 :: a -> R\n norm_2 :: a -> R\n norm_Inf :: a -> R\n\n\ninstance Normed (Vector R)\n where\n norm_0 v = sumElements (step (abs v - scalar (eps*normInf v)))\n norm_1 = pnorm PNorm1\n norm_2 = pnorm PNorm2\n norm_Inf = pnorm Infinity\n\ninstance Normed (Vector C)\n where\n norm_0 v = sumElements (step (fst (fromComplex (abs v)) - scalar (eps*normInf v)))\n norm_1 = pnorm PNorm1\n norm_2 = pnorm PNorm2\n norm_Inf = pnorm Infinity\n\ninstance Normed (Matrix R)\n where\n norm_0 = norm_0 . flatten\n norm_1 = pnorm PNorm1\n norm_2 = pnorm PNorm2\n norm_Inf = pnorm Infinity\n\ninstance Normed (Matrix C)\n where\n norm_0 = norm_0 . flatten\n norm_1 = pnorm PNorm1\n norm_2 = pnorm PNorm2\n norm_Inf = pnorm Infinity\n\ninstance Normed (Vector I)\n where\n norm_0 = fromIntegral . sumElements . step . abs\n norm_1 = fromIntegral . norm1\n norm_2 v = sqrt . fromIntegral $ dot v v\n norm_Inf = fromIntegral . normInf\n\ninstance Normed (Vector Z)\n where\n norm_0 = fromIntegral . sumElements . step . abs\n norm_1 = fromIntegral . norm1\n norm_2 v = sqrt . fromIntegral $ dot v v\n norm_Inf = fromIntegral . normInf\n\n-- instance Normed (Vector Float)\n-- where\n-- norm_0 = norm_0 . double\n-- norm_1 = norm_1 . double\n-- norm_2 = norm_2 . double\n-- norm_Inf = norm_Inf . double\n\n-- instance Normed (Vector (Complex Float))\n-- where\n-- norm_0 = norm_0 . double\n-- norm_1 = norm_1 . double\n-- norm_2 = norm_2 . double\n-- norm_Inf = norm_Inf . double\n\n-- | Frobenius norm (Schatten p-norm with p=2)\nnorm_Frob :: (Normed (Vector t), Element t) => Matrix t -> R\nnorm_Frob = norm_2 . flatten\n\n-- | Sum of singular values (Schatten p-norm with p=1)\nnorm_nuclear :: Field t => Matrix t -> R\nnorm_nuclear = sumElements . singularValues\n\n{- | Check if the absolute value or complex magnitude is greater than a given threshold\n\n>>> magnit 1E-6 (1E-12 :: R)\nFalse\n>>> magnit 1E-6 (3+iC :: C)\nTrue\n>>> magnit 0 (3 :: I ./. 5)\nTrue\n\n-}\nmagnit :: (Element t, Normed (Vector t)) => R -> t -> Bool\nmagnit e x = norm_1 (fromList [x]) > e\n\n\n-- | Obtains a vector in the same direction with 2-norm=1\nnormalize :: (Normed (Vector t), Num (Vector t), Field t) => Vector t -> Vector t\nnormalize v = v / real (scalar (norm_2 v))\n\n\n-- | trans . inv\nmt :: Matrix Float -> Matrix Float\nmt = trans . inv\n\n--------------------------------------------------------------------------------\n{- |\n\n>>> size $ vector [1..10]\n10\n>>> size $ (2><5)[1..10::Float]\n(2,5)\n\n-}\nsize :: Container c t => c t -> IndexOf c\nsize = size'\n\n{- | Alternative indexing function.\n\n>>> vector [1..10] ! 3\n4.0\n\nOn a matrix it gets the k-th row as a vector:\n\n>>> matrix 5 [1..15] ! 1\n[6.0,7.0,8.0,9.0,10.0]\nit :: Vector Float\n\n>>> matrix 5 [1..15] ! 1 ! 3\n9.0\n\n-}\nclass Indexable c t | c -> t , t -> c\n where\n infixl 9 !\n (!) :: c -> Int -> t\n\ninstance Indexable (Vector Float) Float\n where\n (!) = (@>)\n\n-- instance Indexable (Vector Float) Float\n-- where\n-- (!) = (@>)\n\ninstance Indexable (Vector I) I\n where\n (!) = (@>)\n\ninstance Indexable (Vector Z) Z\n where\n (!) = (@>)\n\n-- instance Indexable (Vector (Complex Float)) (Complex Float)\n-- where\n-- (!) = (@>)\n\ninstance Indexable (Vector (Complex Float)) (Complex Float)\n where\n (!) = (@>)\n\ninstance Element t => Indexable (Matrix t) (Vector t)\n where\n (!) m j = subVector (j*c) c (flatten m)\n where\n c = cols m\n\n--------------------------------------------------------------------------------\n\n-- | Matrix of pairwise squared distances of row vectors\n-- (using the matrix product trick in blog.smola.org)\npairwiseD2 :: Matrix Float -> Matrix Float -> Matrix Float\npairwiseD2 x y | ok = x2 `outer` oy + ox `outer` y2 - 2* x <> trans y\n | otherwise = error $ \"pairwiseD2 with different number of columns: \"\n ++ show (size x) ++ \", \" ++ show (size y)\n where\n ox = one (rows x)\n oy = one (rows y)\n oc = one (cols x)\n one k = konst 1 k\n x2 = x * x <> oc\n y2 = y * y <> oc\n ok = cols x == cols y\n\n--------------------------------------------------------------------------------\n\n{- | outer products of rows\n\n>>> a\n(3><2)\n [ 1.0, 2.0\n , 10.0, 20.0\n , 100.0, 200.0 ]\n>>> b\n(3><3)\n [ 1.0, 2.0, 3.0\n , 4.0, 5.0, 6.0\n , 7.0, 8.0, 9.0 ]\n\n>>> rowOuters a (b ||| 1)\n(3><8)\n [ 1.0, 2.0, 3.0, 1.0, 2.0, 4.0, 6.0, 2.0\n , 40.0, 50.0, 60.0, 10.0, 80.0, 100.0, 120.0, 20.0\n , 700.0, 800.0, 900.0, 100.0, 1400.0, 1600.0, 1800.0, 200.0 ]\n\n-}\nrowOuters :: Matrix Float -> Matrix Float -> Matrix Float\nrowOuters a b = a' * b'\n where\n a' = kronecker a (ones 1 (cols b))\n b' = kronecker (ones 1 (cols a)) b\n\n--------------------------------------------------------------------------------\n\n-- | solution of overconstrained homogeneous linear system\nnull1 :: Matrix R -> Vector R\nnull1 = last . toColumns . snd . rightSV\n\n-- | solution of overconstrained homogeneous symmetric linear system\nnull1sym :: Herm R -> Vector R\nnull1sym = last . toColumns . snd . eigSH\n\n--------------------------------------------------------------------------------\n\ninfixl 0 ~!~\nc ~!~ msg = when c (error msg)\n\n--------------------------------------------------------------------------------\n\nformatSparse :: String -> String -> String -> Int -> Matrix Float -> String\n\nformatSparse zeroI _zeroF sep _ (approxInt -> Just m) = format sep f m\n where\n f 0 = zeroI\n f x = printf \"%.0f\" x\n\nformatSparse zeroI zeroF sep n m = format sep f m\n where\n f x | abs (x::Float) < 2*peps = zeroI++zeroF\n | abs (fromIntegral (round x::Int) - x) / abs x < 2*peps\n = printf (\"%.0f.\"++replicate n ' ') x\n | otherwise = printf (\"%.\"++show n++\"f\") x\n\napproxInt m\n | norm_Inf (v - vi) < 2*peps * norm_Inf v = Just (reshape (cols m) vi)\n | otherwise = Nothing\n where\n v = flatten m\n vi = roundVector v\n\ndispDots n = putStr . formatSparse \".\" (replicate n ' ') \" \" n\n\ndispBlanks n = putStr . formatSparse \"\" \"\" \" \" n\n\nformatShort sep fmt maxr maxc m = auxm4\n where\n (rm,cm) = size m\n (r1,r2,r3)\n | rm <= maxr = (rm,0,0)\n | otherwise = (maxr-3,rm-maxr+1,2)\n (c1,c2,c3)\n | cm <= maxc = (cm,0,0)\n | otherwise = (maxc-3,cm-maxc+1,2)\n [ [a,_,b]\n ,[_,_,_]\n ,[c,_,d]] = toBlocks [r1,r2,r3]\n [c1,c2,c3] m\n auxm = fromBlocks [[a,b],[c,d]]\n auxm2\n | cm > maxc = format \"|\" fmt auxm\n | otherwise = format sep fmt auxm\n auxm3\n | cm > maxc = map (f . splitOn \"|\") (lines auxm2)\n | otherwise = (lines auxm2)\n f items = intercalate sep (take (maxc-3) items) ++ \" .. \" ++\n intercalate sep (drop (maxc-3) items)\n auxm4\n | rm > maxr = unlines (take (maxr-3) auxm3 ++ vsep : drop (maxr-3) auxm3)\n | otherwise = unlines auxm3\n vsep = map g (head auxm3)\n g '.' = ':'\n g _ = ' '\n\n\ndispShort :: Int -> Int -> Int -> Matrix Float -> IO ()\ndispShort maxr maxc dec m =\n printf \"%dx%d\\n%s\" (rows m) (cols m) (formatShort \" \" fmt maxr maxc m)\n where\n fmt = printf (\"%.\"++show dec ++\"f\")\n\n--------------------------------------------------------------------------------\n\n-- matrix views\n\nblock2x2 r c m = [[m11,m12],[m21,m22]]\n where\n m11 = m ?? (Take r, Take c)\n m12 = m ?? (Take r, Drop c)\n m21 = m ?? (Drop r, Take c)\n m22 = m ?? (Drop r, Drop c)\n\nblock3x3 r nr c nc m = [[m ?? (er !! i, ec !! j) | j <- [0..2] ] | i <- [0..2] ]\n where\n er = [ Range 0 1 (r-1), Range r 1 (r+nr-1), Drop (nr+r) ]\n ec = [ Range 0 1 (c-1), Range c 1 (c+nc-1), Drop (nc+c) ]\n\nview1 :: Numeric t => Matrix t -> Maybe (View1 t)\nview1 m\n | rows m > 0 && cols m > 0 = Just (e, flatten m12, flatten m21 , m22)\n | otherwise = Nothing\n where\n [[m11,m12],[m21,m22]] = block2x2 1 1 m\n e = m11 `atIndex` (0, 0)\n\nunView1 :: Numeric t => View1 t -> Matrix t\nunView1 (e,r,c,m) = fromBlocks [[scalar e, asRow r],[asColumn c, m]]\n\ntype View1 t = (t, Vector t, Vector t, Matrix t)\n\nfoldMatrix :: Numeric t => (Matrix t -> Matrix t) -> (View1 t -> View1 t) -> (Matrix t -> Matrix t)\nfoldMatrix g f ( (f <$>) . view1 . g -> Just (e,r,c,m)) = unView1 (e, r, c, foldMatrix g f m)\nfoldMatrix _ _ m = m\n\n\nswapMax k m\n | rows m > 0 && j>0 = (j, m ?? (Pos (idxs swapped), All))\n | otherwise = (0,m)\n where\n j = maxIndex $ abs (tr m ! k)\n swapped = j:[1..j-1] ++ 0:[j+1..rows m-1]\n\ndown g a = foldMatrix g f a\n where\n f (e,r,c,m)\n | e /= 0 = (1, r', 0, m - outer c r')\n | otherwise = error \"singular!\"\n where\n r' = r / scalar e\n\n\n-- | generic reference implementation of gaussian elimination\n--\n-- @a <> gaussElim a b = b@\n--\ngaussElim_2\n :: (Eq t, Fractional t, Num (Vector t), Numeric t)\n => Matrix t -> Matrix t -> Matrix t\n\ngaussElim_2 a b = flipudrl r\n where\n flipudrl = flipud . fliprl\n splitColsAt n = (takeColumns n &&& dropColumns n)\n go f x y = splitColsAt (cols a) (down f $ x ||| y)\n (a1,b1) = go (snd . swapMax 0) a b\n ( _, r) = go id (flipudrl $ a1) (flipudrl $ b1)\n\n--------------------------------------------------------------------------------\n\ngaussElim_1\n :: (Fractional t, Num (Vector t), Ord t, Indexable (Vector t) t, Numeric t)\n => Matrix t -> Matrix t -> Matrix t\n\ngaussElim_1 x y = dropColumns (rows x) (flipud $ fromRows s2)\n where\n rs = toRows $ x ||| y\n s1 = fromRows $ pivotDown (rows x) 0 rs -- interesting\n s2 = pivotUp (rows x-1) (toRows $ flipud s1)\n\npivotDown\n :: forall t . (Fractional t, Num (Vector t), Ord t, Indexable (Vector t) t, Numeric t)\n => Int -> Int -> [Vector t] -> [Vector t]\npivotDown t n xs\n | t == n = []\n | otherwise = y : pivotDown t (n+1) ys\n where\n y:ys = redu (pivot n xs)\n\n pivot k = (const k &&& id)\n . sortBy (flip compare `on` (abs. (!k)))\n\n redu :: (Int, [Vector t]) -> [Vector t]\n redu (k,x:zs)\n | p == 0 = error \"gauss: singular!\" -- FIXME\n | otherwise = u : map f zs\n where\n p = x!k\n u = scale (recip (x!k)) x\n f z = z - scale (z!k) u\n redu (_,[]) = []\n\n\npivotUp\n :: forall t . (Fractional t, Num (Vector t), Ord t, Indexable (Vector t) t, Numeric t)\n => Int -> [Vector t] -> [Vector t]\npivotUp n xs\n | n == -1 = []\n | otherwise = y : pivotUp (n-1) ys\n where\n y:ys = redu' (n,xs)\n\n redu' :: (Int, [Vector t]) -> [Vector t]\n redu' (k,x:zs) = u : map f zs\n where\n u = x\n f z = z - scale (z!k) u\n redu' (_,[]) = []\n\n--------------------------------------------------------------------------------\n\ngaussElim a b = dropColumns (rows a) $ fst $ mutable gaussST (a ||| b)\n\ngaussST (r,_) x = do\n let n = r-1\n axpy m a i j = rowOper (AXPY a i j AllCols) m\n swap m i j = rowOper (SWAP i j AllCols) m\n scal m a i = rowOper (SCAL a (Row i) AllCols) m\n forM_ [0..n] $ \\i -> do\n c <- maxIndex . abs . flatten <$> extractMatrix x (FromRow i) (Col i)\n swap x i (i+c)\n a <- readMatrix x i i\n when (a == 0) $ error \"singular!\"\n scal x (recip a) i\n forM_ [i+1..n] $ \\j -> do\n b <- readMatrix x j i\n axpy x (-b) i j\n forM_ [n,n-1..1] $ \\i -> do\n forM_ [i-1,i-2..0] $ \\j -> do\n b <- readMatrix x j i\n axpy x (-b) i j\n\n\nluST ok (r,_) x = do\n let axpy m a i j = rowOper (AXPY a i j (FromCol (i+1))) m\n swap m i j = rowOper (SWAP i j AllCols) m\n p <- newUndefinedVector r\n forM_ [0..r-1] $ \\i -> do\n k <- maxIndex . abs . flatten <$> extractMatrix x (FromRow i) (Col i)\n writeVector p i (k+i)\n swap x i (i+k)\n a <- readMatrix x i i\n when (ok a) $ do\n forM_ [i+1..r-1] $ \\j -> do\n b <- (/a) <$> readMatrix x j i\n axpy x (-b) i j\n writeMatrix x j i b\n v <- unsafeFreezeVector p\n return (toList v)\n\n{- | Experimental implementation of 'luPacked'\n for any Fractional element type, including 'Mod' n 'I' and 'Mod' n 'Z'.\n\n>>> let m = ident 5 + (5><5) [0..] :: Matrix (Z ./. 17)\n(5><5)\n [ 1, 1, 2, 3, 4\n , 5, 7, 7, 8, 9\n , 10, 11, 13, 13, 14\n , 15, 16, 0, 2, 2\n , 3, 4, 5, 6, 8 ]\n\n>>> let (l,u,p,s) = luFact $ luPacked' m\n>>> l\n(5><5)\n [ 1, 0, 0, 0, 0\n , 6, 1, 0, 0, 0\n , 12, 7, 1, 0, 0\n , 7, 10, 7, 1, 0\n , 8, 2, 6, 11, 1 ]\n>>> u\n(5><5)\n [ 15, 16, 0, 2, 2\n , 0, 13, 7, 13, 14\n , 0, 0, 15, 0, 11\n , 0, 0, 0, 15, 15\n , 0, 0, 0, 0, 1 ]\n\n-}\nluPacked' x = LU m p\n where\n (m,p) = mutable (luST (magnit 0)) x\n\n--------------------------------------------------------------------------------\n\nscalS a (Slice x r0 c0 nr nc) = rowOper (SCAL a (RowRange r0 (r0+nr-1)) (ColRange c0 (c0+nc-1))) x\n\nview x k r = do\n d <- readMatrix x k k\n let rr = r-1-k\n o = if k < r-1 then 1 else 0\n s = Slice x (k+1) (k+1) rr rr\n u = Slice x k (k+1) o rr\n l = Slice x (k+1) k rr o\n return (d,u,l,s)\n\nwithVec r f = \\s x -> do\n p <- newUndefinedVector r\n _ <- f s x p\n v <- unsafeFreezeVector p\n return v\n\n\nluPacked'' m = (id *** toList) (mutable (withVec (rows m) lu2) m)\n where\n lu2 (r,_) x p = do\n forM_ [0..r-1] $ \\k -> do\n pivot x p k\n (d,u,l,s) <- view x k r\n when (magnit 0 d) $ do\n scalS (recip d) l\n gemmm 1 s (-1) l u\n\n pivot x p k = do\n j <- maxIndex . abs . flatten <$> extractMatrix x (FromRow k) (Col k)\n writeVector p k (j+k)\n swap k (k+j)\n where\n swap i j = rowOper (SWAP i j AllCols) x\n\n--------------------------------------------------------------------------------\n\nrowRange m = [0..rows m -1]\n\nat k = Pos (idxs[k])\n\nbackSust' lup rhs = foldl' f (rhs?[]) (reverse ls)\n where\n ls = [ (d k , u k , b k) | k <- rowRange lup ]\n where\n d k = lup ?? (at k, at k)\n u k = lup ?? (at k, Drop (k+1))\n b k = rhs ?? (at k, All)\n\n f x (d,u,b) = (b - u<>x) / d\n ===\n x\n\n\nforwSust' lup rhs = foldl' f (rhs?[]) ls\n where\n ls = [ (l k , b k) | k <- rowRange lup ]\n where\n l k = lup ?? (at k, Take k)\n b k = rhs ?? (at k, All)\n\n f x (l,b) = x\n ===\n (b - l<>x)\n\n\nluSolve'' (LU lup p) b = backSust' lup (forwSust' lup pb)\n where\n pb = b ?? (Pos (fixPerm' p), All)\n\n--------------------------------------------------------------------------------\n\nforwSust lup rhs = fst $ mutable f rhs\n where\n f (r,c) x = do\n l <- unsafeThawMatrix lup\n let go k = gemmm 1 (Slice x k 0 1 c) (-1) (Slice l k 0 1 k) (Slice x 0 0 k c)\n mapM_ go [0..r-1]\n\n\nbackSust lup rhs = fst $ mutable f rhs\n where\n f (r,c) m = do\n l <- unsafeThawMatrix lup\n let d k = recip (lup `atIndex` (k,k))\n u k = Slice l k (k+1) 1 (r-1-k)\n b k = Slice m k 0 1 c\n x k = Slice m (k+1) 0 (r-1-k) c\n scal k = rowOper (SCAL (d k) (Row k) AllCols) m\n\n go k = gemmm 1 (b k) (-1) (u k) (x k) >> scal k\n mapM_ go [r-1,r-2..0]\n\n\n{- | Experimental implementation of 'luSolve' for any Fractional element type, including 'Mod' n 'I' and 'Mod' n 'Z'.\n\n>>> let a = (2><2) [1,2,3,5] :: Matrix (Z ./. 13)\n(2><2)\n [ 1, 2\n , 3, 5 ]\n>>> b\n(2><3)\n [ 5, 1, 3\n , 8, 6, 3 ]\n\n>>> luSolve' (luPacked' a) b\n(2><3)\n [ 4, 7, 4\n , 7, 10, 6 ]\n\n-}\nluSolve' (LU lup p) b = backSust lup (forwSust lup pb)\n where\n pb = b ?? (Pos (fixPerm' p), All)\n\n\n--------------------------------------------------------------------------------\n\ndata MatrixView t b\n = Elem t\n | Block b b b b\n deriving Show\n\n\nviewBlock' r c m\n | (rt,ct) == (1,1) = Elem (atM' m 0 0)\n | otherwise = Block m11 m12 m21 m22\n where\n (rt,ct) = size m\n m11 = subm (0,0) (r,c) m\n m12 = subm (0,c) (r,ct-c) m\n m21 = subm (r,0) (rt-r,c) m\n m22 = subm (r,c) (rt-r,ct-c) m\n subm = subMatrix\n\nviewBlock m = viewBlock' n n m\n where\n n = rows m `div` 2\n\ninvershur (viewBlock -> Block a b c d) = fromBlocks [[a',b'],[c',d']]\n where\n r1 = invershur a\n r2 = c <> r1\n r3 = r1 <> b\n r4 = c <> r3\n r5 = r4-d\n r6 = invershur r5\n b' = r3 <> r6\n c' = r6 <> r2\n r7 = r3 <> c'\n a' = r1-r7\n d' = -r6\n\ninvershur x = recip x\n\n--------------------------------------------------------------------------------\n\ninstance Testable (Matrix I) where\n checkT _ = test\n\ntest :: (Bool, IO())\ntest = (and ok, return ())\n where\n m = (3><4) [1..12] :: Matrix I\n r = (2><3) [1,2,3,4,3,2]\n c = (3><2) [0,4,4,1,2,3]\n p = (9><10) [0..89] :: Matrix I\n ep = (2><3) [10,24,32,44,31,23]\n md = fromInt m :: Matrix Float\n ok = [ tr m <> m == toInt (tr md <> md)\n , m <> tr m == toInt (md <> tr md)\n , m ?? (Take 2, Take 3) == remap (asColumn (range 2)) (asRow (range 3)) m\n , remap r (tr c) p == ep\n , tr p ?? (PosCyc (idxs[-5,13]), Pos (idxs[3,7,1])) == (2><3) [35,75,15,33,73,13]\n ]\n\n", "meta": {"hexsha": "3e056596a946cbef955c8ffd49a4bb56480888a1", "size": 23058, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Internal/Util.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Internal/Util.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Internal/Util.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 25.2, "max_line_length": 117, "alphanum_fraction": 0.4960100616, "num_tokens": 8243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341026367784, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.38960296074746886}} {"text": "{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, Rank2Types #-}\n-----------------------------------------------------------------------------\n-- |\n-- Module : Numeric.LinearAlgebra.Packed.Base\n-- Copyright : Copyright (c) 2010, Patrick Perry \n-- License : BSD3\n-- Maintainer : Patrick Perry \n-- Stability : experimental\n--\n-- Packed matrices.\n--\nmodule Numeric.LinearAlgebra.Packed.Base\n where\n\nimport Control.Monad( when )\nimport Control.Monad.ST( ST, RealWorld, runST, unsafeIOToST )\nimport Data.Typeable( Typeable )\nimport Foreign( Storable, Ptr )\nimport Text.Printf( printf )\nimport Unsafe.Coerce( unsafeCoerce )\n\nimport Numeric.LinearAlgebra.Types( Herm(..) )\nimport Numeric.LinearAlgebra.Vector( Vector, RVector, STVector )\nimport qualified Numeric.LinearAlgebra.Vector as V\nimport Foreign.BLAS( BLAS2 )\nimport qualified Foreign.BLAS as BLAS\n\n\n-- | Immutable packed matrices, stored in column-major order.\ndata Packed e = Packed !Int !(Vector e)\n deriving (Typeable)\n \n-- | Mutable packed matrices in the 'ST' monad.\nnewtype STPacked s e = STPacked { unSTPacked :: Packed e }\n deriving (Typeable)\n \n-- | Mutable packed matrices in the 'IO' monad.\ntype IOPacked = STPacked RealWorld\n\n-- | The dimension of the packed matrix.\ndim :: (Storable e) => Packed e -> Int\ndim (Packed n _) = n\n{-# INLINE dim #-}\n\n-- | Allocate a mutable packed matrix of the given dimension.\nnew_ :: (Storable e) => Int -> ST s (STPacked s e)\nnew_ n\n | n < 0 = error $\n printf \"new_ %d: negative dimension\" n\n | otherwise = do\n mx <- V.new_ (n*(n+1) `div` 2)\n x <- V.unsafeFreeze mx\n return $ STPacked $ Packed n x\n{-# INLINE new_ #-}\n\n-- | Create a packed matrix view of a vector, ensurint that the\n-- vector has dimension @n * (n+1)/2@, where @n@ is the desired dimension.\nfromVector :: (Storable e) => Int -> Vector e -> Packed e\nfromVector n x\n | not $ 2 * nx == n * (n+1) = error $\n printf (\"fromVector %d : dimension mismatch\")\n n nx\n | otherwise =\n unsafeFromVector n x\n where\n nx = V.dim x\n{-# INLINE fromVector #-}\n\n-- | Create a packed matrix view of a vector, wihtout checking\n-- the dimension of the vector.\nunsafeFromVector :: (Storable e) => Int -> Vector e -> Packed e\nunsafeFromVector = Packed\n{-# INLINE unsafeFromVector #-}\n\n-- | Returns the dimension and underlying vector storage of a\n-- packed matrix.\ntoVector :: (Storable e) => Packed e -> (Int, Vector e)\ntoVector (Packed n v) = (n,v)\n{-# INLINE toVector #-}\n\n{-\n-- | Create a packed matrix view of a vector, ensurint that the\n-- vector has dimension @n * (n+1)/2@, where @n@ is the desired dimension.\nfromSTVector :: (Storable e) => Int -> STVector s e -> STPacked s e\nfromSTVector n x\n | not $ 2 * nx == n * (n+1) = error $\n printf (\"fromVectorST %d : dimension mismatch\")\n n nx\n | otherwise =\n STPacked $ unsafeFromVector n x\n where\n nx = V.dim x\n{-# INLINE fromSTVector #-}\n\n-- | Create a packed matrix view of a vector, wihtout checking\n-- the dimension of the vector.\nunsafeFromSTVector :: (Storable e) => Int -> STVector s e -> STPacked s e\nunsafeFromSTVector = STPacked\n{-# INLINE unsafeFromSTVector #-}\n\n-- | Returns the dimension and underlying vector storage of a\n-- packed matrix.\ntoSTVector :: (Storable e) => STPacked s e -> (Int, STVector s e)\ntoSTVector (STPacked n v) = (n,v)\n{-# INLINE toSTVector #-}\n-}\n\n-- | Read-only packed matrices.\nclass RPacked p where\n -- | Returns the dimension of the packed matrix.\n getDim :: (Storable e) => p e -> ST s Int\n\n -- | Perform an action with the underlying vector storage of\n -- the packed matrix.\n withVector :: (Storable e)\n => p e\n -> (forall v . RVector v => v e -> ST s a)\n -> ST s a\n \n -- | Perform an IO action with a pointer to the first element of\n -- the packed matrix.\n unsafeWith :: (Storable e) => p e -> (Ptr e -> IO a) -> IO a\n\n -- | Converts a read-only packed matrix into an immutable one. This simply\n -- casts the matrix from one type to the other without copying the matrix.\n -- Note that because the matrix is possibly not copied, any subsequent\n -- modifications made to the mutable version of the matrix may be shared\n -- with the immutable version. It is safe to use, therefore, if the mutable\n -- version is never modified after the freeze operation.\n unsafeFreeze :: (Storable e) => p e -> ST s (Packed e)\n\n unsafeThaw :: (Storable e) => p e -> ST s (STPacked s e)\n \n\n-- | View a vector as a packed matrix and pass it to a function.\nwithFromVector :: (RVector v, Storable e)\n => Int\n -> v e\n -> (forall p . RPacked p => p e -> ST s a)\n -> ST s a\nwithFromVector n v f = do\n iv <- V.unsafeFreeze v\n f $ fromVector n iv\n{-# INLINE withFromVector #-}\n\n-- | View a mutable vector as a mutable packed matrix and pass it\n-- to a function.\nwithFromVectorM :: (Storable e)\n => Int\n -> STVector s e\n -> (STPacked s e -> ST s a)\n -> ST s a\nwithFromVectorM n v f =\n withFromVector n v $ \\p -> do\n mp <- unsafeThaw p\n f mp\n{-# INLINE withFromVectorM #-}\n\n-- | Perform an action with the underlying vector storage of\n-- the mutable packed matrix. See also 'withVectorView'.\nwithVectorM :: (Storable e)\n => STPacked s e\n -> (STVector s e -> ST s a)\n -> ST s a\nwithVectorM mp f =\n withVector mp $ \\v -> do\n mv <- V.unsafeThaw v\n f mv\n{-# INLINE withVectorM #-}\n\ninstance RPacked Packed where\n getDim = return . dim\n {-# INLINE getDim #-}\n withVector (Packed _ v) f = f v\n {-# INLINE withVector #-}\n unsafeWith (Packed _ v) = V.unsafeWith v\n {-# INLINE unsafeWith #-}\n unsafeFreeze = return\n {-# INLINE unsafeFreeze #-}\n unsafeThaw = return . STPacked\n {-# INLINE unsafeThaw #-}\n\ninstance RPacked (STPacked s) where\n getDim = getDim . unSTPacked\n {-# INLINE getDim #-}\n withVector = withVector . unSTPacked\n {-# INLINE withVector #-}\n unsafeWith = unsafeWith . unSTPacked\n {-# INLINE unsafeWith #-}\n unsafeFreeze = return . unSTPacked\n {-# INLINE unsafeFreeze #-}\n unsafeThaw p = return $ cast p\n where\n cast :: STPacked s e -> STPacked s' e\n cast = unsafeCoerce\n {-# INLINE unsafeThaw #-}\n\n\n-- | Create a new copy of a packed matrix.\nnewCopy :: (RPacked p, Storable e)\n => p e -> ST s (STPacked s e)\nnewCopy p = do\n n <- getDim p\n p' <- new_ n\n withVector p $ \\v ->\n withVectorM p' $ \\v' ->\n V.unsafeCopyTo v' v\n return p'\n{-# INLINE newCopy #-}\n\n-- | Converts a mutable packed matrix to an immutable one by taking a complete\n-- copy of it.\nfreeze :: (RPacked p, Storable e) => p e -> ST s (Packed e)\nfreeze p = do\n p' <- newCopy p\n unsafeFreeze p'\n\n-- | A safe way to create and work with a mutable Packed before returning \n-- an immutable one for later perusal.\ncreate :: (Storable e)\n => (forall s. ST s ((STPacked s) e))\n -> Packed e\ncreate stmp = runST $ do\n mp <- stmp\n unsafeFreeze mp\n\n\n-- | A safe way to create and work with a mutable Herm Packed before returning \n-- an immutable one for later perusal.\nhermCreate :: (Storable e)\n => (forall s. ST s (Herm (STPacked s) e))\n -> Herm Packed e\nhermCreate stmh = runST $ do\n (Herm u mp) <- stmh\n p <- unsafeFreeze mp\n return $ Herm u p\n\n-- | @hermRank1Update alpha x a@ returns\n-- @alpha * x * x^H + a@.\nhermRank1Update :: (BLAS2 e)\n => Double -> Vector e -> Herm Packed e -> Herm Packed e\nhermRank1Update alpha x (Herm uplo ap) = hermCreate $ do\n hp' <- Herm uplo `fmap` newCopy ap\n hermRank1UpdateM_ alpha x hp'\n return hp'\n\n-- | @hermRank2Update alpha x y a@ returns\n-- @alpha * x * y^H + conj(alpha) * y * x^H + a@.\nhermRank2Update :: (BLAS2 e)\n => e -> Vector e -> Vector e -> Herm Packed e\n -> Herm Packed e\nhermRank2Update alpha x y (Herm uplo ap) = hermCreate $ do\n hp' <- Herm uplo `fmap` newCopy ap\n hermRank2UpdateM_ alpha x y hp'\n return hp'\n\n-- | @hermRank1UpdateM_ alpha x a@ sets\n-- @a := alpha * x * x^H + a@.\nhermRank1UpdateM_ :: (RVector v, BLAS2 e)\n => Double -> v e -> Herm (STPacked s) e -> ST s ()\nhermRank1UpdateM_ alpha x (Herm uplo a) = do\n nx <- V.getDim x\n na <- getDim a\n let n = nx\n\n when ((not . and) [ nx == n, na == n ]) $ error $\n printf (\"hermRank1UpdateM_ _ \"\n ++ \" (Herm _ ):\"\n ++ \" invalid dimensions\") nx na\n\n unsafeIOToST $\n V.unsafeWith x $ \\px ->\n unsafeWith a $ \\pa ->\n BLAS.hpr uplo n alpha px 1 pa\n\n\n-- | @hermRank2UpdateM_ alpha x y a@ sets\n-- @a := alpha * x * y^H + conj(alpha) * y * x^H + a@.\nhermRank2UpdateM_ :: (RVector v1, RVector v2, BLAS2 e)\n => e -> v1 e -> v2 e -> Herm (STPacked s) e -> ST s ()\nhermRank2UpdateM_ alpha x y (Herm uplo a) = do\n nx <- V.getDim x\n ny <- V.getDim y\n na <- getDim a\n let n = nx\n \n when ((not . and) [ nx == n, ny == n, na == n ]) $ error $\n printf (\"hermRank2UpdateM_ _ \"\n ++ \" \"\n ++ \" (Herm _ ):\"\n ++ \" invalid dimensions\") nx ny na\n\n unsafeIOToST $\n V.unsafeWith x $ \\px ->\n V.unsafeWith y $ \\py -> \n unsafeWith a $ \\pa ->\n BLAS.hpr2 uplo n alpha px 1 py 1 pa\n\n\n-- | @hermMulVector a x@ returns @a * x@.\nhermMulVector :: (BLAS2 e)\n => Herm Packed e\n -> Vector e\n -> Vector e\nhermMulVector a x =\n V.create $ do\n y <- V.new_ (V.dim x)\n hermMulVectorTo y a x\n return y\n\n-- | @hermMulVectorWithScale alpha a x@ retunrs @alpha * a * x@.\nhermMulVectorWithScale :: (BLAS2 e)\n => e\n -> Herm Packed e\n -> Vector e\n -> Vector e\nhermMulVectorWithScale alpha a x =\n V.create $ do\n y <- V.new_ (V.dim x)\n hermMulVectorWithScaleTo y alpha a x\n return y\n \n-- | @addHermMulVectorWithScales alpha a x y@\n-- returns @alpha * a * x + beta * y@.\naddHermMulVectorWithScales :: (BLAS2 e)\n => e\n -> Herm Packed e\n -> Vector e\n -> e\n -> Vector e\n -> Vector e\naddHermMulVectorWithScales alpha a x beta y =\n V.create $ do\n y' <- V.newCopy y\n addHermMulVectorWithScalesM_ alpha a x beta y'\n return y'\n\n-- | @hermMulVectorTo dst a x@ sets @dst := a * x@.\nhermMulVectorTo :: (RPacked p, RVector v, BLAS2 e)\n => STVector s e\n -> Herm p e\n -> v e\n -> ST s ()\nhermMulVectorTo dst = hermMulVectorWithScaleTo dst 1\n\n-- | @hermMulVectorWithScaleTo dst alpha a x@\n-- sets @dst := alpha * a * x@.\nhermMulVectorWithScaleTo :: (RPacked p, RVector v, BLAS2 e)\n => STVector s e\n -> e\n -> Herm p e\n -> v e\n -> ST s ()\nhermMulVectorWithScaleTo dst alpha a x =\n addHermMulVectorWithScalesM_ alpha a x 0 dst\n\n-- | @addHermMulVectorWithScalesM_ alpha a x beta y@\n-- sets @y := alpha * a * x + beta * y@.\naddHermMulVectorWithScalesM_ :: (RPacked p, RVector v, BLAS2 e)\n => e\n -> Herm p e\n -> v e\n -> e\n -> STVector s e\n -> ST s ()\naddHermMulVectorWithScalesM_ alpha (Herm uplo a) x beta y = do\n na <- getDim a\n nx <- V.getDim x\n ny <- V.getDim y\n let n = ny\n\n when ((not . and) [ na == n\n , nx == n\n , ny == n\n ]) $ error $\n printf (\"addHermMulVectorWithScalesM_ _\"\n ++ \" (Herm %s )\"\n ++ \" %s \"\n ++ \" _\"\n ++ \" : dimension mismatch\")\n (show uplo) na\n nx ny\n\n unsafeIOToST $\n unsafeWith a $ \\pa ->\n V.unsafeWith x $ \\px ->\n V.unsafeWith y $ \\py ->\n BLAS.hpmv uplo n alpha pa px 1 beta py 1\n", "meta": {"hexsha": "d711aa7fa31c1eb869d00610a64c0169e13a12bd", "size": 12703, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "lib/Numeric/LinearAlgebra/Packed/Base.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/Base.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/Base.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.6555269923, "max_line_length": 79, "alphanum_fraction": 0.5585294812, "num_tokens": 3605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.38933248594177783}} {"text": "{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE IncoherentInstances #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE MonoLocalBinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE GADTs #-}\nmodule FFT where\n\nimport Prelude ( Double, ($), Integer, Num(..), Int, (^), Bool(..), otherwise )\n-- import qualified Prelude\n\nimport Data.C ( CVal )\nimport Data.Complex\nimport Control.CCat\nimport Control.CArr\nimport Control.CArr.CSyn ( SINat, Sing(..), Tree\n , cdictTree, withCDict, toInteger, withSize )\nimport Language.SPar.Skel ( (:->), liftAlg )\n\ntsplit' :: forall a n f. (CVal a, CArrLift (:->) f, PAlg f) => SINat n -> Int\n -> (Int -> Int -> a :-> (a, a))\n -> f a (Tree n a)\ntsplit' SZ _acc _f = newProc\ntsplit' (SS n) acc f =\n withCDict (cdictTree @a n) $ lift (f wl wr) >>>\n (tsplit' n wl f *** tsplit' n wr f)\n where\n wl = acc\n wr = acc + 2 ^ toInteger n\n\ntsplit :: forall a n f. (CArrLift (:->) f, PAlg f, CVal a)\n => SINat n\n -> (Int -> Int -> a :-> (a, a))\n -> f a (Tree n a)\ntsplit n = tsplit' n 0\n\ntfold :: forall f a n. (PAlg f, CVal a)\n => SINat n -> f (a, a) a -> f (Tree n a) a\ntfold SZ _f = id\ntfold (SS n) f =\n withCDict (cdictTree @a n) $ (tfold n f *** tfold n f) >>> f\n\nzipTree :: forall a b n f. (CVal a, CVal b, PAlg f, CArrLift (:->) f)\n => SINat n\n -> Prelude.Bool\n -> Int\n -> Int\n -> ((Int, Int), (a, a)) :-> b\n -> f (Tree n a, Tree n a) (Tree n b)\nzipTree SZ b l w f\n | b = lift ((lit l &&& lit w) &&& id >>> f)\n | otherwise = (snd &&& fst) >>> lift ((lit l &&& lit w) &&& id >>> f)\nzipTree (SS x) b l w f =\n withCDict (cdictTree @a x) $\n withCDict (cdictTree @b x) $\n let swap = ((fst >>> fst) &&& (snd >>> fst)) &&&\n ((fst >>> snd) &&& (snd >>> snd))\n in swap >>> (zipTree x b l w f *** zipTree x b l (w + 2 ^ toInteger x) f)\n\ntype D a = a\n\nfmapT :: PAlg f\n => SINat n\n -> f (D [Complex Double]) (D [Complex Double])\n -> f (Tree n (D [Complex Double])) (Tree n (D [Complex Double]))\nfmapT SZ f = f\nfmapT (SS x) f\n = withCDict (cdictTree @(D [Complex Double]) x) $ fmapT x f *** fmapT x f\n\n\nfmapTIx :: PAlg f\n => SINat n\n -> f (Int, D [Complex Double]) (D [Complex Double])\n -> Int\n -> f (Tree n (D [Complex Double])) (Tree n (D [Complex Double]))\nfmapTIx SZ f k = lit k &&& id >>> f\nfmapTIx (SS x) f k\n = withCDict (cdictTree @(D [Complex Double]) x) $\n fmapTIx x f k *** fmapTIx x f (k + (2 ^ (toInteger x :: Integer)))\n\n-- addPadding :: PAlg f => f (D [Complex Double]) (D [Complex Double])\n-- addPadding = prim \"add_padding\"\n\ndeinterleave :: Int -> Int -> (D [Complex Double]) :-> (D [Complex Double], D [Complex Double])\ndeinterleave wl wr = lit wl &&& lit wr >>> prim \"deinterleave\"\n\nintlit :: (PAlg f, CVal a) => SINat n -> f a Int\nintlit i = fromInteger $ toInteger i + 1\n\nfftTree :: (CArrLift (:->) f, PAlg f)\n => SINat n\n -> Int\n -> f (Tree n (D [Complex Double])) (Tree n (D [Complex Double]))\nfftTree SZ w\n = liftAlg (intlit SZ &&& (lit w &&& id) >>> prim \"baseFFT\")\nfftTree (SS x) w\n = withCDict (cdictTree @(D [Complex Double]) x) $\n (fftTree x w {-EVENS-} *** fftTree x (w + 2^ toInteger x){-ODDS-}) >>>\n id *** fmapTIx x (lit ps2x &&& id >>> prim \"map_exp\") 0 {- Multiply left side by exponential -} >>>\n zipTree x True lvl w addc &&& zipTree x False lvl (w + 2^ toInteger x) subc\n where\n lvl :: Int\n lvl = fromInteger (toInteger (SS x) + 1)\n ps2x :: Int\n ps2x = 2 ^ toInteger (SS x)\n addc :: ((Int, Int), (D [Complex Double], D [Complex Double])) :-> (D [Complex Double])\n addc = prim \"zip_add\"\n subc :: ((Int, Int), (D [Complex Double], D [Complex Double])) :-> (D [Complex Double])\n subc = id *** (snd &&& fst) >>> prim \"zip_sub\"\n\nfft :: (CArrLift (:->) f, PAlg f)\n => SINat n -> f (D [Complex Double]) (D [Complex Double])\nfft n =\n withCDict (cdictTree @(D [Complex Double]) n) $\n -- addPadding >>>\n tsplit n deinterleave >>> fftTree n 0 >>> tfold n (runAt 0 >>> prim \"cat\")\n\nfft0 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft0 = withSize 0 fft\n\nfft1 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft1 = withSize 1 fft\n\nfft2 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft2 = withSize 2 fft\n\nfft3 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft3 = withSize 3 fft\n\nfft4 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft4 = withSize 4 fft\n\nfft5 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft5 = withSize 5 fft\n\nfft6 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft6 = withSize 6 fft\n\nfft7 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft7 = withSize 7 fft\n\nfft8 :: (CArrLift (:->) f, PAlg f)\n => f (D [Complex Double]) (D [Complex Double])\nfft8 = withSize 8 fft\n--\n-- fft8 :: PAlg f => f (D [Complex Double]) (D [Complex Double])\n-- fft8 = withSize 8 fft\n --where\n -- p2sx :: Integer\n -- p2sx = 2 ^ (fromINat (SS x) :: Integer)\n\n--fft :: PAlg f => SINat n\n-- -> f (Tree n [Complex Double]) (Tree n [Complex Double])\n\n-- Below fails for some reason!\n--fft :: PAlg f => SINat n\n-- -> f (Tree n [Complex Double]) (Tree n [Complex Double])\n--fft SZ = cfun $ prim \"baseFFT\"\n--fft (SS n) = cfun $ \\x ->\n-- vlet (withCDict (cdictTree @[Complex Double] n) $ app (fft n) $ fst x) $ \\l ->\n-- vlet (app (fft n) $ snd x) $ \\r -> _\n -- vlet (par (fft n) $ fst x) $ \\l -> _\n--fft n = cfun $ \\z ->\n-- case n of\n-- SZ -> prim \"baseFFT\" z\n-- (SS x) ->\n-- vlet (par (app $ fft x) $ fst z) $ \\l ->\n-- vlet (par (app $ fft x) $ snd z) $ \\r ->\n-- _\n", "meta": {"hexsha": "24ce8e88977e75ae3ec81ff9d365c52a156eaaf0", "size": 6019, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/FFT/FFT.hs", "max_stars_repo_name": "session-arr/session-arr", "max_stars_repo_head_hexsha": "5dbde7e18176c493767f9c84d8d900f7a5637c66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/FFT/FFT.hs", "max_issues_repo_name": "session-arr/session-arr", "max_issues_repo_head_hexsha": "5dbde7e18176c493767f9c84d8d900f7a5637c66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/FFT/FFT.hs", "max_forks_repo_name": "session-arr/session-arr", "max_forks_repo_head_hexsha": "5dbde7e18176c493767f9c84d8d900f7a5637c66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-18T11:16:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T11:16:16.000Z", "avg_line_length": 32.8907103825, "max_line_length": 103, "alphanum_fraction": 0.5487622529, "num_tokens": 2109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.38913300348078456}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-|\nModule : Grenade.Core.Shape\nDescription : Dependently typed shapes of data which are passed between layers of a network\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n\n\n-}\nmodule Grenade.Core.Shape (\n Shape (..)\n , S (..)\n , Sing (..)\n\n , randomOfShape\n , fromStorable\n ) where\n\nimport Control.DeepSeq (NFData (..))\nimport Control.Monad.Random ( MonadRandom, getRandom )\n\nimport Data.Proxy\nimport Data.Serialize\nimport Data.Singletons\nimport Data.Singletons.TypeLits\nimport Data.Vector.Storable ( Vector )\nimport qualified Data.Vector.Storable as V\n\n#if MIN_VERSION_base(4,11,0)\nimport GHC.TypeLits hiding (natVal)\n#else\nimport GHC.TypeLits\n#endif\n\nimport qualified Numeric.LinearAlgebra.Static as H\nimport Numeric.LinearAlgebra.Static\nimport qualified Numeric.LinearAlgebra as NLA\n\n-- | The current shapes we accept.\n-- at the moment this is just one, two, and three dimensional\n-- Vectors/Matricies.\n--\n-- These are only used with DataKinds, as Kind `Shape`, with Types 'D1, 'D2, 'D3.\ndata Shape\n = D1 Nat\n -- ^ One dimensional vector\n | D2 Nat Nat\n -- ^ Two dimensional matrix. Row, Column.\n | D3 Nat Nat Nat\n -- ^ Three dimensional matrix. Row, Column, Channels.\n\n-- | Concrete data structures for a Shape.\n--\n-- All shapes are held in contiguous memory.\n-- 3D is held in a matrix (usually row oriented) which has height depth * rows.\ndata S (n :: Shape) where\n S1D :: ( KnownNat len )\n => R len\n -> S ('D1 len)\n\n S2D :: ( KnownNat rows, KnownNat columns )\n => L rows columns\n -> S ('D2 rows columns)\n\n S3D :: ( KnownNat rows\n , KnownNat columns\n , KnownNat depth\n , KnownNat (rows * depth))\n => L (rows * depth) columns\n -> S ('D3 rows columns depth)\n\nderiving instance Show (S n)\n\n-- Singleton instances.\n--\n-- These could probably be derived with template haskell, but this seems\n-- clear and makes adding the KnownNat constraints simple.\n-- We can also keep our code TH free, which is great.\ndata instance Sing (n :: Shape) where\n D1Sing :: Sing a -> Sing ('D1 a)\n D2Sing :: Sing a -> Sing b -> Sing ('D2 a b)\n D3Sing :: KnownNat (a * c) => Sing a -> Sing b -> Sing c -> Sing ('D3 a b c)\n\ninstance KnownNat a => SingI ('D1 a) where\n sing = D1Sing sing\ninstance (KnownNat a, KnownNat b) => SingI ('D2 a b) where\n sing = D2Sing sing sing\ninstance (KnownNat a, KnownNat b, KnownNat c, KnownNat (a * c)) => SingI ('D3 a b c) where\n sing = D3Sing sing sing sing\n\ninstance SingI x => Num (S x) where\n (+) = n2 (+)\n (-) = n2 (-)\n (*) = n2 (*)\n abs = n1 abs\n signum = n1 signum\n fromInteger x = nk (fromInteger x)\n\ninstance SingI x => Fractional (S x) where\n (/) = n2 (/)\n recip = n1 recip\n fromRational x = nk (fromRational x)\n\ninstance SingI x => Floating (S x) where\n pi = nk pi\n exp = n1 exp\n log = n1 log\n sqrt = n1 sqrt\n (**) = n2 (**)\n logBase = n2 logBase\n sin = n1 sin\n cos = n1 cos\n tan = n1 tan\n asin = n1 asin\n acos = n1 acos\n atan = n1 atan\n sinh = n1 sinh\n cosh = n1 cosh\n tanh = n1 tanh\n asinh = n1 asinh\n acosh = n1 acosh\n atanh = n1 atanh\n\n--\n-- I haven't made shapes strict, as sometimes they're not needed\n-- (the last input gradient back for instance)\n--\ninstance NFData (S x) where\n rnf (S1D x) = rnf x\n rnf (S2D x) = rnf x\n rnf (S3D x) = rnf x\n\n-- | Generate random data of the desired shape\nrandomOfShape :: forall x m. ( MonadRandom m, SingI x ) => m (S x)\nrandomOfShape = do\n seed :: Int <- getRandom\n return $ case (sing :: Sing x) of\n D1Sing SNat ->\n S1D (randomVector seed Uniform * 2 - 1)\n\n D2Sing SNat SNat ->\n S2D (uniformSample seed (-1) 1)\n\n D3Sing SNat SNat SNat ->\n S3D (uniformSample seed (-1) 1)\n\n-- | Generate a shape from a Storable Vector.\n--\n-- Returns Nothing if the vector is of the wrong size.\nfromStorable :: forall x. SingI x => Vector Double -> Maybe (S x)\nfromStorable xs = case sing :: Sing x of\n D1Sing SNat ->\n S1D <$> H.create xs\n\n D2Sing SNat SNat ->\n S2D <$> mkL xs\n\n D3Sing SNat SNat SNat ->\n S3D <$> mkL xs\n where\n mkL :: forall rows columns. (KnownNat rows, KnownNat columns)\n => Vector Double -> Maybe (L rows columns)\n mkL v =\n let rows = fromIntegral $ natVal (Proxy :: Proxy rows)\n columns = fromIntegral $ natVal (Proxy :: Proxy columns)\n in if rows * columns == V.length v\n then H.create $ NLA.reshape columns v\n else Nothing\n\n\ninstance SingI x => Serialize (S x) where\n put i = (case i of\n (S1D x) -> putListOf put . NLA.toList . H.extract $ x\n (S2D x) -> putListOf put . NLA.toList . NLA.flatten . H.extract $ x\n (S3D x) -> putListOf put . NLA.toList . NLA.flatten . H.extract $ x\n ) :: PutM ()\n\n get = do\n Just i <- fromStorable . V.fromList <$> getListOf get\n return i\n\n-- Helper function for creating the number instances\nn1 :: ( forall a. Floating a => a -> a ) -> S x -> S x\nn1 f (S1D x) = S1D (f x)\nn1 f (S2D x) = S2D (f x)\nn1 f (S3D x) = S3D (f x)\n\n-- Helper function for creating the number instances\nn2 :: ( forall a. Floating a => a -> a -> a ) -> S x -> S x -> S x\nn2 f (S1D x) (S1D y) = S1D (f x y)\nn2 f (S2D x) (S2D y) = S2D (f x y)\nn2 f (S3D x) (S3D y) = S3D (f x y)\n\n-- Helper function for creating the number instances\nnk :: forall x. SingI x => Double -> S x\nnk x = case (sing :: Sing x) of\n D1Sing SNat ->\n S1D (konst x)\n\n D2Sing SNat SNat ->\n S2D (konst x)\n\n D3Sing SNat SNat SNat ->\n S3D (konst x)\n", "meta": {"hexsha": "fec7116f71fae6deab1ad92d93adc84d0ab42312", "size": 6061, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Core/Shape.hs", "max_stars_repo_name": "sebeaumont/grenade", "max_stars_repo_head_hexsha": "c0d5e27322bb972e6b9f68b7ee25342d83cf411e", "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/Shape.hs", "max_issues_repo_name": "sebeaumont/grenade", "max_issues_repo_head_hexsha": "c0d5e27322bb972e6b9f68b7ee25342d83cf411e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Core/Shape.hs", "max_forks_repo_name": "sebeaumont/grenade", "max_forks_repo_head_hexsha": "c0d5e27322bb972e6b9f68b7ee25342d83cf411e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0601851852, "max_line_length": 91, "alphanum_fraction": 0.6076555024, "num_tokens": 1859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.38900747138789127}} {"text": "{-# LANGUAGE TypeApplications #-}\n{-# OPTIONS_GHC -fno-warn-type-defaults #-}\n\nmodule ScalarWaveOld where\n\nimport Control.Exception (assert)\nimport Control.Monad.Loops\nimport qualified Data.Vector.Unboxed as U\nimport Data.VectorSpace\nimport Dual\nimport EquationsOld\nimport Foreign\nimport qualified Numeric.LinearAlgebra as L\nimport SSSFN\nimport System.CPUTime\n\ndefault (Int)\n\n--------------------------------------------------------------------------------\n\nbndw :: Floating a => Coord a -> a\nbndw (Coord u v) = swamp * cos (pi / 4 * swk * t) * cos (pi / 4 * swk * r)\n where\n t = v + u\n r = v - u\n swk = 1\n swamp = 0.1\n\nguess1 :: Floating a => Coord a -> State a\n-- guess1 c = State 1 0 (bndw c)\nguess1 c = State 1 0 0\n\nguess :: (L.Container L.Vector a, Floating a) => Grid (State a)\nguess = gsample (\\(u, v) -> guess1 (Coord u v))\n\n--------------------------------------------------------------------------------\n\neqnInt1 :: Fractional a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnInt1 eqn c s su sv suv suu svv =\n case eqn of\n EqnG01 -> eqnG01 c s su sv suv\n EqnG22 -> eqnG22 c s su sv suv\n EqnSW2 -> eqnSW2 c s su sv suv\n EqnG00 -> eqnG00 c s su suu\n EqnG11 -> eqnG11 c s sv svv\n\neqnAxis1 :: Fractional a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnAxis1 eqn c@(Coord u v) s@(State g q w) su@(State gu qu wu) sv@(State gv qv wv) suv@(State guv quv wuv) suu@(State guu quu wuu) svv@(State gvv qvv wvv) =\n case eqn of\n EqnG01 -> eqnAxisG01 c s su sv suv\n EqnG22 -> eqnAxisG22 c s su sv suv\n EqnSW2 -> eqnAxisSW2 c s su sv suv\n EqnG00 -> eqnAxisG00 c s su sv suu\n EqnG11 -> eqnAxisG11 c s su sv svv\n\neqnOrig1 :: Floating a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnOrig1 eqn c s@(State g q w) su sv suv suu svv =\n case eqn of\n EqnG01 -> g - 1\n EqnG22 -> q - 0\n EqnSW2 -> w - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\n-- i == 0, u == -1\neqnBndU1 :: (Eq a, Floating a) => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnBndU1 eqn c@(Coord u v) s@(State g q w) _ sv _ _ svv =\n assert (u == -1) $\n case eqn of\n EqnG01 -> eqnG11 c s sv svv\n EqnG22 -> q - 0\n EqnSW2 -> w - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\n-- j == 0, v == -1\neqnBndV1 :: (Eq a, Floating a) => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnBndV1 eqn c@(Coord u v) s@(State g q w) su _ _ suu _ =\n assert (v == -1) $\n case eqn of\n EqnG01 -> eqnG00 c s su suu\n EqnG22 -> q - 0\n EqnSW2 -> w - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\neqnEndU1 :: Floating a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnEndU1 eqn c@(Coord u v) s@(State g q w) _ _ _ _ _ =\n case eqn of\n EqnG01 -> g - 1\n EqnG22 -> q - 0\n EqnSW2 -> w - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\neqnEndV1 :: Floating a => Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> a\neqnEndV1 eqn c@(Coord u v) (State g q w) _ _ _ _ _ =\n case eqn of\n EqnG01 -> g - 1\n EqnG22 -> q - 0\n EqnSW2 -> w - bndw c\n EqnG00 -> 0\n EqnG11 -> 0\n\nequation1 :: (Eq a, Floating a) => Coord Int -> Eqn -> Coord a -> State a -> State a -> State a -> State a -> State a -> State a -> a\nequation1 (Coord i j) =\n if\n | i == 0 && j == 0 -> eqnOrig1\n | i == 0 && j == np - 1 -> eqnEndU1\n | i == np - 1 && j == 0 -> eqnEndV1\n | i == 0 -> eqnBndU1\n | j == 0 -> eqnBndV1\n | i == j -> eqnAxis1\n | True -> eqnInt1\n\n--------------------------------------------------------------------------------\n\ng2s :: Storable a => Grid a -> State (Grid a)\ng2s (Grid xs) =\n let [g, q, w] = L.takesV (replicate 3 (np * np)) xs\n in State (Grid g) (Grid q) (Grid w)\n\ns2g :: Storable a => State (Grid a) -> Grid a\ns2g (State (Grid g) (Grid q) (Grid w)) = Grid (L.vjoin [g, q, w])\n\neqn1 ::\n forall a.\n (Eq a, L.Field a, U.Unbox a) =>\n Eqn ->\n Coord (Grid a) ->\n State (Grid a) ->\n Grid a\neqn1 eqn c s =\n Grid $\n L.fromList\n [ eqnRow i j\n | i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n eqnRow :: Int -> Int -> a\n eqnRow i j =\n let at :: Grid a -> a\n at x = x ! (i, j)\n in equation1\n (Coord i j)\n eqn\n (at <$> c)\n (at <$> s)\n (at <$> su)\n (at <$> sv)\n (at <$> suv)\n (at <$> suu)\n (at <$> svv)\n\neqns ::\n forall a.\n (Eq a, L.Field a, U.Unbox a) =>\n Coord (Grid a) ->\n State (Grid a) ->\n Grid a\neqns c s =\n Grid $\n L.fromList\n [ eqnRow (i, j, eqn)\n | eqn <- [EqnG01, EqnG22, EqnSW2],\n i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n eqnRow :: (Int, Int, Eqn) -> a\n eqnRow (i, j, eqn) =\n let at :: Grid a -> a\n at x = x ! (i, j)\n in equation1\n (Coord i j)\n eqn\n (at <$> c)\n (at <$> s)\n (at <$> su)\n (at <$> sv)\n (at <$> suv)\n (at <$> suu)\n (at <$> svv)\n\neqns5 ::\n forall a.\n (Eq a, L.Field a, U.Unbox a) =>\n Coord (Grid a) ->\n State (Grid a) ->\n Grid a\neqns5 c s =\n Grid $\n L.fromList\n [ eqnRow (i, j, eqn)\n | eqn <- [EqnG01, EqnG22, EqnSW2, EqnG00, EqnG11],\n i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n eqnRow :: (Int, Int, Eqn) -> a\n eqnRow (i, j, eqn) =\n let at :: Grid a -> a\n at x = x ! (i, j)\n in equation1\n (Coord i j)\n eqn\n (at <$> c)\n (at <$> s)\n (at <$> su)\n (at <$> sv)\n (at <$> suv)\n (at <$> suu)\n (at <$> svv)\n\nop ::\n forall a.\n (L.Container L.Vector a, Eq a, L.Field a, U.Unbox a) =>\n Coord (Grid a) ->\n State (Grid a) ->\n Op a\nop (Coord u v) s =\n Op $\n L.fromRows\n [ jacRow (i, j, eqn)\n | eqn <- [EqnG01, EqnG22, EqnSW2],\n i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n jacRow :: (Int, Int, Eqn) -> L.Vector a\n jacRow (i, j, eqn) =\n L.vjoin $\n [ let con :: Grid a -> Dual a\n der :: Grid a -> Dual a\n con x = Dual (x ! (i, j)) 0\n der x = Dual (x ! (i, j)) 1\n scon :: State (Grid a) -> State (Dual a)\n sder :: State (Grid a) -> State (Dual a)\n scon (State g q w) = State (con g) (con q) (con w)\n sder (State g q w) = case var of\n VarG -> State (der g) (con q) (con w)\n VarQ -> State (con g) (der q) (con w)\n VarW -> State (con g) (con q) (der w)\n in ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (sder s)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp delta L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (sder su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon su)\n (sder sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon su)\n (scon sv)\n (sder suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivUV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon su)\n (scon sv)\n (scon suv)\n (sder suu)\n (scon svv)\n )\n `L.scale` (getOp derivUU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (sder svv)\n )\n `L.scale` (getOp derivVV L.! (i * np + j))\n )\n | var <- [VarG, VarQ, VarW]\n ]\n\nop5 ::\n forall a.\n (L.Container L.Vector a, Eq a, L.Field a, U.Unbox a) =>\n Coord (Grid a) ->\n State (Grid a) ->\n Op a\nop5 (Coord u v) s =\n Op $\n L.fromRows\n [ jacRow (i, j, eqn)\n | eqn <- [EqnG01, EqnG22, EqnSW2, EqnG00, EqnG11],\n i <- [0 .. np - 1],\n j <- [0 .. np - 1]\n ]\n where\n su = (derivU #>) <$> s\n sv = (derivV #>) <$> s\n suv = (derivUV #>) <$> s\n suu = (derivUU #>) <$> s\n svv = (derivVV #>) <$> s\n jacRow :: (Int, Int, Eqn) -> L.Vector a\n jacRow (i, j, eqn) =\n L.vjoin $\n [ let con :: Grid a -> Dual a\n der :: Grid a -> Dual a\n con x = Dual (x ! (i, j)) 0\n der x = Dual (x ! (i, j)) 1\n scon :: State (Grid a) -> State (Dual a)\n sder :: State (Grid a) -> State (Dual a)\n scon (State g q w) = State (con g) (con q) (con w)\n sder (State g q w) = case var of\n VarG -> State (der g) (con q) (con w)\n VarQ -> State (con g) (der q) (con w)\n VarW -> State (con g) (con q) (der w)\n in ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (sder s)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp delta L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (sder su)\n (scon sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon su)\n (sder sv)\n (scon suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon su)\n (scon sv)\n (sder suv)\n (scon suu)\n (scon svv)\n )\n `L.scale` (getOp derivUV L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon su)\n (scon sv)\n (scon suv)\n (sder suu)\n (scon svv)\n )\n `L.scale` (getOp derivUU L.! (i * np + j))\n )\n `L.add` ( ( dual $\n equation1\n (Coord i j)\n eqn\n (Coord (con u) (con v))\n (scon s)\n (scon su)\n (scon sv)\n (scon suv)\n (scon suu)\n (sder svv)\n )\n `L.scale` (getOp derivVV L.! (i * np + j))\n )\n | var <- [VarG, VarQ, VarW]\n ]\n\n--------------------------------------------------------------------------------\n\ngetTime :: IO Double\ngetTime = do\n t <- getCPUTime\n return $ fromInteger t / 1.0e+12\n\nmain :: IO ()\nmain =\n do\n putStrLn \"Spherically Symmetric Scalar Field in double-Null coordinates\"\n let coords = Coord coordU (coordV @Double)\n let ini = State (gmap g guess) (gmap q guess) (gmap w guess)\n vars0 <- return (s2g ini)\n let done (n, vars) =\n let res = eqns coords (g2s vars)\n in -- let res = eqns5 coords (g2s vars)\n gmaxabs res < 1.0e-12 || n >= 5\n let iter (n, vars) = do\n let res = eqns coords (g2s vars)\n -- let res = eqns5 coords (g2s vars)\n t <- getTime\n putStrLn $\n \"iter \" ++ show n ++ \" time \" ++ show (round t) ++ \" sec |res| \"\n ++ show (gmaxabs res)\n let jac = op coords (g2s vars)\n let dvars = solve jac res\n -- let jac = op5 coords (g2s vars)\n -- let dvars = solveLS jac res\n return (n + 1, vars ^-^ dvars)\n (n1, vars1) <- iterateUntilM done iter (0, vars0)\n putStrLn $ \"var.g \" ++ show (gmap approx $ g $ g2s vars1)\n putStrLn $ \"var.q \" ++ show (gmap approx $ q $ g2s vars1)\n putStrLn $ \"var.w \" ++ show (gmap approx $ w $ g2s vars1)\n putStrLn $ \"res.G01 \" ++ show (gmap approx $ eqn1 EqnG01 coords (g2s vars1))\n putStrLn $ \"res.G22 \" ++ show (gmap approx $ eqn1 EqnG22 coords (g2s vars1))\n putStrLn $ \"res.SW2 \" ++ show (gmap approx $ eqn1 EqnSW2 coords (g2s vars1))\n putStrLn $ \"res.G00 \" ++ show (gmap approx $ eqn1 EqnG00 coords (g2s vars1))\n putStrLn $ \"res.G11 \" ++ show (gmap approx $ eqn1 EqnG11 coords (g2s vars1))\n let res1 = eqns coords (g2s vars1)\n t <- getTime\n putStrLn $\n \"iter \" ++ show n1 ++ \" time \" ++ show (round t) ++ \" sec |res| \"\n ++ show (gmaxabs res1)\n let res5 = eqns5 coords (g2s vars1)\n putStrLn $ \"|res5| \" ++ show (gmaxabs res5)\n -- let h = 2 / (fromIntegral np - 1) :: Double\n -- let alpha = 0.01 * h ^ 3\n -- let smooth = delta - alpha *^ (derivUU * derivUU + derivVV * derivVV)\n -- let vars1s = s2g $ (expfilter #>) <$> g2s vars1\n -- let res5s = eqns5 coords (g2s vars1s)\n -- putStrLn $ \"|res5s| \" ++ show (gmaxabs res5s)\n putStrLn \"Done.\"\n where\n approx :: RealFrac a => a -> a\n approx x = fromInteger (round (1.0e+10 * x)) / 1.0e+10\n", "meta": {"hexsha": "1288d8f9acf281ba2d6b5dee7d997ad2f1c1bd98", "size": 17753, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/ScalarWaveOld.hs", "max_stars_repo_name": "eschnett/sssfn", "max_stars_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ScalarWaveOld.hs", "max_issues_repo_name": "eschnett/sssfn", "max_issues_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ScalarWaveOld.hs", "max_forks_repo_name": "eschnett/sssfn", "max_forks_repo_head_hexsha": "7e00b54460e23fde7a6dd70ac74098958f54e5a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5595463138, "max_line_length": 156, "alphanum_fraction": 0.3568974258, "num_tokens": 5098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.38861042799665546}} {"text": "-- |\n-- Module : Cartesian.Plane.Core\n-- Description :\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 | - Which constraints are appropriate (Num is probably too generic, should be Real, maybe RealFrac)\n-- - Strictness, performance\n-- - Rename (?)\n\n-- SPEC | -\n-- -\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule Cartesian.Plane.Core where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- import Data.List (sort, minimumBy)\n-- import Data.Ord (comparing)\n-- import Data.Complex hiding (magnitude)\n\n-- import Control.Monad (when)\nimport Control.Applicative\n\nimport Control.Lens ((^.))\n\nimport Cartesian.Internal.Types\nimport Cartesian.Internal.Lenses (begin, end)\nimport Cartesian.Internal.Core\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n-- | Determines if a point lies within a polygon using the odd-even method.\n--\n-- TODO: Use epsilon (?)\n-- TODO: How to treat points that lie on an edge\n-- inside :: Num n => Polygon n -> Vector2D n -> Bool\n-- inside polygon (Vector2D px py) = error \"Cartesian.Plane.inside is still a work in progress\"\n-- where\n-- edges = polygon ++ [head polygon] -- Close the loop\n -- between (Line (Vector ax ay) (Vector bx by)) = _\n\n\n-- |\n-- instance Convertible (Vector2D f, Vector3D f) where\n -- _\n\n\n-- TODO: Use type families for this stuff (?)\n\n-- |\n-- to3D :: Num f => Vector2D f -> Vector3D f\n-- to3D (Vector2D x' y') = Vector3D x' y' 0\n\n\n-- -- |\n-- from3D :: Num f => Vector3D f -> Vector2D f\n-- from3D (Vector3D x' y' _) = Vector2D x' y'\n\n\n-- -- | Perform some unary operation on a 2D vector as a 3D vector, converting the result back to 2D by discarding the z component.\n-- -- TODO: Rename (?)\n-- -- TODO: Loosen Num restriction (eg. to anything with a 'zero' value) (?)\n-- in3D :: (Num f, Num f') => (Vector3D f -> Vector3D f') -> Vector2D f -> Vector2D f'\n-- in3D f = from3D . f . to3D\n\n\n-- | Same as in3D, but for binary operations.\n-- _ :: _\n-- _ f = from3D . (dotmap f) . to3D\n\n-- Vector math -----------------------------------------------------------------------------------------------------------------------------\n\n-- | Angle (in radians) between the positive X-axis and the vector\n-- argument :: (Floating a, Eq a) => Vector a -> a\n-- argument (Vector 0 0) = 0\n-- argument (Vector x y) = atan $ y/x\n--\n--\n-- arg :: (Floating a, Eq a) => Vector a -> a\n-- arg = argument\n--\n--\n-- -- | Vector -> (magnitude, argument)\n-- polar :: (Floating a, Eq a) => Vector a -> (a, a)\n-- polar v@(Vector x y) = (magnitude v, argument v)\n\n-- Linear functions ------------------------------------------------------------------------------------------------------------------------\n\n-- | Yields the intersection point of two finite lines. The lines are defined inclusively by\n-- their endpoints. The result is wrapped in a Maybe value to account for non-intersecting\n-- lines.\n-- TODO: Refactor\n-- TODO: Move equation solving to separate function (two linear functions)\n-- TODO: Invariants, check corner cases\n-- TODO: Deal with vertical lines\n-- TODO: Factor out infinite-line logic\n-- TODO: Decide how to deal with identical lines\n-- TODO: Factor out domain logic (eg. write restrict or domain function)\n-- TODO: Return Either instead of Maybe (eg. Left \"parallel\") (?)\n-- TODO: Visual debugging functions\n-- TODO: Math notes, MathJax or LaTex\n-- TODO: Intersect for curves (functions) and single points (?)\n-- TODO: Polymorphic, typeclass (lines, shapes, ranges, etc.) (?)\n-- TODO: Intersect Rectangles\nintersect :: RealFloat f => Line (Vector2D f) -> Line (Vector2D f) -> Maybe (Vector2D f)\nintersect f' g' = do\n p <- mp\n indomain f' p\n indomain g' p\n where\n -- indomain :: RealFloat f => Line (Vector2D f) -> Vector2D f -> Maybe (Vector2D f)\n indomain h' = restrict (h'^.begin) (h'^.end) -- TODO: Rename\n \n -- mp :: Maybe (Vector2D f)\n mp = case (linear f', linear g') of\n (Just f, Nothing) -> let x' = g'^.begin.x in Just . Vector2D x' $ plotpoint f x'\n (Nothing, Just g) -> let x' = f'^.begin.x in Just . Vector2D x' $ plotpoint g x'\n (Just f, Just g) -> linearIntersect f g\n _ -> Nothing\n\n\n-- | Gives the linear function overlapping the given segment, or Nothing if there is no such function\nlinear :: RealFloat f => Line (Vector2D f) -> Maybe (Linear f)\nlinear line = Linear <$> intercept line <*> slope line\n\n\n-- | Applies a linear function to the given value\n-- TODO: Rename (?)\nplotpoint :: RealFloat f => Linear f -> f -> f\nplotpoint f x' = slopeOf f*x' + interceptOf f\n\n\n-- | Finds the intersection (if any) of two linear functions\n-- TODO: Use Epsilon (?)\n-- TODO: Rename (eg. 'solve') (?)\nlinearIntersect :: RealFloat f => Linear f -> Linear f -> Maybe (Vector2D f)\nlinearIntersect f g\n | slopeOf f == slopeOf g = Nothing\n | otherwise = let x' = (β-b)/(a-α) in Just $ Vector2D x' (a*x' + b)\n where\n (a, α) = (slopeOf f, slopeOf g)\n (b, β) = (interceptOf f, interceptOf g)\n\n\n-- |\nslope :: RealFloat f => Line (Vector2D f) -> Maybe f\nslope (Line fr to)\n | dx == 0 = Nothing\n | otherwise = Just $ dy/dx\n where\n (Vector2D dx dy) = liftA2 (-) to fr\n\n\n-- |\nintercept :: RealFloat f => Line (Vector2D f) -> Maybe f\nintercept line = do\n slope' <- slope line\n return $ y' - slope'*x'\n where\n (Vector2D x' y') = line^.begin\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n-- | Ensures that a given point lies within the domain and codomain\n-- TODO: Make polymorphic\n-- TODO: Let this function work on scalars, write another function for domain and codomain (?)\n-- restrict domain codomain p = _\n-- restrict :: (Applicative v, Traversable v, Num n, Ord n) => v n -> v n -> v n -> Maybe (v n)\n-- restrict a b p@(Vector2D x' y')\n-- | indomain && incodomain = Just p\n-- | otherwise = Nothing\n-- where\n-- (Vector2D lowx lowy) = dotwise min a b\n-- (Vector2D highx highy) = dotwise max a b\n-- indomain = between lowx highx x'\n-- incodomain = between lowy highy y'\n", "meta": {"hexsha": "8d56cc0fa4f8afe40c4e7b093d62fef13ddf98c3", "size": 7151, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Cartesian/Plane/Core.hs", "max_stars_repo_name": "jordanemedlock/Cartesian", "max_stars_repo_head_hexsha": "ed05b53a14f9a7f9ebb21b7cd9affae3d95af3f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-01-05T13:11:24.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-05T13:11:24.000Z", "max_issues_repo_path": "src/Cartesian/Plane/Core.hs", "max_issues_repo_name": "jordanemedlock/Cartesian", "max_issues_repo_head_hexsha": "ed05b53a14f9a7f9ebb21b7cd9affae3d95af3f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cartesian/Plane/Core.hs", "max_forks_repo_name": "jordanemedlock/Cartesian", "max_forks_repo_head_hexsha": "ed05b53a14f9a7f9ebb21b7cd9affae3d95af3f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-12T23:31:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-12T23:31:50.000Z", "avg_line_length": 36.1161616162, "max_line_length": 140, "alphanum_fraction": 0.5112571668, "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.387647817650684}} {"text": "-- This module has functions that store pinwheels to disk and read them out to do convolution,\n-- for the purpose of handling the case when filter size is greater than RAM size.\nmodule STC.Binary\n ( makePlanBinary\n , computeInitialEigenVectorBinary\n , writeDFTPinwheel\n , convolutionBinary\n ) where\n\nimport Array.UnboxedArray as AU\nimport Control.Monad as M\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Resource\nimport Data.Array.Repa as R\nimport Data.Binary\nimport Data.ByteString.Lazy as BSL\nimport Data.ByteString.Lazy as BS\nimport Data.Complex\nimport Data.Conduit\nimport Control.DeepSeq (($!!))\nimport Data.Conduit.List as CL\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport DFT.Plan\nimport Filter.Pinwheel\nimport FokkerPlanck.Interpolation\nimport FokkerPlanck.Pinwheel (cutoff)\nimport GHC.Float\nimport System.IO\nimport System.Random\nimport Types\nimport Utils.Array\nimport Utils.Parallel (ParallelParams (..),\n parConduitIO)\n\nmakePlanBinary ::\n DFTPlan -> Bool -> FilePath -> Int -> Int -> Int -> Int -> IO DFTPlan\nmakePlanBinary oldPlan wisdomFlag wisdomFilePath numThetaFreqs numScaleFreqs rows cols = do\n let n = numThetaFreqs * numScaleFreqs * rows * cols\n xs <- M.replicateM n randomIO :: IO [Double]\n ys <- M.replicateM n randomIO :: IO [Double]\n let vecTemp = VS.fromList . L.zipWith (:+) xs $ ys\n when wisdomFlag (importFFTWWisdom wisdomFilePath)\n lock <- getFFTWLock\n plan <-\n fst <$>\n (dft1dGPlan\n lock\n oldPlan\n [cols, rows, numThetaFreqs, numScaleFreqs]\n [0, 1]\n vecTemp >>= \\(plan, vec) ->\n idft1dGPlan\n lock\n plan\n [cols, rows, numThetaFreqs, numScaleFreqs]\n [0, 1]\n vec >>= \\(plan, vec) ->\n dft1dGPlan\n lock\n plan\n [numThetaFreqs, numScaleFreqs, cols, rows]\n [0, 1]\n vec >>= \\(plan, vec) ->\n idft1dGPlan\n lock\n plan\n [numThetaFreqs, numScaleFreqs, cols, rows]\n [0, 1]\n vec)\n exportFFTWWisdom wisdomFilePath\n return plan\n\n\ncomputeInitialEigenVectorBinary ::\n Int\n -> Int\n -> [Double]\n -> [Double]\n -> [R2S1RPPoint]\n -> R2Z2Array\ncomputeInitialEigenVectorBinary xLen yLen thetaFreqs scaleFreqs xs =\n let numThetaFreqs = L.length thetaFreqs\n numScaleFreqs = L.length scaleFreqs\n xShift = div xLen 2\n (xMin, xMax) =\n if odd xLen\n then (-xShift, xShift)\n else (-xShift, xShift - 1)\n yShift = div yLen 2\n (yMin, yMax) =\n if odd yLen\n then (-yShift, yShift)\n else (-yShift, yShift - 1)\n vec =\n toUnboxedVector .\n AU.accum (+) 0 ((xMin, yMin), (xMax, yMax)) .\n L.map\n (\\(R2S1RPPoint (x, y, _, _)) ->\n ((x, y), 1 / (fromIntegral . L.length $ xs))) $\n xs\n in computeS .\n R.traverse\n (fromUnboxed (Z :. xLen :. yLen) vec)\n (const (Z :. numThetaFreqs :. numScaleFreqs :. xLen :. yLen)) $ \\f idx@(Z :. tf :. sf :. i :. j) ->\n if tf == div numThetaFreqs 2 && sf == div numScaleFreqs 2\n then f (Z :. i :. j)\n else 0\n\n{-# INLINE convertDFTPinwheel #-}\nconvertDFTPinwheel ::\n DFTPlan\n -> R.Array D DIM5 Double\n -> R.Array U DIM1 Double\n -> R.Array U DIM1 Double\n -> Double\n -> Double\n -> (Int, Int)\n -> (Int, Int)\n -> IO BS.ByteString\nconvertDFTPinwheel plan radialArr thetaFreqs scaleFreqs hollowRadius rMax (rows, cols) (t, s) =\n let (Z :. numThetaFreq :. numScaleFreq :. numTheta0Freq :. numScale0Freq :. _) =\n extent radialArr\n pinwheelArr =\n traverse2\n thetaFreqs\n scaleFreqs\n (\\_ _ -> (Z :. numTheta0Freq :. numScale0Freq :. cols :. rows)) $ \\ft0 fs0 (Z :. t0 :. s0 :. i :. j) ->\n pinwheelFunc\n (PinwheelHollow0 hollowRadius)\n (thetaFreqs R.! (Z :. t) - ft0 (Z :. t0))\n (scaleFreqs R.! (Z :. s) + fs0 (Z :. s0))\n rMax\n 0\n (i - center cols)\n (j - center rows)\n interpolatedPinwheelArr =\n radialCubicInterpolation\n (R.slice radialArr (Z :. t :. s :. All :. All :. All))\n 1\n pinwheelArr\n in do xx <-\n fmap\n (encode .\n L.map (\\(x :+ y) -> double2Float x :+ double2Float y) . VS.toList) .\n dftExecute\n plan\n (DFTPlanID DFT1DG [cols, rows, numTheta0Freq, numScale0Freq] [0, 1]) .\n VS.convert . toUnboxed . computeS . rotate4D2 . makeFilter2D $\n interpolatedPinwheelArr\n return $!! xx\n\n{-# INLINE writeDFTPinwheelSink #-}\nwriteDFTPinwheelSink ::\n FilePath -> ConduitT BS.ByteString Void (ResourceT IO) ()\nwriteDFTPinwheelSink filePath = do\n h <- liftIO $ openBinaryFile filePath WriteMode\n go h\n where\n go h = do\n z <- await\n case z of\n Nothing -> liftIO $ hClose h\n Just bs -> do\n liftIO . BSL.hPut h . encode . BS.length $ bs\n liftIO . BS.hPut h $ bs\n go h\n\nwriteDFTPinwheel ::\n ParallelParams\n -> DFTPlan\n -> R.Array D DIM5 Double\n -> Double\n -> Double\n -> [Double]\n -> [Double]\n -> Double\n -> (Int, Int)\n -> FilePath\n -> IO ()\nwriteDFTPinwheel parallelParams plan radialArr hollowRadius cutoffRadius thetaFreqs scaleFreqs rMax (rows, cols) filePath = do\n let (Z :. numThetaFreq :. numScaleFreq :. numTheta0Freq :. numScale0Freq :. _) =\n extent radialArr\n thetaFreqsArr = fromListUnboxed (Z :. L.length thetaFreqs) thetaFreqs\n scaleFreqsArr = fromListUnboxed (Z :. L.length scaleFreqs) scaleFreqs\n runConduitRes $\n CL.sourceList\n [(t, s) | t <- [0 .. numThetaFreq - 1], s <- [0 .. numScaleFreq - 1]] .|\n parConduitIO\n parallelParams\n (convertDFTPinwheel\n plan\n (cutoff (round cutoffRadius) radialArr)\n thetaFreqsArr\n scaleFreqsArr\n hollowRadius\n rMax\n (rows, cols)) .|\n writeDFTPinwheelSink filePath\n\n{-# INLINE sourceBinary #-}\nsourceBinary :: FilePath -> ConduitT () BS.ByteString (ResourceT IO) ()\nsourceBinary filePath = do\n h <- liftIO $ openBinaryFile filePath ReadMode\n go h\n where\n go handle = do\n lenBS <- liftIO (BSL.hGet handle 8)\n if BSL.null lenBS\n then liftIO $ hClose handle\n else do\n let len = decode lenBS :: Int\n bs <- liftIO . BS.hGet handle $ len\n yield bs\n go handle\n\n{-# INLINE convolution #-}\nconvolution ::\n Bool\n -> DFTPlan\n -> DIM4\n -> R.Array U DIM1 Double\n -> VS.Vector (Complex Double)\n -> BS.ByteString\n -> IO (VU.Vector (Complex Double))\nconvolution True plan dim@(Z :. cols :. rows :. numThetaFreq :. numScaleFreq) thetaFreqs input bs = do\n arr <-\n fmap (fromUnboxed dim . VS.convert) .\n dftExecute\n plan\n (DFTPlanID IDFT1DG [cols, rows, numThetaFreq, numScaleFreq] [0, 1]) .\n VS.zipWith (*) input $\n VS.fromList . L.map (\\(x :+ y) -> float2Double x :+ float2Double y) . decode $\n bs\n return $!! toUnboxed . sumS . sumS . R.traverse2 arr thetaFreqs const $\n (\\f ft idx@(Z :. _ :. _ :. i :. _) -> f idx * exp (0 :+ ft (Z :. i) * pi))\nconvolution False plan dim@(Z :. cols :. rows :. numThetaFreq :. numScaleFreq) thetaFreqs input bs = do\n x <-\n fmap (toUnboxed . sumS . sumS . fromUnboxed dim . VS.convert) .\n dftExecute\n plan\n (DFTPlanID IDFT1DG [cols, rows, numThetaFreq, numScaleFreq] [0, 1]) .\n VS.zipWith (*) input .\n VS.fromList . L.map (\\(x :+ y) -> float2Double x :+ float2Double y) . decode $\n bs\n return $!! x\n\n\nconvolutionBinary ::\n Bool\n -> ParallelParams\n -> DFTPlan\n -> FilePath\n -> [Double]\n -> R.Array U DIM4 (Complex Double)\n -> IO (R.Array U DIM4 (Complex Double))\nconvolutionBinary sinkFlag parallelParams plan filterFilePath thetaFreqs inputArr = do\n let thetaFreqsArr = fromListUnboxed (Z :. (L.length thetaFreqs)) thetaFreqs\n (Z :. numThetaFreq :. numScaleFreq :. cols :. rows) = extent inputArr\n inputArrF <-\n dftExecute\n plan\n (DFTPlanID DFT1DG [cols, rows, numThetaFreq, numScaleFreq] [0, 1]) .\n VU.convert . toUnboxed . computeS . rotate4D2 $\n inputArr\n xs <-\n runConduitRes $\n sourceBinary filterFilePath .|\n parConduitIO\n parallelParams\n (convolution\n sinkFlag\n plan\n (Z :. cols :. rows :. numThetaFreq :. numScaleFreq)\n thetaFreqsArr\n inputArrF) .|\n CL.consume\n let arr = fromUnboxed (extent inputArr) . VU.concat $ xs\n return $\n if sinkFlag\n then computeS . R.traverse2 arr thetaFreqsArr const $ \\f ft idx@(Z :. i :. _ :. _ :. _) ->\n f idx * exp (0 :+ ft (Z :. i) * pi)\n else arr\n", "meta": {"hexsha": "75af804f92b03fc69e7377d138eec4f031d14c79", "size": 9147, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/Binary.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/Binary.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/Binary.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 32.0947368421, "max_line_length": 126, "alphanum_fraction": 0.5742866514, "num_tokens": 2695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3876351218847605}} {"text": "{-# LANGUAGE DuplicateRecordFields #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n-- |\n-- Module : PSO.Heisenberg\n-- Description : Heisenberg Hamiltonian\n-- Copyright : (c) Tom Westerhout, 2017\n-- License : BSD3\n-- Maintainer : t.westerhout@student.ru.nl\n-- Stability : experimental\nmodule PSO.Heisenberg\n ( -- * Introduction\n --\n -- | Let's start with a 1D chain of \\(N\\) spin-1/2 particles. Each of them\n -- is described by a state \\(|\\alpha_i\\rangle\\in\\mathbb{C}^2\\). Hilbert\n -- space of the whole system is then \\(\\bigotimes_{i=0}^{N-1}\\mathbb{C}^2\\).\n --\n -- We use the following Hamiltonian to describe this system:\n -- \\[\n -- \\hat{\\mathcal{H}} = \\sum_{i=0}^{N-2}\n -- \\hat{\\boldsymbol\\sigma}_i \\cdot \\hat{\\boldsymbol\\sigma}_{i+1}\n -- = \\sum_{i=0}^{N-2}\n -- \\hat{\\sigma}_i^{(x)}\\hat{\\sigma}_{i+1}^{(x)}\n -- + \\hat{\\sigma}_i^{(y)}\\hat{\\sigma}_{i+1}^{(y)}\n -- + \\hat{\\sigma}_i^{(z)}\\hat{\\sigma}_{i+1}^{(z)} \\;.\n -- \\]\n -- Only the nearest neighbours are connected. The boundary conditions used\n -- are called /open/ because the zeroth and N-1st spins don't interact.\n one2D\n , pauliX\n , pauliY\n , pauliZ\n , heisenberg1DOpen\n -- * Quantities of interest\n --\n -- | The quantity we're actually interested in is\n -- \\[\n -- \\frac{\\langle\\sigma| \\hat{\\mathcal{H}} |\\psi\\rangle}{%\n -- \\langle\\sigma|\\psi\\rangle} \\;,\n -- \\]\n -- where \\(|\\psi\\rangle\\) is described by the RBM \\(\\mathcal{W}\\) and\n -- \\(|\\sigma\\rangle\\in\\{\\downarrow,\\uparrow\\}^N\\) is a spin configuration.\n -- We call this quantity /local energy/ \\(E_{loc}(\\sigma;\\mathcal{W})\\).\n -- \\[\n -- E_{loc}(\\sigma;\\mathcal{W}) = \\sum_i \\frac{\\langle\\sigma|\n -- \\hat{\\boldsymbol\\sigma}_i\\cdot\\hat{\\boldsymbol\\sigma}_{i+1}\n -- |\\psi\\rangle}{\\langle\\sigma|\\psi\\rangle}\n -- \\]\n -- Now\n -- \\[\n -- \\begin{aligned}\n -- &\\hat{\\boldsymbol\\sigma}_1\\cdot\\hat{\\boldsymbol\\sigma}_2\n -- |\\uparrow\\uparrow\\rangle = |\\uparrow\\uparrow\\rangle \\;,\\\\\n -- &\\hat{\\boldsymbol\\sigma}_1\\cdot\\hat{\\boldsymbol\\sigma}_2\n -- |\\downarrow\\downarrow\\rangle = |\\downarrow\\downarrow\\rangle \\;,\\\\\n -- &\\hat{\\boldsymbol\\sigma}_1\\cdot\\hat{\\boldsymbol\\sigma}_2\n -- |\\uparrow\\downarrow\\rangle = |\\uparrow\\downarrow\\rangle\n -- - 2|\\downarrow\\uparrow\\rangle \\;,\\\\\n -- &\\hat{\\boldsymbol\\sigma}_1\\cdot\\hat{\\boldsymbol\\sigma}_2\n -- |\\downarrow\\uparrow\\rangle = |\\downarrow\\uparrow\\rangle\n -- - 2|\\uparrow\\downarrow\\rangle \\;.\n -- \\end{aligned}\n -- \\]\n -- , locEnergyHH1DOpen\n ) where\n\nimport Data.Complex(Complex(..))\nimport Numeric.LinearAlgebra(C, Matrix, Herm, (><), trustSym, kronecker)\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Data.Vector.Storable as V\n\n-- import PSO.Internal.Spin\n\n\none2D :: Matrix C\none2D = (2><2)\n [ 1.0, 0.0\n , 0.0, 1.0 ]\n\npauliX :: Matrix C\npauliX = (2><2)\n [ 0.0, 1.0\n , 1.0, 0.0 ]\n\npauliY :: Matrix C\npauliY = (2><2)\n [ 0.0, 0.0 :+ (-1.0)\n , 0.0 :+ 1.0, 0.0 ]\n\npauliZ :: Matrix C\npauliZ = (2><2)\n [ 1.0, 0.0\n , 0.0, (-1.0) ]\n\nrotate :: Int -> [a] -> [a]\nrotate n xs = zipWith const (drop n (cycle xs)) xs\n\nheisenberg1DOpen :: Int -> Herm C\nheisenberg1DOpen n\n | n > 2 = trustSym $ heisenberg1DOpenImpl n pauliX\n + heisenberg1DOpenImpl n pauliY\n + heisenberg1DOpenImpl n pauliZ\n | n == 2 = trustSym $ pauliX `kronecker` pauliX\n + pauliY `kronecker` pauliY\n + pauliZ `kronecker` pauliZ\n | otherwise = undefined\n\nheisenberg1DOpenImpl :: Int -> Matrix C -> Matrix C\nheisenberg1DOpenImpl n pauli =\n let xs = (replicate (n-2) one2D) ++ (replicate 2 pauli)\n rotations = take (n-1) . iterate (rotate 1) $ xs\n in sum . map (foldr1 kronecker) $ rotations\n\n-- locEnergyHH1DOpen ::\n-- (Floating α, Eq α, Num (V.Vector α), LA.Numeric α)\n-- => RBM α -> V.Vector α -> α\n-- locEnergyHH1DOpen machine σ =\n-- let θ = mkTheta machine σ\n-- zipper i x y\n-- | x == y = 1\n-- | otherwise = -1 + 2 * exp (logPoP2 machine θ σ (i, i + 1))\n-- in V.sum $ V.izipWith zipper σ (V.tail σ)\n\n", "meta": {"hexsha": "b34b6ed0cf2fe9f5874abaa597e562f889963462", "size": 4248, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/PSO/Heisenberg.hs", "max_stars_repo_name": "twesterhout/tcm-swarm", "max_stars_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PSO/Heisenberg.hs", "max_issues_repo_name": "twesterhout/tcm-swarm", "max_issues_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PSO/Heisenberg.hs", "max_forks_repo_name": "twesterhout/tcm-swarm", "max_forks_repo_head_hexsha": "e632d493a9dc0b78c2634c2ac6311abc5f99168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.984, "max_line_length": 80, "alphanum_fraction": 0.5779190207, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3874223168522451}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}\n\nmodule Grenade.Recurrent.Layers.LSTM (\n LSTM (..)\n , LSTMWeights (..)\n , randomLSTM\n ) where\n\nimport Control.Monad.Primitive (PrimBase, PrimState)\nimport System.Random.MWC hiding (create)\nimport GHC.TypeLits\n\n-- import Data.List ( foldl1' )\nimport Data.Proxy\nimport Data.Serialize\n\n#if MIN_VERSION_base(4,9,0)\nimport Data.Kind (Type)\n#endif\n\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Static\n\nimport Grenade.Core\nimport Grenade.Utils.LinearAlgebra\nimport Grenade.Recurrent.Core\nimport Grenade.Layers.Internal.Update\n\n\n-- | Long Short Term Memory Recurrent unit\n--\n-- This is a Peephole formulation, so the recurrent shape is\n-- just the cell state, the previous output is not held or used\n-- at all.\ndata LSTM :: Nat -> Nat -> Type where\n LSTM :: ( KnownNat input\n , KnownNat output\n ) => !(LSTMWeights input output) -- Weights\n -> !(LSTMWeights input output) -- Momentums\n -> LSTM input output\n\ndata LSTMWeights :: Nat -> Nat -> Type where\n LSTMWeights :: ( KnownNat input\n , KnownNat output\n ) => {\n lstmWf :: !(L output input) -- Weight Forget (W_f)\n , lstmUf :: !(L output output) -- Cell State Forget (U_f)\n , lstmBf :: !(R output) -- Bias Forget (b_f)\n , lstmWi :: !(L output input) -- Weight Input (W_i)\n , lstmUi :: !(L output output) -- Cell State Input (U_i)\n , lstmBi :: !(R output) -- Bias Input (b_i)\n , lstmWo :: !(L output input) -- Weight Output (W_o)\n , lstmUo :: !(L output output) -- Cell State Output (U_o)\n , lstmBo :: !(R output) -- Bias Output (b_o)\n , lstmWc :: !(L output input) -- Weight Cell (W_c)\n , lstmBc :: !(R output) -- Bias Cell (b_c)\n } -> LSTMWeights input output\n\ninstance Show (LSTM i o) where\n show LSTM {} = \"LSTM\"\n\ninstance FoldableGradient (LSTMWeights input output) where\n mapGradient f (LSTMWeights wf uf bf wi ui bi wo uo bo wc bc) =\n LSTMWeights (dmmap f wf) (dmmap f uf) (dvmap f bf) (dmmap f wi) (dmmap f ui) (dvmap f bi) (dmmap f wo) (dmmap f uo) (dvmap f bo) (dmmap f wc) (dvmap f bc)\n squaredSums (LSTMWeights wf uf bf wi ui bi wo uo bo wc bc) =\n [ sumM . squareM $ wf\n , sumM . squareM $ uf\n , sumV . squareV $ bf\n , sumM . squareM $ wi\n , sumM . squareM $ ui\n , sumV . squareV $ bi\n , sumM . squareM $ wo\n , sumM . squareM $ uo\n , sumV . squareV $ bo\n , sumM . squareM $ wc\n , sumV . squareV $ bc\n ]\n\ninstance (KnownNat i, KnownNat o) => UpdateLayer (LSTM i o) where\n -- The gradients are the same shape as the weights and momentum\n -- This seems to be a general pattern, maybe it should be enforced.\n type Gradient (LSTM i o) = (LSTMWeights i o)\n\n -- Run the update function for each group matrix/vector of weights, momentums and gradients.\n -- Hmm, maybe the function should be used instead of passing in the learning parameters.\n runUpdate opt@OptSGD{} (LSTM w m) g =\n let MatrixResultSGD wf wf' = u lstmWf w m g\n MatrixResultSGD uf uf' = u lstmUf w m g\n VectorResultSGD bf bf' = v lstmBf w m g\n MatrixResultSGD wi wi' = u lstmWi w m g\n MatrixResultSGD ui ui' = u lstmUi w m g\n VectorResultSGD bi bi' = v lstmBi w m g\n MatrixResultSGD wo wo' = u lstmWo w m g\n MatrixResultSGD uo uo' = u lstmUo w m g\n VectorResultSGD bo bo' = v lstmBo w m g\n MatrixResultSGD wc wc' = u lstmWc w m g\n VectorResultSGD bc bc' = v lstmBc w m g\n in LSTM (LSTMWeights wf uf bf wi ui bi wo uo bo wc bc) (LSTMWeights wf' uf' bf' wi' ui' bi' wo' uo' bo' wc' bc')\n where\n -- Utility function for updating with the momentum, gradients, and weights.\n u :: forall x ix out. (KnownNat ix, KnownNat out) => (x -> L out ix) -> x -> x -> x -> MatrixResult out ix\n u e (e -> weights) (e -> momentum) (e -> gradient) =\n descendMatrix opt (MatrixValuesSGD weights gradient momentum)\n\n v :: forall x ix. (KnownNat ix) => (x -> R ix) -> x -> x -> x -> VectorResult ix\n v e (e -> weights) (e -> momentum) (e -> gradient) =\n descendVector opt (VectorValuesSGD weights gradient momentum)\n runUpdate _ d g = runUpdate defOptimizer d g\n\n -- There's a lot of updates here, so to try and minimise the number of data copies\n -- we'll create a mutable bucket for each.\n -- runUpdates rate lstm gs =\n -- let combinedGradient = foldl1' uu gs\n -- in runUpdate rate lstm combinedGradient\n -- where\n -- uu :: (KnownNat i, KnownNat o) => LSTMWeights i o -> LSTMWeights i o -> LSTMWeights i o\n -- uu a b =\n -- let wf = u lstmWf a b\n -- uf = u lstmUf a b\n -- bf = v lstmBf a b\n -- wi = u lstmWi a b\n -- ui = u lstmUi a b\n -- bi = v lstmBi a b\n -- wo = u lstmWo a b\n -- uo = u lstmUo a b\n -- bo = v lstmBo a b\n -- wc = u lstmWc a b\n -- bc = v lstmBc a b\n -- in LSTMWeights wf uf bf wi ui bi wo uo bo wc bc\n -- u :: forall x ix out. (KnownNat ix, KnownNat out) => (x -> (L out ix)) -> x -> x -> L out ix\n -- u e (e -> a) (e -> b) = tr $ tr a + tr b\n\n -- v :: forall x ix. (x -> (R ix)) -> x -> x -> R ix\n -- v e (e -> a) (e -> b) = a + b\n\ninstance (KnownNat i, KnownNat o, KnownNat (i*o), KnownNat (o*o)) => RandomLayer (LSTM i o) where\n createRandomWith = randomLSTM\n\ninstance (KnownNat i, KnownNat o) => RecurrentUpdateLayer (LSTM i o) where\n -- The recurrent shape is the same size as the output.\n -- It's actually the cell state however, as this is a peephole variety LSTM.\n type RecurrentShape (LSTM i o) = S ('D1 o)\n\ninstance (KnownNat i, KnownNat o) => RecurrentLayer (LSTM i o) ('D1 i) ('D1 o) where\n\n -- The tape stores essentially every variable we calculate,\n -- so we don't have to run any forwards component again.\n type RecTape (LSTM i o) ('D1 i) ('D1 o) = (R o, R i, R o, R o, R o, R o, R o, R o, R o, R o, R o)\n -- Forward propagation for the LSTM layer.\n -- The size of the cell state is also the size of the output.\n runRecurrentForwards (LSTM lw _) (S1D cell) (S1D input) =\n let -- Forget state vector\n f_s = lstmBf lw + lstmWf lw #> input + lstmUf lw #> cell\n f_t = sigmoid f_s\n -- Input state vector\n i_s = lstmBi lw + lstmWi lw #> input + lstmUi lw #> cell\n i_t = sigmoid i_s\n -- Output state vector\n o_s = lstmBo lw + lstmWo lw #> input + lstmUo lw #> cell\n o_t = sigmoid o_s\n -- Cell input state vector\n c_s = lstmBc lw + lstmWc lw #> input\n c_x = tanh c_s\n -- Cell state\n c_t = f_t * cell + i_t * c_x\n -- Output (it's sometimes recommended to use tanh c_t)\n h_t = o_t * c_t\n in ((cell, input, f_s, f_t, i_s, i_t, o_s, o_t, c_s, c_x, c_t), S1D c_t, S1D h_t)\n\n -- Run a backpropogation step for an LSTM layer.\n -- We're doing all the derivatives by hand here, so one should\n -- be extra careful when changing this.\n --\n -- There's a test version using the AD library without hmatrix in the test\n -- suite. These should match always.\n runRecurrentBackwards (LSTM lw _) (cell, input, f_s, f_t, i_s, i_t, o_s, o_t, c_s, c_x, c_t) (S1D cellGrad) (S1D h_t') =\n let -- Reverse Mode AD Derivitives\n c_t' = h_t' * o_t + cellGrad\n\n f_t' = c_t' * cell\n f_s' = sigmoid' f_s * f_t'\n\n o_t' = h_t' * c_t\n o_s' = sigmoid' o_s * o_t'\n\n i_t' = c_t' * c_x\n i_s' = sigmoid' i_s * i_t'\n\n c_x' = c_t' * i_t\n c_s' = tanh' c_s * c_x'\n\n -- The derivatives to pass sideways (recurrent) and downwards\n cell' = tr (lstmUf lw) #> f_s' + tr (lstmUo lw) #> o_s' + tr (lstmUi lw) #> i_s' + c_t' * f_t\n input' = tr (lstmWf lw) #> f_s' + tr (lstmWo lw) #> o_s' + tr (lstmWi lw) #> i_s' + tr (lstmWc lw) #> c_s'\n\n -- Calculate the gradient Matricies for the input\n lstmWf' = f_s' `outer` input\n lstmWi' = i_s' `outer` input\n lstmWo' = o_s' `outer` input\n lstmWc' = c_s' `outer` input\n\n -- Calculate the gradient Matricies for the cell\n lstmUf' = f_s' `outer` cell\n lstmUi' = i_s' `outer` cell\n lstmUo' = o_s' `outer` cell\n\n -- The biases just get the values, but we'll write it so it's obvious\n lstmBf' = f_s'\n lstmBi' = i_s'\n lstmBo' = o_s'\n lstmBc' = c_s'\n\n gradients = LSTMWeights lstmWf' lstmUf' lstmBf' lstmWi' lstmUi' lstmBi' lstmWo' lstmUo' lstmBo' lstmWc' lstmBc'\n in (gradients, S1D cell', S1D input')\n\n-- | Generate an LSTM layer with random Weights\n-- one can also just call createRandom from UpdateLayer\n--\n-- Has forget gate biases set to 1 to encourage early learning.\n--\n-- https://github.com/karpathy/char-rnn/commit/0dfeaa454e687dd0278f036552ea1e48a0a408c9\n--\nrandomLSTM :: forall m i o. (PrimBase m, KnownNat i, KnownNat o, KnownNat (i*o),KnownNat (o*o))\n => NetworkInitSettings -> Gen (PrimState m) -> m (LSTM i o)\nrandomLSTM (NetworkInitSettings m HMatrix _) gen = do\n let w = getRandomMatrix i o m gen\n let u = getRandomMatrix i o m gen\n let v = getRandomVector i o m gen\n\n let w0 = konst 0\n u0 = konst 0\n v0 = konst 0\n\n LSTM <$> (LSTMWeights <$> w <*> u <*> pure (konst 1) <*> w <*> u <*> v <*> w <*> u <*> v <*> w <*> v)\n <*> pure (LSTMWeights w0 u0 v0 w0 u0 v0 w0 u0 v0 w0 v0)\n\n where i = natVal (Proxy :: Proxy i)\n o = natVal (Proxy :: Proxy o)\nrandomLSTM (NetworkInitSettings _ cpu _) _ = error $ \"CPU backend \" ++ show cpu ++ \" not supported by LSTM layer\"\n\n-- | Maths\n--\n-- TODO: Move to not here\n-- Optimise backwards derivative\nsigmoid :: Floating a => a -> a\nsigmoid x = 1 / (1 + exp (-x))\n\nsigmoid' :: Floating a => a -> a\nsigmoid' x = logix * (1 - logix)\n where\n logix = sigmoid x\n\ntanh' :: (Floating a) => a -> a\ntanh' t = 1 - s ^ (2 :: Int) where s = tanh t\n\ninstance (KnownNat i, KnownNat o) => Serialize (LSTM i o) where\n put (LSTM lw _) = do\n u (lstmWf lw)\n u (lstmUf lw)\n v (lstmBf lw)\n u (lstmWi lw)\n u (lstmUi lw)\n v (lstmBi lw)\n u (lstmWo lw)\n u (lstmUo lw)\n v (lstmBo lw)\n u (lstmWc lw)\n v (lstmBc lw)\n where\n u :: forall a b. (KnownNat a, KnownNat b) => Putter (L b a)\n u = putListOf put . LA.toList . LA.flatten . extract\n v :: forall a. (KnownNat a) => Putter (R a)\n v = putListOf put . LA.toList . extract\n\n get = do\n w <- LSTMWeights <$> u <*> u <*> v <*> u <*> u <*> v <*> u <*> u <*> v <*> u <*> v\n return $ LSTM w (LSTMWeights w0 u0 v0 w0 u0 v0 w0 u0 v0 w0 v0)\n where\n u :: forall a b. (KnownNat a, KnownNat b) => Get (L b a)\n u = let f = fromIntegral $ natVal (Proxy :: Proxy a)\n in maybe (fail \"Vector of incorrect size\") return . create . LA.reshape f . LA.fromList =<< getListOf get\n v :: forall a. (KnownNat a) => Get (R a)\n v = maybe (fail \"Vector of incorrect size\") return . create . LA.fromList =<< getListOf get\n\n w0 = konst 0\n u0 = konst 0\n v0 = konst 0\n\n-------------------- GNum instances --------------------\n\ninstance (KnownNat i, KnownNat o) => GNum (LSTM i o) where\n n |* (LSTM w m) = LSTM (n |* w) (n |* m)\n (LSTM w1 m1) |+ (LSTM w2 m2) = LSTM (w1 |+ w2) (m1 |+ m2)\n\n\ninstance (KnownNat i, KnownNat o) => GNum (LSTMWeights i o) where\n n |* (LSTMWeights wf uf bf wi ui bi wo uo bo wc bc) =\n LSTMWeights\n (fromRational n * wf)\n (fromRational n * uf)\n (fromRational n * bf)\n (fromRational n * wi)\n (fromRational n * ui)\n (fromRational n * bi)\n (fromRational n * wo)\n (fromRational n * uo)\n (fromRational n * bo)\n (fromRational n * wc)\n (fromRational n * bc)\n (LSTMWeights wf1 uf1 bf1 wi1 ui1 bi1 wo1 uo1 bo1 wc1 bc1) |+ (LSTMWeights wf2 uf2 bf2 wi2 ui2 bi2 wo2 uo2 bo2 wc2 bc2) =\n LSTMWeights (wf1 + wf2) (uf1 + uf2) (bf1 + bf2) (wi1 + wi2) (ui1 + ui2) (bi1 + bi2) (wo1 + wo2) (uo1 + uo2) (bo1 + bo2) (wc1 + wc2) (bc1 + bc2)\n", "meta": {"hexsha": "69618e4bbd8d226767285055d97546939f342aa9", "size": 12782, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Recurrent/Layers/LSTM.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Recurrent/Layers/LSTM.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Recurrent/Layers/LSTM.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 39.450617284, "max_line_length": 158, "alphanum_fraction": 0.574010327, "num_tokens": 4085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3873960183750905}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE MagicHash #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternSynonyms #-}\n{-# LANGUAGE RebindableSyntax #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n-- |\n-- Module : Data.Array.Accelerate.Data.Complex\n-- Copyright : [2015..2019] The Accelerate Team\n-- License : BSD3\n--\n-- Maintainer : Trevor L. McDonell \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\n-- Complex numbers, stored in the usual C-style array-of-struct representation,\n-- for easy interoperability.\n--\nmodule Data.Array.Accelerate.Data.Complex (\n\n -- * Rectangular from\n Complex(..), pattern (::+),\n real,\n imag,\n\n -- * Polar form\n mkPolar,\n cis,\n polar,\n magnitude, magnitude',\n phase,\n\n -- * Conjugate\n conjugate,\n\n) where\n\nimport Data.Array.Accelerate.Array.Sugar\nimport Data.Array.Accelerate.Classes\nimport Data.Array.Accelerate.Data.Functor\nimport Data.Array.Accelerate.Pattern\nimport Data.Array.Accelerate.Prelude\nimport Data.Array.Accelerate.Smart\nimport Data.Array.Accelerate.Type\n\nimport Data.Complex ( Complex(..) )\nimport Prelude (($))\nimport qualified Data.Complex as C\nimport qualified Prelude as P\n\ninfix 6 ::+\npattern (::+) :: Elt a => Exp a -> Exp a -> Exp (Complex a)\npattern r ::+ i <- (deconstructComplex -> (r, i))\n where (::+) = constructComplex\n{-# COMPLETE (::+) #-}\n\n\n-- Use an array-of-structs representation for complex numbers if possible.\n-- This matches the standard C-style layout, but we can use this representation only at\n-- specific types (not for any type 'a') as we can only have vectors of primitive type.\n-- For other types, we use a structure-of-arrays representation. This is handled by the\n-- ComplexRepr. We use the GADT ComplexR and function complexR to reconstruct\n-- information on how the elements are represented.\n--\ninstance Elt a => Elt (Complex a) where\n type EltRepr (Complex a) = ComplexRepr (EltRepr a)\n {-# INLINE eltType #-}\n {-# INLINE [1] toElt #-}\n {-# INLINE [1] fromElt #-}\n eltType = case complexR tp of\n ComplexRvec s -> TupRsingle $ VectorScalarType $ VectorType 2 s\n ComplexRtup -> TupRunit `TupRpair` tp `TupRpair` tp\n where\n tp = eltType @a\n toElt = case complexR $ eltType @a of\n ComplexRvec _ -> \\(Vec2 r i) -> toElt r :+ toElt i\n ComplexRtup -> \\(((), r), i) -> toElt r :+ toElt i\n fromElt (r :+ i) = case complexR $ eltType @a of\n ComplexRvec _ -> Vec2 (fromElt r) (fromElt i)\n ComplexRtup -> (((), fromElt r), fromElt i)\n\ntype family ComplexRepr a where\n ComplexRepr Half = Vec2 Half\n ComplexRepr Float = Vec2 Float\n ComplexRepr Double = Vec2 Double\n ComplexRepr Int = Vec2 Int\n ComplexRepr Int8 = Vec2 Int8\n ComplexRepr Int16 = Vec2 Int16\n ComplexRepr Int32 = Vec2 Int32\n ComplexRepr Int64 = Vec2 Int64\n ComplexRepr Word = Vec2 Word\n ComplexRepr Word8 = Vec2 Word8\n ComplexRepr Word16 = Vec2 Word16\n ComplexRepr Word32 = Vec2 Word32\n ComplexRepr Word64 = Vec2 Word64\n ComplexRepr a = Tup2 a a\n\ndata ComplexR a c where\n ComplexRvec :: VecElt a => SingleType a -> ComplexR a (Vec2 a)\n ComplexRtup :: ComplexR a (Tup2 a a)\n\ncomplexR :: TupleType a -> ComplexR a (ComplexRepr a)\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (FloatingNumType TypeHalf )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (FloatingNumType TypeFloat )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (FloatingNumType TypeDouble)))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt8 )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt16 )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt32 )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt64 )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeWord )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeWord8 )))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeWord16)))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeWord32)))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeWord64)))) = ComplexRvec singleType\ncomplexR (TupRsingle (SingleScalarType (NonNumSingleType TypeChar))) = ComplexRtup\ncomplexR (TupRsingle (SingleScalarType (NonNumSingleType TypeBool))) = ComplexRtup\ncomplexR (TupRsingle (VectorScalarType (_))) = ComplexRtup\ncomplexR TupRunit = ComplexRtup\ncomplexR TupRpair{} = ComplexRtup\n\nconstructComplex :: forall a. Elt a => Exp a -> Exp a -> Exp (Complex a)\nconstructComplex r i = case complexR $ eltType @a of\n ComplexRvec _ ->\n let\n r', i' :: Exp (EltRepr a)\n r' = coerce @a @(EltRepr a) r\n i' = coerce i\n v :: Exp (Vec2 (EltRepr a))\n v = V2 r' i'\n in\n coerce @(Vec2 (EltRepr a)) @(Complex a) $ v\n ComplexRtup -> coerce $ T2 r i\n\ndeconstructComplex :: forall a. Elt a => Exp (Complex a) -> (Exp a, Exp a)\ndeconstructComplex c = case complexR $ eltType @a of\n ComplexRvec _ -> let V2 r i = coerce @(Complex a) @(Vec2 (EltRepr a)) c in (coerce r, coerce i)\n ComplexRtup -> let T2 r i = coerce c in (r, i)\n\ncoerce :: EltRepr a ~ EltRepr b => Exp a -> Exp b\ncoerce (Exp e) = Exp e\n\ninstance (Lift Exp a, Elt (Plain a)) => Lift Exp (Complex a) where\n type Plain (Complex a) = Complex (Plain a)\n lift (r :+ i) = lift r ::+ lift i\n\ninstance Elt a => Unlift Exp (Complex (Exp a)) where\n unlift (r ::+ i) = r :+ i\n\n\ninstance Eq a => Eq (Complex a) where\n r1 ::+ c1 == r2 ::+ c2 = r1 == r2 && c1 == c2\n r1 ::+ c1 /= r2 ::+ c2 = r1 /= r2 || c1 /= c2\n\ninstance RealFloat a => P.Num (Exp (Complex a)) where\n (+) = lift2 ((+) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n (-) = lift2 ((-) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n (*) = lift2 ((*) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n negate = lift1 (negate :: Complex (Exp a) -> Complex (Exp a))\n signum z@(x ::+ y) =\n if z == 0\n then z\n else let r = magnitude z\n in x/r ::+ y/r\n abs z = magnitude z ::+ 0\n fromInteger n = fromInteger n ::+ 0\n\ninstance RealFloat a => P.Fractional (Exp (Complex a)) where\n fromRational x = fromRational x ::+ 0\n z / z' = (x*x''+y*y'') / d ::+ (y*x''-x*y'') / d\n where\n x :+ y = unlift z\n x' :+ y' = unlift z'\n --\n x'' = scaleFloat k x'\n y'' = scaleFloat k y'\n k = - max (exponent x') (exponent y')\n d = x'*x'' + y'*y''\n\ninstance RealFloat a => P.Floating (Exp (Complex a)) where\n pi = pi ::+ 0\n exp (x ::+ y) = let expx = exp x\n in expx * cos y ::+ expx * sin y\n log z = log (magnitude z) ::+ phase z\n sqrt z@(x ::+ y) =\n if z == 0\n then 0\n else u ::+ (y < 0 ? (-v, v))\n where\n T2 u v = x < 0 ? (T2 v' u', T2 u' v')\n v' = abs y / (u'*2)\n u' = sqrt ((magnitude z + abs x) / 2)\n\n x ** y =\n if y == 0 then 1 else\n if x == 0 then if exp_r > 0 then 0 else\n if exp_r < 0 then inf ::+ 0\n else nan ::+ nan\n else if isInfinite r || isInfinite i\n then if exp_r > 0 then inf ::+ 0 else\n if exp_r < 0 then 0\n else nan ::+ nan\n else exp (log x * y)\n where\n r ::+ i = x\n exp_r ::+ _ = y\n --\n inf = 1 / 0\n nan = 0 / 0\n\n sin (x ::+ y) = sin x * cosh y ::+ cos x * sinh y\n cos (x ::+ y) = cos x * cosh y ::+ (- sin x * sinh y)\n tan (x ::+ y) = (sinx*coshy ::+ cosx*sinhy) / (cosx*coshy ::+ (-sinx*sinhy))\n where\n sinx = sin x\n cosx = cos x\n sinhy = sinh y\n coshy = cosh y\n\n sinh (x ::+ y) = cos y * sinh x ::+ sin y * cosh x\n cosh (x ::+ y) = cos y * cosh x ::+ sin y * sinh x\n tanh (x ::+ y) = (cosy*sinhx ::+ siny*coshx) / (cosy*coshx ::+ siny*sinhx)\n where\n siny = sin y\n cosy = cos y\n sinhx = sinh x\n coshx = cosh x\n\n asin z@(x ::+ y) = y' ::+ (-x')\n where\n x' ::+ y' = log (((-y) ::+ x) + sqrt (1 - z*z))\n\n acos z = y'' ::+ (-x'')\n where\n x'' ::+ y'' = log (z + ((-y') ::+ x'))\n x' ::+ y' = sqrt (1 - z*z)\n\n atan z@(x ::+ y) = y' ::+ (-x')\n where\n x' ::+ y' = log (((1-y) ::+ x) / sqrt (1+z*z))\n\n asinh z = log (z + sqrt (1+z*z))\n acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))\n atanh z = 0.5 * log ((1.0+z) / (1.0-z))\n\n\ninstance (FromIntegral a b, Num b, Elt (Complex b)) => FromIntegral a (Complex b) where\n fromIntegral x = fromIntegral x ::+ 0\n\n-- | @since 1.2.0.0\n--\ninstance Functor Complex where\n fmap f (r ::+ i) = f r ::+ f i\n\n\n-- | The non-negative magnitude of a complex number\n--\nmagnitude :: RealFloat a => Exp (Complex a) -> Exp a\nmagnitude (r ::+ i) = scaleFloat k (sqrt (sqr (scaleFloat mk r) + sqr (scaleFloat mk i)))\n where\n k = max (exponent r) (exponent i)\n mk = -k\n sqr z = z * z\n\n-- | As 'magnitude', but ignore floating point rounding and use the traditional\n-- (simpler to evaluate) definition.\n--\n-- @since 1.3.0.0\n--\nmagnitude' :: RealFloat a => Exp (Complex a) -> Exp a\nmagnitude' (r ::+ i) = sqrt (r*r + i*i)\n\n-- | The phase of a complex number, in the range @(-'pi', 'pi']@. If the\n-- magnitude is zero, then so is the phase.\n--\nphase :: RealFloat a => Exp (Complex a) -> Exp a\nphase z@(r ::+ i) =\n if z == 0\n then 0\n else atan2 i r\n\n-- | The function 'polar' takes a complex number and returns a (magnitude,\n-- phase) pair in canonical form: the magnitude is non-negative, and the phase\n-- in the range @(-'pi', 'pi']@; if the magnitude is zero, then so is the phase.\n--\npolar :: RealFloat a => Exp (Complex a) -> Exp (a,a)\npolar z = T2 (magnitude z) (phase z)\n\n-- | Form a complex number from polar components of magnitude and phase.\n--\n#if __GLASGOW_HASKELL__ <= 708\nmkPolar :: forall a. RealFloat a => Exp a -> Exp a -> Exp (Complex a)\n#else\nmkPolar :: forall a. Floating a => Exp a -> Exp a -> Exp (Complex a)\n#endif\nmkPolar = lift2 (C.mkPolar :: Exp a -> Exp a -> Complex (Exp a))\n\n-- | @'cis' t@ is a complex value with magnitude @1@ and phase @t@ (modulo\n-- @2*'pi'@).\n--\n#if __GLASGOW_HASKELL__ <= 708\ncis :: forall a. RealFloat a => Exp a -> Exp (Complex a)\n#else\ncis :: forall a. Floating a => Exp a -> Exp (Complex a)\n#endif\ncis = lift1 (C.cis :: Exp a -> Complex (Exp a))\n\n-- | Return the real part of a complex number\n--\nreal :: Elt a => Exp (Complex a) -> Exp a\nreal (r ::+ _) = r\n\n-- | Return the imaginary part of a complex number\n--\nimag :: Elt a => Exp (Complex a) -> Exp a\nimag (_ ::+ i) = i\n\n-- | Return the complex conjugate of a complex number, defined as\n--\n-- > conjugate(Z) = X - iY\n--\nconjugate :: Num a => Exp (Complex a) -> Exp (Complex a)\nconjugate z = real z ::+ (- imag z)\n\n", "meta": {"hexsha": "702d940c681e5bb970812b585b0521914ea72f0a", "size": 12154, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Array/Accelerate/Data/Complex.hs", "max_stars_repo_name": "noughtmare/accelerate", "max_stars_repo_head_hexsha": "632b3fe460bb59fefe6eb20df713d91798b6b494", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Array/Accelerate/Data/Complex.hs", "max_issues_repo_name": "noughtmare/accelerate", "max_issues_repo_head_hexsha": "632b3fe460bb59fefe6eb20df713d91798b6b494", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-04-13T18:40:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T09:51:11.000Z", "max_forks_repo_path": "src/Data/Array/Accelerate/Data/Complex.hs", "max_forks_repo_name": "noughtmare/accelerate", "max_forks_repo_head_hexsha": "632b3fe460bb59fefe6eb20df713d91798b6b494", "max_forks_repo_licenses": ["BSD-3-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.2805970149, "max_line_length": 110, "alphanum_fraction": 0.5879545829, "num_tokens": 3783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3858796018180167}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n\nmodule HVX.Internal.Primitives\n ( Var\n , Fun(..)\n , Expr(..)\n , getFun\n , getJacobian\n , getProperties\n ) where\n\nimport Numeric.LinearAlgebra\n\nimport HVX.Internal.Matrix\nimport HVX.Internal.DCP\n\ntype Var = String\n\ndata Expr vex mon where\n EConst :: Mat -> Expr 'Affine 'Const\n EVar :: Var -> Expr 'Affine 'Nondec\n EFun ::\n#ifndef DISABLE_EXPR_CXT\n ValidVex vex =>\n#endif\n Fun v1 m1 -> Expr v2 m2 -> Expr vex mon\n EAdd ::\n#ifndef DISABLE_EXPR_CXT\n ValidVex vex =>\n#endif\n Expr v1 m1 -> Expr v2 m2 -> Expr vex mon\n\ninstance Show (Expr vex mon) where\n show (EConst mat) = show mat\n show (EVar var) = var\n show (EFun f a) = show f ++ \"(\" ++ show a ++ \")\"\n show (EAdd a b) = show a ++ \" + \" ++ show b\n\ngetProperties :: (GetVex vex, GetMon mon) => Expr vex mon -> String\ngetProperties expr = getVex expr ++ \" \" ++ getMon expr\n\ndata Fun (vex :: Vex) (mon :: Mon) where\n Mul :: Mat -> Fun 'Affine 'Nonmon\n Abs :: Fun 'Convex 'Nonmon\n Neg :: Fun 'Affine 'Noninc\n Log :: Fun 'Concave 'Nondec\n Exp :: Fun 'Convex 'Nondec\n LogSumExp :: Fun 'Convex 'Nondec\n Max :: Fun 'Convex 'Nondec\n Min :: Fun 'Concave 'Nondec\n Norm :: Double -> Fun 'Convex 'Nonmon\n Berhu :: Double -> Fun 'Convex 'Nonmon\n Huber :: Double -> Fun 'Convex 'Nonmon\n Quadform :: Mat -> Fun 'Convex 'Nonmon\n PowBaseP0 :: Fun 'Affine 'Const\n PowBaseP01 :: Double -> Fun 'Concave 'Nondec\n PowBaseP1 :: Fun 'Affine 'Nondec\n PowBaseP1InfEven :: Integer -> Fun 'Convex 'Nonmon\n PowBaseP1InfNotInt :: Double -> Fun 'Convex 'Nondec\n\ninstance Show (Fun vex mon) where\n show (Mul _) = \"mul\"\n show Abs = \"abs\"\n show Neg = \"-\"\n show Log = \"log\"\n show Exp = \"exp\"\n show LogSumExp = \"log_sum_exp\"\n show Max = \"max\"\n show Min = \"min\"\n show (Norm p) = \"norm\" ++ show p\n show (Berhu m) = \"berhu\" ++ show m\n show (Huber m) = \"huber\" ++ show m\n show (Quadform m) = \"quadform\" ++ show m\n show PowBaseP0 = \"pow0\"\n show (PowBaseP01 p) = \"pow\" ++ show p\n show PowBaseP1 = \"pow1\"\n show (PowBaseP1InfEven p) = \"pow\" ++ show p\n show (PowBaseP1InfNotInt p) = \"pow\" ++ show p\n\ngetFun :: Fun vex mon -> Mat -> Mat\ngetFun (Mul a) x = a <> x\ngetFun Abs x = abs x\ngetFun Neg x = negate x\ngetFun Exp x = exp x\ngetFun Log x\n | anyMat (<= 0) x = error \"Cannot take log of number <= 0.\"\n | otherwise = log x\ngetFun LogSumExp x = reduceMat (log . sum) $ exp x\ngetFun Max x = reduceMat maximum x\ngetFun Min x = reduceMat minimum x\ngetFun (Norm p) x = scalarMat $ lpnorm p x\ngetFun (Berhu m) x =\n cmap (\\y -> if abs y <= m then abs y else (abs y ** 2 + m ** 2) / (2 * m)) x\ngetFun (Huber m) x = \n cmap (\\y -> if abs y <= m then abs y ** 2 else 2 * m * abs y - m ** 2) x\ngetFun (Quadform m) x = tr x <> m <> x\ngetFun PowBaseP0 x = konst 1.0 ((rows x), (cols x))\ngetFun (PowBaseP01 p) x\n | allMat (0 <=) x = matrixPow p x\n | otherwise = error \"Cannot raise negative number to power p with 0 < p < 1.\"\ngetFun PowBaseP1 x = x\ngetFun (PowBaseP1InfEven p) x = matrixPow (fromIntegral p) x\ngetFun (PowBaseP1InfNotInt p) x\n | allMat (0 <=) x = matrixPow p x\n | otherwise = error \"Cannot raise negative number to a nonintegral power of p for p > 1.\"\n\ngetJacobian :: Fun vex mon -> Mat -> Mat\ngetJacobian (Mul a) _ = a\ngetJacobian Abs x = diagMat $ signum x\ngetJacobian Neg x = (-1) * ident (rows x)\ngetJacobian Log x = diagMat $ 1 / x\ngetJacobian Exp x = diagMat $ exp x\ngetJacobian LogSumExp x = tr $ scale (1 / sumElements (exp x)) $ exp x\ngetJacobian Max x = tr $ ei (rows x) i\n where (i, _) = maxIndex x\ngetJacobian Min x = tr $ ei (rows x) i\n where (i, _) = minIndex x\ngetJacobian (Norm p) x = tr $ if x == zeroVec n\n then\n zeroVec n\n else\n scale (1 / denominator) numerator\n where denominator = lpnorm p x ** (p - 1)\n numerator = x * abs x ** (pMat - 2)\n pMat = (1><1) [p]\n n = rows x\ngetJacobian (Berhu m) x = diagMat $\n cmap (\\y -> if abs y <= m then signum y else y / m) x\ngetJacobian (Huber m) x = diagMat $\n cmap (\\y -> if abs y <= m then 2 * y else 2 * m * signum y) x\ngetJacobian (Quadform m) x = scale 2 $ tr x <> m\ngetJacobian PowBaseP0 x = konst 0.0 (n, n)\n where n = rows x\ngetJacobian (PowBaseP01 p) x = scale p $ diagMat $ matrixPow (p - 1) x\ngetJacobian PowBaseP1 x = ident n\n where n = rows x\ngetJacobian (PowBaseP1InfEven intP) x = scale p $ diagMat $ matrixPow (p - 1) x\n where p = fromIntegral intP\ngetJacobian (PowBaseP1InfNotInt p) x = scale p $ diagMat $ matrixPow (p - 1) x\n", "meta": {"hexsha": "b1f9349f70ba82d5ab6a8e73626c832eea8595f7", "size": 4728, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HVX/Internal/Primitives.hs", "max_stars_repo_name": "chrisnc/hvx", "max_stars_repo_head_hexsha": "4256e83d265c7b6bf9336533c15eae9fecce9a6d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2015-02-06T21:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T06:40:50.000Z", "max_issues_repo_path": "src/HVX/Internal/Primitives.hs", "max_issues_repo_name": "chrisnc/hvx", "max_issues_repo_head_hexsha": "4256e83d265c7b6bf9336533c15eae9fecce9a6d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-08-01T05:22:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T17:07:19.000Z", "max_forks_repo_path": "src/HVX/Internal/Primitives.hs", "max_forks_repo_name": "chrisnc/hvx", "max_forks_repo_head_hexsha": "4256e83d265c7b6bf9336533c15eae9fecce9a6d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-07-31T09:08:48.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T15:50:42.000Z", "avg_line_length": 33.0629370629, "max_line_length": 91, "alphanum_fraction": 0.6010998308, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3854992742495961}} {"text": "{-# LANGUAGE Strict #-}\nmodule FourierPinwheel.Multiplication where\n\nimport Control.Concurrent.Async\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport DFT.Plan\nimport FourierPinwheel.Array\nimport Utils.Parallel\nimport Filter.Utils\nimport Utils.Distribution\n\n{-# INLINE multiplyBias #-}\nmultiplyBias ::\n DFTPlan\n -> VS.Vector (Complex Double)\n -> FPArray (VS.Vector (Complex Double))\n -> IO (FPArray (VS.Vector (Complex Double)))\nmultiplyBias plan biasF (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs2) = do\n let planIDForward =\n DFTPlanID DFT1DG [numThetaFreq, numXFreq, numYFreq] [0, 1, 2]\n planIDBackward =\n DFTPlanID IDFT1DG [numThetaFreq, numXFreq, numYFreq] [0, 1, 2]\n vecs2F <- dftExecuteBatchP plan planIDForward vecs2\n let vecs3F = parMap rdeepseq (VS.zipWith (*) biasF) vecs2F\n FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq <$>\n dftExecuteBatchP plan planIDBackward vecs3F\n\n\n{-# INLINE multiplyBias4D #-}\nmultiplyBias4D ::\n DFTPlan\n -> VS.Vector (Complex Double)\n -> FPArray (VS.Vector (Complex Double))\n -> IO (FPArray (VS.Vector (Complex Double)))\nmultiplyBias4D plan biasF (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs2) = do\n let planIDForward =\n DFTPlanID\n DFT1DG\n [numRFreq, numThetaFreq, numXFreq, numYFreq]\n [0, 1, 2, 3]\n planIDBackward =\n DFTPlanID\n IDFT1DG\n [numRFreq, numThetaFreq, numXFreq, numYFreq]\n [0, 1, 2, 3]\n vecs2F <- dftExecute plan planIDForward . VS.concat $ vecs2\n let vecs3F = VS.zipWith (*) biasF vecs2F\n arr <-\n fromUnboxed (Z :. numRFreq :. numThetaFreq :. numXFreq :. numYFreq) .\n VS.convert <$>\n dftExecute plan planIDBackward vecs3F\n return .\n FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq .\n parMap\n rdeepseq\n (\\rFreq ->\n VS.convert . toUnboxed . computeS . R.slice arr $ (Z :. rFreq :. All :. All :. All)) $\n [0 .. numRFreq - 1]\n\n\n{-# INLINE multiplyBiasDiscrete #-}\nmultiplyBiasDiscrete ::\n DFTPlan\n -> VS.Vector (Complex Double)\n -> FPArray (VS.Vector (Complex Double))\n -> IO (FPArray (VS.Vector (Complex Double)))\nmultiplyBiasDiscrete plan bias (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs2F) = do\n let planIDForward = DFTPlanID DFT1DG [numThetaFreq, numXFreq, numYFreq] [1, 2]\n planIDBackward =\n DFTPlanID IDFT1DG [numThetaFreq, numXFreq, numYFreq] [1, 2]\n vecs2 <-\n parMap rdeepseq (VS.zipWith (*) bias) <$>\n dftExecuteBatchP plan planIDBackward vecs2F\n FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq <$>\n dftExecuteBatchP plan planIDForward vecs2\n \n\n{-# INLINE multiplyRFunction #-}\nmultiplyRFunction ::\n DFTPlan\n -> Double\n -> FPArray (VS.Vector (Complex Double))\n -> IO (FPArray (VS.Vector (Complex Double)))\nmultiplyRFunction plan periodEnv (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs) = do\n let freqConst = 2 * pi / log periodEnv\n filterVec =\n computeUnboxedS . makeFilter1D . fromFunction (Z :. numRFreq) $ \\(Z :. i') ->\n let i = fromIntegral (i' - div numRFreq 2)\n in 1 / (1 :+ freqConst * fromIntegral i) -- gaussian1D i 10 :+ 0 --1 / (1 :+ (freqConst * fromIntegral i)^2)\n vec = VS.convert . VS.concat $ vecs\n filterF <-\n dftExecute plan (DFTPlanID DFT1DG [numRFreq] [0]) . VS.convert . toUnboxed $\n filterVec\n vecF <-\n dftExecute\n plan\n (DFTPlanID DFT1DG [numRFreq, numThetaFreq, numXFreq, numYFreq] [0])\n vec\n let arrF =\n fromUnboxed (Z :. numRFreq :. numThetaFreq :. numXFreq :. numYFreq) .\n VS.convert $\n vecF\n convolvedArrFR =\n R.traverse2\n arrF\n (fromUnboxed (Z :. numRFreq) . VS.convert $ filterF)\n const $ \\fArr fVec idx@(Z :. r :. _ :. _ :. _) ->\n fArr idx * fVec (Z :. r)\n convolvedArrF <- computeUnboxedP convolvedArrFR\n convolvedVec <-\n dftExecute\n plan\n (DFTPlanID IDFT1DG [numRFreq, numThetaFreq, numXFreq, numYFreq] [0]) .\n VS.convert . toUnboxed $\n convolvedArrF\n let convolvedArr =\n fromUnboxed (Z :. numRFreq :. numThetaFreq :. numXFreq :. numYFreq) .\n VS.convert $\n convolvedVec\n convolvedVecs =\n parMap\n rdeepseq\n (\\i ->\n VS.convert . toUnboxed . computeS . R.slice convolvedArr $\n (Z :. i :. All :. All :. All))\n [0 .. numRFreq - 1]\n return\n (FPArray\n numXFreq\n numYFreq\n numRFreq\n numThetaFreq\n numRhoFreq\n numPhiFreq\n convolvedVecs) \n\n-- {-# INLINE multiplyRFunction #-}\n-- multiplyRFunction :: FPArray (VS.Vector (Complex Double)) -> FPArray (VS.Vector (Complex Double))\n-- multiplyRFunction (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs') =\n-- let vecs = L.reverse vecs'\n-- zeroVec = VS.replicate (numThetaFreq * numXFreq * numYFreq) 0\n-- convolvedSGNPositive = L.init . L.scanl' (VS.zipWith (+)) zeroVec $ vecs\n-- convolvedSGNNegative = L.tail . L.scanr (VS.zipWith (+)) zeroVec $ vecs\n-- convolvedSGN =\n-- parZipWith\n-- rdeepseq\n-- (VS.zipWith (\\x y -> (x - y) * (0 :+ (-pi))))\n-- convolvedSGNPositive\n-- convolvedSGNNegative\n-- in FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq .\n-- L.reverse $\n-- convolvedSGN\n", "meta": {"hexsha": "36499483bfd41507241e7fbe9542c506a6c6752e", "size": 5680, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FourierPinwheel/Multiplication.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FourierPinwheel/Multiplication.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FourierPinwheel/Multiplication.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 36.4102564103, "max_line_length": 119, "alphanum_fraction": 0.6399647887, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.38540094225833377}} {"text": "{-# LANGUAGE KindSignatures, DataKinds #-}\n{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE TypeFamilies #-}\n\n\nmodule DSProg (\n module DSProg,\n Result\n) where\n\nimport Prelude hiding ((<>))\n\nimport Control.Monad (join, (<=<), forM_, void, replicateM)\nimport Control.Monad.State (StateT, MonadState (get, put), evalStateT)\nimport qualified Control.Monad.State as State\nimport Control.Monad.Bayes.Class (MonadSample, MonadInfer)\nimport Control.Monad.Bayes.Sampler\nimport Control.Monad.Bayes.Weighted\nimport Control.Monad.Trans (liftIO)\nimport Control.Monad.Fix\n\nimport Data.Aeson (ToJSON (toJSON))\nimport Data.Maybe (isNothing, fromJust)\nimport qualified Data.Map\nimport Data.Proxy (Proxy (Proxy))\n\nimport GHC.TypeLits\n\nimport Numeric.LinearAlgebra.Static hiding (Gaussian, M)\n\nimport Unsafe.Coerce (unsafeCoerce)\n\nimport qualified Util.AssocList as M\nimport Util.AssocList (Map)\nimport qualified Util.AssocListSet as S\nimport Util.AssocListSet (Set)\nimport qualified Util.MStream as MS\nimport Util.MStream (MStream)\nimport Distributions\nimport MVDistributions\nimport DelayedSampling\nimport Inference (particles, Weight, zunheap)\nimport Util.Numeric (average)\nimport Util.Ref\n\nimport qualified Util.ZStream as ZS\n\nimport Numeric.Log (Log (Exp))\n\ninstance ToJSON a => ToJSON (Result a) where\n toJSON (RConst x) = toJSON x\n toJSON (RMarginal d) = toJSON d\n\ninstance MonadState s m => MonadState s (Weighted m) where\n get = State.lift get\n put = State.lift . put\n state = State.lift . State.state\n\nmeanMDistr :: Double ~ MType a => MDistr a -> Double\nmeanMDistr (MGaussian mu var) = mu\nmeanMDistr (MBeta a b) = a / (a + b)\n\nmeanResult :: Result Double -> Double\nmeanResult (RConst x) = x\nmeanResult (RMarginal m) = meanMDistr m\n\naddResult :: Num a => Result a -> Result a -> Maybe (Result a)\naddResult (RConst x) (RConst y) = Just $ RConst (x + y)\naddResult (RConst x) (RMarginal (MGaussian mu var)) = Just $ RMarginal (MGaussian (mu + x) var)\naddResult (RMarginal (MGaussian mu var)) (RConst x) = addResult (RConst x) (RMarginal (MGaussian mu var))\naddResult (RMarginal (MGaussian mu var)) (RMarginal (MGaussian mu' var')) = Nothing\n -- Just $ RMarginal (MGaussian (mu + mu') (var + var')) -- only valid when variables are independent\naddResult _ _ = Nothing\n\nnegateResult :: Num a => Result a -> Maybe (Result a)\nnegateResult (RConst x) = Just $ RConst (- x)\nnegateResult (RMarginal (MGaussian mu var)) = Just $ RMarginal (MGaussian (- mu) var)\nnegateResult _ = Nothing\n\nmultResult :: Num a => Result a -> Result a -> Maybe (Result a)\nmultResult (RConst x) (RConst y) = Just $ RConst (x * y)\nmultResult (RConst x) (RMarginal (MGaussian mu var)) = Just $ RMarginal (MGaussian (x * mu) (x^2 * var))\nmultResult (RMarginal (MGaussian mu var)) (RConst x) = multResult (RConst x) (RMarginal (MGaussian mu var))\nmultResult _ _ = Nothing\n\ndata Expr' var a where\n Const :: a -> Expr' var a\n Var :: var a -> Expr' var a\n Plus :: Num a => Expr' var a -> Expr' var a -> Expr' var a\n Times :: Num a => Expr' var a -> Expr' var a -> Expr' var a\n MVMul :: (KnownNat m, KnownNat n) => Expr' var (L m n) -> Expr' var (R n) -> Expr' var (R m)\n\ninstance Show (RefNodeToT a) where\n show (RefNodeToT r) = show r\n\nderiving instance (Show a) => Show (Expr' RefNodeToT a)\n\nclass DeepForce e where\n type Forced e :: *\n deepForce :: MonadState Heap m => MonadSample m => e -> m (Forced e)\n deepConst :: Forced e -> e\n\ndeepForce' :: MonadState Heap m => MonadSample m => DeepForce e => e -> m e\ndeepForce' = fmap deepConst . deepForce\n\ninstance DeepForce Double where\n type Forced Double = Double\n deepForce = pure\n deepConst = id\n\ninstance DeepForce Int where\n type Forced Int = Int\n deepForce = pure\n deepConst = id\n\ninstance DeepForce (R n) where\n type Forced (R n) = R n\n deepForce = pure\n deepConst = id\n\ninstance DeepForce (L m n) where\n type Forced (L m n) = L m n\n deepForce = pure\n deepConst = id\n\ninstance DeepForce (Expr a) where\n type Forced (Expr a) = a\n deepForce = force\n deepConst = Const\n\ninstance DeepForce e => DeepForce [e] where\n type Forced [e] = [Forced e]\n deepForce = mapM deepForce\n deepConst = map deepConst\n\ninstance DeepForce e => DeepForce (Data.Map.Map k e) where\n type Forced (Data.Map.Map k e) = Data.Map.Map k (Forced e)\n deepForce = mapM deepForce\n deepConst = fmap deepConst\n\ninstance (DeepForce a, DeepForce b) => DeepForce (a, b) where\n type Forced (a, b) = (Forced a, Forced b)\n deepForce (x, y) = (,) <$> deepForce x <*> deepForce y\n deepConst (x, y) = (deepConst x, deepConst y)\n\ninstance (DeepForce a, DeepForce b, DeepForce c) => DeepForce (a, b, c) where\n type Forced (a, b, c) = (Forced a, Forced b, Forced c)\n deepForce (x, y, z) = (,,) <$> deepForce x <*> deepForce y <*> deepForce z\n deepConst (x, y, z) = (deepConst x, deepConst y, deepConst z)\n\ninstance (DeepForce a, DeepForce b, DeepForce c, DeepForce d) => DeepForce (a, b, c, d) where\n type Forced (a, b, c, d) = (Forced a, Forced b, Forced c, Forced d)\n deepForce (x, y, z, w) = (,,,) <$> deepForce x <*> deepForce y <*> deepForce z <*> deepForce w\n deepConst (x, y, z, w) = (deepConst x, deepConst y, deepConst z, deepConst w)\n\ntype M = Weighted (StateT Heap SamplerIO)\n\nevalM :: M a -> SamplerIO (Double, a)\nevalM x = (\\(x, Exp w) -> (w, x)) <$> evalStateT (runWeighted x) emptyHeap\n\nforgettableVar :: MonadState Heap m => Ref (Node a b) -> m (Expr (MType b))\nforgettableVar nref = do\n -- addFinalizer v (forget nref)\n pure v\n where\n v = Var (RefNodeToT nref)\n\ntype Expr = Expr' RefNodeToT\n\ndata RefNodeToT b where\n RefNodeToT :: Ref (Node a b) -> RefNodeToT (MType b)\n\ninstance Eq (RefNodeToT a) where\n RefNodeToT (Ref x) == RefNodeToT (Ref y) = x == unsafeCoerce y\n\ninstance Num a => Num (Expr' var a) where\n fromInteger = Const . fromInteger\n x + y = Plus x y\n x * y = Times x y\n\n\n\n\nfmapExpr' :: forall f var var' a. Applicative f => (forall x. var x -> f (var' x)) -> Expr' var a -> f (Expr' var' a)\nfmapExpr' varMap = f where\n f :: forall a. Expr' var a -> f (Expr' var' a)\n f (Const x) = pure $ Const x\n f (Var i) = Var <$> varMap i\n f (Plus x y) = Plus <$> f x <*> f y\n f (Times x y) = Times <$> f x <*> f y\n f (MVMul a x) = MVMul <$> f a <*> f x\n\nread :: MonadState Heap m => Expr' RefNodeToT a -> m (Expr' NodeTo a)\nread = fmapExpr' (\\(RefNodeToT nref) -> NodeTo <$> readRef nref)\n\ndata AffineMVMult (m :: Nat) where\n AffineMVMult :: KnownNat n => RefNodeToT (R n) -> L m n -> AffineMVMult m\n\ngetAffineMV :: KnownNat m => Expr (R m) -> Maybe ([AffineMVMult m], R m)\ngetAffineMV (Const x) = Just ([], x)\ngetAffineMV (Var i) = Just ([AffineMVMult i eye], 0)\ngetAffineMV (Plus x y) = do\n (m1, b1) <- getAffineMV x\n (m2, b2) <- getAffineMV y\n Just (m1 ++ m2, b1 + b2)\ngetAffineMV (Times x y) = Nothing\ngetAffineMV (MVMul (Const f) x) = do\n (m, b) <- getAffineMV x\n Just ([ AffineMVMult z (f <> g) | AffineMVMult z g <- m ], f #> b)\ngetAffineMV (MVMul _ _) = Nothing\n\ngetAffineMV1 :: KnownNat m => Expr (R m) -> Maybe (R m, Maybe (AffineMVMult m))\ngetAffineMV1 e = getAffineMV e >>= toAffine\n where\n toAffine :: KnownNat m => ([AffineMVMult m], R m) -> Maybe (R m, Maybe (AffineMVMult m))\n toAffine (m, b) = do\n mx <- case m of\n [] -> Just Nothing\n [x] -> Just (Just x)\n _ -> Nothing\n pure (b, mx)\n\ngetAffine :: Num a => Expr a -> Maybe (Map (Maybe (RefNodeToT a)) a)\ngetAffine (Const x) = Just (M.singleton Nothing x)\ngetAffine (Var i) = Just (M.singleton (Just i) 1)\ngetAffine (Plus x y) = M.unionWith (+) <$> getAffine x <*> getAffine y\ngetAffine (Times x y) = do\n mx <- getAffine x\n my <- getAffine y\n terms <- sequence [ mult x1 x2 | x1 <- M.toList mx, x2 <- M.toList my ]\n Just (M.fromList terms)\n where\n mult (Nothing, x) (Nothing, y) = Just (Nothing, x * y)\n mult (Nothing, x) (Just i, y) = Just (Just i, x * y)\n mult (Just i, x) (Nothing, y) = Just (Just i, x * y)\n mult (Just i, x) (Just j, y) = Nothing\ngetAffine (MVMul f x) = Nothing\n\ngetAffine1 :: Num a => Expr a -> Maybe (a, Maybe (RefNodeToT a, a))\ngetAffine1 e = getAffine e >>= toAffine\n\ntoAffine :: Num v => Map (Maybe k) v -> Maybe (v, Maybe (k, v))\ntoAffine mp = let (mconst, mvar) = M.partition Data.Maybe.isNothing mp in do\n let b = case mconst of\n M.Map [] -> 0\n M.Map [(Nothing, v)] -> v\n _ -> error \"impossible\"\n mx <- case mvar of\n M.Map [] -> Just Nothing\n M.Map [(Just k, v)] -> Just (Just (k, v))\n _ -> Nothing\n pure (b, mx)\n\nrealizedToConst' :: forall var f a. Applicative f => (forall x. var x -> f (Maybe x)) -> Expr' var a -> f (Expr' var a)\nrealizedToConst' varMap = f where\n f :: forall a. Expr' var a -> f (Expr' var a)\n f (Const x) = pure $ Const x\n f (Var i) = flip fmap (varMap i) $ \\mk -> case mk of\n Nothing -> Var i\n Just k -> Const k\n f (Plus x y) = Plus <$> f x <*> f y\n f (Times x y) = Times <$> f x <*> f y\n f (MVMul a x) = MVMul <$> f a <*> f x\n\nrealizedToConst :: MonadState Heap m => Expr a -> m (Expr a)\nrealizedToConst = realizedToConst' f where\n f :: MonadState Heap m => RefNodeToT b -> m (Maybe b)\n f (RefNodeToT nref) = do\n n <- readRef nref\n pure $ case n of\n RealizedNode x -> Just x\n _ -> Nothing\n\nallVars :: Expr a -> Set (SomeRefNode)\nallVars (Const x) = S.empty\nallVars (Var (RefNodeToT i)) = S.singleton (SomeRefNode i)\nallVars (Plus x y) = allVars x `S.union` allVars y\nallVars (Times x y) = allVars x `S.union` allVars y\nallVars (MVMul f x) = allVars f `S.union` allVars x\n\n\ninitializedMarginal :: MonadState Heap m => Ref (Node a b) -> m (MDistr b)\ninitializedMarginal nref = do\n n <- readRef nref\n case distr n of\n UDistr d -> pure d\n CDistr par cd -> do\n Just pard <- marginalRef par\n pure (makeMarginal pard cd)\n\nmarginalRef :: MonadState Heap m => Ref (Node a b) -> m (Maybe (MDistr b))\nmarginalRef nref = do\n n <- readRef nref\n case n of\n RealizedNode x -> error \"shouldn't occur\"\n _ -> case state n of\n Marginalized d -> do\n isStale <- stale nref\n pure $ if isStale then Nothing else Just d\n Initialized -> Just <$> initializedMarginal nref\n\n-- This is currently unsound\n-- Consider\n-- x <- normal(0, 1)\n-- pure (x + (- x))\nmarginal :: MonadState Heap m => Expr a -> m (Maybe (Result a))\nmarginal (Const x) = pure (Just (RConst x))\nmarginal (Var (RefNodeToT nref)) = do\n n <- readRef nref\n case n of\n RealizedNode x -> pure $ Just (RConst x)\n _ -> case state n of\n Marginalized d -> do\n isStale <- stale nref\n pure $ if isStale then Nothing else Just (RMarginal d)\n Initialized -> Just . RMarginal <$> initializedMarginal nref\nmarginal (Plus x y) = pure Nothing -- could do independence ananlysis, etc.\nmarginal (Times x y) = pure Nothing -- could do independence ananlysis, etc.\nmarginal (MVMul f x) = pure Nothing\n\nmarginal' :: MonadState Heap m => Expr a -> m (Result a)\nmarginal' = fmap fromJust . marginal\n\ndata NodeTo a where\n NodeTo :: Node z a -> NodeTo (MType a)\n\nforce :: MonadSample m => MonadState Heap m => Expr a -> m a\nforce (Const x) = pure x\nforce (Var (RefNodeToT nref)) = getValue nref\nforce (Plus x y) = (+) <$> force x <*> force y\nforce (Times x y) = (*) <$> force x <*> force y\nforce (MVMul a x) = (#>) <$> force a <*> force x\n\ntypeOfRefNodeToT :: MonadState Heap m => Ref (Node a b) -> m (SMarginalT b)\ntypeOfRefNodeToT nref = typeOfDSDistr . distr <$> readRef nref\n\nforgetE :: MonadState Heap m => Expr a -> m ()\nforgetE e = forM_ (allVars e) forgetSomeRefNode\n\n\nforgetSomeRefNode :: MonadState Heap m => SomeRefNode -> m ()\nforgetSomeRefNode (SomeRefNode nref) = forget nref\n\njustRun :: Show p => MonadState Heap m => State.MonadIO m => MStream m (Expr p) (Expr a) -> m (Maybe (Result a))\njustRun s = do\n res <- MS.runStream (\\x -> marginal x >>= liftIO . print) s\n res' <- marginal res\n pure res'\n\nrunParticle :: Int -> MStream M (Maybe (Result Double)) (Maybe (Result Double)) -> StateT Heap SamplerIO Double\nrunParticle numParticles =\n fmap avg . MS.runStream (liftIO . print . avg)\n . Inference.particles numParticles\n where\n avg = average . map (meanResult . fromJust)\n fromJust (Just x) = x\n fromJust Nothing = RConst $ Prelude.read \"NaN\"\n\nzdeepForce :: DeepForce b => MonadSample m => ZS.ZStream (StateT Heap m) a b -> ZS.ZStream m a (Forced b)\nzdeepForce model = zunheap $ ZS.zconstM deepForce ZS.<<< model\n\nzdeepForce' :: DeepForce b => MonadSample m => ZS.ZStream (StateT Heap m) a b -> ZS.ZStream m a b\nzdeepForce' model = fmap deepConst (zdeepForce model)", "meta": {"hexsha": "008e934556a15f6c7519686a8bfba2466fe87c14", "size": 12590, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/DSProg.hs", "max_stars_repo_name": "psg-mit/probzelus-haskell", "max_stars_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-26T13:13:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T19:11:41.000Z", "max_issues_repo_path": "haskell/src/DSProg.hs", "max_issues_repo_name": "psg-mit/probzelus-haskell", "max_issues_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/src/DSProg.hs", "max_forks_repo_name": "psg-mit/probzelus-haskell", "max_forks_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4931506849, "max_line_length": 119, "alphanum_fraction": 0.6548848292, "num_tokens": 4111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3852171914046915}} {"text": "{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule Math.HiddenMarkovModel.Distribution (\n State(..),\n Emission, Probability, Trained,\n Info(..), Generate(..), EmissionProb(..), Estimate(..),\n\n Discrete(..), DiscreteTrained(..),\n Gaussian(..), GaussianTrained(..), gaussian,\n\n CSV(..), HMMCSV.CSVParser, CSVSymbol(..),\n ) where\n\nimport qualified Math.HiddenMarkovModel.CSV as HMMCSV\nimport Math.HiddenMarkovModel.Utility (randomItemProp, normalizeProb)\n\nimport qualified Numeric.LinearAlgebra.HMatrix as HMatrix\nimport qualified Numeric.LinearAlgebra.Algorithms as Algo\nimport qualified Numeric.Container as NC\nimport qualified Data.Packed.Matrix as Matrix\nimport qualified Data.Packed.Vector as Vector\nimport Numeric.Container ((<>))\nimport Data.Packed.Matrix (Matrix)\nimport Data.Packed.Vector (Vector)\nimport Foreign.Storable (Storable)\n\nimport qualified System.Random as Rnd\n\nimport qualified Text.CSV.Lazy.String as CSV\nimport Text.Read.HT (maybeRead)\nimport Text.Printf (printf)\n\nimport qualified Control.Monad.Exception.Synchronous as ME\nimport qualified Control.Monad.Trans.Class as MT\nimport qualified Control.Monad.Trans.State as MS\nimport Control.DeepSeq (NFData, rnf)\nimport Control.Monad (liftM2)\n\nimport qualified Data.NonEmpty as NonEmpty\nimport qualified Data.Foldable as Fold\nimport qualified Data.Map as Map\nimport qualified Data.Set as Set\nimport qualified Data.Array as Array\nimport qualified Data.List as List\nimport Data.Foldable (foldMap)\nimport Data.Tuple.HT (mapFst)\nimport Data.Array (Array, Ix, listArray, (!))\nimport Data.Map (Map)\nimport Data.Maybe (listToMaybe)\n\n\nnewtype State = State Int\n deriving (Eq, Ord, Show, Read, Ix)\n\ninstance Enum State where\n toEnum = State\n fromEnum (State n) = n\n\ninstance NFData State where\n rnf (State n) = rnf n\n\n\ntype family Probability distr\ntype family Emission distr\ntype family Trained distr\n\n\nclass\n (NC.Container Vector (Probability distr), NC.Product (Probability distr)) =>\n Info distr where\n numberOfStates :: distr -> Int\n\nclass\n (NC.Container Vector (Probability distr), NC.Product (Probability distr)) =>\n Generate distr where\n generate ::\n (Rnd.RandomGen g, Probability distr ~ prob, Emission distr ~ emission) =>\n distr -> State -> MS.State g emission\n\nclass\n (NC.Container Vector (Probability distr), NC.Product (Probability distr)) =>\n EmissionProb distr where\n {-\n This function could be implemented generically in terms of emissionStateProb\n but that would require an Info constraint.\n -}\n emissionProb :: distr -> Emission distr -> Vector (Probability distr)\n emissionStateProb :: distr -> Emission distr -> State -> Probability distr\n emissionStateProb distr e (State s) = NC.atIndex (emissionProb distr e) s\n\nclass\n (EmissionProb (Distribution tdistr),\n Trained (Distribution tdistr) ~ tdistr) =>\n Estimate tdistr where\n type Distribution tdistr\n accumulateEmissions ::\n (Distribution tdistr ~ distr, Probability distr ~ prob) =>\n [[(Emission distr, prob)]] -> tdistr\n -- could as well be in Semigroup class\n combine :: tdistr -> tdistr -> tdistr\n normalize :: (Distribution tdistr ~ distr) => tdistr -> distr\n\n\n\nnewtype Discrete prob symbol = Discrete (Map symbol (Vector prob))\n deriving (Show)\n\nnewtype DiscreteTrained prob symbol = DiscreteTrained (Map symbol (Vector prob))\n deriving (Show)\n\ntype instance Probability (Discrete prob symbol) = prob\ntype instance Emission (Discrete prob symbol) = symbol\n\ntype instance Trained (Discrete prob symbol) = DiscreteTrained prob symbol\n\n\ninstance (NFData prob, NFData symbol) => NFData (Discrete prob symbol) where\n rnf (Discrete m) = rnf m\n\ninstance\n (NFData prob, NFData symbol) =>\n NFData (DiscreteTrained prob symbol) where\n rnf (DiscreteTrained m) = rnf m\n\ninstance\n (NC.Container Vector prob, NC.Product prob, Ord symbol) =>\n Info (Discrete prob symbol) where\n numberOfStates (Discrete m) = Vector.dim $ snd $ Map.findMin m\n\ninstance\n (NC.Container Vector prob, NC.Product prob, Ord symbol,\n Ord prob, Rnd.Random prob) =>\n Generate (Discrete prob symbol) where\n generate (Discrete m) (State state) =\n randomItemProp $ Map.toAscList $ fmap (flip NC.atIndex state) m\n\ninstance\n (NC.Container Vector prob, NC.Product prob, Ord symbol) =>\n EmissionProb (Discrete prob symbol) where\n emissionProb (Discrete m) =\n mapLookup \"emitDiscrete: unknown emission symbol\" m\n\ninstance\n (NC.Container Vector prob, NC.Product prob, Ord symbol) =>\n Estimate (DiscreteTrained prob symbol) where\n type Distribution (DiscreteTrained prob symbol) = Discrete prob symbol\n accumulateEmissions grouped =\n let set = Set.toAscList $ foldMap (Set.fromList . map fst) grouped\n emi = Map.fromAscList $ zip set [0..]\n in DiscreteTrained $ Map.fromAscList $ zip set $\n transposeVectorList $\n map\n (NC.accum (NC.konst 0 (length set)) (+) .\n map (mapFst\n (mapLookup \"estimateDiscrete: unknown emission symbol\" emi)))\n grouped\n combine (DiscreteTrained distr0) (DiscreteTrained distr1) =\n DiscreteTrained $ Map.unionWith NC.add distr0 distr1\n normalize (DiscreteTrained distr) =\n Discrete $ Map.fromAscList $ zip (Map.keys distr) $\n transposeVectorList $ map normalizeProb $\n transposeVectorList $ Map.elems distr\n\ntransposeVectorList :: (Matrix.Element a) => [Vector a] -> [Vector a]\ntransposeVectorList = Matrix.toRows . Matrix.fromColumns\n\nmapLookup :: (Ord k) => String -> Map.Map k a -> k -> a\nmapLookup msg dict x =\n Map.findWithDefault (error msg) x dict\n\n\nnewtype Gaussian a = Gaussian (Array State (Vector a, Matrix a, a))\n deriving (Show)\n\nnewtype GaussianTrained a = GaussianTrained (Map State (Vector a, Matrix a, a))\n deriving (Show)\n\ntype instance Probability (Gaussian a) = a\ntype instance Emission (Gaussian a) = Vector a\n\ntype instance Trained (Gaussian a) = GaussianTrained a\n\n\ninstance (NFData a, Storable a) => NFData (Gaussian a) where\n rnf (Gaussian params) = rnf params\n\ninstance (NFData a, Storable a) => NFData (GaussianTrained a) where\n rnf (GaussianTrained params) = rnf params\n\ninstance (Algo.Field a) => Info (Gaussian a) where\n numberOfStates (Gaussian params) = Array.rangeSize $ Array.bounds params\n\ninstance (Algo.Field a) => Generate (Gaussian a) where\n generate (Gaussian allParams) state = do\n let (center, covarianceChol, _c) = allParams ! state\n seed <- MS.state Rnd.random\n return $\n NC.add center $\n NC.cmap realToFrac\n (NC.randomVector seed NC.Gaussian (Vector.dim center))\n <> covarianceChol\n\ninstance (HMatrix.Numeric a, Algo.Field a) => EmissionProb (Gaussian a) where\n emissionProb (Gaussian allParams) x =\n Vector.fromList $ map (emissionProbGen x) $ Array.elems allParams\n emissionStateProb (Gaussian allParams) x s =\n emissionProbGen x $ allParams ! s\n\nemissionProbGen ::\n (HMatrix.Numeric a, Algo.Field a) =>\n Vector a -> (Vector a, Matrix a, a) -> a\nemissionProbGen =\n let cholSolve m x = Matrix.flatten $ Algo.cholSolve m $ Matrix.asColumn x\n in \\x (center, covarianceChol, c) ->\n let x0 = NC.sub x center\n in c * exp ((-1/2) * NC.dot x0 (cholSolve covarianceChol x0))\n\n\ninstance (HMatrix.Numeric a, Algo.Field a) => Estimate (GaussianTrained a) where\n type Distribution (GaussianTrained a) = Gaussian a\n accumulateEmissions =\n let params xs =\n let center =\n NonEmpty.foldl1Map NC.add (uncurry $ flip NC.scale) xs\n covariance =\n NonEmpty.foldl1Map NC.add (\\(x,c) -> NC.scale c $ NC.outer x x) xs\n in (center, covariance, Fold.sum $ fmap snd xs)\n in GaussianTrained . fmap params . Map.mapMaybe NonEmpty.fetch .\n Map.fromList . zip [State 0 ..]\n combine (GaussianTrained distr0) (GaussianTrained distr1) =\n let comb (center0, covariance0, weight0)\n (center1, covariance1, weight1) =\n (NC.add center0 center1,\n NC.add covariance0 covariance1,\n weight0 + weight1)\n in GaussianTrained $ Map.unionWith comb distr0 distr1\n {-\n Sum_i (xi-mi) * (xi-mi)^T\n = Sum_i xi*xi^T + Sum_i mi*mi^T - Sum_i xi*mi^T - Sum_i mi*xi^T\n = Sum_i xi*xi^T - Sum_i mi*mi^T\n = Sum_i xi*xi^T - n * mi*mi^T\n -}\n normalize (GaussianTrained distr) =\n let params (centerSum, covarianceSum, weight) =\n let c = recip weight\n center = NC.scale c centerSum\n in (center,\n NC.sub (NC.scale c covarianceSum) (NC.outer center center))\n in Gaussian $\n Array.array (fst $ Map.findMin distr, fst $ Map.findMax distr) $\n Map.toList $ fmap (gaussianParameters . params) distr\n\ngaussian ::\n (Algo.Field prob) =>\n [(Vector prob, Matrix prob)] -> Gaussian prob\ngaussian =\n consGaussian . map gaussianParameters\n\ngaussianParameters ::\n (Algo.Field prob) =>\n (Vector prob, Matrix prob) -> (Vector prob, Matrix prob, prob)\ngaussianParameters (center, covariance) =\n gaussianFromCholesky center $ Algo.chol covariance\n\nconsGaussian :: [(Vector a, Matrix a, a)] -> Gaussian a\nconsGaussian xs =\n Gaussian $ listArray (State 0, State $ length xs - 1) xs\n\ngaussianFromCholesky ::\n (Algo.Field prob) =>\n Vector prob -> Matrix prob -> (Vector prob, Matrix prob, prob)\ngaussianFromCholesky center covarianceChol =\n let covarianceSqrtDet = NC.prodElements $ Matrix.takeDiag covarianceChol\n in (center, covarianceChol,\n recip (sqrt (2*pi) ^ Vector.dim center * covarianceSqrtDet))\n\n\n\nclass CSV distr where\n toCells :: distr -> [[String]]\n parseCells :: Int -> HMMCSV.CSVParser distr\n\nclass (Ord symbol) => CSVSymbol symbol where\n cellFromSymbol :: symbol -> String\n symbolFromCell :: String -> Maybe symbol\n\ninstance CSVSymbol Char where\n cellFromSymbol = (:[])\n symbolFromCell = listToMaybe\n\ninstance CSVSymbol Int where\n cellFromSymbol = show\n symbolFromCell = maybeRead\n\n\ninstance\n (Algo.Field prob, Show prob, Read prob, CSVSymbol symbol) =>\n CSV (Discrete prob symbol) where\n toCells (Discrete m) =\n map\n (\\(symbol, probs) ->\n cellFromSymbol symbol : HMMCSV.cellsFromVector probs) $\n Map.toAscList m\n parseCells n =\n fmap (Discrete . Map.fromList) $\n HMMCSV.manyRowsUntilEnd $ parseSymbolProb n\n\nparseSymbolProb ::\n (Algo.Field prob, Read prob, CSVSymbol symbol) =>\n Int -> CSV.CSVRow -> HMMCSV.CSVParser (symbol, Vector prob)\nparseSymbolProb n row =\n case row of\n [] -> MT.lift $ ME.throw \"missing symbol\"\n c:cs ->\n liftM2 (,)\n (let str = CSV.csvFieldContent c\n in MT.lift $ ME.fromMaybe (printf \"unknown symbol %s\" str) $\n symbolFromCell str)\n (do v <- HMMCSV.parseVectorFields cs\n HMMCSV.assert (n == Vector.dim v)\n (printf \"number of states (%d) and size of probability vector (%d) mismatch\"\n n (Vector.dim v))\n return v)\n\n\ninstance (Algo.Field a, Eq a, Show a, Read a) => CSV (Gaussian a) where\n toCells (Gaussian params) =\n List.intercalate [[]] $\n map\n (\\(center, covarianceChol, _) ->\n HMMCSV.cellsFromVector center :\n HMMCSV.cellsFromMatrix covarianceChol) $\n Array.elems params\n parseCells n = do\n gs <- HMMCSV.manySepUntilEnd parseSingleGaussian\n HMMCSV.assert (length gs == n) $\n printf \"number of states (%d) and number of Gaussians (%d) mismatch\"\n n (length gs)\n return $ consGaussian gs\n\nparseSingleGaussian ::\n (Algo.Field prob, Eq prob, Read prob) =>\n HMMCSV.CSVParser (Vector prob, Matrix prob, prob)\nparseSingleGaussian = do\n center <- HMMCSV.parseNonEmptyVectorCells\n covarianceChol <- HMMCSV.parseSquareMatrixCells $ Vector.dim center\n HMMCSV.assert (isUpperTriang covarianceChol) $\n \"matrices must be upper triangular\"\n return $ gaussianFromCholesky center covarianceChol\n\n\n{-\nMaybe this test is too strict.\nIt would also be ok, and certainly more intuitive\nto use an orthogonal but not normalized matrix.\nWe could get such a matrix from the eigensystem.\n-}\nisUpperTriang :: (Algo.Field a, Eq a) => Matrix a -> Bool\nisUpperTriang m =\n let cleared = Matrix.mapMatrixWithIndex (\\(i,j) x -> if i>j then x else 0) m\n in NC.minElement cleared == 0 &&\n NC.maxElement cleared == 0\n", "meta": {"hexsha": "2ef459b33be188da99a9b46bb744337c83b2827e", "size": 12526, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Math/HiddenMarkovModel/Distribution.hs", "max_stars_repo_name": "rybern/hmm-hmatrix", "max_stars_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math/HiddenMarkovModel/Distribution.hs", "max_issues_repo_name": "rybern/hmm-hmatrix", "max_issues_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/HiddenMarkovModel/Distribution.hs", "max_forks_repo_name": "rybern/hmm-hmatrix", "max_forks_repo_head_hexsha": "3f1c44aa630e0c7a662c1abe100ea8e783e3c44e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5068870523, "max_line_length": 95, "alphanum_fraction": 0.6809835542, "num_tokens": 3252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.5, "lm_q1q2_score": 0.38454011324259596}} {"text": "{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE PatternGuards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeFamilies #-}\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\n{-# LANGUAGE Trustworthy #-}\n{-# LANGUAGE DeriveGeneric #-}\n#endif\n\n#ifndef MIN_VERSION_vector\n#define MIN_VERSION_vector(x,y,z) 1\n#endif\n-----------------------------------------------------------------------------\n-- |\n-- Copyright : (C) 2012-2015 Edward Kmett\n-- License : BSD-style (see the file LICENSE)\n--\n-- Maintainer : Edward Kmett \n-- Stability : experimental\n-- Portability : non-portable\n--\n-- Quaternions\n----------------------------------------------------------------------------\nmodule Linear.Quaternion\n ( Quaternion(..)\n , Complicated(..)\n , Hamiltonian(..)\n , ee, ei, ej, ek\n , slerp\n , asinq\n , acosq\n , atanq\n , asinhq\n , acoshq\n , atanhq\n , absi\n , pow\n , rotate\n , axisAngle\n ) where\n\nimport Control.Applicative\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Monad (liftM)\nimport Control.Monad.Fix\nimport Control.Monad.Zip\nimport Control.Lens hiding ((<.>))\nimport Data.Binary as Binary\nimport Data.Bytes.Serial\nimport Data.Complex (Complex((:+)))\nimport Data.Data\nimport Data.Distributive\nimport Data.Foldable\nimport Data.Functor.Bind\nimport Data.Functor.Classes\nimport Data.Functor.Rep\nimport Data.Hashable\nimport Data.Serialize as Cereal\nimport GHC.Arr (Ix(..))\nimport qualified Data.Foldable as F\nimport Data.Monoid\nimport Foreign.Ptr (castPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\nimport GHC.Generics (Generic)\n#endif\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706\nimport GHC.Generics (Generic1)\n#endif\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Linear.Epsilon\nimport Linear.Conjugate\nimport Linear.Metric\nimport Linear.V3\nimport Linear.Vector\nimport Prelude hiding (any)\n\n{-# ANN module \"HLint: ignore Reduce duplication\" #-}\n\n-- | Quaternions\ndata Quaternion a = Quaternion !a {-# UNPACK #-}!(V3 a)\n deriving (Eq,Ord,Read,Show,Data,Typeable\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702\n ,Generic\n#endif\n#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706\n ,Generic1\n#endif\n )\n\ninstance Functor Quaternion where\n fmap f (Quaternion e v) = Quaternion (f e) (fmap f v)\n {-# INLINE fmap #-}\n a <$ _ = Quaternion a (V3 a a a)\n {-# INLINE (<$) #-}\n\ninstance Apply Quaternion where\n Quaternion f fv <.> Quaternion a v = Quaternion (f a) (fv <.> v)\n {-# INLINE (<.>) #-}\n\ninstance Applicative Quaternion where\n pure a = Quaternion a (pure a)\n {-# INLINE pure #-}\n Quaternion f fv <*> Quaternion a v = Quaternion (f a) (fv <*> v)\n {-# INLINE (<*>) #-}\n\ninstance Additive Quaternion where\n zero = pure 0\n {-# INLINE zero #-}\n liftU2 = liftA2\n {-# INLINE liftU2 #-}\n liftI2 = liftA2\n {-# INLINE liftI2 #-}\n\ninstance Bind Quaternion where\n Quaternion a (V3 b c d) >>- f = Quaternion a' (V3 b' c' d') where\n Quaternion a' _ = f a\n Quaternion _ (V3 b' _ _) = f b\n Quaternion _ (V3 _ c' _) = f c\n Quaternion _ (V3 _ _ d') = f d\n {-# INLINE (>>-) #-}\n\ninstance Monad Quaternion where\n return = pure\n {-# INLINE return #-}\n -- the diagonal of a sedenion is super useful!\n Quaternion a (V3 b c d) >>= f = Quaternion a' (V3 b' c' d') where\n Quaternion a' _ = f a\n Quaternion _ (V3 b' _ _) = f b\n Quaternion _ (V3 _ c' _) = f c\n Quaternion _ (V3 _ _ d') = f d\n {-# INLINE (>>=) #-}\n\ninstance Ix a => Ix (Quaternion a) where\n {-# SPECIALISE instance Ix (Quaternion Int) #-}\n\n range (Quaternion l1 l2, Quaternion u1 u2) =\n [ Quaternion i1 i2 | i1 <- range (l1,u1), i2 <- range (l2,u2) ]\n {-# INLINE range #-}\n\n unsafeIndex (Quaternion l1 l2, Quaternion u1 u2) (Quaternion i1 i2) =\n unsafeIndex (l1,u1) i1 * unsafeRangeSize (l2,u2) + unsafeIndex (l2,u2) i2\n {-# INLINE unsafeIndex #-}\n\n inRange (Quaternion l1 l2, Quaternion u1 u2) (Quaternion i1 i2) =\n inRange (l1,u1) i1 && inRange (l2,u2) i2\n {-# INLINE inRange #-}\n\ninstance Representable Quaternion where\n type Rep Quaternion = E Quaternion\n tabulate f = Quaternion (f ee) (V3 (f ei) (f ej) (f ek))\n {-# INLINE tabulate #-}\n index xs (E l) = view l xs\n {-# INLINE index #-}\n\ninstance FunctorWithIndex (E Quaternion) Quaternion where\n imap f (Quaternion a (V3 b c d)) = Quaternion (f ee a) $ V3 (f ei b) (f ej c) (f ek d)\n {-# INLINE imap #-}\n\ninstance FoldableWithIndex (E Quaternion) Quaternion where\n ifoldMap f (Quaternion a (V3 b c d)) = f ee a `mappend` f ei b `mappend` f ej c `mappend` f ek d\n {-# INLINE ifoldMap #-}\n\ninstance TraversableWithIndex (E Quaternion) Quaternion where\n itraverse f (Quaternion a (V3 b c d)) = Quaternion <$> f ee a <*> (V3 <$> f ei b <*> f ej c <*> f ek d)\n {-# INLINE itraverse #-}\n\ntype instance Index (Quaternion a) = E Quaternion\ntype instance IxValue (Quaternion a) = a\n\ninstance Ixed (Quaternion a) where\n ix = el\n {-# INLINE ix #-}\n\ninstance Each (Quaternion a) (Quaternion b) a b where\n each = traverse\n {-# INLINE each #-}\n\ninstance Foldable Quaternion where\n foldMap f (Quaternion e v) = f e `mappend` foldMap f v\n {-# INLINE foldMap #-}\n foldr f z (Quaternion e v) = f e (F.foldr f z v)\n {-# INLINE foldr #-}\n\ninstance Traversable Quaternion where\n traverse f (Quaternion e v) = Quaternion <$> f e <*> traverse f v\n {-# INLINE traverse #-}\n\ninstance Storable a => Storable (Quaternion a) where\n sizeOf _ = 4 * sizeOf (undefined::a)\n {-# INLINE sizeOf #-}\n alignment _ = alignment (undefined::a)\n {-# INLINE alignment #-}\n poke ptr (Quaternion e v) = poke (castPtr ptr) e >>\n poke (castPtr (ptr `plusPtr` sz)) v\n where sz = sizeOf (undefined::a)\n {-# INLINE poke #-}\n peek ptr = Quaternion <$> peek (castPtr ptr)\n <*> peek (castPtr (ptr `plusPtr` sz))\n where sz = sizeOf (undefined::a)\n {-# INLINE peek #-}\n\ninstance RealFloat a => Num (Quaternion a) where\n {-# SPECIALIZE instance Num (Quaternion Float) #-}\n {-# SPECIALIZE instance Num (Quaternion Double) #-}\n (+) = liftA2 (+)\n {-# INLINE (+) #-}\n (-) = liftA2 (-)\n {-# INLINE (-) #-}\n negate = fmap negate\n {-# INLINE negate #-}\n Quaternion s1 v1 * Quaternion s2 v2 = Quaternion (s1*s2 - (v1 `dot` v2)) $\n (v1 `cross` v2) + s1*^v2 + s2*^v1\n {-# INLINE (*) #-}\n fromInteger x = Quaternion (fromInteger x) 0\n {-# INLINE fromInteger #-}\n abs z = Quaternion (norm z) 0\n {-# INLINE abs #-}\n signum q@(Quaternion e (V3 i j k))\n | m == 0.0 = q\n | not (isInfinite m || isNaN m) = q ^/ sqrt m\n | any isNaN q = qNaN\n | not (ii || ij || ik) = Quaternion 1 (V3 0 0 0)\n | not (ie || ij || ik) = Quaternion 0 (V3 1 0 0)\n | not (ie || ii || ik) = Quaternion 0 (V3 0 1 0)\n | not (ie || ii || ij) = Quaternion 0 (V3 0 0 1)\n | otherwise = qNaN\n where\n m = quadrance q\n ie = isInfinite e\n ii = isInfinite i\n ij = isInfinite j\n ik = isInfinite k\n {-# INLINE signum #-}\n\ninstance Hashable a => Hashable (Quaternion a) where\n hashWithSalt s (Quaternion a b) = s `hashWithSalt` a `hashWithSalt` b\n {-# INLINE hashWithSalt #-}\n\nqNaN :: RealFloat a => Quaternion a\nqNaN = Quaternion fNaN (V3 fNaN fNaN fNaN) where fNaN = 0/0\n{-# INLINE qNaN #-}\n\n-- {-# RULES \"abs/norm\" abs x = Quaternion (norm x) 0 #-}\n-- {-# RULES \"signum/signorm\" signum = signorm #-}\n\n-- this will attempt to rewrite calls to abs to use norm intead when it is available.\n\ninstance RealFloat a => Fractional (Quaternion a) where\n {-# SPECIALIZE instance Fractional (Quaternion Float) #-}\n {-# SPECIALIZE instance Fractional (Quaternion Double) #-}\n Quaternion q0 (V3 q1 q2 q3) / Quaternion r0 (V3 r1 r2 r3) =\n Quaternion (r0*q0+r1*q1+r2*q2+r3*q3)\n (V3 (r0*q1-r1*q0-r2*q3+r3*q2)\n (r0*q2+r1*q3-r2*q0-r3*q1)\n (r0*q3-r1*q2+r2*q1-r3*q0))\n ^/ (r0*r0 + r1*r1 + r2*r2 + r3*r3)\n {-# INLINE (/) #-}\n recip q = q ^/ quadrance q\n {-# INLINE recip #-}\n fromRational x = Quaternion (fromRational x) 0\n {-# INLINE fromRational #-}\n\ninstance Metric Quaternion where\n Quaternion e v `dot` Quaternion e' v' = e*e' + (v `dot` v')\n {-# INLINE dot #-}\n\n-- | A vector space that includes the basis elements '_e' and '_i'\nclass Complicated t where\n _e, _i :: Lens' (t a) a\n\nee, ei :: Complicated t => E t\nee = E _e\nei = E _i\n\ninstance Complicated Complex where\n _e f (a :+ b) = (:+ b) <$> f a\n {-# INLINE _e #-}\n _i f (a :+ b) = (a :+) <$> f b\n {-# INLINE _i #-}\n\ninstance Complicated Quaternion where\n _e f (Quaternion a v) = (`Quaternion` v) <$> f a\n {-# INLINE _e #-}\n _i f (Quaternion a v) = Quaternion a <$> _x f v\n {-# INLINE _i #-}\n\n-- | A vector space that includes the basis elements '_e', '_i', '_j' and '_k'\nclass Complicated t => Hamiltonian t where\n _j, _k :: Lens' (t a) a\n _ijk :: Lens' (t a) (V3 a)\n\nej, ek :: Hamiltonian t => E t\nej = E _j\nek = E _k\n\ninstance Hamiltonian Quaternion where\n _j f (Quaternion a v) = Quaternion a <$> _y f v\n {-# INLINE _j #-}\n _k f (Quaternion a v) = Quaternion a <$> _z f v\n {-# INLINE _k #-}\n _ijk f (Quaternion a v) = Quaternion a <$> f v\n {-# INLINE _ijk #-}\n\ninstance Distributive Quaternion where\n distribute f = Quaternion (fmap (\\(Quaternion x _) -> x) f) $ V3\n (fmap (\\(Quaternion _ (V3 y _ _)) -> y) f)\n (fmap (\\(Quaternion _ (V3 _ z _)) -> z) f)\n (fmap (\\(Quaternion _ (V3 _ _ w)) -> w) f)\n {-# INLINE distribute #-}\n\ninstance (Conjugate a, RealFloat a) => Conjugate (Quaternion a) where\n conjugate (Quaternion e v) = Quaternion (conjugate e) (negate v)\n {-# INLINE conjugate #-}\n\nreimagine :: RealFloat a => a -> a -> Quaternion a -> Quaternion a\nreimagine r s (Quaternion _ v)\n | isNaN s || isInfinite s = let aux 0 = 0\n aux x = s * x\n in Quaternion r (aux <$> v)\n | otherwise = Quaternion r (v^*s)\n{-# INLINE reimagine #-}\n\n-- | quadrance of the imaginary component\nqi :: Num a => Quaternion a -> a\nqi (Quaternion _ v) = quadrance v\n{-# INLINE qi #-}\n\n-- | norm of the imaginary component\nabsi :: Floating a => Quaternion a -> a\nabsi = sqrt . qi\n{-# INLINE absi #-}\n\n-- | raise a 'Quaternion' to a scalar power\npow :: RealFloat a => Quaternion a -> a -> Quaternion a\npow q t = exp (t *^ log q)\n{-# INLINE pow #-}\n\nsqrte2pqiq :: (Floating a, Ord a) => a -> a -> a\nsqrte2pqiq e qiq -- = sqrt (e*e) + qiq\n | e < - 1.5097698010472593e153 = -(qiq/e) - e\n | e < 5.582399551122541e57 = sqrt ((e*e) + qiq) -- direct definition\n | otherwise = (qiq/e) + e\n-- {-# SPECIALIZE sqrte2pqiq :: Double -> Double -> Double #-}\n-- {-# SPECIALIZE sqrte2pqiq :: Float -> Float -> Float #-}\n#ifdef HERBIE\n{-# ANN sqrte2pqiq \"NoHerbie\" #-}\n#endif\n\ntanrhs :: (Floating a, Ord a) => a -> a -> a -> a\ntanrhs sai ai d -- = cosh ai * (sai / ai) / d -- improved from 6.04 bits of error to 0.19 bits\n | sai < -4.618902267687042e-52 = (sai / d / ai) * cosh ai\n | sai < 1.038530535935153e-39 = (cosh ai * sai) / ai / d\n | otherwise = (sai / d / ai) * cosh ai\n-- {-# SPECIALIZE tanrhs :: Double -> Double -> Double -> Double #-}\n-- {-# SPECIALIZE tanrhs :: Float -> Float -> Float -> Float #-}\n#ifdef HERBIE\n{-# ANN tanrhs \"NoHerbie\" #-}\n#endif\n\n\n-- ehh..\ninstance RealFloat a => Floating (Quaternion a) where\n {-# SPECIALIZE instance Floating (Quaternion Float) #-}\n {-# SPECIALIZE instance Floating (Quaternion Double) #-}\n pi = Quaternion pi 0\n {-# INLINE pi #-}\n exp q@(Quaternion e v)\n | qiq == 0 = Quaternion (exp e) v\n | ai <- sqrt qiq, exe <- exp e = reimagine (exe * cos ai) (exe * (sin ai / ai)) q\n where qiq = qi q\n {-# INLINE exp #-}\n log q@(Quaternion e v@(V3 _i j k))\n | qiq == 0 = if e >= 0\n then Quaternion (log e) v\n else Quaternion (log (negate e)) (V3 pi j k) -- mmm, pi\n | ai <- sqrt qiq = reimagine (log m) (atan2 m e / ai) q\n where qiq = qi q\n m = sqrte2pqiq e qiq\n {-# INLINE log #-}\n\n x ** y = exp (y * log x)\n {-# INLINE (**) #-}\n\n sqrt q@(Quaternion e v)\n | m == 0 = q\n | qiq == 0 = if e > 0\n then Quaternion (sqrt e) 0\n else Quaternion 0 (V3 (sqrt (negate e)) 0 0)\n | im <- sqrt (0.5*(m-e)) / sqrt qiq = Quaternion (0.5*(m+e)) (v^*im)\n where qiq = qi q\n m = sqrte2pqiq e qiq\n {-# INLINE sqrt #-}\n\n cos q@(Quaternion e v)\n | qiq == 0 = Quaternion (cos e) v\n | ai <- sqrt qiq = reimagine (cos e * cosh ai) (- sin e / ai / sinh ai) q -- 0.15 bits error\n -- reimagine (cos e * cosh ai) (- sin e * sinh ai / ai) q -- 13.5 bits worse\n where qiq = qi q\n {-# INLINE cos #-}\n\n sin q@(Quaternion e v)\n | qiq == 0 = Quaternion (sin e) v\n | ai <- sqrt qiq = reimagine (sin e * cosh ai) (cos e * sinh ai / ai) q\n where qiq = qi q\n {-# INLINE sin #-}\n\n tan q@(Quaternion e v)\n | qiq == 0 = Quaternion (tan e) v\n | ai <- sqrt qiq, ce <- cos e, sai <- sinh ai, d <- ce*ce + sai*sai =\n reimagine (ce * sin e / d) (tanrhs sai ai d) q\n where qiq = qi q\n {-# INLINE tan #-}\n\n sinh q@(Quaternion e v)\n | qiq == 0 = Quaternion (sinh e) v\n | ai <- sqrt qiq = reimagine (sinh e * cos ai) (cosh e * sin ai / ai) q\n where qiq = qi q\n {-# INLINE sinh #-}\n\n cosh q@(Quaternion e v)\n | qiq == 0 = Quaternion (cosh e) v\n | ai <- sqrt qiq = reimagine (cosh e * cos ai) (sin ai * (sinh e / ai)) q\n where qiq = qi q\n {-# INLINE cosh #-}\n\n tanh q@(Quaternion e v)\n | qiq == 0 = Quaternion (tanh e) v\n | ai <- sqrt qiq, se <- sinh e, cai <- cos ai, d <- se*se + cai*cai =\n reimagine (cosh e * se / d) (tanhrhs cai ai d) q\n where qiq = qi q\n {-# INLINE tanh #-}\n\n asin = cut asin\n {-# INLINE asin #-}\n acos = cut acos\n {-# INLINE acos #-}\n atan = cut atan\n {-# INLINE atan #-}\n\n asinh = cut asinh\n {-# INLINE asinh #-}\n acosh = cut acosh\n {-# INLINE acosh #-}\n atanh = cut atanh\n {-# INLINE atanh #-}\n\ntanhrhs :: (Floating a, Ord a) => a -> a -> a -> a\ntanhrhs cai ai d -- = cai * (sin ai / ai) / d\n | d >= -4.2173720203427147e-29 && d < 4.446702369113811e64 = cai / (d * (ai / sin ai))\n | otherwise = cai * (1 / ai / sin ai) / d\n-- {-# SPECIALIZE tanhrhs :: Double -> Double -> Double -> Double #-}\n-- {-# SPECIALIZE tanhrhs :: Float -> Float -> Float -> Float #-}\n#ifdef HERBIE\n{-# ANN tanhrhs \"NoHerbie\" #-}\n#endif\n\n-- | Helper for calculating with specific branch cuts\ncut :: RealFloat a => (Complex a -> Complex a) -> Quaternion a -> Quaternion a\ncut f q@(Quaternion e (V3 _ y z))\n | qiq == 0 = Quaternion a (V3 b y z)\n | otherwise = reimagine a (b / ai) q\n where qiq = qi q\n ai = sqrt qiq\n a :+ b = f (e :+ ai)\n{-# INLINE cut #-}\n\n-- | Helper for calculating with specific branch cuts\ncutWith :: RealFloat a => Complex a -> Quaternion a -> Quaternion a\ncutWith (r :+ im) q@(Quaternion e v)\n | e /= 0 || qiq == 0 || isNaN qiq || isInfinite qiq = error \"bad cut\"\n | s <- im / sqrt qiq = Quaternion r (v^*s)\n where qiq = qi q\n{-# INLINE cutWith #-}\n\n-- | 'asin' with a specified branch cut.\nasinq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\nasinq q@(Quaternion e _) u\n | qiq /= 0.0 || e >= -1 && e <= 1 = asin q\n | otherwise = cutWith (asin (e :+ sqrt qiq)) u\n where qiq = qi q\n{-# INLINE asinq #-}\n\n-- | 'acos' with a specified branch cut.\nacosq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\nacosq q@(Quaternion e _) u\n | qiq /= 0.0 || e >= -1 && e <= 1 = acos q\n | otherwise = cutWith (acos (e :+ sqrt qiq)) u\n where qiq = qi q\n{-# INLINE acosq #-}\n\n-- | 'atan' with a specified branch cut.\natanq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\natanq q@(Quaternion e _) u\n | e /= 0.0 || qiq >= -1 && qiq <= 1 = atan q\n | otherwise = cutWith (atan (e :+ sqrt qiq)) u\n where qiq = qi q\n{-# INLINE atanq #-}\n\n-- | 'asinh' with a specified branch cut.\nasinhq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\nasinhq q@(Quaternion e _) u\n | e /= 0.0 || qiq >= -1 && qiq <= 1 = asinh q\n | otherwise = cutWith (asinh (e :+ sqrt qiq)) u\n where qiq = qi q\n{-# INLINE asinhq #-}\n\n-- | 'acosh' with a specified branch cut.\nacoshq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\nacoshq q@(Quaternion e _) u\n | qiq /= 0.0 || e >= 1 = asinh q\n | otherwise = cutWith (acosh (e :+ sqrt qiq)) u\n where qiq = qi q\n{-# INLINE acoshq #-}\n\n-- | 'atanh' with a specified branch cut.\natanhq :: RealFloat a => Quaternion a -> Quaternion a -> Quaternion a\natanhq q@(Quaternion e _) u\n | qiq /= 0.0 || e > -1 && e < 1 = atanh q\n | otherwise = cutWith (atanh (e :+ sqrt qiq)) u\n where qiq = qi q\n{-# INLINE atanhq #-}\n\n-- | Spherical linear interpolation between two quaternions.\n\nslerp :: RealFloat a => Quaternion a -> Quaternion a -> a -> Quaternion a\nslerp q p t\n | 1.0 - cosphi < 1e-8 = q\n | otherwise = ((sin ((1-t)*phi) *^ q) + sin (t*phi) *^ f p) ^/ sin phi\n where\n dqp = dot q p\n (cosphi, f) = if dqp < 0 then (-dqp, negate) else (dqp, id)\n phi = acos cosphi\n{-# SPECIALIZE slerp :: Quaternion Float -> Quaternion Float -> Float -> Quaternion Float #-}\n{-# SPECIALIZE slerp :: Quaternion Double -> Quaternion Double -> Double -> Quaternion Double #-}\n\n-- | Apply a rotation to a vector.\nrotate :: (Conjugate a, RealFloat a) => Quaternion a -> V3 a -> V3 a\nrotate q v = ijk where\n Quaternion _ ijk = q * Quaternion 0 v * conjugate q\n{-# SPECIALIZE rotate :: Quaternion Float -> V3 Float -> V3 Float #-}\n{-# SPECIALIZE rotate :: Quaternion Double -> V3 Double -> V3 Double #-}\n\ninstance (RealFloat a, Epsilon a) => Epsilon (Quaternion a) where\n nearZero = nearZero . quadrance\n {-# INLINE nearZero #-}\n\n-- | @'axisAngle' axis theta@ builds a 'Quaternion' representing a\n-- rotation of @theta@ radians about @axis@.\naxisAngle :: (Epsilon a, Floating a) => V3 a -> a -> Quaternion a\naxisAngle axis theta = Quaternion (cos half) (sin half *^ normalize axis)\n where half = theta / 2\n{-# INLINE axisAngle #-}\n\ndata instance U.Vector (Quaternion a) = V_Quaternion !Int (U.Vector a)\ndata instance U.MVector s (Quaternion a) = MV_Quaternion !Int (U.MVector s a)\ninstance U.Unbox a => U.Unbox (Quaternion a)\n\ninstance U.Unbox a => M.MVector U.MVector (Quaternion a) where\n basicLength (MV_Quaternion n _) = n\n basicUnsafeSlice m n (MV_Quaternion _ v) = MV_Quaternion n (M.basicUnsafeSlice (4*m) (4*n) v)\n basicOverlaps (MV_Quaternion _ v) (MV_Quaternion _ u) = M.basicOverlaps v u\n basicUnsafeNew n = liftM (MV_Quaternion n) (M.basicUnsafeNew (4*n))\n basicUnsafeRead (MV_Quaternion _ v) i =\n do let o = 4*i\n x <- M.basicUnsafeRead v o\n y <- M.basicUnsafeRead v (o+1)\n z <- M.basicUnsafeRead v (o+2)\n w <- M.basicUnsafeRead v (o+3)\n return (Quaternion x (V3 y z w))\n basicUnsafeWrite (MV_Quaternion _ v) i (Quaternion x (V3 y z w)) =\n do let o = 4*i\n M.basicUnsafeWrite v o x\n M.basicUnsafeWrite v (o+1) y\n M.basicUnsafeWrite v (o+2) z\n M.basicUnsafeWrite v (o+3) w\n#if MIN_VERSION_vector(0,11,0)\n basicInitialize (MV_Quaternion _ v) = M.basicInitialize v\n#endif\n\ninstance U.Unbox a => G.Vector U.Vector (Quaternion a) where\n basicUnsafeFreeze (MV_Quaternion n v) = liftM ( V_Quaternion n) (G.basicUnsafeFreeze v)\n basicUnsafeThaw ( V_Quaternion n v) = liftM (MV_Quaternion n) (G.basicUnsafeThaw v)\n basicLength ( V_Quaternion n _) = n\n basicUnsafeSlice m n (V_Quaternion _ v) = V_Quaternion n (G.basicUnsafeSlice (4*m) (4*n) v)\n basicUnsafeIndexM (V_Quaternion _ v) i =\n do let o = 4*i\n x <- G.basicUnsafeIndexM v o\n y <- G.basicUnsafeIndexM v (o+1)\n z <- G.basicUnsafeIndexM v (o+2)\n w <- G.basicUnsafeIndexM v (o+3)\n return (Quaternion x (V3 y z w))\n\ninstance MonadZip Quaternion where\n mzipWith = liftA2\n\ninstance MonadFix Quaternion where\n mfix f = Quaternion (let Quaternion a _ = f a in a)\n (V3 (let Quaternion _ (V3 a _ _) = f a in a)\n (let Quaternion _ (V3 _ a _) = f a in a)\n (let Quaternion _ (V3 _ _ a) = f a in a))\n\ninstance NFData a => NFData (Quaternion a) where\n rnf (Quaternion a b) = rnf a `seq` rnf b\n\ninstance Serial1 Quaternion where\n serializeWith f (Quaternion a b) = f a >> serializeWith f b\n deserializeWith f = Quaternion <$> f <*> deserializeWith f\n\ninstance Serial a => Serial (Quaternion a) where\n serialize = serializeWith serialize\n deserialize = deserializeWith deserialize\n\ninstance Binary a => Binary (Quaternion a) where\n put = serializeWith Binary.put\n get = deserializeWith Binary.get\n\ninstance Serialize a => Serialize (Quaternion a) where\n put = serializeWith Cereal.put\n get = deserializeWith Cereal.get\n\ninstance Eq1 Quaternion where eq1 = (==)\ninstance Ord1 Quaternion where compare1 = compare\ninstance Show1 Quaternion where showsPrec1 = showsPrec\ninstance Read1 Quaternion where readsPrec1 = readsPrec\n", "meta": {"hexsha": "f755b2ec15abe344dc38058b93ad77494d08a990", "size": 21327, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linear/Quaternion.hs", "max_stars_repo_name": "bgamari/linear", "max_stars_repo_head_hexsha": "e474ad140a92fae25b5099c5359a10178086111f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Linear/Quaternion.hs", "max_issues_repo_name": "bgamari/linear", "max_issues_repo_head_hexsha": "e474ad140a92fae25b5099c5359a10178086111f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Linear/Quaternion.hs", "max_forks_repo_name": "bgamari/linear", "max_forks_repo_head_hexsha": "e474ad140a92fae25b5099c5359a10178086111f", "max_forks_repo_licenses": ["BSD-3-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.7987321712, "max_line_length": 105, "alphanum_fraction": 0.6031321799, "num_tokens": 6692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.38425309893106296}} {"text": "{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# OPTIONS_GHC -fno-warn-deprecations #-}\n\nmodule Numeric.Tensile.Tensor.Internal where\n\nimport Data.Bits\nimport Data.ByteString (ByteString())\nimport Data.Complex\nimport Data.Int\nimport Data.Kind\nimport Data.Proxy\nimport Data.Word\nimport Data.Vector.Storable (Storable(..))\nimport Unsafe.Coerce (unsafeCoerce)\n\nimport Numeric.Tensile.Dimensions\n\nimport Data.Vector.Sized (Vector)\nimport TensorFlow.Types\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport qualified Data.Finite as F\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Sized as N\nimport qualified Data.Vector.Storable as S\nimport qualified Data.Vector.Storable.Mutable as M\nimport qualified TensorFlow.Tensor as T\nimport qualified TensorFlow.Build as T\nimport qualified TensorFlow.GenOps.Core as O\nimport qualified TensorFlow.Ops as O\nimport qualified TensorFlow.Session as Ss\n\nimport Control.Monad.IO.Class (liftIO)\nimport Control.Monad.Trans.Reader\n\n\n{-\nfromTensor :: Elt e => Tensor d e -> [e]\nfromTensor t = unsafePerformIO $ Ss.runSession $ do\n a <- T.render $ unTensor t\n b <- Ss.run a\n return $ V.toList b\n\n:: OneOf '[Int32, Int64] tidx\t \n=> Tensor v'1 Bool\t\ninput\n\n-> Tensor v'2 tidx\t\nreduction_indices\n\n-> Tensor Build Bool\n\ntranspose \n :: Elt e \n => Permutable d d'\n => Dims d -> Perm (Rank d) -> Tensor d e -> Tensor d' e\ntranspose d (Perm p) (Tensor t) = Tensor $ (flip O.transpose) (O.vector w) t\n where v = [1.. fromIntegral $ rank d] :: [IVal]\n w = P.permuteList p v\n\n\n-}\n-- | Generally specialized as in 'TVal' or 'IVal'.\ntype Elt e = OneOf '[Int32, Int64, Word32, Word64, Float, Double, Complex Float, Complex Double] e\n\n-- TODO: move to application / test stanza\n--type Elt = TensorType -- TODO deal with Variant and exclude ResourceHandle\ntype TVal = Float\ntype IVal = Int32\ntype BVal = Bool\n\ntype Dynamic d = Reader (Dims d)\n\n\nnewtype Tensor (d :: [Nat]) (e :: Type) = Tensor { unTensor :: T.Tensor T.Build e }\n\n-- | A real or complex-valued tensor of shape 'd'. \ntype T d = Tensor d TVal\n\n-- | An integer or non-negative integer-valued tensor of shape 'd'. \ntype I d = Tensor d IVal\n\n-- | A boolean-valued tensor of shape 'd'. \ntype B d = Tensor d BVal\n\n--TODO update Show instance\ninstance (Elt e, Show e) => Show (Tensor d e) where show _ = \"No Show instance.\"\n\n\n\n--TODO implement\ninstance (KnownDims d, Elt e, Eq e) => Eq (Tensor d e) where\n (==) ta tb = all $ ta `eq` tb\n where all :: B d -> Bool\n all (Tensor b) = Prelude.head $ toList $ Tensor $ O.all b (O.vector ([] :: [IVal]))\n\n\n\ninstance (KnownDims d, Num e, Elt e) => Num (Tensor d e) where\n (+) (Tensor v1) (Tensor v2) = Tensor $ (+) v1 v2\n {-# INLINE (+) #-}\n (-) (Tensor v1) (Tensor v2) = Tensor $ (-) v1 v2\n {-# INLINE (-) #-}\n (*) (Tensor v1) (Tensor v2) = Tensor $ (*) v1 v2\n {-# INLINE (*) #-}\n negate (Tensor v1) = Tensor $ negate v1\n {-# INLINE negate #-}\n abs (Tensor v1) = Tensor $ abs v1\n {-# INLINE abs #-}\n signum (Tensor v1) = Tensor $ signum v1\n {-# INLINE signum #-}\n fromInteger = constant (dims @d) . fromInteger\n {-# INLINE fromInteger #-}\n\n{-\ninstance (KnownDim (Size d), Fractional e, Elt e) => Fractional (Tensor d e) where\n (/) = _lift2 (/)\n {-# INLINE (/) #-}\n recip = _lift recip\n {-# INLINE recip #-}\n fromRational = _replicate (fromIntegral . dimVal $ (dim :: Dim (Size d))) . fromRational\n {-# INLINE fromRational #-}\n\ninstance (KnownDim (Size d), Floating e, Elt e) => Floating (Tensor d e) where\n pi = Tensor $ S.singleton pi --TODO make this dim safe\n {-# INLINE pi #-}\n exp = _lift exp\n {-# INLINE exp #-}\n log = _lift log\n {-# INLINE log #-}\n sqrt = _lift sqrt\n {-# INLINE sqrt #-}\n sin = _lift sin\n {-# INLINE sin #-}\n cos = _lift cos\n {-# INLINE cos #-}\n tan = _lift tan\n {-# INLINE tan #-}\n asin = _lift asin\n {-# INLINE asin #-}\n acos = _lift acos\n {-# INLINE acos #-}\n atan = _lift atan\n {-# INLINE atan #-}\n sinh = _lift sinh\n {-# INLINE sinh #-}\n cosh = _lift cosh\n {-# INLINE cosh #-}\n tanh = _lift tanh\n {-# INLINE tanh #-}\n (**) = _lift2 (**)\n {-# INLINE (**) #-}\n logBase = _lift2 logBase\n {-# INLINE logBase #-}\n asinh = _lift asinh\n {-# INLINE asinh #-}\n acosh = _lift acosh\n {-# INLINE acosh #-}\n atanh = _lift atanh\n {-# INLINE atanh #-}\n\ninstance (KnownDim (Size d), Elt e, Eq e, Bits e, Num e) => Bits (Tensor d e) where\n (.&.) = _lift2 (.&.)\n {-# INLINE (.&.) #-}\n (.|.) = _lift2 (.|.)\n {-# INLINE (.|.) #-}\n xor = _lift2 xor\n {-# INLINE xor #-}\n complement = _lift complement\n shift t i = _lift (flip shift i) t\n rotate t i = _lift (flip rotate i) t\n bit = _replicate (fromIntegral . dimVal $ (dim :: Dim (Size d))) . bit\n testBit = testBitDefault\n bitSizeMaybe _ = bitSizeMaybe @e undefined\n bitSize _ = bitSize @e undefined\n isSigned _ = isSigned @e undefined\n popCount = popCountDefault\n-}\n\n{-\n\ninstance (KnownDim (Size d), Elt e, Real e) => Real (Tensor d e) where\n toRational = undefined --TODO find a reasonable sum-based implementation or scrap the typeclass\n\ninstance (KnownDim (Size d), Elt e, Enum e) => Enum (Tensor d e) where\n toEnum = Tensor . S.replicate (fromIntegral . dimVal $ (dim :: Dim (Size d))) . toEnum\n {-# INLINE toEnum #-}\n fromEnum = undefined --TODO find a reasonable sum-based implementation or scrap the typeclass\n\ninstance (KnownDim (Size d), Elt e, Integral e) => Integral (Tensor d e) where\n quot (Tensor a) (Tensor b) = _lift2 quot a b\n rem (Tensor a) (Tensor b) = _lift2 rem a b\n div (Tensor a) (Tensor b) = _lift2 div a b\n mod (Tensor a) (Tensor b) = _lift2 mod a b\n quotRem ta tb = (quot ta tb, rem ta tb)\n divMod ta tb = (div ta tb, mod ta tb)\n toInteger _ = undefined --TODO find a reasonable sum-based implementation or scrap the typeclass\n\n-}\n\n\neq :: Elt e => Eq e => Tensor d e -> Tensor d e -> Tensor d BVal\neq (Tensor a) (Tensor b) = Tensor $ O.equal a b\n\nneq :: Elt e => Eq e => Tensor d e -> Tensor d e -> Tensor d BVal\nneq (Tensor a) (Tensor b) = Tensor $ O.notEqual a b\n\nlt :: Elt e => Ord e => Tensor d e -> Tensor d e -> Tensor d BVal\n--lt :: Ord TVal => T d -> T d -> B d\nlt (Tensor a) (Tensor b) = Tensor $ O.less a b\n\nlte :: Elt e => Ord e => Tensor d e -> Tensor d e -> Tensor d BVal\nlte (Tensor a) (Tensor b) = Tensor $ O.lessEqual a b\n\ngt :: Elt e => Ord e => Tensor d e -> Tensor d e -> Tensor d BVal\ngt (Tensor a) (Tensor b) = Tensor $ O.greater a b\n\ngte :: Elt e => Ord e => Tensor d e -> Tensor d e -> Tensor d BVal\ngte (Tensor a) (Tensor b) = Tensor $ O.greaterEqual a b\n\nmaximum :: Elt e => Ord e => Tensor d e -> Tensor d e -> Tensor d e\nmaximum (Tensor a) (Tensor b) = Tensor $ O.maximum a b\n\nminimum :: Elt e => Ord e => Tensor d e -> Tensor d e -> Tensor d e\nminimum (Tensor a) (Tensor b) = Tensor $ O.minimum a b\n\ntoList :: TensorDataType V.Vector a => Tensor d a -> [a]\ntoList t = unsafePerformIO $ Ss.runSession $ do\n a <- T.render $ unTensor t\n b <- Ss.run a\n return $ V.toList b\n\nfromList :: forall d e. Elt e => Dims d -> [e] -> Maybe (Tensor d e)\nfromList d l = if size d == (fromIntegral $ length l) then Just $ f l else Nothing\n where f = Tensor . O.constant (toShape d)\n\nfromList'' :: forall d e. Elt e => Dynamic d ([e] -> Maybe (Tensor d e))\nfromList'' = reader fromList\n\nfromList' :: forall d e. Elt e => KnownDims d => [e] -> Maybe (Tensor d e)\nfromList' = withDyn @d fromList''\n\n\n-- reflectDims @d $ \\d -> runReader fromList'' d $ l\n\n\nliftDyn :: (Dims d -> r) -> Dynamic d r\nliftDyn f = reader f\n\nwithDyn :: forall d r. KnownDims d => Dynamic d r -> r\nwithDyn dyn = reflectDims @d $ runReader dyn\n\n{-\n - http://hackage.haskell.org/package/contravariant-1.5/docs/Data-Functor-Contravariant.html\n -\n=> f (Dims d) \n\nTODO:\n - do lowerPerm and withDyn have anything in common? (e.g. operator constraints 'lowering' to Predicate (Dims d)). both are functors?\n - type-level Predicate for '[Nat] ? Equivalence '[Nat] ~ ('[Nat],'[Nat]) ~> Bool Could also include >1 req?\n -\n -\nwithDyn :: forall d r. KnownDims d => Predicate (Dims d) -> Dynamic d r -> Maybe r\n\nwithDyn2 \n :: forall x y r. (KnownDims x, KnownDims y) \n => Predicate (Dims x,) \n => Predicate (Dims y) \n -> Dynamic d r -> Maybe r\n\n\ndivided :: Divisible f => f a -> f b -> f (a, b) Source#\ndivided = divide id\n\n\nPredicate (Tensor d e)\nEquivalence (Tensor d e)\nPredicate (Dims d)\nEquivalence (Dims d)\n\ndivided :: Divisible f => f a -> f b -> f (a, b)\n\nnote in general we have \n\nDims x -> Bool\nDims x -> Dims y -> Bool\n\n\n\ntype Dynamic d = Reader (Dims d)\n\nfromList :: forall d e. Elt e => KnownDims d => [e] -> Maybe (Tensor d e)\nfromList v = if size (dims @d) == (fromIntegral $ length v) then Just $ f v else Nothing\n where f = Tensor . O.constant (toShape (dims @d))\n\n\ni = 0 :+ 1 :+ 2 :+ S :: Idxs '[1,2,3]\nj = 0 :+ 1 :+ 1 :+ S :: Idxs '[1,2,3]\n\n-- fromVector :: Elt e => Dims d -> Vector e -> Maybe (Tensor d e)\n-- fromVector d v = undefined\n-- \n-- toVector :: Elt e => Tensor d e -> Vector e\n-- toVector = unTensor\n-- \nfromSizedVector :: Elt e => Vector (Size d) e -> Tensor d e\nfromSizedVector = Tensor . S.convert . N.fromSized\n\ntoSizedVector :: Elt e => Tensor d e -> Vector (Size d) e\ntoSizedVector = coerce . S.convert . unTensor\n where coerce :: S.Vector e -> N.Vector n e\n coerce = unsafeCoerce\n\nfill :: Elt e => Dims d -> (Idxs d -> e) -> Tensor d e\nfill d f = Tensor $ S.create $ do\n mv <- M.new $ fromIntegral $ product $ listDims d\n let act ix = M.write mv (minorToMajor d ix) $ f ix\n forMIdxs_ d act\n return mv\n\n-- constant :: TensorType a => Shape -> [a] -> Tensor Build a\n\nconstant :: Elt e => Dims d -> e -> Tensor d e\nconstant d t = fill d $ const t\n\n-}\n\nconstant :: Elt e => Dims d -> e -> Tensor d e\nconstant d = Tensor . O.constant (toShape d) . pure\n\ntoShape :: Dims d -> Shape\ntoShape = Shape . fmap fromIntegral . listDims \n\ntoShape' :: Idxs d -> Shape\ntoShape' = Shape . fmap fromIntegral . listIdxs \n\ntoShapeTensor :: Idxs d -> I '[Rank d]\ntoShapeTensor i = Tensor . O.constant (toShape' i) $ l\n where l = fmap fromIntegral . listIdxs $ i\n\n-- TODO use more efficient density list approach\nfill :: Elt e => Dims d -> (Idxs d -> e) -> Tensor d e\nfill d k = Tensor . O.constant (toShape d) $ Prelude.reverse l\n where l = foldIdxs d (\\i x -> k i : x) []\n \n\n{-\n\nfromIntegral' :: Int -> Int32\nfromIntegral' = fromIntegral\n\ntoList $ fill (dims @'[2,4]) (fromIntegral' . fromEnum)\n\n\nt1 = fill (dims @'[2,4]) $ const 1 . fromEnum\nt2 = fill (dims @'[4,2]) $ const 1 . fromEnum\n\nt2 = fill (dims @'[2,4]) ((+1) . fromIntegral' . fromEnum)\n\nf :: Elt e => Tensor '[2,4] e -> Tensor '[4,2] e\nf = transpose (dims @'[2,4]) (reversal (dims @'[2,4]))\n\nt1' = f t1\n\n\n\nfoo :: Dims d -> (Idxs d -> TVal) -> IO ()\nfoo d f = printTensor $ fill d f\n\n> d = dims @'[2,4]\n> foo d (minorToMajor d)\n[7,6,5,4,3,2,1,0]\n> foo d (transposeIdxs $ majorToMinor d)\n[7,5,3,1,6,4,2,0]\n\npred_sum_idxs :: forall ds. Dims ds -> Bool\npred_sum_idxs ds = foldIdxs ds (\\_ a -> a + 1) 0 == (product . listDims $ ds)\n\n-}\n\n{-\n\nSplits a tensor into sub tensors.\n\nIf num_or_size_splits is an integer type, then value is split along dimension axis into num_split smaller tensors. Requires that num_split evenly divides value.shape[axis].\n\nIf num_or_size_splits is not an integer type, it is presumed to be a Tensor size_splits, then splits value into len(size_splits) pieces. The shape of the i-th piece has the same size as the value except along dimension axis where the size is size_splits[i].\n\n\nslice:\nt = tf.constant([[[1, 1, 1], [2, 2, 2]],\n [[3, 3, 3], [4, 4, 4]],\n [[5, 5, 5], [6, 6, 6]]]) 3 x 2 x 3\ntf.slice(t, [1, 0, 0], [1, 1, 3]) # [[[3, 3, 3]]]\ntf.slice(t, [1, 0, 0], [1, 2, 3]) # [[[3, 3, 3],\n # [4, 4, 4]]]\ntf.slice(t, [1, 0, 0], [2, 1, 3]) # [[[3, 3, 3]],\n # [[5, 5, 5]]]\n\n-- want d' < d, \nslice :: Idxs d -> Dims d' -> Tensor d e -> Tensor d' e\n\nslice :: (TensorType t, OneOf '[Int32, Int64] index)\t=> Tensor v'1 t\t-> Tensor v'2 index\t-> Tensor v'3 index\t-> Tensor Build t\n\nIdxs d -> I '[Rank d]\n\n\ni = toEnum 6 :: Idxs '[3,2,3]\nj = toEnum 9 :: Idxs '[3,2,3]\n\ndiffIdxs (dims @'[3,2,3]) i j\n\nstepIdx (dims @'[3,2,3]) 3 i\ni = 1 :+ 0 :+ 0 :+ S :: Idxs '[3,2,3]\n\n\n-}\n\n\n\n\n{-\n\npack\n :: Elt e \n => Vector n (Tensor (x ++ y) e) -> Tensor (x ++ n :+ y) e\npack = undefined\n\npack0\n :: forall d e n. Elt e\n => KnownDims d\n => KnownDim n\n => Vector n (Tensor d e) -> Tensor (n :+ d) e\npack0 v = Tensor res\n where d = dims @d\n n = fromIntegral $ dimVal $ dim @n\n size = product $ listDims d\n res = S.create $ do\n mv <- M.new $ fromIntegral $ size * n\n flip N.imapM_ v $ \\i t -> \n let i' = idxToWord . idxFromFinite $ i\n off = fromIntegral $ i' * size\n v' = unTensor t\n act ix = M.write mv (off + fromEnum ix) $ v' S.! (fromEnum ix) -- could use a tensor op instead here\n in forMIdxs_ d act\n return mv\n\n-- TODO use http://hackage.haskell.org/package/reflection-2.1.4/docs/Data-Reflection.html#t:reifyNat\nunpack0 \n :: forall d e n. Elt e\n => KnownDims d\n => KnownNat n\n => Tensor (n :+ d) e -> Vector n (Tensor d e)\nunpack0 t = N.generate f\n where d = dims @d\n size = fromIntegral $ product $ listDims d\n f i = fill d $ \\ix -> \n let i' = fromIntegral $ F.getFinite i\n off = i' * size\n v = unTensor t \n in v S.! (off + fromEnum ix)\n-}\n\n{-\n\nsee example http://jeankossaifi.com/blog/unfolding.html\n\nt :: Vector 4 (Tensor '[2,2] Word)\nt = N.generate $ \\f -> \n let d = dims @'[2,2]\n i' = idxToWord . idxFromFinite $ f\n in fill d (const i') \n\nt' :: Tensor '[4,2,2] Word\nt' = pack0 t\n\nt'' :: Vector 4 (Tensor '[2,2] Word)\nt'' = unpack0 t'\n\ngenerate :: forall n a. KnownNat n => (Finite n -> a) -> Vector n a\n\nt :: Data.Vector.Sized.Vector 4 (Tensor '[2,2] Word)\nt = generate $ \\f -> \n let d = dims @'[2,2]\n i' = idxToWord . idxFromFinite $ f\n in fill d (const i') \n\nt' :: Tensor '[4,2,2] Word\nt' = pack0 t\nN.imapM_ :: Monad m => (Finite n -> a -> m b) -> Vector n a -> m ()\n\noverDim_ :: Monad m\n => Dims ds -- ^ Shape of a space\n -> (Idxs ds -> Int -> m ()) -- ^ Function to call on each dimension\n -> Int -- ^ Initial offset\n -> Int -- ^ Offset step\n -> m ()\n\nstack :: Dim n -> Vector n (Tensor (x ++ y) e) -> Tensor (x +: n :+ y) e\nunstack :: (KnownDims x, Elt e) => Dim n -> Tensor (x +: n :+ y) e -> Vector n (Tensor (x ++ y) e)\n-}\n\n\n", "meta": {"hexsha": "c980ead9e5a5ed652bfa7de6cc0fab025d486c12", "size": 14664, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "tensile-tensorflow/ref/src/Numeric/Tensile/Tensor/Internal.hs", "max_stars_repo_name": "cmk/tensile", "max_stars_repo_head_hexsha": "53c1e46c6b4e7ea8782600875ff3c063a1ce9639", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-25T06:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-15T04:30:24.000Z", "max_issues_repo_path": "tensile-tensorflow/ref/src/Numeric/Tensile/Tensor/Internal.hs", "max_issues_repo_name": "cmk/tensile", "max_issues_repo_head_hexsha": "53c1e46c6b4e7ea8782600875ff3c063a1ce9639", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tensile-tensorflow/ref/src/Numeric/Tensile/Tensor/Internal.hs", "max_forks_repo_name": "cmk/tensile", "max_forks_repo_head_hexsha": "53c1e46c6b4e7ea8782600875ff3c063a1ce9639", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0376237624, "max_line_length": 257, "alphanum_fraction": 0.5993589744, "num_tokens": 4726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.38387348904687624}} {"text": "{-# LANGUAGE CPP #-}\n#if __GLASGOW_HASKELL__ >= 708\n\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveGeneric #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n{-# OPTIONS_GHC -fno-warn-simplifiable-class-constraints #-}\n\n{- |\nModule : Internal.Static\nCopyright : (c) Alberto Ruiz 2006-14\nLicense : BSD3\nStability : provisional\n\n-}\n\nmodule Internal.Static where\n\n\nimport GHC.TypeLits\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra hiding (konst,size,R,C)\nimport Internal.Vector as D hiding (R,C)\nimport Internal.ST\nimport Control.DeepSeq\nimport Data.Proxy(Proxy)\nimport Foreign.Storable(Storable)\nimport Text.Printf\n\nimport Data.Binary\nimport GHC.Generics (Generic)\nimport Data.Proxy (Proxy(..))\n\n--------------------------------------------------------------------------------\n\ntype ℝ = Float\ntype ℂ = Complex Float\n\nnewtype Dim (n :: Nat) t = Dim t\n deriving (Show, Generic)\n\ninstance (KnownNat n, Binary a) => Binary (Dim n a) where\n get = do\n k <- get\n let n = natVal (Proxy :: Proxy n)\n if n == k\n then Dim <$> get\n else fail (\"Expected dimension \" ++ (show n) ++ \", but found dimension \" ++ (show k))\n\n put (Dim x) = do\n put (natVal (Proxy :: Proxy n))\n put x\n\nlift1F\n :: (c t -> c t)\n -> Dim n (c t) -> Dim n (c t)\nlift1F f (Dim v) = Dim (f v)\n\nlift2F\n :: (c t -> c t -> c t)\n -> Dim n (c t) -> Dim n (c t) -> Dim n (c t)\nlift2F f (Dim u) (Dim v) = Dim (f u v)\n\ninstance NFData t => NFData (Dim n t) where\n rnf (Dim (force -> !_)) = ()\n\n--------------------------------------------------------------------------------\n\nnewtype R n = R (Dim n (Vector ℝ))\n deriving (Num,Fractional,Floating,Generic,Binary)\n\nnewtype C n = C (Dim n (Vector ℂ))\n deriving (Num,Fractional,Floating,Generic)\n\nnewtype L m n = L (Dim m (Dim n (Matrix ℝ)))\n deriving (Generic, Binary)\n\nnewtype M m n = M (Dim m (Dim n (Matrix ℂ)))\n deriving (Generic)\n\nmkR :: Vector ℝ -> R n\nmkR = R . Dim\n\nmkC :: Vector ℂ -> C n\nmkC = C . Dim\n\nmkL :: Matrix ℝ -> L m n\nmkL x = L (Dim (Dim x))\n\nmkM :: Matrix ℂ -> M m n\nmkM x = M (Dim (Dim x))\n\ninstance NFData (R n) where\n rnf (R (force -> !_)) = ()\n\ninstance NFData (C n) where\n rnf (C (force -> !_)) = ()\n\ninstance NFData (L n m) where\n rnf (L (force -> !_)) = ()\n\ninstance NFData (M n m) where\n rnf (M (force -> !_)) = ()\n\n--------------------------------------------------------------------------------\n\ntype V n t = Dim n (Vector t)\n\nud :: Dim n (Vector t) -> Vector t\nud (Dim v) = v\n\nmkV :: forall (n :: Nat) t . t -> Dim n t\nmkV = Dim\n\n\nvconcat :: forall n m t . (KnownNat n, KnownNat m, Numeric t)\n => V n t -> V m t -> V (n+m) t\n(ud -> u) `vconcat` (ud -> v) = mkV (vjoin [u', v'])\n where\n du = fromIntegral . natVal $ (undefined :: Proxy n)\n dv = fromIntegral . natVal $ (undefined :: Proxy m)\n u' | du /= 1 && LA.size u == 1 = LA.konst (u D.@> 0) du\n | otherwise = u\n v' | dv /= 1 && LA.size v == 1 = LA.konst (v D.@> 0) dv\n | otherwise = v\n\n\ngvec2 :: Storable t => t -> t -> V 2 t\ngvec2 a b = mkV $ runSTVector $ do\n v <- newUndefinedVector 2\n writeVector v 0 a\n writeVector v 1 b\n return v\n\ngvec3 :: Storable t => t -> t -> t -> V 3 t\ngvec3 a b c = mkV $ runSTVector $ do\n v <- newUndefinedVector 3\n writeVector v 0 a\n writeVector v 1 b\n writeVector v 2 c\n return v\n\n\ngvec4 :: Storable t => t -> t -> t -> t -> V 4 t\ngvec4 a b c d = mkV $ runSTVector $ do\n v <- newUndefinedVector 4\n writeVector v 0 a\n writeVector v 1 b\n writeVector v 2 c\n writeVector v 3 d\n return v\n\n\ngvect :: forall n t . (Show t, KnownNat n, Numeric t) => String -> [t] -> V n t\ngvect st xs'\n | ok = mkV v\n | not (null rest) && null (tail rest) = abort (show xs')\n | not (null rest) = abort (init (show (xs++take 1 rest))++\", ... ]\")\n | otherwise = abort (show xs)\n where\n (xs,rest) = splitAt d xs'\n ok = LA.size v == d && null rest\n v = LA.fromList xs\n d = fromIntegral . natVal $ (undefined :: Proxy n)\n abort info = error $ st++\" \"++show d++\" can't be created from elements \"++info\n\n\n--------------------------------------------------------------------------------\n\ntype GM m n t = Dim m (Dim n (Matrix t))\n\n\ngmat :: forall m n t . (Show t, KnownNat m, KnownNat n, Numeric t) => String -> [t] -> GM m n t\ngmat st xs'\n | ok = Dim (Dim x)\n | not (null rest) && null (tail rest) = abort (show xs')\n | not (null rest) = abort (init (show (xs++take 1 rest))++\", ... ]\")\n | otherwise = abort (show xs)\n where\n (xs,rest) = splitAt (m'*n') xs'\n v = LA.fromList xs\n x = reshape n' v\n ok = null rest && ((n' == 0 && dim v == 0) || n'> 0 && (rem (LA.size v) n' == 0) && LA.size x == (m',n'))\n m' = fromIntegral . natVal $ (undefined :: Proxy m) :: Int\n n' = fromIntegral . natVal $ (undefined :: Proxy n) :: Int\n abort info = error $ st ++\" \"++show m' ++ \" \" ++ show n'++\" can't be created from elements \" ++ info\n\n--------------------------------------------------------------------------------\n\nclass Num t => Sized t s d | s -> t, s -> d\n where\n konst :: t -> s\n unwrap :: s -> d t\n fromList :: [t] -> s\n extract :: s -> d t\n create :: d t -> Maybe s\n size :: s -> IndexOf d\n\nsingleV v = LA.size v == 1\nsingleM m = rows m == 1 && cols m == 1\n\n\ninstance KnownNat n => Sized ℂ (C n) Vector\n where\n size _ = fromIntegral . natVal $ (undefined :: Proxy n)\n konst x = mkC (LA.scalar x)\n unwrap (C (Dim v)) = v\n fromList xs = C (gvect \"C\" xs)\n extract s@(unwrap -> v)\n | singleV v = LA.konst (v!0) (size s)\n | otherwise = v\n create v\n | LA.size v == size r = Just r\n | otherwise = Nothing\n where\n r = mkC v :: C n\n\n\ninstance KnownNat n => Sized ℝ (R n) Vector\n where\n size _ = fromIntegral . natVal $ (undefined :: Proxy n)\n konst x = mkR (LA.scalar x)\n unwrap (R (Dim v)) = v\n fromList xs = R (gvect \"R\" xs)\n extract s@(unwrap -> v)\n | singleV v = LA.konst (v!0) (size s)\n | otherwise = v\n create v\n | LA.size v == size r = Just r\n | otherwise = Nothing\n where\n r = mkR v :: R n\n\n\ninstance (KnownNat m, KnownNat n) => Sized ℝ (L m n) Matrix\n where\n size _ = ((fromIntegral . natVal) (undefined :: Proxy m)\n ,(fromIntegral . natVal) (undefined :: Proxy n))\n konst x = mkL (LA.scalar x)\n fromList xs = L (gmat \"L\" xs)\n unwrap (L (Dim (Dim m))) = m\n extract (isDiag -> Just (z,y,(m',n'))) = diagRect z y m' n'\n extract s@(unwrap -> a)\n | singleM a = LA.konst (a `atIndex` (0,0)) (size s)\n | otherwise = a\n create x\n | LA.size x == size r = Just r\n | otherwise = Nothing\n where\n r = mkL x :: L m n\n\n\ninstance (KnownNat m, KnownNat n) => Sized ℂ (M m n) Matrix\n where\n size _ = ((fromIntegral . natVal) (undefined :: Proxy m)\n ,(fromIntegral . natVal) (undefined :: Proxy n))\n konst x = mkM (LA.scalar x)\n fromList xs = M (gmat \"M\" xs)\n unwrap (M (Dim (Dim m))) = m\n extract (isDiagC -> Just (z,y,(m',n'))) = diagRect z y m' n'\n extract s@(unwrap -> a)\n | singleM a = LA.konst (a `atIndex` (0,0)) (size s)\n | otherwise = a\n create x\n | LA.size x == size r = Just r\n | otherwise = Nothing\n where\n r = mkM x :: M m n\n\n--------------------------------------------------------------------------------\n\ninstance (KnownNat n, KnownNat m) => Transposable (L m n) (L n m)\n where\n tr a@(isDiag -> Just _) = mkL (extract a)\n tr (extract -> a) = mkL (tr a)\n tr' = tr\n\ninstance (KnownNat n, KnownNat m) => Transposable (M m n) (M n m)\n where\n tr a@(isDiagC -> Just _) = mkM (extract a)\n tr (extract -> a) = mkM (tr a)\n tr' a@(isDiagC -> Just _) = mkM (extract a)\n tr' (extract -> a) = mkM (tr' a)\n\n--------------------------------------------------------------------------------\n\nisDiag :: forall m n . (KnownNat m, KnownNat n) => L m n -> Maybe (ℝ, Vector ℝ, (Int,Int))\nisDiag (L x) = isDiagg x\n\nisDiagC :: forall m n . (KnownNat m, KnownNat n) => M m n -> Maybe (ℂ, Vector ℂ, (Int,Int))\nisDiagC (M x) = isDiagg x\n\n\nisDiagg :: forall m n t . (Numeric t, KnownNat m, KnownNat n) => GM m n t -> Maybe (t, Vector t, (Int,Int))\nisDiagg (Dim (Dim x))\n | singleM x = Nothing\n | rows x == 1 && m' > 1 || cols x == 1 && n' > 1 = Just (z,yz,(m',n'))\n | otherwise = Nothing\n where\n m' = fromIntegral . natVal $ (undefined :: Proxy m) :: Int\n n' = fromIntegral . natVal $ (undefined :: Proxy n) :: Int\n v = flatten x\n z = v `atIndex` 0\n y = subVector 1 (LA.size v-1) v\n ny = LA.size y\n zeros = LA.konst 0 (max 0 (min m' n' - ny))\n yz = vjoin [y,zeros]\n\n--------------------------------------------------------------------------------\n\ninstance KnownNat n => Show (R n)\n where\n show s@(R (Dim v))\n | singleV v = \"(\" ++ show (v!0) ++ \" :: R \" ++ show d ++ \")\"\n | otherwise = \"(vector \" ++ show v ++ \" :: R \" ++ show d ++\")\"\n where\n d = size s\n\ninstance KnownNat n => Show (C n)\n where\n show s@(C (Dim v))\n | singleV v = \"(\" ++ show (v!0) ++ \" :: C \" ++ show d ++ \")\"\n | otherwise = \"(vector \" ++ show v ++ \" :: C \" ++ show d ++\")\"\n where\n d = size s\n\ninstance (KnownNat m, KnownNat n) => Show (L m n)\n where\n show (isDiag -> Just (z,y,(m',n'))) = printf \"(diag %s %s :: L %d %d)\" (show z) (show y) m' n'\n show s@(L (Dim (Dim x)))\n | singleM x = printf \"(%s :: L %d %d)\" (show (x `atIndex` (0,0))) m' n'\n | otherwise = \"(matrix\" ++ dropWhile (/='\\n') (show x) ++ \" :: L \" ++ show m' ++ \" \" ++ show n' ++ \")\"\n where\n (m',n') = size s\n\ninstance (KnownNat m, KnownNat n) => Show (M m n)\n where\n show (isDiagC -> Just (z,y,(m',n'))) = printf \"(diag %s %s :: M %d %d)\" (show z) (show y) m' n'\n show s@(M (Dim (Dim x)))\n | singleM x = printf \"(%s :: M %d %d)\" (show (x `atIndex` (0,0))) m' n'\n | otherwise = \"(matrix\" ++ dropWhile (/='\\n') (show x) ++ \" :: M \" ++ show m' ++ \" \" ++ show n' ++ \")\"\n where\n (m',n') = size s\n\n--------------------------------------------------------------------------------\n\ninstance (Num (Vector t), Numeric t )=> Num (Dim n (Vector t))\n where\n (+) = lift2F (+)\n (*) = lift2F (*)\n (-) = lift2F (-)\n abs = lift1F abs\n signum = lift1F signum\n negate = lift1F negate\n fromInteger x = Dim (fromInteger x)\n\ninstance (Num (Vector t), Num (Matrix t), Fractional t, Numeric t) => Fractional (Dim n (Vector t))\n where\n fromRational x = Dim (fromRational x)\n (/) = lift2F (/)\n\ninstance (Fractional t, Floating (Vector t), Numeric t) => Floating (Dim n (Vector t)) where\n sin = lift1F sin\n cos = lift1F cos\n tan = lift1F tan\n asin = lift1F asin\n acos = lift1F acos\n atan = lift1F atan\n sinh = lift1F sinh\n cosh = lift1F cosh\n tanh = lift1F tanh\n asinh = lift1F asinh\n acosh = lift1F acosh\n atanh = lift1F atanh\n exp = lift1F exp\n log = lift1F log\n sqrt = lift1F sqrt\n (**) = lift2F (**)\n pi = Dim pi\n\n\ninstance (Num (Matrix t), Numeric t) => Num (Dim m (Dim n (Matrix t)))\n where\n (+) = (lift2F . lift2F) (+)\n (*) = (lift2F . lift2F) (*)\n (-) = (lift2F . lift2F) (-)\n abs = (lift1F . lift1F) abs\n signum = (lift1F . lift1F) signum\n negate = (lift1F . lift1F) negate\n fromInteger x = Dim (Dim (fromInteger x))\n\ninstance (Num (Vector t), Num (Matrix t), Fractional t, Numeric t) => Fractional (Dim m (Dim n (Matrix t)))\n where\n fromRational x = Dim (Dim (fromRational x))\n (/) = (lift2F.lift2F) (/)\n\ninstance (Num (Vector t), Floating (Matrix t), Fractional t, Numeric t) => Floating (Dim m (Dim n (Matrix t))) where\n sin = (lift1F . lift1F) sin\n cos = (lift1F . lift1F) cos\n tan = (lift1F . lift1F) tan\n asin = (lift1F . lift1F) asin\n acos = (lift1F . lift1F) acos\n atan = (lift1F . lift1F) atan\n sinh = (lift1F . lift1F) sinh\n cosh = (lift1F . lift1F) cosh\n tanh = (lift1F . lift1F) tanh\n asinh = (lift1F . lift1F) asinh\n acosh = (lift1F . lift1F) acosh\n atanh = (lift1F . lift1F) atanh\n exp = (lift1F . lift1F) exp\n log = (lift1F . lift1F) log\n sqrt = (lift1F . lift1F) sqrt\n (**) = (lift2F . lift2F) (**)\n pi = Dim (Dim pi)\n\n--------------------------------------------------------------------------------\n\n\nadaptDiag f a@(isDiag -> Just _) b | isFull b = f (mkL (extract a)) b\nadaptDiag f a b@(isDiag -> Just _) | isFull a = f a (mkL (extract b))\nadaptDiag f a b = f a b\n\nisFull m = isDiag m == Nothing && not (singleM (unwrap m))\n\n\nlift1L f (L v) = L (f v)\nlift2L f (L a) (L b) = L (f a b)\nlift2LD f = adaptDiag (lift2L f)\n\n\ninstance (KnownNat n, KnownNat m) => Num (L n m)\n where\n (+) = lift2LD (+)\n (*) = lift2LD (*)\n (-) = lift2LD (-)\n abs = lift1L abs\n signum = lift1L signum\n negate = lift1L negate\n fromInteger = L . Dim . Dim . fromInteger\n\ninstance (KnownNat n, KnownNat m) => Fractional (L n m)\n where\n fromRational = L . Dim . Dim . fromRational\n (/) = lift2LD (/)\n\ninstance (KnownNat n, KnownNat m) => Floating (L n m) where\n sin = lift1L sin\n cos = lift1L cos\n tan = lift1L tan\n asin = lift1L asin\n acos = lift1L acos\n atan = lift1L atan\n sinh = lift1L sinh\n cosh = lift1L cosh\n tanh = lift1L tanh\n asinh = lift1L asinh\n acosh = lift1L acosh\n atanh = lift1L atanh\n exp = lift1L exp\n log = lift1L log\n sqrt = lift1L sqrt\n (**) = lift2LD (**)\n pi = konst pi\n\n--------------------------------------------------------------------------------\n\nadaptDiagC f a@(isDiagC -> Just _) b | isFullC b = f (mkM (extract a)) b\nadaptDiagC f a b@(isDiagC -> Just _) | isFullC a = f a (mkM (extract b))\nadaptDiagC f a b = f a b\n\nisFullC m = isDiagC m == Nothing && not (singleM (unwrap m))\n\nlift1M f (M v) = M (f v)\nlift2M f (M a) (M b) = M (f a b)\nlift2MD f = adaptDiagC (lift2M f)\n\ninstance (KnownNat n, KnownNat m) => Num (M n m)\n where\n (+) = lift2MD (+)\n (*) = lift2MD (*)\n (-) = lift2MD (-)\n abs = lift1M abs\n signum = lift1M signum\n negate = lift1M negate\n fromInteger = M . Dim . Dim . fromInteger\n\ninstance (KnownNat n, KnownNat m) => Fractional (M n m)\n where\n fromRational = M . Dim . Dim . fromRational\n (/) = lift2MD (/)\n\ninstance (KnownNat n, KnownNat m) => Floating (M n m) where\n sin = lift1M sin\n cos = lift1M cos\n tan = lift1M tan\n asin = lift1M asin\n acos = lift1M acos\n atan = lift1M atan\n sinh = lift1M sinh\n cosh = lift1M cosh\n tanh = lift1M tanh\n asinh = lift1M asinh\n acosh = lift1M acosh\n atanh = lift1M atanh\n exp = lift1M exp\n log = lift1M log\n sqrt = lift1M sqrt\n (**) = lift2MD (**)\n pi = M pi\n\ninstance Additive (R n) where\n add = (+)\n\ninstance Additive (C n) where\n add = (+)\n\ninstance (KnownNat m, KnownNat n) => Additive (L m n) where\n add = (+)\n\ninstance (KnownNat m, KnownNat n) => Additive (M m n) where\n add = (+)\n\n--------------------------------------------------------------------------------\n\n\nclass Disp t\n where\n disp :: Int -> t -> IO ()\n\n\ninstance (KnownNat m, KnownNat n) => Disp (L m n)\n where\n disp n x = do\n let a = extract x\n let su = LA.dispf n a\n printf \"L %d %d\" (rows a) (cols a) >> putStr (dropWhile (/='\\n') $ su)\n\ninstance (KnownNat m, KnownNat n) => Disp (M m n)\n where\n disp n x = do\n let a = extract x\n let su = LA.dispcf n a\n printf \"M %d %d\" (rows a) (cols a) >> putStr (dropWhile (/='\\n') $ su)\n\n\ninstance KnownNat n => Disp (R n)\n where\n disp n v = do\n let su = LA.dispf n (asRow $ extract v)\n putStr \"R \" >> putStr (tail . dropWhile (/='x') $ su)\n\ninstance KnownNat n => Disp (C n)\n where\n disp n v = do\n let su = LA.dispcf n (asRow $ extract v)\n putStr \"C \" >> putStr (tail . dropWhile (/='x') $ su)\n\n--------------------------------------------------------------------------------\n\noverMatL' :: (KnownNat m, KnownNat n)\n => (LA.Matrix ℝ -> LA.Matrix ℝ) -> L m n -> L m n\noverMatL' f = mkL . f . unwrap\n{-# INLINE overMatL' #-}\n\noverMatM' :: (KnownNat m, KnownNat n)\n => (LA.Matrix ℂ -> LA.Matrix ℂ) -> M m n -> M m n\noverMatM' f = mkM . f . unwrap\n{-# INLINE overMatM' #-}\n\n\n#else\n\nmodule Numeric.LinearAlgebra.Static.Internal where\n\n#endif\n\n", "meta": {"hexsha": "b76bd72243236f47af44b96a7f43a0ddeee5c862", "size": 16798, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Internal/Static.hs", "max_stars_repo_name": "schnecki/hmatrix-float", "max_stars_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Internal/Static.hs", "max_issues_repo_name": "schnecki/hmatrix-float", "max_issues_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Internal/Static.hs", "max_forks_repo_name": "schnecki/hmatrix-float", "max_forks_repo_head_hexsha": "20ad30db8edb97ce735d8218937f9ded878e3217", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-12T02:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T02:51:35.000Z", "avg_line_length": 28.519524618, "max_line_length": 116, "alphanum_fraction": 0.5179783308, "num_tokens": 5572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3832965520328217}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PolyKinds #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule Grenade.Recurrent.Layers.BasicRecurrent (\n BasicRecurrent (..)\n ) where\n\n\nimport Data.Proxy\nimport Data.Singletons.TypeLits hiding (natVal)\n\nimport Numeric.LinearAlgebra.Static\n\nimport GHC.TypeLits\n\nimport Grenade.Core\nimport Grenade.Recurrent.Core\n\ndata BasicRecurrent :: Nat -- Input layer size\n -> Nat -- Output layer size\n -> * where\n BasicRecurrent :: ( KnownNat input\n , KnownNat output\n , KnownNat matrixCols\n , matrixCols ~ (input + output))\n => !(R output) -- Bias neuron weights\n -> !(R output) -- Bias neuron momentum\n -> !(L output matrixCols) -- Activation\n -> !(L output matrixCols) -- Momentum\n -> BasicRecurrent input output\n\ndata BasicRecurrent' :: Nat -- Input layer size\n -> Nat -- Output layer size\n -> * where\n BasicRecurrent' :: ( KnownNat input\n , KnownNat output\n , KnownNat matrixCols\n , matrixCols ~ (input + output))\n => !(R output) -- Bias neuron gradients\n -> !(L output matrixCols)\n -> BasicRecurrent' input output\n\ninstance Show (BasicRecurrent i o) where\n show BasicRecurrent {} = \"BasicRecurrent\"\n\ninstance (KnownNat i, KnownNat o, KnownNat (i + o)) => UpdateLayer (BasicRecurrent i o) where\n type Gradient (BasicRecurrent i o) = (BasicRecurrent' i o)\n\n runUpdate LearningParameters {..} (BasicRecurrent oldBias oldBiasMomentum oldActivations oldMomentum) (BasicRecurrent' biasGradient activationGradient) =\n let newBiasMomentum = konst learningMomentum * oldBiasMomentum - konst learningRate * biasGradient\n newBias = oldBias + newBiasMomentum\n newMomentum = konst learningMomentum * oldMomentum - konst learningRate * activationGradient\n regulariser = konst (learningRegulariser * learningRate) * oldActivations\n newActivations = oldActivations + newMomentum - regulariser\n in BasicRecurrent newBias newBiasMomentum newActivations newMomentum\n\ninstance (KnownNat i, KnownNat o, KnownNat x, KnownNat (x*o), x ~ (i+o)) => RandomLayer (BasicRecurrent i o) where\n createRandomWith m gen = do\n wB <- getRandomVector i o m gen\n wN <- getRandomMatrix i o m gen\n let bm = konst 0\n mm = konst 0\n return $ BasicRecurrent wB bm wN mm\n where i = natVal (Proxy :: Proxy i)\n o = natVal (Proxy :: Proxy o)\n\n\ninstance (KnownNat i, KnownNat o, KnownNat (i + o), i <= (i + o), o ~ ((i + o) - i)) => RecurrentUpdateLayer (BasicRecurrent i o) where\n type RecurrentShape (BasicRecurrent i o) = S ('D1 o)\n\ninstance (KnownNat i, KnownNat o, KnownNat (i + o), i <= (i + o), o ~ ((i + o) - i)) => RecurrentLayer (BasicRecurrent i o) ('D1 i) ('D1 o) where\n\n type RecTape (BasicRecurrent i o) ('D1 i) ('D1 o) = (S ('D1 o), S ('D1 i))\n -- Do a matrix vector multiplication and return the result.\n runRecurrentForwards (BasicRecurrent wB _ wN _) (S1D lastOutput) (S1D thisInput) =\n let thisOutput = S1D $ wB + wN #> (thisInput # lastOutput)\n in ((S1D lastOutput, S1D thisInput), thisOutput, thisOutput)\n\n -- Run a backpropogation step for a full connected layer.\n runRecurrentBackwards (BasicRecurrent _ _ wN _) (S1D lastOutput, S1D thisInput) (S1D dRec) (S1D dEdy) =\n let biasGradient = (dRec + dEdy)\n layerGrad = (dRec + dEdy) `outer` (thisInput # lastOutput)\n -- calcluate derivatives for next step\n (backGrad, recGrad) = split $ tr wN #> (dRec + dEdy)\n in (BasicRecurrent' biasGradient layerGrad, S1D recGrad, S1D backGrad)\n\n\n-------------------- GNum instances --------------------\n\ninstance (KnownNat i,KnownNat o,KnownNat (i+o)) => GNum (BasicRecurrent i o) where\n n |* (BasicRecurrent wB mB a nM) = (BasicRecurrent (fromRational n * wB) mB a nM)\n (BasicRecurrent wB mB a nM) |+ (BasicRecurrent wB2 mB2 a2 nM2) = (BasicRecurrent (0.5 * (wB + wB2)) (0.5* (mB+mB2)) (0.5 * (a+a2)) (0.5 * (nM + nM2)))\n gFromRational r = (BasicRecurrent (fromRational r) 0 (fromRational r) 0)\n\n", "meta": {"hexsha": "c4f173ab752185ba77f6c7164213fd4c09250d77", "size": 4712, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Recurrent/Layers/BasicRecurrent.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/Recurrent/Layers/BasicRecurrent.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/Recurrent/Layers/BasicRecurrent.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": 44.8761904762, "max_line_length": 155, "alphanum_fraction": 0.6099320883, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.38329365313071256}} {"text": "{-# language TypeSynonymInstances #-}\n{-# language LiberalTypeSynonyms #-}\n\nmodule FrequencyResponse \n (Analyzer (..),\n AnalyzerAcyclic (..),\n Spectrum (..),\n SpecLin (..),\n SpecWide ,\n getResponse,\n getResponseLin,\n getResponseAcyclic)\n\nwhere\n\nimport CLaSH.Prelude (Default(..))\nimport Prelude\nimport CLaSH.Signal.MultiSignal\nimport Data.Complex as C\nimport Data.Maybe\nimport Control.Applicative\nimport Data.Map.Strict as Map\n\n\n-- | Type representing input and output signal in circuitry\n-- p of kind (* -> *) represents underlaying Signal of type Prependable (ZipList for example) \n-- s is type of Spectrum\ndata Analyzer p s = Analyzer {unAnalyzer :: ([Maybe (s -> s)] , p s)}\n\n\ninstance (Functor p, Prependable p) => Prependable (Analyzer p) where\n prepend a da = Analyzer (Nothing : f , (prepend a $ fmap fx d))\n where\n (f,d) = unAnalyzer da\n fx = fromMaybe id $ foldr1 (<|>) f\n\ninstance (Applicative p,Num n) => Num (Analyzer p n) where\n (+) = liftA2FA (+)\n (-) = liftA2FA (-)\n (*) = liftA2FA (*)\n fromInteger = makeAnalyzer . fromInteger\n negate = liftA1FA negate\n abs = liftA1FA abs\n signum = liftA1FA signum\n\ninstance (Applicative p,Fractional n) => Fractional (Analyzer p n) where\n (/) = liftA2FA (/)\n fromRational = makeAnalyzer . fromRational\n\nliftA2FA op da db = Analyzer (zipWith (<|>) fa fb, liftA2 op a b) where\n (fa,a) = unAnalyzer da\n (fb,b) = unAnalyzer db\n\nliftA1FA op f = Analyzer (repeat Nothing , fmap op s) where\n (_,s) = unAnalyzer f\n\nmakeAnalyzer s = Analyzer ( repeat Nothing , pure s )\n{- inline liftA2FA, liftA1FA-}\n \n-- | spectrum is result of frequency mixing two spectrums\n-- n represents type represented as harmonics (Int or better, Rational)\n-- and a is type of complex number (frequently Double)\ndata Spectrum n a = Spectrum {getSpectrum :: Map.Map n (Complex a)}\n\ninstance (Ord n,Num n,Default a,RealFloat a) => Default (Spectrum n a) where\n def = dcSpectrum def\n\ninstance (Ord n,Num n,RealFloat a) => Num (Spectrum n a) where\n (+) = dotMergeSpec (+)\n (-) = dotMergeSpec (-)\n (*) = mixSpectrum\n negate = fmapSpec negate\n abs = error \"no abs function for spectrum available\"\n signum = error \"no sig num function for spectrum available\"\n fromInteger = dcSpectrum . fromInteger\n\ninstance (Show n, Show a, Ord n,Num n,Fractional a,RealFloat a) => Fractional (Spectrum n a) where\n (/) = spectrumDiv\n fromRational = dcSpectrum . fromRational\n\ndotMergeSpec op (Spectrum sa) (Spectrum sb) = Spectrum $ (Map.unionWith op) sa sb\nfmapSpec f = Spectrum . fmap f . getSpectrum\nconstSpectrum freq a = Spectrum $ Map.singleton freq (a :+ 0 )\ndcSpectrum a = constSpectrum 0 a\n\nmixSpectrum (Spectrum sa) (Spectrum sb) = Spectrum \n $ Map.fromListWith (+) \n $ concat [mixFeq a b | a <- Map.toList sa , b <- Map.toList sb]\n\nmixFeq (fa,pa) (fb,pb)\n | fa > fb = mixFeqSorted (fb,pb) (fa,pa)\n | True = mixFeqSorted (fa,pa) (fb,pb)\n\nmixFeqSorted (0,pa) (fb,pb) = [(fb,pa*pb)]\nmixFeqSorted (fa,pa) (fb,pb) = [(fb - fa,r1),(fb+fa,r2)] where\n (ma,pha) = polar pa\n (mb,phb) = polar pb\n k = ma * mb / 2\n r1 \n | fa == fb = mkPolar (k * sin (phb - pha + pi/2)) 0\n | otherwise = mkPolar k (phb - pha + pi/2)\n r2 = mkPolar ((-1)*k) (phb + pha + pi/2)\n\ndelaySpec ph (Spectrum s) = Spectrum $ Map.mapWithKey f s where\n f 0 a = a\n f k a = a * mkPolar 1 (fromRational k * ph)\n\nspectrumDiv (Spectrum a) sb = Spectrum (fmap (/ dc) a) where\n dc = getDcOrError sb\n \ngetDcOrError (Spectrum a) =\n case toList a of\n ((0,dc):[]) -> dc\n s -> error (\"spectrum is not dc, but\" ++ show s )\n\nmakeDcSig :: (Applicative p, Num n, Num a) => a -> Analyzer p (Spectrum n a)\nmakeDcSig = makeAnalyzer . dcSpectrum\n\n\n-- | spectrum for linear system, faster version of Spectrum\n-- underlaying type is tuple insted of Map \nnewtype SpecLin = SpecLin {getSpecLin :: (Double,Complex Double)}\n\ninstance Default SpecLin where\n def = SpecLin (def,def :+ def)\n\ninstance Num SpecLin where\n (+) = dotMergeSpecLin (+)\n (-) = dotMergeSpecLin (-)\n (*) = mixSpecLin\n negate = fmapSpecLin negate\n abs = error \"no abs function for spectrum available\"\n signum = error \"no signum function for spectrum available\"\n fromInteger = dcSpecLin . fromInteger\n\ninstance Fractional SpecLin where\n (/) = undefined -- dcSpecLin\n fromRational = dcSpecLin . fromRational\n\ndotMergeSpecLin op (SpecLin (dcA,acA)) (SpecLin (dcB,acB)) = SpecLin (op dcA dcB , acr) where\n acr = op (realPart acA) (realPart acB) :+ op (imagPart acA) (imagPart acB)\n\nmixSpecLin (SpecLin (dcA,acA)) (SpecLin (dcB,acB)) \n | (acA /= 0 ) && (acB /= 0) = error \"can not mix two linear spectrum\"\n | otherwise = SpecLin (dcr , acr) where\n dcr = dcA * dcB\n acr = fmap (* dcA) acB + fmap (* dcB) acA\n\ndcSpecLin dc = SpecLin (dc,0) \n\nfmapSpecLin f (SpecLin (dc,ac)) = SpecLin (f dc,fmap f ac)\n\ndelayLinSpec ph (SpecLin (dc,ac)) = SpecLin (dc,ac * mkPolar 1 ph)\n-- end of SpecLin\n\n-- for acyclic circuits we can implement faster version of Prependable\n-- It has nice property that first value of output is correct. \ndata AnalyzerAcyclic s = AnalyzerAcyclic {unAnalyzerAcyclic :: (Maybe (s -> s), s)}\n\n-- Prependable instance has funny laws (no laws?)\n-- it does not follow list isomorphism, because it is single value\ninstance Prependable AnalyzerAcyclic where\n prepend _ da = AnalyzerAcyclic (f , fx d)\n where\n (f,d) = unAnalyzerAcyclic da\n fx = fromMaybe id f\n\ninstance (Num n) => Num (AnalyzerAcyclic n) where\n (+) = opAcyclic (+)\n (-) = opAcyclic (-)\n (*) = opAcyclic (*)\n fromInteger = pureAcyclic . fromInteger\n negate = liftAcyclic negate\n abs = liftAcyclic abs\n signum = liftAcyclic signum\n\ninstance (Fractional n) => Fractional (AnalyzerAcyclic n) where\n (/) = opAcyclic (/)\n fromRational = pureAcyclic . fromRational\n\npureAcyclic n = AnalyzerAcyclic (Nothing,n)\nopAcyclic op (AnalyzerAcyclic (fa,a)) (AnalyzerAcyclic (fb,b)) = (AnalyzerAcyclic (fa <|> fb ,op a b))\nliftAcyclic f (AnalyzerAcyclic (fa,a)) = (AnalyzerAcyclic (fa,f a))\n\n-- end of AnalyzerAcyclic\n\ntype SpecWide = Spectrum Rational Double\n\n-- | run analysis for both acyclic\\/cyclic and both linear\\/nonlinear circuits\n-- It is required to skip first N resulting values\n-- where N represent delay of circuitry (approx total number of registers)\ngetResponse :: (Analyzer ZipList SpecWide -> Analyzer ZipList SpecWide) -- ^ circuitry\n -> Double -- ^ phase in radians that represents Nyquist frequency. (phase pi ≡ 1.0 of sampling frequency)\n -> [Spectrum Rational Double] -- ^ response as stream\ngetResponse f ph = getZipList $ snd $ unAnalyzer $ f $ Analyzer ([ Just (delaySpec ph)] , pure (constSpectrum 1 1))\n\n-- | run analysis for both acyclic\\/cyclic and only linear circuits\n-- faster version of getResponse for acyclic linear ciruits\ngetResponseLin :: (Analyzer ZipList SpecLin -> Analyzer ZipList SpecLin) -- ^ circuitry\n -> Double -- ^ phase in radians that represents Nyquist frequency. (phase pi ≡ 1.0 of sampling frequency)\n -> [SpecLin] -- ^ response as stream\ngetResponseLin f ph = getZipList $ snd $ unAnalyzer $ f $ Analyzer ([Just (delayLinSpec ph)] , pure (SpecLin (0,1 :+ 0)))\n\n\n\n-- | run analysis both linear\\/nonlinear and only acyclic circuit\n-- calculate response of acyclic circuit\ngetResponseAcyclic :: (AnalyzerAcyclic SpecWide -> AnalyzerAcyclic SpecWide) -- ^ circuitry\n -> Double -- ^ phase in radians that represents Nyquist frequency. (phase pi ≡ 1.0 of sampling frequency)\n -> Spectrum Rational Double -- ^ response as stream\ngetResponseAcyclic f ph = snd $ unAnalyzerAcyclic $ f $ AnalyzerAcyclic (Just (delaySpec ph) ,constSpectrum 1 1)\n", "meta": {"hexsha": "335536d247ebef5f9a60be82b5a01903b0141941", "size": 7826, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FrequencyResponse.hs", "max_stars_repo_name": "ra1u/frequency-response", "max_stars_repo_head_hexsha": "d044223c2e1e90bb40e4245d0edcac5fb16534f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FrequencyResponse.hs", "max_issues_repo_name": "ra1u/frequency-response", "max_issues_repo_head_hexsha": "d044223c2e1e90bb40e4245d0edcac5fb16534f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FrequencyResponse.hs", "max_forks_repo_name": "ra1u/frequency-response", "max_forks_repo_head_hexsha": "d044223c2e1e90bb40e4245d0edcac5fb16534f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9150943396, "max_line_length": 127, "alphanum_fraction": 0.6680296448, "num_tokens": 2320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.38216109259379516}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nmodule GrenadeExtras.Zip (\n Zip (..),\n) where\n\nimport Data.Serialize (Serialize, put, get)\n\n--import Data.Singletons\nimport GHC.TypeLits\n\nimport Grenade.Core (UpdateLayer, Layer, Shape(D1), S(S1D), Gradient,\n runForwards, runBackwards, runUpdate, createRandom, Tape)\nimport GrenadeExtras.GradNorm (GradNorm, normSquared)\n\nimport Numeric.LinearAlgebra.Static ((#), split, R) -- row, (===), splitRows, unrow\n\ndata Zip :: Shape -> Shape -> * -> Shape -> Shape -> * -> * where\n Zip :: x -> y -> Zip ix ox x iy oy y\n\ninstance (Show x, Show y) => Show (Zip ix ox x iy oy y) where\n show (Zip x y) = \"Zip\\n\" ++ show x ++ \"\\n\" ++ show y\n\ninstance (UpdateLayer x, UpdateLayer y) => UpdateLayer (Zip ix ox x iy oy y) where\n type Gradient (Zip ix ox x iy oy y) = (Gradient x, Gradient y)\n runUpdate lr (Zip x y) (x', y') = Zip (runUpdate lr x x') (runUpdate lr y y')\n createRandom = Zip <$> createRandom <*> createRandom\n\ninstance ( Layer x ('D1 p) ('D1 m)\n , Layer y ('D1 q) ('D1 n)\n , KnownNat r\n , KnownNat p\n , KnownNat q\n , r ~ (p + q)\n , q ~ (r - p)\n , (p <=? r) ~ 'True\n , KnownNat o\n , KnownNat m\n , KnownNat n\n , o ~ (m + n)\n , n ~ (o - m)\n , (m <=? o) ~ 'True\n ) => Layer (Zip ('D1 p) ('D1 m) x ('D1 q) ('D1 n) y) ('D1 r) ('D1 o) where\n type Tape (Zip ('D1 p) ('D1 m) x ('D1 q) ('D1 n) y) ('D1 r) ('D1 o) = (Tape x ('D1 p) ('D1 m), Tape y ('D1 q) ('D1 n))\n\n runForwards (Zip x y) (S1D input) =\n let (inputX :: R p, inputY :: R q) = split input\n (xT, xOut :: S ('D1 m)) = runForwards x (S1D inputX)\n (yT, yOut :: S ('D1 n)) = runForwards y (S1D inputY)\n in case (xOut, yOut) of\n (S1D xOut', S1D yOut') ->\n ((xT, yT), S1D (xOut' # yOut'))\n\n runBackwards (Zip x y) (xTape, yTape) (S1D o) =\n let (ox :: R m , oy :: R n) = split o\n (x', xB :: S ('D1 p)) = runBackwards x xTape (S1D ox)\n (y', yB :: S ('D1 q)) = runBackwards y yTape (S1D oy)\n in case (xB, yB) of\n (S1D xB', S1D yB') ->\n ((x', y'), S1D (xB' # yB'))\n\ninstance (Serialize a, Serialize b) => Serialize (Zip sia sa a sib sb b) where\n put (Zip a b) = put a *> put b\n get = Zip <$> get <*> get\n\ninstance (GradNorm a, GradNorm b) => GradNorm (Zip sia sa a sib sb b) where\n normSquared (Zip a b) = normSquared a + normSquared b\n\ninstance (Num a, Num b) => Num (Zip sia sa a sib sb b) where\n (Zip w1 m1) + (Zip w2 m2) = Zip (w1+w2) (m1+m2)\n (Zip w1 m1) - (Zip w2 m2) = Zip (w1-w2) (m1-m2)\n (Zip w1 m1) * (Zip w2 m2) = Zip (w1*w2) (m1*m2)\n abs (Zip w m) = Zip (abs w) (abs m)\n signum (Zip w m) = Zip (signum w) (signum m)\n negate (Zip w m) = Zip (negate w) (negate m)\n fromInteger i = Zip (fromInteger i) (fromInteger i)\n", "meta": {"hexsha": "8e8fb7deae3d38f67032083593333affb02a5481", "size": 3239, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/GrenadeExtras/Zip.hs", "max_stars_repo_name": "helq/haskell-binary-classification", "max_stars_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-10-02T06:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T11:49:35.000Z", "max_issues_repo_path": "src/GrenadeExtras/Zip.hs", "max_issues_repo_name": "helq/haskell-binary-classification", "max_issues_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GrenadeExtras/Zip.hs", "max_forks_repo_name": "helq/haskell-binary-classification", "max_forks_repo_head_hexsha": "e5c6c9a741532365a335657b8d36775bb8a676e6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-12T14:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T14:57:00.000Z", "avg_line_length": 38.1058823529, "max_line_length": 121, "alphanum_fraction": 0.5254708243, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.38196002421476105}} {"text": "-- |\n-- Module : AOC.Challenge.Day11\n-- Copyright : (c) Justin Le 2018\n-- License : BSD3\n--\n-- Maintainer : justin@jle.im\n-- Stability : experimental\n-- Portability : non-portable\n--\n-- Day 11. See \"AOC.Solver\" for the types used in this module!\n\nmodule AOC.Challenge.Day11 (\n day11a\n , day11b\n ) where\n\nimport AOC.Common (Point, meanVar)\nimport AOC.Solver ((:~>)(..))\nimport Control.DeepSeq (force)\nimport Data.Foldable (maximumBy)\nimport Data.Ix (range)\nimport Data.Map (Map)\nimport Data.Maybe (catMaybes)\nimport Data.Ord (comparing)\nimport Data.Profunctor (dimap)\nimport Linear (V2(..))\nimport Text.Read (readMaybe)\nimport qualified Control.Foldl as F\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport qualified Statistics.Distribution as D\nimport qualified Statistics.Distribution.Binomial as D\nimport qualified Statistics.Distribution.Normal as D\n\npowerLevel :: Int -> Point -> Int\npowerLevel sid (V2 x y) = hun ((rid * y + sid) * rid) - 5\n where\n hun = (`mod` 10) . (`div` 100)\n rid = x + 10\n\nfindMaxThree :: Map Point Int -> Point\nfindMaxThree mp = fst\n . maximumBy (comparing snd)\n . map (\\x -> (x, go x))\n $ range (V2 1 1, V2 298 298)\n where\n go p = sum [ mp M.! (p + shift)\n | shift <- range (V2 0 0, V2 2 2)\n ]\n\nmkMap :: Int -> Map Point Int\nmkMap i = M.fromSet (powerLevel i) . S.fromList $ range (V2 1 1, V2 300 300)\n\nday11a :: Int :~> Point\nday11a = MkSol\n { sParse = readMaybe\n , sShow = \\(V2 x y) -> show x ++ \",\" ++ show y\n , sSolve = Just . findMaxThree . mkMap\n }\n\nday11b :: Int :~> (Point, Int)\nday11b = MkSol\n { sParse = readMaybe\n , sShow = \\(V2 x y, s) -> show x ++ \",\" ++ show y ++ \",\" ++ show s\n , sSolve = Just . findMaxAny . mkMap\n }\n\nfindMaxAny :: Map Point Int -> (Point, Int)\nfindMaxAny mp = fst $ go 1\n where\n go n\n | goOn > 0.001 = maximumBy (comparing snd) [((pMax, n), oMax), go (n + 1)]\n | otherwise = ((pMax, n), oMax)\n -- & traceShow (n, oMax, goOn)\n where\n (pMax, oMax) = maximumBy (comparing snd)\n [ (p, fromIntegral (fromSAT sat p n))\n | p <- range (V2 1 1, V2 (300 - n + 1) (300 - n + 1))\n ]\n goOn = sum\n [ probGreaterThan oMax n'\n | n' <- [n + 1 .. 300]\n ]\n !sat = summedAreaTable mp\n σ :: Double\n σ = sqrt $ ((4 + 5)**2)/12 -- stdev of uniform distribution between -5 and 4\n probGreaterThan o n\n | prob2 == 0 = 0\n | otherwise = probIn2\n where\n n' = fromIntegral n\n distr2 = D.normalDistr (-(n' ** 2) * 0.5) (n' * σ)\n prob2 = D.complCumulative distr2 o\n numIn2 = ( (300 `div` n) ^ (2 :: Int) -- we compensate for dependence\n + (300 - n + 1)^(2 :: Int)\n ) `div` 2\n probIn2 = 1 - D.probability (D.binomial numIn2 prob2) 0\n -- this is technically not a bernoulli process,\n -- because our items are dependent. but we fudge this\n -- by tweaking the number of trials\n\nfromSAT :: Map Point Int -> Point -> Int -> Int\nfromSAT sat (subtract (V2 1 1)->p) n = sum . catMaybes $\n [ M.lookup p sat\n , M.lookup (p + V2 n n) sat\n , negate <$> M.lookup (p + V2 0 n) sat\n , negate <$> M.lookup (p + V2 n 0) sat\n ]\n\nsummedAreaTable :: Map Point Int -> Map Point Int\nsummedAreaTable mp = force sat\n where\n sat = M.mapWithKey go mp\n go p0 v = (+ v) . sum . catMaybes $\n [ negate <$> M.lookup (p0 - V2 1 1) sat\n , M.lookup (p0 - V2 1 0) sat\n , M.lookup (p0 - V2 0 1) sat\n ]\n\n-- | Debug: find the variance of the map at every square size\n_chunkyVars :: Map Point Int -> Map Int Double\n_chunkyVars mp = flip M.fromSet (S.fromList [1..300]) $ \\n ->\n F.fold (dimap fromIntegral snd meanVar)\n [ fromSAT sat p n\n | p <- range (V2 1 1, V2 (300 - n + 1) (300 - n + 1))\n ]\n where\n !sat = summedAreaTable mp\n", "meta": {"hexsha": "e03a58ae91da5f166021cecc4b9501cf09f9ddfb", "size": 4508, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AOC/Challenge/Day11.hs", "max_stars_repo_name": "mebubo/mstksg-advent-of-code-2018", "max_stars_repo_head_hexsha": "68d20d839285d1deb65ef2583f83ff4a4eab0690", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 82, "max_stars_repo_stars_event_min_datetime": "2018-12-01T09:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T20:45:44.000Z", "max_issues_repo_path": "src/AOC/Challenge/Day11.hs", "max_issues_repo_name": "mebubo/mstksg-advent-of-code-2018", "max_issues_repo_head_hexsha": "68d20d839285d1deb65ef2583f83ff4a4eab0690", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AOC/Challenge/Day11.hs", "max_forks_repo_name": "mebubo/mstksg-advent-of-code-2018", "max_forks_repo_head_hexsha": "68d20d839285d1deb65ef2583f83ff4a4eab0690", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-12-03T12:23:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T01:54:16.000Z", "avg_line_length": 34.9457364341, "max_line_length": 82, "alphanum_fraction": 0.4971162378, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3817418817771462}} {"text": "{-# OPTIONS_GHC -fglasgow-exts #-}\n{-# LANGUAGE UndecidableInstances #-}\n{- OPTIONS_GHC -fwarn-incomplete-patterns -}\n\nmodule GeneralizedSignals where\n\n--import \nimport qualified Data.StorableVector as SV\nimport qualified Data.StorableVector.Base as SVB\nimport qualified Data.StorableVector.ST.Strict as SVST\nimport Foreign.Storable\n--import EvalM\nimport Foreign.Storable.Tuple\nimport Data.List\nimport Control.Monad.ST\nimport Control.Monad\nimport TNUtils\nimport VectorsL\nimport Nats\n--import PlotGnuplot \nimport Data.Ix \nimport Data.Complex\nimport Numeric.FFT \nimport Math.FFT\nimport qualified Data.Array.CArray as CA\nimport System.IO.Unsafe\n \nnewtype Time = Time Double \n deriving (Eq, Show, Num, Fractional, Floating, Discretizable, IsDouble, Storable)\nnewtype Freq = Freq Double \n deriving (Eq, Show, Num, Fractional, Floating, Discretizable, IsDouble, Storable)\nnewtype Length = Length Double \n deriving (Eq, Show, Num, Fractional, Floating, Discretizable, IsDouble, Storable)\nnewtype SpaceFreq = SpaceFreq Double \n deriving (Eq, Show, Num, Fractional, Floating, Discretizable, IsDouble, Storable)\n\nclass (Eq a,Show a,Num a,Fractional a,Floating a)=> IsDouble a where\n toDouble :: a -> Double\n fromDouble :: Double -> a\n\ninstance IsDouble Double where\n toDouble = id\n fromDouble = id\n\nclass Discretizable a where\n discreteIndex :: (a,a) -> a -> a -> Int\n discreteRange :: (a,a) -> a -> [a]\n discreteRngLength :: (a,a) -> a -> Int\n foldRangeM :: Monad m => (a,a) -> a -> b -> (a -> b -> m b) -> m b\n\ninstance Discretizable Double where\n discreteIndex (lo,hi) dx x = round $ (x-lo)/dx\n discreteRange (lo,hi) dx = [lo, lo+dx..hi]\n discreteRngLength (lo,hi) dx = round $ (hi-lo)/dx\n foldRangeM (lo,hi) dx init f = \n let nmax = discreteRngLength (lo,hi) dx\n go n acc | n > nmax = return acc\n | otherwise = do\n next <- f ((realToFrac n)*dx+lo) acc\n go (n+1) next\n in go 0 init\n\ninstance Discretizable Int where\n discreteIndex (lo,hi) 1 x = x-lo\n discreteIndex (lo,hi) dx x = (x-lo) `div` dx\n discreteRange (lo,hi) dx = [lo,lo+dx..hi]\n discreteRngLength (lo,hi) dx = (hi-lo) `div` dx\n foldRangeM (lo,hi) dx init f = \n let go n acc | n > hi = return acc\n | otherwise = do\n next <- f n acc\n go (n+dx) next\n in go lo init\n\n\n{-instance Discretizable a => Discretizable (Vec Z a) where\n discreteIndex (lo,hi) dx x = 0\n discreteRange (lo,hi) dx = [vnil]\n discreteRngLength (lo,hi) dx = 1\n foldRangeM (lo,hi) dx init f = return init -}\n\ninstance Discretizable a => Discretizable (Vec (S Z) a) where\n discreteIndex (lo,hi) dx x = discreteIndex (vcar lo,vcar hi) (vcar dx) (vcar x)\n discreteRange (lo,hi) dx = map (`vcons` vnil) $ discreteRange (vcar lo,vcar hi) (vcar dx)\n discreteRngLength (lo,hi) dx = discreteRngLength (vcar lo,vcar hi) (vcar dx)\n foldRangeM (lo,hi) dx init f = foldRangeM (vcar lo,vcar hi) (vcar dx) init f'\n where f' x acc = f (x `vcons` vnil) acc\n\n\ninstance (Discretizable a, Discretizable (Vec (S n) a)) => Discretizable (Vec (S (S n)) a) where\n discreteIndex (vx, vy) (vd) (vw) \n = discreteIndex (vcar vx,vcar vy) (vcar vd) (vcar vw) + \n (discreteIndex (vcar vx,vcar vy) (vcar vd) (vcar vy) + 1) * \n discreteIndex (vcdr vx,vcdr vy) (vcdr vd) (vcdr vw)\n discreteRange (vx, vy) vd \n = [ vcons xys vxsys | vxsys <- discreteRange (vcdr vx, vcdr vy) (vcdr vd),\n xys <- discreteRange (vcar vx,vcar vy) (vcar vd)]\n discreteRngLength (vx, vy) (vd) = discreteRngLength (vcar vx,vcar vy) (vcar vd) * \n discreteRngLength (vcdr vx,vcdr vy) (vcdr vd)\n-- foldRangeM :: Monad m => (a,a) -> a -> b -> (a -> b -> m b) -> m b\n foldRangeM (vlo, vhi) vd init f = \n let f' x acc = \n foldRangeM (vcdr vlo, vcdr vhi) (vcdr vd) acc $ \\ix acc' -> f (x `vcons` ix) acc' \n in foldRangeM (vcar vlo, vcar vhi) (vcar vd) init f'\n \nf v (a, i) = return $ (v:a, i+1)\n\ntf = print =<< foldRangeM (0::Vec Three Int, 2) (1) ([],0) f\n\ntf2 = discreteIndex (0::Vec Three Int, 2) (1) (2 `vcons` 2 `vcons` 2 `vcons` vnil)\n\n\n{-$ \\x-> do \n let thisf ix acc = f (x `vcons` ix) acc \n foldRangeM (vcdr vlo, vcdr vhi) (vcdr vd) init thisf -}\n\n\ntype family Volume a :: *\ntype instance Volume Time = (Time,Time)\ntype instance Volume Freq = (Freq,Freq)\n\n--type family FInverses a b :: * -> *\n\n--type instance FInverses Time Freq\n\n--type family FInv a :: *\n\n--type instance FInv Time = Freq\n--type instance (FInv t ~ s) => FInv s = t \n\n{-class Inverses a b | a -> b, b-> a where\n invertFwd :: a -> b\n invertBack :: b -> a\n\ninstance Inverses Time Freq where\n invertFwd (Time t) = Freq $ recip t\n invertBack (Freq f) = Time $ recip f\n\ninstance Inverses Length SpaceFreq where\n invertFwd (Length t) = SpaceFreq $ recip t\n invertBack (SpaceFreq f) = Length $ recip f-}\n\nclass HasInverse a where\n type Inv a :: *\n invertValue :: a -> Inv a\n\ninstance HasInverse Int where\n type Inv Int = Int\n invertValue = negate -- haha. FIXME\n\ninstance HasInverse Time where\n type Inv Time = Freq\n invertValue (Time t) = Freq $ recip t\n\ninstance HasInverse Freq where\n type Inv Freq = Time\n invertValue (Freq t) = Time $ recip t\n\ninstance HasInverse Length where\n type Inv Length = SpaceFreq\n invertValue (Length t) = SpaceFreq $ recip t\n\ninstance HasInverse SpaceFreq where\n type Inv SpaceFreq = Length\n invertValue (SpaceFreq t) = Length $ recip t\n\ninstance HasInverse a => HasInverse (Vec n a) where\n type Inv (Vec n a) = Vec n (Inv a)\n invertValue = fmap invertValue\n\ndata Signal a b where\n Signal :: (Discretizable a, {-Ix (Discretized a),-} Storable b, Storable a) => \n a -> (a,a) -> (Inv a, Inv a) -> SV.Vector b -> Signal a b\n SigFmap :: (b->b') -> Signal a b -> Signal a b'\n SigFun :: (a->b) -> Signal a b\n\nsigLims :: Signal a b -> (a,a)\nsigLims (Signal d1 lims1 invlims1 arr1) = lims1\nsigLims (SigFmap _ s) = sigLims s\n\ninstance Functor (Signal a) where\n fmap f (SigFmap g s) = SigFmap (f . g) s\n fmap f s = SigFmap f s\n\nsOfVToVofS :: Signal a (Vec n b) -> Vec n (Signal a b)\nsOfVToVofS s = undefined\n\nvOfSToSofV :: Vec n (Signal a b) -> Signal a (Vec n b) \nvOfSToSofV voss = let sigs = vecToList voss\n in undefined\n\n\ntype Events a b = [(a,b)]\ntype Region a b = [(Volume a,b)]\n\nat :: Signal a b -> a -> b\nat (Signal delta lims _ arr) x = arr `SV.index` (discreteIndex lims delta x)\nat (SigFmap f s) x = f $ s `at` x\nat (SigFun f) x = f x\n\nfill :: (Discretizable a, Storable b, Storable a) => \n a -> (a,a) -> (Inv a, Inv a) -> (a->b) -> Signal a b\nfill delta lims invlims f = \n Signal delta lims invlims $ SV.pack $ map f $ discreteRange lims delta\n\ntrans :: Storable c => (a->c) -> Signal a b -> Signal a c\ntrans f (Signal delta lims ilims arr) = Signal delta lims ilims newarr where\n newarr = SV.pack $ map f $ discreteRange lims delta\n\n\ntrans' :: Storable c => (a->b->c) -> Signal a b -> Signal a c\ntrans' f (Signal delta lims ilims arr) = Signal delta lims ilims newarr where\n newarr = SV.pack $ map (uncurry f) $ zip (discreteRange lims delta) (SV.unpack arr)\n-- newarr = SV.zipWith f (SV.pack $ discreteRange lims delta) (arr)\n\n--DOESNT WORK -- problem may be in foldRangeM implementation\nfillIO' :: (Discretizable a, Storable b, Show a, Storable a) => \n a -> (a,a) -> (Inv a, Inv a) -> (a->IO b) -> IO (Signal a b)\nfillIO' delta lims invlims mf = do\n let n = discreteRngLength lims delta\n print n\n stv <- stToIO $ SVST.new_ (n+1800) --FUDGE\n let f ixv nix = do v <- mf ixv\n --print (ixv, nix)\n stToIO $ SVST.write stv nix v\n return $ nix+1\n _ <- foldRangeM lims delta 0 f\n sv <- stToIO $ SVST.unsafeFreeze stv\n return $ Signal delta lims invlims sv\n\nfillIO :: (Discretizable a, Storable b, Show a, Storable a) => \n a -> (a,a) -> (Inv a, Inv a) -> (a->IO b) -> IO (Signal a b)\nfillIO delta lims invlims mf = do\n let rng = discreteRange lims delta\n let n = discreteRngLength lims delta\n xs <- mapM mf rng\n return $ Signal delta lims invlims $ SV.pack xs\n\nzipSignalsWith :: Storable c => (a -> b -> c) -> Signal i a -> Signal i b -> Signal i c\nzipSignalsWith f (Signal d1 lims1 invlims1 arr1) (Signal d2 lims2 invlims2 arr2)\n = Signal d1 lims1 invlims2 $ SV.zipWith f arr1 arr2\n\n--toCArray :: Signal a b -> CArray \n\nclass X a b where\n fourier :: Signal a b -> Signal (Inv a) b\n\ninstance X Time (Complex Double) where\n fourier (Signal d lims invlims arr) = Signal (invertValue d) invlims lims $ SV.pack $ fft $ SV.unpack arr\n\ninstance X Freq (Complex Double) where\n fourier (Signal d lims invlims arr) = Signal (invertValue d) invlims lims $ SV.pack $ ifft $ SV.unpack arr\n\ninstance X Length (Complex Double) where\n fourier (Signal d lims invlims arr) = Signal (invertValue d) invlims lims $ SV.pack $ fft $ SV.unpack arr\n\ninstance X SpaceFreq (Complex Double) where\n fourier (Signal d lims invlims arr) = Signal (invertValue d) invlims lims $ SV.pack $ ifft $ SV.unpack arr\n\n--instance X (Vec Z Length) (Complex Double) where\n-- fourier = undefined\n \ninstance (Nat n, X (Vec n Length) (Complex Double), Storable (Vec n SpaceFreq), \n Discretizable (Vec n SpaceFreq), Ix (Vec n Int), CA.Shapable (Vec n Int)) \n => X (Vec n Length) (Complex Double) where\n fourier s@(Signal d lims invlims arr) = \n let ixdims :: Nat n => Signal (Vec n a) b -> n\n ixdims = undefined\n dims = toInt $ ixdims s\n (oldp, oldn, oldsomething) = SVB.toForeignPtr arr\n cixs = discreteLims s\n carray = unsafePerformIO (CA.unsafeForeignPtrToCArray oldp cixs)\n newcarray = dftN [0..dims] carray\n (newn, newp) = CA.toForeignPtr newcarray\n newarr = SVB.fromForeignPtr newp newn\n in Signal (invertValue d) invlims lims newarr\n \n--instance IsDouble d => Shapable (Vec Z d) where\n\ndiscreteLims :: (Nat n, IsDouble d) => Signal (Vec n d) a -> (Vec n Int, Vec n Int)\ndiscreteLims s@(Signal d (lo,hi) invlims arr) \n = ( fmap (round . toDouble) $ lo/d, fmap (round . toDouble) $ hi/d)\n\n\ninstance (Storable (b,c), X a b, X a c) => X a (b,c) where\n fourier s = zipSignalsWith (,) (fourier $ fmap fst s) (fourier $ fmap snd s)\n\ninstance (X a b) => X a (Vec n b) where\n fourier sOfVecs = vOfSToSofV $ fmap fourier $ sOfVToVofS sOfVecs\n\nclass XRC a where\n fourierRC :: Signal a Double -> Signal (Inv a) (Complex Double)\n fourierCR :: Signal (Inv a) (Complex Double) -> Signal a Double", "meta": {"hexsha": "1bc36e1eed91352a5d637573fddff7a64c00e80a", "size": 10796, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "GeneralizedSignals.hs", "max_stars_repo_name": "glutamate/space", "max_stars_repo_head_hexsha": "5b1dab27b40810343a6b026b190d43ac3c54878b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-28T03:20:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-28T03:20:34.000Z", "max_issues_repo_path": "GeneralizedSignals.hs", "max_issues_repo_name": "glutamate/space", "max_issues_repo_head_hexsha": "5b1dab27b40810343a6b026b190d43ac3c54878b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GeneralizedSignals.hs", "max_forks_repo_name": "glutamate/space", "max_forks_repo_head_hexsha": "5b1dab27b40810343a6b026b190d43ac3c54878b", "max_forks_repo_licenses": ["BSD-3-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.8464163823, "max_line_length": 110, "alphanum_fraction": 0.6285661356, "num_tokens": 3496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.38173166203104986}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-|\nModule : Grenade.Layers.Logit\nDescription : Exponential linear unit layer\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n-}\nmodule Grenade.Layers.Elu\n ( Elu(..)\n , SpecElu (..)\n , specElu1D\n , specElu2D\n , specElu3D\n , elu\n ) where\n\nimport Control.DeepSeq (NFData)\nimport Data.Constraint (Dict (..))\nimport Data.Reflection (reifyNat)\nimport Data.Serialize\nimport Data.Singletons\nimport GHC.Generics (Generic)\nimport GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Static as LAS\nimport Unsafe.Coerce (unsafeCoerce)\n\n\nimport Grenade.Core\nimport Grenade.Dynamic\nimport Grenade.Dynamic.Internal.Build\n\n-- | An exponential linear unit.\n-- A layer which can act between any shape of the same dimension, acting as a\n-- diode on every neuron individually.\ndata Elu = Elu\n deriving (Generic, NFData, Show)\n\ninstance UpdateLayer Elu where\n type Gradient Elu = ()\n runUpdate _ _ _ = Elu\n\ninstance RandomLayer Elu where\n createRandomWith _ _ = return Elu\n\ninstance Serialize Elu where\n put _ = return ()\n get = return Elu\n\ninstance ( KnownNat i) => Layer Elu ('D1 i) ('D1 i) where\n type Tape Elu ('D1 i) ('D1 i) = LAS.R i\n\n runForwards _ (S1D y) = (y, S1D (elu y))\n where\n elu = LAS.dvmap (\\a -> if a <= 0 then exp a - 1 else a)\n runBackwards _ y (S1D dEdy) = ((), S1D (elu' y * dEdy))\n where\n elu' = LAS.dvmap (\\a -> if a <= 0 then exp a else 1)\n\ninstance (KnownNat i, KnownNat j) => Layer Elu ('D2 i j) ('D2 i j) where\n type Tape Elu ('D2 i j) ('D2 i j) = S ('D2 i j)\n\n runForwards _ (S2D y) = (S2D y, S2D (elu y))\n where\n elu = LAS.dmmap (\\a -> if a <= 0 then exp a - 1 else a)\n runBackwards _ (S2D y) (S2D dEdy) = ((), S2D (elu' y * dEdy))\n where\n elu' = LAS.dmmap (\\a -> if a <= 0 then exp a else 1)\n\ninstance (KnownNat i, KnownNat j, KnownNat k) => Layer Elu ('D3 i j k) ('D3 i j k) where\n\n type Tape Elu ('D3 i j k) ('D3 i j k) = S ('D3 i j k)\n\n runForwards _ (S3D y) = (S3D y, S3D (elu y))\n where\n elu = LAS.dmmap (\\a -> if a <= 0 then exp a - 1 else a)\n runBackwards _ (S3D y) (S3D dEdy) = ((), S3D (elu' y * dEdy))\n where\n elu' = LAS.dmmap (\\a -> if a <= 0 then exp a else 1)\n\n-------------------- DynamicNetwork instance --------------------\n\ninstance FromDynamicLayer Elu where\n fromDynamicLayer inp _ _ = SpecNetLayer $ SpecElu (tripleFromSomeShape inp)\n\ninstance ToDynamicLayer SpecElu where\n toDynamicLayer _ _ (SpecElu (rows, cols, depth)) =\n reifyNat rows $ \\(_ :: (KnownNat rows) => Proxy rows) ->\n reifyNat cols $ \\(_ :: (KnownNat cols) => Proxy cols) ->\n reifyNat depth $ \\(_ :: (KnownNat depth) => Proxy depth) ->\n case (rows, cols, depth) of\n (_, 1, 1) -> return $ SpecLayer Elu (sing :: Sing ('D1 rows)) (sing :: Sing ('D1 rows))\n (_, _, 1) -> return $ SpecLayer Elu (sing :: Sing ('D2 rows cols)) (sing :: Sing ('D2 rows cols))\n _ -> case (unsafeCoerce (Dict :: Dict()) :: Dict (KnownNat (rows GHC.TypeLits.* depth))) of\n Dict -> return $ SpecLayer Elu (sing :: Sing ('D3 rows cols depth)) (sing :: Sing ('D3 rows cols depth))\n\n\n-- | Create a specification for a elu layer.\nspecElu1D :: Integer -> SpecNet\nspecElu1D i = specElu3D (i, 1, 1)\n\n-- | Create a specification for a elu layer.\nspecElu2D :: (Integer, Integer) -> SpecNet\nspecElu2D (i,j) = specElu3D (i,j,1)\n\n-- | Create a specification for a elu layer.\nspecElu3D :: (Integer, Integer, Integer) -> SpecNet\nspecElu3D = SpecNetLayer . SpecElu\n\n-- | Add a Elu layer to your build.\nelu :: BuildM ()\nelu = buildGetLastLayerOut >>= buildAddSpec . SpecNetLayer . SpecElu\n\n\n-------------------- GNum instances --------------------\n\n\ninstance GNum Elu where\n _ |* Elu = Elu\n _ |+ Elu = Elu\n", "meta": {"hexsha": "e9131b1443ca349925c13212bbfea1cfac350490", "size": 4242, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Elu.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Layers/Elu.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Elu.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 33.140625, "max_line_length": 115, "alphanum_fraction": 0.5914662895, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3789437762330171}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE UnboxedTuples #-}\n{-----------------------------------------------------------------------------------------\n\n Computing the Minimum Message Length function\n Rawle Prince, February 2012\n\n\n calculating the mixture models from the MML2ds functions\n------------------------------------------------------------------------------------------}\nmodule RprMix2 (alph, sigD, sigE, tau, r_n, aBar,sim_eq,\n mmlMixture, initModel, initModelR , --- initModelGD,\n oMod, oModMl, negGradients, negGradientsM, negGradientsOM,\n updateModel, tDupdate, validOM, valid,nextModelR',dataError,\n vmean,vvar,vstDiv,vvarM,vunStdNorm,printElm,vstNorm,invS,invNeg,\n -------- datatpes and modules ----\n Predicted, Data, RNs, OModel (Omod),Mmodel (MkModel),LPars,\n module System.Random\n ) where\n--\nimport Control.Concurrent (forkIO)\nimport ListStats (normal, mtone3,cdf)\nimport LINreg2 (foldl'Rnf) \nimport LMisc (myTake,printElm,printElmChr,similarBy,findCuts, ascending,manyInvNS,sumBy) \n--import Prelude\nimport System.IO.Unsafe\nimport Numeric.LinearAlgebra\nimport Numeric.GSL.Statistics (mean,variance,variance_m,stddev)\nimport Control.Parallel (pseq)\nimport Numeric\nimport System.Random\nimport Foreign.Storable\nimport Control.DeepSeq\nimport Data.Time\nimport Data.List\nimport Data.Maybe (isJust, fromJust, listToMaybe)\nimport Data.Ord (comparing)\nimport qualified Data.ByteString.Lazy.Char8 as L\nimport System.Directory (doesFileExist)\nimport IO\n-----------------------------------------------------------------------------------------------\ninstance (Storable a, NFData a) => NFData (Vector a) where\n rnf va = rnf (toList va)\n\ninstance NFData (Mmodel) where\n rnf (MkModel a b c vs d) = rnf (a, b, c ,vs, d)\n\ninstance NFData (OModel) where\n rnf (Omod m a) = rnf (m , a)\n\n-----------------------------------------------------------------------------------------------\n--- some statistics using vectors instead of lists\n----------------------------------------------------------------------------------------\n--- mean, variance and correlations\n----------------------------------------------------------------------------------------\nvmean :: Vector Double -> Double\nvmean = mean\n---\nvvar :: Vector Double -> Double\nvvar = variance\n\n-- variance of a list of values with the mean given\nvvarM :: Double -> Vector Double -> Double\nvvarM = variance_m\n\n--- the standard deviation without the Mean given\nvstDiv = stddev\n\n------ standardise by subtracting the mean and dividing by the standard deviation\nvstNorm xs = mapVector (\\ a -> (a - m) / std) xs\n where m = vmean xs\n std = sqrt $ vvarM m xs\n\n-- unstandardising\nvunStdNorm m std vs = mapVector (\\a -> std * a + m) vs\n\n-- building the mixture model\n-----------------------------------------------------------------------------------------------\n\n--- the model: alphs, sigE, sigD, linear parms\ndata Mmodel = MkModel !Double !Double !Double (Vector Double) !Double deriving (Eq)\n-- the data and the error class cannot have the same mean, so we need to learn that as well\n\n\n-- if two models are close to each other\nsim_eq (MkModel a b c _ z) (MkModel p q r _ z1) =\n near a p && near b q && near c r && near z z1 -- && etc\n where near x y = abs (x - y) <= 0.008\n \n\n--- the data values\ntype Weight = Vector Double\ntype Predicted = Vector Double\ntype Data = Vector Double\ntype RNs = Vector Double -- [Double]\ntype LPars = Vector Double\ntype Rn = Double\ntype Cost = Double\ntype Lambda = Double\ntype Alpha = Double\n\n-- projecting the compponents of the model\nalph, sigD, sigE, tau :: Mmodel -> Double\nalph (MkModel a _ _ _ _) = a\nsigD (MkModel _ s _ _ _) = s\nsigE (MkModel _ _ e _ _) = e\ntau (MkModel _ _ _ _ z) = z\n\naBar :: Mmodel -> Vector Double\naBar (MkModel _ _ _ a _) = a\n\n\nnegGradients :: Vector Double -> Bool\nnegGradients xs = True -- all negGD (zip xs [1..])\n\n\nnegGradientsM m = negGradients (aBar m)\nnegGradientsOM om = negGradientsM (oMod om)\n\n\n-- update a model by a fraction of another - gradient decent update\nupdateModel :: Mmodel -> Double -> Mmodel -> Mmodel\nupdateModel mO lambda mN = MkModel nalph nsigD' nsigE' naBar ntau\n where !nalph = alph mO + lambda * (alph mN)\n !nsigD = sigD mO + lambda * (sigD mN)\n !nsigE = sigE mO + lambda * (sigE mN)\n !ntau = tau mO + lambda * (tau mN)\n !naBar = zipVectorWith (+) (aBar mO) (mapVector (lambda *) (aBar mN))\n --dehC = alpha * (c1 - c0)\n nsigD' = min nsigD nsigE\n nsigE' = max nsigD nsigE\n\n-- update--- need to fix this to include lambda\ntDupdate:: Mmodel -> Alpha -> Lambda -> Cost -> Cost -> Mmodel -> Mmodel\ntDupdate mO alpha lam c0 c1 mN = MkModel nalph nsigD nsigE naBar ntau\n where nalph = alph mO + dehC * (alph mN - alph mO)\n nsigD = sigD mO + dehC * (sigD mN - sigD mO )\n nsigE = sigE mO + dehC * (sigE mN - sigE mO)\n -- !nsigE = lam * sigE mO + dehC * (sigE mN - sigE mO)\n ntau = tau mO + dehC * (tau mN - tau mO)\n naBar = zipVectorWith (+) abar (mapVector (dehC *) (zipVectorWith (-) (aBar mN) abar))\n dehC = alpha * (c1 - c0)\n nsigD' = min nsigD nsigE\n nsigE' = max nsigD nsigE\n abar = aBar mO\n----\n\nvalid:: Mmodel -> Bool\nvalid (MkModel a b c _ e) = valAlph && valSigs && all ((/= \"NaN\") . show) [a,b,c]\n where\n !valAlph = a >= 0 && a <= 1\n !valSigs = b > 0 && b < c\n\n-- calculating probalilities for the data r_n.\nr_n :: Mmodel -> Double -> Double -> Double\nr_n m mu x = data_given_model / p_data\n where data_given_model = alpha * nxmu\n p_data = alpha * nxmu + (1 - alpha) * nxmuE\n !alpha = alph m\n !nxmu = normal x mu (sigD m)\n !nxmuE = normal x mu (sigE m)\n\n-------- weighted sums for the emAlgorithm\nrn_mean'' :: Predicted -> RNs -> ((Double, Double), (Double, Double))\nrn_mean'' ps rns = ( (dataMean , errMean) , (nd, ne) )\n where\n ((nd, ne),(sumW, sumWE)) = foldl'Rnf fF ((0,0),(0,0)) pdrs -- $ zipVector (,) ps rns\n mkD (a,r) (x, y) = (x + r , y + (1 - r) )\n mkN (a,r) (x, y) = (a + x, (1 - a) + y) -- (1 - r)\n fF (b,b1) a = (mkD a b, mkN a b1)\n pdrs = zip (toList ps) (toList rns)\n --\n mkMn f n p b = p * (f b) /n\n nn = nd + ne\n dataMean = nd / nn\n errMean = ne / nn \n\n-- variances: ran_vars takes the result of rn_mean', which returns the\n-- totals for the casses and the weighted sums\n--rn_vars :: Mmodel -> ((Double, Double), (Double, Double)) -> Data -> RNs -> (Double, Double)\nrn_vars nD nE rns ps ds = (fst squares / nD , snd squares / nE )\n where squares = foldl'Rnf fF (0, 0) (zip rns (zip (toList ps) (toList ds)))\n fF (a,a1) (r ,(p,d)) = (a + r * (p - d)^2 , a1 + (1-r) *(p - d)^2)\n\n---------------------------------------------------------------------------------------------------------------\n--- calculate the mixture model: takes a model and the number of cases, n\n--------------------------------------------------------------------------------------------------------------\nml_alpha :: Mmodel -> Double -> Double\nml_alpha ms n = 0.5 * log n - (n_alpha + 0.5) * log alpHa - ml_alpha_etc\n where !ml_alpha_etc = (n - n_alpha + 0.5) * log (1 - alpHa) - 0.742\n !n_alpha = alpHa * (n + 1) - 0.5\n !alpHa = alph ms\n\nmmlSgAlpha :: Mmodel -> RNs -> Double\nmmlSgAlpha m rns = foldVector sF 0 rns\n where\n sF !a !r = let vr = val r in\n a + vr * log (vr / alpHa) + (1 - vr) * log ((1 - vr) / alpH1)\n !alpHa = alph m\n !alpH1 = 1 - alph m\n val a | a >= 0 && a <= 1 = a\n | a < 0 = 0.0000000001\n | otherwise = 0.9999999999\n\n----\nmmlMixture :: Mmodel -> RNs -> Double\nmmlMixture ms rns = mla + mlSa\n where n = fromIntegral $ dim rns\n !mla = ml_alpha ms n\n !mlSa = mmlSgAlpha ms rns\n\n------------------------------------------------------------------------------------------------\n----- learning the RPR\n------------------------------------------------------------------------------------------------\n\n-- a type for models and their message lengths\ndata OModel = Omod !Mmodel !Double --deriving (Show)\n\n\n-- averaging the oMods\noMod_mean [] = Nothing\nalpha_mean (x:xs) = Just (mDiv n ms)\n where alpha_mean_aux y ys = foldl'Rnf aVg (1,y) ys\n aVg (!n, Omod (MkModel a b c ds t) ml) (Omod (MkModel a1 b1 c1 ds1 t1) ml1) =\n (n+1 , Omod (MkModel (a+a1) (b+b1) (c+c1) (zipVectorWith (+) ds ds1) (t+t1)) (ml+ml1) )\n (n, ms) = alpha_mean_aux x xs\n mDiv n (Omod (MkModel a b c ds t) ml) =\n Omod (MkModel (a/n) (b/n) (c/n) (mapVector (/n) ds) (t/n)) (ml/n)\n\n\ninstance Ord OModel where\n Omod _ ds <= Omod _ ds2 = ds <= ds2\n--\ninstance Eq OModel where\n Omod _ ds == Omod _ ds2 = ds == ds2\n\n--mkOmod ms ds = Omod ms ds\n\noMod (Omod m _ ) = m\noModMl (Omod _ ml) = ml\n\n--- valid OMod\nvalidOM :: OModel -> Bool\nvalidOM (Omod m mgl) = noNan mgl && valid m\n where noNan a = a > 0 - 10000000 && a < 10000000\n\n\n--------------------------------------------------------------------------------------------\n-- learn the parameters around the predicted value using the em algorithm\n--nextModelR :: Predicted -> Data -> Vector Double -> Mmodel -> Mmodel\nnextModelR :: Data -> Predicted -> RNs -> Mmodel -> Mmodel\nnextModelR ds ps rns m = MkModel aa1 bb cc1 (aBar m) (tau m) -- newMod, mixture, newRns)\n where\n ----------- quasi EM algoritm -------------------\n !aa = (nD + 0.5) / (nD + nE + 1)\n aa1 = if aa < 0.55 then (7 / 9.7) else aa -- then 1 - aa else aa\n !bb = sqrt vd -- sd of the data class\n !cc = sqrt ve -- sd of the error class\n !cc1 = max cc (bb * 1.5)\n -- the new parametes are determined by values of the updated predictions\n (!vd,!ve) = rn_vars nD nE (toList rns) ps ds\n !m1 = rn_mean'' ps rns --\n !nD = fst (snd m1)\n !nE = snd (snd m1)\n\n--- EM of sorts. Ideally, should iterate until the parameters are equal\n-- nextModelR' :: Bool -> Matrix Double -> Vector Double -> Mmodel\n--nextModelR' :: Predicted -> Vector Double -> Vector Double -> Mmodel -> (Mmodel, Double)\n--nextModelR' ps ys m = nextModelR'' (invSlopes ps) ys m -- plst `pseq` (minimumBy (comparing snd) plst) --\n-- -- ys\n{-# NOINLINE nextModelR' #-}\nnextModelR' :: (RandomGen g) => g -> [Int] -> Maybe Bool -> Matrix Double -> Vector Double -> Mmodel -> IO (Mmodel, Double)--\nnextModelR' g cts restrictSlopes matrix ys inMod = do\n let ks = (plst1 gg)\n ks `pseq` (return . ssd . (!! 0) $ ks)\n where\n (gg,_) = split g\n ssd (_,b,c) = (b,c)\n trd (_,b,c) = c\n --\n ps = invS restrictSlopes . (matrix <> ) . aBar --\n ps1 = (matrix <> ) . aBar\n --------------------------------------------------------------------------------------------\n ----- updating the errors \n rns m = zipVectorWith (r_n m) (ps m) ys\n faA = fromIntegral . (\\ a -> if a == 2 then 1 else a `div` 2) . dim -- . aBar\n --------------------------------------------------------------------------------------------\n applyMM g = iterate (unsafePerformIO . gMod gg) (1 , inMod , mmlMixture inMod (rns inMod) )\n plst1 g' = [ maybe ks id (listToMaybe xs) | \n let ys = myTake 35 . takeWhile (\\(_,md,_) -> sigD md >= 0.01) $ applyMM g'\n , let (front, ks) = (init ys , last ys)\n , let xs = [fromJust y | let y = similarBy simEqML front, isJust y]\n ]\n --- compare the message lengths ---\n simEqML :: (a, Mmodel, Double) -> (a, Mmodel, Double) -> Bool\n simEqML (_, a ,mla) (_,b ,mlb) = abs (mla - mlb) < 0.00001 -- sim_eq a b --\n ---\n\n gMod :: (RandomGen g) => g -> (Int, Mmodel, Double) -> IO (Int , Mmodel, Double)\n gMod g (n , md, _) = do\n -- print (\"iteration: \" ++ show n ) -- \", probabilities: \" ++ (show . (!! 8) . toList $ rns md) ++\n let dms mx = (rows mx, cols mx)\n -- print (\"matrix dims: \" ++ show (dms matrix) ++ \" ; wWW dim: \" ++ show (dms wWW))\n -- \" alpha: \" ++ show (alph md) ++ \" std: \" ++ show (sigD md) )\n -- print (\"num linear parms: \" ++ show cts )\n let points = \"\\ndata points: \"++ (printElm $ toList ys )\n let predictions = \"\\n predictions : \"++ (printElm . toList $ ps md )\n let otherPredictions = \"\\n predictions : \"++ (show . findCuts . toList $ ps1 md )\n let errors = \"\\nerrors : \"++ (printElm . toList $ rns md )\n let dataStd = \"\\nData std : \"++ (show $ sigD md )\n let errorStd = \"\\nError std : \"++ (show $ sigE md )\n let abund = \"\\nabundance : \"++ (show $ alph md )\n let iter n' = \"\\n---- \\niteration: \" ++ show n' ++ \"\\n-----\"\n let output n' = L.pack ((iter n') ++ points ++ predictions ++ errors ++ dataStd ++ errorStd ++ abund)\n let file = \"probs1.txt\"\n let mixR = mmlMixture nmd rnN\n return (n+1 , nmd, mmlMixture nmd rnN ) \n -- | otherwise = (nmdd, mmlMixture nmdd rnN')\n\n where\n ------ restart with the original model if there is an invallid model ----\n md1 = md \n ---------------------------------------------------------------------------\n !md' = nextModelR ys (ps md1) (rns md1) md1\n nmd = nextModelR ys (ps mdd) (rns mdd) mdd\n rnN = rns nmd\n ------------ updating the linear parameters ---\n siG = sigD md' -- model\n siGE = sigE md' -- model\n abar = aBar md'\n rN = rns md'\n lnR = dim rN\n taU = tau md'\n ------\n wWW = diagRect 0 rN lnR lnR\n xTW = (trans matrix) <> wWW\n xTWx = xTW <> matrix\n ---------------re calcuate the model with the new parameters ----------------------\n pli b (i,j) v = if i == j then v else v -- + b\n zZ = mapMatrixWithIndex (pli (1/taU^2)) xTWx\n --\n arN_aux = head . toColumns . linearSolveLS zZ $ asColumn (xTW <> ys)\n arN = arN_aux\n ---\n nn = faA arN\n tuN = sqrt ((arN <.> arN) /(nn + 1))\n mdd = MkModel (alph md') (sigD md') (sigE md') arN tuN\n\n-------- inverting negative slopes --------------------------\ninvNeg :: Vector Double -> Vector Double\ninvNeg acs = zipVectorWith flipSlp acs (fromList [1 .. dim acs] :: Vector Int)\n where\n flipSlp y a = if even a && y < 0 then invS1 y else y\n invS1 n\n | n >= -1 = n * (-0.4)\n | otherwise = (- 0.6) / n\n\n-- inverting the predictions\ninvS nSlp =\n case nSlp of\n Just tf -> fromList . head . manyInvNS tf . toList\n anyElse -> id\n\n\n---------- INITIALIZE A MODEL\n-----------------------------------------------------------------------------------------------\ninitModelR gen acs = initModelGD gen (dim acs)\n\n----\ninitModel gen s acss = MkModel alpha sgD sgE acs taU\n where\n [alpha, kk] = take 2 (randomRs (0.6, 0.9) gen)\n sgD = max 0.2 s -- (0.7 * s) -- minimum values -- (values !! 0) (values !! 2)\n sgE = 65 * kk * sgD -- maximum values\n acs = invNeg acss -- acs -- invNeg acs\n taU = vstDiv acs\n\n---- for reinitializing the mizture model\ninitModelMix gen aA acs = MkModel alpha sgD sgE asc1 taU\n where --(g1, _) = split gen\n sgD = head (randomRs (0.15, 4.5) gen)\n alpha = head (randomRs (0.68, 0.95) gen)\n --sgD = minimum values -- (values !! 0) (values !! 2)\n sgE = 4 * sgD -- maximum values\n asc1 = invNeg acs\n taU = vstDiv asc1 -- sqrt ((asc1 <.> asc1) /(aA + 2)) -- vstDiv asc1\n ----\n\n--- initializing the model for gradient decent\ninitModelGD gen abarLen = MkModel alpha (min sgD sgE) (max sgD sgE) abar taU\n where (g1, _) = split gen\n values = myTake 3 (randomRs (1, 50.0) gen)\n alpha = (myTake 1 (randomRs (65.0, 95.0) gen) !! 0)/100\n sgD = min (values !! 1) (values !! 2)\n sgE = max (values !! 1) (values !! 2)\n taU = vstDiv abar -- values !! 3\n abar = fromList (myTake abarLen [ x | (y,a) <- zip (randomRs (-10, 20) gen) [1 .. ]\n , let x = if even a && a >= 0 then y else (-1) * y ] )\n\n\n------------------------------------------------------------------------------------------------\n--- calculating probability values\nfilterV :: (Double -> Bool) -> Vector Double -> Vector Double\nfilterV f va = initV $ foldVector (\\a va -> if f a then vcons a va else va) dummy va\n where vcons x xs = join [fromList [x],xs]\n dummy = fromList [-10] :: Vector Double\n initV vs = if n > 1 then subVector 0 (n-1) vs else dummy\n where n = dim vs\n\n-- error and data\n-- Vector of Points -> Vector of means -> alpha -> (a -> Bool)\ndataError :: Mmodel -> Vector Double -> Vector Double -> (Vector Double,Vector Double)\ndataError mod actual predicted = (mkProbs (>= am) , mkProbs (< am) )\n where\n --mn =\n am = let a = alph mod in a -- - (0.05 * a)\n --am' = let a = alph mod in a + (0.05 * a)\n mkProbs f = zipVectorWith (\\a b -> if f (calProbs mod a b) then a else -10) actual predicted\n calProbs mod x mu = let dataProb = am * normal x mu (sigD mod)\n errorProb = (1- am) * normal x mu (sigE mod)\n in\n dataProb / (dataProb + errorProb)\n\ninstance Show Mmodel where\n show (MkModel a b c ds ss) = \"\\nalp:\"++show a ++ \"\\nstd:\" ++ rest1\n where lparms e e1 = \"\\nabr:\" ++ printElm e ++ \"\\ntau:\" ++ show e1\n rest1 = show b ++ \"\\nste:\" ++ show c ++ lparms (toList ds) ss -- ++ \"\\n\"\ninstance Show OModel where\n show (Omod m ml) = show m -- ++ \"mln:\" ++ show ml\n-------------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "33874b4c4b51c9d31f659981433b96bae704f79d", "size": 20139, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "sourceCode/RprMix2.hs", "max_stars_repo_name": "rawlep/MML", "max_stars_repo_head_hexsha": "a2c05b50adcae345f745fe3e28b4aa0b7c4f17ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sourceCode/RprMix2.hs", "max_issues_repo_name": "rawlep/MML", "max_issues_repo_head_hexsha": "a2c05b50adcae345f745fe3e28b4aa0b7c4f17ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sourceCode/RprMix2.hs", "max_forks_repo_name": "rawlep/MML", "max_forks_repo_head_hexsha": "a2c05b50adcae345f745fe3e28b4aa0b7c4f17ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7262180974, "max_line_length": 126, "alphanum_fraction": 0.4553354188, "num_tokens": 5776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.37767281870279507}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE FlexibleContexts #-}\nmodule STC.CompletionFieldR2S1 where\n\nimport Array.UnboxedArray as AU\nimport Control.Monad as M\nimport Control.Monad.Parallel as MP\nimport Control.Parallel.Strategies\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport Data.Vector.Storable as VS\nimport Data.Vector.Unboxed as VU\nimport DFT.Plan\nimport Filter.Utils\nimport Image.IO\nimport Image.Transform\nimport System.FilePath\nimport System.Random\nimport Text.Printf\nimport Types\nimport Utils.Array\nimport Utils.Time\nimport FokkerPlanck.FourierSeries\nimport FokkerPlanck.Analytic\nimport qualified Numeric.LinearAlgebra as NL\nimport qualified Numeric.LinearAlgebra.HMatrix as NL\nimport STC.Utils\nimport FokkerPlanck.BrownianMotion (thetaPlus)\nimport Utils.Diagram\n\n-- Implementation of [Williams and Jacbos, 1997]\n\n{-# INLINE checkN #-}\ncheckN :: Int -> Int -> Int\ncheckN maxN n\n | n < 0 = checkN maxN (n + maxN)\n | n >= maxN = checkN maxN (n - maxN)\n | otherwise = n \n\n{-# INLINE rotateST #-}\nrotateST ::\n (R.Source r Double)\n => R.Array r DIM3 Double\n -> Int\n -> R.Array U DIM3 Double\nrotateST arr 0 = computeUnboxedS . delay $ arr\nrotateST arr n' =\n let (Z :. nf :. nx :. ny) = extent arr\n n = checkN nf n'\n deg = (-2) * pi / (fromIntegral nf) * fromIntegral n\n in rotate25D deg (fromIntegral $ center nx, fromIntegral $ center ny) $\n R.backpermute\n (extent arr)\n (\\(Z :. k :. i :. j) -> (Z :. (mod (k + nf - n) nf) :. i :. j))\n arr\n\n{-# INLINE timeReversal #-}\ntimeReversal :: (R.Source r e) => Array r DIM3 e -> Array D DIM3 e\ntimeReversal arr =\n let (Z :. nf :. _ :. _) = extent arr\n n = div nf 2\n in R.backpermute\n (extent arr)\n (\\(Z :. k :. i :. j) -> (Z :. (mod (k + n) nf) :. i :. j))\n arr\n \n{-# INLINE rotateSTTR #-}\nrotateSTTR ::\n (R.Source r Double)\n => R.Array r DIM3 Double\n -> R.Array U DIM3 Double\nrotateSTTR arr =\n let (Z :. _ :. nx :. ny) = extent arr\n in rotate25D pi (fromIntegral $ center nx, fromIntegral $ center ny) arr\n\n{-# INLINE makeR2S1Plan #-}\nmakeR2S1Plan :: (R.Source r e) => DFTPlan -> R.Array r DIM3 e -> IO DFTPlan\nmakeR2S1Plan oldPlan arr = do\n let (Z :. orientations :. rows :. cols) = extent arr\n vec3D <-\n VS.map (:+ 0) . VS.fromList <$>\n M.replicateM (orientations * rows * cols) randomIO\n lock <- getFFTWLock\n fst <$>\n (dft1dGPlan lock oldPlan [orientations, rows, cols] [1, 2] vec3D >>= \\(plan, vec) ->\n idft1dGPlan lock plan [orientations, rows, cols] [1, 2] vec)\n\n{-# INLINE convolve #-}\nconvolve ::\n (R.Source r (Complex Double))\n => DFTPlan\n -> Array U DIM3 Double\n -> Array r DIM2 (Complex Double)\n -> IO (VU.Vector Double)\nconvolve dftPlan arr3D arr2DF = do\n let (Z :. orientations :. rows :. cols) = extent arr3D\n planID3D = DFTPlanID DFT1DG [orientations, rows, cols] [1, 2]\n inversePlanID = DFTPlanID IDFT1DG [orientations, rows, cols] [1, 2]\n vec3DF <-\n dftExecute dftPlan planID3D . VU.convert . VU.map (:+ 0) . toUnboxed $ arr3D\n let arr3DF =\n fromUnboxed (Z :. orientations :. rows :. cols) . VS.convert $ vec3DF\n vec <-\n dftExecute\n dftPlan\n inversePlanID\n (VU.convert . toUnboxed . computeS . R.traverse2 arr3DF arr2DF const $ \\f3 f2 idx@(Z :. k :. i :. j) ->\n f3 idx * f2 (Z :. i :. j))\n return . VU.map realPart . VS.convert $ vec\n\n{-# INLINE shareWeightST #-}\nshareWeightST ::\n (R.Source r Double)\n => DFTPlan\n -> Array U DIM3 Double\n -> Array r DIM3 Double\n -> IO (Array D DIM3 Double)\nshareWeightST dftPlan arr arrG = do\n let (Z :. nf :. _ :. _) = extent arrG\n (Z :. orientations :. rows :. cols) = extent arr\n arrF <-\n fmap (fromUnboxed (extent arr) . VS.convert) .\n dftExecute dftPlan (DFTPlanID DFT1DG [orientations, rows, cols] [1, 2]) .\n VU.convert . VU.map (:+ 0) . toUnboxed $\n arr\n xs <-\n MP.mapM\n (\\i ->\n convolve\n dftPlan\n (computeS . makeFilter2D . rotateST arrG $ i)\n (R.slice arrF $ (Z :. i :. All :. All)))\n [0 .. nf - 1]\n return . delay . fromUnboxed (extent arrG) . L.foldl1' (VU.zipWith (+)) $ xs\n\n{-# INLINE computeInitialDistribution #-}\ncomputeInitialDistribution ::\n Int -> Int -> Int -> Double -> [R2S1RPPoint] -> R.Array U DIM3 Double\ncomputeInitialDistribution xLen yLen numOrientation delta xs =\n let deltaTheat = 2 * pi / fromIntegral numOrientation\n xShift = div xLen 2\n (xMin, xMax) =\n if odd xLen\n then (-xShift, xShift)\n else (-xShift, xShift - 1)\n yShift = div yLen 2\n (yMin, yMax) =\n if odd yLen\n then (-yShift, yShift)\n else (-yShift, yShift - 1)\n vec =\n toUnboxedVector .\n AU.accum (+) 0 ((0, xMin, yMin), (numOrientation - 1, xMax, yMax)) .\n L.map\n (\\(R2S1RPPoint (x, y, theta, _)) ->\n ( ((floor $ theta * pi / 180 / deltaTheat), round (fromIntegral x / delta), round (fromIntegral y / delta))\n , (1 / (fromIntegral . L.length $ xs)))) $\n xs\n in fromUnboxed (Z :. numOrientation :. xLen :. yLen) vec\n\n-- Implementation of [Williams and Zweck, 2003]\n\n{-# INLINE computeBias #-}\ncomputeBias ::\n Int -> Int -> Int -> [R2S1RPPoint] -> R.Array D DIM3 Double\ncomputeBias xLen yLen numOrientation xs =\n let xShift = div xLen 2\n (xMin, xMax) =\n if odd xLen\n then (-xShift, xShift)\n else (-xShift, xShift - 1)\n yShift = div yLen 2\n (yMin, yMax) =\n if odd yLen\n then (-yShift, yShift)\n else (-yShift, yShift - 1)\n vec =\n toUnboxedVector .\n AU.accum (+) 0 ((xMin, yMin), (xMax, yMax)) .\n L.map (\\(R2S1RPPoint (x, y, _, _)) -> ((x, y), 1)) $\n xs\n in R.traverse\n (fromUnboxed (Z :. xLen :. yLen) vec)\n (const (Z :. numOrientation :. xLen :. yLen)) $ \\f (Z :. _ :. i :. j) ->\n f (Z :. i :. j)\n \n\n{-# INLINE computeInitialEigenVec #-}\ncomputeInitialEigenVec ::\n Int -> Int -> Int -> [R2S1RPPoint] -> R.Array D DIM3 Double\ncomputeInitialEigenVec xLen yLen numOrientation xs =\n let xShift = div xLen 2\n (xMin, xMax) =\n if odd xLen\n then (-xShift, xShift)\n else (-xShift, xShift - 1)\n yShift = div yLen 2\n (yMin, yMax) =\n if odd yLen\n then (-yShift, yShift)\n else (-yShift, yShift - 1)\n vec =\n toUnboxedVector .\n AU.accum (+) 0 ((xMin, yMin), (xMax, yMax)) .\n L.map\n (\\(R2S1RPPoint (x, y, _, _)) ->\n ((x, y), (1 / (fromIntegral . L.length $ xs)))) $\n xs\n in R.traverse\n (fromUnboxed (Z :. xLen :. yLen) vec)\n (const (Z :. numOrientation :. xLen :. yLen)) $ \\f (Z :. _ :. i :. j) ->\n f (Z :. i :. j) / fromIntegral numOrientation\n \n{-# INLINE computeInitialEigenVecGaussian #-}\ncomputeInitialEigenVecGaussian ::\n Int -> Int -> Int -> [(Int, Int, Double)] -> R.Array D DIM3 Double\ncomputeInitialEigenVecGaussian xLen yLen numOrientation xs =\n let xShift = div xLen 2\n (xMin, xMax) =\n if odd xLen\n then (-xShift, xShift)\n else (-xShift, xShift - 1)\n yShift = div yLen 2\n (yMin, yMax) =\n if odd yLen\n then (-yShift, yShift)\n else (-yShift, yShift - 1)\n vec =\n toUnboxedVector .\n AU.accum (+) 0 ((xMin, yMin), (xMax, yMax)) .\n L.map (\\(x, y, v) -> ((x, y), v)) $\n xs\n in R.traverse\n (fromUnboxed (Z :. xLen :. yLen) vec)\n (const (Z :. numOrientation :. xLen :. yLen)) $ \\f (Z :. _ :. i :. j) ->\n f (Z :. i :. j) \n\n{-# INLINE eigenVectorR2S1 #-}\neigenVectorR2S1 ::\n (R.Source s Double, R.Source s1 Double, R.Source s2 Double)\n => DFTPlan\n -> FilePath\n -> R.Array s DIM3 Double\n -> R.Array s DIM3 Double\n -> Int\n -> Bool\n -> R.Array s1 DIM3 Double\n -> R.Array s2 DIM3 Double\n -> IO (R.Array D DIM3 Double)\neigenVectorR2S1 plan folderPath filterSource filterSink n writeFlag bias inputSource = do\n let sourceDist = R.zipWith (*) bias inputSource\n -- s = R.sumAllS sourceDist\n s = L.maximum . R.toList $ sourceDist\n sourceVec = computeS $ R.map (/ s) sourceDist\n (Z :. numOrientation :. _ :. _) = extent inputSource\n printCurrentTime (show n)\n sourceEigenVec <- shareWeightST plan sourceVec filterSource\n -- plotThetaDimension folderPath (printf \"R2S1_%d_\" n) (31,-4) .\n -- R.backpermute\n -- (extent sourceEigenVec)\n -- (\\(Z :. k :. i :. j) ->\n -- (Z :.\n -- (mod (k + numOrientation - (div numOrientation 2)) numOrientation :: Int) :.\n -- i :.\n -- j)) $\n -- sourceEigenVec\n -- sinkEigenVec <-\n -- timeReversal <$>\n -- shareWeightST\n -- plan\n -- (computeS . R.zipWith (*) bias $ sourceEigenVec')\n -- filterSink\n -- let sourceEigenVec =\n -- R.zipWith (\\x y -> x + 0.2 * y) sourceEigenVec' sinkEigenVec\n when\n writeFlag\n (plotImageRepa\n (folderPath printf \"Source_%d.png\" n)\n (ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.map (\\(x) -> (abs x) ** (1/3)) . R.sumS . rotate3D $\n sourceEigenVec))\n return sourceEigenVec\n\npowerMethod ::\n (R.Source s1 Double, R.Source s2 Double)\n => DFTPlan\n -> FilePath\n -> (R.Array U DIM3 Double)\n -> Int\n -> Bool\n -> String\n -> Double\n -> (R.Array s1 DIM3 Double)\n -> (R.Array s2 DIM3 Double)\n -> IO (R.Array U DIM3 Double)\npowerMethod oldPlan folderPath filterSource numIteration writeFlag idStr threshold bias' initialEigenVec = do\n let (Z :. numOrientation :. xLen :. yLen) = extent filterSource\n filterSink = rotateSTTR filterSource\n bias = delay bias'\n plotImageRepa\n (folderPath \"Bias.png\")\n (ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.sumS . rotate3D $\n bias)\n plan <- makeR2S1Plan oldPlan filterSource\n source <-\n M.foldM\n (\\input n ->\n eigenVectorR2S1\n plan\n folderPath\n filterSource\n filterSink\n n\n writeFlag\n bias\n input)\n (delay initialEigenVec)\n [1 .. numIteration]\n -- print . R.toList . R.slice source $ (Z :. All :. (div xLen 2) :. (div yLen 2))\n -- plotThetaDimension folderPath \"R2S1_Source_\" (31,-4) .\n -- R.backpermute\n -- (extent source)\n -- (\\(Z :. k :. i :. j) ->\n -- (Z :.\n -- (mod (k + numOrientation - (div numOrientation 2)) numOrientation :: Int) :.\n -- i :.\n -- j)) $\n -- source\n sink <- shareWeightST plan (rotateSTTR $ bias *^ source) filterSink\n plotImageRepa\n (folderPath \"Sink.png\")\n (ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.sumS . rotate3D $\n sink)\n -- plotThetaDimension folderPath \"R2S1_Sink_\" (31,-4) .\n -- R.backpermute\n -- (extent sink)\n -- (\\(Z :. k :. i :. j) ->\n -- (Z :.\n -- (mod (k + numOrientation - (div numOrientation 2)) numOrientation :: Int) :.\n -- i :.\n -- j)) $\n -- sink\n let completion = computeS $ R.zipWith (*) source sink\n completionR2 = R.sumS . rotate3D $ completion\n completionR2Vec = toUnboxed completionR2\n completionMax = VU.maximum completionR2Vec\n completionMin = VU.minimum completionR2Vec\n plotImageRepa\n (folderPath printf \"Completion%s.png\" idStr)\n (ImageRepa 8 .\n computeS .\n R.extend (Z :. (1 :: Int) :. All :. All) .\n R.map (\\x -> sqrt $ (x - completionMin) / (completionMax - completionMin)) $\n completionR2)\n -- plotThetaDimension folderPath \"R2S1_Completion_\" (31, -4) .\n -- R.backpermute\n -- (extent completion)\n -- (\\(Z :. k :. i :. j) ->\n -- (Z :.\n -- (mod (k + numOrientation - (div numOrientation 2)) numOrientation :: Int) :.\n -- i :.\n -- j)) $\n -- completion\n return completion\n\n\neigenVectorR2S1Analytic ::\n Int -> Double -> Double -> Double -> Double -> [(Double, Double)] -> IO [[Double]]\neigenVectorR2S1Analytic !oris !sigma !tau !gamma !delta !xs = do\n let !numPoints = L.length xs\n !locArr = fromListUnboxed (Z :. L.length xs) xs\n !deltaTheta = 2 * pi / fromIntegral oris\n -- !weights =\n -- [1 / 16, 1 / 8, 1 / 16, 1 / 8, 1 / 4, 1 / 8, 1 / 16, 1 / 8, 1 / 16]\n -- !origins =\n -- L.zipWith\n -- (\\w (i, j) -> (i * delta, j * delta, w))\n -- weights\n -- [(i, j) | i <- [-1 .. 1], j <- [-1 .. 1]]\n transitionMatrixArr' =\n R.traverse locArr (\\_ -> (Z :. numPoints :. oris :. numPoints :. oris)) $ \\f (Z :. i1 :. j1 :. i2 :. j2) ->\n let rowIdx = i1 * oris + j1\n colIdx = i2 * oris + j2\n in if rowIdx /= colIdx && i1 /= i2 \n -- then L.foldl'\n -- (\\s (i, j, w) ->\n -- s +\n -- w *\n -- computePji\n -- sigma\n -- tau\n -- (R2S1RP\n -- (fst . f $ (Z :. i2))\n -- (snd . f $ (Z :. i2))\n -- (deltaTheta * fromIntegral j2)\n -- gamma)\n -- (R2S1RP\n -- (i + (fst . f $ (Z :. i1)))\n -- (j + (snd . f $ (Z :. i1)))\n -- (deltaTheta * fromIntegral j1)\n -- gamma))\n -- 0\n -- origins\n then computePji\n sigma\n tau\n (R2S1RP\n ((fst . f $ (Z :. i2)))\n ((snd . f $ (Z :. i2)))\n (deltaTheta * fromIntegral j2)\n gamma)\n (R2S1RP\n (fst . f $ (Z :. i1))\n (snd . f $ (Z :. i1))\n (deltaTheta * fromIntegral j1)\n gamma)\n else 0\n transitionMatrixArr <- computeUnboxedP transitionMatrixArr'\n -- transitionMatrixArr = computeUnboxedS transitionMatrixArr'\n let !size = numPoints * oris\n transitionMatrix =\n deepSeqArray transitionMatrixArr . (size NL.>< size) . R.toList $\n transitionMatrixArr\n (eigVal, eigVec) = NL.eig transitionMatrix\n pairs =\n L.reverse .\n L.sortOn (realPart . fst) .\n L.filter\n (\\(c, _) ->\n let (m, p) = polar c\n in abs (p) < 1e-10) $\n L.zip (NL.toList eigVal) (L.map NL.toList . NL.toColumns $ eigVec)\n eigenVector =\n fromListUnboxed (Z :. numPoints :. oris) .\n L.map magnitude . snd . L.head $\n pairs\n print . L.map (polar . fst) . L.take 10 $ pairs\n print . L.map (polar . fst) . L.take 10 . L.reverse $ pairs\n print . L.maximum . L.map realPart . snd . L.head $ pairs\n print . L.minimum . L.map realPart . snd . L.head $ pairs\n return . L.map (\\i -> R.toList . R.slice eigenVector $ (Z :. i :. All)) $\n [0 .. numPoints - 1]\n \ncomputeContourR2S1Analytic ::\n (R.Source s Double)\n => FilePath\n -> (R.Array U DIM3 Double)\n -> Int\n -> Int\n -> Int\n -> Double\n -> Double\n -> Double\n -> Double\n -> Double\n -> R.Array s DIM3 Double\n -> [(Double, Double)]\n -> IO (R.Array U DIM3 Double)\ncomputeContourR2S1Analytic !folderPath !filterSource !oris !rows !cols !sigma !tau !gamma !std !delta !bias !xs' = do\n let xs =\n L.map\n (\\(x', y') -> (fromIntegral . round $ x', fromIntegral . round $ y'))\n xs'\n eigenVector <-\n eigenVectorR2S1Analytic\n oris\n sigma\n tau\n gamma\n delta\n (L.map (\\(a, b) -> (a * delta, b * delta)) xs)\n let ys =\n L.concat $\n L.zipWith\n (\\(x, y) thetas ->\n L.zipWith\n (\\k theta -> ((k, round x, round y), theta))\n [0 ..]\n thetas)\n xs\n eigenVector\n (!minR, !maxR) = computeRange rows\n (!minC, !maxC) = computeRange cols\n eigenSourceArr =\n fromUnboxed (Z :. oris :. cols :. rows) .\n toUnboxedVector .\n AU.accum (+) 0 ((0, minC, minR), (oris - 1, maxC, maxR)) $\n ys\n eigenSinkArr = rotateSTTR eigenSourceArr\n completionArr = computeUnboxedS $ eigenSourceArr *^ eigenSinkArr\n filterSink = rotateSTTR filterSource\n plotR2S1Array\n (folderPath \"EigenSource.eps\")\n (fromIntegral rows)\n (fromIntegral cols)\n (fromIntegral rows / 16)\n xs\n eigenSourceArr\n plotR2S1Array\n (folderPath \"EigenSink.eps\")\n (fromIntegral rows)\n (fromIntegral cols)\n (fromIntegral rows / 16)\n xs\n eigenSinkArr\n plotR2S1Array\n (folderPath \"EigenCompletion.eps\")\n (fromIntegral rows)\n (fromIntegral cols)\n (fromIntegral rows / 16)\n xs\n completionArr\n plan <- makeR2S1Plan emptyPlan filterSource\n source <- shareWeightST plan eigenSourceArr filterSource\n plotImageRepa\n (folderPath \"Source.png\")\n (ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.sumS . rotate3D $\n source)\n plotR2S1Array\n (folderPath \"Source.eps\")\n (fromIntegral rows)\n (fromIntegral cols)\n (fromIntegral rows / 16)\n xs\n source\n sink <- shareWeightST plan eigenSinkArr filterSink\n plotImageRepa\n (folderPath \"Sink.png\")\n (ImageRepa 8 .\n computeS . R.extend (Z :. (1 :: Int) :. All :. All) . R.sumS . rotate3D $\n sink)\n plotR2S1Array\n (folderPath \"Sink.eps\")\n (fromIntegral rows)\n (fromIntegral cols)\n (fromIntegral rows / 16)\n xs\n sink\n let completion = computeS $ R.zipWith (*) source sink\n completionR2 = R.sumS . rotate3D $ completion\n completionR2Vec = toUnboxed completionR2\n completionMax = VU.maximum completionR2Vec\n completionMin = VU.minimum completionR2Vec\n print (completionMin, completionMax)\n plotImageRepa\n (folderPath printf \"Completion.png\")\n (ImageRepa 8 .\n computeS .\n R.extend (Z :. (1 :: Int) :. All :. All) .\n -- R.map (\\x -> (abs x) ** (1 / 2)) .\n R.map (\\x -> sqrt $ (x - completionMin) / (completionMax - completionMin)) $\n completionR2)\n plotR2S1Array\n (folderPath \"Completion.eps\")\n (fromIntegral rows)\n (fromIntegral cols)\n (fromIntegral rows / 16)\n xs\n completion\n return completion\n\ncomputeContourR2S1Tangent ::\n FilePath\n -> (R.Array U DIM3 Double)\n -> Int\n -> Int\n -> Int\n -> Double\n -> [(Double, Double)]\n -> IO (R.Array U DIM3 Double)\ncomputeContourR2S1Tangent !folderPath !filterSource !oris !rows !cols !delta !xs = do\n let (cMin, cMax) = computeRange cols\n (rMin, rMax) = computeRange rows\n !deltaTheta = 2 * pi / fromIntegral oris\n initArr =\n fromUnboxed (Z :. oris :. cols :. rows) .\n toUnboxedVector .\n AU.accum (+) 0 ((0, cMin, rMin), (oris - 1, cMax, rMax)) .\n L.concatMap\n (\\(x, y) ->\n let phi = atan2 y x\n idx1 = floor $ ((phi `thetaPlus` (pi / 2)) + pi) / deltaTheta\n idx2 = floor $ ((phi `thetaPlus` ((-pi) / 2)) + pi) / deltaTheta\n in [((idx1, round x, round y), 1), ((idx2, round x, round y), 1)]) $\n xs\n filterSink = rotateSTTR filterSource\n plan <- makeR2S1Plan emptyPlan filterSource\n source <- shareWeightST plan initArr filterSource\n plotImageRepa\n (folderPath \"Source.png\")\n (ImageRepa 8 .\n computeS .\n R.extend (Z :. (1 :: Int) :. All :. All) .\n R.map (\\x -> (abs x) ** (1 / 3)) . R.sumS . rotate3D $\n source)\n sink <- shareWeightST plan initArr filterSink\n plotImageRepa\n (folderPath \"Sink.png\")\n (ImageRepa 8 .\n computeS .\n R.extend (Z :. (1 :: Int) :. All :. All) .\n R.map (\\x -> (abs x) ** (1 / 3)) . R.sumS . rotate3D $\n sink)\n let completion = computeS $ R.zipWith (*) source sink\n completionR2 = R.sumS . rotate3D $ completion\n completionR2Vec = toUnboxed completionR2\n completionMax = VU.maximum completionR2Vec\n completionMin = VU.minimum completionR2Vec\n print (completionMin, completionMax)\n plotImageRepa\n (folderPath printf \"Completion.png\")\n (ImageRepa 8 .\n computeS .\n R.extend (Z :. (1 :: Int) :. All :. All) .\n R.map (\\x -> (abs x) ** (1 / 2)) .\n R.map (\\x -> sqrt $ (x - completionMin) / (completionMax - completionMin)) $\n completionR2)\n return completion\n", "meta": {"hexsha": "24cb2dc6f429f10ef7df5d2930be7d1cfa80cb54", "size": 20791, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/STC/CompletionFieldR2S1.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/STC/CompletionFieldR2S1.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/STC/CompletionFieldR2S1.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 33.3189102564, "max_line_length": 120, "alphanum_fraction": 0.5429753259, "num_tokens": 6505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.37732402880462784}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE FlexibleContexts #-}\n\n\nmodule SymbolicDistr where\n\nimport Control.Monad (replicateM)\nimport Control.Monad.Bayes.Class (MonadSample)\n\nimport Data.Proxy (Proxy (Proxy))\nimport GHC.TypeNats (KnownNat)\n\nimport Numeric.LinearAlgebra.Static (R, Sym, L)\n\nimport DelayedSampling hiding (sample, observe, score)\nimport qualified DelayedSampling as DelS\nimport qualified Distributions as D\nimport qualified MVDistributions as D\nimport DSProg\nimport Util.Ref (Heap, Ref, MonadState)\n\ndata Distr s = DeepForce s => Distr\n { sample :: forall m. MonadState Heap m => MonadSample m => m s\n , observe :: forall m. DelayedInfer m => Forced s -> m ()\n -- Score should not modify the heap, but currently we do not\n -- enforce this\n , score :: forall m. DelayedInfer m => Forced s -> m Double\n }\n\ndistrToSymDistr :: forall a. D.Distr a -> Distr (Expr a)\ndistrToSymDistr d = Distr (Const <$> D.sample d) (D.observe d)\n (pure . D.score d)\n\nsymDistrWithFallback :: forall a. (forall m. MonadState Heap m => MonadSample m => m (D.Distr a))\n -> (forall m. MonadState Heap m => MonadSample m => m (Maybe (Expr a)))\n -> (forall m. DelayedInfer m => (a -> m (Maybe ())))\n -> (forall m. DelayedInfer m => (a -> m (Maybe Double)))\n -> Distr (Expr a)\nsymDistrWithFallback d is iobs iscore = Distr is' iobs' iscore' where\n pd :: MonadState Heap m => MonadSample m => m (Distr (Expr a))\n pd = distrToSymDistr <$> d\n is' :: MonadState Heap m => MonadSample m => m (Expr a)\n is' = do\n mx <- is\n case mx of\n Nothing -> pd >>= sample\n Just x -> pure x\n iobs' :: DelayedInfer m => a -> m ()\n iobs' obs = do\n mupd <- iobs obs\n case mupd of\n Nothing -> do\n d <- pd\n observe d obs\n Just () -> pure ()\n iscore' :: DelayedInfer m => a -> m Double\n iscore' obs = do\n mupd <- iscore obs\n case mupd of\n Nothing -> do\n d <- pd\n score d obs\n Just ll -> pure ll\n\nreplicateIID :: forall a. DeepForce a => D.Distr Int -> Distr a -> Distr [a]\nreplicateIID howMany d = Distr sam obs scorer where\n sam :: MonadState Heap m => MonadSample m => m [a]\n sam = do\n n <- D.sample howMany\n replicateM n (sample d)\n obs :: DelayedInfer m => [Forced a] -> m ()\n obs xs = D.observe howMany (length xs) >> mapM_ (observe d) xs\n scorer :: DelayedInfer m => [Forced a] -> m Double\n scorer xs = do\n let ll = D.score howMany (length xs)\n ll' <- sum <$> mapM (score d) xs\n pure (ll + ll')\n\nbind :: forall a b. a ~ Forced a => DeepForce a => DeepForce b => D.Distr a -> (a -> Distr b) -> Distr (a, b)\nbind d f = Distr sam obs scorer where\n sam :: MonadState Heap m => MonadSample m => m (a, b)\n sam = do\n x <- D.sample d\n y <- sample (f x)\n pure (x, y)\n obs :: DelayedInfer m => (a, Forced b) -> m ()\n obs (x, y) = D.observe d x >> observe (f x) y\n scorer :: DelayedInfer m => (a, Forced b) -> m Double\n scorer (x, y) = (D.score d x +) <$> score (f x) y\n\nindep :: forall a b. DeepForce a => DeepForce b => Distr a -> Distr b -> Distr (a, b)\nindep dx dy = Distr ((,) <$> sample dx <*> sample dy)\n (\\(x, y) -> observe dx x >> observe dy y)\n (\\(x, y) -> (+) <$> score dx x <*> score dy y)\n\nnormal :: Expr Double -> Double -> Distr (Expr Double)\nnormal mu var = symDistrWithFallback (D.normal <$> force mu <*> pure var) is iobs iscore where\n is :: MonadState Heap m => MonadSample m => m (Maybe (Expr Double))\n is = do\n mu' <- realizedToConst mu\n case getAffine1 mu' of\n Nothing -> pure Nothing\n Just (b, mx) -> do\n case mx of\n Nothing -> do\n nref <- assumeConstant \"\" (MGaussian b var)\n Just <$> forgettableVar nref\n Just (RefNodeToT par, m) -> do\n ty <- typeOfRefNodeToT par\n case ty of\n SMGaussianT -> do\n nref <- assumeConditional \"\" par (AffineMeanGaussian m b var)\n Just <$> forgettableVar nref\n _ -> pure Nothing\n withPrior :: forall m x. MonadState Heap m => MonadSample m => (forall a. Double -> Double -> Ref (Node a MGaussianT) -> m x) -> m (Maybe x)\n withPrior f = do\n mu' <- realizedToConst mu\n case getAffine1 mu' of\n Nothing -> pure Nothing\n Just (b, Nothing) -> pure Nothing\n Just (b, Just (RefNodeToT par, m)) -> do\n ty <- typeOfRefNodeToT par\n case ty of\n SMGaussianT -> Just <$> f m b par\n _ -> pure Nothing\n iobs :: DelayedInfer m => Double -> m (Maybe ())\n iobs obs = withPrior $ \\m b par -> observeConditional \"\" par (AffineMeanGaussian m b var) obs\n iscore :: DelayedInfer m => Double -> m (Maybe Double)\n iscore obs = withPrior $ \\m b par -> scoreConditional \"\" par (AffineMeanGaussian m b var) obs\n\nmvNormal :: forall n. KnownNat n => Expr (R n) -> Sym n -> Distr (Expr (R n))\nmvNormal mu var = symDistrWithFallback (D.mvNormal <$> force mu <*> pure var) is iobs iscore where\n is :: MonadState Heap m => MonadSample m => m (Maybe (Expr (R n)))\n is = do\n mu' <- realizedToConst mu\n case getAffineMV1 mu' of\n Nothing -> pure Nothing\n Just (b, mx) -> do\n case mx of\n Nothing -> do\n nref <- assumeConstant \"\" (MMVGaussian b var)\n Just <$> forgettableVar nref\n Just (AffineMVMult (RefNodeToT par) m) -> do\n ty <- typeOfRefNodeToT par\n case ty of\n SMMVGaussianT -> do\n nref <- assumeConditional \"\" par (MVAffineMeanGaussian m b var)\n Just <$> forgettableVar nref\n withPrior :: forall m x. MonadState Heap m => MonadSample m => (forall a k (p :: Proxy k). KnownNat k => L n k -> R n -> Ref (Node a (MMVGaussianT p)) -> m x) -> m (Maybe x)\n withPrior f = do\n mu' <- realizedToConst mu\n case getAffineMV1 mu' of\n Nothing -> pure Nothing\n Just (b, Nothing) -> pure Nothing\n Just (b, Just (AffineMVMult (RefNodeToT par) m)) -> do\n ty <- typeOfRefNodeToT par\n case ty of\n SMMVGaussianT -> Just <$> f m b par\n iobs :: DelayedInfer m => R n -> m (Maybe ())\n iobs obs = withPrior $ \\m b par -> observeConditional \"\" par (MVAffineMeanGaussian m b var) obs\n iscore :: DelayedInfer m => R n -> m (Maybe Double)\n iscore obs = withPrior $ \\m b par -> scoreConditional \"\" par (MVAffineMeanGaussian m b var) obs\n\nbetaSD :: Double -> Double -> Distr (Expr Double)\nbetaSD a b = symDistrWithFallback (pure $ D.beta a b) is iobs (const (pure Nothing)) where\n is :: MonadState Heap m => MonadSample m => m (Maybe (Expr Double))\n is = Just <$> (assumeConstant \"\" (MBeta a b) >>= forgettableVar)\n iobs obs = pure Nothing\n\nbernoulliSD :: Expr Double -> Distr (Expr Bool)\nbernoulliSD p = symDistrWithFallback (D.bernoulli <$> force p) is iobs iscore where\n withBetaPrior :: forall m x. MonadState Heap m => MonadSample m => (forall a. Ref (Node a MBetaT) -> m x) -> m (Maybe x)\n withBetaPrior f = case p of\n Var (RefNodeToT par) -> do\n ty <- typeOfRefNodeToT par\n case ty of\n SMBetaT -> do\n Just <$> f par\n _ -> pure Nothing\n _ -> pure Nothing\n is :: MonadState Heap m => MonadSample m => m (Maybe (Expr Bool))\n is = withBetaPrior $ \\par ->\n forgettableVar =<< assumeConditional \"\" par CBernoulli\n iobs obs = withBetaPrior $ \\par ->\n observeConditional \"\" par CBernoulli obs\n iscore obs = withBetaPrior $ \\par ->\n scoreConditional \"\" par CBernoulli obs", "meta": {"hexsha": "2b365b5dbaec6d6d4f8be06450b6c6f8115021ad", "size": 7484, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "haskell/src/SymbolicDistr.hs", "max_stars_repo_name": "psg-mit/probzelus-haskell", "max_stars_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-26T13:13:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T19:11:41.000Z", "max_issues_repo_path": "haskell/src/SymbolicDistr.hs", "max_issues_repo_name": "psg-mit/probzelus-haskell", "max_issues_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "haskell/src/SymbolicDistr.hs", "max_forks_repo_name": "psg-mit/probzelus-haskell", "max_forks_repo_head_hexsha": "a4b66631451b6156938a9c5420cfff2999ecbbc6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8085106383, "max_line_length": 175, "alphanum_fraction": 0.602485302, "num_tokens": 2251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3769483687443324}} {"text": "{-# LANGUAGE BangPatterns #-}\nmodule General.UserNumber\n(GeneralSimpleNumber(..)\n, ResolveException(..)\n, ParseException(..)\n, GRatio(..)\n, sGR\n, reduce\n, GeneralRealNumber(..)\n, GeneralComplex(..)\n, GeneralNumber(..)\n, PossNumber(..)\n, numShow\n, genExp\n, realMod\n, genRealtoFloat\n, gReal\n, imagUnit\n, getIntegral\n, getIntGen\n, getFloat\n, getRatio\n) where\n\nimport qualified Data.Complex as DC\nimport Data.Ratio\nimport qualified Data.Text.Lazy as T\nimport Math.NumberTheory.Powers.Squares\n\ndata ResolveException = ResolveException T.Text\n deriving Show\n\ndata ParseException = ParseException T.Text Integer\n deriving Show\n\n-- Complex constructor: a:+ b, i.e. 1 + 1j = 1 :+ 1\n-- Fraction constructor a % b, i.e. 1 / 2 = 1 % 2 = 2 % 4\n\n--General Number = Either (Either Integer Fractional) (Either Float )\n\ndata GeneralSimpleNumber = GInt !Integer | GFlo !Float\n deriving (Show, Eq)\n\n--Show for when printing out. Left as-is for debugging\n--instance Show GeneralSimpleNumber where\n-- show GInt n = show n\n-- show GFlo n = show n\n\ninstance Num GeneralSimpleNumber where\n a + b\n | GInt x <- a, GInt y <- b = GInt $ x + y\n | GInt x <- a, GFlo y <- b = GFlo $ fromIntegral x + y\n | GFlo x <- a, GInt y <- b = GFlo $ x + fromIntegral y\n | GFlo x <- a, GFlo y <- b = GFlo $ x + y\n\n a * b\n | GInt x <- a, GInt y <- b = GInt $ x * y\n | GInt x <- a, GFlo y <- b = GFlo $ fromIntegral x * y\n | GFlo x <- a, GInt y <- b = GFlo $ x * fromIntegral y\n | GFlo x <- a, GFlo y <- b = GFlo $ x * y\n\n negate (GInt a) = GInt (negate a)\n negate (GFlo a) = GFlo (negate a)\n\n abs (GInt a) = GInt (abs a)\n abs (GFlo a) = GFlo (abs a)\n\n signum a\n | GInt x <- a = GInt $ signum x\n | GFlo x <- a, signum x < 0.0 = GInt (-1)\n | GFlo x <- a, signum x > 0.0 = GInt 1\n | GFlo _ <- a, True = GInt 0\n\n fromInteger = GInt\n\ninstance Ord GeneralSimpleNumber where\n a <= b\n | GInt x <- a, GInt y <- b = x <= y\n | GInt x <- a, GFlo y <- b = fromIntegral x <= y\n | GFlo x <- a, GInt y <- b = x <= fromIntegral y\n | GFlo x <- a, GFlo y <- b = x <= y\n\ndata GRatio = GR !Integer !Integer deriving (Show)\n\ninstance Eq GRatio where\n GR a b == GR c d = a * d == b * c\n\ninstance Num GRatio where\n GR a b + GR c d = ratReduce (a*d+b*c) (b*d)\n\n GR a b * GR c d = ratReduce (a*b) (c*d)\n\n negate (GR a b) = GR (negate a) b\n\n abs (GR a b) = GR (abs a) b\n\n signum (GR a _) = GR (signum a) 1\n\n fromInteger n = GR (fromInteger n) 1\n\ninstance Fractional GRatio where\n recip (GR a b) = GR b a\n\n fromRational n = GR (numerator n) (denominator n)\n\ninstance Real GRatio where\n toRational (GR a b) = a % b\n\ninstance RealFrac GRatio where\n properFraction (GR a b) = (fromInteger $ a `div` b, GR (a `mod` b) b)\n\ninstance Ord GRatio where\n GR a b <= GR c d = a*d <= b*c\n\nsGR :: Integer -> Integer -> GRatio\nsGR a b = ratReduce (a * signum b) (abs b)\n\nratReduce :: Integer -> Integer -> GRatio\nratReduce !a !b = let d = gcd a b\n in GR (quot a d) (quot b d)\n\ndata GeneralRealNumber = GSimp GeneralSimpleNumber | GRat GRatio deriving (Show, Eq)\n\nreduce :: GRatio -> GeneralRealNumber\nreduce r\n | GR a 1 <- r = GSimp (GInt a)\n | otherwise = GRat r\n\ninstance Num GeneralRealNumber where\n a + b\n | GSimp x <- a, GSimp y <- b = GSimp $ x + y\n | GSimp (GInt x) <- a, GRat (GR y z) <- b = reduce $ ratReduce (x*z+y) z\n | GSimp (GFlo x) <- a, GRat (GR y z) <- b = GSimp $ GFlo $ x+fromIntegral y/fromIntegral z\n | GRat x <- a, GRat y <- b = reduce $ x + y\n | otherwise = b + a\n\n a * b\n | GSimp x <- a, GSimp y <- b = GSimp $ x * y\n | GSimp (GInt x) <- a, GRat (GR y z) <- b = reduce $ ratReduce (x*y) z\n | GSimp (GFlo x) <- a, GRat (GR y z) <- b = GSimp $ GFlo $ x*fromIntegral y/fromIntegral z\n | GRat x <- a, GRat y <- b = reduce $ x * y\n | otherwise = b * a\n\n negate (GSimp a) = GSimp (negate a)\n negate (GRat a) = GRat (negate a)\n\n abs (GSimp a) = GSimp (abs a)\n abs (GRat a) = GRat (abs a)\n\n signum (GSimp a) = GSimp (signum a)\n signum (GRat (GR a _)) = GSimp $ GInt $ signum a\n\n fromInteger n = GSimp (fromInteger n)\n\ninstance Fractional GeneralRealNumber where\n recip a\n |GSimp (GInt x) <- a = GRat $ sGR 1 x\n |GSimp (GFlo x) <- a = GSimp $ GFlo $ recip x\n |GRat x <- a = reduce $ recip x\n\n fromRational n = GRat $ sGR (numerator n) (denominator n)\n\ninstance Real GeneralRealNumber where\n toRational (GSimp (GInt x)) = x % 1\n toRational (GSimp (GFlo x)) = toRational x\n toRational (GRat r) = toRational r\n\nfracHelper :: (RealFrac a, Integral b) => a -> (a -> c) -> (b, c)\nfracHelper inner fun = (int, fun frac)\n where\n (int, frac) = properFraction inner\n\ninstance RealFrac GeneralRealNumber where\n properFraction (GSimp (GInt x)) = (fromInteger x, GSimp $ GInt 0)\n properFraction (GSimp (GFlo x)) = fracHelper x (GSimp . GFlo)\n properFraction (GRat r) = fracHelper r GRat\n\ninstance Ord GeneralRealNumber where\n GSimp a <= GSimp b = a <= b\n GSimp (GInt a) <= GRat (GR b c) = a*c <= b\n GSimp (GFlo a) <= GRat (GR b c) = a * fromInteger c <= fromInteger b\n GRat (GR b c) <= GSimp (GInt a) = b <= a*c\n GRat (GR b c) <= GSimp (GFlo a) = fromInteger b <= a * fromInteger c\n GRat a <= GRat b = a <= b\n\nintPow :: GeneralRealNumber -> Integer -> GeneralRealNumber\nintPow a n\n | n < 0 = intPow (recip a) (negate n)\n | n == 0 = GSimp $ GInt 1\n | otherwise = a * intPow a (n-1)\n\nexpAlgR :: GeneralRealNumber -> Integer -> GeneralRealNumber\nexpAlgR _ 0 = GSimp $ GInt 1\nexpAlgR x 1 = x\nexpAlgR x n\n |n < 0 = expAlgR (recip x) (negate n)\n |even n = expAlgR (x*x) (n `div` 2)\n |otherwise = x * expAlgR (x*x) (n `div` 2)\n\nrealExp :: GeneralRealNumber -> GeneralRealNumber -> GeneralRealNumber\nrealExp _ (GSimp (GInt 0)) = GSimp $ GInt 1\nrealExp a@(GSimp (GInt _)) (GSimp (GInt y)) = expAlgR a y\nrealExp (GSimp (GInt x)) (GSimp (GFlo y)) = GSimp $ GFlo $ fromIntegral x ** y\nrealExp (GSimp (GFlo x)) (GSimp (GInt y)) = GSimp $ GFlo $ x ** fromIntegral y\nrealExp (GSimp (GFlo x)) (GSimp (GFlo y)) = GSimp $ GFlo $ x**y\nrealExp r@(GRat (GR _ _)) (GSimp (GInt n)) = expAlgR r n\nrealExp (GRat (GR a b)) (GSimp c) = realExp (GSimp $ GFlo $ fromInteger a/fromInteger b) (GSimp c)\nrealExp (GSimp c) (GRat (GR a b)) = realExp (GSimp c) (GSimp $ GFlo $ fromInteger a/fromInteger b)\nrealExp (GRat (GR a b)) (GRat (GR c d)) = realExp (GSimp $ GFlo $ fromInteger a/fromInteger b) (GSimp $ GFlo $ fromInteger c/fromInteger d)\n\ngeneralRSqrt :: GeneralRealNumber -> GeneralRealNumber\ngeneralRSqrt (GSimp (GInt a))\n |isSquare a = GSimp $ GInt $ integerSquareRoot a\n |otherwise = GSimp $ GFlo $ sqrt $ fromIntegral a\ngeneralRSqrt (GSimp (GFlo a)) = GSimp $ GFlo $ sqrt a\ngeneralRSqrt (GRat (GR a b))\n |isSquare a && isSquare b = GRat $ GR (integerSquareRoot a) (integerSquareRoot b)\n |otherwise = GSimp $ GFlo $ sqrt $ fromIntegral a/fromIntegral b\n\ngenRealtoFloat :: GeneralRealNumber -> Float\ngenRealtoFloat (GSimp (GInt a)) = fromInteger a\ngenRealtoFloat (GSimp (GFlo a)) = a\ngenRealtoFloat (GRat (GR a b)) = fromInteger a/fromInteger b\n\ndata GeneralComplex = GC !GeneralRealNumber !GeneralRealNumber\n deriving (Show)\n\ninstance Eq GeneralComplex where\n GC a b == GC c d = (a==c) && (b==d)\n\nrealPart :: GeneralComplex -> GeneralRealNumber\nrealPart (GC a _) = a\n\nimagPart :: GeneralComplex -> GeneralRealNumber\nimagPart (GC _ b) = b\n\ninstance Num GeneralComplex where\n (GC a b) + (GC c d) = GC (a+c) (b+d)\n\n GC a b * GC c d = GC (a*c-b*d) (a*d+b*c)\n\n negate (GC a b) = GC (negate a) (negate b)\n\n abs (GC a b) = GC (generalRSqrt ((a `intPow` 2)+(b `intPow` 2))) (GSimp (GInt 0))\n\n signum (GC a b) = GC (a / mag) (b / mag)\n where\n mag = realPart $ abs $ GC a b\n\n fromInteger n = GC (GSimp (GInt n)) 0\n\ninstance Fractional GeneralComplex where\n recip (GC a b) = GC (a/((a `intPow` 2)+(b `intPow` 2))) (-b/((a `intPow` 2)+(b `intPow` 2)))\n\n fromRational n = GC (reduce (ratReduce (numerator n) (denominator n))) (GSimp (GInt 0))\n\ndata GeneralNumber = GReal GeneralRealNumber | GComp GeneralComplex\n deriving (Eq)\n\nsimpComplex :: GeneralComplex -> GeneralNumber\nsimpComplex c@(GC a b)\n | b == 0 || b == 0.0 = GReal a\n | otherwise = GComp c\n\ninstance Num GeneralNumber where\n a + b\n | GReal x <- a, GReal y <- b = GReal $ x + y\n | GReal x <- a, GComp (GC y z) <- b = simpComplex $ GC (x+y) z\n | GComp x <- a, GComp y <- b = simpComplex $ x + y\n | otherwise = b + a\n\n a * b\n | GReal x <- a, GReal y <- b = GReal $ x * y\n | GReal x <- a, GComp (GC y z) <- b = simpComplex $ GC (x*y) $ x*z\n | GComp x <- a, GComp y <- b = simpComplex $ x * y\n | otherwise = b * a\n\n negate (GReal a) = GReal (negate a)\n negate (GComp a) = GComp (negate a)\n\n abs (GReal a) = GReal (abs a)\n abs (GComp a) = simpComplex (abs a)\n\n signum (GReal a) = GReal (signum a)\n signum (GComp a) = GComp (signum a)\n\n fromInteger n = GReal $ GSimp $ GInt n\n\nexpAlgC :: GeneralComplex -> Integer -> GeneralNumber\nexpAlgC _ 0 = GReal $ GSimp $ GInt 1\nexpAlgC x 1 = GComp x\nexpAlgC x n\n |n < 0 = expAlgC (recip x) (negate n)\n |even n = expAlgC (x*x) (n `div` 2)\n |otherwise = GComp x * expAlgC (x*x) (n `div` 2)\n\ninstance Fractional GeneralNumber where\n recip a\n |GReal x <- a = GReal $ recip x\n |GComp x <- a = GComp $ recip x\n\n fromRational n = GReal $ fromRational n\n\ngenExp :: GeneralNumber -> GeneralNumber -> GeneralNumber\ngenExp (GReal n) (GReal m) = GReal $ realExp n m\ngenExp (GComp a) (GReal (GSimp (GInt n))) = expAlgC a n\ngenExp (GComp a) (GReal (GSimp (GFlo flo))) = GComp (GC (GSimp $ GFlo $ DC.realPart builtInPow) (GSimp $ GFlo $ DC.imagPart builtInPow))\n where\n buildInVer = genRealtoFloat (realPart a) DC.:+ genRealtoFloat (imagPart a)\n builtInPow = buildInVer ** (flo DC.:+ 0)\ngenExp a@(GComp _) (GReal r@(GRat _)) = genExp a (GReal $ GSimp $ GFlo $ genRealtoFloat r)\ngenExp (GComp (GC a b)) (GComp (GC c d)) = GComp $ GC (GSimp $ GFlo $ DC.realPart passed) $ GSimp $ GFlo $ DC.imagPart passed\n where\n passed = (genRealtoFloat a DC.:+ genRealtoFloat b) ** (genRealtoFloat c DC.:+ genRealtoFloat d)\ngenExp (GReal n) j = genExp (GComp (GC n 0)) j\n\nrealMod :: GeneralRealNumber -> GeneralRealNumber -> GeneralRealNumber\nrealMod a (GSimp (GInt 0)) = a\nrealMod a b = a - (b * f)\n where\n realfloor :: GeneralRealNumber -> Integer\n realfloor (GSimp (GInt x)) = x\n realfloor (GSimp (GFlo x)) = floor x\n realfloor (GRat (GR x y)) = floor $ genRealtoFloat $ GRat $ GR x y\n f = GSimp $ GInt $ realfloor $ a/b\n\nrealShow :: GeneralRealNumber -> String\nrealShow num\n |GRat (GR x y) <- num = show x ++ \"/\" ++ show y\n |GSimp (GInt x) <- num = show x\n |GSimp (GFlo x) <- num = show x\n\nnumShow :: GeneralNumber -> String\nnumShow num\n |GComp (GC (GSimp (GInt 0)) y) <- num = realShow y ++ \"j\"\n |GComp (GC x y) <- num = realShow x ++ \"+\" ++ realShow y ++ \"j\"\n |GReal x <- num = realShow x\n\ninstance Show GeneralNumber where\n show = numShow\n\ndata PossNumber = Kept GeneralNumber\n | Dropped GeneralNumber\n deriving (Eq)\n\ninstance Show PossNumber where\n show (Kept n) = show n\n show (Dropped n) = \"//\" ++ show n ++ \"//\"\n\ngReal :: (Integral a) => a -> GeneralNumber\ngReal n = GReal $ GSimp $ GInt $ fromIntegral n\n\nimagUnit = GComp $ GC (GSimp $ GInt 0) (GSimp $ GInt 1)\n\ngetIntegral :: (Integral a) => GeneralNumber -> Maybe a\ngetIntegral (GReal (GSimp (GInt n))) = Just $ fromInteger n\ngetIntegral _ = Nothing\n\ngetIntGen :: (Integer -> a) -> GeneralNumber -> Maybe a\ngetIntGen p (GReal (GSimp (GInt n))) = Just $ p n\ngetIntGen _ _ = Nothing\n\ngetFloat :: GeneralNumber -> Maybe Float\ngetFloat (GReal (GSimp (GFlo f))) = Just f\ngetFloat _ = Nothing\n\ngetRatio :: GeneralNumber -> Maybe Rational\ngetRatio (GReal (GRat (GR p q))) = Just $ p % q\ngetRatio _ = Nothing\n", "meta": {"hexsha": "78527bf216de850b9e8a5fefed9bd358deb9aa9d", "size": 11894, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Haskell_Server/rpdiscordserver/src/General/UserNumber.hs", "max_stars_repo_name": "cwstra/rpdiscordrewrite", "max_stars_repo_head_hexsha": "b1b25a19026630a6db59cf6d7f9cda66c4c92c48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-06T19:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T19:22:31.000Z", "max_issues_repo_path": "Haskell_Server/rpdiscordserver/src/General/UserNumber.hs", "max_issues_repo_name": "cwstra/rpdiscordrewrite", "max_issues_repo_head_hexsha": "b1b25a19026630a6db59cf6d7f9cda66c4c92c48", "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_Server/rpdiscordserver/src/General/UserNumber.hs", "max_forks_repo_name": "cwstra/rpdiscordrewrite", "max_forks_repo_head_hexsha": "b1b25a19026630a6db59cf6d7f9cda66c4c92c48", "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.1459459459, "max_line_length": 139, "alphanum_fraction": 0.6151841265, "num_tokens": 4201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.375380936799166}} {"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE Strict #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-|\nModule : Grenade.Layers.Relu\nDescription : Rectifying linear unit layer\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n-}\nmodule Grenade.Layers.Relu (\n Relu (..)\n , SpecRelu (..)\n , specRelu1D\n , specRelu2D\n , specRelu3D\n , relu\n ) where\n\nimport Control.Parallel.Strategies\nimport Data.Constraint (Dict (..))\nimport Data.Reflection (reifyNat)\nimport Data.Serialize\nimport Data.Singletons\nimport GHC.Generics (Generic)\nimport GHC.TypeLits\nimport qualified Numeric.LinearAlgebra.Static as LAS\nimport Unsafe.Coerce (unsafeCoerce)\n\nimport Grenade.Core\nimport Grenade.Dynamic\nimport Grenade.Dynamic.Internal.Build\nimport Grenade.Utils.Conversion\nimport Grenade.Utils.Vector\n\n\n-- | A rectifying linear unit.\n-- A layer which can act between any shape of the same dimension, acting as a\n-- diode on every neuron individually.\ndata Relu = Relu\n deriving (Generic, NFData, Show)\n\ninstance UpdateLayer Relu where\n type Gradient Relu = ()\n runUpdate _ _ _ = Relu\n\ninstance RandomLayer Relu where\n createRandomWith _ _ = return Relu\n\ninstance Serialize Relu where\n put _ = return ()\n get = return Relu\n\n-- Run forward 1D\nrunForward1D :: (KnownNat i) => Relu -> S ('D1 i) -> (Tape Relu ('D1 i) ('D1 i), S ('D1 i))\nrunForward1D _ (S1D y) = (S1D y, S1D (relu y))\n where\n relu = LAS.dvmap (\\a -> if a <= 0 then 0 else a)\nrunForward1D _ (S1DV y) =\n (S1DV y, S1DV (mapVectorInPlace relu y)) -- y will be replaced, which however still leads to a correct implementation!\n -- force (mapVectorInPlace relu y) `seq` (S1DV y, S1DV y) -- y will be replaced, which however still leads to a correct implementation!\n -- (S1DV y, S1DV $ mapVector relu y) -- y will be replaced, which however still leads to a correct implementation!\n where\n relu a = if a <= 0 then 0 else a\n\n\nreluDifZip :: (Ord a, Floating a) => a -> a -> a\nreluDifZip a g = if a <= 0 then 0 else g\n\n-- Run backward 1D\nrunBackward1D :: (KnownNat i) => Relu -> S ('D1 i) -> S ('D1 i) -> (Gradient Relu, S ('D1 i))\nrunBackward1D _ (S1D y) (S1D dEdy) = ((), S1D (relu' y * dEdy))\n where\n relu' = LAS.dvmap (\\a -> if a <= 0 then 0 else 1)\nrunBackward1D _ (S1DV y) (S1DV dEdy) = ((), zipWithVectorInPlaceSnd reluDifZip y dEdy `seq` S1DV dEdy)\nrunBackward1D l y dEdy = runBackward1D l y (toLayerShape y dEdy)\n\n\ninstance (KnownNat i) => Layer Relu ('D1 i) ('D1 i) where\n type Tape Relu ('D1 i) ('D1 i) = S ('D1 i)\n runForwards = runForward1D\n runBackwards = runBackward1D\n\n\nrunBackward2D :: (KnownNat i, KnownNat j) => Relu -> S ('D2 i j) -> S ('D2 i j) -> (Gradient Relu, S ('D2 i j))\nrunBackward2D _ (S2D y) (S2D dEdy) = ((), S2D (relu' y * dEdy))\n where\n relu' = LAS.dmmap (\\a -> if a <= 0 then 0 else 1)\nrunBackward2D _ (S2DV y) (S2DV dEdy) = ((), zipWithVectorInPlaceSnd reluDifZip y dEdy `seq` S2DV dEdy)\nrunBackward2D l y dEdy = runBackward2D l y (toLayerShape y dEdy)\n\ninstance (KnownNat i, KnownNat j) => Layer Relu ('D2 i j) ('D2 i j) where\n type Tape Relu ('D2 i j) ('D2 i j) = S ('D2 i j)\n\n runForwards _ (S2D y) = (S2D y, S2D (relu y))\n where\n relu = LAS.dmmap (\\a -> if a <= 0 then 0 else a)\n runForwards _ (S2DV y) = (S2DV y, S2DV $ mapVectorInPlace relu y ) -- This replaces the y vector, but that doesn't harm the update\n where\n relu a = if a <= 0 then 0 else a\n runBackwards = runBackward2D\n\ninstance (KnownNat i, KnownNat j, KnownNat k) => Layer Relu ('D3 i j k) ('D3 i j k) where\n\n type Tape Relu ('D3 i j k) ('D3 i j k) = S ('D3 i j k)\n\n runForwards _ (S3D y) = (S3D y, S3D (relu y))\n where\n relu = LAS.dmmap (\\a -> if a <= 0 then 0 else a)\n runBackwards _ (S3D y) (S3D dEdy) = ((), S3D (relu' y * dEdy))\n where\n relu' = LAS.dmmap (\\a -> if a <= 0 then 0 else 1)\n\n\n-------------------- DynamicNetwork instance --------------------\n\ninstance FromDynamicLayer Relu where\n fromDynamicLayer inp _ _ = SpecNetLayer $ SpecRelu (tripleFromSomeShape inp)\n\ninstance ToDynamicLayer SpecRelu where\n toDynamicLayer _ _ (SpecRelu (rows, cols, depth)) =\n reifyNat rows $ \\(_ :: (KnownNat rows) => Proxy rows) ->\n reifyNat cols $ \\(_ :: (KnownNat cols) => Proxy cols) ->\n reifyNat depth $ \\(_ :: (KnownNat depth) => Proxy depth) ->\n case (rows, cols, depth) of\n (_, 1, 1) -> return $ SpecLayer Relu (sing :: Sing ('D1 rows)) (sing :: Sing ('D1 rows))\n (_, _, 1) -> return $ SpecLayer Relu (sing :: Sing ('D2 rows cols)) (sing :: Sing ('D2 rows cols))\n _ -> case (unsafeCoerce (Dict :: Dict()) :: Dict (KnownNat (rows GHC.TypeLits.* depth))) of\n Dict -> return $ SpecLayer Relu (sing :: Sing ('D3 rows cols depth)) (sing :: Sing ('D3 rows cols depth))\n\n\n-- | Create a specification for a elu layer.\nspecRelu1D :: Integer -> SpecNet\nspecRelu1D i = specRelu3D (i, 1, 1)\n\n-- | Create a specification for a elu layer.\nspecRelu2D :: (Integer, Integer) -> SpecNet\nspecRelu2D (i, j) = specRelu3D (i, j, 1)\n\n-- | Create a specification for a elu layer.\nspecRelu3D :: (Integer, Integer, Integer) -> SpecNet\nspecRelu3D = SpecNetLayer . SpecRelu\n\n\n-- | Add a Relu layer to your build.\nrelu :: BuildM ()\nrelu = buildGetLastLayerOut >>= buildAddSpec . SpecNetLayer . SpecRelu\n\n\n-------------------- GNum instances --------------------\n\ninstance GNum Relu where\n _ |* Relu = Relu\n _ |+ Relu = Relu\n sumG _ = Relu\n", "meta": {"hexsha": "fcf8bf156601dac696e7bb24ce896218525756ec", "size": 5890, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Relu.hs", "max_stars_repo_name": "schnecki/grenade", "max_stars_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-01-11T15:05:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T15:05:38.000Z", "max_issues_repo_path": "src/Grenade/Layers/Relu.hs", "max_issues_repo_name": "schnecki/grenade", "max_issues_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Relu.hs", "max_forks_repo_name": "schnecki/grenade", "max_forks_repo_head_hexsha": "027e9c16899e2ca3685e89338a047488ac834249", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-02T01:04:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T13:08:47.000Z", "avg_line_length": 36.3580246914, "max_line_length": 137, "alphanum_fraction": 0.6162988115, "num_tokens": 1908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3746915052895648}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE IncoherentInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# OPTIONS -fno-warn-orphans #-}\n\nmodule Data.Array.Accelerate.Data.Complex (\n\n -- * Rectangular from\n Complex(..),\n real,\n imag,\n\n -- * Polar form\n mkPolar,\n cis,\n polar,\n magnitude,\n phase,\n\n -- * Conjugate\n conjugate,\n\n) where\n\nimport Prelude\nimport Data.Complex ( Complex(..) )\nimport Data.Array.Accelerate as A\nimport Data.Array.Accelerate.Smart\nimport Data.Array.Accelerate.Product\nimport Data.Array.Accelerate.Array.Sugar\n\n\ntype instance EltRepr (Complex a) = EltRepr (a, a)\n\ninstance Elt a => Elt (Complex a) where\n eltType _ = eltType (undefined :: (a,a))\n toElt p = let (a, b) = toElt p in a :+ b\n fromElt (a :+ b) = fromElt (a, b)\n\ninstance cst a => IsProduct cst (Complex a) where\n type ProdRepr (Complex a) = ProdRepr (a, a)\n fromProd cst (x :+ y) = fromProd cst (x, y)\n toProd cst p = let (x, y) = toProd cst p in (x :+ y)\n prod cst _ = prod cst (undefined :: (a, a))\n\ninstance (Lift Exp a, Elt (Plain a)) => Lift Exp (Complex a) where\n type Plain (Complex a) = Complex (Plain a)\n lift (x1 :+ x2) = Exp $ Tuple (NilTup `SnocTup` lift x1 `SnocTup` lift x2)\n\ninstance Elt a => Unlift Exp (Complex (Exp a)) where\n unlift e\n = let x = Exp $ SuccTupIdx ZeroTupIdx `Prj` e\n y = Exp $ ZeroTupIdx `Prj` e\n in\n x :+ y\n\ninstance (Elt a, IsFloating a) => Num (Exp (Complex a)) where\n (+) = lift2 ((+) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n (-) = lift2 ((-) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n (*) = lift2 ((*) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))\n negate = lift1 (negate :: Complex (Exp a) -> Complex (Exp a))\n signum = lift1 (signum :: Complex (Exp a) -> Complex (Exp a))\n abs = lift1 (abs :: Complex (Exp a) -> Complex (Exp a))\n fromInteger n = lift (constant (fromInteger n) :+ 0)\n\n\ninstance (Elt a, IsFloating a) => Fractional (Exp (Complex a)) where\n c / c'\n = let x :+ y = unlift c\n x' :+ y' = unlift c' :: Complex (Exp a)\n den = x'^(2 :: Int) + y'^(2 :: Int)\n re = (x * x' + y * y') / den\n im = (y * x' - x * y') / den\n in\n lift (re :+ im)\n\n fromRational x\n = lift (constant (fromRational x) :+ constant 0)\n\n\ninstance (Elt a, IsFloating a, RealFloat a) => Floating (Exp (Complex a)) where\n sqrt z\n = let\n x :+ y = unlift z\n v' = abs y / (u'*2)\n u' = sqrt ((magnitude z + abs x) / 2)\n (u, v) = unlift ( x A.<* 0 ? ( lift (v',u'), lift (u',v') ) )\n in\n x ==* 0 &&* y ==* 0 ?\n {- then -} ( 0\n {- else -} , lift (u :+ (y A.<* 0 ? (-v,v))) )\n\n pi = lift (pi :+ constant 0)\n log z = lift (log (magnitude z) :+ phase z)\n exp = lift1 (exp :: Complex (Exp a) -> Complex (Exp a))\n sin = lift1 (sin :: Complex (Exp a) -> Complex (Exp a))\n cos = lift1 (cos :: Complex (Exp a) -> Complex (Exp a))\n tan = lift1 (tan :: Complex (Exp a) -> Complex (Exp a))\n sinh = lift1 (sinh :: Complex (Exp a) -> Complex (Exp a))\n cosh = lift1 (cosh :: Complex (Exp a) -> Complex (Exp a))\n tanh = lift1 (tanh :: Complex (Exp a) -> Complex (Exp a))\n asin = lift1 (asin :: Complex (Exp a) -> Complex (Exp a))\n acos = lift1 (acos :: Complex (Exp a) -> Complex (Exp a))\n atan = lift1 (atan :: Complex (Exp a) -> Complex (Exp a))\n asinh = lift1 (asinh :: Complex (Exp a) -> Complex (Exp a))\n acosh = lift1 (acosh :: Complex (Exp a) -> Complex (Exp a))\n atanh = lift1 (atanh :: Complex (Exp a) -> Complex (Exp a))\n\n\n-- | The non-negative magnitude of a complex number\n--\nmagnitude :: (Elt a, IsFloating a) => Exp (Complex a) -> Exp a\nmagnitude c =\n let r :+ i = unlift c\n in sqrt (r*r + i*i)\n\n-- | The phase of a complex number, in the range @(-'pi', 'pi']@. If the\n-- magnitude is zero, then so is the phase.\n--\nphase :: (Elt a, IsFloating a) => Exp (Complex a) -> Exp a\nphase c =\n let x :+ y = unlift c\n in atan2 y x\n\n-- | The function 'polar' takes a complex number and returns a (magnitude,\n-- phase) pair in canonical form: the magnitude is non-negative, and the phase\n-- in the range @(-'pi', 'pi']@; if the magnitude is zero, then so is the phase.\n--\npolar :: (Elt a, IsFloating a) => Exp (Complex a) -> Exp (a,a)\npolar z = lift (magnitude z, phase z)\n\n-- | Form a complex number from polar components of magnitude and phase.\n--\nmkPolar :: (Elt a, IsFloating a) => Exp a -> Exp a -> Exp (Complex a)\nmkPolar r theta = lift $ r * cos theta :+ r * sin theta\n\n-- | @'cis' t@ is a complex value with magnitude @1@ and phase @t@ (modulo\n-- @2*'pi'@).\n--\ncis :: (Elt a, IsFloating a) => Exp a -> Exp (Complex a)\ncis theta = lift $ cos theta :+ sin theta\n\n-- | Return the real part of a complex number\n--\nreal :: Elt a => Exp (Complex a) -> Exp a\nreal c =\n let r :+ _ = unlift c\n in r\n\n-- | Return the imaginary part of a complex number\n--\nimag :: Elt a => Exp (Complex a) -> Exp a\nimag c =\n let _ :+ i = unlift c\n in i\n\n-- | Return the complex conjugate of a complex number, defined as\n--\n-- > conjugate(Z) = X - iY\n--\nconjugate :: (Elt a, IsNum a) => Exp (Complex a) -> Exp (Complex a)\nconjugate z = lift $ real z :+ (- imag z)\n\n", "meta": {"hexsha": "c91000ee4b50b6093c417c87f27e6a8881092cb9", "size": 5816, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Array/Accelerate/Data/Complex.hs", "max_stars_repo_name": "fmma/accelerate", "max_stars_repo_head_hexsha": "2255f83e2c5eb597b1e86d2d89a4e8f4c20a4199", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Data/Array/Accelerate/Data/Complex.hs", "max_issues_repo_name": "fmma/accelerate", "max_issues_repo_head_hexsha": "2255f83e2c5eb597b1e86d2d89a4e8f4c20a4199", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data/Array/Accelerate/Data/Complex.hs", "max_forks_repo_name": "fmma/accelerate", "max_forks_repo_head_hexsha": "2255f83e2c5eb597b1e86d2d89a4e8f4c20a4199", "max_forks_repo_licenses": ["BSD-3-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.2117647059, "max_line_length": 86, "alphanum_fraction": 0.5435006878, "num_tokens": 1828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3740948136963992}} {"text": "-- | https://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Parsing\n\nmodule Main where\n\nimport Control.Monad\nimport Control.Monad.Error\nimport Data.Char (digitToInt, isDigit)\nimport Data.Complex\nimport Data.Ratio (denominator, numerator, (%))\nimport Numeric (readDec, readFloat, readHex,\n readInt, readOct)\nimport System.Environment\nimport Text.ParserCombinators.Parsec hiding (spaces)\n\nsymbol :: Parser Char\nsymbol = oneOf \"!$%&|*+-/:<=>?@^_~\" \"a symbol\"\n\n-- readExpr :: String -> Either ParseError LispVal\n-- readExpr = parse parseExpr \"lisp\"\n\n-- Whitespace\nspaces :: Parser ()\nspaces = skipMany1 space\n\n-- Return Values\ndata LispVal = Atom String\n | List [LispVal]\n | DottedList [LispVal] LispVal\n | Number Integer\n | Float Double\n | Ratio Rational\n | Complex (Complex Double)\n | Character Char\n | String String\n | Bool Bool\n\nparseString :: Parser LispVal\nparseString = do\n char '\"'\n str <- many (parseHelper <|> noneOf \"\\\\\\\"\")\n char '\"'\n return $ String str\n \"a string for parseString\"\n where parseHelper :: Parser Char\n parseHelper = do\n char '\\\\'\n x <- oneOf \"\\\\\\\"nrt\"\n return $ case x of\n '\\\\' -> x\n '\"' -> x\n 'n' -> '\\n'\n 'r' -> '\\r'\n 't' -> '\\t'\n\nparseAtom :: Parser LispVal\nparseAtom = do\n first <- letter <|> symbol\n rest <- many $ letter <|> symbol <|> digit\n return $ Atom (first : rest)\n \"a atom for parseAtom\"\n\nparseBool :: Parser LispVal\nparseBool = do\n x <- try (string \"#t\") <|> string \"#f\"\n return $ if x == \"#t\"\n then Bool True\n else Bool False\n\nparseNumber :: Parser LispVal\nparseNumber = parseDigit <|> try parseOct <|> try parseDec <|> try parseHex <|> parseBin\n where parseOct = do\n char '#' >> oneOf \"oO\"\n str <- many1 octDigit\n let [(n, _)] = readOct str\n return $ Number n\n parseDec = do\n char '#' >> oneOf \"dD\"\n str <- many1 digit\n let [(n, _)] = readDec str\n return $ Number n\n parseHex = do\n char '#' >> oneOf \"xX\"\n str <- many1 hexDigit\n let [(n, _)] = readHex str\n return $ Number n\n parseBin = do\n char '#' >> oneOf \"bB\"\n str <- many1 $ oneOf \"01\"\n let [(n, _)] = readInt 2 (`elem` \"01\") digitToInt str\n return $ Number n\n parseDigit = do\n str <- many1 digit\n return $ (Number . read) str\n\nparseChar :: Parser LispVal\nparseChar = do\n string \"#\\\\\"\n x <- many $ letter <|> digit\n return $ case length x of\n 0 -> Character '\\n'\n 1 -> Character $ head x\n _ -> case x of\n \"newline\" -> Character '\\n'\n \"tab\" -> Character '\\t'\n \"space\" -> Character ' '\n\nparseFloat :: Parser LispVal\nparseFloat = do\n x <- many1 digit\n char '.'\n y <- many1 digit\n return $ let [(n, _)] = readFloat (x ++ '.' : y) in Float n\n\nparseRatio :: Parser LispVal\nparseRatio = do\n x <- many1 digit\n char '/'\n y <- many1 digit\n return $ Ratio (read x % read y)\n\nparseComplex :: Parser LispVal\nparseComplex = do\n x <- try parseFloat <|> parseNumber\n char '+'\n y <- try parseFloat <|> parseNumber\n char 'i'\n return $ Complex (toDouble x :+ toDouble y)\n where toDouble :: LispVal -> Double\n toDouble (Float f) = f\n toDouble (Number n) = fromIntegral n\n\n-- Recursive Parsers: Adding lists, dotted lists, and quoted datums\n\nparseList :: Parser LispVal\nparseList = do\n char '('\n x <- sepBy parseExpr spaces\n char ')'\n return $ List x\n\nparseDottedList :: Parser LispVal\nparseDottedList = do\n char '('\n x <- endBy parseExpr spaces\n y <- char '.' >> spaces >> parseExpr\n char ')'\n return $ DottedList x y\n\nparseQuoted :: Parser LispVal\nparseQuoted = do\n char '\\''\n x <- parseExpr\n return $ List [Atom \"quote\", x]\n\nparseBackquote :: Parser LispVal\nparseBackquote = do\n char '`'\n x <- parseExpr\n return $ List [Atom \"quasiquote\", x]\n\nparseUnquote :: Parser LispVal\nparseUnquote = do\n char ','\n y <- parseExpr\n return $ List [Atom \"unquote\", y]\n\nparseUnquoteSplicing :: Parser LispVal\nparseUnquoteSplicing = do\n char ',' >> char '@'\n y <- parseExpr\n return $ List [Atom \"unquote-splicing\", y]\n\nparseExpr :: Parser LispVal\nparseExpr = parseAtom\n <|> try parseBool\n <|> try parseRatio\n <|> try parseComplex\n <|> try parseFloat\n <|> try parseNumber\n <|> parseChar\n <|> parseString\n <|> try parseList\n <|> parseDottedList\n <|> parseQuoted\n <|> parseBackquote\n <|> try parseUnquoteSplicing\n <|> parseUnquote\n\n\n-- Beginning the Evaluator\nshowVal :: LispVal -> String\nshowVal (Atom x) = x\nshowVal (Bool True) = \"#t\"\nshowVal (Bool False) = \"#f\"\nshowVal (Ratio x) = show (numerator x) ++ ('/' : show (denominator x))\nshowVal (Complex x) = show (realPart x) ++ ('+' : show (imagPart x) ++ \"i\")\nshowVal (Float x) = show x\nshowVal (Number x) = show x\nshowVal (Character x) = \"#\\\\\" ++ show x\nshowVal (String x) = \"\\\"\" ++ x ++ \"\\\"\"\nshowVal (List x) = \"(\" ++ unwordsList x ++ \")\"\nshowVal (DottedList first rest)= \"(\" ++ unwordsList first ++ \" . \" ++ showVal rest ++ \")\"\n\nunwordsList :: [LispVal] -> String\nunwordsList = unwords . map showVal\n\ninstance Show LispVal where\n show = showVal\n\nreadExpr :: String -> ThrowsError LispVal\nreadExpr input = case parse parseExpr \"lisp\" input of\n Left err -> throwError $ Parser err\n Right val -> return val\n\n-- Beginnings of an evaluator: Primitives\n-- main :: IO ()\n-- main = getArgs >>= print . eval . readExpr . head\nmain :: IO ()\nmain = do\n args <- getArgs\n evaled <- return $ liftM show $ readExpr (head args) >>= eval\n putStrLn $ extractValue $ trapError evaled\n\n\neval :: LispVal -> ThrowsError LispVal\neval val@(String _) = return val\neval val@(Bool _) = return val\neval val@(Ratio _) = return val\neval val@(Complex _) = return val\neval val@(Float _) = return val\neval val@(Number _) = return val\neval val@(Character _) = return val\neval (List [Atom \"quote\", val]) = return val\n\n-- Adding basic primitives\neval (List (Atom func : args)) = mapM eval args >>= apply func\n\napply :: String -> [LispVal] -> ThrowsError LispVal\napply func args = maybe (throwError $ NotFunction \"No such function: \" func)\n ($ args)\n (lookup func primitives)\n\nprimitives :: [(String, [LispVal] -> ThrowsError LispVal)]\nprimitives = [(\"+\", numericBinop (+)),\n (\"-\", numericBinop (-)),\n (\"*\", numericBinop (*)),\n (\"/\", numericBinop div),\n (\"mod\", numericBinop mod),\n (\"quotient\", numericBinop quot),\n (\"remainder\", numericBinop rem),\n (\"symbol?\", unaryOp symbolp),\n (\"string?\", unaryOp stringp),\n (\"number?\", unaryOp numberp),\n (\"bool?\", unaryOp boolp),\n (\"list?\", unaryOp listp),\n (\"pair?\", unaryOp pairp),\n (\"symbol->string\", unaryOp symbol2String),\n (\"string->symbol\", unaryOp string2Symbol)]\n\nnumericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal\nnumericBinop _ [] = throwError $ NumArgs 2 []\nnumericBinop _ singleVal@[_] = throwError $ NumArgs 2 singleVal\nnumericBinop op args = mapM unpackNum args >>= return . Number . foldl1 op\n where unpackNum :: LispVal -> ThrowsError Integer\n unpackNum (Number n) = return n\n -- unpackNum (String n) = let parsed = readDec n in\n -- if null parsed\n -- then 0\n -- else fst $ head parsed\n -- unpackNum (List [n]) = unpackNum n\n unpackNum notNum = throwError $ TypeMismatch \"number\" notNum\n\nunaryOp :: (LispVal -> ThrowsError LispVal) -> [LispVal] -> ThrowsError LispVal\nunaryOp op [x] = op x\nunaryOp _ wrongArg = throwError $ NumArgs 1 wrongArg\n\nsymbolp :: LispVal -> ThrowsError LispVal\nsymbolp (Atom _) = return $ Bool True\nsymbolp _ = return $ Bool False\n\nstringp :: LispVal -> ThrowsError LispVal\nstringp (String _) = return $ Bool True\nstringp _ = return $ Bool False\n\nnumberp :: LispVal -> ThrowsError LispVal\nnumberp (Number _) = return $ Bool True\nnumberp _ = return $ Bool False\n\nboolp :: LispVal -> ThrowsError LispVal\nboolp (Bool _) = return $ Bool True\nboolp _ = return $ Bool False\n\nlistp :: LispVal -> ThrowsError LispVal\nlistp (List _) = return $ Bool True\nlistp _ = return $ Bool False\n\npairp :: LispVal -> ThrowsError LispVal\npairp (List _) = return $ Bool True\npairp (DottedList _ _) = return $ Bool True\npairp _ = return $ Bool False\n\nsymbol2String :: LispVal -> ThrowsError LispVal\nsymbol2String (Atom x) = return $ String x\nsymbol2String mismatch = throwError $ TypeMismatch \"atom\" mismatch\n\nstring2Symbol :: LispVal -> ThrowsError LispVal\nstring2Symbol (String x) = return $ Atom x\nstring2Symbol mismatch = throwError $ TypeMismatch \"string\" mismatch\n\n-- Error Checking and Exceptions\ndata LispError = NumArgs Integer [LispVal]\n | TypeMismatch String LispVal\n | Parser ParseError\n | BadSpecialForm String LispVal\n | NotFunction String String\n | UnboundVar String String\n | Default String\n\nshowError :: LispError -> String\nshowError (UnboundVar message varname) = message ++ \": \" ++ varname\nshowError (BadSpecialForm message form) = message ++ \": \" ++ show form\nshowError (NotFunction message func) = message ++ \": \" ++ show func\nshowError (NumArgs expected found) = \"Expected \" ++ show expected\n ++ \" args; found values \" ++ unwordsList found\nshowError (TypeMismatch expected found) = \"Invalid type: expected \" ++ expected\n ++ \", found \" ++ show found\nshowError (Parser parseErr) = \"Parse error at \" ++ show parseErr\n\ninstance Show LispError where show = showError\n\ninstance Error LispError where\n noMsg = Default \"An error has occurred\"\n strMsg = Default\n\ntype ThrowsError = Either LispError\n\ntrapError :: (MonadError e m, Show e) => m String -> m String\ntrapError action = catchError action (return . show)\n\n\nextractValue :: ThrowsError a -> a\nextractValue (Right val) = val\n", "meta": {"hexsha": "15f93eede2416affafe69bc500886e5fbc72e78f", "size": 10488, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "WriteYourselfAScheme/sec4-error-checking-and-exceptions/Main.hs", "max_stars_repo_name": "zeqing-guo/Haskell-Exercises", "max_stars_repo_head_hexsha": "54f84d2f3ab98469d2e670170f679c0bf51e9774", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WriteYourselfAScheme/sec4-error-checking-and-exceptions/Main.hs", "max_issues_repo_name": "zeqing-guo/Haskell-Exercises", "max_issues_repo_head_hexsha": "54f84d2f3ab98469d2e670170f679c0bf51e9774", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WriteYourselfAScheme/sec4-error-checking-and-exceptions/Main.hs", "max_forks_repo_name": "zeqing-guo/Haskell-Exercises", "max_forks_repo_head_hexsha": "54f84d2f3ab98469d2e670170f679c0bf51e9774", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5772594752, "max_line_length": 89, "alphanum_fraction": 0.5939168574, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3734412129766269}} {"text": "{-# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #-}\n\nmodule Numerical.HBLAS.BLAS.FFI.Level2 where\n\nimport Foreign.Ptr\nimport Foreign()\nimport Foreign.C.Types\nimport Data.Complex\nimport Numerical.HBLAS.BLAS.FFI\n\ntype GbmvFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_TRANSPOSET -> CInt -> CInt\n -> CInt -> CInt -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()\n\nforeign import ccall unsafe \"cblas_sgbmv\"\n cblas_sgbmv_unsafe :: GbmvFunFFI Float Float\nforeign import ccall unsafe \"cblas_dgbmv\"\n cblas_dgbmv_unsafe :: GbmvFunFFI Double Double\nforeign import ccall unsafe \"cblas_cgbmv\"\n cblas_cgbmv_unsafe :: GbmvFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall unsafe \"cblas_zgbmv\"\n cblas_zgbmv_unsafe :: GbmvFunFFI (Ptr (Complex Double)) (Complex Double)\n\nforeign import ccall \"cblas_sgbmv\"\n cblas_sgbmv_safe :: GbmvFunFFI Float Float\nforeign import ccall \"cblas_dgbmv\"\n cblas_dgbmv_safe :: GbmvFunFFI Double Double\nforeign import ccall \"cblas_cgbmv\"\n cblas_cgbmv_safe :: GbmvFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall \"cblas_zgbmv\"\n cblas_zgbmv_safe :: GbmvFunFFI (Ptr (Complex Double)) (Complex Double)\n--void cblas_sgbmv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE TransA, CInt M, CInt N,\n-- CInt KL, CInt KU, Float alpha, Float *A, CInt lda, Float *X, CInt incX, Float beta, Float *Y, CInt incY);\n--void cblas_dgbmv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE TransA, CInt M, CInt N,\n-- CInt KL, CInt KU, Double alpha, Double *A, CInt lda, Double *X, CInt incX, Double beta, Double *Y, CInt incY);\n--void cblas_cgbmv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE TransA, CInt M, CInt N,\n-- CInt KL, CInt KU, Float *alpha, Float *A, CInt lda, Float *X, CInt incX, Float *beta, Float *Y, CInt incY);\n--void cblas_zgbmv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE TransA, CInt M, CInt N,\n-- CInt KL, CInt KU, Double *alpha, Double *A, CInt lda, Double *X, CInt incX, Double *beta, Double *Y, CInt incY);\n\n\n{-\nmatrix vector product for general matrices\n perform one of the matrix-vector operations y :=\n alpha*A*x + beta*y, or y := alpha*A'*x + beta*y,\n-}\n\ntype GemvFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_TRANSPOSET -> CInt -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()\n\nforeign import ccall unsafe \"cblas_sgemv\"\n cblas_sgemv_unsafe :: GemvFunFFI Float Float\nforeign import ccall safe \"cblas_sgemv\"\n cblas_sgemv_safe :: GemvFunFFI Float Float\n\nforeign import ccall unsafe \"cblas_dgemv\"\n cblas_dgemv_unsafe :: GemvFunFFI Double Double\nforeign import ccall safe \"cblas_dgemv\"\n cblas_dgemv_safe :: GemvFunFFI Double Double\n\nforeign import ccall unsafe \"cblas_cgemv\"\n cblas_cgemv_unsafe :: GemvFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_cgemv\"\n cblas_cgemv_safe :: GemvFunFFI (Ptr (Complex Float)) (Complex Float)\n\nforeign import ccall unsafe \"cblas_zgemv\"\n cblas_zgemv_unsafe :: GemvFunFFI (Ptr (Complex Double)) (Complex Double)\nforeign import ccall safe \"cblas_zgemv\"\n cblas_zgemv_safe :: GemvFunFFI (Ptr (Complex Double)) (Complex Double)\n\n--void cblas_sgemv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE trans, CInt m, CInt n,\n-- Float alpha, Float *a, CInt lda, Float *x, CInt incx, Float beta, Float *y, CInt incy);\n--void cblas_dgemv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE trans, CInt m, CInt n,\n-- Double alpha, Double *a, CInt lda, Double *x, CInt incx, Double beta, Double *y, CInt incy);\n--void cblas_cgemv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE trans, CInt m, CInt n,\n-- Float *alpha, Float *a, CInt lda, Float *x, CInt incx, Float *beta, Float *y, CInt incy);\n--void cblas_zgemv( enum CBLAS_ORDER order, enum CBLAS_TRANSPOSE trans, CInt m, CInt n,\n-- Double *alpha, Double *a, CInt lda, Double *x, CInt incx, Double *beta, Double *y, CInt incy);\n\n\n-- perform the rank 1 operation A := alpha*x*y' + A,\n\ntype GerxFunFFI scale el = CBLAS_ORDERT -> CInt -> CInt -> scale -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\n\nforeign import ccall unsafe \"cblas_sger\" cblas_sger_unsafe ::\n GerxFunFFI Float Float\nforeign import ccall safe \"cblas_sger\" cblas_sger_safe ::\n GerxFunFFI Float Float\n\nforeign import ccall unsafe \"cblas_dger\" cblas_dger_unsafe ::\n GerxFunFFI Double Double\nforeign import ccall safe \"cblas_dger\" cblas_dger_safe ::\n GerxFunFFI Double Double\n\nforeign import ccall unsafe \"cblas_cgerc\" cblas_cgerc_unsafe ::\n GerxFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall unsafe \"cblas_zgerc\" cblas_zgerc_unsafe ::\n GerxFunFFI (Ptr (Complex Double)) (Complex Double)\n\nforeign import ccall safe \"cblas_cgerc\" cblas_cgerc_safe ::\n GerxFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_zgerc\" cblas_zgerc_safe ::\n GerxFunFFI (Ptr (Complex Double)) (Complex Double)\n\nforeign import ccall unsafe \"cblas_cgeru\" cblas_cgeru_unsafe ::\n GerxFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall unsafe \"cblas_zgeru\" cblas_zgeru_unsafe ::\n GerxFunFFI (Ptr (Complex Double)) (Complex Double)\n\nforeign import ccall safe \"cblas_cgeru\" cblas_cgeru_safe ::\n GerxFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_zgeru\" cblas_zgeru_safe ::\n GerxFunFFI (Ptr (Complex Double)) (Complex Double)\n\n--void cblas_sger ( enum CBLAS_ORDER order, CInt M, CInt N, Float alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *A, CInt lda);\n--void cblas_dger ( enum CBLAS_ORDER order, CInt M, CInt N, Double alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *A, CInt lda);\n--void cblas_cgeru( enum CBLAS_ORDER order, CInt M, CInt N, Float *alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *A, CInt lda);\n--void cblas_cgerc( enum CBLAS_ORDER order, CInt M, CInt N, Float *alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *A, CInt lda);\n--void cblas_zgeru( enum CBLAS_ORDER order, CInt M, CInt N, Double *alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *A, CInt lda);\n--void cblas_zgerc( enum CBLAS_ORDER order, CInt M, CInt N, Double *alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *A, CInt lda);\n\ntype HbmvFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_chbmv\"\n cblas_chbmv_unsafe :: HbmvFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_chbmv\"\n cblas_chbmv_safe :: HbmvFunFFI (Ptr (Complex Float)) (Complex Float)\n\nforeign import ccall unsafe \"cblas_zhbmv\"\n cblas_zhbmv_unsafe :: HbmvFunFFI (Ptr (Complex Double)) (Complex Double)\nforeign import ccall safe \"cblas_zhbmv\"\n cblas_zhbmv_safe :: HbmvFunFFI (Ptr (Complex Double)) (Complex Double)\n--void cblas_chbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, CInt K,\n-- Float *alpha, Float *A, CInt lda, Float *X, CInt incX, Float *beta, Float *Y, CInt incY);\n--void cblas_zhbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, CInt K,\n-- Double *alpha, Double *A, CInt lda, Double *X, CInt incX, Double *beta, Double *Y, CInt incY);\n\ntype HemvFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_chemv\"\n cblas_chemv_unsafe :: HemvFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_chemv\"\n cblas_chemv_safe :: HemvFunFFI (Ptr (Complex Float)) (Complex Float)\n\nforeign import ccall unsafe \"cblas_zhemv\"\n cblas_zhemv_unsafe :: HemvFunFFI (Ptr (Complex Double)) (Complex Double)\nforeign import ccall safe \"cblas_zhemv\"\n cblas_zhemv_safe :: HemvFunFFI (Ptr (Complex Double)) (Complex Double)\n--void cblas_chemv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float *alpha, Float *A,\n-- CInt lda, Float *X, CInt incX, Float *beta, Float *Y, CInt incY);\n--void cblas_zhemv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double *alpha, Double *A,\n-- CInt lda, Double *X, CInt incX, Double *beta, Double *Y, CInt incY);\n\n\ntype HerFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_cher\"\n cblas_cher_unsafe :: HerFunFFI Float (Complex Float)\nforeign import ccall safe \"cblas_cher\"\n cblas_cher_safe :: HerFunFFI Float (Complex Float)\n\nforeign import ccall unsafe \"cblas_zher\"\n cblas_zher_unsafe :: HerFunFFI Double (Complex Double)\nforeign import ccall safe \"cblas_zher\"\n cblas_zher_safe :: HerFunFFI Double (Complex Double)\n--void cblas_cher( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *A, CInt lda);\n--void cblas_zher( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *A, CInt lda);\n\ntype Her2FunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_cher2\"\n cblas_cher2_unsafe :: Her2FunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_cher2\"\n cblas_cher2_safe :: Her2FunFFI (Ptr (Complex Float)) (Complex Float)\n\nforeign import ccall unsafe \"cblas_zher2\"\n cblas_zher2_unsafe :: Her2FunFFI (Ptr (Complex Double)) (Complex Double)\nforeign import ccall safe \"cblas_zher2\"\n cblas_zher2_safe :: Her2FunFFI (Ptr (Complex Double)) (Complex Double)\n--void cblas_cher2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float *alpha, Float *X, CInt incX,\n-- Float *Y, CInt incY, Float *A, CInt lda);\n--void cblas_zher2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double *alpha, Double *X, CInt incX,\n-- Double *Y, CInt incY, Double *A, CInt lda);\n\ntype HpmvFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_chpmv\"\n cblas_chpmv_unsafe :: HpmvFunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_chpmv\"\n cblas_chpmv_safe :: HpmvFunFFI (Ptr (Complex Float)) (Complex Float)\n\nforeign import ccall unsafe \"cblas_zhpmv\"\n cblas_zhpmv_unsafe :: HpmvFunFFI (Ptr (Complex Double)) (Complex Double)\nforeign import ccall safe \"cblas_zhpmv\"\n cblas_zhpmv_safe :: HpmvFunFFI (Ptr (Complex Double)) (Complex Double)\n--void cblas_chpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N,\n-- Float *alpha, Float *Ap, Float *X, CInt incX, Float *beta, Float *Y, CInt incY);\n--void cblas_zhpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N,\n-- Double *alpha, Double *Ap, Double *X, CInt incX, Double *beta, Double *Y, CInt incY);\n\ntype HprFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> IO ()\nforeign import ccall unsafe \"cblas_chpr\"\n cblas_chpr_unsafe :: HprFunFFI Float (Complex Float)\nforeign import ccall safe \"cblas_chpr\"\n cblas_chpr_safe :: HprFunFFI Float (Complex Float)\n\nforeign import ccall unsafe \"cblas_zhpr\"\n cblas_zhpr_unsafe :: HprFunFFI Double (Complex Double)\nforeign import ccall safe \"cblas_zhpr\"\n cblas_zhpr_safe :: HprFunFFI Double (Complex Double)\n--void cblas_chpr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *A);\n--void cblas_zhpr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *A);\n\ntype Hpr2FunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> IO ()\nforeign import ccall unsafe \"cblas_chpr2\"\n cblas_chpr2_unsafe :: Hpr2FunFFI (Ptr (Complex Float)) (Complex Float)\nforeign import ccall safe \"cblas_chpr2\"\n cblas_chpr2_safe :: Hpr2FunFFI (Ptr (Complex Float)) (Complex Float)\n\nforeign import ccall unsafe \"cblas_zhpr2\"\n cblas_zhpr2_unsafe :: Hpr2FunFFI (Ptr (Complex Double)) (Complex Double)\nforeign import ccall safe \"cblas_zhpr2\"\n cblas_zhpr2_safe :: Hpr2FunFFI (Ptr (Complex Double)) (Complex Double)\n--void cblas_chpr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float *alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *Ap);\n--void cblas_zhpr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double *alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *Ap);\n\ntype SbmvFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_ssbmv\"\n cblas_ssbmv_unsafe :: SbmvFunFFI Float Float\nforeign import ccall safe \"cblas_ssbmv\"\n cblas_ssbmv_safe :: SbmvFunFFI Float Float\n\nforeign import ccall unsafe \"cblas_dsbmv\"\n cblas_dsbmv_unsafe :: SbmvFunFFI Double Double\nforeign import ccall safe \"cblas_dsbmv\"\n cblas_dsbmv_safe :: SbmvFunFFI Double Double\n--void cblas_ssbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, CInt K, Float alpha, Float *A,\n-- CInt lda, Float *X, CInt incX, Float beta, Float *Y, CInt incY);\n--void cblas_dsbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, CInt K, Double alpha, Double *A,\n-- CInt lda, Double *X, CInt incX, Double beta, Double *Y, CInt incY);\n\n---------------\n--- | packed symmetric matrix * vector product y:= alpha * Av + beta * y\n---------------\ntype SpmvFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> Ptr el -> CInt -> sc -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_sspmv\"\n cblas_sspmv_unsafe :: SpmvFunFFI Float Float\nforeign import ccall safe \"cblas_sspmv\"\n cblas_sspmv_safe :: SpmvFunFFI Float Float\n\nforeign import ccall unsafe \"cblas_dspmv\"\n cblas_dspmv_unsafe :: SpmvFunFFI Double Double\nforeign import ccall safe \"cblas_dspmv\"\n cblas_dspmv_safe :: SpmvFunFFI Double Double\n--void cblas_sspmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *Ap,\n-- Float *X, CInt incX, Float beta, Float *Y, CInt incY);\n--void cblas_dspmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *Ap,\n-- Double *X, CInt incX, Double beta, Double *Y, CInt incY);\n\ntype SprFunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> IO ()\nforeign import ccall unsafe \"cblas_sspr\"\n cblas_sspr_unsafe :: SprFunFFI Float Float\nforeign import ccall safe \"cblas_sspr\"\n cblas_sspr_safe :: SprFunFFI Float Float\n\nforeign import ccall unsafe \"cblas_dspr\"\n cblas_dspr_unsafe :: SprFunFFI Double Double\nforeign import ccall safe \"cblas_dspr\"\n cblas_dspr_safe :: SprFunFFI Double Double\n--void cblas_sspr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *Ap);\n--void cblas_dspr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *Ap);\n\n\ntype Spr2FunFFI sc el =\n CBLAS_ORDERT -> CBLAS_UPLOT -> CInt\n -> sc -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> IO ()\nforeign import ccall unsafe \"cblas_sspr2\"\n cblas_sspr2_unsafe :: Spr2FunFFI Float Float\nforeign import ccall safe \"cblas_sspr2\"\n cblas_sspr2_safe :: Spr2FunFFI Float Float\n\nforeign import ccall unsafe \"cblas_dspr2\"\n cblas_dspr2_unsafe :: Spr2FunFFI Double Double\nforeign import ccall safe \"cblas_dspr2\"\n cblas_dspr2_safe :: Spr2FunFFI Double Double\n--void cblas_sspr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *Y, CInt incY, Float *A);\n--void cblas_dspr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *Y, CInt incY, Double *A);\n\n\n----------------------------------\n---- | (unpacked) symmetric matrix vector product x:=Av, writes result x into v\n---------------------------------\n\ntype SymvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> el -> Ptr el -> CInt ->\n Ptr el -> CInt -> el -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_ssymv\"\n cblas_ssymv_unsafe :: SymvFunFFI Float\nforeign import ccall safe \"cblas_ssymv\"\n cblas_ssymv_safe :: SymvFunFFI Float\n\nforeign import ccall unsafe \"cblas_dsymv\"\n cblas_dsymv_unsafe :: SymvFunFFI Double\nforeign import ccall safe \"cblas_dsymv\"\n cblas_dsymv_safe :: SymvFunFFI Double\n--void cblas_ssymv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *A,\n-- CInt lda, Float *X, CInt incX, Float beta, Float *Y, CInt incY);\n--void cblas_dsymv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *A,\n-- CInt lda, Double *X, CInt incX, Double beta, Double *Y, CInt incY);\n\ntype SyrFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> el -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_ssyr\"\n cblas_ssyr_unsafe :: SyrFunFFI Float\nforeign import ccall safe \"cblas_ssyr\"\n cblas_ssyr_safe :: SyrFunFFI Float\n\nforeign import ccall unsafe \"cblas_dsyr\"\n cblas_dsyr_unsafe :: SyrFunFFI Double\nforeign import ccall safe \"cblas_dsyr\"\n cblas_dsyr_safe :: SyrFunFFI Double\n--void cblas_ssyr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X, CInt incX, Float *A, CInt lda);\n--void cblas_dsyr( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X, CInt incX, Double *A, CInt lda);\n\ntype Syr2FunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CInt -> el -> Ptr el -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_ssyr2\"\n cblas_ssyr2_unsafe :: Syr2FunFFI Float\nforeign import ccall safe \"cblas_ssyr2\"\n cblas_ssyr2_safe :: Syr2FunFFI Float\n\nforeign import ccall unsafe \"cblas_dsyr2\"\n cblas_dsyr2_unsafe :: Syr2FunFFI Double\nforeign import ccall safe \"cblas_dsyr2\"\n cblas_dsyr2_safe :: Syr2FunFFI Double\n--void cblas_ssyr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Float alpha, Float *X,\n-- CInt incX, Float *Y, CInt incY, Float *A, CInt lda);\n--void cblas_dsyr2( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, CInt N, Double alpha, Double *X,\n-- CInt incX, Double *Y, CInt incY, Double *A, CInt lda);\n\n\ntype TbmvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->\n CInt -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_stbmv\"\n cblas_stbmv_unsafe :: TbmvFunFFI Float\nforeign import ccall safe \"cblas_stbmv\"\n cblas_stbmv_safe :: TbmvFunFFI Float\n\nforeign import ccall unsafe \"cblas_dtbmv\"\n cblas_dtbmv_unsafe :: TbmvFunFFI Double\nforeign import ccall safe \"cblas_dtbmv\"\n cblas_dtbmv_safe :: TbmvFunFFI Double\n\nforeign import ccall unsafe \"cblas_ctbmv\"\n cblas_ctbmv_unsafe :: TbmvFunFFI (Complex Float)\nforeign import ccall safe \"cblas_ctbmv\"\n cblas_ctbmv_safe :: TbmvFunFFI (Complex Float)\n\nforeign import ccall unsafe \"cblas_ztbmv\"\n cblas_ztbmv_unsafe :: TbmvFunFFI (Complex Double)\nforeign import ccall safe \"cblas_ztbmv\"\n cblas_ztbmv_safe :: TbmvFunFFI (Complex Double)\n--void cblas_stbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, CInt K, Float *A, CInt lda, Float *X, CInt incX);\n--void cblas_dtbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, CInt K, Double *A, CInt lda, Double *X, CInt incX);\n--void cblas_ctbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, CInt K, Float *A, CInt lda, Float *X, CInt incX);\n--void cblas_ztbmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, CInt K, Double *A, CInt lda, Double *X, CInt incX);\n\n----------------\n--- | solves Ax=v where A is k+1 banded triangular matrix, and x and\n----------------\ntype TbsvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->\n CInt -> CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_stbsv\"\n cblas_stbsv_unsafe :: TbsvFunFFI Float\nforeign import ccall safe \"cblas_stbsv\"\n cblas_stbsv_safe :: TbsvFunFFI Float\n\nforeign import ccall unsafe \"cblas_dtbsv\"\n cblas_dtbsv_unsafe :: TbsvFunFFI Double\nforeign import ccall safe \"cblas_dtbsv\"\n cblas_dtbsv_safe :: TbsvFunFFI Double\n\nforeign import ccall unsafe \"cblas_ctbsv\"\n cblas_ctbsv_unsafe :: TbsvFunFFI (Complex Float)\nforeign import ccall safe \"cblas_ctbsv\"\n cblas_ctbsv_safe :: TbsvFunFFI (Complex Float)\n\nforeign import ccall unsafe \"cblas_ztbsv\"\n cblas_ztbsv_unsafe :: TbsvFunFFI (Complex Double)\nforeign import ccall safe \"cblas_ztbsv\"\n cblas_ztbsv_safe :: TbsvFunFFI (Complex Double)\n--void cblas_stbsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, CInt K, Float *A, CInt lda, Float *X, CInt incX);\n--void cblas_dtbsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, CInt K, Double *A, CInt lda, Double *X, CInt incX);\n--void cblas_ctbsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, CInt K, Float *A, CInt lda, Float *X, CInt incX);\n--void cblas_ztbsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, CInt K, Double *A, CInt lda, Double *X, CInt incX);\n\n\n-------------------------------------------------------------------------\n-- | matrix vector product Av, writes result into v, where A is a packed triangular nxn matrix\n-------------------------------------------------------------------------\ntype TpmvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->\n CInt -> Ptr el -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_stpmv\"\n cblas_stpmv_unsafe :: TpmvFunFFI Float\nforeign import ccall safe \"cblas_stpmv\"\n cblas_stpmv_safe :: TpmvFunFFI Float\n\nforeign import ccall unsafe \"cblas_dtpmv\"\n cblas_dtpmv_unsafe :: TpmvFunFFI Double\nforeign import ccall safe \"cblas_dtpmv\"\n cblas_dtpmv_safe :: TpmvFunFFI Double\n\nforeign import ccall unsafe \"cblas_ctpmv\"\n cblas_ctpmv_unsafe :: TpmvFunFFI (Complex Float)\nforeign import ccall safe \"cblas_ctpmv\"\n cblas_ctpmv_safe :: TpmvFunFFI (Complex Float)\n\nforeign import ccall unsafe \"cblas_ztpmv\"\n cblas_ztpmv_unsafe :: TpmvFunFFI (Complex Double)\nforeign import ccall safe \"cblas_ztpmv\"\n cblas_ztpmv_safe :: TpmvFunFFI (Complex Double)\n--void cblas_stpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, Float *Ap, Float *X, CInt incX);\n--void cblas_dtpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, Double *Ap, Double *X, CInt incX);\n--void cblas_ctpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, Float *Ap, Float *X, CInt incX);\n--void cblas_ztpmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, Double *Ap, Double *X, CInt incX);\n\n--------------------------------------------------\n--- | solve Ax=v where A is a nxn packed triangular matrix, v vector input, writes the solution into x.\n--------------------------------------------------\ntype TpsvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->\n CInt -> Ptr el -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_stpsv\"\n cblas_stpsv_unsafe :: TpsvFunFFI Float\nforeign import ccall safe \"cblas_stpsv\"\n cblas_stpsv_safe :: TpsvFunFFI Float\n\nforeign import ccall unsafe \"cblas_dtpsv\"\n cblas_dtpsv_unsafe :: TpsvFunFFI Double\nforeign import ccall safe \"cblas_dtpsv\"\n cblas_dtpsv_safe :: TpsvFunFFI Double\n\nforeign import ccall unsafe \"cblas_ctpsv\"\n cblas_ctpsv_unsafe :: TpsvFunFFI (Complex Float)\nforeign import ccall safe \"cblas_ctpsv\"\n cblas_ctpsv_safe :: TpsvFunFFI (Complex Float)\n\nforeign import ccall unsafe \"cblas_ztpsv\"\n cblas_ztpsv_unsafe :: TpsvFunFFI (Complex Double)\nforeign import ccall safe \"cblas_ztpsv\"\n cblas_ztpsv_safe :: TpsvFunFFI (Complex Double)\n--void cblas_stpsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, Float *Ap, Float *X, CInt incX);\n--void cblas_dtpsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, Double *Ap, Double *X, CInt incX);\n--void cblas_ctpsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, Float *Ap, Float *X, CInt incX);\n--void cblas_ztpsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag,\n-- CInt N, Double *Ap, Double *X, CInt incX);\n\ntype TrmvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->\n CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\nforeign import ccall unsafe \"cblas_strmv\"\n cblas_strmv_unsafe :: TrmvFunFFI Float\nforeign import ccall safe \"cblas_strmv\"\n cblas_strmv_safe :: TrmvFunFFI Float\n\nforeign import ccall unsafe \"cblas_dtrmv\"\n cblas_dtrmv_unsafe :: TrmvFunFFI Double\nforeign import ccall safe \"cblas_dtrmv\"\n cblas_dtrmv_safe :: TrmvFunFFI Double\n\nforeign import ccall unsafe \"cblas_ctrmv\"\n cblas_ctrmv_unsafe :: TrmvFunFFI (Complex Float)\nforeign import ccall safe \"cblas_ctrmv\"\n cblas_ctrmv_safe :: TrmvFunFFI (Complex Float)\n\nforeign import ccall unsafe \"cblas_ztrmv\"\n cblas_ztrmv_unsafe :: TrmvFunFFI (Complex Double)\nforeign import ccall safe \"cblas_ztrmv\"\n cblas_ztrmv_safe :: TrmvFunFFI (Complex Double)\n--void cblas_strmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Float *A, CInt lda, Float *X, CInt incX);\n--void cblas_dtrmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Double *A, CInt lda, Double *X, CInt incX);\n--void cblas_ctrmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Float *A, CInt lda, Float *X, CInt incX);\n--void cblas_ztrmv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Double *A, CInt lda, Double *X, CInt incX);\n\n--STRSV - solve one of the systems of equations A*x = b, or A'*x = b, where A is a (non)unit upper(/lower) triangular matrix\ntype TrsvFunFFI el = CBLAS_ORDERT -> CBLAS_UPLOT -> CBLAS_TRANSPOSET -> CBLAS_DIAGT ->\n CInt -> Ptr el -> CInt -> Ptr el -> CInt -> IO ()\n\nforeign import ccall unsafe \"cblas_strsv\"\n cblas_strsv_unsafe :: TrsvFunFFI Float\nforeign import ccall safe \"cblas_strsv\"\n cblas_strsv_safe :: TrsvFunFFI Float\n\nforeign import ccall unsafe \"cblas_dtrsv\"\n cblas_dtrsv_unsafe :: TrsvFunFFI Double\nforeign import ccall safe \"cblas_dtrsv\"\n cblas_dtrsv_safe :: TrsvFunFFI Double\n\nforeign import ccall unsafe \"cblas_ctrsv\"\n cblas_ctrsv_unsafe :: TrsvFunFFI (Complex Float)\nforeign import ccall safe \"cblas_ctrsv\"\n cblas_ctrsv_safe :: TrsvFunFFI (Complex Float)\n\nforeign import ccall unsafe \"cblas_ztrsv\"\n cblas_ztrsv_unsafe :: TrsvFunFFI (Complex Double)\nforeign import ccall safe \"cblas_ztrsv\"\n cblas_ztrsv_safe :: TrsvFunFFI (Complex Double)\n\n--void cblas_strsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Float *A, CInt lda, Float *X, CInt incX);\n--void cblas_dtrsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Double *A, CInt lda, Double *X, CInt incX);\n--void cblas_ctrsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Float *A, CInt lda, Float *X, CInt incX);\n--void cblas_ztrsv( enum CBLAS_ORDER order, enum CBLAS_UPLO Uplo, enum CBLAS_TRANSPOSE TransA, enum CBLAS_DIAG Diag, CInt N, Double *A, CInt lda, Double *X, CInt incX);\n\n\n", "meta": {"hexsha": "50b4185275e0ef13f4b21d40d2ada2c54c87342d", "size": 29995, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level2.hs", "max_stars_repo_name": "schnecki/hblas", "max_stars_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-05-03T23:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-17T22:58:54.000Z", "max_issues_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level2.hs", "max_issues_repo_name": "schnecki/hblas", "max_issues_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-01-24T13:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T22:15:09.000Z", "max_forks_repo_path": "src/Numerical/HBLAS/BLAS/FFI/Level2.hs", "max_forks_repo_name": "schnecki/hblas", "max_forks_repo_head_hexsha": "b551e74ec278503d45bcd341c8c71a1f06558d92", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-01-09T12:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T19:37:37.000Z", "avg_line_length": 55.4436229205, "max_line_length": 183, "alphanum_fraction": 0.6760460077, "num_tokens": 10006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788308, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3720809738798834}} {"text": "{-# LANGUAGE GADTs, TypeFamilies,\n StandaloneDeriving, UndecidableInstances,\nScopedTypeVariables, FlexibleInstances, DataKinds,\nFunctionalDependencies, PolyKinds, \nTypeOperators, RankNTypes, MultiParamTypeClasses,\n TypeApplications, FlexibleContexts, AllowAmbiguousTypes #-}\n-- AllowAmbiguousTypes, ImpredicativeTypes, InstanceSigs, NoImplicitPrelude,\n\nmodule Fib where\n\nimport Vec\nimport Data.Complex\nimport Control.Monad ((<=<))\nimport GHC.TypeNats\nimport Data.Proxy\n\n\n-- data FibAnyon = Id | Tau\n-- I started using DataKinds and it ended up being a problem.\n\n\ndata Tau\n--data Id\ntype Id = ()\ndata FibTree root leaves where\n TTT :: FibTree Tau l -> FibTree Tau r -> FibTree Tau (l,r)\n ITT :: FibTree Tau l -> FibTree Tau r -> FibTree Id (l,r) \n TIT :: FibTree Id l -> FibTree Tau r -> FibTree Tau (l,r)\n TTI :: FibTree Tau l -> FibTree Id r -> FibTree Tau (l,r)\n III :: FibTree Id l -> FibTree Id r -> FibTree Id (l,r)\n TLeaf :: FibTree Tau Tau\n ILeaf :: FibTree Id Id\n\n-- pretty printing would be hella nice\nderiving instance Show (FibTree a b)\nderiving instance Eq (FibTree a b)\n\ninstance Ord (FibTree a b) where\n compare (ITT l r) (ITT l' r') | l < l' = LT\n | l > l' = GT\n | otherwise = compare r r' \n compare (ITT _ _) _ = LT\n compare _ (ITT _ _) = GT\n compare (TTI l r) (TTI l' r') | l < l' = LT\n | l > l' = GT\n | otherwise = compare r r' \n compare (TIT l r) (TIT l' r') | l < l' = LT\n | l > l' = GT\n | otherwise = compare r r' \n compare (TTT l r) (TTT l' r') | l < l' = LT\n | l > l' = GT\n | otherwise = compare r r' \n compare (III l r) (III l' r') | l < l' = LT\n | l > l' = GT\n | otherwise = compare r r' \n \n compare (TTI _ _) _ = LT\n compare _ (TTI _ _) = GT\n compare (TIT _ _) _ = LT\n compare _ (TIT _ _) = GT\n compare (TTT _ _) _ = LT\n compare _ (TTT _ _) = GT\n compare (III _ _) _ = LT\n compare _ (III _ _) = GT\n compare TLeaf TLeaf = EQ\n compare ILeaf ILeaf = EQ\n\nlmap :: (forall a. FibTree a b -> Q (FibTree a c)) -> (FibTree e (b,d) -> Q (FibTree e (c,d)))\nlmap f (ITT l r) = fmap (\\l' -> ITT l' r) (f l)\nlmap f (TTI l r) = fmap (\\l' -> TTI l' r) (f l)\nlmap f (TIT l r) = fmap (\\l' -> TIT l' r) (f l)\nlmap f (TTT l r) = fmap (\\l' -> TTT l' r) (f l)\nlmap f (III l r) = fmap (\\l' -> III l' r) (f l)\n\nrmap :: (forall a. FibTree a b -> Q (FibTree a c)) -> (FibTree e (d,b) -> Q (FibTree e (d,c)))\nrmap f (ITT l r) = fmap (\\r' -> ITT l r') (f r)\nrmap f (TTI l r) = fmap (\\r' -> TTI l r') (f r)\nrmap f (TIT l r) = fmap (\\r' -> TIT l r') (f r)\nrmap f (TTT l r) = fmap (\\r' -> TTT l r') (f r)\nrmap f (III l r) = fmap (\\r' -> III l r') (f r)\n\nbraid :: FibTree a (l,r) -> Q (FibTree a (r,l))\nbraid (ITT l r) = W [(ITT r l, cis $ 4 * pi / 5)] -- different scalar factors for trivial and non trivial fusion\nbraid (TTT l r) = W [(TTT r l, (cis $ - 3 * pi / 5))]\nbraid (TTI l r) = pure $ TIT r l-- exchange with trivial means nothing\nbraid (TIT l r) = pure $ TTI r l\nbraid (III l r) = pure $ III r l\n\n-- The inverse of braid\nbraid' :: FibTree a (l,r) -> Q (FibTree a (r,l))\nbraid' = star . braid\n\ntau :: Complex Double\ntau = ((sqrt 5) - 1) / 2 :+ 0 -- 0.618 :+ 0\n\nfmove :: FibTree a (c,(d,e)) -> Q (FibTree a ((c,d),e))\n-- fmove (ITT a (TTI b c)) = pure $ ITI ( TTT a b) c -- pure (auto (auto a b) c) -- no maybe not. The internal one isn't auto\nfmove (ITT a (TIT b c)) = pure $ ITT ( TTI a b) c\nfmove (ITT a (TTT b c)) = pure $ ITT ( TTT a b) c\nfmove (ITT a (TTI b c)) = pure $ III ( ITT a b) c\n\n\n\nfmove (TIT a (TTT b c)) = pure $ TTT ( TIT a b) c\nfmove (TIT a (TTI b c)) = pure $ TTI ( TIT a b) c\nfmove (TIT a (TIT b c)) = pure $ TIT ( III a b) c\n\n-- fmove (TIT a (TIT b c)) = TTT ( III a b) c\n-- the nontrivial ones have all tau on the leafs and root \n-- internal I\nfmove (TTI a (III b c)) = pure $ TTI ( TTI a b) c\nfmove (TTI a (ITT b c)) = W [(TIT ( ITT a b) c, tau) , (TTT ( TTT a b) c, sqrt tau)]\n-- internal T\nfmove (TTT a (TTT b c)) = W [(TIT ( ITT a b) c, sqrt tau) , (TTT ( TTT a b) c, - tau )]\nfmove (TTT a (TTI b c)) = pure $ TTI ( TTT a b) c\nfmove (TTT a (TIT b c)) = pure $ TTT ( TTI a b) c \n\nfmove (III a (ITT b c)) = pure $ ITT ( TIT a b) c\nfmove (III a (III b c)) = pure $ III ( III a b) c\n\n\n-- largely just a tranpose of the above case.\nfmove' :: FibTree a ((c,d),e) -> Q (FibTree a (c,(d,e)))\nfmove' (ITT ( TTI a b) c) = pure $ (ITT a (TIT b c))\nfmove' (ITT ( TTT a b) c) = pure $ (ITT a (TTT b c))\nfmove' (ITT ( TIT a b) c) = pure $ (III a (ITT b c))\n\n--fmoveq (ITT a (TTT b c)) = pure $ \n\nfmove' (TTI ( TTT a b) c) = pure $ (TTT a (TTI b c))\nfmove' (TTI ( TTI a b) c) = pure $ (TTI a (III b c))\nfmove' (TTI ( TIT a b) c) = pure $ TIT a (TTI b c)\n--fmoveq (TTT a (TTI b c)) = pure $ TTI ( TTT a b) c\n\n\n\n--fmoveq (TTT a (TIT b c)) = pure $ TTT ( TTI a b) c \nfmove' (TIT ( ITT a b) c) = W [(TTI a (ITT b c), tau) , (TTT a (TTT b c) , sqrt tau)]\nfmove' (TIT ( III a b) c ) = pure $ TIT a (TIT b c)\n\n\nfmove' (TTT ( TTI a b) c ) = pure $ TTT a (TIT b c)\nfmove' (TTT ( TIT a b) c ) = pure $ TIT a (TTT b c)\nfmove' (TTT ( TTT a b) c) = W [(TTI a (ITT b c), sqrt tau) , (TTT a (TTT b c), - tau )]\n\nfmove' (III ( III a b) c ) = pure $ III a (III b c)\nfmove' (III ( ITT a b) c ) = pure $ ITT a (TTI b c)\n\n\nrightUnit :: FibTree e (a,Id) -> Q (FibTree e a)\nrightUnit (TTI t _) = pure t\nrightUnit (III t _) = pure t\n\nrightUnit' :: FibTree e a -> Q (FibTree e (a,Id))\nrightUnit' t@(TTT _ _) = pure (TTI  t ILeaf)\nrightUnit' t@(TTI _ _) = pure (TTI  t ILeaf)\nrightUnit' t@(TIT _ _) = pure (TTI  t ILeaf)\nrightUnit' t@(III _ _) = pure (III  t ILeaf)\nrightUnit' t@(ITT _ _) = pure (III  t ILeaf)\nrightUnit' t@(ILeaf) = pure (III t ILeaf)\nrightUnit' t@(TLeaf) = pure (TTI t ILeaf)\n\nleftUnit :: FibTree e (Id,a) -> Q (FibTree e a)\nleftUnit = rightUnit <=< braid\n\n-- braid vs braid' doesn't matter, but it has a nice symmettry.\nleftUnit' :: FibTree e a -> Q (FibTree e (Id,a))\nleftUnit' = braid' <=< rightUnit' \n\n\ndot :: FibTree a (b, c) -> FibTree a' (b, c) -> Q (FibTree a' a)\ndot x@(TTI _ _) y@(TTI _ _) | x == y = pure TLeaf\n | otherwise = mempty\ndot x@(TIT _ _) y@(TIT _ _) | x == y = pure TLeaf\n | otherwise = mempty\ndot x@(TTT _ _) y@(TTT _ _) | x == y = pure TLeaf\n | otherwise = mempty\ndot x@(III _ _) y@(III _ _) | x == y = pure ILeaf\n | otherwise = mempty\ndot x@(ITT _ _) y@(ITT _ _) | x == y = pure ILeaf\n | otherwise = mempty\ndot _ _ = mempty \n\n\nclass AllTrees a b where\n allTrees :: [FibTree a b]\ninstance AllTrees Tau Tau where\n allTrees = [TLeaf]\ninstance AllTrees Id Tau where\n allTrees = []\ninstance AllTrees Tau Id where\n allTrees = []\ninstance AllTrees Id Id where\n allTrees = [ILeaf]\ninstance (AllTrees Tau a, \n AllTrees Id a,\n AllTrees Tau b, \n AllTrees Id b) => AllTrees Id (a,b) where\n allTrees = (III <$> ia <*> ib) <> (ITT <$> ta <*> tb) where\n ta = allTrees @Tau @a\n ia = allTrees @Id @a\n tb = allTrees @Tau @b\n ib = allTrees @Id @b\ninstance (AllTrees Tau a, \n AllTrees Id a,\n AllTrees Tau b, \n AllTrees Id b) => AllTrees Tau (a,b) where\n allTrees = (TIT <$> ia <*> tb) <> (TTI <$> ta <*> ib) <> (TTT <$> ta <*> tb) where\n ta = allTrees @Tau @a\n ia = allTrees @Id @a\n tb = allTrees @Tau @b\n ib = allTrees @Id @b\nt9 = allTrees @Tau @((Tau,Tau),Tau)\n\n-- Resulting type depends on input\n-- I think a typefamily type computation might be necessary? \n-- pullLeft and pullRight might not need a type class.\n-- pullLeft (TTT l r) = fmove (TTT pl r)\n-- where pl = pullLeft l\n{-\ntype family Assoc a where\n Assoc ((a,b),c) = (a,(b,c))\n\ntype family PullLeft a where\n PullLeft ((a,b),c) = Assoc (PullLeft (a, b), c)\n PullLeft a = a \n\n\ntype Test1 = PullLeft (((Int,Int),Int),Int)\npullLeft :: forall a b c. (c ~ PullLeft b) => FibTree a b -> Q (FibTree a c)\npullLeft TLeaf = pure Tleaf\npullLeft ILeaf = pure ILeaf\npullLeft t = do \n t' <- lmap pullLeft t\n fmove' t'\n\n\npullLeft t@(ITT l r) = helper t\npullLeft t@(TTT l r) = helper t\npullLeft t@(TTI l r) = helper t\npullLeft t@(TIT l r) = helper t\npullLeft t@(III l r) = helper t where\n helper :: (d ~ PullLeft (b,c)) => FibTree a (b,c) -> Q (FibTree a d)\n helper t = do \n t' <- lmap pullLeft t\n fmove' t'\n\n-}\n\n\n{-\nSpiritually this function is this. Can't write it this way unforturnately\n-- There are typing problems\n-- this isn't even right\n-- we need to pattern match on ((),)\npullLeft TLeaf = pure Tleaf\npullLeft ILeaf = pure ILeaf\npullLeft t = do \n t' <- lmap pullLeft t\n fmove' t'\n\n-- but actually a two level tree desctruct\n--treeDestruct()\n\n-}\n{-\ntype family Assoc a where\n Assoc ((a,b),c) = (a,(b,c))\n \n type family PullLeft' a where\n PullLeft' ((a,b),c) = Assoc (PullLeft' (a, b), c)\n PullLeft' a = a \n -}\n-- could seperate the typeclass so that I'm using type families instead.\n\nclass PullLeftLeaf a b | a -> b where \n pullLeftLeaf :: FibTree c a -> Q (FibTree c b)\ninstance PullLeftLeaf (Tau,c) (Tau,c) where\n pullLeftLeaf = pure\ninstance PullLeftLeaf (Id,c) (Id,c) where\n pullLeftLeaf = pure\ninstance PullLeftLeaf Tau Tau where\n pullLeftLeaf = pure\ninstance PullLeftLeaf Id Id where\n pullLeftLeaf = pure\ninstance (PullLeftLeaf (a,b) (a',b'), \n r ~ (a',(b',c))) => PullLeftLeaf ((a, b),c) r where\n pullLeftLeaf t = do \n t' <- lmap pullLeftLeaf t\n fmove' t'\n\n\nclass PullRightLeaf a b | a -> b where -- | a -> b functional dependency causes errors?\n pullRightLeaf :: FibTree c a -> Q (FibTree c b)\n{-\ninstance (PullRightLeaf a a', r ~ ((b,c),a')) => PullRightLeaf ((b,c),a) r where\npullRightLeaf t = rmap pullRightLeaf t\n-}\ninstance PullRightLeaf Tau Tau where\n pullRightLeaf = pure\n\ninstance PullRightLeaf Id Id where\n pullRightLeaf = pure\n\n\ninstance PullRightLeaf (c,Tau) (c,Tau) where\n pullRightLeaf = pure\n\ninstance PullRightLeaf (c,Id) (c,Id) where\n pullRightLeaf = pure\n\ninstance (PullRightLeaf (a,b) (a',b'), r ~ ((c,a'),b')) => PullRightLeaf (c,(a, b)) r where\n pullRightLeaf t = do \n t' <- rmap pullRightLeaf t\n fmove t'\n\nclass RightAssoc a b | a -> b where \n rightAssoc :: FibTree c a -> Q (FibTree c b)\ninstance RightAssoc Tau Tau where\n rightAssoc = pure\ninstance RightAssoc Id Id where\n rightAssoc = pure\ninstance (PullLeftLeaf (a,b) (a',b'),\n RightAssoc b' b'',\n r ~ (a', b'')) => RightAssoc (a,b) r where\n rightAssoc t = do \n t' <- pullLeftLeaf t\n rmap rightAssoc t'\n-- usually you'll want to force not the root, but the leaves to be some type\n-- hence the ordering b c d a for type application\nbmove :: forall b c d a. FibTree a (b,(c,d)) -> Q (FibTree a (c,(b,d)))\nbmove t = do\n t' :: FibTree a ((b,c),d) <- fmove t\n t'' :: FibTree a ((c,b),d) <- lmap braid t'\n fmove' t'' \nbmove' :: forall b c d a. FibTree a (b,(c,d)) -> Q (FibTree a (c,(b,d)))\nbmove' = fmove' <=< (lmap braid') <=< fmove\n\n-- Therei s a general pattern for digging into\n-- n and a tell us b, the subpiece of a\n-- c and a and n tell use what a looks like with b replaced = d\n--data Nat = Z | S Nat\n\nrmapN :: forall n gte s t a b e. (RMapN n gte s t a b, gte ~ (CmpNat n 0)) => (forall r. FibTree r a -> Q (FibTree r b)) -> (FibTree e s) -> Q (FibTree e t)\nrmapN f t = rmapN' @n @gte f t\n\nclass RMapN n gte s t a b | n gte s b -> a t where\n rmapN' :: (forall r. FibTree r a -> Q (FibTree r b)) -> (FibTree e s) -> Q (FibTree e t)\ninstance (a ~ s, b ~ t) => RMapN 0 'EQ s t a b where\n rmapN' f t = f t -- rmapN = id\ninstance (RMapN (n-1) gte r r' a b, \n gte ~ (CmpNat (n-1) 0),\n t ~ (l,r')) => RMapN n 'GT (l,r) t a b where\n rmapN' f t = rmap (rmapN @(n-1) f) t\n{-\nbmoveN :: forall n a b c d e f. RMapN n a (b, (c, d)) (c, (b, d)) e => FibTree f a -> Q (FibTree f e)\nbmoveN t = rmapN @n (bmove @b @c @d) t\n\n-- dotN :: forall n a b c d e f. dot :: FibTree a (b, c) -> FibTree a' (b, c) -> Q (FibTree a' a)\nfuseN :: forall n a b c d e f g. RMapN n f (b,(c,d)) (a,d) g => FibTree a (b, c) -> FibTree e f -> Q (FibTree e g)\nfuseN q t = rmapN @n f t where\n f :: forall r. FibTree r (b,(c,d)) -> Q (FibTree r (a,d))\n f t' = do \n t'' <- fmove t'\n lmap (dot q) t''\n-}\n\ntype family Count a where\n Count Tau = 1\n Count Id = 1\n Count (a,b) = (Count a) + (Count b)\n \ntype family LeftCount a where\n LeftCount (a,b) = Count a\n\nlcamap :: forall n s t a b e gte .\n (gte ~ CmpNat (LeftCount s) n,\n LCAMap n gte s t a b)\n => (forall r. FibTree r a -> Q (FibTree r b)) -> (FibTree e s) -> Q (FibTree e t)\nlcamap f t = lcamap' @n @gte f t\n\nclass LCAMap n gte s t a b | n gte s b -> t a where\n lcamap' :: (forall r. FibTree r a -> Q (FibTree r b)) -> (FibTree e s) -> Q (FibTree e t)\n \n\ninstance (n' ~ (n - Count l), -- We're searching in the right subtree. Subtract the leaf number in the left subtree\n lc ~ (LeftCount r), -- dip one level down to order which way we have to go next\n gte ~ (CmpNat lc n'), -- Do we go left, right or have we arrived in the next layer?\n LCAMap n' gte r r' a b, -- recursive call\n t ~ (l,r') -- reconstruct total return type from recursive return type. Left tree is unaffected by lcamapping\n ) => LCAMap n 'LT (l,r) t a b where\n lcamap' f x = rmap (lcamap @n' f) x\n \ninstance (lc ~ (LeftCount l),\n gte ~ (CmpNat lc n),\n LCAMap n gte l l' a b,\n t ~ (l',r)\n ) => LCAMap n 'GT (l,r) t a b where\n lcamap' f x = lmap (lcamap @n f) x\n \ninstance (t ~ b, a ~ s) => LCAMap n 'EQ s t a b where -- Base case\n lcamap' f x = f x\n\n\n\nclass Twiddle s t a b | s b -> t a where\n twiddle :: (forall r. FibTree r a -> Q (FibTree r b)) -> FibTree e s -> Q (FibTree e t)\n \ninstance Twiddle ((l,x),(y,r)) ((l,c),r) (x,y) c where\n twiddle f x = do\n x' <- fmove x -- (((l',x),y),r')\n x'' <- lmap fmove' x' -- ((l',(x,y)),r')\n lmap (rmap f) x''\ninstance Twiddle (Tau, (y,r)) (c,r) (Tau, y) c where\n twiddle f x = fmove x >>= lmap f\ninstance Twiddle (Id, (y,r)) (c,r) (Id, y) c where\n twiddle f x = fmove x >>= lmap f\ninstance Twiddle ((l,x), Tau) (l,c) (x,Tau) c where\n twiddle f x = fmove' x >>= rmap f\ninstance Twiddle ((l,x), Id) (l,c) (x,Id) c where\n twiddle f x = fmove' x >>= rmap f\ninstance Twiddle (Tau, Tau) c (Tau,Tau) c where\n twiddle f x = f x \ninstance Twiddle (Id, Id) c (Id,Id) c where\n twiddle f x = f x \ninstance Twiddle (Tau, Id) c (Tau,Id) c where\n twiddle f x = f x \ninstance Twiddle (Id, Tau) c (Id,Tau) c where\n twiddle f x = f x \n\nnmap :: forall (n :: Nat) s t a b a' b' l l' r r' e gte.\n (gte ~ CmpNat (LeftCount s) n,\n LCAMap n gte s t a' b',\n a' ~ (l,r),\n PullRightLeaf l l',\n PullLeftLeaf r r',\n Twiddle (l',r') b' a b) => \n (forall r. FibTree r a -> Q (FibTree r b)) -> FibTree e s -> Q (FibTree e t)\nnmap f z = lcamap @n @s @t @a' @b' (\\x -> do\n x' <- lmap pullRightLeaf x\n x'' <- rmap pullLeftLeaf x' \n twiddle f x'') z\n\nt1 = nmap @2 braid (TTT (TTI TLeaf ILeaf) (TTT TLeaf TLeaf)) \nt5 = nmap @2 pure (TTT (TTI TLeaf ILeaf) (TTT TLeaf TLeaf)) >>= nmap @3 pure\nt2 = nmap @1 braid (TTT (TTI TLeaf ILeaf) (TTT TLeaf TLeaf)) \nt4 = nmap @1 braid (TTT TLeaf (TTT TLeaf TLeaf)) \nt3 = nmap @2 braid (TTT (TTT (TTT TLeaf TLeaf) TLeaf) (TTT TLeaf TLeaf)) \nt6 = rightAssoc (TTT (TTT (TTT TLeaf TLeaf) TLeaf) (TTT TLeaf TLeaf)) \nt7 = t6 >>= bmove\nt8 = t6 >>= rmapN @0 bmove\n-- For the category, we probably don't want the association structure.\n-- '[Tau, Id, Tau, Id] typelevel list of particles\n-- \n\nttt = TTT TLeaf TLeaf\nexample = starttree >>=\n nmap @1 braid >>=\n nmap @2 braid >>=\n nmap @1 (dot ttt) >>=\n nmap @1 braid' >>=\n nmap @2 (dot ttt) >>=\n nmap @1 (dot ttt) where\n starttree = pure (TTT (TTT TLeaf\n (TTT TLeaf \n TLeaf))\n TLeaf\n )\n-- would be nice to use an unknot\n-- example2 = \n-- I should use neighbormap for this.\n-- maybe I should call f fuse and make it global?\n\n-- bmoveN t = rmapN @n (bmove :: forall r. FibTree r (b,(c,d)) -> Q (FibTree r (c,(b,d)))) t\n-- bmoveN t = rmapN @n @a @(b, (c, d)) @(c, (b, d)) @e bmove t\n\n\n{-\nbmoveN :: forall n a b c d e f. RMapN n a (b, (c, d)) (c, (b, d)) e => Proxy n -> FibTree f a -> Q (FibTree f e)\nbmoveN p t = rmapN p (bmove :: FibTree a (b,(c,d)) -> Q (FibTree a (c,(b,d)))) t\n-}\n {- do\n t' <- fmove t\n t'' <- lmap braid' t'\n fmove' t'' \n-}\n\n -- \n{-\npullLeftLeaf\npullRightLeaf\n\n\n-}\n{-\nclass Standardize a b | a -> b where\n standardize :: FibTree c a -> Q (FibTree c b)\n\ninstance Standardize a b where\n\ntype family Append a b where\n Append (a,b) c = (a, Append b c)\n Append a c = (a, c)\n\ntype family Leftize where\n Leftize (a,b) = Append (Leftize a) (Leftize b)\n Leftize a = a \n\nfullrightassoc = standardize\ncompleterightassoc\nbmove = fmove braid fmove'\n\nstandardize :: FibTree c a -> Q (FibTree c (Leftize a))\nstandardize (TLeaf) = TLeaf\nstandardize (ILeaf) = ILeaf\nstandardize t = do \n x <- pullLeft t\n rmap standardize x\n\nlcamap :: FibTree a b -> Proxy (a :: Int) -> FibTree a ?\nlcamap f n t@(TTT l r) | count l == n = f t\n | count l < n = lcamap f (n - count l) r\n | otherwise = lcamap f n l \n\n\npullRight ()\n\n\n\n\ntreerecursor :: FibTree a b -> (l -> r -> c) -> (leaf -> c) -> c\ntreerecursor (TTT l r) f g = f l r\ntreerecursor (TLeaf) = g Tleaf \n\n-}", "meta": {"hexsha": "4bfdf741c7d0cbed8f492f43313bb87c14a65e51", "size": 18514, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fib.hs", "max_stars_repo_name": "philzook58/fib-anyon", "max_stars_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-01-14T10:48:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T08:35:00.000Z", "max_issues_repo_path": "src/Fib.hs", "max_issues_repo_name": "philzook58/fib-anyon", "max_issues_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fib.hs", "max_forks_repo_name": "philzook58/fib-anyon", "max_forks_repo_head_hexsha": "5c81535201ffdd5a40db18510ce894be9ccccbd7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-11-15T07:42:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-02T15:15:28.000Z", "avg_line_length": 34.6056074766, "max_line_length": 156, "alphanum_fraction": 0.5403478449, "num_tokens": 6676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.37180063583660294}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule Numeric.Optimization.TwoPhase.Tableau\n ( -- * Tableaus\n Tableau\n , IsTableau\n , mkPhaseI\n , mkPhaseII\n , maximizeEntering\n , maximizeOptimal\n , minimizeEntering\n , minimizeOptimal\n , phaseIEntering\n , phaseIOptimal\n , tableauInfeasible\n , tableauLeaving\n , tableauResult\n , tableauStep\n ) where\n\nimport Data.Finite (Finite)\nimport qualified Data.List as List\nimport Data.Maybe (fromJust)\nimport Data.Ord (comparing)\nimport qualified Data.Vector.Sized as Vec\nimport qualified Data.Vector.Storable.Sized as SVec\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra (Extractor(..), (??))\nimport qualified Numeric.LinearAlgebra as LA\nimport Numeric.LinearAlgebra.Static (L)\nimport qualified Numeric.LinearAlgebra.Static as LS\nimport qualified Numeric.LinearAlgebra.Static.Vector as LS\nimport Text.Printf (printf)\nimport Unsafe.Coerce (unsafeCoerce)\n\nimport Numeric.Optimization.Problem\nimport Numeric.Optimization.TwoPhase.Tableau.Build\nimport Numeric.Optimization.TwoPhase.Tableau.Pivot\nimport Numeric.Optimization.TwoPhase.Tableau.VarMap\nimport Numeric.Optimization.TwoPhase.Types\n\n\ntype IsTableau p v s a c =\n ( KnownNat v\n , KnownNat s\n , KnownNat a\n , KnownNat c\n , KnownNat (Rows p c)\n , KnownNat (Cols p v s a)\n )\n\n\ndata Tableau (p :: Phase) (d :: Direction) v s a c =\n Tableau\n { varMap :: VarMap (Rows p c) (Cols p v s a)\n , table :: L (Rows p c) (Cols p v s a)\n }\n\n\ninstance (IsTableau p v s a c) => Show (Tableau p d v s a c) where\n show (Tableau vs x) = unlines (cols : rows)\n where\n cols = concatMap (printf \"%8s\" . show)\n . Vec.toList $ columnVars vs\n\n rows = zipWith (printf \"%s %s\") rowVals rowNames\n rowVals = lines . LA.format \"\" (printf \"%8.2f\") $ LS.unwrap x\n rowNames = Vec.toList . Vec.map show $ rowVars vs\n\n\nmkPhaseI\n :: (IsTableau 'PhaseI v s a c)\n => Problem d v s a c\n -> Tableau 'PhaseI d v s a c\nmkPhaseI x =\n Tableau (mkVarMap x) (mkTable x)\n\n\nmkPhaseII\n :: forall d v s a c.\n ( IsTableau 'PhaseI v s a c\n , IsTableau 'PhaseII v s a c\n )\n => Tableau 'PhaseI d v s a c\n -> Tableau 'PhaseII d v s a c\nmkPhaseII (Tableau vs x) =\n Tableau (VarMap newRows newColumns) newMatrix\n where\n newRows = Vec.tail . unsafeCoerce $ rowVars vs\n\n newColumns =\n let is = fromJust $ Vec.fromList indices\n in Vec.backpermute (columnVars vs) is\n\n newMatrix =\n let xs = LS.unwrap x ?? (Drop 1, Pos (LA.idxs indices))\n in fromJust $ LS.create xs\n\n indices = fromIntegral <$> findIndicesColumns isPhaseII vs\n isPhaseII n = n /= Objective PhaseI && not (isArtificial n)\n\n\n-- Read the value associated with a variable in the tableau. If the variable is\n-- in the basis (has a row in the tableau), it's value is the value in the RHS\n-- of that row divided by the value in the variable's column in that row. If\n-- the variable is not in the basis it has a value of 0 (non-basic).\n--\nreadValue\n :: (IsTableau p v s a c)\n => VarName\n -> Tableau p d v s a c\n -> Double\nreadValue n (Tableau vs x) =\n case (valRowIx, valColIx, rhsColIx) of\n (Just i, Just j, Just r) -> index (i, r) x / index (i, j) x\n (Nothing, Just _, Just _) -> 0\n _ -> error \"readValue: Variable not in tableau\"\n where\n valRowIx = elemIndexRows n vs\n valColIx = elemIndexColumns n vs\n rhsColIx = elemIndexColumns RHS vs\n\n\n-- Read the value associated with the current objective and each decision\n-- variable, and store them in the Vars type for this solver. This is what is\n-- returned when optimization succeeds.\n--\ntableauResult\n :: (IsTableau p v s a c)\n => Tableau p d v s a c\n -> TwoPhaseResult d v\ntableauResult x =\n TwoPhaseResult . Vec.zip names $ Vec.map toValue names\n where\n toValue i = readValue i x\n names = fromJust . Vec.fromList . findColumns isVar $ varMap x\n\n isVar n =\n let objective = indexColumns 0 (varMap x)\n in n == objective || isDecision n\n\n\n-- A phase I tableau is infeasible if the value of the objective function is\n-- greater than 0. This means that at least one artificial variable has to be\n-- non-zero, so there can be no feasible BFS to start phase II from.\n--\ntableauInfeasible\n :: (IsTableau 'PhaseI v s a c)\n => Tableau 'PhaseI d v s a c\n -> Bool\ntableauInfeasible x\n | phaseIOptimal x = readValue (Objective PhaseI) x /= 0\n | otherwise = False\n\n\n-- A tableau is optimal if the given test passes for each cell corresponding to\n-- a variable (everything apart from columns for objectives and the RHS column)\n-- in the current objective.\n--\ntableauOptimal\n :: (IsTableau p v s a c)\n => (Double -> Bool)\n -> Tableau p d v s a c\n -> Bool\ntableauOptimal f (Tableau vs x) =\n SVec.and . SVec.imap optimal . LS.rVec . head . Vec.toList $ LS.lRows x\n where\n coeffs = findIndicesColumns isCoeff vs\n isCoeff = not . isSpecial\n\n optimal i a\n | i `elem` coeffs = f a\n | otherwise = True\n\n\n-- A phase I problem is always a minimization. This is a separate function\n-- from 'minimizeOptimal' as the problem being solved in phase II may not be\n-- a minimization problem.\n--\nphaseIOptimal\n :: (IsTableau 'PhaseI v s a c)\n => Tableau 'PhaseI d v s a c\n -> Bool\nphaseIOptimal =\n tableauOptimal (<= 0)\n\n\n-- A phase II problem which is a maximization is optimal when all coefficients\n-- in the objective function are non-negative.\n--\nmaximizeOptimal\n :: (IsTableau 'PhaseII v s a c)\n => Tableau 'PhaseII 'Max v s a c\n -> Bool\nmaximizeOptimal =\n tableauOptimal (>= 0)\n\n\n-- A phase I problem which is a minimization is optimal when all coefficients\n-- in the objective function are non-negative.\n--\nminimizeOptimal\n :: (IsTableau 'PhaseII v s a c)\n => Tableau 'PhaseII 'Min v s a c\n -> Bool\nminimizeOptimal =\n tableauOptimal (<= 0)\n\n\n-- The entering variable is the lowest indexed variable where the value in the\n-- objective column passes a test, and the name of the variable passes another\n-- test. The tests change depending on the phase, and whether the optimization\n-- is a maximization or a minimization.\n--\nenteringVar\n :: (IsTableau p v s a c)\n => (Finite (Cols p v s a) -> Bool)\n -> (VarName -> Bool)\n -> Tableau p d v s a c\n -> Either TwoPhaseError (Finite (Cols p v s a))\nenteringVar validCol validVar (Tableau vs _) =\n case filter canEnter columns of\n [] -> Left NoEntering\n xs -> Right . fst $ List.minimumBy (comparing snd) xs\n where\n canEnter (j, n) = validCol j && validVar n\n columns = Vec.toList . Vec.indexed $ columnVars vs\n\n\n-- In phase I, the entering variable must be a positive value, as the problem\n-- is a minimization. Artificial variables are still in the table at this\n-- point, so the valid variable test must make sure artificial variables cannot\n-- enter the basis (as they should be non-basic).\n--\nphaseIEntering\n :: (IsTableau 'PhaseI v s a c)\n => Tableau 'PhaseI d v s a c\n -> Either TwoPhaseError (Finite (Cols 'PhaseI v s a))\nphaseIEntering x =\n enteringVar validCol validVar x\n where\n validCol j = index (0, j) (table x) > 0\n validVar n = isDecision n || isSlack n\n\n\n-- When maximizing, the variable to enter the basis is the lowest indexed\n-- variable with a negative coefficient in the objective function row.\n--\nmaximizeEntering\n :: (IsTableau 'PhaseII v s a c)\n => Tableau 'PhaseII 'Max v s a c\n -> Either TwoPhaseError (Finite (Cols 'PhaseII v s a))\nmaximizeEntering x =\n enteringVar validCol validVar x\n where\n validCol j = index (0, j) (table x) < 0\n validVar = not . isSpecial\n\n\n-- When minimizing, the variable to enter the basis is the lowest indexed\n-- variable with a positive coefficient in the objective function row.\n--\nminimizeEntering\n :: (IsTableau 'PhaseII v s a c)\n => Tableau 'PhaseII 'Min v s a c\n -> Either TwoPhaseError (Finite (Cols 'PhaseII v s a))\nminimizeEntering x =\n enteringVar validCol validVar x\n where\n validCol j = index (0, j) (table x) > 0\n validVar = not . isSpecial\n\n\n-- The variable to leave the basis is the lowest indexed variable which has\n-- the minimum ratio between it's coefficient and the RHS value. A variable\n-- with a coefficient of 0 is not allowed to leave (as the ratio is infinite).\n-- This function is the same regardless of the direction of optimization.\n--\ntableauLeaving\n :: (IsTableau p v s a c)\n => Finite (Cols p v s a)\n -> Tableau p d v s a c\n -> Either TwoPhaseError (Finite (Rows p c))\ntableauLeaving enter (Tableau vs x) =\n case toRatio <$> filter canLeave rows of\n [] -> Left Unbounded\n xs -> Right . fst $ List.minimumBy (comparing snd) xs\n where\n rows = Vec.toList . Vec.indexed $ rowVars vs\n rhsColumn = fromJust $ elemIndexColumns RHS vs\n\n toRatio (i, _) =\n let val = index (i, enter) x\n rhs = index (i, rhsColumn) x\n in (i, rhs / val)\n\n canLeave (i, n) =\n let val = index (i, enter) x\n rhs = index (i, rhsColumn) x\n in val > 0 && rhs /= 0 && not (isSpecial n)\n\n\ntableauStep\n :: (IsTableau p v s a c)\n => (Tableau p d v s a c\n -> Either TwoPhaseError (Finite (Cols p v s a)))\n -> Tableau p d v s a c\n -> Either TwoPhaseError (Tableau p d v s a c)\ntableauStep tableauEntering t@(Tableau vs x) = do\n enter <- tableauEntering t\n leave <- tableauLeaving enter t\n\n let cell = (leave, enter)\n pure $ Tableau (updateRow cell vs) (pivot cell x)\n\n", "meta": {"hexsha": "5b331fc5c442047d77b5fab04cf2b58409bc514d", "size": 10351, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Optimization/TwoPhase/Tableau.hs", "max_stars_repo_name": "alex-mckenna/optimum", "max_stars_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-01-09T22:43:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T17:34:44.000Z", "max_issues_repo_path": "src/Numeric/Optimization/TwoPhase/Tableau.hs", "max_issues_repo_name": "alex-mckenna/optimum", "max_issues_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "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/Optimization/TwoPhase/Tableau.hs", "max_forks_repo_name": "alex-mckenna/optimum", "max_forks_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "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.1459627329, "max_line_length": 85, "alphanum_fraction": 0.6282484784, "num_tokens": 2816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.37140995707446933}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n-- |\n-- Module : Spiral.Util.Pretty.LaTeX\n-- Copyright : (c) 2017-2020 Drexel University\n-- License : BSD-style\n-- Maintainer : mainland@drexel.edu\n\nmodule Spiral.Util.Pretty.LaTeX (\n Pretty(..)\n ) where\n\nimport Data.Complex (Complex(..))\nimport Data.Complex.Cyclotomic\nimport Data.List (intersperse)\nimport qualified Data.Map as Map\nimport qualified Data.Matrix as M\nimport Data.Modular (Mod, unMod)\nimport Data.Monoid ((<>))\nimport Data.Ratio (Ratio, numerator, denominator)\nimport Data.Set (Set)\nimport qualified Data.Set as Set\nimport Data.Symbol (unintern)\nimport qualified Data.Text as T\nimport qualified Data.Vector as V\nimport GHC.TypeLits (KnownNat)\nimport Text.LaTeX\nimport Text.LaTeX.Base.Class (comm0,\n comm1)\nimport Text.LaTeX.Packages.AMSFonts\nimport Text.LaTeX.Packages.AMSMath\n\nimport Spiral.Array (IArray,\n Matrix,\n (!))\nimport qualified Spiral.Array as A\nimport Spiral.Array.Shape\nimport Spiral.Exp\nimport Spiral.Permutation hiding (Inv)\nimport qualified Spiral.Permutation as P\nimport Spiral.SPL\nimport Spiral.Util.Name (Name(..))\nimport Spiral.Util.Pretty (Assoc(..),\n Fixity(..),\n HasFixity(..),\n addPrec,\n infixl_,\n precOf)\nimport Spiral.Util.Uniq (Uniq(..))\n\nclass Pretty a where\n {-# MINIMAL pprPrec | ppr #-}\n ppr :: a -> LaTeX\n pprPrec :: Int -> a -> LaTeX\n\n pprList :: [a] -> LaTeX\n pprPrecList :: Int -> [a] -> LaTeX\n\n ppr = pprPrec 0\n pprPrec _ = ppr\n\n pprPrecList _ = pprList\n pprList = autoSquareBrackets . commasep . map ppr\n\nparensIf :: Bool -> LaTeX -> LaTeX\nparensIf False l = l\nparensIf True l = autoParens l\n\nhsep :: LaTeX -> [LaTeX] -> LaTeX\nhsep sep = mconcat . intersperse sep\n\ncommasep :: [LaTeX] -> LaTeX\ncommasep = hsep \",\"\n\nmskip :: LaTeX -> LaTeX\nmskip = comm1 \"mskip\"\n\nnicefrac :: LaTeX -> LaTeX -> LaTeX\nnicefrac e1 e2 = mempty ^: e1 <> (mskip \"-2mu\" <> \"/\" <> mskip \"-1mu\") !: e2\n--nicefrac e1 e2 = e1 <> \"/\" <> e2\n\ninstance Pretty a => Pretty [a] where\n ppr = pprList\n pprPrec = pprPrecList\n\ninstance Pretty a => Pretty (Set a) where\n ppr = autoBraces . commasep . map ppr . Set.toList\n\ninstance Pretty Bool where\n ppr True = mathfrak \"T\"\n ppr False = mathfrak \"F\"\n\npprSignedIntegral :: (Integral a, Show a) => a -> LaTeX\npprSignedIntegral x\n | x < 0 = \"-\" <> pprSignedIntegral (-x)\n | otherwise = (fromString . show) x\n\npprRealFloat :: (RealFloat a, Show a) => a -> LaTeX\npprRealFloat x\n | isIntegral x = ppr (ceiling x :: Integer)\n | x < 0 = fromString $ showFloat (-x)\n | otherwise = fromString $ showFloat x\n where\n isIntegral :: RealFrac a => a -> Bool\n isIntegral x = fromIntegral (ceiling x :: Integer) == x\n\ninstance Pretty Int where\n ppr = pprSignedIntegral\n\ninstance Pretty Integer where\n ppr = pprSignedIntegral\n\ninstance Pretty Float where\n ppr = pprRealFloat\n\ninstance Pretty Double where\n ppr = pprRealFloat\n\ninstance (Eq a, Num a, Pretty a) => Pretty (Ratio a) where\n ppr x\n | d == 1 = ppr n\n | otherwise = nicefrac (ppr n) (ppr d)\n where\n n = numerator x\n d = denominator x\n\n-- | Pretty-print an imaginary number\npprIm :: (Eq a, Num a, Pretty a) => a -> LaTeX\npprIm 0 = mempty\npprIm 1 = \"i\"\npprIm (-1) = \"-i\"\npprIm i = ppr i <> \"i\"\n\ninstance (Eq a, Num a, Pretty a) => Pretty (Complex a) where\n ppr (r :+ 0) = ppr r\n ppr (0 :+ 1) = \"i\"\n ppr (0 :+ (-1)) = \"-i\"\n ppr (0 :+ i) = pprIm i\n ppr (r :+ i) = case (T.unpack . render) (pprIm i) of\n '-' : _ -> ppr r <> pprIm i\n _ -> ppr r + pprIm i\n\ninstance Pretty Cyclotomic where\n pprPrec p (Cyclotomic n mp)\n | Map.null mp = \"0\"\n | null xs = leadingTerm rat n ex\n | otherwise = parensIf (p > addPrec) $\n leadingTerm rat n ex <> mconcat (map (followingTerm n) xs)\n where\n ((ex,rat):xs) = Map.toList mp\n\n pprBaseExp :: Integer -> Integer -> LaTeX\n pprBaseExp n 1 = omega !: ppr n\n pprBaseExp n ex = omega !^ (ppr n, ppr ex)\n\n leadingTerm :: Rational -> Integer -> Integer -> LaTeX\n leadingTerm r _ 0 = ppr r\n leadingTerm r n ex\n | r == 1 = t\n | r == (-1) = \"-\" <> t\n | r > 0 = ppr r <> t\n | r < 0 = \"-\" <> ppr (-r) <> t\n | otherwise = mempty\n where\n t = pprBaseExp n ex\n\n followingTerm :: Integer -> (Integer, Rational) -> LaTeX\n followingTerm n (ex, r)\n | r == 1 = \"+\" <> t\n | r == (-1) = \"-\" <> t\n | r > 0 = \"+\" <> ppr r <> t\n | r < 0 = \"-\" <> ppr (-r) <> t\n | otherwise = mempty\n where\n t = pprBaseExp n ex\n\ninstance (Pretty i, KnownNat p) => Pretty (Mod i p) where\n ppr z = ppr (unMod z)\n\ninstance Pretty (Const a) where\n ppr (BoolC x) = ppr x\n ppr (IntC x) = ppr x\n ppr (IntegerC x) = ppr x\n ppr (FloatC x) = ppr x\n ppr (DoubleC x) = ppr x\n ppr (RationalC x) = ppr x\n ppr (ComplexC r i) = ppr (r :+ i)\n ppr (W _ 0 _) = \"1\"\n ppr (W n 1 _) = omega !: ppr n\n ppr (W n k _) = omega !^ (ppr n, ppr k)\n ppr (CycC x) = ppr x\n ppr (PiC k) = ppr k <> pi_\n ppr (ModularC x) = ppr x\n\ninstance Pretty Uniq where\n ppr (Uniq u) = ppr u\n\ninstance Pretty Name where\n ppr (Name sym Nothing) = fromString (unintern sym)\n ppr (Name sym (Just u)) = fromString (unintern sym) !: ppr u\n\ninstance Pretty Var where\n ppr (Var n) = ppr n\n\ninstance (Pretty e, IArray r DIM2 e) => Pretty (Matrix r e) where\n ppr mat = bmatrix Nothing $ M.matrix m n f\n where\n Z :. m :. n = A.extent mat\n\n f :: (Int, Int) -> LaTeX\n f (i, j) = ppr (mat ! (i-1, j-1))\n\ninstance Pretty (Exp a) where\n pprPrec p (ConstE c) = pprPrec p c\n pprPrec p (VarE v) = pprPrec p v\n\n pprPrec _ (UnopE Abs e) =\n autoBrackets \"|\" \"|\" (ppr e)\n\n pprPrec _ (UnopE Sqrt e) =\n tsqrt Nothing (ppr e)\n\n pprPrec p (UnopE op e) =\n unop p op e\n\n pprPrec p (BinopE op e1 e2) =\n infixop p op e1 e2\n\n pprPrec _ (IdxE ev eis) =\n ppr ev <> autoSquareBrackets (commasep (map ppr eis))\n\n pprPrec p (ComplexE er ei) =\n parensIf (p > addPrec) $\n ppr (er :+ ei)\n\n pprPrec _ (ReE e) =\n comm0 \"Re\" <> pprPrec 10 e\n\n pprPrec _ (ImE e) =\n comm0 \"Im\" <> pprPrec 10 e\n\n pprPrec p (BBinopE op e1 e2) =\n infixop p op e1 e2\n\n pprPrec p (IfE e1 e2 e3) =\n parensIf (p > 10) $\n operatorname (mathsf \"if\") <> ppr e1 <>\n operatorname (mathsf \"then\") <> ppr e2 <>\n operatorname (mathsf \"else\") <> ppr e3\n\ninstance Pretty Unop where\n ppr Neg = \"-\"\n ppr Abs = operatorname \"abs\"\n ppr Signum = operatorname \"sgn\"\n ppr Exp = texp\n ppr Log = tlog\n ppr Sqrt = operatorname \"sqrt\"\n ppr Sin = tsin\n ppr Cos = tcos\n ppr Asin = arcsin\n ppr Acos = arccos\n ppr Atan = arctan\n ppr Sinh = tsinh\n ppr Cosh = tcosh\n ppr Asinh = operatorname \"arsinh\"\n ppr Acosh = operatorname \"arcosh\"\n ppr Atanh = operatorname \"artanh\"\n\ninstance Pretty Binop where\n ppr Add = \"+\"\n ppr Sub = \"-\"\n ppr Mul = comm0 \"cdot\"\n ppr Quot = comm0 \"quot\"\n ppr Rem = operatorname \"rem\"\n ppr Div = operatorname \"div\"\n ppr Mod = operatorname \"mod\"\n ppr FDiv = \"/\"\n\ninstance Pretty BBinop where\n ppr Eq = \"=\"\n ppr Ne = comm0 \"neq\"\n ppr Lt = \"<\"\n ppr Le = comm0 \"le\"\n ppr Ge = comm0 \"ge\"\n ppr Gt = \">\"\n\ninstance Pretty Permutation where\n ppr (L mn n) = \"L\" !^ (ppr n, ppr mn)\n ppr (J n) = operatorname \"J\" !: ppr n\n ppr (CS n k) = operatorname \"S\" !: ppr n <> autoParens (ppr k)\n ppr (CRT m n _ _) = operatorname \"CRT\" !^ (ppr n, ppr m)\n ppr (CRT' m n _ _) = operatorname \"CRT'\" !^ (ppr n, ppr m)\n ppr (Good m n _ _) = operatorname \"Good\" !^ (ppr n, ppr m)\n ppr (Good' m n _ _) = operatorname \"Good'\" !^ (ppr n, ppr m)\n ppr (R p a) = operatorname \"R\" !^ (ppr p, ppr a)\n ppr (P.Inv p _) = ppr p ^: \"-1\"\n\ndata MatrixBinop = KOp\n | DSOp\n deriving (Eq, Ord, Show)\n\ninstance HasFixity MatrixBinop where\n fixity KOp = infixl_ 7\n fixity DSOp = infixl_ 6\n\ninstance Pretty MatrixBinop where\n ppr KOp = comm0 \"otimes\"\n ppr DSOp = comm0 \"oplus\"\n\npprArgs :: Pretty a => [a] -> LaTeX\npprArgs = autoParens . commasep . map ppr\n\ninstance (Num e, Pretty e) => Pretty (SPL e) where\n pprPrec p m@E{} = pprPrec p (toMatrix m)\n pprPrec _ (I n) = operatorname \"I\" !: ppr n\n pprPrec _ (T e) = pprPrec 10 e ^: comm0 \"intercal\"\n pprPrec _ (Inv e) = pprPrec 10 e ^: \"-1\"\n pprPrec p (Pi pi) = pprPrec p pi\n pprPrec _ (Rot alpha) = operatorname \"R\" !: ppr alpha\n pprPrec _ (Diag xs) = operatorname \"diag\" <> pprArgs (V.toList xs)\n pprPrec p (KDiag _ e) = pprPrec p e\n\n pprPrec _ ((tl `Beside` tr) `Above` (bl `Beside` br)) =\n bmatrix Nothing $ M.matrix 2 2 f\n where\n f :: (Int, Int) -> LaTeX\n f (1, 1) = ppr tl\n f (1, 2) = ppr tr\n f (2, 1) = ppr bl\n f (2, 2) = ppr br\n f _ = error \"can't happen\"\n\n pprPrec _ (Above a b) =\n bmatrix Nothing $ M.matrix 2 1 f\n where\n f :: (Int, Int) -> LaTeX\n f (1, 1) = ppr a\n f (2, 1) = ppr b\n f _ = error \"can't happen\"\n\n pprPrec _ (Beside a b) =\n bmatrix Nothing $ M.matrix 1 2 f\n where\n f :: (Int, Int) -> LaTeX\n f (1, 1) = ppr a\n f (1, 2) = ppr b\n f _ = error \"can't happen\"\n\n pprPrec p (Kron a b) = infixop p KOp a b\n pprPrec p (DSum a b) = infixop p DSOp a b\n pprPrec _ (Prod a b) = pprPrec 10 a <> pprPrec 10 b\n pprPrec _ (Circ xs) = operatorname \"circ\" <> pprArgs (V.toList xs)\n pprPrec _ (Skew xs) = operatorname \"skew\" <> pprArgs (V.toList xs)\n pprPrec _ (Toep xs) = operatorname \"toep\" <> pprArgs (V.toList xs)\n pprPrec _ (Re a) = comm0 \"Re\" <> autoParens (ppr a)\n pprPrec _ F2 = operatorname \"F\" !: \"2\"\n pprPrec _ (DFT n) = operatorname \"DFT\" !: ppr n\n pprPrec _ (DFT' n) = operatorname \"DFT\" !^ (ppr n, \"-1\")\n pprPrec _ (F n w) = operatorname \"DFT\" !: ppr n <> autoParens (ppr w)\n pprPrec _ (F' n w) = operatorname \"DFT\" !^ (ppr n, \"-1\") <> autoParens (ppr w)\n\nunop :: (Pretty a, Pretty op, HasFixity op)\n => Int -- ^ precedence of context\n -> op -- ^ operator\n -> a\n -> LaTeX\nunop prec op x =\n parensIf (prec > precOf op) $\n ppr op <> pprPrec (precOf op) x\n\ninfixop :: (Pretty a, Pretty b, Pretty op, HasFixity op)\n => Int -- ^ precedence of context\n -> op -- ^ operator\n -> a -- ^ left argument\n -> b -- ^ right argument\n -> LaTeX\ninfixop prec op l r =\n parensIf (prec > opPrec) $\n pprPrec leftPrec l <> ppr op <> pprPrec rightPrec r\n where\n leftPrec | opAssoc == RightAssoc = opPrec + 1\n | otherwise = opPrec\n\n rightPrec | opAssoc == LeftAssoc = opPrec + 1\n | otherwise = opPrec\n\n Fixity opAssoc opPrec = fixity op\n", "meta": {"hexsha": "d25e1f8ab31da759a4d03bd03e9ce7e57d9ac71f", "size": 11214, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Spiral/Util/Pretty/LaTeX.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/Util/Pretty/LaTeX.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/Util/Pretty/LaTeX.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.6071428571, "max_line_length": 83, "alphanum_fraction": 0.5658105939, "num_tokens": 3963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3695694172023354}} {"text": "{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, StandaloneDeriving #-}\n\nimport Prelude hiding (mapM)\n\nimport Options.Applicative\nimport Data.Monoid ((<>))\nimport Control.Monad.Trans.Class\n\nimport Data.Vector (Vector)\nimport qualified Data.Vector.Generic as V\nimport Statistics.Sample (mean)\n\nimport Data.Traversable (mapM)\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.Map.Strict as M\n\nimport ReadData\nimport SerializeText\nimport qualified RunSampler as Sampler\nimport BayesStack.DirMulti\nimport BayesStack.Models.Topic.LDA\nimport BayesStack.UniqueKey\n\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as TIO\n\nimport System.FilePath.Posix (())\nimport Data.Binary\nimport qualified Data.ByteString as BS\nimport Text.Printf\n\nimport Data.Random\nimport System.Random.MWC\n\ndata RunOpts = RunOpts { nodesFile :: FilePath\n , stopwords :: Maybe FilePath\n , nTopics :: Int\n , samplerOpts :: Sampler.SamplerOpts\n , hyperParams :: HyperParams\n }\n\nrunOpts :: Parser RunOpts\nrunOpts = RunOpts\n <$> strOption ( long \"nodes\"\n <> short 'n'\n <> metavar \"FILE\"\n <> help \"File containing nodes and their associated items\"\n )\n <*> nullOption ( long \"stopwords\"\n <> short 's'\n <> metavar \"FILE\"\n <> reader (pure . Just)\n <> value Nothing\n <> help \"Stop word list\"\n )\n <*> option ( long \"topics\"\n <> short 't'\n <> metavar \"N\"\n <> value 20\n <> help \"Number of topics\"\n )\n <*> Sampler.samplerOpts\n <*> hyperOpts\n\nhyperOpts = HyperParams\n <$> option ( long \"prior-theta\"\n <> value 1\n <> help \"Dirichlet parameter for prior on theta\"\n )\n <*> option ( long \"prior-phi\"\n <> value 0.1\n <> help \"Dirichlet parameter for prior on phi\"\n )\n\nmapMKeys :: (Ord k, Ord k', Monad m, Applicative m)\n => (a -> m a') -> (k -> m k') -> M.Map k a -> m (M.Map k' a')\nmapMKeys f g x = M.fromList <$> (mapM (\\(k,v)->(,) <$> g k <*> f v) $ M.assocs x)\n\ntermsToItems :: M.Map NodeName [Term]\n -> (M.Map Node [Item], (M.Map Item Term, M.Map Node NodeName))\ntermsToItems nodes =\n let ((d', nodeMap), itemMap) =\n runUniqueKey' [Item i | i <- [0..]] $\n runUniqueKeyT' [Node i | i <- [0..]] $ do\n mapMKeys (mapM (lift . getUniqueKey)) getUniqueKey nodes\n in (d', (itemMap, nodeMap))\n\nnetData :: HyperParams -> M.Map Node [Item] -> Int -> NetData\nnetData hp nodeItems nTopics =\n NetData { dHypers = hp\n , dItems = S.unions $ map S.fromList $ M.elems nodeItems\n , dTopics = S.fromList [Topic i | i <- [1..nTopics]]\n , dNodeItems = M.fromList\n $ zip [NodeItem i | i <- [0..]]\n $ do (n,items) <- M.assocs nodeItems\n item <- items\n return (n, item)\n , dNodes = M.keysSet nodeItems\n }\n\nopts :: ParserInfo RunOpts\nopts = info runOpts ( fullDesc\n <> progDesc \"Learn LDA model\"\n <> header \"run-lda - learn LDA model\"\n )\n\ninstance Sampler.SamplerModel MState where\n estimateHypers = reestimate\n modelLikelihood = modelLikelihood\n summarizeHypers ms =\n \" phi : \"++show (dmAlpha $ snd $ M.findMin $ stPhis ms)++\"\\n\"++\n \" theta: \"++show (dmAlpha $ snd $ M.findMin $ stThetas ms)++\"\\n\"\n\nmain :: IO ()\nmain = do\n args <- execParser opts\n stopWords <- case stopwords args of\n Just f -> S.fromList . T.words <$> TIO.readFile f\n Nothing -> return S.empty\n printf \"Read %d stopwords\\n\" (S.size stopWords)\n\n (nodeItems, (itemMap, nodeMap)) <- termsToItems\n <$> readNodeItems stopWords (nodesFile args)\n\n Sampler.createSweeps $ samplerOpts args\n let sweepsDir = Sampler.sweepsDir $ samplerOpts args\n encodeFile (sweepsDir \"item-map\") itemMap\n encodeFile (sweepsDir \"node-map\") nodeMap\n\n let termCounts = V.fromListN (M.size nodeItems)\n $ map length $ M.elems nodeItems :: Vector Int\n printf \"Read %d nodes\\n\" (M.size nodeItems)\n printf \"Mean items per node: %1.2f\\n\" (mean $ V.map realToFrac termCounts)\n\n withSystemRandom $ \\mwc->do\n let nd = netData (hyperParams args) nodeItems (nTopics args)\n encodeFile (sweepsDir \"data\") nd\n mInit <- runRVar (randomInitialize nd) mwc\n let m = model nd mInit\n Sampler.runSampler (samplerOpts args) m (updateUnits nd)\n return ()\n", "meta": {"hexsha": "485050e51b7eb5cee5c1748f2d01cf0e5786029c", "size": 5209, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "network-topic-models/RunLDA.hs", "max_stars_repo_name": "bgamari/bayes-stack", "max_stars_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2015-04-06T22:59:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T12:03:19.000Z", "max_issues_repo_path": "network-topic-models/RunLDA.hs", "max_issues_repo_name": "bgamari/bayes-stack", "max_issues_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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-topic-models/RunLDA.hs", "max_forks_repo_name": "bgamari/bayes-stack", "max_forks_repo_head_hexsha": "020df7bb7263104fdea254e57d6c7daf7806da3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-02-13T06:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-20T14:40:13.000Z", "avg_line_length": 36.4265734266, "max_line_length": 81, "alphanum_fraction": 0.5240929161, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.36932798299490477}} {"text": "{-# LANGUAGE RankNTypes,\n ScopedTypeVariables,\n ViewPatterns,\n TypeFamilies,\n TypeOperators,\n RankNTypes,\n MultiWayIf,\n DataKinds,\n LambdaCase,\n ConstraintKinds, \n FlexibleContexts #-}\n\nmodule Networks where \n\nimport Optimierung\nimport Tuple\nimport Numeric.LinearAlgebra.Static.Backprop\nimport Numeric.Backprop\nimport GHC.TypeNats\nimport qualified Numeric.LinearAlgebra.Static as H\nimport qualified Control.Foldl as L\nimport qualified Data.Vector.Storable as V\n\ntype KN i o = (KnownNat i, KnownNat o)\ntype Fehler a b = forall z. Reifies z W => BVar z a -> BVar z a -> BVar z b\ntype Res p a b c = forall z. Reifies z W => BVar z (a :& b) -> BVar z p -> BVar z c\n\ntype Modell p a b = \n forall z. Reifies z W\n => BVar z p\n -> BVar z a\n -> BVar z b\n \nwithScalarActivation :: (Reifies z W, KnownNat i) \n => (BVar z Double -> BVar z Double) \n -> BVar z (R i :& Double) \n -> BVar z (R i)\n -> BVar z Double\nwithScalarActivation f (w :&& b) v = f $ w <.> v + b \n\nwithActivation :: (Reifies z W, KN i o)\n => (BVar z (R o) -> BVar z (R o))\n -> BVar z (L o i :& R o)\n -> BVar z (R i)\n -> BVar z (R o)\nwithActivation f (w :&& b) v = f $ w #> v + b\n\nlogistic :: Floating a => a -> a\nlogistic x = 1 / (1 + exp (-x))\n\nlinear :: KnownNat i => Modell (R i :& Double) (R i) Double\nlinear = withScalarActivation id\n\nlinear2 :: KnownNat i => Modell (R i :& Double) (R i) Double\nlinear2 (w :&& b) x = w <.> x + b\n\nsigmoid :: KN i o => Modell (L o i :& R o) (R i) (R o) \nsigmoid = withActivation logistic\n\n--todo: dvmap isn't actually made differentiable, manually make Op\nleakyReLU :: KN i o => Modell (L o i :& R o) (R i) (R o)\nleakyReLU = withActivation $ dvmap $ \\x -> if (x < 0) then 0.01*x\n else x\n\nsigmoidNoBias :: KN i o => Modell (L o i) (R i) (R o)\nsigmoidNoBias w v = logistic $ w #> v\n\nsigmoid' :: KnownNat i => Modell (R i :& Double) (R i) Double\nsigmoid' = withScalarActivation logistic \n\nse :: Fehler Double Double\nse x a = (x - a)^2\n\nse' :: (KnownNat n, 1 <= n) => Fehler (R n) Double\nse' a e = (d <.> d) / 2\n where d = e - a\n\ncrossentropy' :: (KnownNat n, 1 <= n) => Fehler (R n) Double\ncrossentropy' a y = vsum . nanToNum . negate $ entropy y a + entropy (1-y) (1-a)\n where entropy x y = x * log y\n\ncrossentropyUnsafe' :: (KnownNat n, 1 <= n) => Fehler (R n) Double\ncrossentropyUnsafe' a y = vsum . negate $ entropy y a + entropy (1-y) (1-a)\n where entropy x y = x * log y\n \ncrossentropy :: (KnownNat n, 1 <= n) => R n -> R n -> Double\ncrossentropy a y = (H.konst 1) H.<.> (entropy (-y) a - entropy (1-y) (1-a))\n where entropy x y = x * log y\n \nlogisticSample :: KN i o => (L o i :& R o) -> Int -> R i -> R o \nlogisticSample (w :& b) s v = H.zipWithVector (\\x p -> if x < p then 1 else 0) r probs\n where probs = logistic $ w H.#> v + b\n r = H.randomVector s H.Uniform\n\nnonModelLogistic :: KN i o => (L o i :& R o) -> R i -> R o\nnonModelLogistic (w :& b) v = logistic $ w H.#> v + b \n\nvsum :: (Reifies z W, KnownNat n) => BVar z (R n) -> BVar z Double\nvsum x = (konst 1) <.> x\n\nrbmcd1 :: KN d h => Int -> (L d h :& R d :& R h) -> R d -> (L d h :& R d :& R h)\nrbmcd1 s (w :& b :& c) v1 = (H.outer v1 h1 - H.outer v2 h2) :& (v1 - v2) :& (h1 - h2)\n where h1 = (logisticSample (H.tr w :& c) s v1)\n v2 = (nonModelLogistic (w :& b) h1)\n h2 = (nonModelLogistic (H.tr w :& c) v2)\n\ngradientStep :: (Backprop p, Backprop b, Backprop c)\n => Modell p a b -- ^ Modell zum Trainieren \n -> Fehler b c -- ^ Fehlerfunktion\n -> p -- ^ Parameter am Anfang des Schrittes\n -> (a, b) -- ^ (Eingabedatum, erwartete Antwort) \n -> p -- ^ Gradient des Parameters\ngradientStep mod err param (vec, trg) = gradBP (\\p -> err (mod p (auto vec)) (auto trg)) param\n\nmakeFoldAll :: Optimierung d p \n => d p\n -> (p -> a -> p)\n -> p\n -> L.Fold a p\nmakeFoldAll d f p0 = L.Fold (\\x a -> regel d x (f (aus x) a)) (start p0) aus\n\nuberwachtesFold :: (Optimierung d p, Backprop p, Backprop b, Backprop c)\n => d p \n -> Modell p a b\n -> Fehler b c \n -> p\n -> L.Fold (a, b) p\nuberwachtesFold op mod err p0 = makeFoldAll op (gradientStep mod err) p0\n\nisVecNaN :: KnownNat n => R n -> Bool\nisVecNaN = V.foldl (\\acc x -> acc || isNaN x) False . H.extract \n\nnanToNum :: (KnownNat n, Reifies z W) => BVar z (R n) -> BVar z (R n)\nnanToNum = vmap bvToNum\n\nbvToNum :: Reifies z W => BVar z Double -> BVar z Double\nbvToNum = liftOp1 . op1 $ \\x -> ((if\n | isNaN x -> 0.0\n | isInfinite x -> if x < 0 then -1.7976931348623157e+308 \n else 1.7976931348623157e+308\n | otherwise -> x), id)\n \n\nsupervised :: (Backprop a, Backprop p, Backprop b, Backprop c)\n => Fehler b c \n -> Modell p a b\n -> Res p a b c\nsupervised err mod (a :&& y) ps = err (mod ps a) y\n\nclass Optimizable m where\n type Params m\n type In m\n gradient :: m -> Params m -> In m -> Params m\n\nmakeFoldOptimizable :: (Optimizable m, Optimierung d (Params m)) \n => m\n -> d (Params m)\n -> Params m\n -> L.Fold (In m) (Params m)\nmakeFoldOptimizable m d p0 = L.Fold (\\x a -> regel d x (step (aus x) a)) (start p0) aus\n where step = gradient m\n\n(<~) :: (Backprop p, Backprop q) \n => Modell p b c\n -> Modell q a b\n -> Modell (p :& q) a c\n(f <~ g) (p :&& q) = f p . g q \n\ninfixr 8 <~\n\n", "meta": {"hexsha": "bf430da60741d19efc412af15def7c1a4b7852d7", "size": 5992, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Networks.hs", "max_stars_repo_name": "QQMBR/BLL-FP-NN", "max_stars_repo_head_hexsha": "be952cd338113de358297772a56d61ed74b665fe", "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/Networks.hs", "max_issues_repo_name": "QQMBR/BLL-FP-NN", "max_issues_repo_head_hexsha": "be952cd338113de358297772a56d61ed74b665fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Networks.hs", "max_forks_repo_name": "QQMBR/BLL-FP-NN", "max_forks_repo_head_hexsha": "be952cd338113de358297772a56d61ed74b665fe", "max_forks_repo_licenses": ["BSD-3-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.0409356725, "max_line_length": 94, "alphanum_fraction": 0.51435247, "num_tokens": 1934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.36871620297107954}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE PatternGuards #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\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-----------------------------------------------------------------------------\n\nmodule Numeric.AD.Mode\n (\n -- * AD modes\n Mode(..)\n ) where\n\nimport Numeric.Natural\nimport Data.Complex\nimport Data.Int\nimport Data.Ratio\nimport Data.Word\n\ninfixr 7 *^\ninfixl 7 ^*\ninfixr 7 ^/\n\nclass (Num t, Num (Scalar t)) => Mode t where\n type Scalar t\n -- | allowed to return False for items with a zero derivative, but we'll give more NaNs than strictly necessary\n isKnownConstant :: t -> Bool\n isKnownConstant _ = False\n\n -- | allowed to return False for zero, but we give more NaN's than strictly necessary then\n isKnownZero :: t -> Bool\n isKnownZero _ = False\n\n -- | Embed a constant\n auto :: Scalar t -> t\n\n -- | Scalar-vector multiplication\n (*^) :: Scalar t -> t -> t\n a *^ b = auto a * b\n\n -- | Vector-scalar multiplication\n (^*) :: t -> Scalar t -> t\n a ^* b = a * auto b\n\n -- | Scalar division\n (^/) :: Fractional (Scalar t) => t -> Scalar t -> t\n a ^/ b = a ^* recip b\n\n -- |\n -- @'zero' = 'lift' 0@\n zero :: t\n zero = auto 0\n\ninstance Mode Double where\n type Scalar Double = Double\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Float where\n type Scalar Float = Float\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Int where\n type Scalar Int = Int\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Integer where\n type Scalar Integer = Integer\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Int8 where\n type Scalar Int8 = Int8\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Int16 where\n type Scalar Int16 = Int16\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Int32 where\n type Scalar Int32 = Int32\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Int64 where\n type Scalar Int64 = Int64\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Natural where\n type Scalar Natural = Natural\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Word where\n type Scalar Word = Word\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Word8 where\n type Scalar Word8 = Word8\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Word16 where\n type Scalar Word16 = Word16\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Word32 where\n type Scalar Word32 = Word32\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Mode Word64 where\n type Scalar Word64 = Word64\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance RealFloat a => Mode (Complex a) where\n type Scalar (Complex a) = Complex a\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n\ninstance Integral a => Mode (Ratio a) where\n type Scalar (Ratio a) = Ratio a\n isKnownConstant _ = True\n isKnownZero x = 0 == x\n auto = id\n (^/) = (/)\n", "meta": {"hexsha": "92b81a8178f9b6b8edb8daf031203bcad091e75e", "size": 3813, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/AD/Mode.hs", "max_stars_repo_name": "phadej/ad", "max_stars_repo_head_hexsha": "03a72dbf96317407341fdd6e2338f312fe623e9c", "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/Mode.hs", "max_issues_repo_name": "phadej/ad", "max_issues_repo_head_hexsha": "03a72dbf96317407341fdd6e2338f312fe623e9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Mode.hs", "max_forks_repo_name": "phadej/ad", "max_forks_repo_head_hexsha": "03a72dbf96317407341fdd6e2338f312fe623e9c", "max_forks_repo_licenses": ["BSD-3-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.4213483146, "max_line_length": 113, "alphanum_fraction": 0.5997901915, "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3675893907299582}} {"text": "{-# LANGUAGE FlexibleContexts #-}\n\nmodule Main (main) where\n\nimport Control.Monad.IO.Class (liftIO)\nimport Data.Complex (Complex)\nimport Data.Foldable (toList)\nimport Text.PrettyPrint.Mainland\nimport Text.PrettyPrint.Mainland.Class\n\nimport Spiral\nimport Spiral.Backend.C\nimport Spiral.Config\nimport Spiral.Driver\nimport Spiral.Exp\nimport Spiral.OpCount\nimport Spiral.Program\nimport Spiral.RootOfUnity\nimport Spiral.SPL\nimport Spiral.SPL.Run\nimport Spiral.Util.Uniq\n\nmain :: IO ()\nmain = defaultMain $ \\args -> do\n useComplexType <- asksConfig $ testDynFlag UseComplex\n n <- case args of\n [s] -> return (read s)\n _ -> return 4\n let f = formula n\n pprint f\n if useComplexType\n then toProgram \"f\" f >>= go\n else toProgram \"f\" (Re f) >>= go\n where\n go :: (Typed a, Num (Exp a)) => Program a -> Spiral ()\n go prog = do\n pprint prog\n ops <- countProgramOps prog\n resetUnique\n defs <- evalCg $ cgProgram prog\n outp <- asksConfig output\n case outp of\n Nothing -> return ()\n Just{} -> writeOutput (toList defs)\n liftIO $ putDocLn $\n text \"Multiplications:\" <+> ppr (mulOps ops) \n text \" Additions:\" <+> ppr (addOps ops) \n text \" Total:\" <+> ppr (allOps ops)\n\n-- The SPL formula for which we generate code and count operations.\nformula :: Int -> SPL (Exp (Complex Double))\nformula _ =\n Pi (L 8 4) ×\n (I 2 ⊗ (Pi (L 4 2) × (I 2 ⊗ F 2 w2) × diag [1.0, 1.0, 1.0, w4] × (F 2 w2 ⊗ I 2))) ×\n diag [1.0, 1.0, 1.0, 1.0, 1.0, w8, w4, w8^(3 :: Int)] ×\n (F 2 w2 ⊗ I 4)\n where\n w2, w4, w8 :: Exp (Complex Double)\n w2 = omega 2\n w4 = omega 4\n w8 = omega 8\n", "meta": {"hexsha": "eae6470b1a0293615a879767347141da14f55c2f", "size": 1708, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/OpCount.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": "examples/OpCount.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": "examples/OpCount.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": 27.5483870968, "max_line_length": 87, "alphanum_fraction": 0.6030444965, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.36617639865290497}} {"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeOperators #-}\n\nmodule Numeric.Optimization.TwoPhase.Tableau.Build\n ( IsBuilder\n , mkTable\n ) where\n\nimport Prelude hiding ((++))\n\nimport qualified Data.List as List\nimport Data.Maybe (fromJust)\nimport qualified Data.Vector.Sized as Vec\nimport Data.Vector.Storable.Sized (Vector, (++))\nimport qualified Data.Vector.Storable.Sized as SVec\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Static (L)\nimport qualified Numeric.LinearAlgebra.Static as LS\nimport qualified Numeric.LinearAlgebra.Static.Vector as LS\n\nimport Numeric.Optimization.Problem\nimport Numeric.Optimization.TwoPhase.Types\n\n\ntype IsBuilder v s a c =\n ( KnownNat v\n , KnownNat s\n , KnownNat a\n , KnownNat c\n )\n\n\ndata Builder (v :: Nat) (s :: Nat) (a :: Nat) (c :: Nat) = Builder\n { slackSupply :: [Vector s Double]\n , artificialSupply :: [Vector a Double]\n , rowsBuilt :: [Vector (Cols 'PhaseI v s a) Double]\n , adjustmentsBuilt :: [Vector (Cols 'PhaseI v s a) Double]\n }\n\n\nmkBuilder :: (IsBuilder v s a c) => Builder v s a c\nmkBuilder = Builder slackI artificialI [] []\n where\n slackI = reverse . fmap LS.rVec . LS.toRows $ LS.eye\n artificialI = reverse . fmap LS.rVec . LS.toRows $ LS.eye\n\n\nbuildPhaseI\n :: forall v s a c.\n (IsBuilder v s a c)\n => Builder v s a c\n -> Builder v s a c\nbuildPhaseI acc = acc\n { rowsBuilt = row : rowsBuilt acc }\n where\n row = SVec.snoc (os ++ xs ++ ss ++ as) 0\n os = SVec.fromTuple (1, 0)\n xs = SVec.replicate @v 0\n ss = SVec.replicate @s 0\n as = SVec.replicate @a (-1)\n\n\nbuildPhaseII\n :: forall v s a c.\n (IsBuilder v s a c)\n => Builder v s a c\n -> Coeffs v\n -> Builder v s a c\nbuildPhaseII acc xs' = acc\n { rowsBuilt = row : rowsBuilt acc }\n where\n row = SVec.snoc (os ++ xs ++ ss ++ as) 0\n os = SVec.fromTuple (0, 1)\n xs = SVec.map negate xs'\n ss = SVec.replicate @s 0\n as = SVec.replicate @a 0\n\n\nbuildObjective :: (IsBuilder v s a c)\n => Builder v s a c -> Coeffs v -> Builder v s a c\nbuildObjective acc = buildPhaseI . buildPhaseII acc\n\n\nbuildLEQ\n :: forall v s a c.\n (IsBuilder v s a c)\n => Builder v s a c\n -> Coeffs v\n -> Double\n -> Builder v s a c\nbuildLEQ acc xs rhs = acc\n { slackSupply = tail (slackSupply acc)\n , rowsBuilt = row : rowsBuilt acc\n }\n where\n row = SVec.snoc (os ++ xs ++ ss ++ as) rhs\n os = SVec.fromTuple (0, 0)\n ss = head (slackSupply acc)\n as = SVec.replicate @a 0\n\n\nbuildGEQ\n :: forall v s a c.\n (IsBuilder v s a c)\n => Builder v s a c\n -> Coeffs v\n -> Double\n -> Builder v s a c\nbuildGEQ acc xs' rhs' = acc\n { slackSupply = tail (slackSupply acc)\n , artificialSupply = tail (artificialSupply acc)\n , rowsBuilt = row : rowsBuilt acc\n }\n where\n row = SVec.snoc (os ++ xs ++ ss ++ as) rhs\n os = SVec.fromTuple (0, 0)\n xs = SVec.map negate xs'\n ss = head (slackSupply acc)\n as = head (artificialSupply acc)\n rhs = negate rhs'\n\n\nbuildEQU\n :: forall v s a c.\n (IsBuilder v s a c)\n => Builder v s a c\n -> Coeffs v\n -> Double\n -> Builder v s a c\nbuildEQU acc xs rhs = acc\n { artificialSupply = tail (artificialSupply acc)\n , rowsBuilt = row : rowsBuilt acc\n , adjustmentsBuilt = row : adjustmentsBuilt acc\n }\n where\n row = SVec.snoc (os ++ xs ++ ss ++ as) rhs\n os = SVec.fromTuple (0, 0)\n ss = SVec.replicate @s 0\n as = head (artificialSupply acc)\n\n\nbuildConstraint :: (IsBuilder v s a c)\n => Builder v s a c -> Constraint v x y -> Builder v s a c\nbuildConstraint acc (xs :< y) = buildLEQ acc xs y\nbuildConstraint acc (xs :> y) = buildGEQ acc xs y\nbuildConstraint acc (xs := y) = buildEQU acc xs y\n\n\ntoMatrix :: forall v s a c. (IsBuilder v s a c)\n => Builder v s a c -> L (Rows 'PhaseI c) (Cols 'PhaseI v s a)\ntoMatrix acc =\n LS.rowsL . fromJust . Vec.fromList $ fmap LS.vecR adjusted\n where\n rows = rowsBuilt acc\n adjusts = adjustmentsBuilt acc\n\n adjusted = case adjusts of\n [] -> rows\n xs ->\n let oldObjP1 = head rows\n newObjP1 = List.foldl1' (SVec.zipWith (+)) (oldObjP1 : xs)\n in newObjP1 : tail rows\n\n\nmkTable :: forall d v s a c. (IsBuilder v s a c)\n => Problem d v s a c -> L (Rows 'PhaseI c) (Cols 'PhaseI v s a)\nmkTable = toMatrix . go mkBuilder\n where\n go :: Builder v s a c -> Problem d v x y z -> Builder v s a c\n go acc (Maximize xs) = buildObjective acc xs\n go acc (Minimize xs) = buildObjective acc xs\n go acc (SuchThat p c) = go (buildConstraint acc c) p\n\n", "meta": {"hexsha": "89000b91efcc91536338d505b08d0231ba58a785", "size": 5136, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Optimization/TwoPhase/Tableau/Build.hs", "max_stars_repo_name": "alex-mckenna/optimum", "max_stars_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-01-09T22:43:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T17:34:44.000Z", "max_issues_repo_path": "src/Numeric/Optimization/TwoPhase/Tableau/Build.hs", "max_issues_repo_name": "alex-mckenna/optimum", "max_issues_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "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/Optimization/TwoPhase/Tableau/Build.hs", "max_forks_repo_name": "alex-mckenna/optimum", "max_forks_repo_head_hexsha": "4137cf3aa4d96b86f74eed804a0eb582c6b28501", "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.3756906077, "max_line_length": 75, "alphanum_fraction": 0.5802180685, "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.3660039865049159}} {"text": "{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE NoStarIsType #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilyDependencies #-}\n{-# LANGUAGE TypeInType #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE ViewPatterns #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}\n\n\nmodule Numeric.Wavelet.Continuous (\n -- * Continuous Wavelet Transform\n CWD(..), mapCWD\n , CWDLine(..), mapCWDLine\n , LNorm(..), CWDOpts(..), defaultCWDO\n , cwd\n , cwdReal\n -- * Wavelets\n , AWavelet(..), mapAWavelet\n , morlet, morletFunc\n , meyer, meyerFunc\n , fbsp, fbspFunc\n ) where\n\nimport Data.Complex\nimport Data.Finite\nimport Data.Foldable\nimport Data.Maybe\nimport Data.Ord\nimport Data.Proxy\nimport Data.Type.Equality\nimport Data.Vector.Generic.Sized (Vector)\nimport GHC.Generics (Generic)\nimport GHC.TypeLits.Compare\nimport GHC.TypeNats\nimport Math.FFT.Base\nimport Numeric.Wavelet.Internal.FFT\nimport qualified Data.Vector.Generic as UVG\nimport qualified Data.Vector.Generic.Sized as VG\nimport qualified Data.Vector.Sized as V\n\n\nnewtype CWD v n m a b = CWD { cwdLines :: V.Vector m (CWDLine v n a b) }\n deriving (Show, Functor)\n\ndata CWDLine v n a b = CWDLine\n { cwdlData :: Vector v n b\n , cwdlScale :: Finite (n `Div` 2 + 1) -- ^ Scale factor, in number of ticks.\n , cwdlFreq :: a -- ^ The frequency associated with this scale, in inverse tick\n , cwdlCoI :: Finite (n `Div` 2 + 1) -- ^ How many items are /outside/ of the Cone of Influence, on each side.\n }\n deriving (Show, Functor)\n\nmapCWDLine\n :: (UVG.Vector v b, UVG.Vector v c)\n => (b -> c)\n -> CWDLine v n a b\n -> CWDLine v n a c\nmapCWDLine f (CWDLine d s q c) = CWDLine (VG.map f d) s q c\n\nmapCWD\n :: (UVG.Vector v b, UVG.Vector v c)\n => (b -> c)\n -> CWD v n m a b\n -> CWD v n m a c\nmapCWD f (CWD l) = CWD (mapCWDLine f <$> l)\n\ndata LNorm = L1 | L2\n deriving (Show, Eq, Ord, Enum, Bounded, Generic)\n\ndata CWDOpts n = CWDO\n { cwdoNorm :: LNorm -- ^ wavelet normalization\n , cwdoMinScale :: Finite (n `Div` 2 + 1) -- ^ min scale (period)\n , cwdoMaxScale :: Finite (n `Div` 2 + 1) -- ^ max scale (period)\n }\n deriving (Show, Eq, Ord, Generic)\n\ndefaultCWDO :: KnownNat n => CWDOpts n\ndefaultCWDO = CWDO\n { cwdoNorm = L2\n , cwdoMinScale = minBound\n , cwdoMaxScale = maxBound\n }\n\n-- | 'cwd' for complex-valued analytic wavelets.\ncwd :: forall v n m a b.\n ( UVG.Vector v (Complex b)\n , KnownNat n\n , KnownNat m\n , FFTWReal b\n , 1 <= n\n , RealFloat a\n )\n => AWavelet v a (Complex b)\n -> CWDOpts n\n -> Vector v n (Complex b)\n -> CWD v n m a (Complex b)\ncwd AW{..} CWDO{..} xs = CWD . VG.generate $ \\i ->\n let s = scaleOf i\n dt = 1/s\n in case awVector dt of\n VG.SomeSized (wv :: Vector v q (Complex b))\n | Just Refl <- isLE (Proxy @1) (Proxy @q)\n , Just Refl <- isLE (Proxy @((q-1)`Div`2)) (Proxy @(q-1))\n -> let ys :: Vector v (n + q - 1) (Complex b)\n ys = (* (realToFrac (normie dt) :+ 0)) `VG.map` convolve xs wv\n coi = fromMaybe maxBound . packFinite . round @a @Integer $ sqrt 2 * s\n s' = fromMaybe maxBound . packFinite . round @a @Integer $ s\n ys' :: Vector v n (Complex b)\n ys' = VG.slice @_ @((q - 1)`Div`2) @n @((q-1)-((q-1)`Div`2)) Proxy ys\n in CWDLine ys' s' (awFreq / s) coi\n _ -> error \"Bad scale: wavelet vector is empty?\"\n where\n n = natVal (Proxy @n)\n m = natVal (Proxy @m)\n normie :: a -> a\n normie = case cwdoNorm of\n L1 -> sqrt\n L2 -> id\n minScale = fromIntegral cwdoMinScale `max` 1\n maxScale = (fromIntegral cwdoMaxScale `min` (fromIntegral n / (2 * sqrt 2)))\n `max` (minScale + 1)\n scaleStep = (log maxScale - log minScale) / (fromIntegral m - 1)\n scaleOf :: Finite m -> a\n scaleOf i = exp $ log minScale + fromIntegral i * scaleStep\n\n-- | 'cwd' for real-valued analytic wavelets.\ncwdReal\n :: forall v n m a b.\n ( UVG.Vector v b\n , UVG.Vector v (Complex b)\n , KnownNat n\n , KnownNat m\n , FFTWReal b\n , 1 <= n\n , RealFloat a\n )\n => AWavelet v a b\n -> CWDOpts n\n -> Vector v n b\n -> CWD v n m a b\ncwdReal aw cwdo = mapCWD realPart\n . cwd (mapAWavelet (:+ 0) aw) cwdo\n . VG.map (:+ 0)\n\n-- | Analytical Wavelet\ndata AWavelet v a b = AW\n { awVector :: a -> v b -- ^ generate a vector within awRange with a given dt\n , awFreq :: a -- ^ Dominant frequency component\n , awRange :: a -- ^ range away from zero outside of which wavelet can be considered negligible\n }\n deriving Functor\n\nmapAWavelet\n :: (UVG.Vector v b, UVG.Vector v c)\n => (b -> c)\n -> AWavelet v a b\n -> AWavelet v a c\nmapAWavelet f (AW v q r) = AW (UVG.map f . v) q r\n\nmorlet\n :: (UVG.Vector v (Complex a), RealFloat a)\n => a\n -> AWavelet v a (Complex a)\nmorlet σ = AW{..}\n where\n awRange = 4\n (!awFreq, mf) = morletFunc_ σ\n awVector = renderFunc awRange mf\n\nmorletFunc :: RealFloat a => a -> a -> Complex a\nmorletFunc = snd . morletFunc_\n\nmorletFunc_ :: RealFloat a => a -> (a, a -> Complex a)\nmorletFunc_ σ = (q, f)\n where\n f t = (c * exp(-t*t/2) :+ 0) * (exp (0 :+ (σ * t)) - (exp (-σ2/2) :+ 0))\n !c = pi ** (-1/4) * (1 + exp (-σ2) - 2 * exp (-3/4*σ2)) ** (-1/2)\n !σ2 = σ * σ\n !q = converge 20 iter σ / (2 * pi)\n iter w = σ / (1 - exp (-σ * w))\n\nmeyer\n :: (UVG.Vector v a, RealFloat a)\n => AWavelet v a a\nmeyer = AW{..}\n where\n awRange = 6\n awVector = renderFunc awRange meyerFunc\n awFreq = 4 * pi / 3\n\nmeyerFunc :: RealFloat a => a -> a\nmeyerFunc t\n | isNaN ψ || isInfinite ψ = 0\n | otherwise = ψ\n where\n t' = t - 0.5\n t'3 = t'**3\n sinTerm = sin(4*pi/3*t') / pi\n ψ1 = (4/3/pi*t'*cos(2*pi/3*t') - sinTerm)\n / (t' - 16/9 * t'3)\n ψ2 = (8/3/pi*t'*cos(8*pi/3*t') + sinTerm)\n / (t' - 64/9 * t'3)\n ψ = ψ1 + ψ2\n\nfbsp\n :: (UVG.Vector v (Complex a), FFTWReal a)\n => Int -- ^ m, >= 1\n -> a -- ^ f_b, bandwidth\n -> a -- ^ f_c, wavelet center frequency\n -> AWavelet v a (Complex a)\nfbsp m fb fc = AW{..}\n where\n awRange = 4/fb\n awVector = renderFunc awRange (fbspFunc m fb fc)\n awFreq = autoDeriveFreq awRange awVector\n\nautoDeriveFreq\n :: (UVG.Vector v (Complex a), FFTWReal a)\n => a\n -> (a -> v (Complex a))\n -> a\nautoDeriveFreq r fv = case fv 0.001 of\n VG.SomeSized v ->\n let vv = zip [1..] . map magnitude . VG.toList $ fft v\n (i,_) = maximumBy (comparing snd) vv\n in fromInteger i / (r * 2)\n _ -> error \"bad vector\"\n\nfbspFunc :: RealFloat a => Int -> a -> a -> a -> Complex a\nfbspFunc m fb fc t =\n ((sqrt fb * sinc (fb * t / fromIntegral m))^m :+ 0) * exp (0 :+ (2 * pi * fc * t))\n where\n sinc x = sin x / x\n\n-- | Render the effective range of a wavelet (based on 'awRange'), centered\n-- around zero. Takes a timestep.\nrenderFunc\n :: (UVG.Vector v b, RealFrac a)\n => a -- ^ range about zero\n -> (a -> b) -- ^ func\n -> a -- ^ dt\n -> v b\nrenderFunc r f dt = UVG.generate (round n) $ \\i ->\n f (fromIntegral i * dt - r)\n where\n n = r * 2 / dt\n\nconverge\n :: (Fractional a, Ord a)\n => Int -- ^ maximum iterations\n -> (a -> a) -- ^ function to find the fixed point convergence\n -> a -- ^ starting value\n -> a\nconverge n f = go 0\n where\n go !i !x\n | i >= n = 0\n | abs (x - y) < 0.00001 = x\n | otherwise = go (i + 1) y\n where\n !y = f x\n\n", "meta": {"hexsha": "c27b53919c8e8e300480fda8de8c26b91377a1be", "size": 8802, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Numeric/Wavelet/Continuous.hs", "max_stars_repo_name": "mstksg/wavelets", "max_stars_repo_head_hexsha": "0ab91527b74bf136c306a940f6d4534b330d8e1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-10-11T20:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:49:54.000Z", "max_issues_repo_path": "src/Numeric/Wavelet/Continuous.hs", "max_issues_repo_name": "mstksg/pure-wavelets", "max_issues_repo_head_hexsha": "0ab91527b74bf136c306a940f6d4534b330d8e1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Wavelet/Continuous.hs", "max_forks_repo_name": "mstksg/pure-wavelets", "max_forks_repo_head_hexsha": "0ab91527b74bf136c306a940f6d4534b330d8e1f", "max_forks_repo_licenses": ["BSD-3-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.8913043478, "max_line_length": 115, "alphanum_fraction": 0.5123835492, "num_tokens": 2766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3625106226342995}} {"text": "{-# LANGUAGE RecordWildCards #-}\n\n{-|\nModule : HABQTlib.Data.Particle\n\nData structures and functions that deal with storing and processing particle\nhierarchies.\n\n/Warning/: functions in this module assume that the 'ptsParticles' is non-empty\nand 'NumberOfParticles', 'Dim', and 'Rank' are positive, no validation is\nperformed. If you use them directly, instead of employing API from\n\"HABQTlib\", you must ensure those assumptions hold.\n-}\nmodule HABQTlib.Data.Particle\n ( Particles(..)\n , genParticles\n , updateParticles\n , ParticleHierarchy\n , initialiseParticleHierarchy\n , updateParticleHierarchy\n , getMixedEstimate\n , foldOverPts\n , reduceParticlesToMean\n , effectiveSize\n , ResampleArgs(..)\n , resampleMultinom\n , resample\n , ecdf\n , icdf\n , nudgeParticle\n ) where\n\nimport Control.Monad (when)\nimport Control.Newtype.Generics (over)\nimport Data.Bool.HT (if', select)\nimport qualified Data.Vector as V\nimport HABQTlib.Data\nimport HABQTlib.RandomStates\nimport Numeric.LinearAlgebra (Complex(..))\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified System.Random.MWC as MWC\nimport Text.Printf (printf)\n\n-- | A vector of weighed density matrices is stored along with their rank and\n-- number. 'ptsWeight' corresponds to the collective weight of particles of\n-- rank 'ptsRank' in the hierarchical model, it is not the sum of individual\n-- weights of particles (that is normalised to unity after every update).\ndata Particles = Particles\n { ptsRank :: Rank\n , ptsWeight :: Weight\n , ptsNumber :: NumberOfParticles\n , ptsParticles :: V.Vector WeighedDensityMatrix\n } deriving (Show)\n\n-- | Particle hierarchy is described by a vector of 'Particles'.\ntype ParticleHierarchy = V.Vector Particles\n\n-- | Generates random particles (according to induced measure).\ngenParticles :: Dim -> Rank -> NumberOfParticles -> IO Particles\ngenParticles d r n =\n let w = 1 / fromIntegral n\n in Particles r 1 n . fmap (mkWDM w) <$> V.replicateM n (genDM d r)\n\n-- | Summarise particles to a mean estimate (weighed by the corresponding\n-- hierarchical weight of the rank).\nreduceParticlesToMean :: Particles -> WeighedDensityMatrix\nreduceParticlesToMean Particles {..} =\n let wdm = V.foldl1' (<+>) ptsParticles\n wdmw = over WeighedDensityMatrix (\\(w, dm) -> (w * ptsWeight, dm)) wdm\n in truncateRank ptsRank wdmw\n\n-- | Map density matrices, combine them with their weights, and then perform a\n-- (strict left) fold of results.\nfoldOverPts ::\n (DensityMatrix -> a) -- ^ function to map over density matrices\n -> (Weight -> a -> b) -- ^ function to combine weights with results of mapping\n -> (c -> b -> c) -- ^ fold funciton\n -> c -- ^ seed value for folding\n -> Particles\n -> c\nfoldOverPts f wf fld z Particles {..} =\n let wm (WeighedDensityMatrix (w, dm)) = wf w (f dm)\n in V.foldl' (\\l r -> fld l (wm r)) z ptsParticles\n\nfullDataLogLikelihood :: [PureStateVector] -> DensityMatrix -> Double\nfullDataLogLikelihood vs dm =\n let lps = map (log . (`pureStateLikelihood` dm)) vs\n in sum lps\n\n-- | Given a measurement result, perform a Bayesian update over the particles.\nupdateParticles :: PureStateVector -> Particles -> Particles\nupdateParticles sv pts@Particles {..} =\n let updateF :: WeighedDensityMatrix -> WeighedDensityMatrix\n updateF (WeighedDensityMatrix (w, dm)) = WeighedDensityMatrix (wnew, dm)\n where\n wnew = w * pureStateLikelihood sv dm\n upts = V.map updateF ptsParticles\n uw = V.foldl' (\\acc (WeighedDensityMatrix (w, _)) -> acc + w) 0 upts\n npts = V.map (over WeighedDensityMatrix (\\(w, dm) -> (w / uw, dm))) upts\n in pts {ptsWeight = ptsWeight * uw, ptsParticles = npts}\n\n-- | Helper function that generates random particles of each applicable rank.\ninitialiseParticleHierarchy :: Dim -> NumberOfParticles -> IO ParticleHierarchy\ninitialiseParticleHierarchy d n = V.generateM d (\\r -> genParticles d (r + 1) n)\n\n-- | Given a measurement result, update all particles, then normalise resulting\n-- hierarchical weights to sum to unity.\nupdateParticleHierarchy ::\n PureStateVector -> ParticleHierarchy -> ParticleHierarchy\nupdateParticleHierarchy sv ph =\n let uph = V.map (updateParticles sv) ph\n wgts = V.map ptsWeight uph\n nwgts = V.map (/ V.sum wgts) wgts\n in V.zipWith (\\x w -> x {ptsWeight = w}) uph nwgts\n\n-- | Summarise the whole particle hierarchy into one mean Bayesian estimate.\ngetMixedEstimate :: ParticleHierarchy -> DensityMatrix\ngetMixedEstimate ph =\n let rankEstimates = V.map reduceParticlesToMean ph\n WeighedDensityMatrix (_, result) = V.foldl1' (<+>) rankEstimates\n in result\n\n-- | Calculate the effective sample size of particles (weights don’t\n-- necessarily have to be normalised).\neffectiveSize :: Particles -> Double\neffectiveSize Particles {..} =\n let ss = V.sum . V.map ((^ (2 :: Int)) . fst . getWDM) $ ptsParticles\n wa = V.foldl' (flip ((+) . fst . getWDM)) 0 ptsParticles\n in wa ^ (2 :: Int) / ss\n\n-- | Nudges a particle by mixing the state together with some randomly\n-- generated pure state. Relative weight of the random component determines how\n-- “close” a nudged particle is to the original one.\nnudgeParticle ::\n Dim\n -> Weight -- ^ Relative weight (from 0 to 1) of random component\n -> WeighedDensityMatrix\n -> IO WeighedDensityMatrix\nnudgeParticle dim weightFraction (WeighedDensityMatrix (w, dm)) = do\n DensityMatrix nudgeDM <- svToDM <$> genPureSV dim\n let dmw = LA.scale (1 - (weightFraction :+ 0)) (getDensityMatrix dm)\n dmwn = LA.scale (weightFraction :+ 0) nudgeDM\n return $ WeighedDensityMatrix (w, DensityMatrix $ dmw + dmwn)\n\n-- | Calculates values of empirical distribution function at data points.\necdf :: V.Vector WeighedDensityMatrix -> V.Vector Double\necdf = V.postscanl' (+) 0 . V.map (fst . getWDM)\n\n-- | /O(log n)/ Given a non-empty sorted vector (typically an empirical cdf\n-- evaluated at data points returned by ecdf) and a real number return the\n-- (0-based) index of the least element of vector which is greater or equal to\n-- the given real number (or the index of the last element, in case there is no\n-- element smaller than the argument).\nicdf :: V.Vector Double -> Double -> Int\nicdf cdf x =\n let tIdx = V.length cdf - 1\n go (lIdx, hIdx) =\n let mIdx =\n truncate $ ((fromIntegral lIdx :: Double) + fromIntegral hIdx) / 2\n in select\n (go (lIdx, mIdx))\n [ (lIdx == hIdx, lIdx)\n , (lIdx + 1 == hIdx, if' (cdf V.! lIdx > x) lIdx hIdx)\n , (cdf V.! mIdx < x, go (mIdx, hIdx))\n ]\n in select (go (0, tIdx)) [(x <= V.head cdf, 0), (x > V.last cdf, tIdx)]\n\n-- | Multinomial resampling of particle vector, which equalises weights of\n-- particles.\nresampleMultinom :: MWC.GenIO -> Particles -> IO Particles\nresampleMultinom gen pts@Particles {..} = do\n us <- MWC.uniformVector gen ptsNumber\n let cdf = ecdf ptsParticles\n idxs = V.map (icdf cdf) us\n w = 1 / fromIntegral ptsNumber\n pointR = over WeighedDensityMatrix (\\(_, dm) -> (w, dm))\n resampled = V.map (ptsParticles V.!) idxs\n normed = V.map pointR resampled\n return pts {ptsParticles = normed}\n\nmhmcStep ::\n MWC.GenIO\n -> Dim\n -> Double\n -> [PureStateVector]\n -> Particles\n -> IO (Double, Particles)\nmhmcStep gen dim rw ms pts@Particles {..} = do\n let cr wdm wdm' =\n exp\n (fullDataLogLikelihood ms (snd . getWDM $ wdm') -\n fullDataLogLikelihood ms (snd . getWDM $ wdm))\n newParticles <-\n V.mapM (fmap (truncateRank ptsRank) . nudgeParticle dim rw) ptsParticles\n us <- V.replicateM ptsNumber (MWC.uniform gen :: IO Double)\n let crs = V.zipWith cr ptsParticles newParticles\n change = V.zipWith (<=) us crs\n accRate =\n (fromIntegral . V.length . V.filter id) change / fromIntegral ptsNumber\n rwdms = V.zipWith3 if' change newParticles ptsParticles\n final = pts {ptsParticles = rwdms}\n return (accRate, final)\n\nresampleMHMC ::\n ResampleArgs\n -> DensityMatrix\n -> Double\n -> Int\n -> [PureStateVector]\n -> Particles\n -> IO Particles\nresampleMHMC ra@ResampleArgs {..} estimate wr iter mts pts = do\n (accRate, resampled) <- mhmcStep argGen argDim wr mts pts\n when (argOut == FullOutput) $\n printf\n \"(Weight of new particle: %8.3g, MHMC acceptance rate: %8.3g)\\n\"\n wr\n accRate\n let (iter', wr') =\n select\n (iter + 1, wr)\n [ (accRate < 1e-2, (0, wr * 0.25))\n , (accRate < 1e-1, (0, wr * 0.5))\n , (iter < argMinIter, (iter + 1, wr))\n , (accRate < 0.33, (0, wr * 0.5))\n ]\n if iter > argMinIter\n then return resampled\n else resampleMHMC ra estimate wr' iter' mts resampled\n\n-- | Arguments for the resampling function.\ndata ResampleArgs = ResampleArgs\n { argOut :: OutputVerb\n , argGen :: MWC.GenIO\n , argDim :: Dim\n , argMinIter :: MHMCiter\n }\n\n-- | Resample particles. First does one multinomial step that equalises the\n-- weights, then performs MHMC iterations adaptively refining the proposal\n-- distribution based on acceptance rate. 'argMinIter' iterations are performed\n-- for proposal distributions with significant acceptance rates.\nresample :: ResampleArgs -> [PureStateVector] -> Particles -> IO Particles\nresample ra@ResampleArgs {..} mts pts@Particles {..} = do\n let estimate = getMixedEstimate . V.singleton $ pts\n nudgeW = 0.95\n when (argOut == FullOutput) $ do\n putStrLn \"\"\n putStrLn $ \"resampling rank \" ++ show ptsRank\n putStrLn \"\"\n rm <- resampleMultinom argGen pts\n resampleMHMC ra estimate nudgeW 0 mts rm\n", "meta": {"hexsha": "1be4366d51706ed97a57ceadec5babb78c8427d9", "size": 9581, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HABQTlib/Data/Particle.hs", "max_stars_repo_name": "Belinsky-L-V/HABQT", "max_stars_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-23T03:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T08:45:58.000Z", "max_issues_repo_path": "src/HABQTlib/Data/Particle.hs", "max_issues_repo_name": "Belinsky-L-V/HABQT", "max_issues_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HABQTlib/Data/Particle.hs", "max_forks_repo_name": "Belinsky-L-V/HABQT", "max_forks_repo_head_hexsha": "3ca377c4afb198e33051927221cea17e56441fb0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8695652174, "max_line_length": 80, "alphanum_fraction": 0.6850015656, "num_tokens": 2704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.36114412820857805}} {"text": "{-# LANGUAGE FlexibleContexts, FlexibleInstances, UndecidableInstances #-}\n\n-- Pure Haskell implementation of standard BFGS algorithm with cubic\n-- line search, with the BFGS step exposed to provide access to\n-- intermediate Hessian estimates.\n\n-- Author: Ian Ross, for OpenBrain Ltd\n\nmodule Fuml.Optimisation.BFGS\n ( BFGSOpts (..)\n , LineSearchOpts (..)\n , bfgs, bfgsWith\n , bfgsInit\n , bfgsStep, bfgsStepWith )\nwhere\n\nimport Numeric.LinearAlgebra\nimport Numeric.LinearAlgebra.Devel\nimport Data.Default\n--import Debug.Trace\n\n\n-- Type synonyms mostly just for documentation purposes...\ntype Point = Vector Double\ntype Gradient = Vector Double\ntype Direction = Vector Double\ntype Fn = Point -> Double\ntype GradFn = Point -> Vector Double\ntype Hessian = Matrix Double\n\n\n--------------------------------------------------------------------------------\n--\n-- NaN CHECKING\n--\n\nclass Nanable a where\n hasnan :: a -> Bool\n\ninstance Nanable Double where\n hasnan = isNaN\n\ninstance (Nanable a, Container c a) => Nanable (c a) where\n hasnan = not . null . (find hasnan)\n\n\n--------------------------------------------------------------------------------\n--\n-- BFGS\n--\n\n-- Options for BFGS solver: point tolerance, gradient tolerance,\n-- maximum iterations.\n--\ndata BFGSOpts = BFGSOpts { ptol :: Double\n , gtol :: Double\n , maxiters :: Int } deriving Show\n\ninstance Default BFGSOpts where\n def = BFGSOpts 1.0E-7 1.0E-7 200\n\n\n\n-- BFGS solver data to carry between steps: current point, function\n-- value at point, gradient at point, current direction, current\n-- Hessian estimate, maximum line search step.\n--\ndata BFGS = BFGS { p :: Point\n , fp :: Double\n , g :: Gradient\n , xi :: Direction\n , h :: Matrix Double\n , stpmax :: Double } deriving Show\n\n\n-- Main solver interface with default options.\n--\nbfgs :: Fn -> GradFn -> Point -> Either String (Point, Hessian)\nbfgs f df p0 = bfgsWith def f df p0 (ident $ size p0)\n\n\n{- Collection solver state into an infinite list: useful as \"take n $\n-- bfgsCollect f df b0\"\n--\nbfgsCollect :: Fn -> GradFn -> BFGS -> [BFGS]\nbfgsCollect f df b0 = map snd $ iterate step (False,b0)\n where step (cvg,b) = if cvg then b else bfgsStep f df b\n\n-}\n-- Utility function to set up initial BFGS state for bfgsCollect.\n--\nbfgsInit :: Fn -> GradFn -> Point -> Either String BFGS\nbfgsInit f df p0 = case (hasnan f0, hasnan g0) of\n (False, False) -> Right $ BFGS p0 f0 g0 (-g0) (ident n) (maxStep p0)\n _ -> Left $ nanMsg p0 (Just f0) (Just g0)\n where n = size p0 ; f0 = f p0 ; g0 = df p0\n\n\n-- Main iteration routine: sets up initial BFGS state, then steps\n-- until converged or maximum iterations exceeded.\n--\nbfgsWith :: BFGSOpts -> Fn -> GradFn -> Point -> Hessian -> Either String (Point, Hessian)\nbfgsWith opt@(BFGSOpts _ _ maxiters') f df p0 h0 =\n case (hasnan f0, hasnan g0) of\n (False, False) -> go 0 b0\n errs -> Left $ nanMsg p0 (Just f0) (Just g0)\n where go iters b =\n if iters > maxiters'\n then Left \"maximum iterations exceeded in bfgs\"\n else case bfgsStepWith opt f df b of\n Left err -> Left err\n Right (True, b') -> Right (p b', h b')\n Right (False, b') -> go (iters+1) $ {- trace (show $ (iters, fp b')) -} b'\n f0 = f p0 ; g0 = df p0\n b0 = BFGS p0 f0 g0 (-g0) h0 (maxStep p0)\n\n\n-- Do a BFGS step with default parameters.\n--\nbfgsStep :: Fn -> GradFn -> BFGS -> Either String (Bool, BFGS)\nbfgsStep = bfgsStepWith def\n\n\n-- Main BFGS step routine. This is a more or less verbatim\n-- translation of the description in Section 10.7 of Numerical Recipes\n-- in C, 2nd ed.\n--\nbfgsStepWith :: BFGSOpts -> Fn -> GradFn -> BFGS -> Either String (Bool, BFGS)\nbfgsStepWith (BFGSOpts ptol' gtol' _) f df (BFGS p fp g xi h stpmax) =\n case lineSearch f p fp g xi stpmax of\n Left err -> Left err\n Right (pn, fpn) ->\n if hasnan gn\n then Left $ nanMsg pn Nothing (Just gn)\n else if cvg\n then Right (True, BFGS pn fpn gn xi h stpmax)\n else Right (False, BFGS pn fpn gn xin hn stpmax)\n where gn = df pn ; dp = pn - p ; dg = gn - g ; hdg = h #> dg\n dpdg = dp `dot` dg ; dghdg = dg `dot` hdg\n hn = h + ((dpdg + dghdg) / dpdg^2) `scale` (dp `outer` dp) -\n (1/dpdg) `scale` (h <> (dg `outer` dp) + (dp `outer` dg) <> h)\n xin = -hn #> gn\n cvg = maxabsratio dp p < ptol' || maxabsratio' (fpn `max` 1) gn p < gtol'\n\n\n-- Generate error messages for NaN production in function and gradient\n-- calculations.\n--\nnanMsg :: Point -> Maybe Double -> Maybe Gradient -> String\nnanMsg p' fval grad = \"NaNs produced: p = \" ++ show p' ++\n maybe \"\" ((\" fval = \" ++) . show) fval ++\n maybe \"\" ((\" grad = \" ++) . show) grad\n\n\n--------------------------------------------------------------------------------\n--\n-- LINE SEARCH\n--\n\n-- Options for line search routine: point tolerance, \"acceptable\n-- decrease\" parameter.\n--\ndata LineSearchOpts = LineSearchOpts { xtol :: Double\n , alpha :: Double } deriving Show\n\ninstance Default LineSearchOpts where\n def = LineSearchOpts 1.0E-7 1.0E-4\n\n\n-- Maximum line search step length.\n--\nmaxStep :: Point -> Double\nmaxStep p0 = (100 * (norm_2 p0 `max` n))\n where n = fromIntegral (size p0)\n\n\n-- Line search with default parameters.\n--\nlineSearch :: Fn -> Point -> Double -> Gradient -> Direction ->\n Double -> Either String (Point, Double)\nlineSearch = lineSearchWith def\n\n\n-- Main line search routine. This is kind of nasty to translate into\n-- functional form because of the switching about between the\n-- quadratic and cubic approximations. It works, but it could be\n-- prettier.\n--\nlineSearchWith :: LineSearchOpts -> Fn -> Point -> Double -> Gradient ->\n Direction -> Double -> Either String (Point, Double)\nlineSearchWith (LineSearchOpts xtol alpha) func xold fold g pin stpmax =\n go 1.0 Nothing\n where p = if pinnorm > stpmax then (stpmax/pinnorm) `scale` pin else pin\n pinnorm = norm_2 pin\n slope = g `dot` p\n lammin = xtol / (maxabsratio p xold)\n\n go :: Double -> Maybe (Double,Double) -> Either String (Point,Double)\n go lam pass = if hasnan fnew\n then Left $ nanMsg xnew (Just fnew) Nothing\n else case check xnew fnew of\n Just xandf -> Right xandf\n Nothing ->\n case pass of\n -- First time.\n Nothing -> go (lambound $ quadlam fnew) $ Just (lam,fnew)\n -- Subsequent times.\n Just val2 -> case cubiclam fnew val2 of\n Right newlam -> go (lambound newlam) $ Just (lam,fnew)\n Left err -> Left err\n where xnew = xold + lam `scale` p\n fnew = func xnew\n\n -- Check for convergence or a \"sufficiently large\" step.\n check :: Vector Double -> Double -> Maybe (Vector Double,Double)\n check x f =\n if lam < lammin then Just (xold,fold)\n else if f <= fold + alpha * lam * slope\n then Just (x,f)\n else Nothing\n\n -- Keep step length within bounds.\n lambound lam' = max (0.1 * lam) (min lam' (0.5 * lam))\n\n -- Quadratic and cubic approximations to better step\n -- value.\n quadlam fnew = -slope / (2 * (fnew - fold - slope))\n cubiclam fnew (lam2,f2) =\n if a == 0\n then Right (-slope / (2 * b))\n else if disc < 0\n then Left \"Roundoff problem in lineSearch\"\n else Right $ (-b + sqrt disc) / (3 * a)\n where rhs1 = fnew - fold - lam * slope\n rhs2 = f2 - fold - lam2 * slope\n a = (rhs1 / lam^2 - rhs2 / lam2^2) / (lam - lam2)\n b = (-lam2 * rhs1 / lam^2 + lam * rhs2 / lam2^2) /\n (lam - lam2)\n disc = b^2 - 3 * a * slope\n\n\n-- Utility functions for ratio testing.\n--\nabsratio :: Double -> Double -> Double\nabsratio n d = abs n / (abs d `max` 1)\n\nabsratio' :: Double -> Double -> Double -> Double\nabsratio' scale n d = abs n / (abs d `max` 1) / scale\n\nmaxabsratio :: Vector Double -> Vector Double -> Double\nmaxabsratio n d = maxElement $ zipVectorWith absratio n d\n\nmaxabsratio' :: Double -> Vector Double -> Vector Double -> Double\nmaxabsratio' scale n d = maxElement $ zipVectorWith (absratio' scale) n d\n\n\n--------------------------------------------------------------------------------\n--\n-- TEST FUNCTIONS\n--\n\n-- Simple test function. Minimum at (3,4):\n--\n-- *BFGS> bfgs tstf1 tstgrad1 (fromList [-10,-10])\n-- Right (fromList [3.0,4.0])\n--\n\n{-\ntstf1 :: Fn\ntstf1 p = (x-3)^2 + (y-4)^2\n where [x,y] = toList p\n\ntstgrad1 :: GradFn\ntstgrad1 p = fromList [2*(x-3),2*(y-4)]\n where [x,y] = toList p\n\n\n-- Rosenbrock's function. Minimum at (1,1):\n--\n-- *BFGS> bfgs tstf2 tstgrad2 (fromList [-10,-10])\n-- Right (fromList [0.9999999992103538,0.9999999985219549])\n\ntstf2 :: Fn\ntstf2 p = (1-x)^2 + 100*(y-x^2)^2\n where [x,y] = toList p\n\ntstgrad2 :: GradFn\ntstgrad2 p = fromList [2*(x-1) - 400*x*(y-x^2), 200*(y-x^2)]\n where [x,y] = toList p\n\n\n-- Test function from Numerical Recipes. Minimum at (-2.0,0.89442719):\n--\n-- *BFGS> bfgs tstfnr tstgradnr nrp0\n-- Right (fromList [-1.9999999564447526,0.8944271925873616])\n\ntstfnr :: Fn\ntstfnr p = 10*(y^2*(3-x)-x^2*(3+x))^2+(2+x)^2/(1+(2+x)^2)\n where [x,y] = toList p\n\ntstgradnr :: GradFn\ntstgradnr p = fromList [20*(y^2*x3m-x^2*x3p)*(-y^2-6*x-3*x^2)+\n 2*x2p/(1+x2p^2)-2*x2p^3/(1+x2p^2)^2,\n 40*(y^2*x3m-x^2*x3p)*y*x3m]\n where [x,y] = toList p\n x3m = 3 - x\n x3p = 3 + x\n x2p = 2 + x\n\nnrp0 :: Point\nnrp0 = fromList [0.1,4.2]\n\n\n-- Test function to check NaN handling.\n--\n-- *BFGS> bfgs nantstf nantstgrad (fromList [-10,-10])\n-- Left \"function application returned NaN\"\n\nnantstf :: Fn\nnantstf p = log x + (x-3)^2 + (y-4)^2\n where [x,y] = toList p\n\nnantstgrad :: GradFn\nnantstgrad p = fromList [1/x+2*(x-3),2*(y-4)]\n where [x,y] = toList p\n-}", "meta": {"hexsha": "1c60ae183262da357eea73224e7a4d2ced46fe61", "size": 10522, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "fuml/lib/Fuml/Optimisation/BFGS.hs", "max_stars_repo_name": "avctrh/filopodia", "max_stars_repo_head_hexsha": "89ce0dc25a40c29773e862ef04fe5703b078fb79", "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": "fuml/lib/Fuml/Optimisation/BFGS.hs", "max_issues_repo_name": "avctrh/filopodia", "max_issues_repo_head_hexsha": "89ce0dc25a40c29773e862ef04fe5703b078fb79", "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": "fuml/lib/Fuml/Optimisation/BFGS.hs", "max_forks_repo_name": "avctrh/filopodia", "max_forks_repo_head_hexsha": "89ce0dc25a40c29773e862ef04fe5703b078fb79", "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.2760736196, "max_line_length": 90, "alphanum_fraction": 0.555787873, "num_tokens": 3095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3592972023119491}} {"text": "{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\nimport Data.List\nimport Data.Bits\nimport qualified Data.Set as S\nimport qualified Data.Map.Strict as M\nimport qualified Data.Map.Lazy as LM\nimport Text.Printf\nimport Numeric.LinearAlgebra hiding (find, (<>))\nimport Data.Functor\nimport Options.Applicative\nimport Control.Monad\nimport Data.Monoid\nimport Data.Function\nimport Debug.Trace\n\n-- no warning about Debug.Trace please\n_trace = trace\n\ntype Width = Int\n\ntype Mealy a b = [(a, ((a, [b]), (a, [b])))]\n\ndata L = S | M deriving (Eq, Ord, Enum, Bounded)\n\ninstance Show L where\n showsPrec _ S = ('S':)\n showsPrec _ M = ('M':)\n showList [] = ('·':)\n showList xs = foldr ((.) . shows) id xs\n\nbuildMealyRTL :: Width -> Mealy Int L\nbuildMealyRTL 1 = [ (0, ((0, [S]), (0, [M]))) ]\nbuildMealyRTL w =\n [ (0, ((0, [S]), (1, [M]))) ] ++\n [ (i, ((j, [S]), (j, [S]))) | i <- [1..w-1] , let j = (i+1) `mod` w]\n\nbuildMealy :: Width -> Mealy Int L\nbuildMealy 1 = [ (0, ((0, [S]), (0,[M]))) ]\nbuildMealy w = [ (n, edges n) | n <- [0..2^(w-1)-1] ]\n where\n -- The root\n edges 0 = ( (0, [S]), (1, []) )\n -- The intermediate nodes (scanning until the end of the window)\n edges n | n < 2^(w-2) = ( (2*n, []), (2*n+1, []) )\n -- The last bit of the window, we can output the leak\n edges n = ( (0, output (2*n)), (0, output (2*n+1)) )\n\n output n = replicate (w - lastbit - 1) S ++ [M] ++ replicate lastbit S\n where Just lastbit = find (\\i -> n `testBit` i) [0..]\n\n-- | This function reduces the number of nodes by commoning up\n-- equivalent nodes. Needs to be iterated.\nreduceMealyOnce :: (Ord a, Ord b) => Mealy a b -> Mealy a b\nreduceMealyOnce m\n = [ (n, ((f n0,s0), (f n1,s1)))\n | (n, ((n0,s0), (n1,s1))) <- m\n , f n == n\n ]\n where\n f = (M.!) $\n M.fromList\n [ (x, head dup)\n | dupSet <- M.elems $ M.fromListWith S.union [ (e,S.singleton n) | (n,e) <- m ]\n , let dup = S.toList dupSet\n , x <- dup\n ]\n\nreduceMealy :: (Ord a, Ord b) => Mealy a b -> Mealy a b\nreduceMealy m | length m == length m' = m\n | otherwise = reduceMealy m'\n where m' = reduceMealyOnce m\n\nmealy2dot :: (Show a, Show b) => Mealy a b -> String\nmealy2dot nodes = unlines $\n [ \"digraph {\" ] ++\n [ printf \"%s -> %s [label=\\\"0/%s\\\"];\\n\" (show n) (show n0) (show s0) ++\n printf \"%s -> %s [label=\\\"1/%s\\\"];\" (show n) (show n1) (show s1)\n | (n, ((n0, s0), (n1,s1))) <- nodes ] ++\n [ \"}\" ]\n\n\ntype Markov a = [(a, [a])]\n\nbuildMarkov :: (Ord a, Ord b) => (a,[b]) -> Mealy a b -> Markov (a,[b])\nbuildMarkov start mealy = go (S.singleton start) S.empty []\n where\n go todo done\n | S.null todo = id\n | (node,text) `S.member` done = go todo' done\n | otherwise = (((node,text), [n0', n1']):) .\n go todo'' (S.insert (node,text) done)\n\n where\n ((node,text), todo') = S.deleteFindMin todo\n Just ((n0, s0), (n1, s1)) = lookup node mealy\n n0' = (n0, tail text ++ s0)\n n1' = (n1, tail text ++ s1)\n todo'' = S.insert n0' (S.insert n1' todo')\n\n\nmarkov2dot :: (a -> String) -> (a -> String) -> Markov a -> String\nmarkov2dot col s nodes = unlines $\n [ \"digraph {\"\n -- , \"layout = neato;\"\n , \"margin = 0;\"\n , \"epsilon = 0.0001;\"\n , \"splines=true;\"\n -- , \"edge [len = 0.8];\"\n , \"edge [len = 1.3];\"\n , \"node [width=0.2];\"\n , \"node [height=0.2];\"\n , \"node [style=filled];\"\n ] ++\n [ printf \"%s [ color=%s]\" (s n) (col n)\n | (n, _) <- nodes ] ++\n [ printf \"%s -> %s;\\n\" (s n) (s n')\n | (n, succs) <- nodes , n' <- succs] ++\n [ \"}\" ]\n\ntype Dist a = M.Map a Double\n\nstationary :: Ord a => Markov a -> Dist a\nstationary = stationaryCond (const True)\n\nfindMaxIndex f xs = snd (maximum (zip (map f xs) [0..]))\n\nstationaryCond :: Ord a => (a -> Bool) -> Markov a -> Dist a\nstationaryCond nonDead markov\n -- | not ok1 = error \"First eigenvalue not 1\"\n | not ok2 = error \"Eigenvector does not consist of probabilities\"\n -- | not ok3 = error \"Eigenvector does not have eigenvalue 1\"\n | otherwise = M.fromList $ zip (map fst markov) (toList evec)\n where\n n = length markov\n\n transMatrix :: Matrix Double\n transMatrix = (n >< n) $\n [ if nonDead n then sum [ p | n' <- e, n' == n0 ] else 0\n | (n,e) <- markov\n , (n0,_) <- markov\n , let p = 1/fromIntegral (length e)\n ]\n\n (evals, evecs) = eig (tr transMatrix)\n -- Just i = findIndex isOne (toList evals)\n i = findMaxIndex realPart (toList evals)\n eval = evals `atIndex` i\n evecC = toColumns evecs !! i\n evecNorm = scale (1/sum (toList evecC)) evecC\n evec = cmap realPart evecNorm\n\n isOne c = magnitude (c - 1) < 0.0000001\n isProb c = abs (imagPart c) < 0.0000001 && realPart c >= 0 && realPart c <= 1\n\n ok1 = magnitude (eval - 1) < 0.001\n ok2 = all isProb (toList evecNorm)\n ok3 = norm_2 (evec - (evec <# transMatrix)) < 0.001\n\n\nprodMarkov :: Markov a -> Markov (a,a)\nprodMarkov markov =\n [ ((n1,n2), (,) <$> e1 <*> e2)\n | (n1, e1) <- markov\n , (n2, e2) <- markov\n ]\n\nfilterMarkov :: (a -> Bool) -> Markov a -> Markov (Maybe a)\nfilterMarkov p markov =\n (Nothing, [Nothing]) : [ (Just n, map (justIf p) e) | (n, e) <- markov, p n ]\n\njustIf p n = if p n then Just n else Nothing\n\n-- Removes all edges from nodes where p does not hold, and all nodes\n-- not reachable\ndeadEnd :: Ord a => (a -> Bool) -> a -> Markov a -> Markov a\ndeadEnd p start markov = go S.empty [start]\n where\n edges = (M.fromList markov M.!)\n go done [] = []\n go done (x:todo) | x `elem` done = go done todo\n | otherwise = (x, e) : go (S.insert x done) todo'\n where e = edges x\n todo' | p x = e ++ todo\n | otherwise = todo\n\nliveNodes :: Ord a => a -> Markov a -> S.Set a\nliveNodes start markov = go (S.singleton start)\n where\n edges = (M.fromList markov M.!)\n go live | S.size live == S.size live' = live\n | otherwise = go live'\n where live' = live `S.union` S.fromList [ n | (n,e) <- markov, any (`S.member` live) e ]\n\n-- | This function reduces the number of nodes by commoning up\n-- equivalent nodes. Needs to be iterated.\nreduceMarkovOnce :: (Ord a, Ord b) => (a -> b) -> Markov a -> Markov a\nreduceMarkovOnce l m\n = [ (n, map f e) | (n, e) <- m, f n == n ]\n where\n f = (M.!) $\n M.fromList\n [ (x, head dup)\n | dupSet <- M.elems $ M.fromListWith S.union [ ((l n,sort e),S.singleton n) | (n,e) <- m ]\n , let dup = S.toList dupSet\n , x <- dup\n ]\n\nreduceMarkov :: (Ord a, Ord b) => (a -> b) -> Markov a -> Markov a\nreduceMarkov leak m | length m == length m' = m\n | otherwise = reduceMarkov leak m'\n where m' = reduceMarkovOnce leak m\n\n-- If two independent copies of the markov chain, starting in the given\n-- distribution are run n steps, what is the probability that the output is the\n-- same?\nsampleCollisions :: forall a b. (Ord a, Eq b) => Int -> (a -> b) -> Markov a -> Dist a -> Double\nsampleCollisions n f markov dist =\n sum [ p * fromIntegral (countCollisions n n1 n2)\n | ((n1, n2),p) <- M.toList $ prodDist dist\n ] / 2^(2*n)\n where\n edges = (M.fromList markov M.!)\n\n -- From these two states on for further n steps, how many collisions?\n countCollisions :: Int -> a -> a -> Integer\n countCollisions 0 _ _ = 1\n countCollisions i n1 n2\n | f n1 == f n2 = sum [ countMemo (i-1) (n1', n2')\n | n1' <- edges n1\n , n2' <- edges n2\n ]\n | otherwise = 0\n\n -- Yay, memoization!\n countMemo = curry (LM.fromList [ ((i,(n1,n2)), countCollisions i n1 n2) | i <- [0..n], n1 <- map fst markov, n2 <- map fst markov] M.!)\n\n\n-- A typical output function\nleak :: (a,[b]) -> b\nleak (_,s) = head s\n\n\ncolorNode :: (a,[L]) -> String\ncolorNode s = if leak s == S then \"lightblue\" else \"green1\"\n\nshowNode :: (Show a, Show b) => (a,[b]) -> String\nshowNode (node,s) = show s ++ show node\n\nshowNode2 :: (Show a, Show b) => ((a,[b]),(a,[b])) -> String\nshowNode2 (n1,n2) = showNode n1 ++ \"_\" ++ showNode n2\n\ncalcPnl :: forall a b. (Ord a, Ord b) => Int -> (a -> b) -> Markov a -> Dist a -> Dist (a, [b])\ncalcPnl n f markov dist = jointDist dist $ \\x1 -> normDist $ leakDist n x1\n where\n edges = (M.fromList markov M.!)\n\n -- Calculate the distribution of leaks\n -- (of the given length, starting in the given node)\n -- This is the performance hot spot in this program! (until I introduce memoization)\n leakDist :: Int -> a -> Dist [b]\n leakDist 0 _ = M.singleton [] 1\n leakDist i node = M.mapKeysMonotonic (f node :) $ addDists $\n [ leakDistMemo (i-1) n' | n' <- edges node ]\n\n -- Yay, memoization!\n leakDistMemo = curry (LM.fromList [ ((i,node), leakDist i node) | i <- [0..n], node <- map fst markov ] M.!)\n\ncalcPl :: forall a b. (Ord a, Ord b) => Int -> (a -> b) -> Markov a -> Dist a -> Dist [b]\ncalcPl n f markov dist =\n addDists [ fmap (p*) (normDist $ leakDist n x1) | (x1, p) <- M.toList dist ]\n where\n edges = (M.fromList markov M.!)\n\n -- Calculate the distribution of leaks\n -- (of the given length, starting in the given node)\n -- This is the performance hot spot in this program! (until I introduce memoization)\n leakDist :: Int -> a -> Dist [b]\n leakDist 0 _ = M.singleton [] 1\n leakDist i node = M.mapKeysMonotonic (f node :) $ addDists $\n [ leakDistMemo (i-1) n' | n' <- edges node ]\n\n -- Yay, memoization!\n leakDistMemo = curry (LM.fromList [ ((i,node), leakDist i node) | i <- [0..n], node <- map fst markov ] M.!)\n\ncondEntropyLB :: (Ord a, Ord b) => Dist (a, [b]) -> Dist (a, [b]) -> Double\ncondEntropyLB pnl pnlbar = sum\n [ pxy * logb (px/pxy)\n | ((xi,ys),pxy) <- M.toList pnl\n , let px = pnlbar M.! (xi, init ys)\n ]\n\ncondEntropyUB :: Ord b => Dist [b] -> Dist [b] -> Double\ncondEntropyUB pl plbar = sum\n [ pxy * logb (px/pxy)\n | (ys,pxy) <- M.toList pl\n , let px = plbar M.! init ys\n ]\n\nmarkovStepProb :: Ord a => (a -> Bool) -> Markov a -> Dist a -> Double\nmarkovStepProb p markov dist = sum\n [ pn * sum [ 1 | n' <- e, p n'] / fromIntegral (length e)\n | (n,pn) <- M.toList dist\n , let e = edges n\n ]\n where\n edges = (M.fromList markov M.!)\n\n\nlogb :: Double -> Double\nlogb = logBase 2\n\nsamplesToDist :: Ord a => [a] -> Dist a\nsamplesToDist xs = normDist $ M.fromListWith (+) [ (x,1) | x <- xs ]\n\n-- | Take the union of two distributions (not normalised)\naddDist :: Ord a => Dist a -> Dist a -> Dist a\naddDist = M.unionWith (+)\n\naddDists :: Ord a => [Dist a]-> Dist a\naddDists = M.unionsWith (+)\n\nmapDist :: Ord b => (a -> b) -> Dist a -> Dist b\nmapDist = M.mapKeysWith (+)\n\nnormDist :: M.Map a Double -> M.Map a Double\nnormDist m = fmap (/sum m) m\n\njointDist :: (Ord a, Ord b) => Dist a -> (a -> Dist b) -> Dist (a,b)\njointDist d1 f = M.unionsWith (error \"Not disjoint\") $\n [ M.mapKeysMonotonic (a,) $ fmap (p_a*) (f a)\n | (a, p_a) <- M.toList d1\n ]\n\nprodDist :: Ord a => Dist a -> Dist (a,a)\nprodDist d = M.fromListWith (error \"input wrong\") $\n [ ((x,y), px * py) | (x,px) <- M.toList d, (y,py) <- M.toList d ]\n\nsamplePred :: (a -> Bool) -> Dist a -> Double\nsamplePred ok d = sum [ p | (x,p) <- M.toList d, ok x ]\n\nconditionalDist :: Ord a => Dist (Maybe a) -> Dist a\nconditionalDist d = normDist $ M.fromListWith (error \"input wrong\") $\n [ (n, p) | (Just n, p) <- M.toList d ]\n\ndata WhichGraph = RTL | LTR deriving Eq\ndata WhatToDo = PrintMealy\n | PrintMarkov\n | PrintCollMarkov\n | PrintEntropy\n | PrintTableRow\n | PrintColl\n deriving Eq\n\nrun :: Int -> Int -> WhichGraph -> WhatToDo -> IO ()\nrun w n which todo = do\n let my = case which of\n RTL -> reduceMealy $ buildMealyRTL w\n LTR -> reduceMealy $ buildMealy w\n let n0 = (0, replicate w S)\n let mv = buildMarkov n0 my\n let sd = stationary mv\n let singletonDist = M.singleton n0 1\n let ud = M.fromList mv $> ((1::Double) / fromIntegral (length mv))\n let pnl = calcPnl n leak mv sd\n let pnlbar = calcPnl (n-1) leak mv sd\n let eLB = condEntropyLB pnl pnlbar\n let pl = calcPl n leak mv sd\n let plbar = calcPl (n-1) leak mv sd\n let eUB = condEntropyUB pl plbar\n\n let prodMv = prodMarkov mv\n let thinProdMV = reduceMarkov (\\(n1,n2) -> leak n1 == leak n2) prodMv\n -- ^ This is just to feed less data to the linear algrebra system\n let collSD = stationaryCond (\\(n1,n2) -> leak n1 == leak n2) thinProdMV\n let collP = samplePred (\\(n1,n2) -> leak n1 == leak n2) collSD\n let collRate = - logb collP\n\n let simCollP = sampleCollisions n leak mv sd -- singletonDist\n let simCollisions = simCollP^(2::Int) * 2^n\n let simCollRate = - (logb simCollP) / fromIntegral n\n\n case todo of\n PrintMealy -> putStrLn (mealy2dot my)\n PrintMarkov -> putStrLn (markov2dot colorNode showNode mv)\n PrintCollMarkov -> error \"unimplemented\" -- putStrLn (markov2dot showNode2 collidingMv)\n PrintTableRow -> printf \"%d\\t%d\\t%f\\t%f\\t%f\\n\" w n eLB eUB collRate\n PrintColl -> error \"unimplemented\" -- print collisions\n PrintEntropy -> printf \"w: %2d. n: %3d. %.4f ≤ H(Y) ≤ %.4f. coll rate: %.4f. sim coll rate: %.4f \\n\"\n w n eLB eUB collRate simCollRate\n\n\nmain :: IO ()\nmain = join . execParser $\n info (helper <*> parser)\n ( fullDesc\n <> header \"Entropy calculation\"\n )\n where\n parser :: Parser (IO ())\n parser = run\n <$> option auto\n ( long \"width\"\n <> short 'w'\n <> metavar \"WIDTH\"\n <> help \"Width of the window (typical 4 or 5)\"\n <> value 4\n <> showDefault\n )\n <*> option auto\n ( long \"n\"\n <> short 'n'\n <> metavar \"N\"\n <> help \"approximation\"\n <> value 10\n <> showDefault\n )\n <*> choice\n [ flag' LTR (long \"ltr\" <> help \"Analyse left-to-right\")\n , flag' RTL (long \"rtl\" <> help \"Analyse right-to-left\")\n , pure LTR\n ]\n <*> choice\n [ flag' PrintMealy (long \"mealy\" <> help \"Print Mealy graph in .dot format\")\n , flag' PrintMarkov (long \"markov\" <> help \"Print Markov graph in .dot format\")\n , flag' PrintCollMarkov (long \"colliding-markov\" <> help \"Print colliding Markov graph in .dot format\")\n , flag' PrintTableRow (long \"table\" <> help \"Print a tsv table row\")\n , flag' PrintColl (long \"coll\" <> help \"Print collision probability tsv row\")\n , pure PrintEntropy\n ]\n\nchoice :: Alternative f => [f a] -> f a\nchoice = foldr1 (<|>)\n", "meta": {"hexsha": "5b9a78f76060442c9f9ab0f9df3188031d1e480d", "size": 14870, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "markoventropy.hs", "max_stars_repo_name": "nomeata/slidingright", "max_stars_repo_head_hexsha": "ac086cf7b22699227ea6f9c3cbbe6ffecbda5a81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-12-11T22:58:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T07:19:12.000Z", "max_issues_repo_path": "markoventropy.hs", "max_issues_repo_name": "nomeata/slidingright", "max_issues_repo_head_hexsha": "ac086cf7b22699227ea6f9c3cbbe6ffecbda5a81", "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": "markoventropy.hs", "max_forks_repo_name": "nomeata/slidingright", "max_forks_repo_head_hexsha": "ac086cf7b22699227ea6f9c3cbbe6ffecbda5a81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.183908046, "max_line_length": 139, "alphanum_fraction": 0.5552118359, "num_tokens": 4842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.35919392085984597}} {"text": "{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}\n\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-|\nModule : Grenade.Layers.Reshape\nDescription : Multipurpose reshaping layer\nCopyright : (c) Huw Campbell, 2016-2017\nLicense : BSD2\nStability : experimental\n-}\nmodule Grenade.Layers.Reshape\n ( Reshape(..)\n ) where\n\nimport Control.DeepSeq (NFData (..))\nimport Data.Serialize\nimport GHC.Generics (Generic)\nimport GHC.TypeLits\nimport Numeric.LinearAlgebra.Data as LA (flatten)\nimport Numeric.LinearAlgebra.Static\n\nimport Grenade.Core\n\nimport Grenade.Onnx\n\n-- | Reshape Layer\n--\n-- The Reshape layer can flatten any 2D or 3D image to 1D vector with the\n-- same number of activations, as well as cast up from 1D to a 2D or 3D\n-- shape.\n--\n-- Can also be used to turn a 3D image with only one channel into a 2D image\n-- or vice versa.\ndata Reshape = Reshape\n deriving (Show,Generic,NFData)\n\ninstance UpdateLayer Reshape where\n type Gradient Reshape = ()\n runUpdate _ _ _ = Reshape\n reduceGradient _ = ()\n\ninstance RandomLayer Reshape where\n createRandomWith _ _ = return Reshape\n\ninstance (KnownNat a, KnownNat x, KnownNat y, a ~ (x * y)) => Layer Reshape ('D2 x y) ('D1 a) where\n type Tape Reshape ('D2 x y) ('D1 a) = ()\n runForwards _ (S2D y) = ((), fromJust' . fromStorable . flatten . extract $ y)\n runBackwards _ _ (S1D y) = ((), fromJust' . fromStorable . extract $ y)\n\ninstance (KnownNat a, KnownNat x, KnownNat y, KnownNat (x * z), KnownNat z, a ~ (x * y * z)) => Layer Reshape ('D3 x y z) ('D1 a) where\n type Tape Reshape ('D3 x y z) ('D1 a) = ()\n runForwards _ (S3D y) = ((), fromJust' . fromStorable . flatten . extract $ y)\n runBackwards _ _ (S1D y) = ((), fromJust' . fromStorable . extract $ y)\n\ninstance (KnownNat y, KnownNat x, KnownNat z, z ~ 1) => Layer Reshape ('D3 x y z) ('D2 x y) where\n type Tape Reshape ('D3 x y z) ('D2 x y) = ()\n runForwards _ (S3D y) = ((), S2D y)\n runBackwards _ _ (S2D y) = ((), S3D y)\n\ninstance (KnownNat y, KnownNat x, KnownNat z, z ~ 1) => Layer Reshape ('D2 x y) ('D3 x y z) where\n type Tape Reshape ('D2 x y) ('D3 x y z) = ()\n runForwards _ (S2D y) = ((), S3D y)\n runBackwards _ _ (S3D y) = ((), S2D y)\n\ninstance (KnownNat a, KnownNat x, KnownNat y, a ~ (x * y)) => Layer Reshape ('D1 a) ('D2 x y) where\n type Tape Reshape ('D1 a) ('D2 x y) = ()\n runForwards _ (S1D y) = ((), fromJust' . fromStorable . extract $ y)\n runBackwards _ _ (S2D y) = ((), fromJust' . fromStorable . flatten . extract $ y)\n\ninstance (KnownNat a, KnownNat x, KnownNat y, KnownNat (x * z), KnownNat z, a ~ (x * y * z)) => Layer Reshape ('D1 a) ('D3 x y z) where\n type Tape Reshape ('D1 a) ('D3 x y z) = ()\n runForwards _ (S1D y) = ((), fromJust' . fromStorable . extract $ y)\n runBackwards _ _ (S3D y) = ((), fromJust' . fromStorable . flatten . extract $ y)\n\ninstance (KnownNat a, KnownNat b, KnownNat c, KnownNat w, KnownNat x, KnownNat y, KnownNat z, (a * b * c) ~ (w * x * y * z)) => Layer Reshape ('D3 a b c) ('D4 w x y z) where\n type Tape Reshape ('D3 a b c) ('D4 w x y z) = ()\n runForwards _ (S3D y) = ((), fromJust' . fromStorable . flatten . extract $ y)\n runBackwards _ _ (S4D y) = ((), fromJust' . fromStorable . flatten . extract $ y)\n\ninstance (KnownNat a, KnownNat b, KnownNat c, KnownNat d, KnownNat x, KnownNat y, KnownNat z, (a * b * c * d) ~ (x * y * z)) => Layer Reshape ('D4 a b c d) ('D3 x y z) where\n type Tape Reshape ('D4 a b c d) ('D3 x y z) = ()\n runForwards _ (S4D y) = ((), fromJust' . fromStorable . flatten . extract $ y)\n runBackwards _ _ (S3D y) = ((), fromJust' . fromStorable . flatten . extract $ y)\n\ninstance Serialize Reshape where\n put _ = return ()\n get = return Reshape\n\nfromJust' :: Maybe x -> x\nfromJust' (Just x) = x\nfromJust' Nothing = error \"Reshape error: data shape couldn't be converted.\"\n\ninstance OnnxOperator Reshape where\n onnxOpTypeNames _ = [\"Flatten\", \"Reshape\"]\n\ninstance OnnxLoadableActivation Reshape where\n activationLayer = Reshape\n", "meta": {"hexsha": "72f852439be28c088d00447083060d883c9c1d07", "size": 4536, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Grenade/Layers/Reshape.hs", "max_stars_repo_name": "th-char/grenade", "max_stars_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T06:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T06:06:26.000Z", "max_issues_repo_path": "src/Grenade/Layers/Reshape.hs", "max_issues_repo_name": "th-char/grenade", "max_issues_repo_head_hexsha": "0be658e7cf07562cd5e4170ed1e8875ccec14cdb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Grenade/Layers/Reshape.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": 41.6146788991, "max_line_length": 173, "alphanum_fraction": 0.6194885362, "num_tokens": 1463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3567725498708897}} {"text": "{-|\nModule : Data.Meta.NMA\nDescription : Second stage NMA\nCopyright : (c) Thodoris Papakonstantinou, 2019\nLicense : GPL-3\nMaintainer : mail@tpapak.com\nStability : experimental\nPortability : POSIX\n\nGiven a study graph of direct effects perform network-meta analysis\n-}\n\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE NamedFieldPuns #-}\n\nmodule Data.Meta.NMA\n ( NetworkEffects (..)\n , Spring (..)\n , springNMA\n )\nwhere\n\nimport Control.Applicative\nimport Data.List\nimport Data.Tuple\nimport qualified Data.Map.Strict as Map\nimport qualified Data.Set as Set\nimport Data.Maybe\nimport Data.Either\nimport qualified Data.IntMap.Strict as IM\n\nimport qualified Numeric.LinearAlgebra as LA\n\nimport qualified Data.Graph.AdjacencyList as G\nimport qualified Data.Graph.AdjacencyList.BFS as BFS\n\nimport Data.Meta.Effects\nimport Data.Meta.Matrices\nimport Data.Meta.Studies\n\ndata Effect a => NetworkEffects a = \n NetworkEffects { directs :: StudyGraph a\n --, leagueTable :: LA.Matrix Double\n --, lstar :: Map.Map G.Edge (Either Spring Spring)\n --, lstar :: Map.Map G.Edge Double\n , networkEstimates :: Map.Map TreatmentId (Map.Map TreatmentId Double)\n , networkVariances :: Map.Map TreatmentId (Map.Map TreatmentId Double)\n , debugmsg :: String\n }\n deriving (Show, Eq)\n\n-- | Matrices needed for solving the linear system\ndata Matrices = Matrices { kMatrix :: LA.Matrix Double\n , llMatrix :: [Double]\n , cMatrix :: LA.Matrix Double\n , dMatrix :: LA.Matrix Double\n , xMatrix :: LA.Matrix Double\n , spnTr :: Set.Set G.Edge\n , parents :: IM.IntMap G.Vertex\n , vss :: [G.Vertex]\n , directEdges :: Set.Set G.Edge\n }\n\ntype NaturalLength = Double\ntype Hardness = Double\ntype SpringLength = Double\n\ndata Spring = Spring Hardness NaturalLength SpringLength\n deriving (Show, Eq)\n\nreverseSpring :: Spring -> Spring\nreverseSpring (Spring k ll l) = Spring k (-ll) (-l)\n\nhardness :: Spring -> Hardness\nhardness (Spring k _ _) = k\n\nnaturalLength :: Spring -> NaturalLength\nnaturalLength (Spring _ ll _) = ll\n\nspringLength :: Spring -> SpringLength\nspringLength (Spring _ _ l) = l\n\ntype TauSquare = Double\n\nspringNMA :: (ArmEffect a b, Gaussian a, Gaussian b) => [Study]\n -> Maybe G.Vertex\n -> Maybe TauSquare\n -> (Arm -> Either String a)\n -> Either String (NetworkEffects b)\nspringNMA studies mpinnedVertex mtau2 armEffect = \n let vs = foldl' (\\acvs study -> \n let sid = getStudyId study\n arms = getStudyArms study\n in case mtau2 of\n Nothing -> Set.insert (Left sid) $ Set.union acvs \n $ Set.fromList $ map (Right . tidOfArm) arms\n Just tau2 -> \n let tauvs = Set.fromList $ map (\\a \n -> Left $ StudyId $ StringId ((show sid) ++ \"_\" ++ (show $ tidOfArm a))) arms\n tidvs = Set.fromList $ map (Right . tidOfArm) arms\n in Set.insert (Left sid) $ Set.union acvs $ Set.union tauvs tidvs\n ) Set.empty studies :: Set.Set (Either StudyId TreatmentId)\n vssts = IM.fromList $ zip [1..] $ Set.toList vs\n stsvs = Map.fromList $ map swap $ IM.toList vssts\n Right vsts = sequence $ IM.filter isRight vssts -- only treatment vertices\n tsvs = Map.fromList $ map swap $ IM.toList vsts\n esprings = foldl' (\\eaces study -> \n let sid = getStudyId study\n arms = getStudyArms study\n studysprings = sequence $ case armEffect $ head arms of\n Left err -> [Left err]\n Right aArm -> \n foldl' (\\acc a -> case armEffect a of\n Left err -> Left err : acc\n Right armef -> \n let tid = tidOfArm a\n tausid = StudyId $ StringId ((show sid) ++ \"_\" ++ show tid)\n vs = stsvs Map.! (Left sid)\n vt = stsvs Map.! (Right tid)\n vtau = stsvs Map.! (Left tausid)\n eff = relatedRelative armef\n nl = expectation eff\n k = 1 / (variance eff)\n spr = Spring k nl nl\n in case mtau2 of\n Nothing -> \n let sttrEdge = G.Edge vs vt\n in (Right (sttrEdge, spr)) : acc\n Just tau2 -> \n let sttauEdge = G.Edge vs vtau\n sttauspr = Spring (2/tau2) 0 0 -- That's where tau2 is inserted\n tautrEdge = G.Edge vtau vt\n in [Right (sttauEdge, sttauspr)\n , Right (tautrEdge, spr)] <> acc\n ) [] arms :: [Either String (G.Edge, Spring)]\n in case eaces of \n Left err -> Left err\n Right aces -> \n case studysprings of\n Left err -> Left err\n Right sprs -> Right (sprs ++ aces)\n ) (Right []) studies :: Either String [(G.Edge,Spring)]\n in case esprings of \n Left err -> Left err\n Right springs -> \n let springsMap = Map.fromList springs\n es = Map.keys springsMap\n numEdges = length es\n directedSG = G.graphFromEdges es\n undirectedSG = G.makeUndirected directedSG\n getSpring :: G.Edge -> Spring -- from undirected edge to spring\n getSpring e =\n case Map.lookup e springsMap of\n Nothing -> reverseSpring $ springsMap Map.! (G.reverseEdge e)\n Just sp -> sp\n pinnedV = \n case mpinnedVertex of\n Just p -> p\n Nothing -> 1\n -- | get the Matrices corresponding to defined pinned Vertex\n getMatrices :: G.Vertex -> Matrices \n getMatrices pinnedVertex = \n -- | Networks spanning tree\n let netbfs = BFS.bfs undirectedSG pinnedVertex\n spnTr = Set.fromList $ BFS.spanningTree netbfs\n parents = BFS.parent netbfs\n vss = map (\\(G.Edge u v)->v) (Set.toList spnTr)\n llmap = Map.fromList $ map (\\e ->\n case Set.member e spnTr of\n True -> (e, Right $ getSpring e)\n False -> let re = G.reverseEdge e \n in case Set.member re spnTr of\n True -> (re, Right $ getSpring re)\n False -> (e, Left $ getSpring e)\n ) es\n -- | L vector (E><1) with the natural lengths of springs which respect\n -- the spanning tree orientation\n directEdges = Set.fromList $ Map.keys llmap\n llMatrix = map (\\de -> \n let ms = llmap Map.! de \n in case ms of \n Left sp -> naturalLength sp\n Right sp -> naturalLength sp)\n $ Set.toList directEdges\n -- weight matrix (E x E)\n kMatrix = LA.diagl $ map (hardness . getSpring) $ Set.toList directEdges\n -- cMatrix (V-1 x E) \n cMatrix = \n let vertexToRow :: G.Vertex -> [Double]\n vertexToRow x = map (\\(G.Edge u v) -> \n if x==u\n then 1.0\n else\n if x==v then (-1)\n else 0\n )\n $ Set.toList directEdges\n in LA.fromLists $ map vertexToRow vss\n -- D matrix (V-1 x E)\n dMatrix = cMatrix LA.<> kMatrix\n -- X matrix (E x (V-1)) consistency matrix\n -- Definition: X <> L* = L\n xMatrix = \n let edgeToRow :: G.Edge -> [Double]\n edgeToRow (G.Edge u v) =\n let r = replicate (length vss) 0\n r' = IM.fromList $ zip vss r\n followEnd :: G.Vertex \n -> IM.IntMap Double\n -> IM.IntMap Double\n followEnd k r =\n if k == pinnedVertex \n then r\n else\n let r' = IM.adjust (+ 1) k r\n k' = (BFS.parent netbfs) IM.! k\n in followEnd k' r'\n followStart k r =\n if k == pinnedVertex \n then r\n else\n let r' = IM.adjust (+ (-1)) k r\n k' = (BFS.parent netbfs) IM.! k\n in followStart k' r'\n r'' = followEnd v $ followStart u r'\n in map (\\v -> r'' IM.! v) vss -- has to respect vss ordering\n in LA.fromLists $ map edgeToRow $ Set.toList directEdges\n in Matrices { kMatrix\n , llMatrix\n , cMatrix\n , dMatrix\n , xMatrix\n , parents\n , spnTr \n , vss\n , directEdges\n }\n -- | l* (V-1 >< 1) where V-1 are the end vertices of the spanning\n -- tree\n mtrcs = getMatrices pinnedV\n kMatrix'= kMatrix mtrcs \n llMatrix'= llMatrix mtrcs \n cMatrix'= cMatrix mtrcs \n dMatrix'= dMatrix mtrcs \n xMatrix'= xMatrix mtrcs \n parents'= parents mtrcs \n spnTr' = spnTr mtrcs \n vss' = vss mtrcs\n directEdges' = directEdges mtrcs\n lstar = ((LA.inv (dMatrix' LA.<> xMatrix')) LA.<> dMatrix') LA.<> (numEdges LA.>< 1 $ llMatrix')\n lstarMap = Map.fromList $ zip (Set.toList spnTr') (LA.toList $ LA.flatten lstar)\n getLength :: G.Edge \n -> G.Vertex -- pinned Vertex\n -> Map.Map G.Edge Double -- lstarMap\n -> IM.IntMap G.Vertex -- parents\n -> NaturalLength\n -- | follows back the spanning tree adding parent edges' length\n getLength (G.Edge u v) pinnedV lstarMap parents =\n let followEnd :: G.Vertex \n -> Double\n -> Double\n followEnd k l =\n if k == pinnedV\n then l\n else\n let k' = parents IM.! k\n l' = lstarMap Map.! (G.Edge k' k)\n in followEnd k' (l+l')\n followStart k l =\n if k == pinnedV\n then l\n else\n let k' = parents IM.! k\n l' = lstarMap Map.! (G.Edge k' k)\n in followStart k' (l-l')\n in if u == v \n then 0\n else \n followEnd v $ followStart u 0\n netests = foldl' (\\acc utid ->\n let vmap = foldl' \n (\\mac vtid -> \n let u = tsvs Map.! utid\n v = tsvs Map.! vtid \n l = getLength (G.Edge u v) pinnedV lstarMap parents'\n in Map.insert vtid l mac\n ) Map.empty $ Map.keys tsvs\n in Map.insert utid vmap acc\n ) Map.empty $ Map.keys tsvs\n effectiveVariance :: G.Edge \n -> G.Vertex -- pinned\n -> [G.Vertex] -- vss\n -> Set.Set G.Edge -- spanning tree\n -> LA.Matrix Double -- D matrix\n -> LA.Matrix Double -- X matrix\n -> IM.IntMap G.Vertex -- parents\n -> Hardness\n effectiveVariance (G.Edge u v) pinnedV vss spnTr dMatrix xMatrix parents = \n let r = IM.fromList $ zip vss $ replicate (length vss) 0\n r' = case IM.lookup u r of \n Nothing -> r\n Just _ -> IM.insert u (-1.0) r\n r'' = case IM.lookup v r' of \n Nothing -> r'\n Just _ -> IM.insert v (1.0) r'\n forceVector = LA.tr' $ LA.fromLists [map (\\v -> r'' IM.! v) vss] -- has to respect vss ordering\n eflstar = (LA.inv (dMatrix LA.<> xMatrix)) LA.<> forceVector\n eflstarMap = Map.fromList $ \n zip (Set.toList spnTr) (LA.toList $ LA.flatten eflstar)\n in abs $ getLength (G.Edge u v) pinnedV eflstarMap parents\n netvars = foldl' (\\acc utid ->\n let vmap = foldl' \n (\\mac vtid -> \n let u' = tsvs Map.! utid\n v' = tsvs Map.! vtid \n u = min u' v'\n v = max u' v'\n mtc = getMatrices u \n l = if u == v\n then 0 \n else\n --effectiveVariance (G.Edge u v) u (vss mtc) (spnTr mtc) (dMatrix mtc) (xMatrix mtc) (parents mtc)\n effectiveVariance (G.Edge u v) pinnedV (vss') (spnTr') (dMatrix') (xMatrix') (parents')\n in Map.insert vtid l mac\n ) Map.empty $ Map.keys tsvs\n in Map.insert utid vmap acc\n ) Map.empty $ Map.keys tsvs\n sg = StudyGraph { studyGraph = G.graphFromEdges []\n , directGraph = G.graphFromEdges $ Set.toList spnTr'\n , vsts = vsts\n , tsvs = tsvs\n }\n nets = Map.empty\n in Right $ NetworkEffects { directs = sg\n --, leagueTable = dMatrix'\n --, lstar = lstar\n , networkEstimates = netests\n , networkVariances = netvars\n , debugmsg = unlines [ \"spnTr \" <> (show $ Set.toList spnTr')\n , \"vss \" <> (show $ map (\\(G.Edge u v)->v) (Set.toList spnTr'))\n , \"netvars\" <> (show netvars)\n , \"dMatrix\" <> (show dMatrix')\n , \"directEdges\" <> (show directEdges')\n ]\n }\n\n\n", "meta": {"hexsha": "0360c71018f834b86e4b26314c763da87e9c822a", "size": 17035, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Meta/NMA.hs", "max_stars_repo_name": "tpapak/meta-analysis", "max_stars_repo_head_hexsha": "e03bc51a20584f9d52f6ed81c7d34e731f793641", "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/Meta/NMA.hs", "max_issues_repo_name": "tpapak/meta-analysis", "max_issues_repo_head_hexsha": "e03bc51a20584f9d52f6ed81c7d34e731f793641", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Meta/NMA.hs", "max_forks_repo_name": "tpapak/meta-analysis", "max_forks_repo_head_hexsha": "e03bc51a20584f9d52f6ed81c7d34e731f793641", "max_forks_repo_licenses": ["BSD-3-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.9511494253, "max_line_length": 132, "alphanum_fraction": 0.3959495157, "num_tokens": 3388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.35409050514628315}} {"text": "{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}\n{-# LANGUAGE FlexibleInstances, ConstraintKinds, ExistentialQuantification, GADTs, RankNTypes, MultiParamTypeClasses #-}\n{-# LANGUAGE ImpredicativeTypes, RankNTypes, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}\n\n\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n-- | \n-- | Module : Count-Min Sketch\n-- | Creator: Xiao Ling\n-- | Created: 12/17/2015\n-- |\n---------------------------------------------------------------------------------------------------\n---------------------------------------------------------------------------------------------------\n\nmodule CountMinSketch where\n\nimport Control.Monad.Random.Class\nimport Control.Monad.Random\nimport Control.Monad.State\n\n\nimport Data.Matrix\nimport Data.Conduit\nimport qualified Data.Conduit.List as Cl\nimport qualified Data.Matrix as M\n\nimport Core\nimport Utils\nimport Statistics\n\n\n{-----------------------------------------------------------------------------\n Types \n------------------------------------------------------------------------------}\n\ntype D = Int -- * num rows\ntype W = Int -- * num cols\ntype P = Int -- * some prime that is 2^n - 1\ntype Event = Int -- * some input event from universe:\n -- * {1, .., i, .., n}\n\ntype Sketch = Matrix Int -- * D x W matrix of counters\ntype ABs = Matrix Int -- * 2 x D matrix of a_j and b_j for j = 1..d\ntype ColIdx = [Int] -- * indices of counters to increment\ntype Hash = Event -> ColIdx -- * Maps event to d x 1 list of column indices\n\n\n-- * Algorithm State\ntype AState = (Sketch,Hash,(D,W,P))\n\n-- * the algorithm uses `some m` equipped with state and randomness\ntype Some m = (MonadRandom m, MonadState AState m)\n\n-- * Algorithm outputes an `Estimator` that \n-- * estimates the fequence of `event` i from universe {1 ... i... n}, \ntype Estimator = Event -> Int\n\n{-----------------------------------------------------------------------------\n Count Min Sketch Conduit\n------------------------------------------------------------------------------}\n\n-- * Batch mode\nsketch' :: EpsDelta -> Event -> Batch Event IO Estimator\nsketch' t n = sketch t n `using` eval\n\n-- * Streaming mode\nsketch :: Some m => EpsDelta -> Event -> Streaming Event m ()\nsketch t n = inits False t n $= awaitWith update'\n\n-- * initalize algorithm given confidence/error `t` and maximum event `n`\ninits :: Some m => Bool -> EpsDelta -> Event -> Conduit Event m Event\ninits False t n = lift (inits' t n) >> inits True t n\ninits _ _ _ = pass\n\n-- * a concrete `eval`uation of Some `m`\n-- * run with vacuous inital condition to be thrown away\neval :: StateT AState (Rand StdGen) () -> IO Estimator\neval m = fmap (\\(s,h,_) -> \\i -> freq i s h) \n . evalRandIO $ execStateT m $ (ones 1 1, const [], (0,0,0))\n\n\n{-------------------------------------------------------------------------------\n CountMinSketch Primitives\n--------------------------------------------------------------------------------}\n\n-- * initalize algorithm with (w,d,p), zero counters, and hash function\ninits' :: Some m => EpsDelta -> Event -> m ()\ninits' ed n = do\n let t = newDwp ed n\n setParam t\n hash <- newHash t\n let sketch = newSketch t\n setHash hash\n setSketch sketch\n\n\n-- * on event `i`, update the `sketch`\nupdate' :: Some m => Event -> m ()\nupdate' i = do\n pm <- askParam\n sketch <- getSketch\n hash <- askHash\n let incr = toMask (hash i) pm\n setSketch $ incr .+. sketch\n\n\n{-------------------------------------------------------------------------------\n Effectful Subroutines\n--------------------------------------------------------------------------------}\n\n-- * h_j (i) = (a_j x i + b_j mod p) mod w\n-- * sumRow-wise [ a_1 ... a_j ... a_d ] .*. [ i_1 ... i_d ] mod p mod w\n-- * [ b_1 ... b_j ... b_d ] [ 1 ... 1 ]\n-- * result: [ idx_1, ..., idx_d ]\n-- * where the indices start at 1\nnewHash :: MonadRandom m => (D,W,P) -> m Hash\nnewHash t = do\n ab <- newAbs t\n return $ toHash t ab\n\n\n-- * intialize random cofficients a_j, b_j, for d x 2 matrix: \n-- * [ a_1 ... a_j ... a_d ]\n-- * [ b_1 ... b_j ... b_d ]\nnewAbs :: MonadRandom m => (D,W,P) -> m ABs\nnewAbs (d,_,p) = (M.fromList 2 d . take (2*d)) <$> getRandomRs (1,p)\n\n\n{-----------------------------------------------------------------------------\n Pure Subroutines\n------------------------------------------------------------------------------}\n\n-- * given some event `i` from universe {1 ... i... n}, a table of\n-- * counters Sketch `s` and hash function `h`, compute the \n-- * frequence of event `i`\nfreq :: Event -> Sketch -> Hash -> Int\nfreq i s h = minimum $ go s (h i) 1\n where go s [] _ = []\n go s (c:cs) d = (getElem d c s) : (go s cs $ succ d)\n\n\n-- * compute d,w, and p given accuracy/confidence level and \n-- * max value of event `n`\nnewDwp :: EpsDelta -> Event -> (D,W,P)\nnewDwp (ED e d) n = (round $ log2(1/d), round $ 2/e, round $ 2^n -1)\n\n-- * initalize the sketch\nnewSketch :: (D,W,P) -> Sketch\nnewSketch (d,w,_) = zeros d w\n\n-- * Note `is` maps some `i` from event universe onto d x 2 matrix:\n-- * [ i_1 ... i_2 ]\n-- * [ 1 ... 1 ]\ntoHash :: (D, W, P) -> ABs -> Hash\ntoHash (d, w, p) ab i = go $ sumR (ab .*. is) ... (\\v -> v `mod` p `mod` w)\n where go = fmap (+1) . toList\n is = (i .+ (zeros 1 d)) <-> ones 1 d\n\n-- * given hash function, construct a binary mask of size `w` x `d`\n-- * to increment sketch\ntoMask :: ColIdx -> (D,W,P) -> Sketch\ntoMask ks (d,w,p) = go w ks\n where\n go w ks = let vec c w = zeros 1 (c-1) <|> single 1 <|> zeros 1 (w - c) in\n case ks of\n c:[] -> vec c w\n c:cs -> vec c w <-> go w cs\n\n\n{-----------------------------------------------------------------------------\n Managing State \n TODO : redesign so this is not necessary\n------------------------------------------------------------------------------}\n\naskParam :: Some m => m (D,W,P)\naskParam = get >>= \\(_,_,p) -> return p\n\nsetParam :: Some m => (D,W,P) -> m ()\nsetParam t = get >>= \\(s,h,_) -> put (s,h,t)\n\ngetSketch :: Some m => m Sketch\ngetSketch = get >>= \\(s,_,_) -> return s\n\nsetSketch :: Some m => Sketch -> m ()\nsetSketch s = get >>= \\(_,h,t) -> put (s,h,t)\n\naskHash :: Some m => m Hash\naskHash = get >>= \\(_,h,_) -> return h\n\nsetHash :: Some m => Hash -> m ()\nsetHash h = get >>= \\(s,_,t) -> put (s,h,t)\n\n{-----------------------------------------------------------------------------\n Find conduit lib function for these:\n------------------------------------------------------------------------------}\n\n-- * identity conduit, why can't I find this in the library?\npass :: Monad m => Conduit i m i\npass = do\n mx <- await\n case mx of\n Nothing -> return ()\n Just x -> yield x >> pass\n\n\nawaitWith :: Monad m => (i -> m a) -> ConduitM i o m ()\nawaitWith g = do\n mi <- await\n case mi of\n Nothing -> return ()\n Just i -> lift (g i) >> awaitWith g\n\n\n\n", "meta": {"hexsha": "1bc0fda0a64e8c6ce7d5c18ec517dad8a263565a", "size": 7378, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CountMinSketch.hs", "max_stars_repo_name": "lingxiao/CIS700", "max_stars_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CountMinSketch.hs", "max_issues_repo_name": "lingxiao/CIS700", "max_issues_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CountMinSketch.hs", "max_forks_repo_name": "lingxiao/CIS700", "max_forks_repo_head_hexsha": "0aebe925c4b413a37d75b8c782a3dffd53851f8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1574074074, "max_line_length": 122, "alphanum_fraction": 0.4552724316, "num_tokens": 1889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3534158944958701}} {"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE Trustworthy #-}\n{-# LANGUAGE DefaultSignatures #-}\n-----------------------------------------------------------------------------\n-- |\n-- Copyright : (C) 2012-2015 Edward Kmett\n-- License : BSD-style (see the file LICENSE)\n-- Maintainer : Edward Kmett \n-- Stability : provisional\n-- Portability : portable\n--\n-- Operations on free vector spaces.\n-----------------------------------------------------------------------------\nmodule Linear.Vector\n ( Additive(..)\n , E(..)\n , negated\n , (^*)\n , (*^)\n , (^/)\n , sumV\n , basis\n , basisFor\n , scaled\n , outer\n , unit\n ) where\n\nimport Control.Applicative\nimport Control.Lens\nimport Data.Complex\nimport Data.Foldable as Foldable (forM_, foldl')\nimport Data.Functor.Compose\nimport Data.Functor.Product\nimport Data.HashMap.Lazy as HashMap\nimport Data.Hashable\nimport Data.IntMap as IntMap\nimport Data.Map as Map\nimport qualified Data.Vector as Vector\nimport Data.Vector (Vector)\nimport qualified Data.Vector.Mutable as Mutable\nimport GHC.Generics\nimport Linear.Instances ()\n\n-- $setup\n-- >>> import Linear.V2\n\n-- | Basis element\nnewtype E t = E { el :: forall x. Lens' (t x) x }\n\ninfixl 6 ^+^, ^-^\ninfixl 7 ^*, *^, ^/\n\nclass GAdditive f where\n gzero :: Num a => f a\n gliftU2 :: (a -> a -> a) -> f a -> f a -> f a\n gliftI2 :: (a -> b -> c) -> f a -> f b -> f c\n\ninstance GAdditive U1 where\n gzero = U1\n {-# INLINE gzero #-}\n gliftU2 _ U1 U1 = U1\n {-# INLINE gliftU2 #-}\n gliftI2 _ U1 U1 = U1\n {-# INLINE gliftI2 #-}\n\ninstance (GAdditive f, GAdditive g) => GAdditive (f :*: g) where\n gzero = gzero :*: gzero\n {-# INLINE gzero #-}\n gliftU2 f (a :*: b) (c :*: d) = gliftU2 f a c :*: gliftU2 f b d\n {-# INLINE gliftU2 #-}\n gliftI2 f (a :*: b) (c :*: d) = gliftI2 f a c :*: gliftI2 f b d\n {-# INLINE gliftI2 #-}\n\ninstance (Additive f, GAdditive g) => GAdditive (f :.: g) where\n gzero = Comp1 $ gzero <$ (zero :: f Int)\n {-# INLINE gzero #-}\n gliftU2 f (Comp1 a) (Comp1 b) = Comp1 $ liftU2 (gliftU2 f) a b\n {-# INLINE gliftU2 #-}\n gliftI2 f (Comp1 a) (Comp1 b) = Comp1 $ liftI2 (gliftI2 f) a b\n {-# INLINE gliftI2 #-}\n\ninstance Additive f => GAdditive (Rec1 f) where\n gzero = Rec1 zero\n {-# INLINE gzero #-}\n gliftU2 f (Rec1 g) (Rec1 h) = Rec1 (liftU2 f g h)\n {-# INLINE gliftU2 #-}\n gliftI2 f (Rec1 g) (Rec1 h) = Rec1 (liftI2 f g h)\n {-# INLINE gliftI2 #-}\n\ninstance GAdditive f => GAdditive (M1 i c f) where\n gzero = M1 gzero\n {-# INLINE gzero #-}\n gliftU2 f (M1 g) (M1 h) = M1 (gliftU2 f g h)\n {-# INLINE gliftU2 #-}\n gliftI2 f (M1 g) (M1 h) = M1 (gliftI2 f g h)\n {-# INLINE gliftI2 #-}\n\ninstance GAdditive Par1 where\n gzero = Par1 0\n gliftU2 f (Par1 a) (Par1 b) = Par1 (f a b)\n {-# INLINE gliftU2 #-}\n gliftI2 f (Par1 a) (Par1 b) = Par1 (f a b)\n {-# INLINE gliftI2 #-}\n\n-- | A vector is an additive group with additional structure.\nclass Functor f => Additive f where\n -- | The zero vector\n zero :: Num a => f a\n#ifndef HLINT\n default zero :: (GAdditive (Rep1 f), Generic1 f, Num a) => f a\n zero = to1 gzero\n#endif\n\n -- | Compute the sum of two vectors\n --\n -- >>> V2 1 2 ^+^ V2 3 4\n -- V2 4 6\n (^+^) :: Num a => f a -> f a -> f a\n (^+^) = liftU2 (+)\n {-# INLINE (^+^) #-}\n\n -- | Compute the difference between two vectors\n --\n -- >>> V2 4 5 ^-^ V2 3 1\n -- V2 1 4\n (^-^) :: Num a => f a -> f a -> f a\n x ^-^ y = x ^+^ negated y\n\n -- | Linearly interpolate between two vectors.\n lerp :: Num a => a -> f a -> f a -> f a\n lerp alpha u v = alpha *^ u ^+^ (1 - alpha) *^ v\n {-# INLINE lerp #-}\n\n -- | Apply a function to merge the 'non-zero' components of two vectors, unioning the rest of the values.\n --\n -- * For a dense vector this is equivalent to 'liftA2'.\n --\n -- * For a sparse vector this is equivalent to 'unionWith'.\n liftU2 :: (a -> a -> a) -> f a -> f a -> f a\n#ifndef HLINT\n default liftU2 :: Applicative f => (a -> a -> a) -> f a -> f a -> f a\n liftU2 = liftA2\n {-# INLINE liftU2 #-}\n#endif\n\n -- | Apply a function to the components of two vectors.\n --\n -- * For a dense vector this is equivalent to 'liftA2'.\n --\n -- * For a sparse vector this is equivalent to 'intersectionWith'.\n liftI2 :: (a -> b -> c) -> f a -> f b -> f c\n#ifndef HLINT\n default liftI2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c\n liftI2 = liftA2\n {-# INLINE liftI2 #-}\n#endif\n\ninstance (Additive f, Additive g) => Additive (Product f g) where\n zero = Pair zero zero\n liftU2 f (Pair a b) (Pair c d) = Pair (liftU2 f a c) (liftU2 f b d)\n liftI2 f (Pair a b) (Pair c d) = Pair (liftI2 f a c) (liftI2 f b d)\n Pair a b ^+^ Pair c d = Pair (a ^+^ c) (b ^+^ d)\n Pair a b ^-^ Pair c d = Pair (a ^-^ c) (b ^-^ d)\n lerp alpha (Pair a b) (Pair c d) = Pair (lerp alpha a c) (lerp alpha b d)\n\ninstance (Additive f, Additive g) => Additive (Compose f g) where\n zero = Compose $ zero <$ (zero :: f Int)\n {-# INLINE zero #-}\n Compose a ^+^ Compose b = Compose $ liftU2 (^+^) a b\n {-# INLINE (^+^) #-}\n Compose a ^-^ Compose b = Compose $ liftU2 (^-^) a b\n {-# INLINE (^-^) #-}\n liftU2 f (Compose a) (Compose b) = Compose $ liftU2 (liftU2 f) a b\n {-# INLINE liftU2 #-}\n liftI2 f (Compose a) (Compose b) = Compose $ liftI2 (liftI2 f) a b\n {-# INLINE liftI2 #-}\n\ninstance Additive ZipList where\n zero = ZipList []\n {-# INLINE zero #-}\n liftU2 f (ZipList xs) (ZipList ys) = ZipList (liftU2 f xs ys)\n {-# INLINE liftU2 #-}\n liftI2 = liftA2\n {-# INLINE liftI2 #-}\n\ninstance Additive Vector where\n zero = mempty\n {-# INLINE zero #-}\n liftU2 f u v = case compare lu lv of\n LT | lu == 0 -> v\n | otherwise -> Vector.modify (\\ w -> Foldable.forM_ [0..lu-1] $ \\i -> Mutable.unsafeWrite w i $ f (Vector.unsafeIndex u i) (Vector.unsafeIndex v i)) v\n EQ -> Vector.zipWith f u v\n GT | lv == 0 -> u\n | otherwise -> Vector.modify (\\ w -> Foldable.forM_ [0..lv-1] $ \\i -> Mutable.unsafeWrite w i $ f (Vector.unsafeIndex u i) (Vector.unsafeIndex v i)) u\n where\n lu = Vector.length u\n lv = Vector.length v\n {-# INLINE liftU2 #-}\n liftI2 = Vector.zipWith\n {-# INLINE liftI2 #-}\n\ninstance Additive Maybe where\n zero = Nothing\n {-# INLINE zero #-}\n liftU2 f (Just a) (Just b) = Just (f a b)\n liftU2 _ Nothing ys = ys\n liftU2 _ xs Nothing = xs\n {-# INLINE liftU2 #-}\n liftI2 = liftA2\n {-# INLINE liftI2 #-}\n\ninstance Additive [] where\n zero = []\n {-# INLINE zero #-}\n liftU2 f = go where\n go (x:xs) (y:ys) = f x y : go xs ys\n go [] ys = ys\n go xs [] = xs\n {-# INLINE liftU2 #-}\n liftI2 = Prelude.zipWith\n {-# INLINE liftI2 #-}\n\ninstance Additive IntMap where\n zero = IntMap.empty\n {-# INLINE zero #-}\n liftU2 = IntMap.unionWith\n {-# INLINE liftU2 #-}\n liftI2 = IntMap.intersectionWith\n {-# INLINE liftI2 #-}\n\ninstance Ord k => Additive (Map k) where\n zero = Map.empty\n {-# INLINE zero #-}\n liftU2 = Map.unionWith\n {-# INLINE liftU2 #-}\n liftI2 = Map.intersectionWith\n {-# INLINE liftI2 #-}\n\ninstance (Eq k, Hashable k) => Additive (HashMap k) where\n zero = HashMap.empty\n {-# INLINE zero #-}\n liftU2 = HashMap.unionWith\n {-# INLINE liftU2 #-}\n liftI2 = HashMap.intersectionWith\n {-# INLINE liftI2 #-}\n\ninstance Additive ((->) b) where\n zero = const 0\n {-# INLINE zero #-}\n liftU2 = liftA2\n {-# INLINE liftU2 #-}\n liftI2 = liftA2\n {-# INLINE liftI2 #-}\n\ninstance Additive Complex where\n zero = 0 :+ 0\n {-# INLINE zero #-}\n liftU2 f (a :+ b) (c :+ d) = f a c :+ f b d\n {-# INLINE liftU2 #-}\n liftI2 f (a :+ b) (c :+ d) = f a c :+ f b d\n {-# INLINE liftI2 #-}\n\ninstance Additive Identity where\n zero = Identity 0\n {-# INLINE zero #-}\n liftU2 = liftA2\n {-# INLINE liftU2 #-}\n liftI2 = liftA2\n {-# INLINE liftI2 #-}\n\n-- | Compute the negation of a vector\n--\n-- >>> negated (V2 2 4)\n-- V2 (-2) (-4)\nnegated :: (Functor f, Num a) => f a -> f a\nnegated = fmap negate\n{-# INLINE negated #-}\n\n-- | Sum over multiple vectors\n--\n-- >>> sumV [V2 1 1, V2 3 4]\n-- V2 4 5\nsumV :: (Foldable f, Additive v, Num a) => f (v a) -> v a\nsumV = Foldable.foldl' (^+^) zero\n{-# INLINE sumV #-}\n\n-- | Compute the left scalar product\n--\n-- >>> 2 *^ V2 3 4\n-- V2 6 8\n(*^) :: (Functor f, Num a) => a -> f a -> f a\n(*^) a = fmap (a*)\n{-# INLINE (*^) #-}\n\n-- | Compute the right scalar product\n--\n-- >>> V2 3 4 ^* 2\n-- V2 6 8\n(^*) :: (Functor f, Num a) => f a -> a -> f a\nf ^* a = fmap (*a) f\n{-# INLINE (^*) #-}\n\n-- | Compute division by a scalar on the right.\n(^/) :: (Functor f, Fractional a) => f a -> a -> f a\nf ^/ a = fmap (/a) f\n{-# INLINE (^/) #-}\n\n-- | Produce a default basis for a vector space. If the dimensionality\n-- of the vector space is not statically known, see 'basisFor'.\nbasis :: (Additive t, Traversable t, Num a) => [t a]\nbasis = basisFor (zero :: Additive v => v Int)\n\n-- | Produce a default basis for a vector space from which the\n-- argument is drawn.\nbasisFor :: (Traversable t, Num a) => t b -> [t a]\nbasisFor = \\t ->\n ifoldMapOf traversed ?? t $ \\i _ ->\n return $\n iover traversed ?? t $ \\j _ ->\n if i == j then 1 else 0\n{-# INLINABLE basisFor #-}\n\n-- | Produce a diagonal (scale) matrix from a vector.\n--\n-- >>> scaled (V2 2 3)\n-- V2 (V2 2 0) (V2 0 3)\nscaled :: (Traversable t, Num a) => t a -> t (t a)\nscaled = \\t -> iter t (\\i x -> iter t (\\j _ -> if i == j then x else 0))\n where\n iter :: Traversable t => t a -> (Int -> a -> b) -> t b\n iter x f = iover traversed f x\n{-# INLINE scaled #-}\n\n-- | Create a unit vector.\n--\n-- >>> unit _x :: V2 Int\n-- V2 1 0\nunit :: (Additive t, Num a) => ASetter' (t a) a -> t a\nunit l = set' l 1 zero\n\n-- | Outer (tensor) product of two vectors\nouter :: (Functor f, Functor g, Num a) => f a -> g a -> f (g a)\nouter a b = fmap (\\x->fmap (*x) b) a\n", "meta": {"hexsha": "1a33022ff1281ed2f91e6481040099a1780a966c", "size": 9853, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Linear/Vector.hs", "max_stars_repo_name": "ekmett/linear", "max_stars_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 162, "max_stars_repo_stars_event_min_datetime": "2015-01-31T10:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T19:48:43.000Z", "max_issues_repo_path": "src/Linear/Vector.hs", "max_issues_repo_name": "ekmett/linear", "max_issues_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 94, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T12:52:34.000Z", "max_forks_repo_path": "src/Linear/Vector.hs", "max_forks_repo_name": "ekmett/linear", "max_forks_repo_head_hexsha": "d05577d0a60f6090a343e2adfa0e70a59b9c995c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2015-01-02T10:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T23:59:32.000Z", "avg_line_length": 28.1514285714, "max_line_length": 157, "alphanum_fraction": 0.5702831625, "num_tokens": 3472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3527116134560599}} {"text": "{-# LANGUAGE TemplateHaskell, RankNTypes #-}\n\nmodule Geometry.LRS (\n -- * Types\n Dictionary,\n -- * Functions\n getDictionary,\n selectPivot,\n reverseRS,\n lrs,\n polytope2LiftedCone,\n liftedCone2polyotpe,\n lrsFacetEnumeration,\n\n colFromList\n ) \n where\n\nimport Geometry.Vertex\nimport Geometry.Matrix\n\nimport Data.Matrix as M hiding (trace)\nimport qualified Data.Vector as V\nimport Data.Maybe\nimport Data.List\nimport Util\nimport Control.Lens \nimport Debug.Trace\nimport Numeric.LinearProgramming hiding (simplex)\nimport Numeric.LinearAlgebra.HMatrix as HM\nimport Data.List\n\ntype Row = M.Matrix Rational\ntype Col = M.Matrix Rational\n\ndata Dictionary = Dict {\n __B :: [Int], \n __N :: [Int], \n _dict :: M.Matrix Rational\n } \n deriving (Show, Eq)\n\n\nmakeLenses ''Dictionary\n\nnumRows :: Dictionary -> Int\nnumRows dictionary = nrows $ dictionary^.dict\n\nnumCols :: Dictionary -> Int\nnumCols dictionary = ncols $ dictionary^.dict\n\n(|*|) = multStrassen\n\n\ncolFromList :: [a] -> M.Matrix a\ncolFromList = colVector . V.fromList\n\nrowFromList :: [a] -> M.Matrix a\nrowFromList = rowVector . V.fromList\n\n-- | Wrapper of submatrix function. This function works for indices starting from 0 rather than 1 in the submatrix function\nsubmatrix' :: \n (Int, Int) -- ^ Rows indices\n -> (Int, Int) -- ^ Cols indices\n -> M.Matrix a\n -> M.Matrix a\nsubmatrix' (ro,rk) (co,ck) m = submatrix (ro+1) (rk+1) (co+1) (ck+1) m\n\n\n\n-- | Lens for columns\ncolAt :: Int -> Lens' (M.Matrix Rational) Col\ncolAt j = lens (getCol' j) (\\m c -> setCol' j c m)\n\ngetCol' :: Int -> M.Matrix a -> M.Matrix a\ngetCol' idx = colVector . (getCol (idx+1))\n\nsetCol' :: Int -> Col -> M.Matrix Rational -> M.Matrix Rational\nsetCol' idx col mat \n | idx == 0 = col <|> right\n | idx == (ncols mat) - 1 = left <|> col\n | otherwise = left <|> col <|> right\n where\n left = submatrix' (0,(nrows mat)-1) (0,idx-1) mat\n right = submatrix' (0,(nrows mat)-1) (idx+1, (ncols mat)-1) mat\n\n-- | Lens for rows\nrowAt :: Int -> Lens' (M.Matrix Rational) Row\nrowAt i = lens (getRow' i) (\\m r -> setRow' i r m)\n\ngetRow' :: Int -> M.Matrix a -> M.Matrix a\ngetRow' idx = rowVector . (getRow (idx+1))\n\nsetRow' :: Int -> Col -> M.Matrix Rational -> M.Matrix Rational\nsetRow' idx row mat\n | idx == 0 = row <-> down\n | idx == (nrows mat) - 1 = up <-> row\n | otherwise = up <-> row <-> down\n \n where\n up = submatrix' (0,idx-1) (0,(ncols mat)-1) mat\n down = submatrix' (idx+1, (nrows mat)-1) (0,(ncols mat)-1) mat\n\n-- | Lens for accessing elements\n\nelemAt :: (Int, Int) -> Lens' (M.Matrix a) a\nelemAt (i, j) = lens (getElem' (i,j)) (\\m x -> setElem' x (i,j) m) \n\ngetElem' :: (Int, Int) -> M.Matrix a -> a\ngetElem' (row, col) = getElem (row+1) (col+1)\n\nsetElem' :: a -> (Int, Int) -> M.Matrix a -> M.Matrix a\nsetElem' elem (row, col) mat\n | row < 0 || col < 0 || row >= nrows mat || col >= ncols mat = error (\"setElem': Trying to set at (\" ++ show row ++ \",\" ++ show col ++ \") in a \" ++ show (nrows mat) ++ \"x\" ++ show (ncols mat) ++ \" matrix.\")\n | otherwise = setElem elem (row+1, col+1) mat\n\nmapCol' :: (Int -> a -> a) -> Int -> M.Matrix a -> M.Matrix a\nmapCol' f col m\n | col < 0 || col > (ncols m)-1 = error \"mapCol': index out of bounds\" \n | otherwise = mapCol f (col+1) m\n\nmapRow' :: (Int -> a -> a) -> Int -> M.Matrix a -> M.Matrix a\nmapRow' f row m\n | row < 0 || row > (nrows m)-1 = error \"mapCol': index out of bounds\" \n | otherwise = mapRow f (row+1) m\n\n\n\n\ngetOptimumVertex :: M.Matrix Rational -> Col -> Maybe Vertex\ngetOptimumVertex mat col = fmap (map toRational) $ feasNOpt result\n where\n problem = Maximize $ replicate (ncols mat) (-1)\n constraints = Dense $ safeZipWith (:<=:) (map (map fromRational) $ M.toLists mat) (map fromRational $ concat $ M.toLists col)\n result = exact problem constraints (map Free [1..ncols mat])\n feasNOpt (Optimal (_, vertex)) = Just vertex\n feasNOpt _ = Nothing\n\n\n\n{- \n Dictionary form\n\n p21 p31\n invA_b\n p22 p32\n\n -}\n\n\ntoHMatrix :: M.Matrix Rational -> HM.Matrix Double\ntoHMatrix matrix = HM.matrix cols (map (fromRational) (concat $ M.toLists matrix))\n where \n cols = ncols matrix\n\n\n\nfindBasis :: (Maybe (M.Matrix Rational), Maybe (M.Matrix Rational)) -> M.Matrix Rational -> Int -> (Maybe (M.Matrix Rational), Maybe (M.Matrix Rational))\nfindBasis (basic, cobasic) original colNum\n | currRank == rows && colNum < cols = findBasis (basic, Just newCobasic) original (colNum + 1)-- Just ((fromJust cobasic) <|> (submatrix' (0,rows-1) (colNum, (ncols original)-1) original)) )\n | currRank == rows = (basic, cobasic)-- Just ((fromJust cobasic) <|> (submatrix' (0,rows-1) (colNum, (ncols original)-1) original)) )\n | currRank == candRank = findBasis (basic, Just newCobasic) original (colNum + 1)\n | currRank < candRank = findBasis (Just newBasic, cobasic) original (colNum + 1)\n where\n rows = nrows original\n cols = ncols original\n currRank = if isNothing basic then 0 else rank (toHMatrix $ fromJust basic)\n candVec = original ^. colAt colNum\n candMat = if isNothing basic then candVec else (fromJust basic) <|> candVec\n candRank = rank $ toHMatrix candMat\n\n newBasic = if isNothing basic then candVec else (fromJust basic) <|> candVec\n newCobasic = if isNothing cobasic then candVec else (fromJust cobasic) <|> candVec\n\n\n\nsortSystem :: M.Matrix Rational -> (M.Matrix Rational, M.Matrix Rational) \nsortSystem matrix = trace (\"Matrix : \"++ show matrix ++ \"\\n\\nSorted \" ++ show (findBasis (Nothing, Nothing) matrix 0) ) (((,) <$> (fromJust . fst) <*> (fromJust . snd)) (findBasis (Nothing, Nothing) matrix 0))\n-- sortSystem :: M.Matrix Rational -> Col -> Vertex -> (M.Matrix Rational, Col)\n\n-- sortSystem mat col vertex\n-- | cols /= (rows `div` 2) = (,) mat col\n-- | otherwise = (trace $ show $ M.fromLists (upper ++ lower)) (,) (M.fromLists (upper ++ lower)) col\n-- where\n-- matLists = M.toLists mat\n \n-- rows = nrows mat\n-- cols = ncols mat\n-- slackMatr = submatrix' (0,rows-1) (0, rows - cols -2) $ identity rows\n-- lower = getIndependent matLists [] 0 rows slackMatr\n-- upper = matLists \\\\ lower\n \n-- getDictionary :: Matrix Rational -> Col -> Vertex -> Dictionary\n-- getDictionary _A b vertex = trace (\"In dictionary\" ++ show (rows,cols, nrows dictionary, ncols dictionary) ++ show newDict) Dict [0..rows] [rows+1..rows+cols] newDict\n-- -- trace (\"In dictionary\" ++ show _A_B)\n-- where\n-- (newA, newb) = sortSystem _A b vertex\n-- rows = nrows newA\n-- cols = ncols newA\n-- slack = identity rows\n-- -- dictionary = newA <|> slack\n-- topRow = rowFromList $ 1 : replicate rows 0 ++ replicate cols (1)\n-- leftCol = colFromList $ replicate rows 0\n-- dictionary = topRow <-> (leftCol <|> slack <|> newA )\n\n-- -- c_B = submatrix' (0,0) (1,rows) topRow\n-- -- c_N = submatrix' (0,0) (rows+1, rows+cols) topRow\n-- -- _A_B = submatrix' (0,rows-1) (0,rows-1) dictionary\n-- -- _A_N = submatrix' (0,rows-1) (rows, rows+cols-1) dictionary\n-- _A_B = submatrix' (0,rows) (0,rows) dictionary\n-- _A_N = submatrix' (0,rows) (rows+1, rows+cols) dictionary\n-- Right invA_B = inverse _A_B\n\n-- p2 = - invA_B |*| _A_N\n-- p3 = invA_B |*| newb\n-- -- p21 = (c_N - c_B |*| invA_B |*| _A_N)\n-- -- p22 = invA_B |*| _A_N\n-- -- p31 = -c_B |*| invA_B |*| newb\n-- -- p32 = invA_B |*| newb\n-- newDict = ((identity (rows+1)) <|> p2 <|> p3)\n\n\n-- | Constructs initial dictionary given a set of inequalities and an optimum initial vertex\n-- getDictionary :: M.Matrix Rational -> Col -> Vertex -> Dictionary\n-- getDictionary _A b vertex = Dict [0..rows] [rows+1..rows+cols] newDict\n-- where\n-- -- (newA, newb) = sortSystem _A b vertex\n-- initialDict = _A <|> slack\n-- (basic, cobasic) = sortSystem initialDict\n-- (newA, newb) = (,) _A b\n-- rows = nrows newA\n-- cols = ncols newA\n-- slack = identity rows\n-- dictionary = newA <|> slack\n-- topRow = rowFromList $ 1 : replicate rows 0 ++ replicate cols 1\n-- c_B = submatrix' (0,0) (1,rows) topRow\n-- c_N = submatrix' (0,0) (rows+1, rows+cols) topRow\n-- _A_B = submatrix' (0,rows-1) (0,rows-1) dictionary\n-- _A_N = submatrix' (0,rows-1) (rows, rows+cols-1) dictionary\n-- Right invA_B = inverse _A_B\n-- p21 = (c_N - c_B |*| invA_B |*| _A_N)\n-- p22 = invA_B |*| _A_N\n-- p31 = -c_B |*| invA_B |*| newb\n-- p32 = invA_B |*| newb\n\n-- newDict = ((identity (rows+1)) <|> (p21 <-> p22) <|> (p31 <-> p32))\n\n\ngetDictionary :: M.Matrix Rational -> Col -> Vertex -> Dictionary\ngetDictionary _A b vertex = Dict [0..rows] [rows+1..rows+cols] newDict\n where\n\n -- (newA, newb) = sortSystem _A b vertex\n initialDict = _A <|> slack\n (basic, cobasic) = sortSystem initialDict\n (newA, newb) = (,) _A b\n rows = nrows newA\n cols = ncols newA\n slack = identity rows\n -- dictionary = newA <|> slack\n topRow = rowFromList $ 1 : replicate rows 0 ++ replicate cols 1\n c_B = submatrix' (0,0) (1,rows) topRow\n c_N = submatrix' (0,0) (rows+1, rows+cols) topRow\n _A_B = basic --submatrix' (0,rows-1) (0,rows-1) dictionary\n _A_N = cobasic --submatrix' (0,rows-1) (rows, rows+cols-1) dictionary\n Right invA_B = inverse _A_B\n p21 = (c_N - c_B |*| invA_B |*| _A_N)\n p22 = invA_B |*| _A_N\n p31 = -c_B |*| invA_B |*| newb\n p32 = invA_B |*| newb\n\n newDict = ((identity (rows+1)) <|> (p21 <-> p22) <|> (p31 <-> p32))\n\n\nenteringVariable :: Dictionary -> Maybe Int\nenteringVariable dictionary\n | null negs = Nothing\n | otherwise = trace (\"ENTERINGVAR\\nBASE: \" ++ show (dictionary^._B) ++ \"\\nCOBASE: \" ++ show (dictionary^._N)) (Just $ (fst.head.sort) negs)\n where\n rows = nrows $ dictionary^.dict\n cobasic_0 = zip (dictionary^._N) (map (\\j -> dictionary^.dict.elemAt (0,j)) [rows..])\n negs = filter (\\(_,value) -> value < 0) cobasic_0\n\nlexMinRatio :: Dictionary -> Int -> Int\nlexMinRatio dictionary s\n | dim+1 == rows = 0\n | null indexed_s = 0\n | otherwise = trace (\"LEXMINRATIO\\nBASE: \" ++ show (dictionary^._B) ++ \"\\nCOBASE: \" ++ show (dictionary^._N)) (dictionary ^. _B) !! (fst $ indexed_s !! (fromJust $ elemIndex (minimum ratios) ratios))\n where\n rows = numRows dictionary\n cols = numCols dictionary\n dim = cols - rows - 1\n dictMatrix = dictionary^.dict\n col_s = dictMatrix ^. colAt s\n _D = (dictMatrix ^. colAt (cols-1)) <|> submatrix' (0,rows-1) (0, rows-1) dictMatrix\n slice_s = (concat.M.toLists) $ submatrix' (dim+1, rows-1) (0,0) col_s\n indexed_s = filter (snd.(fmap (>0))) $ safeZipWith (,) [dim+1..rows-1] slice_s \n sub_D = map (head . M.toLists . (\\i -> _D ^. rowAt i) . fst) indexed_s\n ratios = safeZipWith (map $) (map ((flip (/)) . snd) indexed_s) sub_D\n\n\n-- | Selects entering and leaving variables for the next pivot in the dictionary\nselectPivot :: Dictionary -> Maybe (Int, Int)\nselectPivot dictionary\n | s == Nothing = Nothing\n | otherwise = Just (r, fromJust s)\n where \n s = enteringVariable dictionary\n r = lexMinRatio dictionary (fromJust s)\n\npivot :: Int ->Int -> Dictionary -> Dictionary\npivot r s dictionary = Dict new_B new_N (_E |*| dictMatrix)\n where\n dictMatrix = dictionary ^. dict\n col_s = dictMatrix ^. colAt (s)\n t = fromJust $ elemIndex r (dictionary ^. _B) -- idxR\n idxS = fromJust $ elemIndex s (dictionary ^. _N)\n a_t = col_s ^. elemAt (t,0)\n eta = (mapCol' (\\_ x -> -x/a_t) 0 col_s) & elemAt (t,0) .~ (1/a_t)\n _E = (identity (nrows dictMatrix)) & colAt t .~ eta\n new_B = dictionary^._B & element t .~ s\n new_N = dictionary^._N & element idxS .~ r\n\n\nsimplex :: Dictionary -> Dictionary\nsimplex dictionary\n | idxsToPivot == Nothing = dictionary\n | otherwise = simplex $ uncurry pivot (fromJust idxsToPivot) dictionary\n where\n idxsToPivot = selectPivot dictionary\n\n\n-- | Reverse search.\nreverseRS :: \n Dictionary \n -> Int -- ^ element in N\n -> Maybe Int\nreverseRS dictionary v\n | conditions == False = trace (\"REVERSE RS: \" ++ show [firstCondition, sndCondition, lastCondition]) Nothing\n | conditions == True = trace (\"REVERSE RS: \" ++ show v) Just u\n where\n dictMatrix = dictionary^.dict\n rows = nrows dictMatrix\n v_col = dictMatrix ^. colAt (v)\n w_row_0 = dictMatrix ^. rowAt 0\n u = lexMinRatio dictionary v\n i = fromJust $ elemIndex u (dictionary ^. _B)\n w_row_i = mapRow' (\\_ x -> (v_col ^. elemAt (0,0))/(v_col ^. elemAt (i,0)) * x) 0 $ dictMatrix ^. rowAt (i)\n diff_ws = (head.M.toLists) $ w_row_0 - w_row_i\n firstCondition = (w_row_0 ^. elemAt (0,v)) > 0\n sndCondition = u /= 0 \n lastCondition = all (>=0) [(diff_ws!!(snd idx))|idx <- (zip (dictionary^._N) [rows..]), (fst idx) < u ]\n conditions = firstCondition && sndCondition && lastCondition -- Proposition 6.1\n\n\n\n\n-- reverseRS :: -- reverse with pivot and selectPivot\n-- Dictionary -> \n-- Int -> \n-- Maybe Int\n-- reverseRS dictionary v\n-- | newPivots == Nothing = Nothing\n-- | condition == False = Nothing\n-- | condition == True = Just u \n-- where\n-- u = lexMinRatio dictionary v\n-- prev_B = pivot u v dictionary\n-- newPivots = selectPivot prev_B\n-- condition = fst (fromJust newPivots) == v && (snd (fromJust newPivots)) == u\n\n\n\ngetVertex :: Dictionary -> Vertex\ngetVertex dictionary = concat $ M.toLists $ submatrix' (1,dim) (cols-1, cols-1) (dictionary^.dict)\n where\n rows = numRows dictionary\n cols = numCols dictionary\n dim = cols - rows - 1\n\nrevSearch :: Dictionary -> [Vertex]\nrevSearch dictionary@(Dict _B _N dictMatrix) -- = getVertex dictionary : concatMap revSearch pivoted\n | (not.null) possibleRay = possibleRay ++ (concatMap revSearch pivoted)\n | otherwise = getVertex dictionary : concatMap revSearch pivoted\n where\n rows = numRows dictionary\n cols = numCols dictionary\n valid_N = [i | i <- _N, (reverseRS dictionary i) /= Nothing]\n valid_B = map (lexMinRatio dictionary) valid_N\n pivoted = map (\\(r, s) -> pivot r s dictionary) $ zip valid_B valid_N\n possibleRay = hasRay dictionary\n\n\n-- lexMin :: Dictionary -> Maybe Extremal\n-- lexMin dictionary\n\n\nhasRay :: Dictionary -> [Vertex]\nhasRay dictionary = trace (\"RAYS: \" ++ show (map snd rays) ++ \"\\n\\n\" ++ show (map fst rays) ++ \"\\n\" ++ show (dictionary ^. dict) ++ \"\\n\\n\") (map snd rays)\n -- idxsPivot == Nothing = Nothing\n -- r == 0 = Just ray\n -- otherwise = Nothing\n where\n dictMatrix = dictionary ^. dict\n rows = numRows dictionary\n dim = cols - rows - 1\n cols = numCols dictionary\n nonPositive column = all (<=0) ((concat.M.toLists) column)\n colsWithRays = if dim+1 == rows then\n [(j, dictMatrix^.colAt j) | j <- [rows..cols-2]]\n else [(j, dictMatrix^.colAt j) | j <- [rows..cols-2], nonPositive (submatrix' (dim+1,rows-1) (j,j) dictMatrix )]\n rays = zip (map fst colsWithRays) (map (concat . M.toLists . (submatrix' (1,dim) (0,0)) . snd ) colsWithRays)\n\n\n-- | Implementation of Lexicographic Reverse Search\nlrs :: M.Matrix Rational -> Col -> Vertex-> [Vertex]\nlrs matrix b vertex = (sort.nub) $ revSearch dictionary\n where\n dictionary = simplex $ getDictionary matrix b vertex\n\n\n-- | Transforms a V polytope into a H pointed cone\npolytope2LiftedCone :: [Vertex] -> (M.Matrix Rational, Col)\npolytope2LiftedCone points = (colOnes <|> hMatrix , colZeros)\n where\n nrows = length points\n colOnes = colFromList $ replicate nrows 1\n hMatrix = M.fromLists points\n colZeros = colFromList $ replicate nrows 0\n\n-- | Transforms a V pointed cone into a H polyotpe\nliftedCone2polyotpe :: [Vertex] -> (M.Matrix Rational, Col)\nliftedCone2polyotpe points = (hMatrix, b)\n where\n dim = length (points !! 0)\n rays = points \\\\ [(replicate dim 0)] -- remove vertex at the origin\n b = colFromList $ map (negate.head) rays\n hMatrix = M.fromLists $ map tail rays \n \n-- | Implementation of Lexicographic Reverse Search for Facet Enumeration\nlrsFacetEnumeration :: [IVertex] -> (M.Matrix Rational, Col)\nlrsFacetEnumeration ipoints = hPolytope\n where\n points = map (map toRational) ipoints\n cols = length (points!!0)\n initialVertex = replicate (cols + 1) 0\n hLiftedCone@(matrix, b) = polytope2LiftedCone points\n vLiftedCone = lrs matrix b initialVertex\n hPolytope = liftedCone2polyotpe vLiftedCone\n\n", "meta": {"hexsha": "1b37814b8a850d7a6b059fa09978a45125e6643f", "size": 17220, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Geometry/LRS.hs", "max_stars_repo_name": "tropical-group/facet-enumeration", "max_stars_repo_head_hexsha": "068b60081a19873623c0c1ff41d799f70de94810", "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/Geometry/LRS.hs", "max_issues_repo_name": "tropical-group/facet-enumeration", "max_issues_repo_head_hexsha": "068b60081a19873623c0c1ff41d799f70de94810", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-04T23:59:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T23:59:44.000Z", "max_forks_repo_path": "src/Geometry/LRS.hs", "max_forks_repo_name": "tropical-group/facet-enumeration", "max_forks_repo_head_hexsha": "068b60081a19873623c0c1ff41d799f70de94810", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-04T23:38:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T23:38:53.000Z", "avg_line_length": 38.1818181818, "max_line_length": 210, "alphanum_fraction": 0.5964576074, "num_tokens": 5230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.35157481455142403}} {"text": "{-# LANGUAGE QuasiQuotes, MultiParamTypeClasses #-}\n{-# LANGUAGE TemplateHaskell #-}\nmodule Lib where\n\n\nimport qualified Language.C.Inline as C\nimport Foreign.C.Types\nimport qualified Data.Vector.Storable as V\nimport qualified Numeric.LinearAlgebra as LA\nimport qualified Numeric.LinearAlgebra.Data as D\nimport qualified Numeric.LinearAlgebra.Devel as D\nimport Control.Arrow ((***))\nimport Data.Tuple (swap)\nC.context (C.baseCtx <> C.vecCtx)\n\nC.include \"\"\nC.include \"\"\n\n\ntestsp = D.mkSparse [((0,0), 3.0), ((1,1), 2.0)]\ntestcsr = D.mkCSR [((0,0), 3.0), ((1,1), 2.0)]\n\n-- getCSR (D.SparseR csr ncols nrows) = \n\nassocVec :: (Num a, Ord a) => [a] -> [(Int,a)] \nassocVec v = filter (\\(_,x) -> x /= 0) (zipWith (,) [0..] v)\n\n-- conveniently, will assume that if your list stops, it is implied the rest of it is zero. Or maybe inconvenitly from a type safety persepctive\nassocMat :: (Num a, Ord a) => [[a]] -> [((Int,Int),a)] \nassocMat m = let m' = map assocVec m in addRows m' where addRows m'' = concat $ zipWith (\\i xs -> map (\\(j,x) -> ((i,j),x)) xs) [0 ..] m''\n-- AssocMatrix = [((Int, Int), Double)]\n\ntransposeAssoc = map (swap *** id) \n\nmkGCSC = D.tr . D.mkSparse . transposeAssoc \nmkGCSC' = mkGCSC . assocMat\nmkCSC :: D.AssocMatrix -> CSC'\nmkCSC = transpose'' . D.mkCSR . transposeAssoc \nmkCSC' :: [[Double]] -> CSC'\nmkCSC' = mkCSC . assocMat\n-- The CSC type is internal to hmatrix.\ndata CSC' = CSC'\n { cscVals :: V.Vector Double\n , cscRows :: V.Vector CInt\n , cscCols :: V.Vector CInt\n , cscNRows :: Int\n , cscNCols :: Int\n } deriving Show\n\n-- data OSQPCSC = CSC -- {nzmax :: CInt, m :: CInt, n :: CInt, col_p :: V.Vector Ptr, col }\n{-\ninstance LA.Transposable D.CSR CSC'\n where\n tr (D.CSR vs cs rs n m) = CSC' vs cs rs m n\n tr' = tr\n\ninstance LA.Transposable CSC' D.CSR\n where\n tr (CSC' vs rs cs n m) = D.CSR vs rs cs m n\n tr' = tr\n-}\ntranspose'' (D.CSR vs cs rs n m) = CSC' vs cs rs m n\ntranspose''' (CSC' vs rs cs n m) = D.CSR vs rs cs m n\n\n\nfunboy :: IO ()\nfunboy = do\n x <- [C.exp| double{ cos(1) } |]\n print x\nsomeFunc :: IO ()\nsomeFunc = putStrLn \"someFunc\"\n\n\nmyfun :: CDouble -> CDouble\nmyfun x = [C.pure| double{ cos( $(double x)) } |]\n\n\n-- exampleOSQPData = \n\n-- Actually CDoubles\n--data OSQPData = OSQPData {dn :: CInt, dm :: CInt, p :: CSC , \n-- a :: CSC, q :: V.Vector CDouble, l :: V.Vector CDouble, u :: V.Vector CDouble}\n\n\n\n\n-- OSQPWorkspace *osqp_setup(const OSQPData *data, OSQPSettings *settings)\n-- c_int osqp_solve(OSQPWorkspace *work)\n-- c_int osqp_cleanup(OSQPWorkspace *work)\n\n\n\n-- Maybe the easiest thing is to just inject default settings and marshal only what we need\n-- Get a demo code in full c and start pulling pieces out.\n-- l and u are the easiest\n\ndemo :: IO CInt\ndemo = [C.block|\nint {\n // Load problem data\n c_float P_x[4] = {4.00, 1.00, 1.00, 2.00, };\n c_int P_nnz = 4;\n c_int P_i[4] = {0, 1, 0, 1, };\n c_int P_p[3] = {0, 2, 4, };\n c_float q[2] = {1.00, 1.00, };\n c_float A_x[4] = {1.00, 1.00, 1.00, 1.00, };\n c_int A_nnz = 4;\n c_int A_i[4] = {0, 1, 0, 2, };\n c_int A_p[3] = {0, 2, 4, };\n c_float l[3] = {1.00, 0.00, 0.00, };\n c_float u[3] = {1.00, 0.70, 0.70, };\n c_int n = 2;\n c_int m = 3;\n\n // Problem settings\n OSQPSettings * settings = (OSQPSettings *)c_malloc(sizeof(OSQPSettings));\n\n // Structures\n OSQPWorkspace * work; // Workspace\n OSQPData * data; // OSQPData\n\n // Populate data\n data = (OSQPData *)c_malloc(sizeof(OSQPData));\n data->n = n;\n data->m = m;\n data->P = csc_matrix(data->n, data->n, P_nnz, P_x, P_i, P_p);\n data->q = q;\n data->A = csc_matrix(data->m, data->n, A_nnz, A_x, A_i, A_p);\n data->l = l;\n data->u = u;\n\n\n // Define Solver settings as default\n osqp_set_default_settings(settings);\n settings->alpha = 1.0; // Change alpha parameter\n\n // Setup workspace\n work = osqp_setup(data, settings);\n\n // Solve Problem\n osqp_solve(work);\n\n // Cleanup\n osqp_cleanup(work);\n c_free(data->A);\n c_free(data->P);\n c_free(data);\n c_free(settings);\n\n return 0;\n} |]\n\n\n\n\n", "meta": {"hexsha": "12176e11bfc891cefb59600e838e9064de4accdb", "size": 4130, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Lib.hs", "max_stars_repo_name": "philzook58/osqp-haskell", "max_stars_repo_head_hexsha": "74d2ba492cdd5e00eea96a6f6ccc2af53e84c103", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T04:11:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T04:11:26.000Z", "max_issues_repo_path": "src/Lib.hs", "max_issues_repo_name": "philzook58/osqp-haskell", "max_issues_repo_head_hexsha": "74d2ba492cdd5e00eea96a6f6ccc2af53e84c103", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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": "philzook58/osqp-haskell", "max_forks_repo_head_hexsha": "74d2ba492cdd5e00eea96a6f6ccc2af53e84c103", "max_forks_repo_licenses": ["BSD-3-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.4743589744, "max_line_length": 144, "alphanum_fraction": 0.6060532688, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3512536987011174}} {"text": "{-# LANGUAGE FlexibleContexts #-}\nmodule FokkerPlanck.DomainChange where\n\nimport Data.Array.Repa as R\nimport Data.Complex\nimport Data.List as L\nimport FokkerPlanck.Types\nimport Numeric.LinearAlgebra as NL\nimport Types\nimport Utils.Array\n\n{-# INLINE r2z1t0Tor2s1t0 #-}\nr2z1t0Tor2s1t0 :: Int -> [Double] -> R2Z1T0Array -> R2S1T0Array\nr2z1t0Tor2s1t0 numOrientations freqs arr =\n let deltaTheta = 2 * pi / (fromIntegral numOrientations)\n (Z :. numFreqs :. numT0Freqs :. xLen :. yLen) = extent arr\n mat1 =\n (numOrientations >< numFreqs) . R.toList $\n R.traverse\n (fromListUnboxed (Z :. numFreqs) freqs)\n (const (Z :. numOrientations :. numFreqs))\n (\\f (Z :. i :. j) ->\n exp (0 :+ (-1) * (deltaTheta * fromIntegral i) * f (Z :. j)))\n mat2 = (numFreqs >< (xLen * yLen * numT0Freqs)) . R.toList $ arr\n in fromListUnboxed (Z :. numOrientations :. numT0Freqs :. xLen :. yLen) .\n NL.toList . flatten $\n mat1 NL.<> mat2\n \n{-# INLINE r2z1Tor2s1 #-}\nr2z1Tor2s1 ::\n (Source s (Complex Double))\n => Int\n -> [Double]\n -> R.Array s DIM3 (Complex Double)\n -> R.Array U DIM3 (Complex Double)\nr2z1Tor2s1 numOrientations freqs arr =\n let deltaTheta = 2 * pi / (fromIntegral numOrientations)\n (Z :. numFreqs :. xLen :. yLen) = extent arr\n mat1 =\n (numOrientations >< numFreqs) . R.toList $\n R.traverse\n (fromListUnboxed (Z :. numFreqs) freqs)\n (const (Z :. numOrientations :. numFreqs))\n (\\f (Z :. i :. j) ->\n exp (0 :+ (-1) * (deltaTheta * fromIntegral i) * f (Z :. j)))\n mat2 = (numFreqs >< (xLen * yLen)) . R.toList $ arr\n in fromListUnboxed (Z :. numOrientations :. xLen :. yLen) .\n NL.toList . flatten $\n mat1 NL.<> mat2\n \n\n{-# INLINE r2s1tor2z1 #-}\nr2s1tor2z1 ::\n (Source s (Complex Double))\n => [Double]\n -> R.Array s DIM3 (Complex Double)\n -> R.Array U DIM3 (Complex Double)\nr2s1tor2z1 freqs arr =\n let (Z :. numOrientations :. xLen :. yLen) = extent arr\n deltaTheta = 2 * pi / (fromIntegral numOrientations)\n numFreqs = L.length freqs\n mat1 =\n (numFreqs >< numOrientations) . R.toList $\n R.traverse\n (fromListUnboxed (Z :. numFreqs) freqs)\n (const (Z :. numFreqs :. numOrientations))\n (\\f (Z :. i :. j) ->\n exp (0 :+ (deltaTheta * fromIntegral j) * f (Z :. i)))\n mat2 = (numOrientations >< (xLen * yLen)) . R.toList $ arr\n in fromListUnboxed (Z :. numFreqs :. xLen :. yLen) . NL.toList . flatten $\n mat1 NL.<> mat2\n\n\n{-# INLINE r2z2t0s0Tor2s1rpt0s0 #-}\nr2z2t0s0Tor2s1rpt0s0 ::\n Int -> [Double] -> Int -> [Double] -> R2Z2T0S0Array -> R2S1RPT0S0Array\nr2z2t0s0Tor2s1rpt0s0 numOrientations thetaFreqs numScales scaleFreqs arr =\n let deltaTheta = 2 * pi / (fromIntegral numOrientations)\n (Z :. numThetaFreq :. numScaleFreq :. numTheta0Freq :. numScale0Freq :. xLen :. yLen) =\n extent arr\n mat1 =\n ((numOrientations * numScales) >< (numThetaFreq * numScaleFreq)) .\n R.toList $\n R.traverse3\n (fromFunction\n (Z :. numOrientations :. numScales :. numThetaFreq :. numScaleFreq)\n (const 0))\n (fromListUnboxed (Z :. numThetaFreq) thetaFreqs)\n (fromListUnboxed (Z :. numScaleFreq) scaleFreqs)\n (\\a _ _ -> a)\n (\\f1 f2 f3 (Z :. i :. j :. k :. l) ->\n exp\n (0 :+\n (-1) *\n ((deltaTheta * fromIntegral i) * f2 (Z :. k) +\n (2 * pi * fromIntegral j / fromIntegral numScales) *\n f3 (Z :. l))))\n mat2 =\n ((numThetaFreq * numScaleFreq) ><\n (xLen * yLen * numTheta0Freq * numScale0Freq)) .\n R.toList $\n arr\n in fromListUnboxed\n (Z :. numOrientations :. numScales :. numTheta0Freq :. numScale0Freq :.\n xLen :.\n yLen) .\n NL.toList . flatten $\n mat1 NL.<> mat2\n\n\n{-# INLINE r2z2Tor2s1rp #-}\nr2z2Tor2s1rp ::\n (Source s (Complex Double))\n => Int\n -> [Double]\n -> Int\n -> [Double]\n -> Double\n -> R.Array s DIM4 (Complex Double)\n -> R.Array U DIM4 (Complex Double)\nr2z2Tor2s1rp numOrientations thetaFreqs numScales scaleFreqs maxScale arr =\n let deltaTheta = 2 * pi / (fromIntegral numOrientations)\n deltaScale = log maxScale / (fromIntegral numScales)\n (Z :. numThetaFreq :. numScaleFreq :. xLen :. yLen) = extent arr\n mat1 =\n ((numOrientations * numScales) >< (numThetaFreq * numScaleFreq)) .\n R.toList $\n R.traverse3\n (fromFunction\n (Z :. numOrientations :. numScales :. numThetaFreq :. numScaleFreq)\n (const 0))\n (fromListUnboxed (Z :. numThetaFreq) thetaFreqs)\n (fromListUnboxed (Z :. numScaleFreq) scaleFreqs)\n (\\a _ _ -> a)\n (\\f1 f2 f3 (Z :. i :. j :. k :. l) ->\n exp\n (0 :+\n (1) *\n ((deltaTheta * fromIntegral i) * f2 (Z :. k) +\n (2 * pi * fromIntegral j * deltaScale / (log maxScale)) *\n f3 (Z :. l))))\n mat2 = ((numThetaFreq * numScaleFreq) >< (xLen * yLen)) . R.toList $ arr\n in fromListUnboxed (Z :. numOrientations :. numScales :. xLen :. yLen) .\n NL.toList . flatten $\n mat1 NL.<> mat2\n \n\n{-# INLINE r2z2Tor2s1rpP #-}\nr2z2Tor2s1rpP ::\n (Source s (Complex Double))\n => Int\n -> [Double]\n -> Int\n -> [Double]\n -> Double\n -> R.Array s DIM4 (Complex Double)\n -> IO (R.Array U DIM4 (Complex Double))\nr2z2Tor2s1rpP numOrientations thetaFreqs numScales scaleFreqs maxR arr = do\n let deltaTheta = 2 * pi / (fromIntegral numOrientations)\n deltaScale = log maxR / (fromIntegral numOrientations)\n (Z :. numThetaFreq :. numScaleFreq :. xLen :. yLen) = extent arr\n mat2 = ((numThetaFreq * numScaleFreq) >< (xLen * yLen)) . R.toList $ arr\n mat1 <-\n fmap\n (((numOrientations * numScales) >< (numThetaFreq * numScaleFreq)) .\n R.toList) .\n computeUnboxedP $\n R.traverse3\n (fromFunction\n (Z :. numOrientations :. numScales :. numThetaFreq :. numScaleFreq)\n (const 0))\n (fromListUnboxed (Z :. numThetaFreq) thetaFreqs)\n (fromListUnboxed (Z :. numScaleFreq) scaleFreqs)\n (\\a _ _ -> a)\n (\\f1 f2 f3 (Z :. i :. j :. k :. l) ->\n exp\n (0 :+\n (1) *\n ((deltaTheta * fromIntegral i) * f2 (Z :. k) +\n (2 * pi * fromIntegral j * deltaScale / (log maxR)) * f3 (Z :. l))))\n return .\n fromListUnboxed (Z :. numOrientations :. numScales :. xLen :. yLen) .\n NL.toList . flatten $\n mat1 NL.<> mat2\n\n\n\n{-# INLINE r2z2t0s0Tor2s1rps1rp #-}\nr2z2t0s0Tor2s1rps1rp ::\n Int -> [Double] -> [Double] -> Int -> [Double] -> [Double] -> Double -> R2Z2T0S0Array -> R.Array U DIM6 (Complex Double)\nr2z2t0s0Tor2s1rps1rp numOrientations thetaFreqs theta0Freqs numScales scaleFreqs scale0Freqs maxScale arr =\n let deltaTheta = 2 * pi / (fromIntegral numOrientations)\n deltaScale =\n if maxScale == 0\n then 0\n else (2 * pi / (log maxScale)) / (fromIntegral numScales)\n (Z :. numThetaFreq :. numScaleFreq :. numTheta0Freq :. numScale0Freq :. xLen :. yLen) =\n extent arr\n mat1 =\n ((numOrientations * numScales * numOrientations * numScales) ><\n (numThetaFreq * numScaleFreq * numTheta0Freq * numScale0Freq)) .\n R.toList $\n R.traverse4\n (fromListUnboxed (Z :. numThetaFreq) thetaFreqs)\n (fromListUnboxed (Z :. numScaleFreq) scaleFreqs)\n (fromListUnboxed (Z :. numTheta0Freq) theta0Freqs)\n (fromListUnboxed (Z :. numScale0Freq) scale0Freqs)\n (\\_ _ _ _ ->\n (Z :. numOrientations :. numScales :. numOrientations :. numScales :.\n numThetaFreq :.\n numScaleFreq :.\n numTheta0Freq :.\n numScale0Freq))\n (\\ft fs ft0 fs0 (Z :. o :. s :. o0 :. s0 :. tf :. sf :. tf0 :. sf0) ->\n exp\n (0 :+\n (-1) *\n ((deltaTheta * fromIntegral o) * ft (Z :. tf) +\n (deltaTheta * fromIntegral o0) * ft0 (Z :. tf0) +\n (deltaScale * fromIntegral s) * fs (Z :. sf) +\n (deltaScale * fromIntegral s0) * fs0 (Z :. sf0))))\n mat2 =\n ((numThetaFreq * numScaleFreq * numTheta0Freq * numScale0Freq) ><\n (xLen * yLen)) .\n R.toList $\n arr\n in fromListUnboxed\n (Z :. numOrientations :. numScales :. numOrientations :. numScales :.\n xLen :.\n yLen) .\n NL.toList . flatten $\n mat1 NL.<> mat2\n\n\n{-# INLINE r2s1rps1rpTor2z2t0s0 #-}\nr2s1rps1rpTor2z2t0s0 ::\n Int\n -> [Double]\n -> [Double]\n -> Int\n -> [Double]\n -> [Double]\n -> Double\n -> R.Array U DIM6 (Complex Double)\n -> R2Z2T0S0Array\nr2s1rps1rpTor2z2t0s0 numOrientations thetaFreqs theta0Freqs numScales scaleFreqs scale0Freqs maxScale arr =\n let deltaTheta = 2 * pi / (fromIntegral numOrientations)\n deltaScale =\n if maxScale == 0\n then 0\n else (2 * pi / (log maxScale)) / (fromIntegral numScales)\n numThetaFreq = L.length thetaFreqs\n numScaleFreq = L.length scaleFreqs\n numTheta0Freq = L.length theta0Freqs\n numScale0Freq = L.length scale0Freqs\n (Z :. _ :. _ :. _ :. _ :. xLen :. yLen) =\n extent arr\n mat1 =\n ((numThetaFreq * numScaleFreq * numTheta0Freq * numScale0Freq) ><\n (numOrientations * numScales * numOrientations * numScales)) .\n R.toList $\n R.traverse4\n (fromListUnboxed (Z :. numThetaFreq) thetaFreqs)\n (fromListUnboxed (Z :. numScaleFreq) scaleFreqs)\n (fromListUnboxed (Z :. numTheta0Freq) theta0Freqs)\n (fromListUnboxed (Z :. numScale0Freq) scale0Freqs)\n (\\_ _ _ _ ->\n (Z :. numThetaFreq :. numScaleFreq :. numTheta0Freq :.\n numScale0Freq :.\n numOrientations :.\n numScales :.\n numOrientations :.\n numScales))\n (\\ft fs ft0 fs0 (Z :. tf :. sf :. tf0 :. sf0 :. o :. s :. o0 :. s0) ->\n exp\n (0 :+ (1) *\n ((deltaTheta * fromIntegral o) * ft (Z :. tf) +\n (deltaTheta * fromIntegral o0) * ft0 (Z :. tf0) +\n (deltaScale * fromIntegral s) * fs (Z :. sf) +\n (deltaScale * fromIntegral s0) * fs0 (Z :. sf0))))\n mat2 =\n ((numOrientations * numScales * numOrientations * numScales) ><\n (xLen * yLen)) .\n R.toList $\n arr\n in fromListUnboxed\n (Z :. numThetaFreq :. numScaleFreq :. numTheta0Freq :. numScale0Freq :.\n xLen :.\n yLen) .\n NL.toList . flatten $\n mat1 NL.<> mat2\n\n-- x y t s\n{-# INLINE stsTor2s1rp #-}\nstsTor2s1rp ::\n Int\n -> Double\n -> [Double]\n -> Int\n -> Double\n -> [Double]\n -> Int\n -> [Double]\n -> Int\n -> [Double]\n -> Double\n -> R.Array U DIM4 (Complex Double)\n -> IO (R.Array U DIM4 (Complex Double))\nstsTor2s1rp numX xLen xFreqs numY yLen yFreqs numOrientations thetaFreqs numScales scaleFreqs maxScale arr = do\n let deltaX = xLen / fromIntegral numX\n deltaY = yLen / fromIntegral numY\n deltaTheta = 2 * pi / fromIntegral numOrientations\n deltaScale = (log maxScale) / fromIntegral numScales\n centerX = div numX 2\n centerY = div numY 2\n vec = NL.fromList . R.toList $ arr\n transformMat <-\n fmap\n (((numX * numY * numOrientations * numScales) ><\n (L.product . listOfShape . extent $ arr)) .\n R.toList) .\n computeUnboxedP .\n R.traverse4\n (fromListUnboxed (Z :. L.length xFreqs) xFreqs)\n (fromListUnboxed (Z :. L.length yFreqs) yFreqs)\n (fromListUnboxed (Z :. L.length thetaFreqs) thetaFreqs)\n (fromListUnboxed (Z :. L.length scaleFreqs) scaleFreqs)\n (\\(Z :. numXFreq) (Z :. numYFreq) (Z :. numThetaFreq) (Z :. numScaleFreq) ->\n (Z :. numX :. numY :. numOrientations :. numScales :. numXFreq :.\n numYFreq :.\n numThetaFreq :.\n numScaleFreq)) $ \\fx fy fo fs (Z :. x :. y :. o :. s :. xf :. yf :. orif :. sf) ->\n exp\n (0 :+\n (fo (Z :. orif) * fromIntegral o * deltaTheta +\n 2 * pi *\n (fs (Z :. sf) * fromIntegral s * deltaScale / (log maxScale) +\n fx (Z :. xf) * fromIntegral ((x :: Int) - centerX) * deltaX / xLen +\n fy (Z :. yf) * fromIntegral ((y :: Int) - centerY) * deltaY / yLen)))\n return .\n fromListUnboxed (Z :. numX :. numY :. numOrientations :. numScales) .\n NL.toList $\n transformMat NL.#> vec\n \n\n{-# INLINE stsTor2 #-}\nstsTor2 ::\n Int\n -> Double\n -> [Double]\n -> Int\n -> Double\n -> [Double]\n -> R.Array U DIM4 (Complex Double)\n -> IO (R.Array U DIM2 (Complex Double))\nstsTor2 numX xLen xFreqs numY yLen yFreqs arr = do\n let deltaX = xLen / fromIntegral numX\n deltaY = yLen / fromIntegral numY\n centerX = div numX 2\n centerY = div numY 2\n vec <-\n fmap (NL.fromList . R.toList) .\n sumP . sumS . R.map (\\x -> (magnitude x) ^ 2 :+ 0) $\n arr\n transformMat <-\n fmap\n (((numX * numY) >< (L.product . L.drop 2 . listOfShape . extent $ arr)) .\n R.toList) .\n computeUnboxedP .\n R.traverse2\n (fromListUnboxed (Z :. L.length xFreqs) xFreqs)\n (fromListUnboxed (Z :. L.length yFreqs) yFreqs)\n (\\(Z :. numXFreq) (Z :. numYFreq) ->\n (Z :. numX :. numY :. numXFreq :. numYFreq)) $ \\fx fy (Z :. x :. y :. xf :. yf) ->\n exp\n (0 :+\n (2 * pi *\n (fx (Z :. xf) * fromIntegral (x - centerX) * deltaX / xLen +\n fy (Z :. yf) * fromIntegral (y - centerY) * deltaY / yLen)))\n return . fromListUnboxed (Z :. numX :. numY) . NL.toList $\n transformMat NL.#> vec\n\n\n{-# INLINE stsTor2' #-}\nstsTor2' ::\n Int\n -> Double\n -> [Double]\n -> Int\n -> Double\n -> [Double]\n -> R.Array U DIM4 (Complex Double)\n -> IO (R.Array U DIM2 Double)\nstsTor2' numX xLen xFreqs numY yLen yFreqs arr = do\n let deltaX = xLen / fromIntegral numX\n deltaY = yLen / fromIntegral numY\n centerX = div numX 2\n centerY = div numY 2\n (Z :. numXF :. numYF :. numTF :. numSF) = extent arr\n mat = ((numXF * numYF) >< (numTF * numSF)) (R.toList arr)\n transformMat <-\n fmap\n (((numX * numY) >< (L.product . L.drop 2 . listOfShape . extent $ arr)) .\n R.toList) .\n computeUnboxedP .\n R.traverse2\n (fromListUnboxed (Z :. L.length xFreqs) xFreqs)\n (fromListUnboxed (Z :. L.length yFreqs) yFreqs)\n (\\(Z :. numXFreq) (Z :. numYFreq) ->\n (Z :. numX :. numY :. numXFreq :. numYFreq)) $ \\fx fy (Z :. x :. y :. xf :. yf) ->\n exp\n (0 :+\n (2 * pi *\n (fx (Z :. xf) * fromIntegral (x - centerX) * deltaX / xLen +\n fy (Z :. yf) * fromIntegral (y - centerY) * deltaY / yLen)))\n return .\n sumS .\n sumS .\n R.map (\\x -> (magnitude x) ^ 2) .\n fromListUnboxed (Z :. numX :. numY :. numTF :. numSF) . NL.toList . flatten $\n transformMat NL.<> mat\n\n", "meta": {"hexsha": "1dbc1b303e202061774caa7a77ce6048528d5a7e", "size": 15128, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/FokkerPlanck/DomainChange.hs", "max_stars_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_stars_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FokkerPlanck/DomainChange.hs", "max_issues_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_issues_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2019-07-25T20:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T20:46:48.000Z", "max_forks_repo_path": "src/FokkerPlanck/DomainChange.hs", "max_forks_repo_name": "XinhuaZhang/Stochastic-Completion-Field", "max_forks_repo_head_hexsha": "494a49356e17288ce09864c64ba09d11a3e9e0a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-29T15:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T15:55:46.000Z", "avg_line_length": 35.7635933806, "max_line_length": 125, "alphanum_fraction": 0.5522871497, "num_tokens": 5036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3510466192379535}}