```-- |
-- Module:     FRP.NetWire.Analyze
-- Copyright:  (c) 2011 Ertugrul Soeylemez
-- License:    BSD3
-- Maintainer: Ertugrul Soeylemez <es@ertes.de>
--
-- Signal analysis.

module FRP.NetWire.Analyze
( -- * Changes
diff,

-- * Statistics
-- ** Average
avg,
avgAll,
avgFps,

-- ** Peak
highPeak,
lowPeak,
peakBy,
)
where

import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Control.DeepSeq
import Control.Monad.ST
import FRP.NetWire.Wire

-- | Calculate the average of the signal over the given number of last
-- samples.  This wire has O(n) space complexity and O(1) time
-- complexity.
--
-- If you need an average over all samples ever produced, consider using
-- 'avgAll' instead.

avg :: forall m v. (Fractional v, Monad m, NFData v, U.Unbox v) => Int -> Wire m v v
avg n = mkGen \$ \_ x -> return (Right x, avg' (U.replicate n (x/d)) x 0)
where
avg' :: U.Vector v -> v -> Int -> Wire m v v
avg' samples' s' cur' =
mkGen \$ \_ ((/d) -> x) -> do
let cur = let cur = succ cur' in if cur >= n then 0 else cur
x' = samples' U.! cur
samples =
x' `seq` runST \$ do
s <- U.unsafeThaw samples'
UM.write s cur x
U.unsafeFreeze s
let s = s' - x' + x
s `deepseq` return (Right s, avg' samples s cur)

d :: v
d = realToFrac n

-- | Calculate the average of the signal over all samples.
--
-- Please note that somewhat surprisingly this wire runs in constant
-- space and is generally faster than 'avg', but most applications will
-- benefit from averages over only the last few samples.

avgAll :: forall m v. (Fractional v, Monad m, NFData v) => Wire m v v
avgAll = mkGen \$ \_ x -> return (Right x, avgAll' 1 x)
where
avgAll' :: v -> v -> Wire m v v
avgAll' n' a' =
mkGen \$ \_ x ->
let n = n' + 1
a = a' - a'/n + x/n in
n `deepseq` a `deepseq` return (Right a, avgAll' n a)

-- | Calculate the average number of frames per virtual second for the
-- last given number of frames.
--
-- Please note that this wire uses the clock, which you give the network
-- using the stepping functions in "FRP.NetWire.Session".  If this clock
-- doesn't represent real time, then the output of this wire won't
-- either.

avgFps :: forall a m. Monad m => Int -> Wire m a Double
avgFps = avgFps' . avg
where
avgFps' :: Wire m Double Double -> Wire m a Double
avgFps' w' =
mkGen \$ \ws@(wsDTime -> dt) _ -> do
(ma, w) <- toGen w' ws dt
return (fmap recip ma, avgFps' w)

-- | Emits an event, whenever the input signal changes.  The event
-- contains the last input value and the time elapsed since the last
-- change.

diff :: forall a m. (Eq a, Monad m) => Wire m a (Event (a, Time))
diff =
mkGen \$ \(wsDTime -> dt) x' ->
return (Right Nothing, diff' dt x')

where
diff' :: Time -> a -> Wire m a (Event (a, Time))
diff' t' x' =
mkGen \$ \(wsDTime -> dt) x ->
let t = t' + dt in
if x' == x
then return (Right Nothing, diff' t x')
else return (Right (Just (x', t)), diff' 0 x)

-- | Return the high peak.

highPeak :: (Monad m, NFData a, Ord a) => Wire m a a
highPeak = peakBy compare

-- | Return the low peak.

lowPeak :: (Monad m, NFData a, Ord a) => Wire m a a
lowPeak = peakBy (flip compare)

-- | Return the high peak with the given comparison function.

peakBy :: forall a m. (Monad m, NFData a) => (a -> a -> Ordering) -> Wire m a a
peakBy comp = mkGen \$ \_ x -> return (Right x, peakBy' x)
where
peakBy' :: a -> Wire m a a
peakBy' p' =
mkGen \$ \_ x -> do
let p = if comp x p' == GT then x else p'
p `deepseq` return (Right p, peakBy' p)
```