public override void ReadFrom(GraphFactory factory, BinaryReader reader) { var lap = factory?.LinearAlgebraProvider; InputSize = reader.ReadInt32(); OutputSize = reader.ReadInt32(); // read the bias parameters var bias = FloatVector.ReadFrom(reader); if (Bias == null) { Bias = lap.CreateVector(bias); } else { Bias.Data = bias; } // read the weight parameters var weight = FloatMatrix.ReadFrom(reader); if (Weight == null) { Weight = lap.CreateMatrix(weight); } else { Weight.Data = weight; } if (_updater == null) { _updater = factory?.CreateWeightUpdater(Weight); } }
/// <summary> /// Creates random integers added together as feature vectors /// The input feature contains two features, one for each bit at that position /// The output feature contains a single feature: 1 or 0 if that bit is set in the result /// </summary> /// <param name="sampleCount">How many samples to generate</param> /// <param name="stochastic">True to generate random integers</param> /// <returns>A list of sequences</returns> public static IDataTable Addition(int sampleCount, bool stochastic) { Random rand = stochastic ? new Random() : new Random(0); var builder = DataTableBuilder.CreateTwoColumnMatrix(); for (var i = 0; i < sampleCount; i++) { // generate some random numbers (sized to prevent overflow) var a = rand.Next(int.MaxValue / 2); var b = rand.Next(int.MaxValue / 2); var a2 = _GetBitArray(a); var b2 = _GetBitArray(b); var r2 = _GetBitArray(a + b); var inputList = new FloatVector[r2.Length]; var outputList = new FloatVector[r2.Length]; for (int j = 0; j < r2.Length; j++) { inputList[j] = new FloatVector { Data = new[] { a2[j], b2[j] } }; outputList[j] = new FloatVector { Data = new[] { r2[j] } }; } builder.Add(FloatMatrix.Create(inputList), FloatMatrix.Create(outputList)); } return(builder.Build()); }
private Tuple <QuantityValues, FloatMatrix> getTimeAndAllValuesFor(DataRow row) { var allValuesForQuantity = row[_aggreationName] as IReadOnlyList <QuantityValues>; if (allValuesForQuantity == null || allValuesForQuantity.Count == 0) { return(emptyTimeAndValues()); } var firstQuantityValue = allValuesForQuantity.First(); if (firstQuantityValue.IsNull() || firstQuantityValue.Time.IsNull()) { return(emptyTimeAndValues()); } var matrix = new FloatMatrix(); var time = firstQuantityValue.Time; var length = time.Length; for (int i = 0; i < length; i++) { //values might have different lenght if using different time arrays. We base our arrays on the first time values var values = allValuesForQuantity.Where(qv => i < qv.Length) .Select(qv => qv.ValueAt(i)); matrix.AddValuesAndSort(values); } return(new Tuple <QuantityValues, FloatMatrix>(time, matrix)); }
public void WriteLine (FloatMatrix matrix, int z, MatrixLine mask) { int start = (z-matrix.rect.offset.z)*matrix.rect.size.x - matrix.rect.offset.x + offset; for (int x=0; x<length; x++) matrix.arr[start+x] = arr[x] * mask.arr[x]; //matrix[x+offset, z]; }
///<summary>Calculates the inverse of the matrix.</summary> ///<returns>the inverse of the matrix.</returns> ///<exception cref="NotPositiveDefiniteException">A is not positive definite.</exception> public FloatMatrix GetInverse() { Compute(); if (!ispd) { throw new NotPositiveDefiniteException(); } else { #if MANAGED FloatMatrix ret = FloatMatrix.CreateIdentity(order); ret = Solve(ret); return(ret); #else float[] inverse = new float[l.data.Length]; Array.Copy(l.data, inverse, l.data.Length); Lapack.Potri.Compute(Lapack.UpLo.Lower, order, inverse, order); FloatMatrix ret = new FloatMatrix(order, order); ret.data = inverse; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if (j > i) { ret.data[j * order + i] = ret.data[i * order + j]; } } } return(ret); #endif } }
public void NonSymmFactorTest() { FloatMatrix b = new FloatMatrix(3); b[0, 0] = 2; b[0, 1] = 1; b[0, 2] = 1; b[1, 0] = 1; b[1, 1] = 2; b[1, 2] = 0; b[2, 0] = 0; b[2, 1] = 0; b[2, 2] = 3; FloatCholeskyDecomp dcd = new FloatCholeskyDecomp(b); Assert.AreEqual(dcd.Factor[0, 0], 1.414, TOLERENCE); Assert.AreEqual(dcd.Factor[0, 1], 0.000, TOLERENCE); Assert.AreEqual(dcd.Factor[0, 2], 0.000, TOLERENCE); Assert.AreEqual(dcd.Factor[1, 0], 0.707, TOLERENCE); Assert.AreEqual(dcd.Factor[1, 1], 1.225, TOLERENCE); Assert.AreEqual(dcd.Factor[1, 2], 0.000, TOLERENCE); Assert.AreEqual(dcd.Factor[2, 0], 0.000, TOLERENCE); Assert.AreEqual(dcd.Factor[2, 1], 0.000, TOLERENCE); Assert.AreEqual(dcd.Factor[2, 2], 1.732, TOLERENCE); }
public void GetInverseSingularTest() { FloatMatrix a = new FloatMatrix(3, 3); FloatLUDecomp dlu = new FloatLUDecomp(a); dlu.GetInverse(); }
public void GetInverseNotPositiveDefiniteTest() { FloatMatrix a = new FloatMatrix(3, 3); FloatCholeskyDecomp dcd = new FloatCholeskyDecomp(a); dcd.GetInverse(); }
static FloatQRDecompTest() { FloatMatrix a = new FloatMatrix(3); a[0,0] = -1.0f; a[0,1] = 5.0f; a[0,2] = 6.0f; a[1,0] = 3.0f; a[1,1] = -6.0f; a[1,2] = 1.0f; a[2,0] = 6.0f; a[2,1] = 8.0f; a[2,2] = 9.0f; qr = new FloatQRDecomp(a); a = new FloatMatrix(2,3); a[0,0] = -1.0f; a[0,1] = 5.0f; a[0,2] = 6.0f; a[1,0] = 3.0f; a[1,1] = -6.0f; a[1,2] = 1.0f; wqr = new FloatQRDecomp(a); a = new FloatMatrix(3,2); a[0,0] = -1.0f; a[0,1] = 5.0f; a[1,0] = 3.0f; a[1,1] = -6.0f; a[2,0] = 6.0f; a[2,1] = 8.0f; lqr = new FloatQRDecomp(a); }
public ManyToOneDataTableAdaptor(ILinearAlgebraProvider lap, IDataTable dataTable) : base(lap, dataTable) { if (_dataColumnIndex.Count() > 1) { throw new NotImplementedException("Sequential datasets not supported with more than one input data column"); } _rowDepth = new int[dataTable.RowCount]; FloatMatrix inputMatrix = null; FloatVector outputVector = null; dataTable.ForEach((row, i) => { inputMatrix = row.GetField <FloatMatrix>(_dataColumnIndex[0]); outputVector = row.GetField <FloatVector>(_dataTargetIndex); _rowDepth[i] = inputMatrix.RowCount; if (inputMatrix.ColumnCount != outputVector.Size) { throw new ArgumentException("Rows between input and output data tables do not match"); } }); _inputSize = inputMatrix.ColumnCount; _outputSize = outputVector.Size; }
static FloatQRDecompTest() { FloatMatrix a = new FloatMatrix(3); a[0, 0] = -1.0f; a[0, 1] = 5.0f; a[0, 2] = 6.0f; a[1, 0] = 3.0f; a[1, 1] = -6.0f; a[1, 2] = 1.0f; a[2, 0] = 6.0f; a[2, 1] = 8.0f; a[2, 2] = 9.0f; qr = new FloatQRDecomp(a); a = new FloatMatrix(2, 3); a[0, 0] = -1.0f; a[0, 1] = 5.0f; a[0, 2] = 6.0f; a[1, 0] = 3.0f; a[1, 1] = -6.0f; a[1, 2] = 1.0f; wqr = new FloatQRDecomp(a); a = new FloatMatrix(3, 2); a[0, 0] = -1.0f; a[0, 1] = 5.0f; a[1, 0] = 3.0f; a[1, 1] = -6.0f; a[2, 0] = 6.0f; a[2, 1] = 8.0f; lqr = new FloatQRDecomp(a); }
public void Current() { var test = new FloatMatrix(new float[2, 2] { { 1f, 2f }, { 3f, 4f } }); IEnumerator enumerator = test.GetEnumerator(); bool movenextresult; movenextresult = enumerator.MoveNext(); Assert.IsTrue(movenextresult); Assert.AreEqual(enumerator.Current, test[0, 0]); movenextresult = enumerator.MoveNext(); Assert.IsTrue(movenextresult); Assert.AreEqual(enumerator.Current, test[1, 0]); movenextresult = enumerator.MoveNext(); Assert.IsTrue(movenextresult); Assert.AreEqual(enumerator.Current, test[0, 1]); movenextresult = enumerator.MoveNext(); Assert.IsTrue(movenextresult); Assert.AreEqual(enumerator.Current, test[1, 1]); movenextresult = enumerator.MoveNext(); Assert.IsFalse(movenextresult); }
/// <summary> /// One hot encodes the REBER strings /// </summary> /// <param name="strList">A list of REBER sequences</param> /// <returns>A data table with matrices to represent the sequences of vectors and their corresponding outputs</returns> public static IDataTable GetOneHot(IEnumerable <string> strList) { var strList2 = strList.ToList(); // build the following item table var following = new Dictionary <string, HashSet <int> >(); foreach (var str in strList2) { var sb = new StringBuilder(); string prev = null; foreach (var ch in str) { sb.Append(ch); var key = sb.ToString(); if (prev != null) { if (!following.TryGetValue(prev, out HashSet <int> temp)) { following.Add(prev, temp = new HashSet <int>()); } temp.Add(_ch[ch]); } prev = key; } } var builder = DataTableBuilder.CreateTwoColumnMatrix(); foreach (var str in strList2) { var inputList = new FloatVector[str.Length]; var outputList = new FloatVector[str.Length]; var sb = new StringBuilder(); for (var i = 0; i < str.Length; i++) { var ch = str[i]; sb.Append(ch); var input = new float[_ch.Count]; var output = new float[_ch.Count]; input[_ch[ch]] = 1f; if (following.TryGetValue(sb.ToString(), out HashSet <int> temp)) { foreach (var item in temp) { output[item] = 1f; } } inputList[i] = new FloatVector { Data = input }; outputList[i] = new FloatVector { Data = output }; } builder.Add(FloatMatrix.Create(inputList), FloatMatrix.Create(outputList)); } return(builder.Build()); }
public void Current() { FloatMatrix test = new FloatMatrix(new float[2, 2] { { 1f, 2f }, { 3f, 4f } }); IEnumerator enumerator = test.GetEnumerator(); bool movenextresult; movenextresult = enumerator.MoveNext(); Assert.IsTrue(movenextresult); Assert.AreEqual(enumerator.Current, test[0, 0]); movenextresult = enumerator.MoveNext(); Assert.IsTrue(movenextresult); Assert.AreEqual(enumerator.Current, test[1, 0]); movenextresult = enumerator.MoveNext(); Assert.IsTrue(movenextresult); Assert.AreEqual(enumerator.Current, test[0, 1]); movenextresult = enumerator.MoveNext(); Assert.IsTrue(movenextresult); Assert.AreEqual(enumerator.Current, test[1, 1]); movenextresult = enumerator.MoveNext(); Assert.IsFalse(movenextresult); }
/// <summary>Performs the QR factorization.</summary> protected override void InternalCompute() { int m = matrix.RowLength; int n = matrix.ColumnLength; #if MANAGED int minmn = m < n ? m : n; r_ = new FloatMatrix(matrix); // create a copy FloatVector[] u = new FloatVector[minmn]; for (int i = 0; i < minmn; i++) { u[i] = Householder.GenerateColumn(r_, i, m-1, i); Householder.UA(u[i], r_, i, m-1, i + 1, n-1); } q_ = FloatMatrix.CreateIdentity(m); for (int i = minmn - 1; i >= 0; i--) { Householder.UA(u[i], q_, i, m - 1, i, m - 1); } #else qr = new float[matrix.data.Length]; Array.Copy(matrix.data, qr, matrix.data.Length); jpvt = new int[n]; jpvt[0] = 1; Lapack.Geqp3.Compute(m, n, qr, m, jpvt, out tau); r_ = new FloatMatrix(m, n); // Populate R for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i <= j) { r_.data[j * m + i] = qr[(jpvt[j]-1) * m + i]; } else { r_.data[j * m + i] = 0.0f; } } } q_ = new FloatMatrix(m, m); for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { if (j < n) q_.data[j * m + i] = qr[j * m + i]; else q_.data[j * m + i] = 0.0f; } } if( m < n ){ Lapack.Orgqr.Compute(m, m, m, q_.data, m, tau); } else{ Lapack.Orgqr.Compute(m, m, n, q_.data, m, tau); } #endif for (int i = 0; i < m; i++) { if (q_[i, i] == 0) isFullRank = false; } }
static void ManyToOne() { var grammar = new SequenceGenerator(dictionarySize: 16, minSize: 3, maxSize: 6, noRepeat: true, isStochastic: false); var sequences = grammar.GenerateSequences().Take(1000).ToList(); var builder = BrightWireProvider.CreateDataTableBuilder(); builder.AddColumn(ColumnType.Matrix, "Sequence"); builder.AddColumn(ColumnType.Vector, "Summary"); foreach (var sequence in sequences) { var list = new List <FloatVector>(); var charSet = new HashSet <char>(); foreach (var ch in sequence) { charSet.Add(ch); list.Add(grammar.Encode(ch)); } var target = grammar.Encode(charSet.Select(ch2 => (ch2, 1f))); builder.Add(FloatMatrix.Create(list.ToArray()), target); } var data = builder.Build().Split(0); using (var lap = BrightWireProvider.CreateLinearAlgebra(false)) { var graph = new GraphFactory(lap); var errorMetric = graph.ErrorMetric.BinaryClassification; // create the property set var propertySet = graph.CurrentPropertySet .Use(graph.GradientDescent.RmsProp) .Use(graph.WeightInitialisation.Xavier) ; // create the engine var trainingData = graph.CreateDataSource(data.Training); var testData = trainingData.CloneWith(data.Test); var engine = graph.CreateTrainingEngine(trainingData, 0.03f, 8); // build the network const int HIDDEN_LAYER_SIZE = 128; var memory = new float[HIDDEN_LAYER_SIZE]; var network = graph.Connect(engine) .AddGru(memory) //.AddSimpleRecurrent(graph.ReluActivation(), memory) .AddFeedForward(engine.DataSource.OutputSize) .Add(graph.SigmoidActivation()) .AddBackpropagationThroughTime(errorMetric) ; engine.Train(20, testData, errorMetric); var networkGraph = engine.Graph; var executionEngine = graph.CreateEngine(networkGraph); var output = executionEngine.Execute(testData); Console.WriteLine(output.Where(o => o.Target != null).Average(o => o.CalculateError(errorMetric))); } }
public void IsSingularTest() { Assert.IsFalse(lu.IsSingular); FloatMatrix b = new FloatMatrix(3); FloatLUDecomp dlu = new FloatLUDecomp(b); Assert.IsTrue(dlu.IsSingular); }
public void CurrentException() { FloatMatrix test = new FloatMatrix(new float[2, 2] { { 1f, 2f }, { 3f, 4f } }); IEnumerator enumerator = test.GetEnumerator(); object value = enumerator.Current; }
private static void dscalColumn(FloatMatrix A, int Col, int Start, float z) { // A part of column Col of matrix A from row Start to end multiply by z for (int i = Start; i < A.RowLength; i++) { A[i, Col] = A[i, Col] * z; } }
///<summary>Constructor for SVD decomposition class.</summary> ///<param name="matrix">The matrix to decompose.</param> ///<exception cref="ArgumentNullException">matrix is null.</exception> public FloatSVDDecomp(IROMatrix <float> matrix) { if (matrix == null) { throw new System.ArgumentNullException("matrix cannot be null."); } this.matrix = new FloatMatrix(matrix); }
static FloatMatrix Relu(FloatMatrix m) { float[,] output = new float[m.x, m.y]; FloatMatrix.MatrixLoop((i, j) => { output[i, j] = m[i, j] > 0 ? m[i, j] : 0; }, m.x, m.y); return(output); }
/// <summary> /// Create a matrix /// </summary> /// <param name="lap"></param> /// <param name="matrix">Matrix to copy</param> /// <returns></returns> public static IMatrix CreateMatrix(this ILinearAlgebraProvider lap, FloatMatrix matrix) { var ret = lap.CreateMatrix(matrix.RowCount, matrix.ColumnCount, false); ret.Data = matrix; return(ret); //return lap.CreateMatrix(matrix.RowCount, matrix.ColumnCount, (i, j) => matrix.Row[i].Data[j]); }
static FloatMatrix Sigmoid(FloatMatrix m) { float[,] output = m; FloatMatrix.MatrixLoop((i, j) => { output[i, j] = 1 / (1 + UnityEngine.Mathf.Exp(-output[i, j])); }, m.x, m.y); return(output); }
protected override void Context() { sut = new StatisticalDataCalculator(); _floatMatrix = new FloatMatrix(); _floatMatrix.AddSortedValues(_values1); _floatMatrix.AddSortedValues(_values2); _floatMatrix.AddSortedValues(_values3); }
///<summary>Solves a system on linear equations, AX=B, where A is the factored matrixed.</summary> ///<param name="B">RHS side of the system.</param> ///<returns>the solution matrix, X.</returns> ///<exception cref="ArgumentNullException">B is null.</exception> ///<exception cref="SingularMatrixException">Ais singular.</exception> ///<exception cref="ArgumentException">The number of rows of A and B must be the same.</exception> public FloatMatrix Solve(IROFloatMatrix B) { if (B == null) { throw new System.ArgumentNullException("B cannot be null."); } Compute(); if (singular) { throw new SingularMatrixException(); } else { if (B.Rows != order) { throw new System.ArgumentException("Matrix row dimensions must agree."); } #if MANAGED // Copy right hand side with pivoting int nx = B.Columns; FloatMatrix X = Pivot(B); // Solve L*Y = B(piv,:) for (int k = 0; k < order; k++) { for (int i = k + 1; i < order; i++) { for (int j = 0; j < nx; j++) { X.data[i][j] -= X.data[k][j] * factor[i][k]; } } } // Solve U*X = Y; for (int k = order - 1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X.data[k][j] /= factor[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X.data[i][j] -= X.data[k][j] * factor[i][k]; } } } return(X); #else float[] rhs = FloatMatrix.ToLinearArray(B); Lapack.Getrs.Compute(Lapack.Transpose.NoTrans, order, B.Columns, factor, order, pivots, rhs, B.Rows); FloatMatrix ret = new FloatMatrix(order, B.Columns); ret.data = rhs; return(ret); #endif } }
public void WideQTest() { FloatMatrix Q = wqr.Q; Assert.AreEqual(System.Math.Abs(Q[0, 0]), 0.316, TOLERENCE); Assert.AreEqual(System.Math.Abs(Q[0, 1]), 0.949, TOLERENCE); Assert.AreEqual(System.Math.Abs(Q[1, 0]), 0.949, TOLERENCE); Assert.AreEqual(System.Math.Abs(Q[1, 1]), 0.316, TOLERENCE); }
///<summary>Constructor for SVD decomposition class.</summary> ///<param name="matrix">The matrix to decompose.</param> ///<param name="computeVectors">Whether to compute the singular vectors or not.</param> ///<exception cref="ArgumentNullException">matrix is null.</exception> public FloatSVDDecomp(IROFloatMatrix matrix, bool computeVectors) { if (matrix == null) { throw new System.ArgumentNullException("matrix cannot be null."); } this.matrix = new FloatMatrix(matrix); this.computeVectors = computeVectors; }
public static void AssertEqual(FloatMatrix m1, FloatMatrix m2, int maxDifference = 6) { Assert.AreEqual(m1.RowCount, m2.RowCount); Assert.AreEqual(m1.ColumnCount, m2.ColumnCount); for (var i = 0; i < m1.RowCount; i++) { AssertEqual(m1.Row[i], m2.Row[i], maxDifference); } }
///<summary>Solves a system on linear equations, AX=B, where A is the factored matrixed.</summary> ///<param name="B">RHS side of the system.</param> ///<returns>the solution matrix, X.</returns> ///<exception cref="ArgumentNullException">B is null.</exception> ///<exception cref="NotPositiveDefiniteException">A is not positive definite.</exception> ///<exception cref="ArgumentException">The number of rows of A and B must be the same.</exception> public FloatMatrix Solve(IROFloatMatrix B) { if (B == null) { throw new System.ArgumentNullException("B cannot be null."); } Compute(); if (!ispd) { throw new NotPositiveDefiniteException(); } else { if (B.Rows != order) { throw new System.ArgumentException("Matrix row dimensions must agree."); } #if MANAGED // Copy right hand side. int cols = B.Columns; FloatMatrix X = new FloatMatrix(B); for (int c = 0; c < cols; c++) { // Solve L*Y = B; for (int i = 0; i < order; i++) { float sum = B[i, c]; for (int k = i - 1; k >= 0; k--) { sum -= l.data[i][k] * X.data[k][c]; } X.data[i][c] = sum / l.data[i][i]; } // Solve L'*X = Y; for (int i = order - 1; i >= 0; i--) { float sum = X.data[i][c]; for (int k = i + 1; k < order; k++) { sum -= l.data[k][i] * X.data[k][c]; } X.data[i][c] = sum / l.data[i][i]; } } return(X); #else float[] rhs = FloatMatrix.ToLinearArray(B); Lapack.Potrs.Compute(Lapack.UpLo.Lower, order, B.Columns, l.data, order, rhs, B.Rows); FloatMatrix ret = new FloatMatrix(order, B.Columns); ret.data = rhs; return(ret); #endif } }
public void CtorDimensions() { FloatMatrix test = new FloatMatrix(2, 2); Assert.AreEqual(test.RowLength, 2); Assert.AreEqual(test.ColumnLength, 2); Assert.AreEqual(test[0, 0], 0); Assert.AreEqual(test[0, 1], 0); Assert.AreEqual(test[1, 0], 0); Assert.AreEqual(test[1, 1], 0); }
private static float ddot(FloatMatrix A, int Col1, int Col2, int Start) { float z = 0.0f; for (int i = Start; i < A.RowLength; i++) { z += A[i, Col2] * A[i, Col1]; } return(z); }
public void WideRTest() { FloatMatrix R = wqr.R; Assert.AreEqual(System.Math.Abs(R[0, 0]), 3.162, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[0, 1]), 7.273, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[0, 2]), 0.949, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[1, 0]), 0.000, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[1, 1]), 2.846, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[1, 2]), 6.008, TOLERENCE); }
public void CtorInitialValues() { FloatMatrix test = new FloatMatrix(2, 2, 1); Assert.AreEqual(test.RowLength, 2); Assert.AreEqual(test.ColumnLength, 2); Assert.AreEqual(test[0, 0], 1); Assert.AreEqual(test[0, 1], 1); Assert.AreEqual(test[1, 0], 1); Assert.AreEqual(test[1, 1], 1); }
private float[] calculateValueFor(FloatMatrix quantityResults, Func <float[], float> calculationMethodForSortedArray) { var result = new float[quantityResults.NumberOfRows]; for (int i = 0; i < result.Length; i++) { result[i] = calculationMethodForSortedArray(quantityResults.SortedValueAt(i)); } return(result); }
public void LongRTest() { FloatMatrix R = lqr.R; Assert.AreEqual(System.Math.Abs(R[0, 0]), 6.782, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[0, 1]), 3.686, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[1, 0]), 0.000, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[1, 1]), 10.555, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[2, 0]), 0.000, TOLERENCE); Assert.AreEqual(System.Math.Abs(R[2, 1]), 0.000, TOLERENCE); }
///<summary>Computes the algorithm.</summary> protected override void InternalCompute() { #if MANAGED l = new FloatMatrix(order); for (int j = 0; j < order; j++) { float[] rowj = l.data[j]; float d = 0.0f; for (int k = 0; k < j; k++) { float[] rowk = l.data[k]; float s = 0.0f; for (int i = 0; i < k; i++) { s += rowk[i] * rowj[i]; } rowj[k] = s = (matrix.data[j][k] - s) / l.data[k][k]; d = d + s * s; } d = matrix.data[j][j] - d; if (d <= 0.0) { ispd = false; return; } l.data[j][j] = (float)System.Math.Sqrt(System.Math.Max(d, 0.0)); for (int k = j + 1; k < order; k++) { l.data[j][k] = 0.0f; } } #else float[] factor = new float[matrix.data.Length]; Array.Copy(matrix.data, factor, matrix.data.Length); int status = Lapack.Potrf.Compute(Lapack.UpLo.Lower, order, factor, order); if (status != 0 ) { ispd = false; } l = new FloatMatrix(order); l.data = factor; for (int i = 0; i < order; i++) { for (int j = 0; j < order; j++) { if ( j > i) { l.data[j*order+i] = 0; } } } #endif }
static FloatCholeskyDecompTest() { FloatMatrix a = new FloatMatrix(3); a[0,0] = 2; a[0,1] = 1; a[0,2] = 0; a[1,0] = 1; a[1,1] = 2; a[1,2] = 0; a[2,0] = 0; a[2,1] = 0; a[2,2] = 3; cd = new FloatCholeskyDecomp(a); }
static FloatLUDecompTest() { FloatMatrix a = new FloatMatrix(3); a[0, 0] = -1; a[0, 1] = 5; a[0, 2] = 6; a[1, 0] = 3; a[1, 1] = -6; a[1, 2] = 1; a[2, 0] = 6; a[2, 1] = 8; a[2, 2] = 9; lu = new FloatLUDecomp(a); }
///<summary>Constructor for Cholesky decomposition class. The constructor performs the factorization of a symmetric positive ///definite matrax and the Cholesky factored matrix is accessible by the <c>Factor</c> property. The factor is the lower ///triangular factor.</summary> ///<param name="matrix">The matrix to factor.</param> ///<exception cref="ArgumentNullException">matrix is null.</exception> ///<exception cref="NotSquareMatrixException">matrix is not square.</exception> ///<remarks>This class only uses the lower triangle of the input matrix. It ignores the ///upper triangle.</remarks> public FloatCholeskyDecomp(IROFloatMatrix matrix) { if (matrix == null) { throw new System.ArgumentNullException("matrix cannot be null."); } if (matrix.Rows != matrix.Columns) { throw new NotSquareMatrixException("Matrix must be square."); } order = matrix.Columns; this.matrix = new FloatMatrix(matrix); }
public void CtorCopy() { FloatMatrix a = new FloatMatrix(2, 2); a[0, 0] = 1; a[0, 1] = 2; a[1, 0] = 3; a[1, 1] = 4; FloatMatrix b = new FloatMatrix(a); Assert.AreEqual(a.RowLength, b.RowLength); Assert.AreEqual(a.ColumnLength, b.ColumnLength); Assert.AreEqual(a[0, 0], a[0, 0]); Assert.AreEqual(a[0, 1], b[0, 1]); Assert.AreEqual(a[1, 0], b[1, 0]); Assert.AreEqual(a[1, 1], b[1, 1]); }
public void NonSymmFactorTest() { FloatMatrix b = new FloatMatrix(3); b[0,0] = 2; b[0,1] = 1; b[0,2] = 1; b[1,0] = 1; b[1,1] = 2; b[1,2] = 0; b[2,0] = 0; b[2,1] = 0; b[2,2] = 3; FloatCholeskyDecomp dcd = new FloatCholeskyDecomp(b); Assert.AreEqual(dcd.Factor[0,0],1.414,TOLERENCE); Assert.AreEqual(dcd.Factor[0,1],0.000,TOLERENCE); Assert.AreEqual(dcd.Factor[0,2],0.000,TOLERENCE); Assert.AreEqual(dcd.Factor[1,0],0.707,TOLERENCE); Assert.AreEqual(dcd.Factor[1,1],1.225,TOLERENCE); Assert.AreEqual(dcd.Factor[1,2],0.000,TOLERENCE); Assert.AreEqual(dcd.Factor[2,0],0.000,TOLERENCE); Assert.AreEqual(dcd.Factor[2,1],0.000,TOLERENCE); Assert.AreEqual(dcd.Factor[2,2],1.732,TOLERENCE); }
public void SetupTestCases() { a = new FloatMatrix(3); a[0,0] = 1.91f; a[0,1] = 9.82f; a[0,2] = 2.73f; a[1,0] = 8.64f; a[1,1] = 3.55f; a[1,2] = 7.46f; a[2,0] = 4.37f; a[2,1] = 6.28f; a[2,2] = 5.19f; svd = new FloatSVDDecomp(a, true); wa = new FloatMatrix(2,4); wa[0,0] = 1.91f; wa[0,1] = 9.82f; wa[0,2] = 2.73f; wa[0,3] = 8.64f; wa[1,0] = 3.55f; wa[1,1] = 7.46f; wa[1,2] = 4.37f; wa[1,3] = 6.28f; wsvd = new FloatSVDDecomp(wa, true); la = new FloatMatrix(4,2); la[0,0] = 1.91f; la[0,1] = 9.82f; la[1,0] = 2.73f; la[1,1] = 8.64f; la[2,0] = 3.55f; la[2,1] = 7.46f; la[3,0] = 4.37f; la[3,1] = 6.28f; lsvd = new FloatSVDDecomp(la, true); }
public void CtorCopyDouble() { FloatMatrix a = new FloatMatrix(2,2); a[0,0] = 1; a[0,1] = 2; a[1,0] = 3; a[1,1] = 4; ComplexFloatMatrix b = new ComplexFloatMatrix(a); Assert.AreEqual(a.RowLength, b.RowLength); Assert.AreEqual(a.ColumnLength, b.ColumnLength); Assert.AreEqual(a[0,0], b[0,0].Real); Assert.AreEqual(a[0,1], b[0,1].Real); Assert.AreEqual(a[1,0], b[1,0].Real); Assert.AreEqual(a[1,1], b[1,1].Real); Assert.AreEqual(0, b[0,0].Imag); Assert.AreEqual(0, b[0,1].Imag); Assert.AreEqual(0, b[1,0].Imag); Assert.AreEqual(0, b[1,1].Imag); }
public void CDLong() { FloatMatrix lm = new FloatMatrix(3,2); FloatCholeskyDecomp lcd = new FloatCholeskyDecomp(lm); }
///<summary>Constructor for QR decomposition class. The constructor performs the factorization and the upper and ///lower matrices are accessible by the <c>Q</c> and <c>R</c> properties.</summary> ///<param name="matrix">The matrix to factor.</param> ///<exception cref="ArgumentNullException">matrix is null.</exception> public FloatQRDecomp(IROFloatMatrix matrix) { if (matrix == null) throw new System.ArgumentNullException("matrix cannot be null."); this.matrix = new FloatMatrix(matrix); }
/// <summary>Finds the least squares solution of <c>A*X = B</c>, where <c>m >= n</c></summary> /// <param name="B">A matrix with as many rows as A and any number of columns.</param> /// <returns>X that minimizes the two norm of <c>Q*R*X-B</c>.</returns> /// <exception cref="ArgumentException">Matrix row dimensions must agree.</exception> /// <exception cref="InvalidOperationException">Matrix is rank deficient or <c>m < n</c>.</exception> public FloatMatrix Solve (IROFloatMatrix B) { if (B.Rows != matrix.RowLength) { throw new ArgumentException("Matrix row dimensions must agree."); } if (matrix.RowLength < matrix.ColumnLength) { throw new System.InvalidOperationException("A must have at lest as a many rows as columns."); } Compute(); if (!this.isFullRank) { throw new System.InvalidOperationException("Matrix is rank deficient."); } // Copy right hand side int m = matrix.RowLength; int n = matrix.ColumnLength; int nx = B.Columns; FloatMatrix ret = new FloatMatrix(n,nx); #if MANAGED FloatMatrix X = new FloatMatrix(B); // Compute Y = transpose(Q)*B float[] column = new float[q_.RowLength]; for (int j = 0; j < nx; j++) { for (int k = 0; k < m; k++) { column[k] = X.data[k][j]; } for (int i = 0; i < m; i++) { float s = 0; for (int k = 0; k < m; k++) { s += q_.data[k][i] * column[k]; } X.data[i][j] = s; } } // Solve R*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X.data[k][j] /= r_.data[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X.data[i][j] -= X.data[k][j]*r_.data[i][k]; } } } for( int i = 0; i < n; i++ ) { for( int j = 0; j < nx; j++ ) { ret.data[i][j] = X.data[i][j]; } } #else float[] c = FloatMatrix.ToLinearArray(B); Lapack.Ormqr.Compute(Lapack.Side.Left, Lapack.Transpose.Trans, m, nx, n, qr, m, tau, c, m); Blas.Trsm.Compute(Blas.Order.ColumnMajor, Blas.Side.Left, Blas.UpLo.Upper, Blas.Transpose.NoTrans, Blas.Diag.NonUnit, n, nx, 1, qr, m, c, m); for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < nx; j++) { ret.data[j*n+i] = c[j*m+(jpvt[i]-1)]; } } #endif return ret; }
/// <summary> /// Get the inverse of the Toeplitz matrix. /// </summary> /// <returns>The inverse matrix.</returns> /// <exception cref="SingularMatrixException"> /// The Toeplitz matrix or one of the the leading sub-matrices is singular. /// </exception> /// <remarks> /// The class implicitly decomposes the inverse Toeplitz matrix into a <b>UDL</b> factorisation /// using the Levinson algorithm, before using Trench's algorithm to complete /// the calculation of the inverse. /// <para> /// Trench's algorithm requires approximately <b>N</b> squared FLOPS, compared to <b>N</b> cubed FLOPS /// if we simply multiplied the <b>UDL</b> factors (<b>N</b> is the matrix order). /// </para> /// </remarks> public FloatMatrix GetInverse() { Compute(); if (m_IsSingular == true) { throw new SingularMatrixException("The Toeplitz matrix or one of the the leading sub-matrices is singular."); } FloatMatrix I = new FloatMatrix(m_Order); // the solution matrix float[] A = m_LowerTriangle[m_Order - 1]; float A1, A2, scale; #if MANAGED float[] current, previous; // references to rows in the solution int i, j, k, l; // setup the first row in wedge scale = m_Diagonal[m_Order - 1]; current = I.data[0]; for (i = 0, j = m_Order - 1; i < m_Order; i++, j--) { current[i] = scale * A[j]; } // calculate values in the rest of the wedge for (i = 1; i < (1 + m_Order) / 2; i++) { previous = current; current = I.data[i]; A1 = A[m_Order - i - 1]; A2 = A[i - 1]; for (j = i, k = i - 1, l = m_Order - i - 1; j < m_Order - i; j++, k++, l--) { current[j] = previous[k] + scale * (A1 * A[l] - A2 * A[k]); } } #else int i, j, k, l; // setup the first row in wedge scale = m_Diagonal[m_Order-1]; for (i = 0, j = m_Order - 1; i < m_Order; i++, j--) { I[0, i] = scale* A[j]; } // calculate values in the rest of the wedge for (i = 1; i < (1 + m_Order) / 2; i++) { A1 = A[m_Order - i - 1]; A2 = A[i - 1]; for (j = i, k = i - 1, l = m_Order - i - 1; j < m_Order - i; j++, k++, l--) { I[i, j] = I[i - 1, k] + scale * (A1 * A[l] - A2 * A[k]); } } #endif // this is symmetric matrix ... for (i = 0; i < (1 + m_Order) / 2; i++) { for (j = i; j < m_Order - i; j++) { I[j, i] = I[i, j]; } } // and a persymmetric matrix. for (i = 0, j = m_Order - 1; i < m_Order; i++, j--) { for (k = 0, l = m_Order - 1; k < j; k++, l--) { I[l, j] = I[i, k]; } } return I; }
public void Equals() { DoubleMatrix a = new DoubleMatrix(2,2,4); DoubleMatrix b = new DoubleMatrix(2,2,4); DoubleMatrix c = new DoubleMatrix(2,2); c[0,0] = 4; c[0,1] = 4; c[1,0] = 4; c[1,1] = 4; DoubleMatrix d = new DoubleMatrix(2,2,5); DoubleMatrix e = null; FloatMatrix f = new FloatMatrix(2,2,4); Assert.IsTrue(a.Equals(b)); Assert.IsTrue(b.Equals(a)); Assert.IsTrue(a.Equals(c)); Assert.IsTrue(b.Equals(c)); Assert.IsTrue(c.Equals(b)); Assert.IsTrue(c.Equals(a)); Assert.IsFalse(a.Equals(d)); Assert.IsFalse(d.Equals(b)); Assert.IsFalse(a.Equals(e)); Assert.IsFalse(a.Equals(f)); }
public void ImplictToFloatMatrix() { FloatMatrix a = new FloatMatrix(2,2); a[0,0] = 1; a[0,1] = 2; a[1,0] = 3; a[1,1] = 4; DoubleMatrix b = DoubleMatrix.ToDoubleMatrix(a); Assert.AreEqual(a.RowLength, b.RowLength); Assert.AreEqual(a.ColumnLength, b.ColumnLength); Assert.AreEqual(a[0,0], b[0,0]); Assert.AreEqual(a[0,1], b[0,1]); Assert.AreEqual(a[1,0], b[1,0]); Assert.AreEqual(a[1,1], b[1,1]); }
public void SolveMatrix() { FloatMatrix b = new FloatMatrix(3); b[0,0] = 2; b[0,1] = 2; b[0,2] = 2; b[1,0] = 13; b[1,1] = 13; b[1,2] = 13; b[2,0] = 25; b[2,1] = 25; b[2,2] = 25; FloatMatrix x = qr.Solve(b); Assert.AreEqual(x[0,0],2.965,TOLERENCE); Assert.AreEqual(x[0,1],2.965,TOLERENCE); Assert.AreEqual(x[0,2],2.965,TOLERENCE); Assert.AreEqual(x[1,0],-0.479,TOLERENCE); Assert.AreEqual(x[1,1],-0.479,TOLERENCE); Assert.AreEqual(x[1,2],-0.479,TOLERENCE); Assert.AreEqual(x[2,0],1.227,TOLERENCE); Assert.AreEqual(x[2,1],1.227,TOLERENCE); Assert.AreEqual(x[2,2],1.227,TOLERENCE); b = new FloatMatrix(3,2); b[0,0] = 2; b[0,1] = 2; b[1,0] = 13; b[1,1] = 13; b[2,0] = 25; b[2,1] = 25; x = qr.Solve(b); Assert.AreEqual(x[0,0],2.965,TOLERENCE); Assert.AreEqual(x[0,1],2.965,TOLERENCE); Assert.AreEqual(x[1,0],-0.479,TOLERENCE); Assert.AreEqual(x[1,1],-0.479,TOLERENCE); Assert.AreEqual(x[2,0],1.227,TOLERENCE); Assert.AreEqual(x[2,1],1.227,TOLERENCE); b = new FloatMatrix(3,4); b[0,0] = 2; b[0,1] = 2; b[0,2] = 2; b[0,3] = 2; b[1,0] = 13; b[1,1] = 13; b[1,2] = 13; b[1,3] = 13; b[2,0] = 25; b[2,1] = 25; b[2,2] = 25; b[2,3] = 25; x = qr.Solve(b); Assert.AreEqual(x[0,0],2.965,TOLERENCE); Assert.AreEqual(x[0,1],2.965,TOLERENCE); Assert.AreEqual(x[0,2],2.965,TOLERENCE); Assert.AreEqual(x[0,3],2.965,TOLERENCE); Assert.AreEqual(x[1,0],-0.479,TOLERENCE); Assert.AreEqual(x[1,1],-0.479,TOLERENCE); Assert.AreEqual(x[1,2],-0.479,TOLERENCE); Assert.AreEqual(x[1,3],-0.479,TOLERENCE); Assert.AreEqual(x[2,0],1.227,TOLERENCE); Assert.AreEqual(x[2,1],1.227,TOLERENCE); Assert.AreEqual(x[2,2],1.227,TOLERENCE); Assert.AreEqual(x[2,3],1.227,TOLERENCE); FloatMatrix A = new FloatMatrix(4,3); A[0,0] = -4.18f; A[0,1] = -5.011f; A[0,2] = -5.841f; A[1,0] = 4.986f; A[1,1] = 5.805f; A[1,2] = 6.624f; A[2,0] = 3.695f; A[2,1] = 3.687f; A[2,2] = 3.679f; A[3,0] = -5.489f; A[3,1] = -7.024f; A[3,2] = 8.56f; FloatQRDecomp qrd = new FloatQRDecomp(A); FloatMatrix B = new FloatMatrix(4,1); B[0,0] = 1; B[1,0] = 4; B[2,0] = 2; B[3,0] = 1; x = qrd.Solve(B); Assert.AreEqual(x[0,0],2.73529,TOLERENCE); Assert.AreEqual(x[1,0],-2.15822,TOLERENCE); Assert.AreEqual(x[2,0], 0.0998564,TOLERENCE); B = new FloatMatrix(4,3); B[0,0] = 1; B[1,0] = 4; B[2,0] = 2; B[3,0] = 1; B[0,1] = 1; B[1,1] = 4; B[2,1] = 2; B[3,1] = 1; B[0,2] = 1; B[1,2] = 4; B[2,2] = 2; B[3,2] = 1; x = qrd.Solve(B); Assert.AreEqual(x[0,0],2.73529,TOLERENCE); Assert.AreEqual(x[1,0],-2.15822,TOLERENCE); Assert.AreEqual(x[2,0], 0.0998564,TOLERENCE); Assert.AreEqual(x[0,1],2.73529,TOLERENCE); Assert.AreEqual(x[1,1],-2.15822,TOLERENCE); Assert.AreEqual(x[2,1], 0.0998564,TOLERENCE); Assert.AreEqual(x[0,2],2.73529,TOLERENCE); Assert.AreEqual(x[1,2],-2.15822,TOLERENCE); Assert.AreEqual(x[2,2], 0.0998564,TOLERENCE); }
///<summary> Constructor </summary> public FloatMatrixEnumerator (FloatMatrix matrix) { m=matrix; index=-1; length=m.RowLength*m.ColumnLength; }
public void ForEach() { FloatMatrix test = new FloatMatrix(new float[2, 2] { { 1f, 2f }, { 3f, 4f } }); foreach (float f in test) Assert.IsTrue(test.Contains(f)); }
/// <summary> /// Solve a symmetric square Toeplitz system with a right-side matrix. /// </summary> /// <param name="Y">The right-hand side of the system.</param> /// <returns>The solution matrix.</returns> /// <exception cref="ArgumentNullException"> /// Parameter <B>Y</B> is a null reference. /// </exception> /// <exception cref="RankException"> /// The number of rows in <B>Y</B> is not equal to the number of rows in the Toeplitz matrix. /// </exception> /// <exception cref="SingularMatrixException"> /// The Toeplitz matrix or one of the the leading sub-matrices is singular. /// </exception> /// <remarks> /// This member solves the linear system <B>TX</B> = <B>Y</B>, where <B>T</B> is /// a symmetric square Toeplitz matrix, <B>X</B> is the unknown solution matrix /// and <B>Y</B> is a known matrix. /// <para> /// The class implicitly decomposes the inverse Toeplitz matrix into a <b>UDL</b> factorisation /// using the Levinson algorithm, and then calculates the solution matrix. /// </para> /// </remarks> public FloatMatrix Solve(IROFloatMatrix Y) { FloatMatrix X; // check parameters if (Y == null) { throw new System.ArgumentNullException("Y"); } else if (m_Order != Y.Columns) { throw new RankException("The numer of rows in Y is not equal to the number of rows in the Toeplitz matrix."); } Compute(); if (m_IsSingular == true) { throw new SingularMatrixException("The Toeplitz matrix or one of the the leading sub-matrices is singular."); } int M = Y.Rows; int i, j, l, m; // index/loop variables float[] Inner; // inner product float[] G; // scaling constant float[] A; // reference to current order coefficients float scalar; // allocate memory for solution X = new FloatMatrix(m_Order, M); Inner = new float[M]; G = new float[M]; // setup zero order solution scalar = 1.0f / m_LeftColumn[0]; for (m = 0; m < M; m++) { #if MANAGED X.data[0][m] = scalar * Y[0,m]; #else X.data[m*m_Order] = scalar * Y[0,m]; #endif } // solve systems of increasing order for (i = 1; i < m_Order; i++) { // calculate inner product for (m = 0; m < M; m++) { #if MANAGED Inner[m] = Y[i,m]; #else Inner[m] = Y[i,m]; #endif } for (j = 0, l = i; j < i; j++, l--) { scalar = m_LeftColumn[l]; for (m = 0; m < M; m++) { #if MANAGED Inner[m] -= scalar * X.data[j][m]; #else Inner[m] -= scalar * X.data[m*m_Order+j]; #endif } } // get the current predictor coefficients row A = m_LowerTriangle[i]; // update the solution matrix for (m = 0; m < M; m++) { G[m] = m_Diagonal[i] * Inner[m]; } for (j = 0; j <= i; j++) { scalar = A[j]; for (m = 0; m < M; m++) { #if MANAGED X.data[j][m] += scalar * G[m]; #else X.data[m*m_Order+j] += scalar * G[m]; #endif } } } return X; }
public void CDWide() { FloatMatrix wm = new FloatMatrix(2,3); FloatCholeskyDecomp wcd = new FloatCholeskyDecomp(wm); }
/// <summary> /// Invert a symmetric square Toeplitz matrix. /// </summary> /// <param name="T">The left-most column of the symmetric Toeplitz matrix.</param> /// <returns>The inverse matrix.</returns> /// <exception cref="ArgumentNullException"> /// <B>T</B> is a null reference. /// </exception> /// <exception cref="RankException"> /// The length of <B>T</B> must be greater than zero. /// </exception> /// <exception cref="SingularMatrixException"> /// The Toeplitz matrix or one of the the leading sub-matrices is singular. /// </exception> /// <remarks> /// This static member combines the <b>UDL</b> decomposition and Trench's algorithm into a /// single algorithm. When compared to the non-static member it requires minimal data storage /// and suffers from no speed penalty. /// <para> /// Trench's algorithm requires <b>N</b> squared FLOPS, compared to <b>N</b> cubed FLOPS /// if we simply solved a linear Toeplitz system with a right-side identity matrix (<b>N</b> is the matrix order). /// </para> /// </remarks> public static FloatMatrix Inverse(IROFloatVector T) { FloatMatrix X; // check parameters if (T == null) { throw new System.ArgumentNullException("T"); } else if (T.Length < 1) { throw new System.RankException("The length of T must be greater than zero."); } else if (T.Length == 1) { X = new FloatMatrix(1); X[0, 0] = 1.0f / T[0]; } else { int N = T.Length; float f, g; int i, j, l, k, m, n; X = new FloatMatrix(N); // calculate the predictor coefficients FloatVector Y = FloatSymmetricLevinson.YuleWalker(T); // calculate gamma f = T[0]; for (i = 1, j = 0; i < N; i++, j++) { f += T[i] * Y[j]; } g = 1.0f / f; // calculate first row of inverse X[0, 0] = g; for (i = 1, j = 0; i < N; i++, j++) { X[0, i] = g * Y[j]; } // calculate successive rows of upper wedge for (i = 0, j = 1, k = N - 2; i < N / 2; i++, j++, k--) { for (l = j, m = i, n = N - 1 - j; l < N - j; l++, m++, n--) { X[j, l] = X[i, m] + g * (Y[i] * Y[m] - Y[k] * Y[n]); } } // this is symmetric matrix ... for (i = 0; i <= N / 2; i++) { for (j = i + 1; j < N - i; j++) { X[j, i] = X[i, j]; } } // and a persymmetric matrix. for (i = 0, j = N - 1; i < N; i++, j--) { for (k = 0, l = N - 1; k < j; k++, l--) { X[l, j] = X[i, k]; } } } return X; }
/// <summary> /// Solve a symmetric square Toeplitz system with a right-side matrix. /// </summary> /// <param name="T">The left-most column of the Toeplitz matrix.</param> /// <param name="Y">The right-side matrix of the system.</param> /// <returns>The solution matrix.</returns> /// <exception cref="ArgumentNullException"> /// <B>T</B> and/or <B>Y</B> are null references /// </exception> /// <exception cref="RankException"> /// The length of <B>T</B> does not match the number of rows in <B>Y</B>. /// </exception> /// <exception cref="SingularMatrixException"> /// The Toeplitz matrix or one of the the leading sub-matrices is singular. /// </exception> /// <remarks> /// This method solves the linear system <B>AX</B> = <B>Y</B>. Where /// <B>T</B> is a symmetric square Toeplitz matrix, <B>X</B> is an unknown /// matrix and <B>Y</B> is a known matrix. /// <para> /// This static member combines the <b>UDL</b> decomposition and the calculation of the solution into a /// single algorithm. When compared to the non-static member it requires minimal data storage /// and suffers from no speed penalty. /// </para> /// </remarks> public static FloatMatrix Solve(IROFloatVector T, IROFloatMatrix Y) { FloatMatrix X; // check parameters if (T == null) { throw new System.ArgumentNullException("T"); } else if (Y == null) { throw new System.ArgumentNullException("Y"); } else if (T.Length != Y.Columns) { throw new RankException("The length of T and Y are not equal."); } else { // allocate memory int N = T.Length; int M = Y.Rows; X = new FloatMatrix(N, M); // solution matrix FloatVector Z = new FloatVector(N); // temporary storage vector float e; // prediction error int i, j, l, m; // setup zero order solution e = T[0]; if (e == 0.0f) { throw new SingularMatrixException("The Toeplitz matrix or one of the the leading sub-matrices is singular."); } for (m = 0; m < M; m++) { X[0, m] = Y[0, m] / T[0]; } if (N > 1) { FloatVector a = new FloatVector(N - 1); // prediction coefficients float p; // reflection coefficient float inner; // inner product float k; // calculate solution for successive orders for (i = 1; i < N; i++) { // calculate first inner product inner = T[i]; for (j = 0, l = i - 1; j < i - 1; j++, l--) { inner += a[j] * T[l]; } // update predictor coefficients p = -(inner / e); for (j = 0, l = i - 2; j < i - 1; j++, l--) { Z[j] = a[j] + p * a[l]; } // copy vector for (j = 0; j < i - 1; j++) { a[j] = Z[j]; } a[i - 1] = p; e *= (1.0f - p * p); if (e == 0.0f) { throw new SingularMatrixException("The Toeplitz matrix or one of the the leading sub-matrices is singular."); } // update the solution matrix for (m = 0; m < M; m++) { // retrieve a copy of solution column for (j = 0; j < i; j++) { Z[j] = X[j, m]; } // calculate second inner product inner = Y[i, m]; for (j = 0, l = i; j < i; j++, l--) { inner -= Z[j] * T[l]; } // update solution vector k = inner / e; for (j = 0, l = i - 1; j < i; j++, l--) { Z[j] = Z[j] + k * a[l]; } Z[j] = k; // store solution column in matrix for (j = 0; j <= i; j++) { X[j, m] = Z[j]; } } } } } return X; }
public void CurrentException2() { FloatMatrix test = new FloatMatrix(new float[2, 2] { { 1f, 2f }, { 3f, 4f } }); IEnumerator enumerator = test.GetEnumerator(); enumerator.MoveNext(); enumerator.MoveNext(); enumerator.MoveNext(); enumerator.MoveNext(); enumerator.MoveNext(); object value = enumerator.Current; }
public void ImplictToFloatMatrix() { FloatMatrix a = new FloatMatrix(2,2); a[0,0] = 1; a[0,1] = 2; a[1,0] = 3; a[1,1] = 4; ComplexFloatMatrix b = ComplexFloatMatrix.ToComplexFloatMatrix(a); Assert.AreEqual(a.RowLength, b.RowLength); Assert.AreEqual(a.ColumnLength, b.ColumnLength); Assert.AreEqual(a[0,0], b[0,0].Real); Assert.AreEqual(a[0,1], b[0,1].Real); Assert.AreEqual(a[1,0], b[1,0].Real); Assert.AreEqual(a[1,1], b[1,1].Real); }
/// <summary> /// Get a copy of the Toeplitz matrix. /// </summary> public FloatMatrix GetMatrix() { int i, j; // allocate memory for the matrix FloatMatrix tm = new FloatMatrix(m_Order); #if MANAGED // fill top row float[] top = tm.data[0]; Array.Copy(m_LeftColumn.data, 0, top, 0, m_Order); if (m_Order > 1) { // fill bottom row (reverse order) float[] bottom = tm.data[m_Order - 1]; for (i = 0, j = m_Order - 1; i < m_Order; i++, j--) { bottom[i] = m_LeftColumn[j]; } // fill rows in-between for (i = 1, j = m_Order - 1; j > 1; i++) { Array.Copy(top, 0, tm.data[i], i, j--); Array.Copy(bottom, j, tm.data[i], 0, i); } } #else if (m_Order > 1) { float[] top = new float[m_Order]; Array.Copy(m_LeftColumn.data, 0, top, 0, m_Order); tm.SetRow(0, top); // fill bottom row (reverse order) float[] bottom = new float[m_Order]; for (i = 0, j = m_Order - 1; i < m_Order; i++, j--) { bottom[i] = m_LeftColumn[j]; } // fill rows in-between for (i = 1, j = m_Order - 1 ; j > 0; i++) { float[] temp = new float[m_Order]; Array.Copy(top, 0, temp, i, j--); Array.Copy(bottom, j, temp, 0, i); tm.SetRow(i, temp); } } else { Array.Copy(m_LeftColumn.data, 0, tm.data, 0, m_Order); } #endif return tm; }
public void Equals() { ComplexFloatMatrix a = new ComplexFloatMatrix(2,2,new ComplexFloat(4,4)); ComplexFloatMatrix b = new ComplexFloatMatrix(2,2,new ComplexFloat(4,4)); ComplexFloatMatrix c = new ComplexFloatMatrix(2,2); c[0,0] = new ComplexFloat(4,4); c[0,1] = new ComplexFloat(4,4); c[1,0] = new ComplexFloat(4,4); c[1,1] = new ComplexFloat(4,4); ComplexFloatMatrix d = new ComplexFloatMatrix(2,2,5); ComplexFloatMatrix e = null; FloatMatrix f = new FloatMatrix(2,2,4); Assert.IsTrue(a.Equals(b)); Assert.IsTrue(b.Equals(a)); Assert.IsTrue(a.Equals(c)); Assert.IsTrue(b.Equals(c)); Assert.IsTrue(c.Equals(b)); Assert.IsTrue(c.Equals(a)); Assert.IsFalse(a.Equals(d)); Assert.IsFalse(d.Equals(b)); Assert.IsFalse(a.Equals(e)); Assert.IsFalse(a.Equals(f)); }