Manipulating sparse matrices in Swift before solving system

33 views Asked by At

I would like to solve a very large sparse system of equations, but before I need to manipulate the SparseMatrix_Double because otherwise I cannot solve it (the matrix is singular). To make the problem easy, consider the matrix:

enter image description here

The system is singular, so before I can solve it, I need to remove the singularity. One way is to "zero out" certain rows and columns of the matrix and add 1's in the diagonal (essentially adding trivial equations). So the new system would then be (for instance for the first row):

enter image description here

I can then in Swift solve it with the code as follows:

var rows: [Int32] = [0, 0, 1, 1, 2, 1, 2, 3, 2, 3]
var columns: [Int32] = [0, 1, 0, 1, 1, 2, 2, 2, 3, 3 ]
var values: [Double] = [1, 0, 0, 2, -1, -1, 2, -1, -1, 1]

let blockCount = 11
let blockSize = 1
    
let A = SparseConvertFromCoordinate(4, 4,
                                        blockCount, UInt8(blockSize),
                                        SparseAttributes_t(),
                                        &rows, &columns,
                                        &values)
    
var b: [Double] = [0,0,0,1]
    
let factor = SparseFactor(SparseFactorizationQR, A)
defer {
    SparseCleanup(A)
    SparseCleanup(factor)
}

var x = Array(b)
    
x.withUnsafeMutableBufferPointer { fPtr in
        
    let xb = DenseVector_Double(count: 4,
                               data: fPtr.baseAddress!)
        
    SparseSolve(factor, xb)
}

print("x \(x)")

which prints what I expect:

x [8.790702249468562e-18, 1.0, 2.0, 3.0]

So the question I have is whether there is a way to quickly modify the SparseMatrix_Double structure, say, if I have all the rows and columns that have to be zeroed out in another array? The matrix does not support indexing, so I can't use the usual syntax used in other languages. My main issue is that I have a huge sparse matrix and a sufficiently large number of rows and columns that need to be modified, so checking the two arrays against each other leads to and all-to-all comparison with O(N*M) complexity (N the size of either of the 3 arrays in the sparse matrix and M the size of my array with rows/columns that need to be modified).

0

There are 0 answers