Skip to content
wo80 edited this page Jun 8, 2015 · 4 revisions

This example shows how to create a sparse LU factorization:

using System;
using CSparse;
using CSparse.Double;
using CSparse.Double.Factorization;
using CSparse.IO;
using CSparse.Ordering;
using CSparse.Storage;

public static class Example
{
    public static bool Solve(string fileName)
    {
        // Load matrix from a file.
        var reader = new MatrixMarketReader<double>(fileName);
        var storage = reader.ReadMatrix();

        // Convert from coordinate to CSC storage.
        var A = Converter.ToCompressedColumnStorage(storage);

        int m = A.RowCount;
        int n = A.ColumnCount;

        // Cannot solve rectangular system.
        if (m != n) return false;

        // Randomized Dulmage-Mendelsohn analysis.
        var dm = DulmageMendelsohn.Generate(A, 1);

        // Cannot solve singular system.
        if (dm.StructuralRank < n) return false;

        // Create test data.
        var x = Vector.Create(n, 1.0);
        var b = new double[m];
        var r = new double[m];

        // Compute right hand side vector b.
        A.Multiply(1.0, x, 0.0, b);

        // Apply column ordering to A to reduce fill-in.
        var order = ColumnOrdering.MinimumDegreeAtPlusA;

        // Partial pivoting tolerance (0.0 to 1.0)
        double tolerance = 1.0;

        // Create LU factorization.
        var lu = new SparseLU(A, order, tolerance);

        // Solve Ax = b.
        Vector.Copy(b, x);
        lu.Solve(x);

        // Compute residual r = b - Ax.
        Vector.Copy(b, r);
        A.Multiply(-1.0, x, 1.0, r);

        return true;
    }
}
Clone this wiki locally