jeudi 28 janvier 2021

Error in applying different if statements to each element of a numpy array

Good morning, I have a simple question about applying a different if statement to every element of a numpy array. I have written a function that take as input a numpy array made of 12 elements, checks if the element is 0 or 1 and, if it's 1, acts on another array. The function is the following:

def symmetry_test(determinant):
    print(determinant)
    ag=np.array([1,1,1,1])
    bg=np.array([1,-1,-1,1])
    au=np.array([1,1,-1,-1])
    bu=np.array([1,-1,1,-1])
    representations=np.zeros((4,12))
    print(determinant[0])
    if int(determinant[0])==1:
       representations[:,0]=au
   
    print(determinant[1])
    if int(determinant[1])==1:
       representations[:,1]=au
   
    print(determinant[2])
    if determinant[2]==1:
       representations[:,2]=ag

    print(determinant[3])
    if determinant[3]==1:
       representations[:,3]=ag
  
    if determinant[4]==1:
       representations[:,4]=bg

    if determinant[5]==1:
       representations[:,5]=bg
 
    if determinant[6]==1:
       representations[:,6]=ag
   
    if determinant[7]==1:
       representations[:,7]=ag
 
    if determinant[8]==1:
       representations[:,1]=bu

    if determinant[9]==1:
       representations[:,9]=bu
 
    if determinant[10]==1:
       representations[:,10]=au
  
    if determinant[11]==1:
       representations[:,11]=au

    idx = np.argwhere(np.all(representations[..., :] == 0, axis=0))
    representations = np.delete(representations, idx, axis=1)
    return representations

The function takes determinant as input, which is a numpy array, generates an array called representations and fills it. I put print(determinant[0])and int(determinant[0]) in the definition to check if the function reads the array properly. The problem is the following: if I give as input an array defined as test=np.array([1,1,1,1,1,1,0,0,0,0,0,0]) the function works fine and returns and array like

 1  1  1  1  1  1
 1  1  1  1 -1 -1
-1 -1  1  1  1  1
-1 -1  1  1 -1 -1

which is exactly what I want. Now, if I give to the function the array test=np.array([1,1,1,1,0,0,0,0,1,1,0,0]) and use it as a=symmetry_test(test),the output is

 1  1  1  1  1
 1 -1  1  1 -1
-1  1  1  1  1
-1 -1  1  1 -1

(yes, it only has 5 columns) instead of

 1  1  1  1  1  1
 1  1  1  1 -1 -1
-1 -1  1  1 -1 -1
-1 -1  1  1  1  1

Honestly I have no idea of the reason why it doesn't work and what puzzles me the most is the fact that for one array it works and for another it fails completely. I tried to punt the else condition

else:
    representations[:,0]=np.zeros(4)

after each if statement without success; I also tried to put determinant=np.asarray(determinant) at the beginning of the function but, also in this case, it didn't solve the problem. Any suggestion will be greatly appreciated. Thanks in advance and sorry for the easy question.

Aucun commentaire:

Enregistrer un commentaire