I have a problem where I need to interpolate a 3D function using e.g. SciPy, and then save the output of this interpolation for future use. That is, I don't want to have to run the interpolation procedure every time as generating the 3D function to be interpolated is computationally demanding (it is from the Biot-Savart law so is a lot of numerical integrations).
However, I'm having trouble understanding if this is possible and, secondly, how to implement this. From what I've seen on some other posts, it should be possible, but the solutions don't seem to work for me.
I have written the following test code, but I receive the below error when testing it:
TypeError: 'numpy.ndarray' object is not callable
This error is when is on the code line starting zeroVal
in the function loadInterpolation()
. I was hoping the allow_pickle=True
would have solved this, based on what I read previously
.
import scipy
from scipy.interpolate import RegularGridInterpolator
def f(x,y,z):
field = -x**2-y**2+z**2
return field
def performSaveInterpolation():
print(scipy.__version__)
print('Performing Interpolation...')
x = np.linspace(-1,1,100)
y = np.linspace(-1,1,100)
z = np.linspace(-1,1,100)
xg, yg ,zg = np.meshgrid(x, y, z, indexing='ij', sparse=True)
data = f(xg,yg,zg)
my_interpolating_function = RegularGridInterpolator((x, y, z), data)
zeroVal = my_interpolating_function([0,0,0])
oneVal = my_interpolating_function([1,1,1])
print('Interpolated function @ (0,0,0): ' + str(zeroVal))
print('Interpolated function @ (1,1,1): ' + str(oneVal))
np.save('interpolation.npy',my_interpolating_function,allow_pickle=True)
return 0
def loadInterpolation():
print('Loading Interpolation...')
interpolationFunc = np.load('interpolation.npy',allow_pickle=True)
zeroVal = interpolationFunc([0,0,0])
oneVal = interpolationFunc([1,1,1])
print('Interpolated function @ (0,0,0): ' + str(zeroVal))
print('Interpolated function @ (1,1,1): ' + str(oneVal))
return 0
performSaveInterpolation()
loadInterpolation()