2-- Module : Streamly.Internal.Data.Fold.Window
3-- Copyright : (c) 2020 Composewell Technologies
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
9-- Simple incremental statistical measures over a stream of data. All
10-- operations use numerically stable floating point arithmetic.
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.
16-- Currently there is no overflow detection.
18-- For more advanced statistical measures see the @streamly-statistics@
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
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.
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
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 as Ring
71import Prelude hiding (length, sum, minimum, maximum)
74-- >>> import Data.Bifunctor(bimap)
75-- >>> import qualified Streamly.Data.Fold as Fold
76-- >>> import qualified Streamly.Internal.Data.Fold.Window as Fold
77-- >>> import qualified Streamly.Internal.Data.Ring as Ring
78-- >>> import qualified Streamly.Data.Stream as Stream
79-- >>> import Prelude hiding (length, sum, minimum, maximum)
81-------------------------------------------------------------------------------
83-------------------------------------------------------------------------------
85-- | Map a function on the incoming as well as outgoing element of a rolling
88-- >>> lmap f = Fold.lmap (bimap f (f <$>))
90{-# INLINE windowLmap #-}
91windowLmap :: (c -> a) -> Fold m (a, Maybe a) b -> Fold m (c, Maybe c) b
92windowLmap 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.
97-- >>> cumulative f = Fold.lmap (\x -> (x, Nothing)) f
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
108{-# INLINE windowRollingMapM #-}
109windowRollingMapM :: Monad m =>
110 (Maybe a -> a -> m (Maybe b)) -> Fold m (a, Maybe a) (Maybe b)
111windowRollingMapM f = Fold.foldlM' f1 initial
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.
121-- >>> windowRollingMap f = Fold.windowRollingMapM (\x y -> return $ f x y)
123{-# INLINE windowRollingMap #-}
124windowRollingMap :: Monad m =>
125 (Maybe a -> a -> Maybe b) -> Fold m (a, Maybe a) (Maybe b)
126windowRollingMap f = Fold.foldl' f1 initial
132 f1 _ (a, ma) = f ma a
134-------------------------------------------------------------------------------
136-------------------------------------------------------------------------------
140-- | The sum of all the elements in a rolling window. The input elements are
141-- required to be intergal numbers.
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!
149{-# INLINE windowSumInt #-}
150windowSumInt :: forall m a. (Monad m, Integral a) => Fold m (a, Maybe a) a
151windowSumInt = Fold step initial extract extract
155 initial = return $ Partial (0 :: a)
162 Just old -> s + a - old
168-- | Sum of all the elements in a rolling window:
170-- \(S = \sum_{i=1}^n x_{i}\)
172-- This is the first power sum.
174-- >>> sum = powerSum 1
176-- Uses Kahan-Babuska-Neumaier style summation for numerical stability of
177-- floating precision arithmetic.
179-- /Space/: \(\mathcal{O}(1)\)
181-- /Time/: \(\mathcal{O}(n)\)
183{-# INLINE windowSum #-}
184windowSum :: forall m a. (Monad m, Num a) => Fold m (a, Maybe a) a
185windowSum = Fold step initial extract extract
193 (0 :: a) -- running sum
194 (0 :: a) -- accumulated rounding error
196 step (Tuple' total err) (new, mOld) =
199 -- XXX new may be large and err may be small we may lose it
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.
218-- This is the \(0\)th power sum.
220-- >>> length = powerSum 0
222{-# INLINE windowLength #-}
223windowLength :: (Monad m, Num b) => Fold m (a, Maybe a) b
224windowLength = Fold.foldl' step 0
228 step w (_, Nothing) = w + 1
231-- | Sum of the \(k\)th power of all the elements in a rolling window:
233-- \(S_k = \sum_{i=1}^n x_{i}^k\)
235-- >>> powerSum k = lmap (^ k) sum
237-- /Space/: \(\mathcal{O}(1)\)
239-- /Time/: \(\mathcal{O}(n)\)
240{-# INLINE windowPowerSum #-}
241windowPowerSum :: (Monad m, Num a) => Int -> Fold m (a, Maybe a) a
242windowPowerSum k = windowLmap (^ k) windowSum
244-- | Like 'powerSum' but powers can be negative or fractional. This is slower
245-- than 'powerSum' for positive intergal powers.
247-- >>> powerSumFrac p = lmap (** p) sum
249{-# INLINE windowPowerSumFrac #-}
250windowPowerSumFrac :: (Monad m, Floating a) => a -> Fold m (a, Maybe a) a
251windowPowerSumFrac p = windowLmap (** p) windowSum
253-------------------------------------------------------------------------------
255-------------------------------------------------------------------------------
257-- XXX Remove MonadIO constraint
259-- | Determine the maximum and minimum in a rolling window.
261-- If you want to compute the range of the entire stream @Fold.teeWith (,)
262-- Fold.maximum Fold.minimum@ would be much faster.
264-- /Space/: \(\mathcal{O}(n)\) where @n@ is the window size.
266-- /Time/: \(\mathcal{O}(n*w)\) where \(w\) is the window size.
268{-# INLINE windowRange #-}
269windowRange :: (MonadIO m, Storable a, Ord a) => Int -> Fold m a (Maybe (a, a))
270windowRange n = Fold step initial extract extract
274 -- XXX Use Ring unfold and then fold for composing maximum and minimum to
279 then error "range: window size must be > 0"
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.
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.
296 | i < n = Ring.unsafeFoldRingM
297 | otherwise = Ring.unsafeFoldRingFullM
299 extract (Tuple3Fused' rb rh i) =
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.
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
314-- If you want to compute the minimum of the entire stream
315-- 'Streamly.Data.Fold.minimum' is much faster.
317-- /Time/: \(\mathcal{O}(n*w)\) where \(w\) is the window size.
319{-# INLINE windowMinimum #-}
320windowMinimum :: (MonadIO m, Storable a, Ord a) => Int -> Fold m a (Maybe a)
321windowMinimum n = fmap (fmap fst) $ windowRange n
323-- | The maximum element in a rolling window.
325-- See the performance related comments in 'minimum'.
327-- If you want to compute the maximum of the entire stream 'Fold.maximum' would
330-- /Time/: \(\mathcal{O}(n*w)\) where \(w\) is the window size.
332{-# INLINE windowMaximum #-}
333windowMaximum :: (MonadIO m, Storable a, Ord a) => Int -> Fold m a (Maybe a)
334windowMaximum n = fmap (fmap snd) $ windowRange n
336-- | Arithmetic mean of elements in a sliding window:
338-- \(\mu = \frac{\sum_{i=1}^n x_{i}}{n}\)
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
344-- >>> mean = Fold.teeWith (/) sum length
346-- /Space/: \(\mathcal{O}(1)\)
348-- /Time/: \(\mathcal{O}(n)\)
349{-# INLINE windowMean #-}
350windowMean :: forall m a. (Monad m, Fractional a) => Fold m (a, Maybe a) a
351windowMean = Fold.teeWith (/) windowSum windowLength
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list