%matplotlib inline
from scipy.spatial import Delaunay
from mpl_toolkits import mplot3d
N=20
X,Y = np.meshgrid(np.linspace(-1,1,N), np.linspace(-1,1,N))
X += (np.random.rand(N,N)*2-1)/20
Y += (np.random.rand(N,N)*2-1)/20
points = np.vstack([X.reshape(N*N), Y.reshape(N*N)]).T
print(points[0:5])
fig, ax = plt.subplots(figsize=(8,8))
ax.plot(points[:,0], points[:,1], 'o')
ax.set_aspect('equal')
msk = np.linalg.norm(points, axis=1) < 1
print(msk[0:50])
fig, ax = plt.subplots(figsize=(8,8))
ax.plot(points[msk,0], points[msk,1], 'o')
ax.set_aspect('equal')
z = -(3*points[:,0]-0.25)**2 - (3*points[:,1]+0.25)**2
fig, ax = plt.subplots(figsize=(8,8))
p=ax.scatter(points[:,0], points[:,1], c=z)
fig.colorbar(p)
ax.set_aspect('equal')
fig = plt.figure(figsize=(8,8))
ax = plt.axes(projection='3d')
#ax.contour3D(points[:,0].reshape(N,N), points[:,1].reshape(N,N), z.reshape(N,N), 50)
ax.plot(points[:,0], points[:,1], z, 'o')
dln = Delaunay(points)
print(dln.simplices[0:10])
fig, ax = plt.subplots(figsize=(8,8))
ax.plot(points[:,0], points[:,1], 'o')
for i, tri in enumerate(dln.simplices):
for j in range(3):
k = (j+1)%3
ax.plot(points[[tri[j], tri[k]],0], points[[tri[j], tri[k]],1], '-k')
ax.set_aspect('equal')
fig = plt.figure(figsize=(8,8))
ax = plt.axes(projection='3d')
ax.plot_trisurf(points[:,0], points[:,1], z, triangles=dln.simplices, cmap='viridis')
print(dln.convex_hull)
fig, ax = plt.subplots(figsize=(8,8))
ax.plot(points[:,0], points[:,1], 'o')
for i, seg in enumerate(dln.convex_hull):
ax.plot(points[[seg[0], seg[1]],0], points[[seg[0], seg[1]],1], '-k')
ax.set_aspect('equal')
dlnmsk = Delaunay(points[msk])
print(dlnmsk.simplices[0:10])
fig, ax = plt.subplots(figsize=(8,8))
ax.plot(points[msk,0], points[msk,1], 'o')
for i, seg in enumerate(dlnmsk.convex_hull):
ax.plot(points[msk][[seg[0], seg[1]],0], points[msk][[seg[0], seg[1]],1], '-k')
ax.set_aspect('equal')