Friday, 27 September 2013

F# for Visualization 0.7 released

A new version of F# for Visualization has been released that boasts the following features:
  1. Easier to use than ever before!
  2. Contour plots.
  3. Interactive charts: pan and zoom with the mouse.
  4. New API.
  5. Programmatically close chart windows.

To use F# for Visualization in a script, simply put the DLL in the same directory as the .fsx file and reference it in the script like this:

  #r "FSharpForVisualization"

The following namespace contains lots of helpful functions that make F# for Visualization extremely easy to use:

  open FlyingFrog.FSharpForVisualization

For example, you can plot a sine wave like this:

  plot sin

Note that the chart can be dragged and zoomed using the mouse.

Heuristics are used to guess ranges when none are supplied:

  plot sqrt

Ranges over x are easily supplied like this:

  plot(atan, (0, 10))

Ranges over y can be supplied in a similar way:

  plot(atan, (-10, 10), (-1.5, 1.5))

Note that ranges need not be given as floating point numbers but can, in fact, be any numeric type.

We can also label the axes like this:

  plot(atan, (-10, 10), (-1.5, 1.5), ("x", "atan(x)"))

Run-time type information is used to determine the kind of chart used to visualize a function. For example, a function of two variables is automatically visualized as a contour plot:

  plot atan2

Functions of the type Complexfloat are also visualized as contour plots, this time with default axis labels. For example, the function Im(√z):

  open System.Numerics
  plot(fun z -> Complex.Sqrt(z).Imaginary)

The plot function can also be used to plot series. For example, sequences of numbers are taken to be y coordinates:

  plot [for i in 0..10 -> i*i]

Sequences of pairs of numbers are x,y coordinates:

  plot [for i in 0..10 -> i*i, i]

Sequences of such sequences are assumed to be multiple series:

  plot[[for i in 0..10 -> i*i, i]; [for i in 0..10 -> i*i*i, i]]

Predator-prey population evolution may then be visualized like this:

  let g, k, t = 0.02, 5e2, 1500

  let evolve (r, f) _ =
    let dtrf = 1e-4 * r * f
    r + (1.0 - r/k)*r*g - dtrf, dtrf + (1.0 - g)*f

  plot(Seq.scan evolve (50.0, 10.0) [1..t], ("Rabbits", "Foxes"))

The plot function returns an object with SaveAsPng and Close members that allow the visualization to be saved programmatically and closed:

  let window = plot floor

  window.SaveAsPng "TheFloorFunction.png"


Charts support typeset mathematics for both labels and annotations. For example, plot the sinc function and label the axes accordingly:

  open FlyingFrog.Controls
  open FlyingFrog.Graphics.Typeset.Math
  open FlyingFrog.Interactive

  let sinc x = sin x / x

  let g = Plot([Function sinc], (-10.0, 10.0))
  g.Labels <- font="" math="">"x", Fraction(Row[Text "sin"; math "(x)"], math "x"))

Annotate a point on the graph:

  #r "PresentationCore.dll"
  #r "PresentationFramework.dll"
  #r "WindowsBase.dll"

  open System.Windows
  open FlyingFrog.Graphics.Scene
  open FlyingFrog.Graphics.Typeset

  let pi = System.Math.PI
  g.Data <- data="" o:p="" pi="" sinc="" unction="">
  g.Epilog <- font="" label="" math="" ow="" scene="">"("; Fraction(Greek.pi, math "2"); math ",";
                              Fraction(math "2", Greek.pi); math ")"]),
                    0.003, Point(pi/2.0, sinc(pi/2.0)), Vector(-1.2, -1.2))

Although F# for Visualization does not depend upon F# for Numerics or the F# PowerPack it can consume types from those libraries. For example, the following computes the 5x5 Hilbert matrix using arbitrary-precision rational elements:

  #r "FSharp.PowerPack.dll"

  open Microsoft.FSharp.Math

  let A =
      [ for i in 0N..4N ->
          [ for j in 0N..4N ->
              1N / (i + j + 1N) ] ]

Just as our plot function attempts to chart any value of any type so the view function attempts to visualize any value of any type, such as our Hilbert matrix:

  view A

or even a typeset mathematical matrix equation:

  view(Row[math A; Symbols.Times; math A; math "="; math(A*A)])

