pythonarraysinterpolationspatial-interpolation

interpolating 1D array into 3D array grid in python


I have a 1D array with 81 numbers that corresponds to 81 temperature every 2.5 meters depth and I need to interpolate it to a 3D array grid that has 100 points in z-dir, 6 points in x-dir, and 599 points in y-dir. My function to create the 1D values are:

zz = np.arange(-200,0.1,2.5)
def grid_function(x, ABath=-0.2, BBath=0.1, CBath=50.,DBath=10.):
    """This function creates a theoretical grid"""

    from numpy import tanh, arange


    ans = ABath * (tanh(BBath * (-x - CBath))) + DBath
    return ans

temp = grid_function(zz)

Below there's a cross section of my grid enter image description here

I don't know if I am clear with what I am asking but if anyone knows a way I would be really thankful.

Regards,


Solution

  • You should be able to construct a 3D array from your existing temp 1D array as follows:

    zz = np.arange(-200,0.1,2.5)
    def grid_function(x, ABath=-0.2, BBath=0.1, CBath=50.,DBath=10.):
        """This function creates a theoretical grid"""
    
        from numpy import tanh, arange
    
    
        ans = ABath * (tanh(BBath * (-x - CBath))) + DBath
        return ans
    
    temp = grid_function(zz)
    
    # Construct 1D 100-element array with z-coordinates
    z_new = np.linspace(zz[0], zz[-1], 100)
    
    # Interpolate 1D temperatures at new set of 100 z-coordinates
    temp_1d_new = np.interp(z_new, zz, temp)
    
    # Replicate 1D temperatures into two additional dimensions
    temp_3d_new = np.tile(temp_1d_new, (6, 599, 1))
    

    You could also take a more direct approach however and start immediately with a z-coordinates 1D array with the desired 100 elements (i.e. skip the interpolation step). Like so:

    def grid_function(x, ABath=-0.2, BBath=0.1, CBath=50.,DBath=10.):
        """This function creates a theoretical grid"""
    
        from numpy import tanh, arange
    
    
        ans = ABath * (tanh(BBath * (-x - CBath))) + DBath
        return ans
    
    # Create 1D arrays with x-coordinates, y-coordinates and z-coordinates
    x = np.linspace(0., 100., 6)
    y = np.linspace(0., 100., 599)
    z = np.linspace(-200., 0., 100)
    
    # Create 3D meshgrids for x-coordinates, y-coordinates and z-coordinates
    (xx, yy, zz) = np.meshgrid(x, y, z)
    
    # Calculate temperatures 3D array from z-coordinates 3D array
    temp = grid_function(zz)
    

    Side note

    It's considered good practice to place import statements always at the top of your code file.