Fast interpolation over 3D array

后端 未结 6 995
梦毁少年i
梦毁少年i 2020-12-13 22:03

I have a 3D array that I need to interpolate over one axis (the last dimension). Let\'s say y.shape = (nx, ny, nz), I want to interpolate in nz for

6条回答
  •  醉酒成梦
    2020-12-13 22:37

    Although there are several nice answers, they're still doing 250k interpolations in a fixed 500-long array:

    j250k = np.searchsorted( X500, X250k )  # indices in [0, 500)
    

    This can be sped up with a LUT, LookUp Table, with say 5k slots:

    lut = np.interp( np.arange(5000), X500, np.arange(500) ).round().astype(int)
    xscale = (X - X.min()) * (5000 - 1) \
            / (X.max() - X.min()) 
    j = lut.take( xscale.astype(int), mode="clip" )  # take(floats) in numpy 1.7 ?
    
    #---------------------------------------------------------------------------
    # X     |    |       | |             |
    # j     0    1       2 3             4 ...
    # LUT   |....|.......|.|.............|....  -> int j (+ offset in [0, 1) )
    #---------------------------------------------------------------------------
    

    searchsorted is pretty fast, time ~ ln2 500, so this is probably not much faster.
    But LUTs are very fast in C, a simple speed / memory tradeoff.

提交回复
热议问题