The ability to visualize values of F# types as typeset mathematics so easily is invaluable for interactive technical computing.

F# for Visualization also provides an easy-to-use API for general 2D vector graphics. Vector graphics are styled by a sequence of strokes or fills colored with WPF brushes:

  open System.Windows.Media
  open FlyingFrog.Graphics.Style

  let styles =
    [ Stroke(Brushes.Red, {Width = 0.001}) ]

The geometry of a shape is a sequence of contours that may be closed or open (only closed contours will be filled):

  open FlyingFrog.Graphics.Contour

  let geometry =
    let n = 50
    [ for i in 0 .. n do
        for j in 0 .. 1 do
          let x, y = float i / float n, float j
            Contour.Open(Point(x, y), [lineTo(y, 1.0 - x)]) ]

A vector graphics scene may contain shapes, groups of scenes, transformed scenes and clipped scenes:

  open FlyingFrog.Graphics.Scene

  let scene = Shape(styles, geometry)

The view function visualizes the vector graphics scene:

  view scene
The scene may also be visualized on a pair of axes by making it the epilog of an empty plot:

  Plot([], (0., 1.), (0., 1.), Epilog=scene)

F# for Visualization also does 3D graphics.

  open FlyingFrog.Graphics3D
  open FlyingFrog.Graphics3D.Scene3D

A Mesh describes a geometry and a Shape3D combines a mesh with a WPF Brush in order to represent a colored 3D object as a piece of scene graph. For example, the following creates a white icosahedron:

  let scene3d = Shape3D(Polyhedra.icosahedron, Brushes.White)

The same "view" function can be used to visualize 3D objects:

  view scene3d

F# for Visualization is currently available for just £49 under our beta release scheme. This latest release brings F# for Visualization much closer to it's first full release whereupon the price will increase. So why wait? Order your copy of F# for Visualization today!

Thursday, 26 September 2013

Predator Prey sample revisited

Thanks to progress in .NET and F# tooling that sample example can now be done in just 7 lines of F# code.

Create an F# project, install the FSharp.Charting NuGet by typing the following into the Package Manager Console:

Install-Package FSharp.Charting

And then enter the code shown on the following screenshot:

Saturday, 21 September 2013

3D printing a Hilbert Coaster

The F# Journal just published an article about 3D printing:
"The Hilbert curve is a fractal space filling curve. Like many mathematical shapes, Hilbert curves can be used to generate interesting objects for 3D printers. This article describes a simple program to compute and visualize 2D Hilbert curves and use them to generate GCode that, with a little extra effort, can produce nifty coasters for your drinks..."
To read this article and more, subscribe to The F# Journal today!

Tuesday, 17 September 2013

Downloading stock prices

This post describes a little program to download Microsoft stock prices from Yahoo Finance. The program includes downloading a URL as a string, splitting the string at newlines and generating sequence elements when input lines can be parsed as floats.

We begin by defining the URL that we shall be downloading from:

let url = ""

The following function uses a WebClient to download a url as a string, splits it at newline characters and yields the resulting sequence:

let downloadLines (url: string) =
  seq { use wc = new System.Net.WebClient()
        yield! wc.DownloadString(url).Split '\n' }

The following active pattern wraps the built-in TryParse and will only match a string pattern if that string can be parsed as a float:

let (|Float|_|) s =
  let mutable x = 0.0
  if System.Double.TryParse(s, &x) then Some x else None

Stock prices are given in the form open, high, low and close which we encapsulate in a record type:

type Prices = { Open: float; High: float; Low: float; Close: float }

The following function downloads prices of the given stock:

let getStockPrices stock =
  seq { for line in downloadLines(url + stock) do
          match line.Split ',' |> List.ofSeq with
          | _::Float first::Float hi::Float lo::Float last::_ ->
              yield { Open=first; High=hi; Low=lo; Close=last }
          | _ -> () }

Note how easy it is to parse a line containing four floats using active patterns.

Now we can get the historical stock price data for Microsoft from Yahoo! Finance:

getStockPrices "MSFT"

Subscribe to the F# Journal today!

Machine learning: Principal component analysis

