Difference between revisions of "Netwire"

From HaskellWiki
Jump to navigation Jump to search
(Sections restructured.)
Line 125: Line 125:
   
 
Local time is a switching effect, which is especially visible, when you use the switching combinators from '''FRP.NetWire.Switch'''. Local time starts when switching in.
 
Local time is a switching effect, which is especially visible, when you use the switching combinators from '''FRP.NetWire.Switch'''. Local time starts when switching in.
  +
  +
Time is measured in ''Double'' in Netwire. To improve type signatures there are two type aliases defined for you:
  +
  +
<haskell>
  +
type DTime = Double
  +
type Time = Double
  +
</haskell>
  +
  +
While ''Time'' refers to time, ''DTime'' refers to time deltas, i.e. time differences.
   
 
=== Pure stateless wires ===
 
=== Pure stateless wires ===
Line 215: Line 224:
   
 
Again I have simplified the types to help understanding. Just like with integration you can differentiate over any vectorspace, as long as your type has an ''NFData'' instance.
 
Again I have simplified the types to help understanding. Just like with integration you can differentiate over any vectorspace, as long as your type has an ''NFData'' instance.
  +
  +
=== Events ===
  +
  +
Events are a useful tool to add discrete values to the system. As the name states an event usually denotes some condition or external event, which can be present at some instants and absent at others. A common use case for events is user input.
  +
  +
Technically events are nothing special. Since they simply denote values, which can be absent, they are simply ''Maybe'' values. Netwire defines a type alias ''Event'' to enable you to be more specific in your type signatures:
  +
  +
<haskell>
  +
type Event = Maybe
  +
</haskell>
  +
  +
There is a large number of event wires in the '''FRP.NetWire.Event''' module. I will give you examples for some of the common ones here. It is worthwhile to have a look at the aforementioned module.
  +
  +
==== after ====
  +
  +
<haskell>
  +
after :: DTime -> Wire a (Event a)
  +
</haskell>
  +
  +
The ''after'' wire causes an event after a certain number of seconds. This means that the output signal is ''Nothing'', until the specified time has passed, at which point the output becomes ''Just x'' for a single instant, where ''x'' is the input value at that instant. After that the event never happens again.
  +
  +
==== once ====
  +
  +
<haskell>
  +
once :: Wire (Event a) (Event a)
  +
</haskell>
  +
  +
This wire takes a potential event. It waits, until the event happens (i.e. the input becomes a ''Just''). It outputs the event once and then never again, even if the event happens again in the future.
  +
  +
==== repeatedly ====
  +
  +
<haskell>
  +
repeatedly :: Wire (DTime, a) (Event a)
  +
</haskell>
  +
  +
This wire takes two input signals. It produces events repeatedly after the time delta given by the left signal. This delta can change over time, making the event happen more or less frequently. The right signal is the desired event value.
  +
  +
==== hold ====
  +
  +
<haskell>
  +
hold :: a -> Wire (Event a) a
  +
</haskell>
  +
  +
This wire turns events into continuous signals. At the beginning the output is the value given by the argument. Each time the input event occurs, the ouput switches to its value and keeps it until the next event occurs.
  +
  +
=== Random numbers ===
  +
  +
Netwire provides a few wires for random noise generation. Probably the most important one is the ''noise'' wire:
  +
  +
<haskell>
  +
noise :: Wire a Double
  +
</haskell>
  +
  +
This wire outputs a random number between 0 (inclusive) and 1 (exclusive). The underlying random number generator is a fast implementation of the Mersenne Twister algorithm provided by Don Stewart's [http://hackage.haskell.org/package/mersenne-random mersenne-random] package.
  +
  +
=== Signal analysis ===
  +
  +
Netwire provides some wires to perform signal analysis. One useful wire is ''diff'':
  +
  +
<haskell>
  +
diff :: Eq a => Wire a (Event (a, Time))
  +
</haskell>
  +
  +
