使用相同的I,J向量的COO到CSC格式

时间:2017-12-19 20:58:08

标签: julia sparse-matrix csr csc

现在,我调用K =稀疏(I,J,V,n,n)函数在Julia中创建稀疏(对称)K矩阵。而且,我正在做很多步骤。

由于内存和效率的考虑,我想修改K.nzval值,而不是创建一个新的稀疏K矩阵。请注意,每个步骤的I和J矢量相同,但非零值(V)在每一步都在变化。基本上,我们可以说我们知道COO格式的稀疏模式。 (我和J没有订购,可能有多个(I [i],J [i])条目)

我尝试命令我的COO格式向量与CSC / CSR格式存储相关。但是,我发现它非常重要(至少目前为止)。

有没有办法做到这一点或神奇的“稀疏!”功能?谢谢,

以下是与我的问题相关的示例代码。

n=19 # this is much bigger in reality ~ 100000. It is the dimension of a global stiffness matrix in finite element method, and it is highly sparse! 
I = rand(1:n,12)
J = rand(1:n,12)
#
for k=365
  I,J,val = computeVal()  # I,J are the same as before, val is different, and might have duplicates in it. 
  K = sparse(I,J,val,19,19)
  # compute eigs(K,...)
end

# instead I would like to decrease the memory/cost of these operations with following
# we know I,J
for k=365
  I,J,val = computeVal()  # I,J are the same as before, val is different, and might have duplicates in it. 
  # note that nonzeros(K) and val might have different size due to dublicate entries.
  magical_sparse!(K,val)
  # compute eigs(K,...)
end

# what I want to implement 
function magical_sparse!(K::SparseMatrixCSC,val::Vector{Float64}) #(Note that this is not a complete function)
    # modify K 
    K.nzval[some_array] = val
end

编辑:

这里给出了一个更具体的例子。

n=4 # dimension of sparse K matrix
I = [1,1,2,2,3,3,4,4,1,4,1]
J = [1,2,1,2,3,4,4,3,2,4,2]
# note that the (I,J) -> (1,2) and (4,4) are duplicates.
V = [1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.]

function computeVal!(V)
  # dummy function
  # return modified V
  rand!(V) # this part is involed, so I will just use rand to represent that we compute new values at each step for V vector. 
end

for k=1:365
  computeVal!(V)
  K = sparse(I,J,V,n,n)
  # do things with K
end

# Things to notice:
# println(length(V))       -> 11
# println(length(K.nzval)) -> 8

# I don't want to call sparse function at each step. 
# instead I would like to decrease the cost of these operations with following
# we know I,J
for k=1:365
  computeVal!(V)
  magical_sparse!(K,V)
  # do things with K
end

# what I want to implement 
function magical_sparse!(K::SparseMatrixCSC,V::Vector{Float64}) #(Note that this is not a complete function)
  # modify nonzeros of K and return K  
end

1 个答案:

答案 0 :(得分:0)

更新当前问题

根据问题的变化,新的解决方案是:

for k=365
  computeVal!(V)
  foldl((x,y)->(x[y[1],y[2]]+=y[3];x),fill!(K, 0.0), zip(I,J,V))
  # do things with K
end

此解决方案使用了一些技巧,例如使用K清零fill!,默认情况下会返回K,然后将其用作foldl的初始值。同样,使用?foldl应该清除这里发生的事情。

回答旧问题

更换

for k=365
  val = rand(12)
  magical_sparse!(K,val)
  # compute eigs(K,...)
end

for k=365
  rand!(nonzeros(K))
  # compute eigs(K,...)
end

应该这样做。

使用?rand!?nonzeros获取相应功能的帮助。