user1220086
user1220086

Reputation: 215

Indexing Numpy arrays with arrays

This question is a little more abstract than finding the solution with actual code. I am trying to understand some code for some software I am working with. Specifically, I am working with a 4D numpy array which is indexed by 3 other 3D arrays. I've read the following page: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html however it does not really cover the complexity of what I am dealing with (or I do not understand it fully to apply it to my situation).

My ultimate goal is to convert this code into C code, and so I need to understand how these arrays are accessed so that I may convert it. Does anyone know any tricks or tips to reading these numpy arrays with 3D array indexing? Is there some procedure I can follow to reconstruct a numpy array in C?

Any help would be appreciated!

For reference the following is what I am dealing with:

state = history[delays, var, node, :]

history.shape = (4192, 2, 74, 1)

delays.shape = (74,1,74)

var.shape = (74,1,74)

node.shape = (74,1,74)

The node matrix is actually just [[[ 0 0 0... 00]] [[ 1 1 1 ... 1 1]] [[ 2 2 2 ... 2 2]] ... [[73 73 73 ... 73 73 ]]] The var matrix is all 0's. The delays matrix is all integers of various values all modulus 4192.

Thanks!

Upvotes: 2

Views: 319

Answers (2)

Jaime
Jaime

Reputation: 67507

Your resulting array will have shape (74, 1, 74, 1). It would be interesting to see the content of your delays array: does it really have 5476 different values, or is it just 74 different values repeated 74 times? I ask, because that is actually what is happening with var and node.

If they are all different, an unoptimized C version of that same indexing would be something like this:

float history[4192][2][74][1], state[74][1][74][1];
int delays[74][1][74];

for (int j = 0; j < 74; j++) {
    for (int k = 0; k < 74; k++) {
        state[j][k] = history[delays[j][0][k]][0][k][0];
    }
}

If delays is not really a 2D array, but a 1D array repeated 74 times side by side, i.e. if np.all(np.equal.reduce(delays, axis=1)) returns True, then you can simplify the above code as follows:

float history[4192][2][74][1], state[74][1][74][1];
int delays[74]; /* keep only the unique values */

for (int j = 0; j < 74; j++) {
    for (int k = 0; k < 74; k++) {
        state[j][k] = history[delays[j]][0][k][0];
    }
}

Upvotes: 2

U2EF1
U2EF1

Reputation: 13289

Say I have a 4x4x4x4 numpy array 'a'. Then:

repr(a).replace('[', '{').replace(']', '}').replace('\n', '')

prints out an array ready for consumption in C.

double a[4][4][4][4] = {{{{  6.92719862e-01,   2.76015214e-01,   7.01148124e-01,            2.56710822e-01}, .......

Indexing will have the same coordinates in both, so a[(0,1,2,3)] in python will be the same as a[0][1][2][3] in C (and in fact you can use the latter syntax in both).

Upvotes: 1

Related Questions