Home > Software engineering >  Numpy error when creating ragged nested sequences
Numpy error when creating ragged nested sequences

Time:07-09

I have the following Numpy array with will have a shape of (3, N):

import numpy as np
arr = np.array([[4, 4, 4, 7], [6, 6, 8, 9], [2, 4, 10, 29]])

I have a function named get_wheel_status:

def get_wheel_status(arr, Dr, Dl, Db):
    
    delta_right = arr[0,:]
    delta_left  = arr[1,:]
    delta_back = arr[2,:]
    
    delta_theta = (delta_left - delta_right) / (Dr   Dl)
    delta_theta_cumul = np.cumsum(delta_theta, axis=0)
    
    delta_x = 2*np.sin(delta_theta/2) * np.array([(delta_back / delta_theta)   Db])
    delta_y = 2*np.sin(delta_theta/2) * np.array([(delta_right / delta_theta)   Dr])

    delta_x_cumul = np.cumsum(delta_x, axis=0)
    delta_y_cumul = np.cumsum(delta_y, axis=0)
  
    return np.array([[delta_theta_cumul], [delta_x_cumul], [delta_y_cumul]])

I want to return a (3, N) matrix. But, when I pass the following:

get_wheel_status(arr, 1, 1, 1)

I get this error:

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  return np.array([[delta_theta_cumul], [delta_x_cumul], [delta_y_cumul]])

Can someone please help me understand why my return statement is causing this 'ragged nested sequence'?

Thanks!

CodePudding user response:

1. Quick Fix

A quick fix would be to add dtype=object to the np.array that is being returned by the function. In particular,

np.array([[delta_theta_cumul], [delta_x_cumul], [delta_y_cumul]], dtype=object)

The warning stems from the fact that NumPy does not support jagged arrays natively.

2. Proper Solution

Regardless, I'd suggest a more proper solution. Since you want to return a 3xN matrix, deleting a few superfluous [ and ] yields the desired output without throwing any warnings.

def get_wheel_status(arr, Dr, Dl, Db):
    
    delta_right = arr[0,:]
    delta_left  = arr[1,:]
    delta_back  = arr[2,:]
    
    delta_theta = (delta_left - delta_right) / (Dr   Dl)
    delta_theta_cumul = np.cumsum(delta_theta, axis=0)
    
    delta_x = 2*np.sin(delta_theta/2) * np.array((delta_back / delta_theta)   Db)
    delta_y = 2*np.sin(delta_theta/2) * np.array((delta_right / delta_theta)   Dr)

    delta_x_cumul = np.cumsum(delta_x, axis=0)
    delta_y_cumul = np.cumsum(delta_y, axis=0)
  
    return np.array([delta_theta_cumul, delta_x_cumul, delta_y_cumul])

This yields

out = get_wheel_status(arr, 1, 1, 1)
out
>array([[ 1.        ,  2.        ,  4.        ,  5.        ],
        [ 2.87655323,  7.67080862, 17.76846044, 46.53399275],
        [ 4.79425539,  9.58851077, 14.63733668, 22.3081453 ]])

out.shape
>(3, 4)
  • Related