Computer Science Experimentation

Tuesday, September 14, 2010

Graphics in F# interactive

The following script snippets present graphics functionalities available in FlyingFrog.Graphics namespace from FSharpForVisualization assembly.
This functionalities allow the usage of F# interactive with plots much like other tools as Matlab or Python with MatPlotLib.
#I @"C:\cs\Docs"
#r "FSharp.PowerPack.dll"

// Reference WPF
#r "PresentationCore.dll"
#r "PresentationFramework.dll"
#r "WindowsBase.dll"

// Reference to FlyingFrog
#r @"FSharpForVisualization.dll"


open System.Windows
open System.Windows.Media
open FlyingFrog.Graphics;;

//Plot
Plot([Function sin], (-6., 6.));;

// Plot coordinates
let xys =
   [ for x in -5 .. 5 ->
       let x = float x
       x, sin x ]

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


// Progressive creation of a plot. Begin with an empty plot:
let g = Plot([], (-6., 6.));;

// And then specify a function to be plotted:
g.Data <- [Function sinc; Data[System.Math.PI, 0.]];;

// Specify as many functions:
g.Data <- [Function sin; Function cos];;

// Alter the styles:
g.Styles <- [Brushes.Black; Brushes.Gray];;



// 3D surface plot
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.));;
 
 
// Vector graphic shapes are styled by a sequence of strokes or fills:

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), [ Segment.Line(Point(y, 1. - x)) ]) ]
let scene = Shape(styles, geometry)

View scene;;



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


// 3D object - icosahedron
let scene1 = Shape3D(Polyhedra.Icosahedron.mesh, Brushes.White)
View3D scene1;;

2 comments:

  1. Very cool! I wish there was a free version of the flying frog library. I'm doing similar post series from a MATLAB perspective using F# and WPF.

    ReplyDelete
  2. This looks like an interesting tool:
    http://code.msdn.microsoft.com/fschart

    ReplyDelete