Search code examples
pythonnumpyvalueerroropenmesh

Adding new lines results in ValueError in numpy.asarray


Prior to adding the neighbor statements (that I commented with 'new'), everything worked just fine. Now, when using numpy.asarray, there is following error:

ValueError: could not broadcast input array from shape (3,3) into shape (3).

I'm really confused as the new lines didn't change anything about the rotations-array.

def rre(mesh, rotations):
"""
Relative Rotation Encoding (RRE).
Return a compact representation of all relative face rotations.
"""
all_rel_rotations = neighbors = []
for f in mesh.faces():
    temp = [] # new
    for n in mesh.ff(f):
        rel_rotation = np.matmul(rotations[f.idx()], np.linalg.inv(rotations[n.idx()]))
        all_rel_rotations.append(rel_rotation)
        temp.append(n.idx()) # new
    neighbors.append(temp) # new
all_rel_rotations = np.asarray(all_rel_rotations)
neighbors = np.asarray(neighbors) # new
return all_rel_rotations, neighbors

Solution

  • The source of the problem is very likely the line:

    all_rel_rotations = neighbors = []
    

    In Python lists are mutables and all_rel_rotations and neighbors point to the same list, so if you do all_rel_rotations.append(42) you will see that neighbors = [42, ]

    The line:

    all_rel_rotations.append(rel_rotation)
    

    appends a 2D array, while

    neighbors.append(temp)
    

    appends a 1D array (or the other way around) to the same list. Then:

    all_rel_rotations = np.asarray(all_rel_rotations)
    

    tries to convert to an array and get confused.

    If you need to list do

    all_rel_rotations = []
    neighbors = []