python中点和曲线之间的距离

Ele*_*reg 0 scipy python-3.x

我有几个点和一条曲线,描述为两个列表(包括位置)。我尝试获取点和曲线之间的差异列表。我试图关注这个网络,但我不明白这个命令

X = fmin_cobyla(objective, x0=[0.5,0.5], cons=[c1])
Run Code Online (Sandbox Code Playgroud)

请问我的案例中正确的论据是什么?

import numpy as np  
import matplotlib.pyplot as plt
from scipy.optimize import fmin_cobyla

data = np.loadtxt('O_Cout.dat', unpack=True, usecols=[0, 2])

z_1v1 = np.polyfit(data[0], data[1], 2)
f_1v1 = np.poly1d(z_1v1)
# Creating more points on the streamline - defining new time with more steps
x_new = list(np.arange(0,100000,1))
y_new = f_1v1(x_new)

# Plot figure with size
fig, ax = plt.subplots()

ax.scatter(data[0], data[1])

ax.plot(x_new, y_new)


def objective(X):
    x,y = X
    return np.sqrt((x - P[0])**2 + (y - P[1])**2)

def c1(X):
    x,y = X
    return f(x) - y


for i in range(len(data[1])-1):
    P = (data[0][i], data[1][i])
    print(P)

    X = fmin_cobyla(objective, x0=[0.5,0.5], cons=[c1])

    print ('The minimum distance is', objective(X))


# Save the figure
plt.tight_layout()
plt.savefig('OC_parabola.png')
Run Code Online (Sandbox Code Playgroud)

Max*_*ini 7

您找到的脚本适用于已知函数 f(x) 但 IIUC 您不知道 f(x):您的曲线仅由坐标 (x,y) 定义,并且您不知道 f(x) 所以y=f(x)。

在这种情况下,您可以使用相同的基础知识。

给定一个点P

在此输入图像描述

和由坐标 (x,y) 定义的曲线,点 P 和曲线上的点之间的距离可以简单地定义为

在此输入图像描述

我们希望最小化,即找到定义域中的最小值/a。

例如

import numpy as np  
import matplotlib.pyplot as plt

# Here I define a function f(x) to
# generate y coordinates, but let us
# suppose we don't know it and that
# we got only x and y
def f(x):
    return np.cbrt( np.exp(2*x) -1 )

# This is what we really got
x = np.linspace(-2, 2, 1000)
y = f(x)

# The point P
P = (.5, .5)

fig, ax = plt.subplots(figsize=(7, 7))
ax.plot(x, y, lw=4)
ax.plot(*P, 'or')
ax.text(
    P[0], P[1], 
    f"  P ({P[0]}, {P[1]})", 
    ha='left', va='center',
    fontsize=15
)
ax.set(
    xlim=(-2, 2),
    ylim=(-2, 2),
)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

让我们定义函数 d,即点 P 和曲线之间的距离

def distance(x, y, x0, y0):
    d_x = x - x0
    d_y = y - y0
    dis = np.sqrt( d_x**2 + d_y**2 )
    return dis
Run Code Online (Sandbox Code Playgroud)

现在计算给定 P 和 (x,y) 之间的 d 并找到最小值

from scipy.signal import argrelmin

# compute distance
dis = distance(x, y, P[0], P[1])
# find the minima
min_idxs = argrelmin(dis)[0]
# take the minimum
glob_min_idx = min_idxs[np.argmin(dis[min_idxs])]
# coordinates and distance
min_x = x[glob_min_idx]
min_y = y[glob_min_idx]
min_d = dis[glob_min_idx]
Run Code Online (Sandbox Code Playgroud)

并绘制结果

fig, ax = plt.subplots(figsize=(7, 7))

ax.plot(x, y, lw=4)
ax.plot(
    [P[0], min_x],
    [P[1], min_y],
    'k--', lw=1,
    label=f'distance {min_d:.2f}'
)
ax.plot(*P, 'or')
ax.text(
    P[0], P[1], 
    f"  P ({P[0]}, {P[1]})", 
    ha='left', va='center',
    fontsize=15
)
ax.set(
    xlim=(-2, 2),
    ylim=(-2, 2),
)
ax.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑

改进一下,可以定义一个简单的函数来返回所有最小距离,例如

import numpy as np  
import matplotlib.pyplot as plt

def distance(x, y, x0, y0):
    """
    Return distance between point
    P[x0,y0] and a curve (x,y)
    """
    d_x = x - x0
    d_y = y - y0
    dis = np.sqrt( d_x**2 + d_y**2 )
    return dis

def min_distance(x, y, P, precision=5):
    """
    Compute minimum/a distance/s between
    a point P[x0,y0] and a curve (x,y)
    rounded at `precision`.
    
    ARGS:
        x, y      (array)
        P         (tuple)
        precision (int)
        
    Returns min indexes and distances array.
    """
    # compute distance
    d = distance(x, y, P[0], P[1])
    d = np.round(d, precision)
    # find the minima
    glob_min_idxs = np.argwhere(d==np.min(d)).ravel()
    return glob_min_idxs, d
Run Code Online (Sandbox Code Playgroud)

即使有多个最小值也有效

def f(x):
    return x**2

x = np.linspace(-2, 2, 1000)
y = f(x)

P = (0, 1)

min_idxs, dis = min_distance(x, y, P)

fig, ax = plt.subplots(figsize=(7, 7))

ax.plot(x, y, lw=4)
for idx in min_idxs:
    ax.plot(
        [P[0], x[idx]],
        [P[1], y[idx]],
        '--', lw=1,
        label=f'distance {dis[idx]:.2f}'
    )
ax.plot(*P, 'or')
ax.text(
    P[0], P[1], 
    f"  P ({P[0]}, {P[1]})", 
    ha='left', va='center',
    fontsize=15
)
ax.set(
    xlim=(-2, 2),
    ylim=(-1, 3),
)
ax.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

def f(x):
    return np.sqrt(4 - x**2)

x = np.linspace(-2, 2, 21)
y = f(x)

P = (0, 0)

min_idxs, dis = min_distance(x, y, P)

fig, ax = plt.subplots(figsize=(7, 7))

ax.plot(x, y, lw=4)
for idx in min_idxs:
    ax.plot(
        [P[0], x[idx]],
        [P[1], y[idx]],
        '--', lw=1,
        label=f'distance {dis[idx]:.2f}'
    )
ax.plot(*P, 'or')
ax.text(
    P[0], P[1], 
    f"  P ({P[0]}, {P[1]})", 
    ha='left', va='center',
    fontsize=15
)
ax.set(
    xlim=(-2, 2),
    ylim=(-1, 3),
)
ax.legend(loc='upper left', bbox_to_anchor=(1,1))
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • YVW。我使用返回所有最小距离的函数改进了答案(不仅仅是距离数组中的第一次出现) (2认同)
  • 这是一个令人惊奇的回应。感谢您付出的努力! (2认同)