我想計算 3D 中的點與 3D 中的凸集之間的距離,該距離在 numpy(python)中作為半平面的交集給出。
點和集合之間的距離定義為點到集合中任何點的距離的下確界(最小值)。
假設該點作為一維 numpy 陣列給出,例如:
P = np.array([-1,-2,-3], ndmin = 1)
P 表示點 (x,y,z) = (-1,-2,-3)。并假設凸集作為 2D numpy 陣列給出,例如:
C = np.array([1,2,3,4], [5,6,7,8] , [9,10,11,12] )
C 表示由 (x 2y 3y >= 4) /\ (5x 6y 7y >= 8) /\ (9x 10y 11y >= 12) 給出的凸集。如何計算 P 和 C 之間的距離?(我們可以假設所有的半平面只使用運算子 >=)
注意:正如 Pierre 在評論中提到的,點的距離不僅僅是點和半平面邊界上所有線段的距離的最小值。我們也必須考慮凸集的面。
uj5u.com熱心網友回復:
一種簡單的方法是考慮尋找最接近 的點的凸優化(在本例中為二次程式)P, st 約束Ax b <= 0。請注意,可能有更有效、更專業和更準確的方法來執行此操作(參見例如這個 mathoverflow 答案及其參考的鏈接)。
您可以使用 解決凸問題scipy.optimize.minimize。您的半空間定義了約束,最小化的函式是到點的距離(或其平方)P。
請注意,我們使用Ax b <= 0半空間的約定,并對它們進行編碼[A; b]。
import numpy as np
from scipy.optimize import minimize, LinearConstraint
def dist(x, p):
return np.linalg.norm(x - p)
def find_closest(halfspaces, p):
return minimize(
dist,
np.zeros(3),
args=(p,),
constraints=[LinearConstraint(halfspaces[:, :-1], -np.inf, -halfspaces[:, -1])],
)
例如,考慮由點(0,0,0)、(2,0,0)、(1,2,0)和定義的四面體(1,1,1):
halfspaces = np.array(
[[0,0,-1,0], # Ax b <= 0; each row of A is a vector normal to
# hyperplane and pointing outside C
[2,1,1,-4],
[-2,1,1,0],
[0,-1,1,0]])
然后:
>>> find_closest(halfspaces, [0,0,10])
fun: 9.110433579144301
jac: array([ 0.10976422, 0.10976422, -0.98787833])
message: 'Optimization terminated successfully'
nfev: 12
nit: 3
njev: 3
status: 0
success: True
x: array([1., 1., 1.])
# note: closest to a point (the top point)
>>> find_closest(halfspaces, [1,-0.1,0])
fun: 0.10000032194980375
jac: array([2.53758579e-03, 9.99996780e-01, 7.45058060e-08])
message: 'Optimization terminated successfully'
nfev: 13
nit: 3
njev: 3
status: 0
success: True
x: array([ 1.00025375e 00, -2.22044605e-17, 6.04908606e-17])
# note: closest to an edge (the x-aligned line segment)
>>> find_closest(halfspaces, [1,1,-0.5])
fun: 0.5000000000000011
jac: array([0.00000000e 00, 5.96046448e-08, 1.00000000e 00])
message: 'Optimization terminated successfully'
nfev: 26
nit: 6
njev: 6
status: 0
success: True
x: array([9.99999991e-01, 1.00000002e 00, 4.83315889e-16])
# note: closest to a face (the bottom face)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453054.html
