I need to estimate a multivariate function, known from discrete scattered data.
I am using ILNumerics interpolation toolbox for that.
I have the following code to test the library from F#:
let inline (!) (x :RetArray<'T>) = Array<'T>.op_Implicit(x)
let inline (!!) (x:Array<'T> ) = InArray<'T>.op_Implicit(x)
let inline (!!!) (x:float[]) :InArray<float> = x
|> InArray.op_Implicit
let inline (!~) (x:float[]) : Array<float> = x
|> Array.op_Implicit
let X3 :OutArray<float>= null
let V (x:'T[]) :Array<'T> = (ILMath.vector<'T> x) |> Array.op_Implicit
let X1':Array<float> = (linspace<float>((!!!)[|-3.0|],(!!!) [|3.0|],(!!!)[|20.0|]))
|> (Seq.toArray >> V )
let Y:Array<float> = sin(X1')|> (Seq.toArray >> V)
let result = kriging( (!!)Y, (!!) X1', (!!) X1', null, X3) |> (Seq.toArray >> V)
I get the following error:
System.ArgumentException: V must be a non-empty matrix of size [k x n], where n = X.S[1]
I suspect that the internal code tries to evaluate X.S[1] and it fails, in F#, since it would need X.S.[1]; I may be completely wrong, but I would like to know whether the library may also be used from F# or it is pointless even to try.
I have also tried using the KrigingInterpolator class and I get a similar error.
On a side note: do you know any reliable library which performs multivariate interpolation for scattered data, with F#?
Related
I am trying to use ILNumerics from F#. It seems quite difficult.
I would like to replicate this example
What I have so far is the following code:
open ILNumerics
open type ILMath
let inline (!) (x :RetArray<'T>) = Array<'T>.op_Implicit(x)
let inline (!!) (x:Array<'T> ) = InArray<'T>.op_Implicit(x)
let inline (!!!) (x:float[]) :InArray<float> = Array.map float32 x
|> InArray.op_Implicit
let inline (!~) (x:float[]) : Array<float> = Array.map float32 x
|> Array.op_Implicit
let vec1 = (!~) [|1.0 .. 0.1 .. 2.0 |]
let X1 = (linspace<float>((!!!)[|-3.0|],(!!!) [|3.0|],(!!!)[|20.0|]))
|> Seq.toArray
|> (!~)
|> (!!)
let X2 = X1
let X3 :OutArray<float>= null
let T = meshgrid(X1,X2, X3)
Do I really need all these conversions to make it work? Also, how do I use an interpolant? I have scattered data and have to map from R3 -> R2 and from R4 -> R3.
I was considering Kriging interpolation, but it seems quite tough to use the library from F#. Any suggestion? Otherwise will be better off to solve the problem in C# and call it from F#, when needed?
In my effort to shift from using native F# types to Math.NET Numerics types an example would be most helpful.
How would the following be expressed as an operation on DenseMatrix or DenseVector types? I've played around with the snippet below to try and express all containers as Math.NET types but kept getting a variety of errors.
open MathNet.Numerics
open MathNet.Numerics.LinearAlgebra
open MathNet.Numerics.Random
open MathNet.Numerics.Distributions
open MathNet.Numerics.Statistics
let Tsize = 10
let Tsamps = 5
let expLL (arr : float []) =
arr |> Array.average
let arrL = Array.init Tsamps (
fun i ->
[|
for i in 1 .. Tsize do
yield Exponential.Sample(1.)
|] |> expLL
)
In addition, whats the quickest way to convert a float [] or a float [] [] to a DenseMatrix?
I do not think there is anything about your sample that needs to be done differently - Math.NET provides nice functionality for doing linear algebra, but you're not really doing any matrix or vector calculations here, so basic arrays work just fine. If you wanted to turn the result into a vector, I'd probably write something like this (with minor tweak to avoid too long lines):
let sample () = Array.init Tsize (fun _ -> Exponential.Sample(1.0)) |> expLL
let vecL = vector [ for i in 1 .. Tsamps -> sample() ]
As for turning data into matrices, there is a matrix function:
let nested = [ [1.0; 2.0; 3.0]; [4.0; 5.0; 6.0] ]
let m = matrix nested
I want to generalize my standard deviation function to allow for calculations of multiples of deviations, but still use it in the context of piping. It appears that I am setting up my function incorrectly.
let variance (x:seq<float>) =
let mean = x |> Seq.average
x |> Seq.map(fun x -> (x - mean) ** 2.0)
|> Seq.average
let stdDeviation (deviations:float, x:seq<float>) =
sqrt (x |> variance) * deviations
Example usage would be
let sTester = seq{1.0 .. 20.0}
let stdDev = sTester |> stdDeviation 1.0
I keep getting the error: The expression was expecting to have the type: seq -> a' but here has type float
Help is greatly appreciated.
Thanks,
~David
If you change your stdDeviation so that it takes two parameters, rather than a tuple then it works:
let stdDeviation (deviations:float) (x:seq<float>) =
sqrt (x |> variance) * deviations
let stdDev = sTester |> stdDeviation 1.0
The idea is that when you write let stdDeviation (deviations, x:seq<float>) then you are defining a function that takes a single parameter that is actually a tuple.
The way the |> operator works is that it supplies one parameter to the function on the right. So if you have just one parameter (which is a tuple), then the pipe isn't all that useful.
But if you say let stdDeviation deviations (x:seq<float>) then you are defining a function with two parameters. When you write input |> stdDeviations 1.0 you are then providing the first parameter on the right hand side and the input (second parameter) on the left via the pipe.
I've been trying to get my head round various bits of F# (I'm coming from more of a C# background), and parsers interest me, so I jumped at this blog post about F# parser combinators:
http://santialbo.com/blog/2013/03/24/introduction-to-parser-combinators
One of the samples here was this:
/// If the stream starts with c, returns Success, otherwise returns Failure
let CharParser (c: char) : Parser<char> =
let p stream =
match stream with
| x::xs when x = c -> Success(x, xs)
| _ -> Failure
in p //what does this mean?
However, one of the things that confused me about this code was the in p statement. I looked up the in keyword in the MSDN docs:
http://msdn.microsoft.com/en-us/library/dd233249.aspx
I also spotted this earlier question:
Meaning of keyword "in" in F#
Neither of those seemed to be the same usage. The only thing that seems to fit is that this is a pipelining construct.
The let x = ... in expr allows you to declare a binding for some variable x which can then be used in expr.
In this case p is a function which takes an argument stream and then returns either Success or Failure depending on the result of the match, and this function is returned by the CharParser function.
The F# light syntax automatically nests let .. in bindings, so for example
let x = 1
let y = x + 2
y * z
is the same as
let x = 1 in
let y = x + 2 in
y * z
Therefore, the in is not needed here and the function could have been written simply as
let CharParser (c: char) : Parser<char> =
let p stream =
match stream with
| x::xs when x = c -> Success(x, xs)
| _ -> Failure
p
The answer from Lee explains the problem. In F#, the in keyword is heritage from earlier functional languages that inspired F# and required it - namely from ML and OCaml.
It might be worth adding that there is just one situation in F# where you still need in - that is, when you want to write let followed by an expression on a single line. For example:
let a = 10
if (let x = a * a in x = 100) then printfn "Ok"
This is a bit funky coding style and I would not normally use it, but you do need in if you want to write it like this. You can always split that to multiple lines though:
let a = 10
if ( let x = a * a
x = 100 ) then printfn "Ok"
(I'm still banging on with units of measure in F#)
I'm having a problem making 'generic' functions which take 'typed' floats.
The following mockup class is intended to keep tabs on a cumulative error in position, based on a factor 'c'. The compiler doesn't like me saying 0.<'a> in the body of the type ("Unexpected type parameter in unit-of-measure literal").
///Corrects cumulative error in position based on s and c
type Corrector(s_init:float<'a>) =
let deltaS ds c = sin (ds / c) //incremental error function
//mutable values
let mutable nominal_s = s_init
let mutable error_s = 0.<'a> //<-- COMPILER NO LIKE
///Set new start pos and reset error to zero
member sc.Reset(s) =
nominal_s <- s
error_s <- 0.<'a> //<-- COMPILER NO LIKE
///Pass in new pos and c to corrector, returns corrected s and current error
member sc.Next(s:float<'a>, c:float<'a>) =
let ds = s - nominal_s //distance since last request
nominal_s <- s //update nominal s
error_s <- error_s + (deltaS ds c) //calculate cumulative error
(nominal_s + error_s, error_s) //pass back tuple
Another related question, I believe, still to do with 'generic' functions.
In the following code, what I am trying to do is make a function which will take a #seq of any type of floats and apply it to a function which only accepts 'vanilla' floats. The third line gives a 'Value Restriction' error, and I can't see any way out. (Removing the # solves the problem, but I'd like to avoid having to write the same thing for lists, seqs, arrays etc.)
[<Measure>] type km //define a unit of measure
let someFloatFn x = x + 1.2 //this is a function which takes 'vanilla' floats
let MapSeqToNonUnitFunction (x:#seq<float<'a>>) = Seq.map (float >> someFloatFn) x
let testList = [ 1 .. 4 ] |> List.map float |> List.map ((*) 1.0<km>)
MapSeqToNonUnitFunction testList
You can change the first 'compiler no like' to
let mutable error_s : float<'a> = 0.0<_>
and the compiler seems to like that.
As for the second question, I am not seeing the same error as you, and this
[<Measure>] type km
//define a unit of measure
let someFloatFn x = x + 1.2 //this is a function which takes 'vanilla' floats
let MapSeqToNonUnitFunction (x:seq<float<_>>) = Seq.map (float >> someFloatFn) x
let testList = [ 1 .. 4 ] |> List.map float |> List.map ((*) 1.0<km>)
let testList2 = testList :> seq<_>
let result = MapSeqToNonUnitFunction testList2
printfn "%A" result
compiles for me (though the upcast to seq<_> is a little annoying, I am not sure if there is an easy way to get rid of it or not).
Aside, I think convention is to name units parameters 'u, 'v, ... rather than 'a, 'b, ...
Units of measure cannot be used as type parameters. This is because the are erased by the compiler during compilation. This question is quite similar:
F# Units of measure - 'lifting' values to float<something>