Tuesday, April 15, 2014

WPF 3D Tutorial in F#

Mike Hodnick published an excellent WPF 3D tutorial for C#. I took this as a nice opportunity to practice frontend development by porting it to F#. This post is a summary of lessons learned of this excercise.

 Porting the Application

I started with the standard project template "F# Empty Windows App (WPF)". Following the tutorial, the first step is to fill the main window XAML file with the layout of the application. Using the XAML type provider of the FSharpx package which is already included to the project references by the project template, the GUI binding declarations in the XAML configuration are available in the F# source file. The only issue I ran into was the failing access to the TextBox widget which I had to bind manually:

The other aspect to deal with relates to the treatment of the wire model. The model is built up by using the 3DTools library (published under the Microsoft Limited Permissive License (Ms-LPL)). This model does not comply to the necessary type hierarchy as expected by WPF. Hence, a workaround has to be applied:

In order to achieve this, the Viewport3D element of the main window needs to be available as a reference within the MainWindow module:

The application demonstrates the functionality to toggle between graphic objects (triangle, cube and mesh). Each of these objects comes with its own additions to the viewport container. In order to restore the ViewportObject to the initial state as declared in the XAML file, these added elements have to be removed. The baseline of the initial is the preconfigured the camera:

The strategy of the demo application is to deleted all elements which were added after the initial state:

The solution, while certainly not idiomatic, shows an interesting difference between F# and C#, because C# allows to iteratively change a mutable collection which is not possible in the same fashion in F#:

At this point, the release version of the 3DTools library contains an error which leads to dangling null pointer: the viewport descendants register internally a handler which becomes void after removal of the corresponding descendant. A later patch fixes this issue. I retrieved the patched version from Mike Hodnick´s github repository and added it to my own project.

The code of this port is on Github.
© Apache 2.0 license, the same as F#, where applicable.

Genetic Algorithm

Tao Liu published an implementation of a Genetic Algorithm on his blog in 2011. In order to understand the concept, I reworked the original and added a heat map representation.

The Concept of the Genetic Algorithm

In essence, the genetic algorithm is a randomized simulation of the evolution of a chromosome type across a given number of  of generations. The properties of a chromosome are given by a set of Geno Types and Pheno Types, both represented as a list of integers of same length and value range. the evolution from one generation to the next is modelled via a fitness function. The function used in the demonstration code is simply the sum of the Pheno Type values. The evolutionary selection is driven by the cross over rate of the best fit, overlapped with a randomized mutation of the chromosomes by rate. The settings in the demo simulation rates are 90 % and 10 % respectively which effectivly predetermines the outcome of the simulation.

The Heat Map Representation

I added a heat map representation which maps the value of the chromosome types to a color scale from green to red in ascending order of the underlying integer values. Hence, after a simulation across 75 generations, the original chromosomes with a randomly distributed coloring turn into almost completely red population.


Notes on the Implementation

The reworked version on the genetic algorithm is based on generic types for the model for the Genos and Phenos. As such, the implementation leverages on the type system features of F#, namely type restrictions. The refactoring is significantly eased by the type inference cleverness of the compiler.

The .NET framework provides support for the JPG format handling. In order to deal with video formats, I chose to use the AviFile-Library wrapper provided by Corinna John under the CPOL license. For convenience, I include the necessary library file AviFile.dll in this project package. Otherwise, the Apache 2.0 license, the same as F#, applies.

When the script is executed, the AviFile library opens a dialog which needs to be accepted with the setting as shown here:

In my installation, the other options related to file compression do not work but throw an exception.

The code is on Github.

Saturday, April 12, 2014

Kalman Filter

Kalman filter separate signal from noise. A nice explanation and a implementation in presented in this TKJ Electronics blog post. The port to F# is straight forward.

The first example uses a course grid with respect to time. As a result, the Kalman filter cannot detect the underlying signal shape correctly. Instead, the filtered signal follows closely the noisy signal:

Using a finer grid for the time component, the Kalman filter is enabled to detect the true signal through the noise:

The source code is on Github.


PID Control

Recently, I successfully followed on Coursera the lecture Control of Mobile Robots by Dr. Magnus Egerstedt. I recommend the excellent course material, which is kept available, to everybody interested in this topic. For the PID control algorithm, I came across another source on youtube from Mark Harrison: East Bay Guide to PID Loops, Part 2: The math and the coding which is even superior the corresponding lecture.

The essence of the algorithm fits on one page:

I implemented the PID control in F# using measures in order to enforce correctness of calculations with respect to the physical units in use. Differently from the standard convention to use for the time slice a implicitely defined time unit, I explicitely use the time unit as a parameter. As a consequence, the values of the P, I, D parameters are always correctly scaled in the model.

The following chart shows the PID control in effect for a mass point x moving in one dimension from point 0 to point 3.5, measured in meter, in about 3 seconds:

 The source code is available on Github.