The F# Journal just published an article about machine learning:
"Many machine learning algorithms benefit from preconditioning the data to reduce a high dimensional problem into a low dimensional problem. For example, by identifying two orthonormal vectors such that projecting the inputs onto those two vectors captures most of the variability in the data set. Principal component analysis is one such algorithm. This article discusses the topic, describes two different solutions and visualizes the results..."
To read this article and more, subscribe to The F# Journal today!

Thursday, 12 September 2013

Stanford Bunny using OpenGL ES 1.1 on Android

The F# Journal just published an article about Android development:
"Xamarin's products can be used to run F# applications on non-Windows operating systems including Android and iOS. This article covers the use of MonoDroid to run an F# program on an Android device such as a Google Nexus table. The program is the same Stanford Bunny demo from a previous article ported to OpenGL ES 1.1..."

To read this article and more, subscribe to The F# Journal today!

Wednesday, 11 September 2013

Color wheel

The following program uses our F# for Visualization library to draw a color wheel:

open System.Windows
open FlyingFrog.Graphics

let brush(r, g, b) =
  let f x = 256.0 * x |> max 0.0 |> min 255.0 |> byte
  Media.SolidColorBrush(Media.Color.FromRgb(f r, f g, f b))

let polygon brush xys =
  Shape([Interior brush], [ Contour.Closed[for x, y in xys -> line_to x y] ])

let wheel m n =
 let a = System.Math.PI / float n
  let ka, sa = cos a, sin a
  let ta = (ka + sa) / (ka - sa)
  let d = ka + sa * ta
  let m = float m
    [ for e in 0.0..m-1.0 do
        let r = 1.0 / (ka - sa) ** e
        for i in 0..n-1 do
          let t = a * (float(2*i) + e)
          let k, s = r * cos t, r * sin t
            polygon (brush(float i / float n, 0.5*(1.0 + e/m), 0.5*(2.0 - e/m)))
              [ k, s
                d*k*ka - d*s*sa, d*s*ka + d*k*sa
                ta*k, ta*s
                d*k*ka + d*s*sa, d*s*ka - d*k*sa ] ]

View(wheel 12 16)

Tuesday, 10 September 2013

A simple Fast Fourier Transform (FFT)

The Fast Fourier Transform is the most important spectral method in computing and lies at the heart of many common algorithms including compressed formats for image, video and sound.

The following is a simple 15-line implementation of the FFT written in F#:

open System.Numerics

let fft a =
  let rec loop n a =
    if n < 2 then Array.init n a else
      let e = loop (n/2) (fun i -> a(2*i))
      let o = loop (n/2) (fun i -> a(2*i + 1))
      let a = Array.create n Complex.Zero
      let f k k' =
        let t = 2. * System.Math.PI * float k / float n
        a.[k] <- complex="" cos="" e.="" k="" o.="" o:p="" sin="" t="">
      for k=0 to n/2 - 1 do
        f k k
      for k=n/2 to n - 1 do
        f k (k - n/2)
  loop (Array.length a) (Array.get a)

Note that this implementation works only for inputs with an integral-power-of-two number of samples. For a professional high-performance solution that handles any size input please buy our F# for Numerics software library.

The following array of complex numbers represents the spectrum of a low-frequency cosine wave:

let zs =
  [|0; 1; 0; 0; 0; 0; 0; 1|]
  |> (fun x -> Complex(float x, 0.0))

In order to make the output from F# Interactive comprehensible we shall provide our own custom pretty printer for complex numbers. Firstly, we wish to truncate small floating point numbers to zero:

let chop x =
  if abs x < 1e-5 then 0.0 else x

Now we can write a function to convert the chopped real and imaginary components of a complex number into a string, skipping any zeros:

let stringOfComplex (z: Complex) =
  match chop z.Real, chop z.Imaginary with
  | 0.0, 0.0 -> "0"
  | 0.0, y -> sprintf "%fi" y
  | x, 0.0 -> sprintf "%f" x
  | x, y -> sprintf "%f + %fi" x y

This function may be registered as the pretty printed for complex numbers with F# Interactive as follows:

fsi.AddPrinter stringOfComplex

The output of our fft function is then:

fft zs

val it : Complex [] =
  [|2.000000; 1.414214; 0; -1.414214; -2.000000; -1.414214; 0; 1.414214|]