This wire emits an event, whenever the input signal changes. The event contains the last value as well as the time elapsed since then. One possible use case is file monitoring. Pass the file's modification time or even its contents as the input signal.
  +
  +
Another useful wire is ''avg'', which computes the average value of the input signal over the specified number of most recent samples:
  +
  +
<haskell>
  +
avg :: Int -> Wire Double Double
  +
</haskell>
  +
  +
Since the ''noise'' wire returns random numbers between 0 and 1, you should get a value close to 0.5, if the argument is suitably large:
  +
  +
<haskell>
  +
avgOfNoise :: Wire a Double
  +
avgOfNoise = avg 1000 <<< noise
  +
</haskell>

Revision as of 02:06, 7 August 2011

Netwire is a library for functional reactive programming, which uses the concept of arrows for modelling an embedded domain-specific language. This language lets you express reactive systems, which means systems that change over time. It shares the basic concept with Yampa and its fork Animas, but it is itself not a fork.

Download netwire


Features

Here is a list of some of the features of netwire:

  • arrowized interface,
  • applicative interface,
  • signal inhibition (ArrowZero / Alternative),
  • choice and combination (ArrowPlus / Alternative),
  • self-adjusting wires (ArrowChoice),
  • rich set of event wires,
  • signal analysis wires (average, peak, etc.),
  • impure wires.

Quickstart

This is a quickstart introduction to Netwire for Haskell programmers familiar with arrowized functional reactive programming (AFRP), for example Yampa or Animas. It should quickly give you an idea of how the library works and how it differs from the two mentioned.

The wire

Netwire calls its signal transformation functions wires. You can think of a wire as a device with an input line and an output line. The difference between a function and a wire is that a wire can change itself throughout its lifetime. This is the basic idea of arrowized FRP. It gives you time-dependent values.

A wire is parameterized over its input and output types:

data Wire a b


Differences from Yampa

If you are not familiar with Yampa or Animas, you can safely skip this section.

The main difference between Yampa and Netwire is that the underlying arrow is impure. While you can choose not to use the impure wires inside of the FRP.NetWire.IO module, it is a design choice for this library to explicitly allow impure computations. One theoretical implication is that you need to differentiate between pure stateless, pure stateful and impure signal transformations.

A concept not found in Yampa is signal inhibition. A wire can choose not to return anything. This way you can temporarily block entire subnetworks. This is most useful with the combination operator <+>. Example:

w = w1 <+> w2

The w wire runs its signal through the wire w1, and if it inhibits, it passes the signal to w2.

Another concept not found in Yampa is choice. Through the ArrowChoice instance wires allow you to choose one of a set of subwires for its signal without needing a switch. Essentially you can write if and case constructs inside of arrow notation.

Because of their impurity wires do not have an ArrowLoop instance. It is possible to write one, but it will diverge most of the time, rendering it useless.


Using a wire

To run a wire you will need to use the withWire and stepWire functions. The withWire initializes a wire and gives you a Session value. As metioned earlier in general a wire is a function, which can mutate itself over time. The session value captures the current state of the wire.

initWire :: Wire a b -> (Session a b -> IO c) -> IO c
stepWire :: a -> Session a b -> IO (Maybe b)

