2-Dimensional Least Squares FitΒΆ

2d lsq
 7 import ndsplines
 8 from scipy import interpolate
 9 import matplotlib.pyplot as plt
10 import numpy as np
11
12 from mpl_toolkits.mplot3d import Axes3D
13
14
15 NUM_X = 50
16 NUM_Y = 50
17 x = np.linspace(-3, 3, NUM_X)
18 y = np.linspace(-3, 3, NUM_Y)
19 meshx, meshy = np.meshgrid(x,y, indexing='ij')
20 input_coords = np.stack((meshx, meshy), axis=-1)
21 K = np.array([[1, -0.7,], [-0.7, 1.5]])
22 meshz = np.exp(-np.einsum(K, [1,2,], input_coords, [...,1], input_coords, [...,2])) + 0.1 * np.random.randn(NUM_X,NUM_Y)
23
24
25 xt = [-1, 0, 1]
26 yt = [-1, 0, 1]
27 k = 3
28 xt = np.r_[(x[0],)*(k+1),
29           xt,
30           (x[-1],)*(k+1)]
31 yt = np.r_[(y[0],)*(k+1),
32           yt,
33           (y[-1],)*(k+1)]
34
35 ts = [xt, yt]
36
37 samplex = input_coords.reshape((-1,2))
38 sampley = meshz.reshape((-1))
39
40 spl = ndsplines.make_lsq_spline(samplex, sampley, ts, np.array([3,3]))
41
42 fig = plt.figure()
43 ax = fig.add_subplot(111, projection='3d')
44
45 ax.scatter(meshx, meshy, meshz, alpha=0.25)
46 ax.plot_wireframe(meshx, meshy, spl(input_coords), color='C1')
47 plt.show()

Total running time of the script: (0 minutes 0.241 seconds)

Gallery generated by Sphinx-Gallery