[Python] Cut-and-overlap reduction of N-dimensional array

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    Note: I have no idea what one might call this operation, so I've gone with "cut-and-overlap". Please let me know if there is an accepted terminology for something like this!

    Intro


    I need to implement an operation that can be performed on N-dimensional arrays, which I will describe below. I am working in Python with numpy and am looking for a numerical library in that ecosystem which might be able to do this, but am interested in any implementation in any language. While implementing this with for loops for 1D or 2D is possible, although fidly, I need an implementation that would work with N-dimensional arrays (not up to anything crazy, but at least 4D).

    Is there some neat way to do this, with some kind of fancy sliding windows and ravelling and reshaping? ;)

    The operation


    The principle of the operation is to make a number of "cuts" in the array, and then slide the array over itself at the cut locations so it overlaps, and finally aggregate the overlapping values. In my case, that aggregation is a simple sum. I think the easiest way to illustrate it is to give some examples, which are below for 1D and 2D cases. Hopefully the generalisation to N-dimensional arrays follows fairly obviously.

    Examples

    1D case


    arr = [0,2,5,3,2,1,0,3,4,5,2,3,6,4,1,2,3]
    cut_locations = [3,6,11]
    slide_amount = [3,7,1]


    The array is cut like so: [0,2,5,3|2,1,0|3,4,5,2,3|6,4,1,2,3]
    Then, it is slid together like so:

    0253
    210
    34523
    64123


    Finally, the result is summed, giving the resulting array:
    [3,8,11,5,9,4,1,2,3]

    2D case


    The 2D case is a bit harder to visualise:

    INPUT



    [​IMG]

    OUTPUT



    [​IMG]

    Final thoughts


    An extreme example is if the shift is greater than the length of the array... For example:

    arr = [0,2,5,3,2,1,0,3,4,5,2,3,6,4,1,2,3]
    cut_locations = [5]
    slide_amount = [20]


    Result: [1,0,3,4,5,2,3,6,4,1,2,3,0,0,0,0,2,5,3,2]

    Continue reading...

Compartilhe esta Página