Hi all,
For pedagogic purposes, I am trying to solve simple partial differential
equations (say a diffusion equation on a regular mesh in 2D) with Ruby.
Using the NArray gem, I have built a satisfactory tool from an interface
(and ease of use) point of view but the performance are suboptimal.
I am now wondering what is the right way to improve my code
performance-wise. I am doing a lot of matrix-vector and vector-vector
products.
From 2 2D NArrays describing two scalar fields, dot-product is
implemented as :
def dot_product(vec_a, vec_b)
dot_product=(vec_avec_b">vec_avec_b).sum
end
and as I am working with sparse matrices, (for the time being) a matrix
is an Array of Hashes. Each key of the hash contains the index of the
non-vanishing coefficients (the value of this coefficient is the value
of the Hash) of the matrix. For the identity matrix it gives
def identity(sizeX, sizeY)
mat=[]
(0…sizeXsizeY">sizeXsizeY).each { |ind|
mat << {ind=>1.0}
}
mat
end
Matrix vector product is then defined as
def matrix_vector_product(mat, vector)
ff=NArray.float(100,100)
(0…100100).each { |ind|
matrix[ind].each do |key,value|
ff[[ind]]+=valuevector[[key]][0]
end
}
ff
end
I am wondering what is the best way to tackle this performance problem :
- Improve the ruby code (and how? Should I avoid using hashes?
- Write an extension to perform these operations in C. BTW is there a
way to access directly NArray data (without copy) from a C extension? - Use a wrapper like Ruby-lapack
(
https://rubyforge.org/projects/ruby-lapack/
).
What do you think?
Thanks for your help !