[Python] scipy.sparse: one subarray at many locations in a larger array

Discussão em 'Python' iniciado por Stack, Abril 28, 2025.

  1. Stack

    Stack Membro Participativo

    Say I have a sparse subarray whose contents and shape are known:

    import scipy.sparse as sp
    sub = sp.coo_array([[a, b], [c, d]])


    I'd like to place this subarray at many locations, according to some known pattern, in a larger sparse array of arbitrary size. The code can compute the size of the large array (say NxN) but the numerical value of N isn't known to me.

    Using our contrived NxN and an arbitrary pattern, if N=4, the end result might be:

    [[a, b, a, b]
    [c, d, c, d]
    [0, 0, a, b]
    [0, 0, c, d]]


    and for N=8:

    [[a, b, a, b, 0, 0, 0, 0]
    [c, d, c, d, 0, 0, 0, 0]
    [0, 0, a, b, a, b, 0, 0]
    [0, 0, c, d, c, d, 0, 0]
    [0, 0, 0, 0, a, b, a, b]
    [0, 0, 0, 0, c, d, c, d]
    [0, 0, 0, 0, 0, 0, a, b]
    [0, 0, 0, 0, 0, 0, c, d]]


    N can be huge (tens of thousands), therefore a dense array is not computationally manageable, and it's not practical to manually specify each of the locations.

    sp.block_array appears to require specifying placement manually. sp.block_diag gets close to the contrived example but doesn't handle an arbitrary pattern. This question is similar but a) uses numpy, not scipy.sparse, and b) doesn't address placing the same subarray many times. This answer is related but only practical for arrays where N is small: in my case, alist would be huge and mostly full of None, even if I use a loop as suggested, which defeats the purpose of sparse arrays.

    An ideal solution might have a list of array indices at which the top left corner of the submatrix is placed. It should work with any pattern, even a bunch of random locations within NxN. I'm not very experienced with scipy.sparse but it seems like there should be a "good" way to do this sort of operation.

    Continue reading...

Compartilhe esta Página