I have a real life problem. I have a segment representing a road that is defined by its geographic coordinates (let's call them p1_road_test and p2_road_test) and want to test whether it intersects with another set of segments (I gave all segments different coordinates to keep it simple) :
p1_road_test = np.array([1, 1]) # x, y value of point 1 of the road segment
p2_road_test = np.array([2, 4]) # x, y value of point 2 of the road segment
The other segments are defined by an original point (p_origin_test) and another point (p_moved_test) that describes to which position the original point has moved within a year:
p_origin_test = np.matrix([(3, 5, 6), (1, 1, 2)])
p_moved_test = np.matrix([(1,3, 3), (3, 3, 2)])
# basically, the original point (3, 1) moved to position (1, 3) and spans the segment accordingly. (5, 1) moves to (3, 3) etc.
p_origin_test
Out[46]:
matrix([[3, 5, 6],
[1, 1, 2]])
p_moved_test Out[47]:
matrix([[1, 3, 3],
[3, 3, 2]])
I chose a numpy matrix to store the data to speed up the calculation, since I have 30000+ segments I need to test against the street segment. In the end I would like to know if the second segment will ever intersect with the street segment when it continues to move at this "velocity" (the p_moved was surveyed after a month).
I followed this post to calculate if two segments intersect and derive their s and t value. So far so good.
X1, Y1 = p1_road_test[0], p1_road_test[1]
X2, Y2 = p2_road_test[0], p2_road_test[1]
#count = 0
Segment1 = ((X1, Y1), (X2, Y2))
for i in range(0, np.shape(p_origin_test)[1]):
X3, Y3 = p_origin_test[0, i], p_origin_test[1, i]
X4, Y4 = p_moved_test[0, i], p_moved_test[1, i]
Segment2 = ((X3, Y3), (X4, Y4))
dx1 = X2 - X1
dx2 = X4 - X3
dy1 = Y2 - Y1
dy2 = Y4 - Y3
det = dx1 * dy2 - dx2 * dy1
dx3 = X1 - X3
dy3 = Y1 - Y3
det1 = dx1 * dy3 - dx3 * dy1
det2 = dx2 * dy3 - dx3 * dy2
s = 3 / dx1
t = 1 / dx1
s = det1 / det
t = det2 / det
if s < 0.0 or s > 1.0 or t < 0.0 or t > 1.0:
print('false', s, t) # no intersect
else:
print(s, t)
which results in the anticipated output:
0.75 0.5
false 1.5 1.0
false 1.5555555555555556 0.3333333333333333
However, I would rather like to have another matrix as output with the same dimension as my input dataset (2, 30000) containing the s and t value since I will be needing it to further derive the "change per time unit". Also I know there is a more elegant way of doing this calculation than looping through the columns, but I can't figure it out.
I would really appreciate your input on this one.
I am working with Python 3.6.9 in Spyder3 on a Linux Mint 19.3.