Search code examples
pythonpython-3.xnumpyscipywolfram-mathematica

Analogue function of Wolfram Mathematica in Python in NumPy or SciPy


I am rewriting some code writed in Wolfram Mathematica to Python. And, in some moment I needed an analogue of function ArrayResample[array,dspec]. May be you know a function from any package (NumPy or SciPy)?


Solution

  • You could use scipy.ndimage.map_coordinates. Here are map_coordinate equivalents of the ArrayResample examples:

    In [51]: import scipy.ndimage as ndimage
    
    In [67]: ndimage.map_coordinates(np.array([1,2,3,4,5], dtype=float), [np.linspace(0,4,9)], order=1)
    Out[67]: array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])
    
    In [68]: ndimage.map_coordinates(np.array([1,2,3,4,5], dtype=float), [np.linspace(0,4,3)], order=1)
    Out[68]: array([1., 3., 5.])
    
    In [65]: ndimage.map_coordinates(np.array([(1,2,3), (2,3,4), (3,4,5)], dtype=float), np.meshgrid(np.linspace(0,2,6), np.linspace(0,2,6), indexing='ij'), order=1)
    Out[65]: 
    array([[1. , 1.4, 1.8, 2.2, 2.6, 3. ],
           [1.4, 1.8, 2.2, 2.6, 3. , 3.4],
           [1.8, 2.2, 2.6, 3. , 3.4, 3.8],
           [2.2, 2.6, 3. , 3.4, 3.8, 4.2],
           [2.6, 3. , 3.4, 3.8, 4.2, 4.6],
           [3. , 3.4, 3.8, 4.2, 4.6, 5. ]])
    

    The first argument to ndimage.map_coordinates is mainly self-explanatory. Unlike Mathematica's ArrayResample function, the second argument are the coordinates at which you wish to resample the array.

    When calling ndimage.map_coordinates(input, coordinates), if input is an N-dimensional array, then coordinates is expected to be sequence of N arrays -- one array for each axis.


    If A is an array of shape (h, w), and you wish to resample A to a new array of shape (H, W), then you would use

    ndimage.map_coordinates(A, np.meshgrid(np.linspace(0,h-1,H), np.linspace(0,w-1,W), 
                                           indexing='ij'), order=1)
    

    np.linspace is used to generate equally spaced values between 0 and h-1 (and 0 and w-1). These values are 1D coordinates. np.meshgrid is used to combine the 1D coordinates into a 2D grid.