COO 到具有相同 I、J 向量的 CSC 格式

COO to CSC format with the same I,J vectors

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

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

我试图命令我的 COO 格式向量与 CSC/CSR 格式存储相关。但是,我发现它很重要(至少目前如此)。

有没有办法做到这一点或神奇的 "sparse!" 功能?谢谢,

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

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

当前问题的更新

根据题目的变化,新的解法是:

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

此解决方案使用了一些技巧,例如使用 fill!K 归零,默认情况下 returns 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 获取有关各自功能的帮助。