]> Git — Sourcephile - gargantext.git/blob - src/Gargantext/Prelude.hs
[API][NGRAMS-TABLE] WIP for meeting.
[gargantext.git] / src / Gargantext / Prelude.hs
1 {-|
2 Module : Gargantext.Prelude
3 Description : Specific Prelude of the project
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
8 Portability : POSIX
9
10 Here is a longer description of this module, containing some
11 commentary with @some markup@.
12 -}
13
14 {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
15 {-# OPTIONS_GHC -fno-warn-type-defaults #-}
16
17 {-# LANGUAGE NoImplicitPrelude #-}
18 {-# LANGUAGE OverloadedStrings #-}
19
20 module Gargantext.Prelude
21 ( module Gargantext.Prelude
22 , module Protolude
23 , headMay, lastMay
24 , module GHC.Err.Located
25 , module Text.Show
26 , module Text.Read
27 , cs
28 , module Data.Maybe
29 , sortWith
30 )
31 where
32
33 import GHC.Exts (sortWith)
34 import GHC.Err.Located (undefined)
35 import Control.Monad.IO.Class (MonadIO)
36 import Data.Maybe (isJust, fromJust, maybe)
37 import Protolude ( Bool(True, False), Int, Int64, Double, Integer
38 , Fractional, Num, Maybe(Just,Nothing)
39 , Enum, Bounded, Float
40 , Floating, Char, IO
41 , pure, (>>=), (=<<), (<*>), (<$>)
42 , putStrLn
43 , head, flip
44 , Ord, Integral, Foldable, RealFrac, Monad, filter
45 , reverse, map, mapM, zip, drop, take, zipWith
46 , sum, fromIntegral, length, fmap, foldl, foldl'
47 , takeWhile, sqrt, identity
48 , abs, min, max, maximum, minimum, return, snd, truncate
49 , (+), (*), (/), (-), (.), ($), (&), (**), (^), (<), (>), log
50 , Eq, (==), (>=), (<=), (<>), (/=)
51 , (&&), (||), not, any, all
52 , fst, snd, toS
53 , elem, die, mod, div, const, either
54 , curry, uncurry, repeat
55 , otherwise, when
56 , IO()
57 , compare
58 , on
59 , panic
60 )
61
62 -- TODO import functions optimized in Utils.Count
63 -- import Protolude hiding (head, last, all, any, sum, product, length)
64 -- import Gargantext.Utils.Count
65 import qualified Data.List as L hiding (head, sum)
66 import qualified Control.Monad as M
67
68 import Data.Map (Map)
69 import qualified Data.Map as M
70
71 import Data.Map.Strict (insertWith)
72 import qualified Data.Vector as V
73 import Safe (headMay, lastMay)
74 import Text.Show (Show(), show)
75 import Text.Read (Read())
76 import Data.String.Conversions (cs)
77
78
79 printDebug :: (Show a, MonadIO m) => [Char] -> a -> m ()
80 printDebug msg x = putStrLn $ msg <> " " <> show x
81 -- printDebug _ _ = pure ()
82
83
84 map2 :: (t -> b) -> [[t]] -> [[b]]
85 map2 fun = map (map fun)
86
87
88 -- Some Statistics sugar functions
89 -- Exponential Average
90 eavg :: [Double] -> Double
91 eavg (x:xs) = a*x + (1-a)*(eavg xs)
92 where a = 0.70
93 eavg [] = 0
94
95 -- Simple Average
96 mean :: Fractional a => [a] -> a
97 mean xs = if L.null xs then 0.0
98 else sum xs / fromIntegral (length xs)
99
100
101 sumMaybe :: Num a => [Maybe a] -> Maybe a
102 sumMaybe = fmap sum . M.sequence
103
104 variance :: Floating a => [a] -> a
105 variance xs = mean $ map (\x -> (x - m) ** 2) xs where
106 m = mean xs
107
108 deviation :: [Double] -> Double
109 deviation = sqrt . variance
110
111 movingAverage :: (Eq b, Fractional b) => Int -> [b] -> [b]
112 movingAverage steps xs = map mean $ chunkAlong steps 1 xs
113
114 ma :: [Double] -> [Double]
115 ma = movingAverage 3
116
117 -- | splitEvery n == chunkAlong n n
118 splitEvery :: Int -> [a] -> [[a]]
119 splitEvery _ [] = []
120 splitEvery n xs =
121 let (h,t) = L.splitAt n xs
122 in h : splitEvery n t
123
124 type Grain = Int
125 type Step = Int
126
127 -- | Function to split a range into chunks
128 -- if step == grain then linearity
129 -- elif step < grain then overlapping
130 -- else dotted with holes
131 chunkAlong :: Eq a => Grain -> Step -> [a] -> [[a]]
132 chunkAlong a b l = case a > 0 && b > 0 of
133 True -> chunkAlong_ a b l
134 False -> panic "ChunkAlong: Parameters should be > 0 and Grain > Step"
135
136 chunkAlong_ :: Eq a => Int -> Int -> [a] -> [[a]]
137 chunkAlong_ a b l = filter (/= []) $ only (while dropAlong)
138 where
139 only = map (take a)
140 while = takeWhile (\x -> length x >= a)
141 dropAlong = L.scanl (\x _y -> drop b x) l ([1..] :: [Integer])
142
143 -- | Optimized version (Vector)
144 chunkAlong' :: Int -> Int -> V.Vector a -> V.Vector (V.Vector a)
145 chunkAlong' a b l = only (while dropAlong)
146 where
147 only = V.map (V.take a)
148 while = V.takeWhile (\x -> V.length x >= a)
149 dropAlong = V.scanl (\x _y -> V.drop b x) l (V.fromList [1..])
150
151 -- | TODO Inverse of chunk ? unchunkAlong ?
152 -- unchunkAlong :: Int -> Int -> [[a]] -> [a]
153 -- unchunkAlong = undefined
154
155
156 -- splitAlong [2,3,4] ("helloworld" :: [Char]) == ["he", "llo", "worl", "d"]
157 splitAlong :: [Int] -> [Char] -> [[Char]]
158 splitAlong _ [] = [] -- No list? done
159 splitAlong [] xs = [xs] -- No place to split at? Return the remainder
160 splitAlong (x:xs) ys = take x ys : splitAlong xs (drop x ys) -- take until our split spot, recurse with next split spot and list remainder
161
162 takeWhileM :: (Monad m) => (a -> Bool) -> [m a] -> m [a]
163 takeWhileM _ [] = return []
164 takeWhileM p (a:as) = do
165 v <- a
166 if p v
167 then do
168 vs <- takeWhileM p as
169 return (v:vs)
170 else return []
171
172 -- SUMS
173 -- To select the right algorithme according to the type:
174 -- https://github.com/mikeizbicki/ifcxt
175
176 sumSimple :: Num a => [a] -> a
177 sumSimple = L.foldl' (+) 0
178
179 -- | https://en.wikipedia.org/wiki/Kahan_summation_algorithm
180 sumKahan :: Num a => [a] -> a
181 sumKahan = snd . L.foldl' go (0,0)
182 where
183 go (c,t) i = ((t'-t)-y,t')
184 where
185 y = i-c
186 t' = t+y
187
188 -- | compute part of the dict
189 count2map :: (Ord k, Foldable t) => t k -> Map k Double
190 count2map xs = M.map (/ (fromIntegral (length xs))) (count2map' xs)
191
192 -- | insert in a dict
193 count2map' :: (Ord k, Foldable t) => t k -> Map k Double
194 count2map' xs = L.foldl' (\x y -> insertWith (+) y 1 x) M.empty xs
195
196
197 trunc :: (RealFrac a, Integral c, Integral b) => b -> a -> c
198 trunc n = truncate . (* 10^n)
199
200 trunc' :: Int -> Double -> Double
201 trunc' n x = fromIntegral $ truncate $ (x * 10^n)
202
203
204 ------------------------------------------------------------------------
205 bool2num :: Num a => Bool -> a
206 bool2num True = 1
207 bool2num False = 0
208
209 bool2double :: Bool -> Double
210 bool2double = bool2num
211
212 bool2int :: Bool -> Int
213 bool2int = bool2num
214 ------------------------------------------------------------------------
215
216 -- Normalizing && scaling data
217 scale :: [Double] -> [Double]
218 scale = scaleMinMax
219
220 scaleMinMax :: [Double] -> [Double]
221 scaleMinMax xs = map (\x -> (x - mi / (ma - mi + 1) )) xs'
222 where
223 ma = maximum xs'
224 mi = minimum xs'
225 xs' = map abs xs
226
227 scaleNormalize :: [Double] -> [Double]
228 scaleNormalize xs = map (\x -> (x - v / (m + 1))) xs'
229 where
230 v = variance xs'
231 m = mean xs'
232 xs' = map abs xs
233
234 normalize :: [Double] -> [Double]
235 normalize as = normalizeWith identity as
236
237 normalizeWith :: Fractional b => (a -> b) -> [a] -> [b]
238 normalizeWith extract bs = map (\x -> x/(sum bs')) bs'
239 where
240 bs' = map extract bs
241
242 -- Zip functions to add
243 zipFst :: ([b] -> [a]) -> [b] -> [(a, b)]
244 zipFst f xs = zip (f xs) xs
245
246 zipSnd :: ([a] -> [b]) -> [a] -> [(a, b)]
247 zipSnd f xs = zip xs (f xs)
248
249 -- | maximumWith
250 maximumWith :: (Ord a1, Foldable t) => (a2 -> a1) -> t a2 -> a2
251 maximumWith f = L.maximumBy (compare `on` f)
252