public void TestVelocityOnPlane() { Frisbee.SimulationState st = new Frisbee.SimulationState { VX = 1, VY = 1, Theta = Math.PI / 4 }; Matrix<double> transformation = new SparseMatrix(new [,] { {st.CosTheta, st.SinTheta*st.SinPhi, -st.SinTheta*st.CosPhi}, {0, st.CosPhi, st.SinPhi}, {st.SinTheta, -st.CosTheta*st.SinPhi, st.CosTheta*st.CosPhi} }); SparseVector c3 = new SparseVector(transformation.Row(2)); SparseVector velocity = new SparseVector(new[] { st.VX, st.VY, st.VZ }); double velocityMagnitude = velocity.Norm(2); double velocityC3 = velocity.DotProduct(c3); Vector<double> vp = velocity.Subtract(c3.Multiply(velocityC3)); double vpMagnitude = vp.Norm(2); }
/// <summary> /// Learn the current input. /// </summary> /// <param name="input"></param> /// <exception cref="HtmRuleException"></exception> public override void Learn(SparseMatrix input) { // Limitation due to HTM v1.x design (cannot learn after inference without modifying ouput vector structure) if (!IsLearning) // TODOlater allow learning after training when using FixedMaxSize nodes throw new HtmRuleException("Cannot learn after any other mode than learning", this); // Ignore blank input //TODOlater? treat any input with identical values for *all* components as blank? //TODOlater use DetectBlanks/DetectBlanksMode properties if (input.NonZerosCount == 0) { return; } // Check matrix size if (CoincidencesFrequencies.Count > 0 && (CoincidencesFrequencies.Keys.First().RowCount != input.RowCount || CoincidencesFrequencies.Keys.First().ColumnCount != input.ColumnCount)) throw new HtmRuleException("Cannot learn varying sized inputs", this); SparseMatrix existingCoincidence = FindClosestCoincidence(input); if (existingCoincidence != null) CoincidencesFrequencies[existingCoincidence] += 1; else if (CoincidencesFrequencies.Count < MaxOutputSize) CoincidencesFrequencies[input] = 1; }
public void ErrorWhenLearningAfterInferenceMode() { var node = new SpatialNode2DGaussian(); var mat = new SparseMatrix(4, 4, 4.0); var learnAfterInferFails = false; var learnAfterTBInferFails = false; node.Learn(mat); node.Infer(mat); try { node.Learn(mat); } catch (HtmRuleException e) { learnAfterInferFails = true; Debug.WriteLine(e.Message); } node.TimeInfer(mat); try { node.Learn(mat); } catch (HtmRuleException e) { learnAfterTBInferFails = true; Debug.WriteLine(e.Message); } Assert.IsTrue(learnAfterInferFails); Assert.IsTrue(learnAfterTBInferFails); }
public void SolveWideMatrixThrowsArgumentException() { var matrix = new SparseMatrix(2, 3); var input = new DenseVector(2); var solver = new MlkBiCgStab(); Assert.Throws<ArgumentException>(() => matrix.SolveIterative(input, solver)); }
public void SolveLongMatrixThrowsArgumentException() { var matrix = new SparseMatrix(3, 2); var input = new DenseVector(3); var solver = new GpBiCg(); Assert.Throws<ArgumentException>(() => matrix.SolveIterative(input, solver)); }
public void SolveLongMatrixThrowsArgumentException() { var matrix = new SparseMatrix(3, 2); var input = new DenseVector(3); var solver = new MlkBiCgStab(); Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException); }
public void SparseMatrixSubMatrixMethodWorks() { var matrix = new SparseMatrix(10, 10, 1.0); var sub = matrix.SubMatrix(8, 2, 0, 2); Assert.AreEqual(2, sub.RowCount); Assert.AreEqual(2, sub.ColumnCount); }
public void SolveWideMatrixThrowsArgumentException() { var matrix = new SparseMatrix(2, 3); var input = new DenseVector(2); var solver = new TFQMR(); Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException); }
/// <summary> /// Create unit matrix. /// </summary> /// <param name="size">Matrix size.</param> /// <returns>New unit matrix.</returns> internal SparseMatrix CreateUnitMatrix(int size) { var matrix = new SparseMatrix(size); for (var i = 0; i < size; i++) { matrix[i, i] = 2; } return matrix; }
/// <summary> /// Check the result. /// </summary> /// <param name="preconditioner">Specific preconditioner.</param> /// <param name="matrix">Source matrix.</param> /// <param name="vector">Initial vector.</param> /// <param name="result">Result vector.</param> protected override void CheckResult(IPreconditioner<double> preconditioner, SparseMatrix matrix, Vector<double> vector, Vector<double> result) { Assert.AreEqual(typeof (UnitPreconditioner<double>), preconditioner.GetType(), "#01"); // Unit preconditioner is doing nothing. Vector and result should be equal for (var i = 0; i < vector.Count; i++) { Assert.IsTrue(vector[i] == result[i], "#02-" + i); } }
public void SparseMatrixSubtractsCorrectlyFromZeroComponents() { var m1 = new SparseMatrix(new double[,] { { 1, 0, 0, 1 }, { 1, 1, 0, 1 } }); var m2 = new SparseMatrix(new double[,] { { 1, 1, 1, 0 }, { 1, 0, 0, 1 } }); var diff1 = new SparseMatrix(new double[,] { { 0, -1, -1, 1 }, { 0, 1, 0, 0 } }); var diff2 = new SparseMatrix(new double[,] { { 0, 1, 1, -1 }, { 0, -1, 0, 0 } }); Assert.AreEqual(diff2, m2 - m1); Assert.AreEqual(diff1, m1 - m2); }
public void SparseMatrixAddsCorrectlyToZeroComponents() { var m1 = new SparseMatrix(1, 3); var m2 = new SparseMatrix(new double[,] { { 0, 1, 1 } }); var sum1 = m1 + m2; var sum2 = m2 + m1; Assert.AreEqual(m2, sum2); Assert.AreEqual(m2, sum1); }
/// <summary> /// Check the result. /// </summary> /// <param name="preconditioner">Specific preconditioner.</param> /// <param name="matrix">Source matrix.</param> /// <param name="vector">Initial vector.</param> /// <param name="result">Result vector.</param> protected override void CheckResult(IPreconditioner<double> preconditioner, SparseMatrix matrix, Vector<double> vector, Vector<double> result) { Assert.AreEqual(typeof (DiagonalPreconditioner), preconditioner.GetType(), "#01"); // Compute M * result = product // compare vector and product. Should be equal var product = new DenseVector(result.Count); matrix.Multiply(result, product); for (var i = 0; i < product.Count; i++) { Assert.IsTrue(vector[i].AlmostEqualNumbersBetween(product[i], -Epsilon.Magnitude()), "#02-" + i); } }
public void BuildRatingMatrix(List<Movie> movies) { ratingMatrix = InitMatrix(movies); for (int i = 0; i < movies.Count; i++) { Dictionary<int, int> ratings = movies[i].Ratings; foreach (var rating in ratings) { ratingMatrix[i, userMap[rating.Key]] = rating.Value; } movieMap.Add(movies[i].Id, i); } }
public static SparseMatrix Extract(this SparseMatrix matrix, int[] rows, int[] columns) { var extractedMatrix = new SparseMatrix(rows.Length, columns.Length); for (int c = 0; c < columns.Length; c++) { for (int r = 0; r < rows.Length; r++) { extractedMatrix[r, c] = matrix[rows[r], columns[c]]; } } return extractedMatrix; }
/// <summary> /// Do Flash inference for the given input /// </summary> /// <param name="input"></param> /// <returns></returns> public override Vector Infer(SparseMatrix input) { State = NodeState.FlashInference; if (LearnedCoincidences.Length == 0) { return new SparseVector(1); } var output = new DenseVector(LearnedCoincidences.Length); for (int i = 0; i < LearnedCoincidences.Length; ++i) { var diff = LearnedCoincidences[i] - input; var norm = diff.FrobeniusNorm(); output[i] = Math.Exp(-(norm * norm) / (2 * SquaredSigma)); } return output; }
/// <summary> /// List indexing is 2000x faster than Matrix.Row() or enumeration. /// </summary> public static void SpeedOfGetRow() { SparseMatrix myMatrix = new SparseMatrix(1000, 1000); SparseVector myVector = SparseVector.OfVector(Vector.Build.Random(1000)); myVector.CoerceZero(1.8); for (int i = 0; i < 1000; i++) { myMatrix.SetRow(i, myVector); } List<Vector<double>> myList = new List<Vector<double>>(myMatrix.EnumerateRows()); Utils.StartTimer(); for (int repeat = 0; repeat < 10; repeat++) { for (int i = 0; i < 1000; i++) { double foo = myMatrix.Row(i)[0]; } } Utils.StopTimer(); Utils.StartTimer(); for (int repeat = 0; repeat < 10; repeat++) { foreach(var row in myMatrix.EnumerateRowsIndexed()) { double foo = row.Item2[0]; } } Utils.StopTimer(); Utils.StartTimer(); for (int repeat = 0; repeat < 10; repeat++) { for (int i = 0; i < 1000; i++) { double foo = myList[i][0]; } } Utils.StopTimer(); }
public SimpleComponentFinder(Matrix degree, Matrix adjacency, TokenIndexMap tokens, int clusterCount) { //var spectralDecomposition = dependencies.Evd (); //var smallestEigenvector = spectralDecomposition.EigenVectors.Row (1); //ComponentCount = Math.Min (smallestEigenvector.Count, clusterCount); var laplacian = degree - adjacency; var fiedlerVector = laplacian.Evd().EigenVectors.Row(1); clusterCount = (int)Math.Min(fiedlerVector.Count(d => d != 0d) / 2.0d, clusterCount); var offset = (fiedlerVector.Minimum() < 0d ? (-1.0d * fiedlerVector.Minimum()) + EPSILON : EPSILON); var shifted = fiedlerVector.Add(offset); var sortedElements = shifted.Select((e, i) => new KeyValuePair <int, double> (i, e)) .OrderByDescending(kv => kv.Value).Reverse().ToList(); var breaks = NaturalBreaks((from kv in sortedElements select kv.Value).ToList(), clusterCount); var firstGroup = sortedElements.Where(e => e.Value < breaks.ElementAt(0)).Select(e => tokens [e.Key]).ToList(); var secondGroup = sortedElements.Where(e => e.Value < breaks.ElementAt(1) && (!firstGroup.Contains(tokens[e.Key]))) .Select(e => tokens [e.Key]).ToList(); var thirdGroup = sortedElements.Where(e => (!firstGroup.Contains(tokens[e.Key])) && (!secondGroup.Contains(tokens[e.Key]))) .Select(e => tokens [e.Key]).ToList(); }
public SparseMatrix GetMeanMatrix() { SparseMatrix meanMatix = new SparseMatrix(ratingMatrix.RowCount, ratingMatrix.ColumnCount); double totalMean = ratingMatrix.SumMatrix() * (1 / (double)ratingMatrix.NonZerosCount); SparseVector movieMeans = ratingMatrix.MeanRowVector(); SparseVector userMeans = ratingMatrix.MeanColumnVector(); for (int i = 0; i < meanMatix.RowCount; i++) { for (int j = 0; j < meanMatix.ColumnCount; j++) { double cell = ratingMatrix[i, j]; if (cell > 0 || cell < 0) meanMatix[i, j] = ratingMatrix[i, j] - movieMeans[i] - userMeans[j] + totalMean; } } return meanMatix; }
public void CanLearnAndInfer1OnRecognizedSubInputs_5By4Layer0_5Coverage() { uint maxoutputsize = 5; var coverage = 0.5; var clone = false; uint layerheight = 5; uint layerwidth = 4; int inputtolayerratio = 2; var layer = new Spatial2DLayer(SpatialLayerType.Gaussian, layerheight, layerwidth, coverage, clone, maxoutputsize); var input1 = new SparseMatrix((int)layerheight * inputtolayerratio, (int)layerwidth * inputtolayerratio, 1.0); var input2 = 2 * input1; // layer.Learn(input1); layer.Learn(input2); var infer2 = layer.Infer(input2); var infer1 = layer.Infer(input1); var input3 = (SparseMatrix)new SparseMatrix((int)layerwidth * inputtolayerratio, (int)layerwidth * inputtolayerratio, 1.0) .Stack(new SparseMatrix((int)(layerheight - layerwidth) * inputtolayerratio, (int)layerwidth * inputtolayerratio, 3.0)); var infer3 = layer.Infer(input3); // foreach (var infer in new SparseMatrix[] { infer1, infer2, infer3 }) { for (int row = 0; row < layerheight; row++) { for (int col = 0; col < layerwidth * layer.MaxNodeOutputSize; col += layer.MaxNodeOutputSize) { var subInput = infer.SubMatrix(row, 1, col, layer.MaxNodeOutputSize); if (infer.Equals(infer3) && row >= layerheight - 2 && row < layerheight) for (int i = 0; i < subInput.ColumnCount; i++) Assert.IsTrue(subInput[0, i] < 0.1); else Assert.IsTrue(subInput[0, 0] == 1.0 || subInput[0, 1] == 1.0); } } } }
public void CanAddSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); var sum1 = m1 + m2; var sum2 = m2 + m1; Assert.IsTrue(sum1.Equals(m2)); Assert.IsTrue(sum1.Equals(sum2)); Matrix<double> sparseResult = new SparseMatrix(1, 3); sparseResult.Add(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); sparseResult.Add(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); m1.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = Matrix<double>.Build.SparseOfArray(new double[,] { { 0, 1, 1 } }); sparseResult.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(2*sum1)); Matrix<double> denseResult = new DenseMatrix(1, 3); denseResult.Add(m2, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); denseResult = Matrix<double>.Build.DenseOfArray(new double[,] { { 0, 1, 1 } }); denseResult.Add(m1, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); var m3 = Matrix<double>.Build.DenseOfArray(new double[,] { { 0, 1, 1 } }); var sum3 = m1 + m3; var sum4 = m3 + m1; Assert.IsTrue(sum3.Equals(m3)); Assert.IsTrue(sum3.Equals(sum4)); }
public void SparseMatrixIndexedEnumeratorWorks() { var cols = 7; var rows = 7; var matrix = new SparseMatrix(rows, cols, new double[] { 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, /**/2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 34.5104995998366, 3.30253638788279, 2.7461515689052E-06, 2.7461515689052E-06, /**/2.7461515689052E-06, 2.7461515689052E-06, 3.30253638788279, 255, 3.30253638788279, 2.7461515689052E-06, 2.37450036851675E-06, /**/2.7461515689052E-06, 2.7461515689052E-06, 24.4026090935093, 255, 24.4026090935093, 2.7461515689052E-06, 2.7461515689052E-06, /**/2.7461515689052E-06, 2.7461515689052E-06, 3.30253638788279, 34.5104995998366, 3.30253638788279, 2.7461515689052E-06, 2.37450036851675E-06, /**/2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, /**/2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06, 6.62979636198309E-06, 2.7461515689052E-06, 2.7461515689052E-06, 2.7461515689052E-06 }); var normalized = matrix.Normalize(1.0, 2.7461515689052E-06); // var count = 0; foreach (var el in matrix.IndexedEnumerator()) { count++; } var count2 = 0; foreach (var el in normalized.IndexedEnumerator()) { count2++; } // Assert.AreEqual(cols * rows, count); Assert.AreEqual(cols * rows, count2); }
public BasicFluid2D(int max_x, int max_y) { if (max_x != max_y) throw new ArgumentException(); this.max_x = max_x; this.max_y = max_y; u_x = new double[max_x + 1, max_y]; u_y = new double[max_x, max_y + 1]; cells = new GridCell[max_x, max_y]; A = new SparseMatrix(max_x * max_y); for (int i = 0; i < max_x; i++) for (int j = 0; j < max_y; j++) { A[i * max_x + j, i * max_x + j] = 2 + (i == 0 || i + 1 == max_x ? 1 : 0) + (j == 0 || j + 1 == max_y ? 1 : 0); if (i > 0) A[(i - 1) * max_x + j, i * max_x + j] = A[i * max_x + j, (i - 1) * max_x + j] = -1; if (j > 0) A[i * max_x + j - 1, i * max_x + j] = A[i * max_x + j, i * max_x + j - 1] = -1; if (i < max_x - 1) A[(i + 1) * max_x + j, i * max_x + j] = A[i * max_x + j, (i + 1) * max_x + j] = -1; if (j < max_y - 1) A[i * max_x + j + 1, i * max_x + j] = A[i * max_x + j, i * max_x + j + 1] = -1; cells[i, j] = new GridCell(); //cells[i, j].Adiag = (short)(2 + (i == 0 || i + 1 == max_x ? 1 : 0) + (j == 0 || j + 1 == max_y ? 1 : 0)); //cells[i, j].Aplusi = (short)(i + 1 < max_x ? -1 : 0); //cells[i, j].Aplusj = (short)(j + 1 < max_y ? -1 : 0); if (new Vector2(i - max_x / 2, j - max_y / 2).LengthSquared < max_x * max_y / 16) cells[i, j].ImplicitSurface = 5; } using (TextWriter tw = new StreamWriter("output.txt")) tw.WriteLine(A.ToMatrixString(900, 900)); solver = new MathNet.Numerics.LinearAlgebra.Double.Solvers.Preconditioners.IncompleteLU(); solver.Initialize(A); p = new DenseVector(max_x * max_y); d = new DenseVector(max_x * max_y); }
/// <summary> /// Creates a new <see cref="SparseMatrix"/> and inserts the given row at the given index. /// </summary> /// <param name="rowIndex">The index of where to insert the row.</param> /// <param name="row">The row to insert.</param> /// <returns>A new <see cref="SparseMatrix"/> with the inserted column.</returns> /// <exception cref="ArgumentNullException">If <paramref name="row"/> is <see langword="null" />. </exception> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="rowIndex"/> is < zero or > the number of rows.</exception> /// <exception cref="ArgumentException">If the size of <paramref name="row"/> != the number of columns.</exception> public override Matrix<double> InsertRow(int rowIndex, Vector<double> row) { if (row == null) { throw new ArgumentNullException("row"); } if (rowIndex < 0 || rowIndex > RowCount) { throw new ArgumentOutOfRangeException("rowIndex"); } if (row.Count != ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension, "row"); } var result = new SparseMatrix(RowCount + 1, ColumnCount); for (var i = 0; i < rowIndex; i++) { result.At(i, i, At(i, i)); } result.SetRow(rowIndex, row); for (var i = rowIndex + 1; i < result.RowCount; i++) { result.At(i, i - 1, At(i - 1, i - 1)); } return result; }
/// <summary> /// Creates a new <see cref="SparseMatrix"/> and inserts the given column at the given index. /// </summary> /// <param name="columnIndex">The index of where to insert the column.</param> /// <param name="column">The column to insert.</param> /// <returns>A new <see cref="SparseMatrix"/> with the inserted column.</returns> /// <exception cref="ArgumentNullException">If <paramref name="column "/> is <see langword="null" />. </exception> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="columnIndex"/> is < zero or > the number of columns.</exception> /// <exception cref="ArgumentException">If the size of <paramref name="column"/> != the number of rows.</exception> public override Matrix<double> InsertColumn(int columnIndex, Vector<double> column) { if (column == null) { throw new ArgumentNullException("column"); } if (columnIndex < 0 || columnIndex > ColumnCount) { throw new ArgumentOutOfRangeException("columnIndex"); } if (column.Count != RowCount) { throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension, "column"); } var result = new SparseMatrix(RowCount, ColumnCount + 1); for (var i = 0; i < columnIndex; i++) { result.SetColumn(i, Column(i)); } result.SetColumn(columnIndex, column); for (var i = columnIndex + 1; i < ColumnCount + 1; i++) { result.SetColumn(i, Column(i - 1)); } return result; }
/// <summary> /// Outer product of two vectors /// </summary> /// <param name="u">First vector</param> /// <param name="v">Second vector</param> /// <returns>Matrix M[i,j] = u[i]*v[j] </returns> /// <exception cref="ArgumentNullException">If the u vector is <see langword="null" />.</exception> /// <exception cref="ArgumentNullException">If the v vector is <see langword="null" />.</exception> public static Matrix<double> OuterProduct(SparseVector u, SparseVector v) { if (u == null) { throw new ArgumentNullException("u"); } if (v == null) { throw new ArgumentNullException("v"); } var matrix = new SparseMatrix(u.Count, v.Count); for (var i = 0; i < u._storage.ValueCount; i++) { for (var j = 0; j < v._storage.ValueCount; j++) { matrix.At(i, j, u._storage.Values[i] * v._storage.Values[j]); } } return matrix; }
static void Main(string[] args) { Stopwatch timer = new Stopwatch(); /*Console.WriteLine(Stopwatch.Frequency); * Console.WriteLine(Stopwatch.IsHighResolution); * Console.WriteLine(Stopwatch.GetTimestamp()); * DateTime now = new DateTime(); * long totalMS = 0; * long totalTicks = 0; * long[] msHistory = new long[10000]; * long[] ticksHistory = new long[10000]; * for (int i = 0; i < 10000; ++i) * { * timer.Restart(); * now = DateTime.Now; * timer.Stop(); * totalMS += timer.ElapsedMilliseconds; * totalTicks += timer.ElapsedTicks; * msHistory[i] = timer.ElapsedMilliseconds; * ticksHistory[i] = timer.ElapsedTicks; * System.Threading.Thread.Sleep(20); * } * Console.WriteLine(Stopwatch.GetTimestamp()); * Console.WriteLine("{0} - {1}", msHistory.Average(), ticksHistory.Average()); * Console.ReadLine();*/ //TestMatrix(); //Console.ReadLine(); var matrix = Matrix.Deserialize(@"E:\Work Programming\Insight Program Files\Neural Network\AreaStats2.mtx"); lin.Matrix <double> matrix2 = null; var compacted = new double[matrix.Count]; Array.Copy(matrix._compactedMatrix, compacted, matrix.Count); int numCols = matrix.NumCols; int numRows = matrix.NumRows; var storage = lin.Storage.SparseCompressedRowMatrixStorage <double> .OfRowArrays(matrix.ToArray()); Console.WriteLine("Compacted Initialization:"); long matrixMS = 0; long matrixTicks = 0; long matrix2MS = 0; long matrix2Ticks = 0; for (int i = 0; i < 1024; ++i) { matrix = null; timer.Restart(); matrix = new Matrix(compacted, numCols); timer.Stop(); matrixMS += timer.ElapsedMilliseconds; matrixTicks += timer.ElapsedTicks; matrix2 = null; timer.Restart(); matrix2 = new dbl.SparseMatrix(storage); timer.Stop(); matrix2MS += timer.ElapsedMilliseconds; matrix2Ticks += timer.ElapsedTicks; } Console.WriteLine("\tMatrix1: {0} - {1}", matrixMS, matrixTicks); Console.WriteLine("\tMatrix2: {0} - {1}", matrix2MS, matrix2Ticks); matrixMS = 0; matrixTicks = 0; matrix2MS = 0; matrix2Ticks = 0; Console.WriteLine("Transposition: "); for (int i = 0; i < 1024; ++i) { timer.Restart(); matrix = matrix.T(); timer.Stop(); matrixMS += timer.ElapsedMilliseconds; matrixTicks += timer.ElapsedTicks; timer.Restart(); matrix2 = matrix2.Transpose(); timer.Stop(); matrix2MS += timer.ElapsedMilliseconds; matrix2Ticks += timer.ElapsedTicks; } Console.WriteLine("\tMatrix1: {0} - {1}", matrixMS, matrixTicks); Console.WriteLine("\tMatrix2: {0} - {1}", matrix2MS, matrix2Ticks); matrixMS = 0; matrixTicks = 0; matrix2MS = 0; matrix2Ticks = 0; Console.ReadLine(); /*long loadFileSumMS = 0; * long loadFileSumTicks = 0; * long serializeFileSumMS = 0; * long serializeFileSumTicks = 0; * * Matrix matrix = null; * * Console.WriteLine("Human-readable:"); * * for (int i = 0; i < 1024; ++i) * { * timer.Restart(); * matrix = Matrix.LoadFile(@"E:\Insight Temp Files\Lists\AreaStats.mtx"); * timer.Stop(); * loadFileSumMS += timer.ElapsedMilliseconds; * loadFileSumTicks += timer.ElapsedTicks; * timer.Restart(); * matrix.SerializeToFile(@"E:\Insight Program Files\Neural Network", "AreaStats"); * timer.Stop(); * matrix = null; * serializeFileSumMS += timer.ElapsedMilliseconds; * serializeFileSumTicks += timer.ElapsedTicks; * } * * Console.WriteLine("\tLoad File: {0} - {1}", loadFileSumMS / 1024, loadFileSumTicks / 1024); * Console.WriteLine("\tSerialize to File: {0} - {1}", serializeFileSumMS / 1024, serializeFileSumTicks/ 1024); * GC.Collect(); * loadFileSumMS = 0; * loadFileSumTicks = 0; * serializeFileSumMS = 0; * serializeFileSumTicks = 0; * * Console.WriteLine(); * Console.WriteLine("Binary format:"); * matrix = Matrix.LoadFile(@"E:\Insight Temp Files\Lists\AreaStats.mtx"); * * for (int i = 0; i < 1024; ++i) * { * timer.Restart(); * matrix.SerializeToFile2(@"E:\Insight Program Files\Neural Network", "AreaStats2"); * timer.Stop(); * serializeFileSumMS += timer.ElapsedMilliseconds; * serializeFileSumTicks += timer.ElapsedTicks; * matrix = null; * timer.Restart(); * matrix = Matrix.LoadFile2(@"E:\Insight Program Files\Neural Network\AreaStats2.mtx"); * timer.Stop(); * loadFileSumMS += timer.ElapsedMilliseconds; * loadFileSumTicks += timer.ElapsedTicks; * } * * Console.WriteLine("\tLoad File: {0} - {1}", loadFileSumMS / 1024, loadFileSumTicks / 1024); * Console.WriteLine("\tSerialize to File: {0} - {1}", serializeFileSumMS / 1024, serializeFileSumTicks / 1024); * * Console.ReadLine();*/ }
public void SolveWideMatrixThrowsArgumentException() { var matrix = new SparseMatrix(2, 3); var input = new DenseVector(2); var solver = new TFQMR(); Assert.Throws<ArgumentException>(() => solver.Solve(matrix, input)); }
public void SolvePoissonMatrixAndBackMultiply() { // Create the matrix var matrix = new SparseMatrix(100); // Assemble the matrix. We assume we're solving the Poisson equation // on a rectangular 10 x 10 grid const int GridSize = 10; // The pattern is: // 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0 for (var i = 0; i < matrix.RowCount; i++) { // Insert the first set of -1's if (i > (GridSize - 1)) { matrix[i, i - GridSize] = -1; } // Insert the second set of -1's if (i > 0) { matrix[i, i - 1] = -1; } // Insert the centerline values matrix[i, i] = 4; // Insert the first trailing set of -1's if (i < matrix.RowCount - 1) { matrix[i, i + 1] = -1; } // Insert the second trailing set of -1's if (i < matrix.RowCount - GridSize) { matrix[i, i + GridSize] = -1; } } // Create the y vector var y = DenseVector.Create(matrix.RowCount, i => 1); // Create an iteration monitor which will keep track of iterative convergence var monitor = new Iterator<double>(new IIterationStopCriterium<double>[] { new IterationCountStopCriterium<double>(MaximumIterations), new ResidualStopCriterium(ConvergenceBoundary), new DivergenceStopCriterium(), new FailureStopCriterium() }); var solver = new TFQMR(monitor); // Solve equation Ax = y var x = solver.Solve(matrix, y); // Now compare the results Assert.IsNotNull(x, "#02"); Assert.AreEqual(y.Count, x.Count, "#03"); // Back multiply the vector var z = matrix.Multiply(x); // Check that the solution converged Assert.IsTrue(monitor.HasConverged, "#04"); // Now compare the vectors for (var i = 0; i < y.Count; i++) { Assert.IsTrue(Math.Abs(y[i] - z[i]).IsSmaller(ConvergenceBoundary, 1), "#05-" + i); } }
/// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfDiagonalVector(int rows, int columns, Vector<double> diagonal) { var m = new SparseMatrix(rows, columns); m.SetDiagonal(diagonal); return m; }
/// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfDiagonalVector(Vector<double> diagonal) { var m = new SparseMatrix(diagonal.Count, diagonal.Count); m.SetDiagonal(diagonal); return m; }
/// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfDiagonalArray(int rows, int columns, double[] diagonal) { var m = new SparseMatrix(rows, columns); m.SetDiagonal(diagonal); return m; }