I testing F# code which calculates "nearness" of two N-dimensional points using a least square euclidean distance algorithm. The class library is written in F# and the calling will be from VB.NET. The code will eventually be used for scientific binary data, however I wanted a simple real world test environment.
I choose to create an rgb color table class based upon a list of color names along with their 3 digit rgb value. The rgb values will be used for the distance algorithm. The code works, however I'd like to make sure that the distance algorithm in written in an efficient manner. The code will be called heavily in the final package.
My VB code will create the class instance, adds colors to the color table and finally searches for the nearest match of an unnamed color. The results is DarkGoldenRod.
Dim GreenYellow() As Double = {173, 255, 47}
Dim Orange() As Double = {255, 127, 0}
Dim Lavender() As Double = {230, 230, 250}
Dim Magenta() As Double = {255, 0, 255}
Dim DarkGoldenRod() As Double = {184, 134, 11}
Dim test() As Double = {122, 122, 122}
Dim objFSColorTable As New MyFSColorTable("GreenYellow", GreenYellow)
objFSColorTable.AddEntry("Lavender", Lavender)
objFSColorTable.AddEntry("Orange", Orange)
objFSColorTable.AddEntry("Magenta", {255, 0, 255})
objFSColorTable.AddEntry("DarkGoldenRod", {184, 134, 11})
Dim name = objFSColorTable.ColorSearch(test)
The F# code contains the color table library which should be self explanatory
type MyColor =
{ Name: string;
Values: float[];
}
type MyFSColorTable(name: string, rgb:float[]) = class
let mutable myHash = Hashtable()
let mutable CurName = name
let mutable CurDist = 0.0
let mutable CurColor =
{ Name = name;
Values = rgb;
}
let mutable CurList = [CurColor]
member x.AddColor name rgb = CurList <- List.append CurList [{Name = name; Values = rgb}]
member x.Name = name
// Euclidean distance between 2 vectors
member x.Dist (V1: float[]) V2 =
Array.zip V1 V2
|> Array.map(fun (v1, v2) -> (v1 - v2) * (v1 - v2))
|> Array.sum
// Loop thru color hash and find the nearest match
member x.ColorSearch (R1: float[]) =
let mutable mindist = x.Dist R1 CurList.Head.Values
let mutable name = CurList.Head.Name
for i in (CurList) do
let mutable s = 0.0
s <- x.Dist R1 i.Values
if s < mindist then
mindist <- s
name <- i.Name
name
// RGB Hash Table
member x.RGBHash = myHash
member x.AddEntry (name:string) (rgb: float[]) = x.AddColor name rgb
end