on 4300a9f help sign in
351 lines 11 kB history raw
1-- |
2-- Module : Streamly.Internal.Data.Fold.Window
3-- Copyright : (c) 2020 Composewell Technologies
4-- License : Apache-2.0
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
7-- Portability : GHC
8--
9-- Simple incremental statistical measures over a stream of data. All
10-- operations use numerically stable floating point arithmetic.
11--
12-- Measurements can be performed over the entire input stream or on a sliding
13-- window of fixed or variable size. Where possible, measures are computed
14-- online without buffering the input stream.
15--
16-- Currently there is no overflow detection.
17--
18-- For more advanced statistical measures see the @streamly-statistics@
19-- package.
21-- XXX A window fold can be driven either using the Ring.slidingWindow
22-- combinator or by zipping nthLast fold and last fold.
24module Streamly.Internal.Data.Fold.Window
25 (
26 -- * Incremental Folds
27 -- | Folds of type @Fold m (a, Maybe a) b@ are incremental sliding window
28 -- folds. An input of type @(a, Nothing)@ indicates that the input element
29 -- @a@ is being inserted in the window without ejecting an old value
30 -- increasing the window size by 1. An input of type @(a, Just a)@
31 -- indicates that the first element is being inserted in the window and the
32 -- second element is being removed from the window, the window size remains
33 -- the same. The window size can only increase and never decrease.
34 --
35 -- You can compute the statistics over the entire stream using sliding
36 -- window folds by keeping the second element of the input tuple as
37 -- @Nothing@.
38 --
39 lmap
40 , cumulative
42 , rollingMap
43 , rollingMapM
45 -- ** Sums
46 , length
47 , sum
48 , sumInt
49 , powerSum
50 , powerSumFrac
52 -- ** Location
53 , minimum
54 , maximum
55 , range
56 , mean
57 )
58where
60import Control.Monad.IO.Class (MonadIO (liftIO))
61import Data.Bifunctor(bimap)
62import Foreign.Storable (Storable, peek)
64import Streamly.Internal.Data.Fold.Type (Fold(..), Step(..))
65import Streamly.Internal.Data.Tuple.Strict
66 (Tuple'(..), Tuple3Fused' (Tuple3Fused'))
68import qualified Streamly.Internal.Data.Fold.Type as Fold
69import qualified Streamly.Internal.Data.Ring.Unboxed as Ring
71import Prelude hiding (length, sum, minimum, maximum)
73-- $setup
74-- >>> import Data.Bifunctor(bimap)
75-- >>> import qualified Streamly.Data.Fold as Fold
76-- >>> import qualified Streamly.Internal.Data.Fold.Window as FoldW
77-- >>> import qualified Streamly.Internal.Data.Ring.Unboxed as Ring
78-- >>> import qualified Streamly.Data.Stream as Stream
79-- >>> import Prelude hiding (length, sum, minimum, maximum)
81-------------------------------------------------------------------------------
82-- Utilities
83-------------------------------------------------------------------------------
85-- | Map a function on the incoming as well as outgoing element of a rolling
86-- window fold.
87--
88-- >>> lmap f = Fold.lmap (bimap f (f <$>))
89--
90{-# INLINE lmap #-}
91lmap :: (c -> a) -> Fold m (a, Maybe a) b -> Fold m (c, Maybe c) b
92lmap f = Fold.lmap (bimap f (f <$>))
94-- | Convert an incremental fold to a cumulative fold using the entire input
95-- stream as a single window.
96--
97-- >>> cumulative f = Fold.lmap (\x -> (x, Nothing)) f
98--
99{-# INLINE cumulative #-}
100cumulative :: Fold m (a, Maybe a) b -> Fold m a b
101cumulative = Fold.lmap (, Nothing)
103-- XXX Exchange the first two arguments of rollingMap or exchange the order in
104-- the fold input tuple.
106-- | Apply an effectful function on the latest and the oldest element of the
107-- window.
108{-# INLINE rollingMapM #-}
109rollingMapM :: Monad m =>
110 (Maybe a -> a -> m (Maybe b)) -> Fold m (a, Maybe a) (Maybe b)
111rollingMapM f = Fold.foldlM' f1 initial
113 where
115 initial = return Nothing
117 f1 _ (a, ma) = f ma a
119-- | Apply a pure function on the latest and the oldest element of the window.
120--
121-- >>> rollingMap f = FoldW.rollingMapM (\x y -> return $ f x y)
122--
123{-# INLINE rollingMap #-}
124rollingMap :: Monad m =>
125 (Maybe a -> a -> Maybe b) -> Fold m (a, Maybe a) (Maybe b)
126rollingMap f = Fold.foldl' f1 initial
128 where
130 initial = Nothing
132 f1 _ (a, ma) = f ma a
134-------------------------------------------------------------------------------
135-- Sum
136-------------------------------------------------------------------------------
138-- XXX Overflow.
139--
140-- | The sum of all the elements in a rolling window. The input elements are
141-- required to be intergal numbers.
142--
143-- This was written in the hope that it would be a tiny bit faster than 'sum'
144-- for 'Integral' values. But turns out that 'sum' is 2% faster than this even
145-- for intergal values!
146--
147-- /Internal/
148--
149{-# INLINE sumInt #-}
150sumInt :: forall m a. (Monad m, Integral a) => Fold m (a, Maybe a) a
151sumInt = Fold step initial extract
153 where
155 initial = return $ Partial (0 :: a)
157 step s (a, ma) =
158 return
159 $ Partial
160 $ case ma of
161 Nothing -> s + a
162 Just old -> s + a - old
164 extract = return
166-- XXX Overflow.
167--
168-- | Sum of all the elements in a rolling window:
169--
170-- \(S = \sum_{i=1}^n x_{i}\)
171--
172-- This is the first power sum.
173--
174-- >>> sum = powerSum 1
175--
176-- Uses Kahan-Babuska-Neumaier style summation for numerical stability of
177-- floating precision arithmetic.
178--
179-- /Space/: \(\mathcal{O}(1)\)
180--
181-- /Time/: \(\mathcal{O}(n)\)
182--
183{-# INLINE sum #-}
184sum :: forall m a. (Monad m, Num a) => Fold m (a, Maybe a) a
185sum = Fold step initial extract
187 where
189 initial =
190 return
191 $ Partial
192 $ Tuple'
193 (0 :: a) -- running sum
194 (0 :: a) -- accumulated rounding error
196 step (Tuple' total err) (new, mOld) =
197 let incr =
198 case mOld of
199 -- XXX new may be large and err may be small we may lose it
200 Nothing -> new - err
201 -- XXX if (new - old) is large we may lose err
202 Just old -> (new - old) - err
203 -- total is large and incr may be small, we may round incr here but
204 -- we will accumulate the rounding error in err1 in the next step.
205 total1 = total + incr
206 -- Accumulate any rounding error in err1
207 -- XXX In the Nothing case above we may lose err, therefore we
208 -- should use ((total1 - total) - new) + err here.
209 -- Or even in the just case if (new - old) is large we may lose
210 -- err, so we should use ((total1 - total) + (old - new)) + err.
211 err1 = (total1 - total) - incr
212 in return $ Partial $ Tuple' total1 err1
214 extract (Tuple' total _) = return total
216-- | The number of elements in the rolling window.
217--
218-- This is the \(0\)th power sum.
219--
220-- >>> length = powerSum 0
221--
222{-# INLINE length #-}
223length :: (Monad m, Num b) => Fold m (a, Maybe a) b
224length = Fold.foldl' step 0
226 where
228 step w (_, Nothing) = w + 1
229 step w _ = w
231-- | Sum of the \(k\)th power of all the elements in a rolling window:
232--
233-- \(S_k = \sum_{i=1}^n x_{i}^k\)
234--
235-- >>> powerSum k = lmap (^ k) sum
236--
237-- /Space/: \(\mathcal{O}(1)\)
238--
239-- /Time/: \(\mathcal{O}(n)\)
240{-# INLINE powerSum #-}
241powerSum :: (Monad m, Num a) => Int -> Fold m (a, Maybe a) a
242powerSum k = lmap (^ k) sum
244-- | Like 'powerSum' but powers can be negative or fractional. This is slower
245-- than 'powerSum' for positive intergal powers.
246--
247-- >>> powerSumFrac p = lmap (** p) sum
248--
249{-# INLINE powerSumFrac #-}
250powerSumFrac :: (Monad m, Floating a) => a -> Fold m (a, Maybe a) a
251powerSumFrac p = lmap (** p) sum
253-------------------------------------------------------------------------------
254-- Location
255-------------------------------------------------------------------------------
257-- XXX Remove MonadIO constraint
259-- | Determine the maximum and minimum in a rolling window.
260--
261-- If you want to compute the range of the entire stream @Fold.teeWith (,)
262-- Fold.maximum Fold.minimum@ would be much faster.
263--
264-- /Space/: \(\mathcal{O}(n)\) where @n@ is the window size.
265--
266-- /Time/: \(\mathcal{O}(n*w)\) where \(w\) is the window size.
267--
268{-# INLINE range #-}
269range :: (MonadIO m, Storable a, Ord a) => Int -> Fold m a (Maybe (a, a))
270range n = Fold step initial extract
272 where
274 -- XXX Use Ring unfold and then fold for composing maximum and minimum to
275 -- get the range.
277 initial =
278 if n <= 0
279 then error "range: window size must be > 0"
280 else
281 let f (a, b) = Partial $ Tuple3Fused' a b (0 :: Int)
282 in fmap f $ liftIO $ Ring.new n
284 step (Tuple3Fused' rb rh i) a = do
285 rh1 <- liftIO $ Ring.unsafeInsert rb rh a
286 return $ Partial $ Tuple3Fused' rb rh1 (i + 1)
288 -- XXX We need better Ring array APIs so that we can unfold the ring to a
289 -- stream and fold the stream using a fold of our choice.
290 --
291 -- We could just scan the stream to get a stream of ring buffers and then
292 -- map required folds over those, but we need to be careful that all those
293 -- rings refer to the same mutable ring, therefore, downstream needs to
294 -- process those strictly before it can change.
295 foldFunc i
296 | i < n = Ring.unsafeFoldRingM
297 | otherwise = Ring.unsafeFoldRingFullM
299 extract (Tuple3Fused' rb rh i) =
300 if i == 0
301 then return Nothing
302 else do
303 x <- liftIO $ peek rh
304 let accum (mn, mx) a = return (min mn a, max mx a)
305 fmap Just $ foldFunc i rh accum (x, x) rb
307-- | Find the minimum element in a rolling window.
308--
309-- This implementation traverses the entire window buffer to compute the
310-- minimum whenever we demand it. It performs better than the dequeue based
311-- implementation in @streamly-statistics@ package when the window size is
312-- small (< 30).
313--
314-- If you want to compute the minimum of the entire stream
315-- 'Streamly.Data.Fold.minimum' is much faster.
316--
317-- /Time/: \(\mathcal{O}(n*w)\) where \(w\) is the window size.
318--
319{-# INLINE minimum #-}
320minimum :: (MonadIO m, Storable a, Ord a) => Int -> Fold m a (Maybe a)
321minimum n = fmap (fmap fst) $ range n
323-- | The maximum element in a rolling window.
324--
325-- See the performance related comments in 'minimum'.
326--
327-- If you want to compute the maximum of the entire stream 'Fold.maximum' would
328-- be much faster.
329--
330-- /Time/: \(\mathcal{O}(n*w)\) where \(w\) is the window size.
331--
332{-# INLINE maximum #-}
333maximum :: (MonadIO m, Storable a, Ord a) => Int -> Fold m a (Maybe a)
334maximum n = fmap (fmap snd) $ range n
336-- | Arithmetic mean of elements in a sliding window:
337--
338-- \(\mu = \frac{\sum_{i=1}^n x_{i}}{n}\)
339--
340-- This is also known as the Simple Moving Average (SMA) when used in the
341-- sliding window and Cumulative Moving Avergae (CMA) when used on the entire
342-- stream.
343--
344-- >>> mean = Fold.teeWith (/) sum length
345--
346-- /Space/: \(\mathcal{O}(1)\)
347--
348-- /Time/: \(\mathcal{O}(n)\)
349{-# INLINE mean #-}
350mean :: forall m a. (Monad m, Fractional a) => Fold m (a, Maybe a) a
351mean = Fold.teeWith (/) sum length