/// <summary> /// 連立線形方程式を作成する /// </summary> /// <param name="count">未知数の数</param> /// <param name="maxNonZeroCount">0でない要素の最大数</param> public LinerEquations(int count, int maxNonZeroCount) { // 係数行列・未知数・右辺ベクトルを初期化 this.A = new SparseMatrix(count, maxNonZeroCount); this.x = new double[count]; this.b = new double[count]; }
public CCSMatrix(SparseMatrix matrix, bool transponse) { // get number of non-zero elements m = matrix.ColumnSize; n = matrix.RowSize; int nnz = 0; foreach (List<SparseMatrix.Element> col in matrix.Columns) nnz += col.Count; // create temp arrays rowIndex = new int[nnz]; colIndex = new int[n + 1]; values = new double[nnz]; // copy values to arrays int index = 0; int index2 = 0; colIndex[0] = 0; foreach (List<SparseMatrix.Element> row in matrix.Rows) { foreach (SparseMatrix.Element e in row) { rowIndex[index] = e.j; values[index] = e.value; index++; } colIndex[++index2] = index; } }
public void WriteMatrix(ref SparseMatrix sparseMatrix, string modelName) { string fileName = Path.GetFileNameWithoutExtension(modelName); string path = GetPath() + fileName + ".matrix"; WriteMatrix(sparseMatrix, path); }
public SparseMatrix BuildLaplaceCot(TriMesh mesh) { int n = mesh.Vertices.Count; SparseMatrix L = new SparseMatrix(n, n); for (int i = 0; i < mesh.Faces.Count; i++) { int c1 = mesh.Faces[i].GetVertex(0).Index; int c2 = mesh.Faces[i].GetVertex(1).Index; int c3 = mesh.Faces[i].GetVertex(2).Index; Vector3D v1 = mesh.Faces[i].GetVertex(0).Traits.Position; Vector3D v2 = mesh.Faces[i].GetVertex(1).Traits.Position; Vector3D v3 = mesh.Faces[i].GetVertex(2).Traits.Position; double cot1 = (v2 - v1).Dot(v3 - v1) / (v2 - v1).Cross(v3 - v1).Length(); double cot2 = (v3 - v2).Dot(v1 - v2) / (v3 - v2).Cross(v1 - v2).Length(); double cot3 = (v1 - v3).Dot(v2 - v3) / (v1 - v3).Cross(v2 - v3).Length(); L.AddValueTo(c1, c2, -cot3 / 2); L.AddValueTo(c2, c1, -cot3 / 2); L.AddValueTo(c2, c3, -cot1 / 2); L.AddValueTo(c3, c2, -cot1 / 2); L.AddValueTo(c3, c1, -cot2 / 2); L.AddValueTo(c1, c3, -cot2 / 2); } for (int i = 0; i < n; i++) { double sum = 0; foreach (SparseMatrix.Element e in L.Rows[i]) { sum += e.value; } L.AddValueTo(i, i, -sum); } L.SortElement(); return L; }
public void TestFrobeniusNorm() { var matrix = new SparseMatrix<double>(5, 5); Assert.AreEqual(0, matrix.FrobeniusNorm()); matrix[1, 1] = 5; Assert.AreEqual(Math.Sqrt(25), matrix.FrobeniusNorm()); }
/// <summary>Write a sparse matrix of integers to a StreamWriter object</summary> /// <param name="writer">a <see cref="StreamWriter"/></param> /// <param name="matrix">the matrix of doubles to write out</param> static public void WriteSparseMatrix(this TextWriter writer, SparseMatrix<int> matrix) { writer.WriteLine(matrix.NumberOfRows + " " + matrix.NumberOfColumns); foreach (var index_pair in matrix.NonEmptyEntryIDs) writer.WriteLine(index_pair.Item1 + " " + index_pair.Item2 + " " + matrix[index_pair.Item1, index_pair.Item2].ToString()); writer.WriteLine(); }
[Test()] public void TestFrobeniusNorm() { var float_matrix = new SparseMatrix<float>(5, 5); Assert.AreEqual(0, float_matrix.FrobeniusNorm()); float_matrix[1, 1] = 5; Assert.AreEqual(Math.Sqrt(25), float_matrix.FrobeniusNorm()); }
public void Factorization(SparseMatrix A) { TripletArraryData data = ConvertToTripletArrayData(A); int rowCount = A.Rows.Count; int columnCount = A.Columns.Count; int nnz = data.nnz; fixed (int* ri = data.rowIndex, ci = data.colIndex) fixed (double* val = data.values) { switch (SolverType) { case EnumSolver.UmfpackLU: solver = CreateSolverLUUMFPACK(rowCount, nnz, ri, ci, val); break; case EnumSolver.SuperLULU: solver = CreateSolverLUSuperLU(rowCount, rowCount, nnz, ri, ci, val); break; case EnumSolver.CholmodCholesky: solver = CreateSolverCholeskyCHOLMOD(rowCount, rowCount, nnz, nnz, ri, ci, val); break; case EnumSolver.SPQRLeastNormal: solver = CreateSolverQRSuiteSparseQR(rowCount, columnCount, nnz, nnz, ri, ci, val); break; case EnumSolver.SPQRLeastSqure: solver = CreateSolverQRSuiteSparseQR(rowCount, columnCount, nnz, nnz, ri, ci, val); break; } } if (solver == null) throw new Exception("Create Solver Fail"); }
void ComputeProbabilities(IList<int> users) { foreach (int user_id in users) { // initialize counter variables var user_class_counts = new int[ratings.Scale.Levels.Count]; var user_attribute_given_class_counts = new SparseMatrix<int>(ratings.Scale.Levels.Count, ItemAttributes.NumberOfColumns); // count foreach (int index in ratings.ByUser[user_id]) { int item_id = ratings.Items[index]; int level_id = ratings.Scale.LevelID[ratings[index]]; user_class_counts[level_id]++; foreach (int attribute_id in item_attributes.GetEntriesByRow(item_id)) user_attribute_given_class_counts[attribute_id, level_id]++; } // compute probabilities float denominator = user_class_counts.Sum() + ClassSmoothing; foreach (int level_id in ratings.Scale.LevelID.Values) { user_class_probabilities[user_id, level_id] = (user_class_counts[level_id] + ClassSmoothing) / denominator; // TODO sparsify? for (int attribute_id = 0; attribute_id < NumItemAttributes; attribute_id++) user_attribute_given_class_probabilities[user_id][attribute_id, level_id] = (user_attribute_given_class_counts[attribute_id, level_id] + AttributeSmoothing) / (NumItemAttributes + AttributeSmoothing); } } }
public void SolveLongMatrixThrowsArgumentException() { var matrix = new SparseMatrix(3, 2); Vector input = new DenseVector(3); var solver = new BiCgStab(); Assert.Throws<ArgumentException>(() => solver.Solve(matrix, input)); }
[Test()] public void TestIsSymmetric() { var matrix1 = new SparseMatrix<double>(3, 5); Assert.IsFalse(matrix1.IsSymmetric); var matrix2 = new SparseMatrix<double>(5, 5); Assert.IsFalse(matrix2.IsSymmetric); }
public void SolveWideMatrixThrowsArgumentException() { var matrix = new SparseMatrix(2, 3); Vector input = new DenseVector(2); var solver = new GpBiCg(); Assert.Throws<ArgumentException>(() => solver.Solve(matrix, input)); }
public void TestNonEmptyRows() { var matrix = new SparseMatrix<double>(3, 5); Assert.AreEqual(0, matrix .NonEmptyRows.Count); matrix [3, 1] = 1.0; Assert.AreEqual(1, matrix.NonEmptyRows.Count); Assert.AreEqual(3, matrix .NonEmptyRows[0].Key); }
public SparseMatrix MultiplyByMatlab(SparseMatrix A, SparseMatrix B) { IOHuiZhao.Instance.WriteMatrix(ref A, "abf_A.matrix"); IOHuiZhao.Instance.WriteMatrix(ref B, "abf_B.matrix"); SparseMatrix C = IOHuiZhao.Instance.ReadMatrix("AB.matrix"); return C; }
/// <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 preconditioner, SparseMatrix matrix, Vector vector, Vector result) { Assert.AreEqual(typeof(UnitPreconditioner), 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 Eigen ComputeEigensByLib(SparseMatrix sparse, int count) { SparseMatrixDouble ds = new SparseMatrixDouble(sparse); Eigen eigen = ComputeEigensByLib(ds, 0.0, count); return eigen; }
public SparseMatrix BuildLaplaceMatrixDual() { // build dual Laplacian weight matrix L int vn = this.Vertices.Count; int fn = this.Faces.Count; SparseMatrix L = new SparseMatrix(fn, vn, 6); for (int i = 0; i < fn; i++) { int f1 = this.Faces[i].GetFace(0).Index; int f2 = this.Faces[i].GetFace(1).Index; int f3 = this.Faces[i].GetFace(2).Index; Vector3D dv = this.DualGetVertexPosition(i); Vector3D dv1 = this.DualGetVertexPosition(f1); Vector3D dv2 = this.DualGetVertexPosition(f2); Vector3D dv3 = this.DualGetVertexPosition(f3); Vector3D u = dv - dv3; Vector3D v1 = dv1 - dv3; Vector3D v2 = dv2 - dv3; Vector3D normal = (v1.Cross(v2)).Normalize(); Matrix3D M = new Matrix3D(v1, v2, normal); Vector3D coord = M.Inverse() * u; double alpha; alpha = 1.0 / 3.0; L.AddValueTo(i, this.Faces[i].GetVertex(0).Index, alpha); L.AddValueTo(i, this.Faces[i].GetVertex(1).Index, alpha); L.AddValueTo(i, this.Faces[i].GetVertex(2).Index, alpha); alpha = coord[0] / 3.0; L.AddValueTo(i, this.Faces[f1].GetVertex(0).Index, -alpha); L.AddValueTo(i, this.Faces[f1].GetVertex(1).Index, -alpha); L.AddValueTo(i, this.Faces[f1].GetVertex(2).Index, -alpha); alpha = coord[1] / 3.0; L.AddValueTo(i, this.Faces[f2].GetVertex(0).Index, -alpha); L.AddValueTo(i, this.Faces[f2].GetVertex(1).Index, -alpha); L.AddValueTo(i, this.Faces[f2].GetVertex(2).Index, -alpha); alpha = (1.0 - coord[0] - coord[1]) / 3.0; L.AddValueTo(i, this.Faces[f3].GetVertex(0).Index, -alpha); L.AddValueTo(i, this.Faces[f3].GetVertex(1).Index, -alpha); L.AddValueTo(i, this.Faces[f3].GetVertex(2).Index, -alpha); } L.SortElement(); return L; }
/// <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; }
public double[] SloveSquare(ref SparseMatrix A, ref double[] rightB) { double[] unknown = new double[rightB.Length]; LinearSystemLib linearSolver = new LinearSystemLib(EnumSolver.UmfpackLU); linearSolver.Factorization(A); linearSolver.SolveLinerSystem(ref rightB, ref unknown); linearSolver.FreeSolver(); return unknown; }
public Eigen ComputeEigensByMatLab(SparseMatrix sparse, int count, string modelName) { IOHuiZhao.Instance.WriteMatrix(ref sparse, modelName); Eigen eigen = IOHuiZhao.Instance.ReadEigen(modelName); return eigen; }
public RapportManager(ConversationManager parent, DM_TYPE type = DM_TYPE.RULE_BASED) { _parent = parent; _type = type; _dialoguePolicy = new SparseMatrix<DialogueState, DialogueAction>(); _dialogueState = new DialogueState(); _agentID = parent.getAgentID(); _parent.DSUpdated += new DSUpdatedEventHandler(DSUpdated); }
[Test()] public void TestNumberOfNonEmptyEntries() { var matrix = new SparseMatrix<double>(3, 5); Assert.AreEqual(0, matrix.NumberOfNonEmptyEntries); matrix[3, 1] = 1.0; Assert.AreEqual(1, matrix.NumberOfNonEmptyEntries); matrix[3, 1] = 2.0; Assert.AreEqual(1, matrix.NumberOfNonEmptyEntries); }
public Eigen ComputeEigen(SparseMatrix sparse, int count, string modelName) { if (LinearSystemInfo.Matlab) { return ComputeEigensByMatLab(sparse, count, modelName); } else { return ComputeEigensByLib(sparse, count); } }
public void CanWriteMatrices() { Matrix mat1 = new DenseMatrix(5, 3); for (var i = 0; i < mat1.ColumnCount; i++) { mat1[i, i] = new Complex32(i + .1f, i + .1f); } Matrix mat2 = new DenseMatrix(4, 5); for (var i = 0; i < mat2.RowCount; i++) { mat2[i, i] = new Complex32(i + .1f, i + .1f); } Matrix mat3 = new SparseMatrix(5, 4); for (var i = 0; i < mat3.ColumnCount; i++) { mat3[i, i] = new Complex32(i + .1f, i + .1f); } Matrix mat4 = new SparseMatrix(3, 5); for (var i = 0; i < mat4.RowCount; i++) { mat4[i, i] = new Complex32(i + .1f, i + .1f); } var write = new[] { mat1, mat2, mat3, mat4 }; var names = new[] { "mat1", "dense_matrix_2", "s1", "sparse2" }; if (File.Exists("test.mat")) { File.Delete("test.mat"); } var writer = new MatlabMatrixWriter("test.mat"); writer.WriteMatrices(write, names); writer.Dispose(); var reader = new MatlabMatrixReader("test.mat"); var read = reader.ReadMatrices(names); Assert.AreEqual(write.Length, read.Count); for (var i = 0; i < write.Length; i++) { var w = write[i]; var r = read[names[i]]; Assert.AreEqual(w.RowCount, r.RowCount); Assert.AreEqual(w.ColumnCount, r.ColumnCount); Assert.IsTrue(w.Equals(r)); } }
[Test()] public void TestMax() { var int_matrix = new SparseMatrix<int>(3, 3); Assert.AreEqual(0, int_matrix.Max()); int_matrix[1, 1] = 9; Assert.AreEqual(9, int_matrix.Max()); var float_matrix = new SparseMatrix<float>(3, 3); Assert.AreEqual(0, float_matrix.Max()); float_matrix[1, 1] = 9.0f; Assert.AreEqual(9.0f, float_matrix.Max()); }
public double[] SolveSystem(ref SparseMatrix A, ref double[] rightB,string modelname) { if (LinearSystemInfo.Matlab) { return SolveByMatLab(ref A, ref rightB,modelname); } else { return SolveByLib(ref A, ref rightB); } }
[Test()] public void TestNonEmptyEntryIDs() { var matrix = new SparseMatrix<double>(3, 5); Assert.AreEqual(0, matrix.NonEmptyEntryIDs.Count); matrix[3, 1] = 1.0; Assert.AreEqual(1, matrix.NonEmptyEntryIDs.Count); foreach (var pair in matrix.NonEmptyEntryIDs) { Assert.AreEqual(3, pair.Item1); Assert.AreEqual(1, pair.Item2); } }
/// <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 preconditioner, SparseMatrix matrix, Vector vector, Vector result) { Assert.AreEqual(typeof(Diagonal), preconditioner.GetType(), "#01"); // Compute M * result = product // compare vector and product. Should be equal Vector product = new DenseVector(result.Count); matrix.Multiply(result, product); for (var i = 0; i < product.Count; i++) { Assert.IsTrue(vector[i].AlmostEqual(product[i], -Epsilon.Magnitude()), "#02-" + i); } }
/// <summary> /// Returns the upper triagonal matrix that was created during the LU decomposition. /// </summary> /// <returns>A new matrix containing the upper triagonal elements.</returns> internal Matrix UpperTriangle() { var result = new SparseMatrix(_decompositionLU.RowCount); for (var i = 0; i < _decompositionLU.RowCount; i++) { for (var j = i; j < _decompositionLU.ColumnCount; j++) { result[i, j] = _decompositionLU[i, j]; } } return result; }
/// <summary> /// Creates a new sparse matrix with zero values everywhere except /// on the diagonal where the values are equal to 1.0. /// </summary> private Matrix CreateMatrix(int size) { // Create the sparse matrix with the specified size Matrix matrix = new SparseMatrix(size); // Add values to the matrix. For now we'll make the matrix // a unit matrix. for (int i = 0; i < size; i++) { matrix[i, i] = 1.0; } return matrix; }
public void SaveSparseMatrix(string fileName) { SparseMatrix sm = GenerateSparseMatrix(); sm.saveMatrix(fileName); }