scipy 具有多边形遮罩的2D向量场:离任意给定点最近的顶点

rlcwz9us  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(193)

我试图创建一个2D向量场,应用多边形“遮罩”,使得每个点的Angular 和值都是它们与该多边形最近顶点的距离的函数。
我猜scipy.interpolate可能有我需要的东西,但我需要一些指导。
到目前为止,我可以用matplotlib创建一个多边形,得到它的顶点,然后用它们来创建一个插值器,但是在那之后,我不知道我在做什么。
我认为相关的伪代码应该是这样的:

for point in all_points:
    nearest = NearestPoint(polygon_vertices, point)
    value = point - nearest
    angle = Angle(nearest, point)

最困难的部分是计算任何给定坐标的多边形的最近顶点:但是必须有一个numpy/scipy函数来实现这个...
这是我目前得到的:

def CircleVertices():
    circ = plt.Circle((0.5, 0.5), radius=0.4, edgecolor='b', facecolor='None')
    return circ.get_path().vertices

def NearestNeighborInterpolate():
    vertices = CircleVertices()
    x, y = vertices[:,0], vertices[:,1]
    z = [np.hypot(x, y) for x,y in vertices]

    X = np.linspace(min(x)-0.5, max(x)+0.5, num=100)
    Y = np.linspace(min(y)-0.5, max(y)+0.5, num=100)

    X, Y = np.meshgrid(X, Y)
    interp = scipy.interpolate.NearestNDInterpolator(list(zip(x, y)), z)
    Z = interp(X, Y)

    plt.pcolormesh(X, Y, Z, shading='auto')
    plt.plot(x, y, "ok", label="input point")

    plt.legend()
    plt.colorbar()
    plt.axis("equal")
    plt.show()

def GriddataInterpolate():
    vertices = CircleVertices()
    x, y = vertices[:,0], vertices[:,1]

    xx = np.linspace(-1, 1, 20)
    yy = np.linspace(-1, 1, 20)
    xx, yy = np.meshgrid(xx, yy)

    u = [np.hypot(x, y) for x,y in vertices]
    v = [0.5 for _ in x]

    u_interp = scipy.interpolate.griddata(vertices, u, (xx, yy), method='linear')
    v_interp = scipy.interpolate.griddata(vertices, v, (xx, yy), method='linear')

    plt.quiver(xx, yy, u_interp, v_interp)
    plt.show()

它会生成以下两个图形:
nearest neighbor circle
grid data interpolation

31moq8wy

31moq8wy1#

可以使用NearestNDInterpolator
对文档中的示例稍作修改

from scipy.interpolate import NearestNDInterpolator
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng()
x = rng.random(10) - 0.5
y = rng.random(10) - 0.5
# in 2D you can represent the point as a complex number
z = x + 1j * y 
X = np.linspace(-0.5, 0.5, 256)
Y = np.linspace(-0.5, 0.5, 256)
X, Y = np.meshgrid(X, Y)  # 2D grid for interpolation
interp = NearestNDInterpolator(list(zip(x, y)), z)
Z = interp(X, Y)

plt.figure(figsize=(12, 4.5))
plt.subplot(121)
plt.pcolormesh(X, Y, abs(Z - (X + 1j*Y)), shading='auto')
plt.plot(x, y, "ok", label="input point")
plt.colorbar()
plt.title('Distance')
plt.axis("equal")

plt.subplot(122)
plt.pcolormesh(X, Y, (180 / np.pi) * np.angle((X + 1j*Y) - Z), shading='auto')
plt.plot(x, y, "ok", label="input point")
plt.colorbar()
plt.title('Angle')
plt.axis("equal")
plt.show()

plt.show()

你有这个

相关问题