The stepWire function passes the given input value through the wire. If you use stepWire, then the wire will mutate in real time. If you need a different rate of time, you can use stepWireDelta or stepWireTime instead. The stepWireDelta function takes a time delta, and the stepWireTime function takes the current time (which doesn't need to be the real time):

stepWireDelta :: Double -> a -> Session a b -> IO (Maybe b)
stepWireTime :: UTCTime -> a -> Session a b -> IO (Maybe b)

Note that it is allowed to give zero or negative deltas and times, which are earlier than the last time. This lets you run the system backwards in time. If you do that, your wire should be prepared to handle it properly.

The stepping functions return a Maybe b. If the wire inhibits, then the result is Nothing, otherwise it will be Just the output. Here is a complete example:

{-# LANGUAGE Arrows #-}

module Main where

import Control.Monad
import FRP.NetWire
import Text.Printf


myWire :: Wire () String
myWire =
    proc _ -> do
        t <- time -< ()
        fps <- avgFps 1000 -< ()
        fpsPeak <- highPeak -< fps

        if t < 4
          then identity -< "Waiting four seconds."
          else identity -<
                   printf "Got them! (%8.0f FPS, peak: %8.0f)"
                          fps fpsPeak


main :: IO ()
main = withWire myWire loop
    where
    loop :: Session () String -> IO ()
    loop session =
        forever $ do
            mResult <- stepWire () session
            case mResult of
              Nothing -> putStr "Signal inhibted."
              Just x  -> putStr x
            putChar '\r'

This program should display the string "Waiting four seconds." for four seconds and then switch to a string, which displays the current average frames per second and peak frames per second.

Note: Sessions are thread-safe. You are allowed to use the stepping functions for the same session from multiple threads. This makes it easy to implement conditional stepping based on system events.

Writing a wire

I will assume that you are familiar with arrow notation, and I will use it instead of the raw arrow combinators most of the time. If you haven't used arrow notation before, see the GHC arrow notation manual.

Time

To use this library you need to understand the concept of time very well. Netwire has a continuous time model, which means that when you write your applications you disregard the discrete steps, in which your wire is executed.

Technically at each execution instant (i.e. each time you run stepWire or one of the other stepping functions) the wire is fed with the input as well as a time delta, which is the time passed since the last instant. Hence wires do not by themselves keep track of what time it is, since most applications don't need that anyway. If you need a clock, you can use the predefined time wire, which will be explained later.

Wires have a local time, which can be different from the global time. This can happen, when a wire is not actually run, because an earlier wire inhibited the signal. It also happens, when you use choice. For example you can easily write a gateway, which repeatedly runs one wire the one second and another wire the other second. While one wire is run, the other wire is suspended, including its local time.

Local time is a switching effect, which is especially visible, when you use the switching combinators from FRP.NetWire.Switch. Local time starts when switching in.

Time is measured in Double in Netwire. To improve type signatures there are two type aliases defined for you:

type DTime = Double
type Time = Double

While Time refers to time, DTime refers to time deltas, i.e. time differences.

Pure stateless wires

Pure stateless wires are easy to explain, so let's start with them. A pure stateless wire is essentially just a function of input. The simplest wire is the identity wire. It just returns its input verbatim:

identity :: Wire a a

If you run such a wire (see the previous section), then you will just get your input back all the time. Another simple wire is the constant wire, which also disregards time:

constant :: b -> Wire a b

If you run the wire constant 15, you will get as output the number 15 all the time, regardless of the current time and the input.

Note: You can express identity as arr id, but you should prefer identity, because it's faster. Likewise you can express constant x as arr (const x), but again you should prefer constant.

Pure stateful wires

Let's see a slightly more interesting wire. The time wire will return the current local time. What local means in this context was explained earlier.

time :: Wire a Double

As the type suggests, time is measured in seconds and represented as a Double. The local time starts from 0 at the point, where the wire starts to run. There is also a wire, which counts time from a different origin:

timeFrom :: Double -> Wire a Double

The difference between these stateful and the stateless wires from the previous section is that stateful wires mutate themselves over time. The timeFrom x wire calculates the current time as x plus the current time delta. Let's say that sum is y. It then mutates into the wire timeFrom y. As you can see there is no internal clock. It is really this self-mutation, which gives you a clock.

Calculus

One of the compelling features of FRP is integration and differentiation over time. It is a very cheap operation to integrate over time. In fact the time wire you have seen in the last section is really just the integral of the constant 1. Here is the type of the integral wire, which integrates over time:

integral :: Double -> Wire Double Double

The argument is the integration constant or starting value. The input is the subject of integration. Let's write a clock, which runs at half the speed of the real clock:

slowClock :: Wire a Double
slowClock = proc _ -> integral 0 -< 0.5

Since the integration constant is 0, the time will start at zero. Integration becomes more interesting, as soon as you integrate non-constants:

particle :: Wire a Double
particle =
    proc _ -> do
        v <- integral 1 -< -0.1
        integral 15 -< v

This wire models a one-dimensional particle, which starts at position 15 and velocity +1. A constant acceleration of 0.1 per second per second is applied to the velocity, hence the particle moves right towards positive infinity at first, while gradually becoming slower, until it reverses its direction and moves left towards negative infinity.

The above type signature is actually a special case, which i provided for the sake of simplicity. The real type signature is a bit more interesting:

integral ::
    (NFData v, VectorSpace v, Scalar v ~ Double) =>
    v -> Wire v v

You can integrate over time in any real vectorspace. Some examples of vectorspaces include tuples, complex numbers and any type, for which you define NFData and VectorSpace instances. Let's see the particle example in two dimensions:

particle2D :: Wire a (Double, Double)
particle2D =
    proc _ -> do
        v <- integral (1, -0.5) -< (-0.1, 0.4)
        integral (0, 0) -< v

Differentiation works similarly, although there are two variants:

derivative :: Wire Double Double
derivativeFrom :: Double -> Wire Double Double

The difference between the two variants is that derivative will inhibit at the first instant (inhibition is explained later), because it needs at least two samples to compute the rate of change over time. The derivativeFrom variant does not have that shortcoming, but you need to provide the first sample as an argument.

Again I have simplified the types to help understanding. Just like with integration you can differentiate over any vectorspace, as long as your type has an NFData instance.

Events

Events are a useful tool to add discrete values to the system. As the name states an event usually denotes some condition or external event, which can be present at some instants and absent at others. A common use case for events is user input.

Technically events are nothing special. Since they simply denote values, which can be absent, they are simply Maybe values. Netwire defines a type alias Event to enable you to be more specific in your type signatures:

type Event = Maybe

There is a large number of event wires in the FRP.NetWire.Event module. I will give you examples for some of the common ones here. It is worthwhile to have a look at the aforementioned module.

after

after :: DTime -> Wire a (Event a)

The after wire causes an event after a certain number of seconds. This means that the output signal is Nothing, until the specified time has passed, at which point the output becomes Just x for a single instant, where x is the input value at that instant. After that the event never happens again.

once

once :: Wire (Event a) (Event a)

This wire takes a potential event. It waits, until the event happens (i.e. the input becomes a Just). It outputs the event once and then never again, even if the event happens again in the future.

repeatedly

repeatedly :: Wire (DTime, a) (Event a)

This wire takes two input signals. It produces events repeatedly after the time delta given by the left signal. This delta can change over time, making the event happen more or less frequently. The right signal is the desired event value.

hold

hold :: a -> Wire (Event a) a

This wire turns events into continuous signals. At the beginning the output is the value given by the argument. Each time the input event occurs, the ouput switches to its value and keeps it until the next event occurs.

Random numbers

Netwire provides a few wires for random noise generation. Probably the most important one is the noise wire:

noise :: Wire a Double

This wire outputs a random number between 0 (inclusive) and 1 (exclusive). The underlying random number generator is a fast implementation of the Mersenne Twister algorithm provided by Don Stewart's mersenne-random package.

Signal analysis

Netwire provides some wires to perform signal analysis. One useful wire is diff:

diff :: Eq a => Wire a (Event (a, Time))

This wire emits an event, whenever the input signal changes. The event contains the last value as well as the time elapsed since then. One possible use case is file monitoring. Pass the file's modification time or even its contents as the input signal.

Another useful wire is avg, which computes the average value of the input signal over the specified number of most recent samples:

avg :: Int -> Wire Double Double

Since the noise wire returns random numbers between 0 and 1, you should get a value close to 0.5, if the argument is suitably large:

avgOfNoise :: Wire a Double
avgOfNoise = avg 1000 <<< noise