diff --git a/src/FSharp/BigRational.fs b/src/FSharp/BigRational.fs index 221970e2..3f78da44 100644 --- a/src/FSharp/BigRational.fs +++ b/src/FSharp/BigRational.fs @@ -1,7 +1,5 @@ // First version copied from the F# Power Pack // https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack/math/q.fs - - // (c) Microsoft Corporation. All rights reserved #nowarn "44" // OK to use the "compiler only" function RangeGeneric diff --git a/src/FSharp/BigRational.fsi b/src/FSharp/BigRational.fsi index d6c7d422..2b863431 100644 --- a/src/FSharp/BigRational.fsi +++ b/src/FSharp/BigRational.fsi @@ -1,7 +1,5 @@ // First version copied from the F# Power Pack // https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack/math/q.fsi - - // (c) Microsoft Corporation 2005-2009. namespace MathNet.Numerics @@ -93,4 +91,4 @@ namespace MathNet.Numerics val FromOne : unit -> BigRational val FromInt32 : int32 -> BigRational val FromInt64 : int64 -> BigRational - val FromString : string -> BigRational \ No newline at end of file + val FromString : string -> BigRational diff --git a/src/FSharp/Complex.fsi b/src/FSharp/Complex.fsi index 605cb4cb..c2ffadb7 100644 --- a/src/FSharp/Complex.fsi +++ b/src/FSharp/Complex.fsi @@ -53,7 +53,7 @@ namespace MathNet.Numerics val mul : complex -> complex -> complex /// Complex division of two complex numbers val div : complex -> complex -> complex - + /// Multiply a scalar by a complex number val smul : float -> complex -> complex /// Multiply a complex number by a scalar @@ -156,7 +156,7 @@ namespace MathNet.Numerics val mul : complex32 -> complex32 -> complex32 /// Complex division of two complex numbers val div : complex32 -> complex32 -> complex32 - + /// Multiply a scalar by a complex number val smul : float32 -> complex32 -> complex32 /// Multiply a complex number by a scalar @@ -222,7 +222,7 @@ namespace MathNet.Numerics /// Constructs a double precision complex number from both the real and imaginary part. val complex : float -> float -> complex - + /// Constructs a single precision complex number from both the real and imaginary part. val complex32 : float32 -> float32 -> complex32 diff --git a/src/FSharp/LinearAlgebra.Double.Matrix.fs b/src/FSharp/LinearAlgebra.Double.Matrix.fs index 81542be8..aaecc1bf 100644 --- a/src/FSharp/LinearAlgebra.Double.Matrix.fs +++ b/src/FSharp/LinearAlgebra.Double.Matrix.fs @@ -35,7 +35,7 @@ open MathNet.Numerics.LinearAlgebra.Generic /// A module which implements functional matrix operations. [] module Matrix = - + /// Fold a function over all matrix elements. let inline fold (f: 'a -> float -> 'a) (acc0: 'a) (A: #Matrix) = let n = A.RowCount @@ -71,8 +71,8 @@ module Matrix = let n = A.RowCount let m = A.ColumnCount Array2D.init n m (fun i j -> (A.Item(i,j))) - - /// Checks whether a predicate holds for all elements of a matrix. + + /// Checks whether a predicate holds for all elements of a matrix. let inline forall (p: float -> bool) (A: #Matrix) = let mutable b = true let mutable i = 0 @@ -82,7 +82,7 @@ module Matrix = j <- j+1 if j = A.ColumnCount then i <- i+1; j <- 0 b - + /// Chechks whether a predicate holds for at least one element of a matrix. let inline exists (p: float -> bool) (A: #Matrix) = let mutable b = false @@ -93,7 +93,7 @@ module Matrix = j <- j+1 if j = A.ColumnCount then i <- i+1; j <- 0 b - + /// Checks whether a position dependent predicate holds for all elements of a matrix. let inline foralli (p: int -> int -> float -> bool) (A: #Matrix) = let mutable b = true @@ -104,7 +104,7 @@ module Matrix = j <- j+1 if j = A.ColumnCount then i <- i+1; j <- 0 b - + /// Checks whether a position dependent predicate holds for at least one element of a matrix. let inline existsi (p: int -> int -> float -> bool) (A: #Matrix) = let mutable b = false @@ -115,7 +115,7 @@ module Matrix = j <- j+1 if j = A.ColumnCount then i <- i+1; j <- 0 b - + /// Map every matrix element using the given function. let inline map (f: float -> float) (A: #Matrix) = let N = A.RowCount @@ -125,7 +125,7 @@ module Matrix = for j=0 to M-1 do C.[i,j] <- f (C.Item(i,j)) C - + /// Map every matrix element using the given position dependent function. let inline mapi (f: int -> int -> float -> float) (A: #Matrix) = let N = A.RowCount @@ -135,7 +135,7 @@ module Matrix = for j=0 to M-1 do C.[i,j] <- f i j (C.Item(i,j)) C - + /// In-place map every matrix column using the given position dependent function. let inline inplaceMapCols (f: int -> Vector -> Vector) (A: #Matrix) = for j = 0 to A.ColumnCount-1 do @@ -165,19 +165,19 @@ module Matrix = for i=0 to A.RowCount-1 do for j=0 to A.ColumnCount-1 do A.Item(i,j) <- f i j - + /// In-place map of every matrix element using a position dependent function. let inline inplaceMapi (f: int -> int -> float -> float) (A: #Matrix) = for i=0 to A.RowCount-1 do for j=0 to A.ColumnCount-1 do A.Item(i,j) <- f i j (A.Item(i,j)) - + /// Creates a sequence that iterates the non-zero entries in the matrix. let inline nonZeroEntries (A: #Matrix) = seq { for i in 0 .. A.RowCount-1 do for j in 0 .. A.ColumnCount-1 do if A.Item(i,j) <> 0.0 then yield (i,j, A.Item(i,j)) } - + /// Returns the sum of all elements of a matrix. let inline sum (A: #Matrix) = let mutable f = 0.0 @@ -189,7 +189,7 @@ module Matrix = /// Returns the sum of the results generated by applying a position dependent function to each column of the matrix. let inline sumColsBy (f: int -> Vector -> 'a) (A: #Matrix) = A.ColumnEnumerator() |> Seq.map (fun (j,col) -> f j col) |> Seq.reduce (+) - + /// Returns the sum of the results generated by applying a position dependent function to each row of the matrix. let inline sumRowsBy (f: int -> Vector -> 'a) (A: #Matrix) = A.RowEnumerator() |> Seq.map (fun (i,row) -> f i row) |> Seq.reduce (+) @@ -200,21 +200,21 @@ module Matrix = for j=0 to A.ColumnCount-1 do f (A.Item(i,j)) () - + /// Iterates over all elements of a matrix using the element indices. let inline iteri (f: int -> int -> float -> unit) (A: #Matrix) = for i=0 to A.RowCount-1 do for j=0 to A.ColumnCount-1 do f i j (A.Item(i,j)) () - + /// Fold one column. let inline foldCol (f: 'a -> float -> 'a) acc (A: #Matrix) k = let mutable macc = acc for i=0 to A.RowCount-1 do macc <- f macc (A.Item(i,k)) macc - + /// Fold one row. let inline foldRow (f: 'a -> float -> 'a) acc (A: #Matrix) k = let mutable macc = acc @@ -231,7 +231,7 @@ module Matrix = macc <- f macc (A.Item(i,k)) v.[k] <- macc v :> Vector - + /// Fold all rows into one column vector. let inline foldByRow (f: float -> float -> float) acc (A: #Matrix) = let v = new DenseVector(A.RowCount) @@ -253,7 +253,7 @@ module DenseMatrix = for j=0 to m-1 do A.[i,j] <- f i j A - + /// Create a matrix from a list of float lists. Every list in the master list specifies a row. let inline ofList (fll: float list list) = let n = List.length fll @@ -263,7 +263,7 @@ module DenseMatrix = if (List.length fl) <> m then failwith "Each subrow must be of the same length." else List.iteri (fun j f -> A.[i,j] <- f) fl) A - + /// Create a matrix from a list of sequences. Every sequence in the master sequence specifies a row. let inline ofSeq (fss: #seq<#seq>) = let n = Seq.length fss @@ -276,20 +276,20 @@ module DenseMatrix = /// Create a matrix from a 2D array of floating point numbers. let inline ofArray2 (arr: float[,]) = new DenseMatrix(arr) - + /// Create a matrix with the given entries. let inline initDense (n: int) (m: int) (es: #seq) = let A = new DenseMatrix(n,m) Seq.iter (fun (i,j,f) -> A.[i,j] <- f) es A - + /// Create a square matrix with constant diagonal entries. let inline constDiag (n: int) (f: float) = let A = new DenseMatrix(n,n) for i=0 to n-1 do A.[i,i] <- f A - + /// Create a square matrix with the vector elements on the diagonal. let inline diag (v: #Vector) = let n = v.Count @@ -313,26 +313,26 @@ module DenseMatrix = /// A module which implements functional sparse vector operations. [] module SparseMatrix = - + /// Create a matrix from a list of float lists. Every list in the master list specifies a row. let inline ofList (rows: int) (cols: int) (fll: list) = let A = new SparseMatrix(rows, cols) fll |> List.iter (fun (i, j, x) -> A.[i,j] <- x) A - + /// Create a matrix from a list of sequences. Every sequence in the master sequence specifies a row. let inline ofSeq (rows: int) (cols: int) (fss: #seq) = let A = new SparseMatrix(rows, cols) fss |> Seq.iter (fun (i, j, x) -> A.[i,j] <- x) A - + /// Create a square matrix with constant diagonal entries. let inline constDiag (n: int) (f: float) = let A = new SparseMatrix(n,n) for i=0 to n-1 do A.[i,i] <- f A - + /// Create a square matrix with the vector elements on the diagonal. let inline diag (v: #Vector) = let n = v.Count diff --git a/src/FSharp/LinearAlgebra.Double.Vector.fs b/src/FSharp/LinearAlgebra.Double.Vector.fs index cdd2c0a5..4a076426 100644 --- a/src/FSharp/LinearAlgebra.Double.Vector.fs +++ b/src/FSharp/LinearAlgebra.Double.Vector.fs @@ -35,12 +35,12 @@ open MathNet.Numerics.LinearAlgebra.Generic /// A module which implements functional vector operations. [] module Vector = - + /// Transform a vector into an array. let inline toArray (v: #Vector) = let n = v.Count Array.init n (fun i -> v.Item(i)) - + /// Transform a vector into an array. let inline toList (v: #Vector) = let n = v.Count @@ -57,30 +57,30 @@ module Vector = for i=0 to v.Count-1 do v.Item(i) <- f i (v.Item(i)) () - + /// In-place vector addition. let inline addInPlace (v: #Vector) (w: #Vector) = v.Add(w, v) - + /// In place vector subtraction. let inline subInPlace (v: #Vector) (w: #Vector) = v.Subtract(w, v) - + /// Functional map operator for vectors. - /// + /// let inline map f (v: #Vector) = let w = v.Clone() mapInPlace (fun x -> f x) w w - + /// Applies a function to all elements of the vector. let inline iter (f: float -> unit) (v: #Vector) = for i=0 to v.Count-1 do f (v.Item i) - + /// Applies a function to all elements of the vector. let inline iteri (f: int -> float -> unit) (v: #Vector) = for i=0 to v.Count-1 do f i (v.Item i) - + /// Maps a vector to a new vector by applying a function to every element. let inline mapi (f: int -> float -> float) (v: #Vector) = let w = v.Clone() @@ -107,7 +107,7 @@ module Vector = for i=0 to v.Count-1 do acc <- f i acc (v.Item(i)) acc - + /// Checks whether a predicate is satisfied for every element in the vector. let inline forall (p: float -> bool) (v: #Vector) = let mutable b = true @@ -116,7 +116,7 @@ module Vector = b <- b && (p (v.Item(i))) i <- i+1 b - + /// Checks whether there is an entry in the vector that satisfies a given predicate. let inline exists (p: float -> bool) (v: #Vector) = let mutable b = false @@ -125,7 +125,7 @@ module Vector = b <- b || (p (v.Item(i))) i <- i+1 b - + /// Checks whether a predicate is true for all entries in a vector. let inline foralli (p: int -> float -> bool) (v: #Vector) = let mutable b = true @@ -134,7 +134,7 @@ module Vector = b <- b && (p i (v.Item(i))) i <- i+1 b - + /// Checks whether there is an entry in the vector that satisfies a given position dependent predicate. let inline existsi (p: int -> float -> bool) (v: #Vector) = let mutable b = false @@ -177,13 +177,13 @@ module Vector = p /// Creates a new vector and inserts the given value at the given index. - let inline insert index value (v: #Vector) = - let newV = new DenseVector(v.Count + 1) - for i = 0 to index - 1 do - newV.Item(i) <- v.Item(i) - newV.Item(index) <- value - for i = index + 1 to v.Count do - newV.Item(i) <- v.Item(i - 1) + let inline insert index value (v: #Vector) = + let newV = new DenseVector(v.Count + 1) + for i = 0 to index - 1 do + newV.Item(i) <- v.Item(i) + newV.Item(index) <- value + for i = index + 1 to v.Count do + newV.Item(i) <- v.Item(i - 1) newV /// A module which implements functional dense vector operations. @@ -203,14 +203,14 @@ module DenseVector = let v = DenseVector(n) fl |> List.iteri (fun i f -> v.[i] <- f) v - + /// Create a vector from a sequences. let inline ofSeq (fs: #seq) = let n = Seq.length fs let v = DenseVector(n) fs |> Seq.iteri (fun i f -> v.[i] <- f) v - + /// Create a vector with evenly spaced entries: e.g. rangef -1.0 0.5 1.0 = [-1.0 -0.5 0.0 0.5 1.0] let inline rangef (start: float) (step: float) (stop: float) = let n = (int ((stop - start) / step)) + 1 @@ -218,7 +218,7 @@ module DenseVector = for i=0 to n-1 do v.[i] <- (float i) * step + start v - + /// Create a vector with integer entries in the given range. let inline range (start: int) (stop: int) = new DenseVector([| for i in [start .. stop] -> float i |]) @@ -226,13 +226,13 @@ module DenseVector = /// A module which implements functional sparse vector operations. [] module SparseVector = - + /// Create a sparse vector with a given dimension from a list of entry, value pairs. let inline ofList (dim: int) (fl: list) = let v = new SparseVector(dim) fl |> List.iter (fun (i, f) -> v.[i] <- f) v - + /// Create a sparse vector with a given dimension from a sequence of entry, value pairs. let inline ofSeq (dim: int) (fs: #seq) = let v = new SparseVector(dim) diff --git a/src/FSharp/LinearAlgebra.fs b/src/FSharp/LinearAlgebra.fs index f81ed35e..366b8505 100644 --- a/src/FSharp/LinearAlgebra.fs +++ b/src/FSharp/LinearAlgebra.fs @@ -33,19 +33,19 @@ namespace MathNet.Numerics.LinearAlgebra.Generic // Module that contains implementation of useful F#-specific // extension members for generic Matrix and Vector types [] -module FSharpExtensions = +module FSharpExtensions = - // A type extension for the generic vector type that + // A type extension for the generic vector type that // adds the 'GetSlice' method to allow vec.[a .. b] syntax type MathNet.Numerics.LinearAlgebra.Generic. - Vector<'T when 'T : struct and 'T : (new : unit -> 'T) - and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable + Vector<'T when 'T : struct and 'T : (new : unit -> 'T) + and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable and 'T :> System.ValueType> with /// Gets a slice of a vector starting at a specified index /// and ending at a specified index (both indices are optional) /// This method can be used via the x.[start .. finish] syntax - member x.GetSlice(start, finish) = + member x.GetSlice(start, finish) = let start = defaultArg start 0 let finish = defaultArg finish (x.Count - 1) x.SubVector(start, finish - start + 1) @@ -53,14 +53,14 @@ module FSharpExtensions = // A type extension for the generic matrix type that // adds the 'GetSlice' method to allow m.[r1 .. r2, c1 .. c2] syntax type MathNet.Numerics.LinearAlgebra.Generic. - Matrix<'T when 'T : struct and 'T : (new : unit -> 'T) - and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable + Matrix<'T when 'T : struct and 'T : (new : unit -> 'T) + and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable and 'T :> System.ValueType> with - /// Gets a submatrix using a specified column range and + /// Gets a submatrix using a specified column range and /// row range (all indices are optional) /// This method can be used via the x.[r1 .. r2, c1 .. c2 ] syntax - member x.GetSlice(rstart, rfinish, cstart, cfinish) = + member x.GetSlice(rstart, rfinish, cstart, cfinish) = let cstart = defaultArg cstart 0 let rstart = defaultArg rstart 0 let cfinish = defaultArg cfinish (x.ColumnCount - 1) diff --git a/src/FSharp/RandomVariable.fs b/src/FSharp/RandomVariable.fs index 9bbd1e09..352b7ff4 100644 --- a/src/FSharp/RandomVariable.fs +++ b/src/FSharp/RandomVariable.fs @@ -10,22 +10,22 @@ open MathNet.Numerics type Outcome<'T> = { Value: 'T Probability : BigRational } - + type RandomVariable<'T> = Outcome<'T> seq - + // P(A AND B) = P(A | B) * P(B) let private bind f dist = - dist - |> Seq.map (fun p1 -> + dist + |> Seq.map (fun p1 -> f p1.Value - |> Seq.map (fun p2 -> - { Value = p2.Value; - Probability = + |> Seq.map (fun p2 -> + { Value = p2.Value; + Probability = p1.Probability * p2.Probability})) |> Seq.concat - + /// Inject a value into the RandomVariable type -let private returnM value = +let private returnM value = Seq.singleton { Value = value ; Probability = 1N/1N } type RandomVariableBuilder() = @@ -35,61 +35,61 @@ type RandomVariableBuilder() = let randomVariable = RandomVariableBuilder() -type CoinSide = - | Heads +type CoinSide = + | Heads | Tails - + [] [] -module RandomVariable = - +module RandomVariable = + // Create some helpers let toUniformDistribution seq = let l = Seq.length seq - seq + seq |> Seq.map (fun e -> - { Value = e; + { Value = e; Probability = 1N / bignum.FromInt l }) - - let probability dist = + + let probability dist = dist |> Seq.map (fun o -> o.Probability) |> Seq.sum - + let certainly = returnM let impossible<'a> :'a RandomVariable = toUniformDistribution [] - + let fairDice sides = toUniformDistribution [1..sides] - + let fairCoin = toUniformDistribution [Heads; Tails] - + let filter predicate dist = dist |> Seq.filter (fun o -> predicate o.Value) - + let filterInAnyOrder items dist = items |> Seq.fold (fun d item -> filter (Seq.exists ((=) (item))) d) dist /// Transforms a RandomVariable value by using a specified mapping function. - let map f dist = - dist + let map f dist = + dist |> Seq.map (fun o -> { Value = f o.Value; Probability = o.Probability }) - + let selectOne values = - [for e in values -> e,values |> Seq.filter ((<>) e)] + [for e in values -> e,values |> Seq.filter ((<>) e)] |> toUniformDistribution - + let rec selectMany n values = - match n with + match n with | 0 -> certainly ([],values) - | _ -> + | _ -> randomVariable { let! (x,c1) = selectOne values let! (xs,c2) = selectMany (n-1) c1 return x::xs,c2} - - let select n values = - selectMany n values + + let select n values = + selectMany n values |> map (fst >> List.rev) - + let remove items = Seq.filter (fun v -> Seq.forall ((<>) v) items) diff --git a/src/FSharpExamples/Apply.fs b/src/FSharpExamples/Apply.fs index 155b195e..16475939 100644 --- a/src/FSharpExamples/Apply.fs +++ b/src/FSharpExamples/Apply.fs @@ -90,5 +90,5 @@ for (name, fs, dotnet) in FunctionList do if prettyPrint then printfn "\tApply.Map (MKL): %d milliseconds." sw.ElapsedMilliseconds else printf "\t%d" sw.ElapsedMilliseconds sw.Reset()*) - + printfn "" \ No newline at end of file diff --git a/src/FSharpExamples/MCMC.fs b/src/FSharpExamples/MCMC.fs index d0ee5337..e48ac373 100644 --- a/src/FSharpExamples/MCMC.fs +++ b/src/FSharpExamples/MCMC.fs @@ -45,7 +45,7 @@ let rnd = new MersenneTwister() // ----------------------------------------------------------------------------- do printfn "Rejection Sampling Example" - + /// The target distribution. let beta = new Beta(2.7, 6.3) @@ -76,7 +76,7 @@ do // ----------------------------------------------------------------------------- do printfn "Metropolis Sampling Example" - + let mean, stddev = 1.0, 3.5 let normal = new Normal(mean, stddev) @@ -93,7 +93,7 @@ do printfn "\tEmpirical StdDev = %f (should be %f)" (Statistics.StandardDeviation(arr)) normal.StdDev printfn "\tAcceptance rate = %f" ms.AcceptanceRate printfn "" - + // @@ -107,12 +107,12 @@ do printfn "Metropolis Hastings Sampling Example (Symmetric Proposal)" let mean, stddev = 1.0, 3.5 let normal = new Normal(mean, stddev) - + /// Evaluates the log normal distribution. let npdf x m s = -0.5*(x-m)*(x-m)/(s*s) - 0.5 * log(2.0 * System.Math.PI * s * s) /// Implements the rejection sampling procedure. - let ms = new MetropolisHastingsSampler( 0.1, (fun x -> log(normal.Density(x))), + let ms = new MetropolisHastingsSampler( 0.1, (fun x -> log(normal.Density(x))), (fun x y -> npdf x y 0.3), (fun x -> Normal.Sample(rnd, x, 0.3)), 10, RandomSource = rnd ) @@ -138,22 +138,22 @@ do printfn "Metropolis Hastings Sampling Example (Assymetric Proposal)" let mean, stddev = 1.0, 3.5 let normal = new Normal(mean, stddev) - + /// Evaluates the logarithm of the normal distribution function. let npdf x m s = -0.5*(x-m)*(x-m)/(s*s) - 0.5 * log(2.0 * System.Math.PI * s * s) - + /// Samples from a mixture that is biased towards samples larger than x. let mixSample x = if Bernoulli.Sample(rnd, 0.5) = 1 then Normal.Sample(rnd, x, 0.3) else Normal.Sample(rnd, x + 0.1, 0.3) - + /// The transition kernel for the proposal above. let krnl xnew x = log (0.5 * exp(npdf xnew x 0.3) + 0.5 * exp(npdf xnew (x+0.1) 0.3)) /// Implements the rejection sampling procedure. - let ms = new MetropolisHastingsSampler( 0.1, (fun x -> log(normal.Density(x))), + let ms = new MetropolisHastingsSampler( 0.1, (fun x -> log(normal.Density(x))), (fun xnew x -> krnl xnew x), (fun x -> mixSample x), 10, RandomSource = rnd ) @@ -178,7 +178,7 @@ do printfn "Slice Sampling Example" let mean, stddev = 1.0, 3.5 let normal = new Normal(mean, stddev) - + /// Evaluates the unnormalized logarithm of the normal distribution function. let npdf x m s = -0.5*(x-m)*(x-m)/(s*s) diff --git a/src/FSharpUnitTests/BigRationalTests.fs b/src/FSharpUnitTests/BigRationalTests.fs index 65915416..d6f2bd5c 100644 --- a/src/FSharpUnitTests/BigRationalTests.fs +++ b/src/FSharpUnitTests/BigRationalTests.fs @@ -1,4 +1,4 @@ -// First version copied from the F# Power Pack +// First version copied from the F# Power Pack // https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack.Unittests/BigRationalTests.fs namespace MathNet.Numerics.Tests @@ -69,14 +69,14 @@ type public BigRationalTests() = points let pointsNonZero = [for p,q in points do if p<>0I then yield p,q] // non zero points - let makeQs p q = + let makeQs p q = if q = 1I && minIntI <= p && p <= maxIntI then // (p,1) where p is int32 let p32 = int32 p - [natA p32;natB p32;BigRational.FromBigInt p] // two reprs for int32 + [natA p32;natB p32;BigRational.FromBigInt p] // two reprs for int32 else [BigRational.FromBigInt p / BigRational.FromBigInt q] - + let miscQs = [for p,q in points do yield! makeQs p q] let product xs ys = [for x in xs do for y in ys do yield x,y] @@ -84,7 +84,7 @@ type public BigRationalTests() = let vector2s = product points points [] - member this.BasicTests1() = + member this.BasicTests1() = check "generic format h" "1N" (sprintf "%A" 1N) check "generic format q" "-1N" (sprintf "%A" (-1N)) @@ -92,7 +92,7 @@ type public BigRationalTests() = test "d3oc002" (LanguagePrimitives.GenericZero = 0N) test "d3oc112w" (LanguagePrimitives.GenericOne = 1N) - check "weioj3h" (sprintf "%O" 3N) "3" + check "weioj3h" (sprintf "%O" 3N) "3" check "weioj3k" (sprintf "%O" (3N / 4N)) "3/4" check "weioj3k" (sprintf "%O" (3N / 400000000N)) "3/400000000" check "weioj3l" (sprintf "%O" (3N / 3N)) "1" @@ -105,21 +105,21 @@ type public BigRationalTests() = let v = -30000000000000000000000000000000000000000000000000000000000000N check "weioj3r" (sprintf "%O" v) ((box v).ToString()) - + [] - member this.BasicTests2() = + member this.BasicTests2() = // Test arithmetic ops: tests - let test2One name f check ((p,q),(pp,qq)) = + let test2One name f check ((p,q),(pp,qq)) = // There may be several ways to construct the test rationals let zs = makeQs p q let zzs = makeQs pp qq - let results = [for z in zs do for zz in zzs do yield f (z,zz)] - let refP,refQ = check (p,q) (pp,qq) + let results = [for z in zs do for zz in zzs do yield f (z,zz)] + let refP,refQ = check (p,q) (pp,qq) let refResult = BigRational.FromBigInt refP / BigRational.FromBigInt refQ - let resOK (result:BigRational) = - result.Numerator * refQ = refP * result.Denominator && + let resOK (result:BigRational) = + result.Numerator * refQ = refP * result.Denominator && BigRational.Equals(refResult,result) match List.tryFind (fun result -> not (resOK result)) results with | None -> () // ok @@ -135,9 +135,9 @@ type public BigRationalTests() = test2All "div" (BigRational.(/)) (fun (p,q) (pp,qq) -> (p*qq,q*pp)) (product points pointsNonZero) - + [] - member this.RangeTests() = + member this.RangeTests() = // Test x0 .. dx .. x1 let checkRange3 (x0:BigRational) dx x1 k = let f (x:BigRational) = x * BigRational.FromBigInt k |> BigRational.ToBigInt @@ -146,7 +146,7 @@ type public BigRationalTests() = //printf "Length=%d\n" (Seq.length rangeA) let same = Seq.forall2 (=) rangeA rangeB check (sprintf "Range3 %A .. %A .. %A scaled to %A" x0 dx x1 k) same true - + checkRange3 (0I /% 1I) (1I /% 7I) (100I /% 1I) (7I*1I) checkRange3 (0I /% 1I) (1I /% 7I) (100I /% 11I) (7I*11I) checkRange3 (1I /% 13I) (1I /% 7I) (100I /% 11I) (7I*11I*13I) @@ -161,15 +161,15 @@ type public BigRationalTests() = // Test x0 .. x1 let checkRange2 (x0:BigRational) x1 = let z0 = BigRational.ToBigInt x0 - let z01 = BigRational.ToBigInt (x1 - x0) + let z01 = BigRational.ToBigInt (x1 - x0) let f (x:BigRational) = x |> BigRational.ToBigInt let rangeA = [x0 .. x1] |> List.map f // range with each item rounded down let rangeB = [z0 .. z0 + z01] // range of same length from the round down start point check (sprintf "Range2: %A .. %A" x0 x1) rangeA rangeB - checkRange2 (0I /% 1I) (100I /% 1I) - checkRange2 (0I /% 1I) (100I /% 11I) - checkRange2 (1I /% 13I) (100I /% 11I) + checkRange2 (0I /% 1I) (100I /% 1I) + checkRange2 (0I /% 1I) (100I /% 11I) + checkRange2 (1I /% 13I) (100I /% 11I) for i = 0 to 1000 do let m = 10000 // max steps is -m to m in steps of 1 i.e. 2.m let p0,q0 = nextZ m ,nextZ m + 1I @@ -178,7 +178,7 @@ type public BigRationalTests() = // ToString() // Cases: integer, computed integer, rational<1, rational>1, +/-infinity, nan - (natA 1).ToString() |> check "ToString" "1" + (natA 1).ToString() |> check "ToString" "1" (natA 0).ToString() |> check "ToString" "0" (natA (-12)).ToString() |> check "ToString" "-12" (natB 1).ToString() |> check "ToString" "1" @@ -211,29 +211,29 @@ type public BigRationalTests() = check "OneB" BigRational.One (natB 1) [] - member this.BinaryAndUnaryOperators() = + member this.BinaryAndUnaryOperators() = // Test: generic bop - let testR2One name f check ((p,q),(pp,qq)) = + let testR2One name f check ((p,q),(pp,qq)) = // There may be several ways to construct the test rationals let zs = makeQs p q let zzs = makeQs pp qq - let resultRef = check (p,q) (pp,qq) // : bool - let args = [for z in zs do for zz in zzs do yield (z,zz)] + let resultRef = check (p,q) (pp,qq) // : bool + let args = [for z in zs do for zz in zzs do yield (z,zz)] match List.tryFind (fun (z,zz) -> resultRef <> f (z,zz)) args with | None -> () // ok | Some (z,zz) -> printf "Test failed. %s (%A,%A) (%A,%A) = %s %A %A. Expected %A.\n" name p q pp qq name z zz resultRef reportFailure "cknwe9" // Test: generic uop - let testR1One name f check (p,q) = + let testR1One name f check (p,q) = // There may be several ways to construct the test rationals - let zs = makeQs p q - let resultRef = check (p,q) //: bool + let zs = makeQs p q + let resultRef = check (p,q) //: bool match List.tryFind (fun z -> resultRef <> f z) zs with | None -> () // ok | Some z -> printf "Test failed. %s (%A,%A) = %s %A. Expected %A.\n" name p q name z resultRef reportFailure "vekjkrejvre0" - + let testR2All name f check vectors = List.iter (testR2One name f check) vectors let testR1All name f check vectors = List.iter (testR1One name f check) vectors @@ -260,14 +260,14 @@ type public BigRationalTests() = testR1All "IsZero" (fun (x:BigRational) -> x = q0) (fun (p,q) -> sign p = 0I) vector1s - let test1One name f check (p,q) = + let test1One name f check (p,q) = // There may be several ways to construct the test rationals - let zs = makeQs p q + let zs = makeQs p q let results = [for z in zs -> f z] - let refP,refQ = check (p,q) + let refP,refQ = check (p,q) let refResult = BigRational.FromBigInt refP / BigRational.FromBigInt refQ - let resOK (result:BigRational) = - result.Numerator * refQ = refP * result.Denominator && + let resOK (result:BigRational) = + result.Numerator * refQ = refP * result.Denominator && BigRational.Equals(refResult,result) match List.tryFind (fun result -> not (resOK result)) results with | None -> () // ok @@ -275,7 +275,7 @@ type public BigRationalTests() = reportFailure "klcwe09wek" let test1All name f check vectors = List.iter (test1One name f check) vectors - + test1All "neg" (BigRational.(~-)) (fun (p,q) -> (-p,q)) vector1s test1All "pos" (BigRational.(~+)) (fun (p,q) -> (p,q)) vector1s // why have ~+ ??? @@ -312,27 +312,27 @@ type BigNumType() = let g_normal = 88N let g_bigintpositive = 1000000000000000000000000000000000018I let g_bigintnegative = -1000000000000000000000000000000000018I - + // Interfaces [] - member this.IComparable() = + member this.IComparable() = // Legit IC - let ic = g_positive1 :> IComparable - Assert.AreEqual(ic.CompareTo(g_positive1),0) + let ic = g_positive1 :> IComparable + Assert.AreEqual(ic.CompareTo(g_positive1),0) checkThrowsArgumentException( fun () -> ic.CompareTo(g_bigintpositive) |> ignore) - + // Base class methods [] member this.ObjectToString() = - + // Currently the CLR 4.0 and CLR 2.0 behavior of BigInt.ToString is different, causing this test to fail. - + Assert.AreEqual(g_positive1.ToString(), "1000000000000000000000000000000000018") - Assert.AreEqual(g_zero.ToString(),"0") + Assert.AreEqual(g_zero.ToString(),"0") Assert.AreEqual(g_normal.ToString(),"88") - - // Static methods + + // Static methods [] member this.Abs() = Assert.AreEqual(bignum.Abs(g_negative1), g_positive1) @@ -341,7 +341,7 @@ type BigNumType() = Assert.AreEqual(bignum.Abs(g_normal), g_normal) Assert.AreEqual(bignum.Abs(g_zero), g_zero) () - + [] member this.FromBigInt() = Assert.AreEqual(bignum.FromBigInt(g_bigintpositive), @@ -351,7 +351,7 @@ type BigNumType() = Assert.AreEqual(bignum.FromBigInt(0I),g_zero) Assert.AreEqual(bignum.FromBigInt(88I),g_normal) () - + [] member this.FromInt() = Assert.AreEqual(bignum.FromInt(2147483647), 2147483647N) @@ -359,12 +359,12 @@ type BigNumType() = Assert.AreEqual(bignum.FromInt(0), 0N) Assert.AreEqual(bignum.FromInt(88), 88N) () - + [] member this.One() = Assert.AreEqual(bignum.One,1N) () - + [] member this.Parse() = Assert.AreEqual(bignum.Parse("100"), 100N) @@ -372,7 +372,7 @@ type BigNumType() = Assert.AreEqual(bignum.Parse("0"), g_zero) Assert.AreEqual(bignum.Parse("88"), g_normal) () - + [] member this.PowN() = Assert.AreEqual(bignum.PowN(100N,2), 10000N) @@ -380,8 +380,8 @@ type BigNumType() = Assert.AreEqual(bignum.PowN(g_zero,2147483647), 0N) Assert.AreEqual(bignum.PowN(g_normal,0), 1N) () - - + + [] member this.Sign() = Assert.AreEqual(g_positive1.Sign, 1) @@ -389,9 +389,9 @@ type BigNumType() = Assert.AreEqual(g_zero.Sign, 0) Assert.AreEqual(g_normal.Sign, 1) () - - - + + + [] member this.ToBigInt() = Assert.AreEqual(bignum.ToBigInt(g_positive1), g_bigintpositive) @@ -399,9 +399,9 @@ type BigNumType() = Assert.AreEqual(bignum.ToBigInt(g_zero), 0I) Assert.AreEqual(bignum.ToBigInt(g_normal), 88I) () - - - + + + [] member this.ToDouble() = Assert.AreEqual(bignum.ToDouble(179769N*1000000000000000N), 1.79769E+20) @@ -413,8 +413,8 @@ type BigNumType() = Assert.AreEqual(double(0N),0.0) Assert.AreEqual(double(88N),88.0) () - - + + [] member this.ToInt32() = Assert.AreEqual(bignum.ToInt32(2147483647N), 2147483647) @@ -425,18 +425,18 @@ type BigNumType() = Assert.AreEqual(int32(-2147483648N), -2147483648) Assert.AreEqual(int32(0N), 0) Assert.AreEqual(int32(88N), 88) - - - + + + [] member this.Zero() = Assert.AreEqual(bignum.Zero,0N) () - - // operator methods + + // operator methods [] member this.test_op_Addition() = - + Assert.AreEqual(100N + 200N, 300N) Assert.AreEqual((-100N) + (-200N), -300N) Assert.AreEqual(g_positive1 + g_negative1, 0N) @@ -444,163 +444,163 @@ type BigNumType() = Assert.AreEqual(g_normal + g_normal, 176N) Assert.AreEqual(g_normal + g_normal, 176N) () - - - + + + [] member this.test_op_Division() = Assert.AreEqual(g_positive1 / g_positive1, 1N) Assert.AreEqual(-100N / 2N, -50N) Assert.AreEqual(g_zero / g_positive1, 0N) () - + [] member this.test_op_Equality() = - + Assert.IsTrue((g_positive1 = g_positive1)) Assert.IsTrue((g_negative1 = g_negative1)) Assert.IsTrue((g_zero = g_zero)) Assert.IsTrue((g_normal = g_normal)) () - + [] - member this.test_op_GreaterThan() = + member this.test_op_GreaterThan() = Assert.AreEqual((g_positive1 > g_positive2), true) Assert.AreEqual((g_negative1 > g_negative2), false) Assert.AreEqual((g_zero > g_zero), false) Assert.AreEqual((g_normal > g_normal), false) - - + + () [] - member this.test_op_GreaterThanOrEqual() = + member this.test_op_GreaterThanOrEqual() = Assert.AreEqual((g_positive1 >= g_positive2), true) - Assert.AreEqual((g_positive2 >= g_positive1), false) + Assert.AreEqual((g_positive2 >= g_positive1), false) Assert.AreEqual((g_negative1 >= g_negative1), true) Assert.AreEqual((0N >= g_zero), true) - + () - [] - member this.test_op_LessThan() = + [] + member this.test_op_LessThan() = Assert.AreEqual((g_positive1 < g_positive2), false) Assert.AreEqual((g_negative1 < g_negative3), false) Assert.AreEqual((0N < g_zero), false) - + () [] - member this.test_op_LessThanOrEqual() = + member this.test_op_LessThanOrEqual() = Assert.AreEqual((g_positive1 <= g_positive2), false) - Assert.AreEqual((g_positive2 <= g_positive1), true) + Assert.AreEqual((g_positive2 <= g_positive1), true) Assert.AreEqual((g_negative1 <= g_negative1), true) Assert.AreEqual((0N <= g_zero), true) - + () - + [] - member this.test_op_Multiply() = + member this.test_op_Multiply() = Assert.AreEqual(3N * 5N, 15N) Assert.AreEqual((-3N) * (-5N), 15N) Assert.AreEqual((-3N) * 5N, -15N) Assert.AreEqual(0N * 5N, 0N) - + () - + [] - member this.test_op_Range() = + member this.test_op_Range() = let resultPos = [0N .. 2N] - let seqPos = [0N; 1N; 2N] + let seqPos = [0N; 1N; 2N] verifySeqsEqual resultPos seqPos - - let resultNeg = [-2N .. 0N] - let seqNeg = [-2N; -1N; 0N] + + let resultNeg = [-2N .. 0N] + let seqNeg = [-2N; -1N; 0N] verifySeqsEqual resultNeg seqNeg - + let resultSmall = [0N ..5N] - let seqSmall = [0N; 1N; 2N; 3N; 4N; 5N] + let seqSmall = [0N; 1N; 2N; 3N; 4N; 5N] verifySeqsEqual resultSmall seqSmall - + () - - + + [] - member this.test_op_RangeStep() = + member this.test_op_RangeStep() = let resultPos = [0N .. 3N .. 6N] - let seqPos = [0N; 3N; 6N] + let seqPos = [0N; 3N; 6N] verifySeqsEqual resultPos seqPos - - let resultNeg = [-6N .. 3N .. 0N] - let seqNeg = [-6N; -3N; 0N] + + let resultNeg = [-6N .. 3N .. 0N] + let seqNeg = [-6N; -3N; 0N] verifySeqsEqual resultNeg seqNeg - + let resultSmall = [0N .. 3N .. 9N] - let seqSmall = [0N; 3N; 6N; 9N] + let seqSmall = [0N; 3N; 6N; 9N] verifySeqsEqual resultSmall seqSmall - + () - + [] - member this.test_op_Subtraction() = + member this.test_op_Subtraction() = Assert.AreEqual(g_positive1 - g_positive2,18N) Assert.AreEqual(g_negative1 - g_negative3,18N) Assert.AreEqual(0N-g_positive1, g_negative1) () - + [] - member this.test_op_UnaryNegation() = + member this.test_op_UnaryNegation() = Assert.AreEqual(-g_positive1, g_negative1) Assert.AreEqual(-g_negative1, g_positive1) - Assert.AreEqual(-0N,0N) - + Assert.AreEqual(-0N,0N) + () - + [] - member this.test_op_UnaryPlus() = + member this.test_op_UnaryPlus() = Assert.AreEqual(+g_positive1,g_positive1) Assert.AreEqual(+g_negative1,g_negative1) Assert.AreEqual(+0N, 0N) - + () - + // instance methods [] - member this.Denominator() = + member this.Denominator() = Assert.AreEqual(g_positive1.Denominator, 1I) Assert.AreEqual(g_negative1.Denominator, 1I) Assert.AreEqual(0N.Denominator, 1I) - - () - + + () + [] - member this.IsNegative() = + member this.IsNegative() = Assert.IsFalse(g_positive1.IsNegative) Assert.IsTrue(g_negative1.IsNegative) Assert.IsFalse( 0N.IsNegative) Assert.IsFalse(-0N.IsNegative) - - () - - + + () + + [] - member this.IsPositive() = + member this.IsPositive() = Assert.IsTrue(g_positive1.IsPositive) Assert.IsFalse(g_negative1.IsPositive) Assert.IsFalse( 0N.IsPositive) Assert.IsFalse(-0N.IsPositive) - - () - + + () + [] - member this.Numerator() = + member this.Numerator() = Assert.AreEqual(g_positive1.Numerator, g_bigintpositive) Assert.AreEqual(g_negative1.Numerator, g_bigintnegative) Assert.AreEqual(0N.Numerator, 0I) - - () - - - - - + + () + + + + + diff --git a/src/FSharpUnitTests/DenseMatrixTests.fs b/src/FSharpUnitTests/DenseMatrixTests.fs index b06107d9..992fefc8 100644 --- a/src/FSharpUnitTests/DenseMatrixTests.fs +++ b/src/FSharpUnitTests/DenseMatrixTests.fs @@ -13,39 +13,39 @@ module DenseMatrixTests = /// A large vector with increasingly large entries let largeM = new DenseMatrix( Array2D.init 100 100 (fun i j -> float i * 100.0 + float j) ) - - [] - let ``DenseMatrix.init`` () = + + [] + let ``DenseMatrix.init`` () = DenseMatrix.init 100 100 (fun i j -> float i * 100.0 + float j) |> should equal largeM - [] - let ``DenseMatrix.ofList`` () = + [] + let ``DenseMatrix.ofList`` () = DenseMatrix.ofList [[0.3;0.3];[0.3;0.3]] |> should equal smallM - [] - let ``DenseMatrix.ofSeq`` () = + [] + let ``DenseMatrix.ofSeq`` () = DenseMatrix.ofSeq (Seq.ofList [[0.3;0.3];[0.3;0.3]]) |> should equal smallM - [] - let ``DenseMatrix.ofArray2`` () = + [] + let ``DenseMatrix.ofArray2`` () = DenseMatrix.ofArray2 (Array2D.create 2 2 0.3) |> should equal smallM - [] - let ``DenseMatrix.initDense`` () = + [] + let ``DenseMatrix.initDense`` () = DenseMatrix.initDense 100 100 (seq { for i in 0 .. 99 do for j in 0 .. 99 -> (i,j, float i * 100.0 + float j)}) |> should equal largeM - [] - let ``DenseMatrix.constDiag`` () = + [] + let ``DenseMatrix.constDiag`` () = DenseMatrix.constDiag 100 2.0 |> should equal (2.0 * (DenseMatrix.Identity 100)) - [] - let ``DenseMatrix.diag`` () = + [] + let ``DenseMatrix.diag`` () = DenseMatrix.diag (new DenseVector(100, 2.0)) |> should equal (2.0 * (DenseMatrix.Identity 100)) - - [] - let ``DenseMatrix.init_row`` () = + + [] + let ``DenseMatrix.init_row`` () = DenseMatrix.initRow 100 100 (fun i -> (DenseVector.init 100 (fun j -> float i * 100.0 + float j))) |> should equal largeM - - [] - let ``DenseMatrix.init_col`` () = + + [] + let ``DenseMatrix.init_col`` () = DenseMatrix.initCol 100 100 (fun j -> (DenseVector.init 100 (fun i -> float i * 100.0 + float j))) |> should equal largeM diff --git a/src/FSharpUnitTests/DenseVectorTests.fs b/src/FSharpUnitTests/DenseVectorTests.fs index 346e55a6..e179c0a8 100644 --- a/src/FSharpUnitTests/DenseVectorTests.fs +++ b/src/FSharpUnitTests/DenseVectorTests.fs @@ -13,23 +13,23 @@ module DenseVectorTests = /// A large vector with increasingly large entries let largev = new DenseVector( Array.init 100 (fun i -> float i / 100.0) ) - - [] - let ``DenseVector.init`` () = + + [] + let ``DenseVector.init`` () = DenseVector.init 100 (fun i -> float i / 100.0) |> should equal largev - - [] - let ``DenseVector.ofList`` () = + + [] + let ``DenseVector.ofList`` () = DenseVector.ofList [ for i in 0 .. 99 -> float i / 100.0 ] |> should equal largev - - [] - let ``DenseVector.ofSeq`` () = + + [] + let ``DenseVector.ofSeq`` () = DenseVector.ofSeq (seq { for i in 0 .. 99 -> float i / 100.0 }) |> should equal largev - - [] - let ``DenseVector.rangef`` () = + + [] + let ``DenseVector.rangef`` () = DenseVector.rangef 0.0 0.01 0.99 |> should equal (new DenseVector( [| for i in 0 .. 99 -> 0.01 * float i |] ) ) - - [] - let ``DenseVector.range`` () = + + [] + let ``DenseVector.range`` () = DenseVector.range 0 99 |> should equal (new DenseVector( [| for i in 0 .. 99 -> float i |] ) ) diff --git a/src/FSharpUnitTests/FsUnit.fs b/src/FSharpUnitTests/FsUnit.fs index d5c8a7a7..a0a37243 100644 --- a/src/FSharpUnitTests/FsUnit.fs +++ b/src/FSharpUnitTests/FsUnit.fs @@ -9,7 +9,7 @@ let should (f : 'a -> #Constraint) x (y : obj) = | :? (unit -> unit) -> box (TestDelegate(y :?> unit -> unit)) | _ -> y Assert.That(y, c) - + let equal x = EqualConstraint(x) let equalWithin tolerance x = equal(x).Within tolerance diff --git a/src/FSharpUnitTests/MatrixTests.fs b/src/FSharpUnitTests/MatrixTests.fs index bea3a6c9..60526fe4 100644 --- a/src/FSharpUnitTests/MatrixTests.fs +++ b/src/FSharpUnitTests/MatrixTests.fs @@ -14,99 +14,99 @@ module MatrixTests = /// A large vector with increasingly large entries let largeM = new DenseMatrix( Array2D.init 100 100 (fun i j -> float i * 100.0 + float j) ) - - [] - let ``Matrix.fold`` () = + + [] + let ``Matrix.fold`` () = Matrix.fold (fun a b -> a - b) 0.0 smallM |> should equal -1.2 - [] - let ``Matrix.foldBack`` () = + [] + let ``Matrix.foldBack`` () = Matrix.foldBack (fun a b -> a - b) 0.0 smallM |> should equal 0.0 - [] - let ``Matrix.foldBackSummation`` () = + [] + let ``Matrix.foldBackSummation`` () = Matrix.foldBack( fun a b -> a + b) 0.0 failingFoldBackM |> should equal 6.0 - [] - let ``Matrix.foldi`` () = + [] + let ``Matrix.foldi`` () = Matrix.foldi (fun i j acc x -> acc + x + float (i+j)) 0.0 smallM |> should equal 5.2 - - [] - let ``Matrix.toArray2`` () = + + [] + let ``Matrix.toArray2`` () = Matrix.toArray2 smallM |> should array2_equal (Array2D.create 2 2 0.3) - - [] - let ``Matrix.forall`` () = + + [] + let ``Matrix.forall`` () = Matrix.forall (fun x -> x = 0.3) smallM |> should equal true - - [] - let ``Matrix.exists`` () = + + [] + let ``Matrix.exists`` () = Matrix.exists (fun x -> x = 0.5) smallM |> should equal false - - [] - let ``Matrix.foralli`` () = + + [] + let ``Matrix.foralli`` () = Matrix.foralli (fun i j x -> x = float i * 100.0 + float j) largeM |> should equal true - - [] - let ``Matrix.existsi`` () = + + [] + let ``Matrix.existsi`` () = Matrix.existsi (fun i j x -> x = float i * 100.0 + float j) largeM |> should equal true - - [] - let ``Matrix.map`` () = + + [] + let ``Matrix.map`` () = Matrix.map (fun x -> 2.0 * x) smallM |> should equal (2.0 * smallM) - - [] - let ``Matrix.mapi`` () = + + [] + let ``Matrix.mapi`` () = Matrix.mapi (fun i j x -> float i * 100.0 + float j + x) largeM |> should equal (2.0 * largeM) - - [] - let ``Matrix.mapCols`` () = + + [] + let ``Matrix.mapCols`` () = Matrix.mapCols (fun j col -> col.Add(float j)) smallM |> should (approximately_matrix_equal 14) (matrix [[0.3;1.3];[0.3;1.3]]) - - [] - let ``Matrix.mapRows`` () = + + [] + let ``Matrix.mapRows`` () = Matrix.mapRows (fun i row -> row.Add(float i)) smallM |> should (approximately_matrix_equal 14) (matrix [[0.3;0.3];[1.3;1.3]]) - - [] - let ``Matrix.inplaceAssign`` () = + + [] + let ``Matrix.inplaceAssign`` () = let N = smallM.Clone() Matrix.inplaceAssign (fun i j -> 0.0) N N |> should equal (0.0 * smallM) - - [] - let ``Matrix.inplaceMapi`` () = + + [] + let ``Matrix.inplaceMapi`` () = let N = largeM.Clone() Matrix.inplaceMapi (fun i j x -> 2.0 * (float i * 100.0 + float j) + x) N N |> should equal (3.0 * largeM) - - [] - let ``Matrix.nonZeroEntries`` () = + + [] + let ``Matrix.nonZeroEntries`` () = Seq.length (Matrix.nonZeroEntries smallM) |> should equal 4 - - [] - let ``Matrix.sum`` () = + + [] + let ``Matrix.sum`` () = Matrix.sum smallM |> should equal 1.2 - - [] - let ``Matrix.sumColsBy`` () = + + [] + let ``Matrix.sumColsBy`` () = Matrix.sumColsBy (fun j col -> col.[0] * col.[1]) (matrix [[1.0; 2.0]; [3.0; 4.0]]) |> should equal 11.0 - - [] - let ``Matrix.sumRowsBy`` () = + + [] + let ``Matrix.sumRowsBy`` () = Matrix.sumRowsBy (fun i row -> row.[0] * row.[1]) (matrix [[1.0; 2.0]; [3.0; 4.0]]) |> should equal 14.0 - [] - let ``Matrix.foldCol`` () = + [] + let ``Matrix.foldCol`` () = Matrix.foldCol (+) 0.0 largeM 0 |> should equal 495000.0 - - [] - let ``Matrix.foldRow`` () = + + [] + let ``Matrix.foldRow`` () = Matrix.foldRow (+) 0.0 largeM 0 |> should equal 4950.0 - [] - let ``Matrix.foldByCol`` () = + [] + let ``Matrix.foldByCol`` () = Matrix.foldByCol (+) 0.0 smallM |> should equal (DenseVector.ofList [0.6;0.6] :> Vector) - - [] - let ``Matrix.foldByRow`` () = + + [] + let ``Matrix.foldByRow`` () = Matrix.foldByRow (+) 0.0 smallM |> should equal (DenseVector.ofList [0.6;0.6] :> Vector) diff --git a/src/FSharpUnitTests/RandomVariableTests.fs b/src/FSharpUnitTests/RandomVariableTests.fs index 93305aab..3d4267a0 100644 --- a/src/FSharpUnitTests/RandomVariableTests.fs +++ b/src/FSharpUnitTests/RandomVariableTests.fs @@ -17,9 +17,9 @@ let sumOfTwoFairDices = randomVariable { [] let ``When creating two fair dices, then P(Sum of 2 dices = 7) should be 1/6``() = - sumOfTwoFairDices + sumOfTwoFairDices |> RandomVariable.filter ((=) 7) - |> RandomVariable.probability + |> RandomVariable.probability |> should equal (1N/6N) let fairCoinAndDice = randomVariable { @@ -29,23 +29,23 @@ let fairCoinAndDice = randomVariable { [] let ``When creating a fair coin and a fair dice, then P(Heads) should be 1/2``() = - fairCoinAndDice + fairCoinAndDice |> RandomVariable.filter (fun (_,c) -> c = Heads) - |> RandomVariable.probability + |> RandomVariable.probability |> should equal (1N/2N) [] let ``When creating a fair coin and a fair dice, then P(Heads and dice > 3) should be 1/4``() = - fairCoinAndDice + fairCoinAndDice |> RandomVariable.filter (fun (d,c) -> c = Heads && d > 3) - |> RandomVariable.probability + |> RandomVariable.probability |> should equal (1N/4N) // MontyHall Problem -// See Martin Erwig and Steve Kollmansberger's paper +// See Martin Erwig and Steve Kollmansberger's paper // "Functional Pearls: Probabilistic functional programming in Haskell" -type Outcome = +type Outcome = | Car | Goat @@ -53,18 +53,18 @@ let firstChoice = RandomVariable.toUniformDistribution [Car; Goat; Goat] let switch firstCoice = match firstCoice with - | Car -> + | Car -> // If you had the car and you switch ==> you lose since there are only goats left - RandomVariable.certainly Goat - | Goat -> + RandomVariable.certainly Goat + | Goat -> // If you had the goat, the host has to take out another goat ==> you win - RandomVariable.certainly Car - + RandomVariable.certainly Car + [] let ``When making the first choice in a MontyHall situation, the chances to win should be 1/3``() = - firstChoice + firstChoice |> RandomVariable.filter ((=) Car) - |> RandomVariable.probability + |> RandomVariable.probability |> should equal (1N/3N) let montyHallWithSwitch = randomVariable { @@ -75,5 +75,5 @@ let montyHallWithSwitch = randomVariable { let ``When switching in a MontyHall situation, the chances to win should be 2/3``() = montyHallWithSwitch |> RandomVariable.filter ((=) Car) - |> RandomVariable.probability + |> RandomVariable.probability |> should equal (2N/3N) \ No newline at end of file diff --git a/src/FSharpUnitTests/SparseMatrixTests.fs b/src/FSharpUnitTests/SparseMatrixTests.fs index 0ebfc195..3650d35a 100644 --- a/src/FSharpUnitTests/SparseMatrixTests.fs +++ b/src/FSharpUnitTests/SparseMatrixTests.fs @@ -3,23 +3,23 @@ open NUnit.Framework open FsUnit open MathNet.Numerics.LinearAlgebra.Generic -open MathNet.Numerics.LinearAlgebra.Double +open MathNet.Numerics.LinearAlgebra.Double /// Unit tests for the sparse matrix type. module SparseMatrixTests = /// A small uniform vector. let smallM = DenseMatrix.init 4 4 (fun i j -> if i = 1 && j = 2 then 1.0 else 0.0) :> Matrix - - [] + + [] let ``SparseMatrix.ofList`` () = (SparseMatrix.ofList 4 4 [(1,2,1.0)] :> Matrix) |> should equal smallM - [] + [] let ``SparseMatrix.ofSeq`` () = (SparseMatrix.ofSeq 4 4 (Seq.ofList [(1,2,1.0)]) :> Matrix) |> should equal smallM - [] + [] let ``SparseMatrix.constDiag`` () = SparseMatrix.constDiag 100 2.0 |> should equal (2.0 * (SparseMatrix.Identity 100)) diff --git a/src/FSharpUnitTests/SparseVectorTests.fs b/src/FSharpUnitTests/SparseVectorTests.fs index 9526695d..d6753894 100644 --- a/src/FSharpUnitTests/SparseVectorTests.fs +++ b/src/FSharpUnitTests/SparseVectorTests.fs @@ -10,12 +10,12 @@ module SparseVectorTests = /// A small uniform vector. let smallv = new DenseVector( [|0.0;0.3;0.0;0.0;0.0|] ) :> Vector - - [] - let ``SparseVector.ofList`` () = + + [] + let ``SparseVector.ofList`` () = (SparseVector.ofList 5 [ (1,0.3) ] :> Vector) |> should equal smallv - - [] - let ``SparseVector.ofSeq`` () = + + [] + let ``SparseVector.ofSeq`` () = (SparseVector.ofSeq 5 (List.toSeq [ (1,0.3) ]) :> Vector) |> should equal smallv diff --git a/src/FSharpUnitTests/Utilities.fs b/src/FSharpUnitTests/Utilities.fs index 77975580..29d06bc0 100644 --- a/src/FSharpUnitTests/Utilities.fs +++ b/src/FSharpUnitTests/Utilities.fs @@ -1,4 +1,4 @@ -// First version copied from the F# Power Pack +// First version copied from the F# Power Pack // https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack.Unittests/Utilities.fs namespace MathNet.Numerics.Tests @@ -7,9 +7,9 @@ open System open System.Collections.Generic [] -module Utilities = +module Utilities = let test msg b = Assert.IsTrue(b, "MiniTest '" + msg + "'") - let logMessage msg = + let logMessage msg = System.Console.WriteLine("LOG:" + msg) // System.Diagnostics.Trace.WriteLine("LOG:" + msg) let check msg v1 v2 = test msg (v1 = v2) @@ -18,85 +18,85 @@ module Utilities = let throws f = try f() |> ignore; false with e -> true let countEnumeratorsAndCheckedDisposedAtMostOnceAtEnd (seq: seq<'a>) = - let enumerator() = + let enumerator() = numActiveEnumerators := !numActiveEnumerators + 1; let disposed = ref false in let endReached = ref false in let ie = seq.GetEnumerator() in - { new System.Collections.Generic.IEnumerator<'a> with + { new System.Collections.Generic.IEnumerator<'a> with member x.Current = test "rvlrve0" (not !endReached); test "rvlrve1" (not !disposed); ie.Current - member x.Dispose() = + member x.Dispose() = test "rvlrve2" !endReached; test "rvlrve4" (not !disposed); numActiveEnumerators := !numActiveEnumerators - 1; disposed := true; - ie.Dispose() - interface System.Collections.IEnumerator with - member x.MoveNext() = + ie.Dispose() + interface System.Collections.IEnumerator with + member x.MoveNext() = test "rvlrve0" (not !endReached); test "rvlrve3" (not !disposed); endReached := not (ie.MoveNext()); not !endReached - member x.Current = + member x.Current = test "qrvlrve0" (not !endReached); test "qrvlrve1" (not !disposed); box ie.Current - member x.Reset() = + member x.Reset() = ie.Reset() } in - { new seq<'a> with - member x.GetEnumerator() = enumerator() - interface System.Collections.IEnumerable with + { new seq<'a> with + member x.GetEnumerator() = enumerator() + interface System.Collections.IEnumerable with member x.GetEnumerator() = (enumerator() :> _) } let countEnumeratorsAndCheckedDisposedAtMostOnce (seq: seq<'a>) = - let enumerator() = + let enumerator() = let disposed = ref false in let endReached = ref false in let ie = seq.GetEnumerator() in numActiveEnumerators := !numActiveEnumerators + 1; - { new System.Collections.Generic.IEnumerator<'a> with + { new System.Collections.Generic.IEnumerator<'a> with member x.Current = test "qrvlrve0" (not !endReached); test "qrvlrve1" (not !disposed); ie.Current - member x.Dispose() = + member x.Dispose() = test "qrvlrve4" (not !disposed); numActiveEnumerators := !numActiveEnumerators - 1; disposed := true; - ie.Dispose() - interface System.Collections.IEnumerator with - member x.MoveNext() = + ie.Dispose() + interface System.Collections.IEnumerator with + member x.MoveNext() = test "qrvlrve0" (not !endReached); test "qrvlrve3" (not !disposed); endReached := not (ie.MoveNext()); not !endReached - member x.Current = + member x.Current = test "qrvlrve0" (not !endReached); test "qrvlrve1" (not !disposed); box ie.Current - member x.Reset() = + member x.Reset() = ie.Reset() } in - { new seq<'a> with - member x.GetEnumerator() = enumerator() - interface System.Collections.IEnumerable with + { new seq<'a> with + member x.GetEnumerator() = enumerator() + interface System.Collections.IEnumerable with member x.GetEnumerator() = (enumerator() :> _) } // Verifies two sequences are equal (same length, equiv elements) let verifySeqsEqual seq1 seq2 = if Seq.length seq1 <> Seq.length seq2 then Assert.Fail() - + let zippedElements = Seq.zip seq1 seq2 - if zippedElements |> Seq.forall (fun (a, b) -> a = b) + if zippedElements |> Seq.forall (fun (a, b) -> a = b) then () else Assert.Fail() - + /// Check that the lamda throws an exception of the given type. Otherwise /// calls Assert.Fail() let private checkThrowsExn<'a when 'a :> exn> (f : unit -> unit) = diff --git a/src/FSharpUnitTests/VectorTests.fs b/src/FSharpUnitTests/VectorTests.fs index b0f0294b..b24f5d00 100644 --- a/src/FSharpUnitTests/VectorTests.fs +++ b/src/FSharpUnitTests/VectorTests.fs @@ -13,91 +13,91 @@ module VectorTests = /// A large vector with increasingly large entries let largev = new DenseVector(Array.init 100 (fun i -> float i / 100.0)) :> Vector - - [] - let ``Vector.toArray`` () = + + [] + let ``Vector.toArray`` () = Vector.toArray smallv |> should array_equal [|0.3;0.3;0.3;0.3;0.3|] - [] - let ``Vector.toList`` () = + [] + let ``Vector.toList`` () = Vector.toList smallv |> should equal [0.3;0.3;0.3;0.3;0.3] - - [] - let ``Vector.mapInPlace`` () = + + [] + let ``Vector.mapInPlace`` () = let w = smallv.Clone() Vector.mapInPlace (fun x -> 2.0 * x) w w |> should equal (2.0 * smallv) - - [] - let ``Vector.mapiInPlace`` () = + + [] + let ``Vector.mapiInPlace`` () = let w = largev.Clone() Vector.mapiInPlace (fun i x -> float i / 100.0) w w |> should equal (largev) - - [] - let ``Vector.addInPlace`` () = + + [] + let ``Vector.addInPlace`` () = let w = largev.Clone() Vector.addInPlace w largev w |> should equal (2.0 * largev) - - [] - let ``Vector.subInPlace`` () = + + [] + let ``Vector.subInPlace`` () = let w = largev.Clone() Vector.subInPlace w largev w |> should equal (0.0 * largev) - [] - let ``Vector.map`` () = + [] + let ``Vector.map`` () = Vector.map (fun x -> 2.0 * x) largev |> should equal (2.0 * largev) - - [] - let ``Vector.mapi`` () = + + [] + let ``Vector.mapi`` () = Vector.mapi (fun i x -> float i / 100.0) largev |> should equal largev - [] - let ``Vector.fold`` () = + [] + let ``Vector.fold`` () = Vector.fold (fun a b -> a - b) 0.0 smallv |> should equal -1.5 - - [] - let ``Vector.foldBack`` () = + + [] + let ``Vector.foldBack`` () = Vector.foldBack (fun a b -> a - b) 0.0 smallv |> should equal 0.0 - - [] - let ``Vector.foldi`` () = + + [] + let ``Vector.foldi`` () = Vector.foldi (fun i a b -> a + b) 0.0 smallv |> should equal 1.5 - - [] - let ``Vector.forall`` () = + + [] + let ``Vector.forall`` () = Vector.forall (fun x -> x = 0.3) smallv |> should equal true - - [] - let ``Vector.exists`` () = + + [] + let ``Vector.exists`` () = Vector.exists (fun x -> x = 0.3) smallv |> should equal true - - [] - let ``Vector.foralli`` () = + + [] + let ``Vector.foralli`` () = Vector.foralli (fun i x -> x = 0.3 && i < 5) smallv |> should equal true - - [] - let ``Vector.existsi`` () = + + [] + let ``Vector.existsi`` () = Vector.existsi (fun i x -> x = 0.3 && i = 2) smallv |> should equal true - - [] - let ``Vector.scan`` () = - Vector.scan (fun acc x -> acc + x) smallv |> should (approximately_vector_equal 14) (new DenseVector( [|0.3;0.6;0.9;1.2;1.5|] ) :> Vector) - - [] - let ``Vector.scanBack`` () = - Vector.scanBack (fun x acc -> acc + x) smallv |> should (approximately_vector_equal 14) (new DenseVector( [|1.5;1.2;0.9;0.6;0.3|] ) :> Vector) - - [] - let ``Vector.reduce`` () = + + [] + let ``Vector.scan`` () = + Vector.scan (fun acc x -> acc + x) smallv |> should (approximately_vector_equal 14) (new DenseVector( [|0.3;0.6;0.9;1.2;1.5|] ) :> Vector) + + [] + let ``Vector.scanBack`` () = + Vector.scanBack (fun x acc -> acc + x) smallv |> should (approximately_vector_equal 14) (new DenseVector( [|1.5;1.2;0.9;0.6;0.3|] ) :> Vector) + + [] + let ``Vector.reduce`` () = Vector.reduce (fun acc x -> acc ** x) smallv |> should (approximately_equal 14) 0.990295218585507 - - [] - let ``Vector.reduceBack`` () = + + [] + let ``Vector.reduceBack`` () = Vector.reduceBack (fun x acc -> x ** acc) smallv |> should (approximately_equal 14) 0.488911287726319 - - [] - let ``Vector.insert`` () = + + [] + let ``Vector.insert`` () = Vector.insert 2 0.5 smallv |> should (approximately_vector_equal 14) (new DenseVector ( [|0.3;0.3;0.5;0.3;0.3;0.3|] ) :> Vector)