This is one complete cycle of a cosine wave (the lowest possible frequency with this sampling) with amplitude two. Note the appearance of 2×cos(pi/4) = √2.

Monday, 9 September 2013

Ten F# one-liners to impress your friends

These ten one-liners are trending in other languages so here is an F# translation:

Multiply each item in a list by two
[for n in 1..10 -> 2*n]

Sum a list of numbers
Seq.sum [1..1000]

Verify if word exists as a substring in a string
Seq.exists tweet.Contains wordList

Read a file as a single string or line-by-line
System.IO.File.ReadAllText "data.txt"
System.IO.File.ReadLines "data.txt"

Happy birthday to you
for i in 1..4 do printfn "Happy Birthday %s" (if i=3 then "dear NAME" else "to You")

Filter list of numbers
let failed, passed = List.partition ((>) 60) [49; 58; 76; 82; 88; 90]

Load XML
#r "System.Xml.Linq"; System.Xml.Linq.XDocument.Load "data.xml"

Find min/max of list of numbers
Seq.min [14; 35; -7; 46; 98]
Seq.max [14; 35; -7; 46; 98]

Parallel processing ((*) 2) [|1..100|]

Seq.filter (fun i -> Seq.forall (fun j -> i%j<>0) [2..i-1]) [2..50]

Sunday, 8 September 2013

F# for Visualization update

A new version of our F# for Visualization library has been released. This library makes it easy to create interactive 2D and 3D graphs using F# including mathematically typeset labels and annotations.

Watch this tutorial video and see the pictures below:

A labelled plot of a sine wave:

Plot([Function sin; Data xys], (-6., 6.), Labels=(Text "x", Text "sin(x)"))

F# for Visualization provides a handy View function that tries to visualize any value of any type, such as an F# PowerPack matrix of arbitrary-precision rational numbers:

let A =
    [ for i in 0N..4N ->
        [ for j in 0N..4N ->
            1N / (i + j + 1N) ] ]

View A

In combination with mathematical typesetting, this allows us to build up and visualize complicated expressions:

View(Row[math A; Symbols.Times; math(inverse A); math "="; math(A*inverse A)])

Arbitrary 2D vector graphics can be drawn, such as the following doodle:

let styles = [ Stroke(Brushes.Red, {width = 0.001}) ]

let geometry =
  let n = 50
  [ for i in 0 .. n do
      for j in 0 .. 1 do
        let x, y = float i / float n, float j
        yield Contour.Open(Point(x, y), [line_to y (1. - x)]) ]

View(Shape(styles, geometry))

Using a vector graphic as an Epilog allows it to be rendered with axes:

Plot([], (0., 1.), (0., 1.), Epilog=scene)

Plot a function of two variables in 3D:

let f x z =
  let r = 5. * sqrt(x*x + z*z)
  sin(r + 3. * x) / r
Plot3D(f, (-5., 5.), (-5., 5.), (-0.1, 1.))

Visualize a predefined mesh:

View(Shape3D(Polyhedra.Icosahedron.mesh, Brushes.White))

And many more features...

Friday, 6 September 2013

F# for Numerics

A version of our F# for Numerics library optimized for .NET 4.x has been released. New features include:

  • Linear least-squares regression (curve fitting).
  • 2D convex hulls.
  • Delaunay triangulation.
  • k-means algorithm for machine learning with example data.
  • Longest common subsequence and Levenshtein edit distance.
  • Root finding.
  • Parallel aggregates: mapReduce, reduce, minBy, maxBy, tryPick, tryFindIndex, exists and forall.

Existing customers can download the latest .NET assembly and an F# script providing extensive worked examples for free.

As always, the new features are designed for ease of use and integrate seamlessly with our F# for Visualization library. Convex hull:

Delaunay triangulation:
 Linear least squares best fit of a quadratic through a sine wave:

Tuesday, 3 September 2013

Massaging data for optical character recognition

The F#.NET Journal just published an article about optical character recognition:
"Optical character recognition is a family of algorithms designed to convert scanned images of text into sequences of characters. This article describes a simple technique to segment an image of hand-written numbers into individual digits and use a simple metric to identify each digit..."
To read this article and more, subscribe to The F#.NET Journal today!