次の問題があります。2D 空間の 2 つのデータ セットが与えられます。2 つのデータ セットは、例で (0,0) によって指定された中心点からの 2D 測定点です。ポイント間の線形補間を使用して、2 番目のデータ セットによって定義された線分に最初のデータ セット (x1、y1) のポイントを集中投影する必要があります。
import numpy as np
import matplotlib.pyplot as plt
x1 = np.arange(-50, 50, 1)
y1 = 50+np.random.rand(100)*5
x2 = np.arange(-20, 30, 50.0/320)
y2 = 30+np.random.rand(320)*0.5
plt.plot(x1, y1, '*',
x2, y2, 'x',
0.0, 0.0, 'o')
plt.show()
set1 をソース ポイントと set2 の線分に接続するすべての線に対して、従来の線交差計算を既に実装しています。残念ながら、ネストされた for ループはあまり効率的ではありません。
このアルゴリズムをより速く実行する方法はありますか? おそらくベクトル化された実装ですか?
何か案は?前もって感謝します。
わかった。問題を再定義させてください。
次のコードがあります。
import numpy as np
import matplotlib.pyplot as plt
import time
set1 = np.zeros((100, 2))
set2 = np.zeros((320, 2))
set3 = np.zeros((100, 2))
# p1
set1[:, 0] = np.arange(-50, 50, 1)
set1[:, 1] = 50+np.random.binomial(5, 0.4, size=100)
# p2 and p3
set2[:, 0] = np.arange(-20, 50, 70.0/320)
set2[:, 1] = 30+np.random.binomial(8, 0.25, size=320)
# p0
sp = np.array([0.0, 0.0])
tstamp = time.time()
# building line direction vectors
s1 = set1 # set 1 is already the direction vector as sp=[0,0]
s2 = set2[1:] - set2[0:-1] # set 2 direction vector (p3-p2)
projected_profile = np.zeros((100, 2))
# project set1 on set2
for i in range(np.size(s1)/2):
intersect_points = np.zeros((100, 2))
ts = np.zeros(100)
ind1 = 0
for j in range(np.size(s2)/2):
# calculate line intersection
div = s1[i, 0] * s2[j, 1] - s2[j, 0] * s1[i, 1]
s = (s1[i, 1] * set2[j, 0] - s1[i, 0] * set2[j, 1]) / div
t = (s2[j, 1] * set2[j, 0] - s2[j, 0] * set2[j, 1]) / div
# check wether we are still on the line segments
if (s>=0 and s<=1 and t>=0 and t <=1):
intersect_points[ind1, :] = t * s1[i]
ts[ind1] = t
ind1 += 1
# take the intersection with maximal distance from source point (sp)
if ts.sum()>0:
projected_profile[i, :] = intersect_points[np.argmax(ts), :]
print time.time()-tstamp
plt.plot(set1[:, 0], set1[:, 1], '*',
set2[:, 0], set2[:, 1], '-',
projected_profile[:, 0], projected_profile[:, 1], 'x',
sp[0], sp[1], 'o')
plt.show()
コード central は、線形補間を使用して set2 の点によって定義される曲線上に set1 の点を投影します。