Note
Go to the end to download the full example code
2-Dimensional Interpolation of Tidy DataΒΆ
True
True
True
True
True
True
True
7 import numpy as np
8 import matplotlib.pyplot as plt
9 from scipy import interpolate
10 from scipy.stats import norm
11 from mpl_toolkits.mplot3d import Axes3D
12
13 import pandas as pd
14
15 import itertools
16
17 import ndsplines
18
19 def gaussian(x_in):
20 z = norm.ppf(.995)
21 x = z*(2*x_in-1)
22 return norm.pdf(x)
23
24 def sin(x_in):
25 x = np.pi*(x_in-0.5)
26 return np.sin(x)
27
28 def tanh(x_in):
29 x = 2*np.pi*(x_in-0.5)
30 return np.tanh(x)
31
32 def dist(x_in, y_in):
33 return np.sqrt((x_in-0.25)**2 + (y_in-0.25)**2)
34
35 funcs = [gaussian, sin, tanh]
36
37 def wrap2d(funcx, funcy):
38 def func2d(x_in, y_in):
39 return funcx(x_in)*funcy(y_in)
40 func2d.__name__ = '_'.join([funcx.__name__, funcy.__name__])
41 return func2d
42
43 funcs = [ wrap2d(*funcs_to_wrap) for funcs_to_wrap in itertools.combinations_with_replacement(funcs, r=2)]
44 funcs.append(dist)
45
46 x = np.linspace(0, 1, 7)
47 y = np.linspace(0, 1, 7)
48
49 xx = np.linspace(0,1,64)
50 yy = np.linspace(0,1,64)
51
52 xx = np.linspace(-.25, 1.25, 64)
53 yy = np.linspace(-.25, 1.25, 64)
54 k = 3
55
56
57 meshx, meshy = np.meshgrid(x, y, indexing='ij')
58 gridxy = np.r_['0,3', meshx, meshy]
59 gridxy = np.stack((meshx, meshy), axis=-1)
60 tidyxy = gridxy.reshape((-1,2))
61
62
63 meshxx, meshyy = np.meshgrid(xx, yy, indexing='ij')
64 gridxxyy = np.stack((meshxx, meshyy), axis=-1)
65
66 for func in funcs:
67 fvals = func(meshx, meshy)
68 truef = func(meshxx, meshyy)
69
70 tidy_array = np.concatenate((fvals.reshape((-1,1)), tidyxy,), axis=1)
71
72 tidy_df = pd.DataFrame(tidy_array, columns=['z', 'x', 'y',])
73 test_NDBspline3 = ndsplines.make_interp_spline(gridxy, fvals[:, :, None])
74 test_NDBspline = ndsplines.make_interp_spline_from_tidy(tidy_df, ['x', 'y'], ['z'])
75 test_RectSpline = interpolate.RectBivariateSpline(x, y, fvals)
76 test_NDBspline2 = ndsplines.make_interp_spline_from_tidy(tidy_array, [1,2], [0])
77
78 print(np.allclose(test_NDBspline2(gridxxyy),test_NDBspline(gridxxyy)))
79
80 fig = plt.figure()
81 ax = fig.add_subplot(111, projection='3d')
82
83 ax.plot_wireframe(meshxx, meshyy, truef, alpha=0.25, color='C0')
84 ax.plot_wireframe(meshxx, meshyy, test_NDBspline(gridxxyy)[...,0], color='C1')
85 ax.plot_wireframe(meshxx, meshyy, test_RectSpline(meshxx, meshyy, grid=False), color='C2')
86 plt.show()
Total running time of the script: (0 minutes 1.515 seconds)