Mercurial Hosting > traffic-intelligence
changeset 24:6fb59cfb201e
first version of segmentIntersection
author | Nicolas Saunier <nico@confins.net> |
---|---|
date | Sat, 05 Dec 2009 11:04:03 -0500 |
parents | 5f2921ad4f7e |
children | 28e546861263 |
files | python/utils.py |
diffstat | 1 files changed, 40 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/python/utils.py Fri Dec 04 13:47:22 2009 -0500 +++ b/python/utils.py Sat Dec 05 11:04:03 2009 -0500 @@ -8,6 +8,46 @@ commentChar = '#'; +# maths + +def segmentIntersection(s1, s2): + '''Returns the intersecting point, None otherwise + format for a segment is [[x1, x2], [y1,y2]] + + >>> segmentIntersection([[0, 1], [0,1]], [[0, 1], [1,2]]) + >>> segmentIntersection([[0, 1], [1,0]], [[0, 1], [2,1]]) + >>> segmentIntersection([[0, 2], [0,0]], [[1, 1], [-1,1]]) + [1.0, 0.0] + >>> segmentIntersection([[0, 2], [0,0]], [[1, 1], [1,2]]) + ''' + from numpy import matrix + from numpy.linalg import linalg, det + + ds1 = [s1[0][1]-s1[0][0], s1[1][1]-s1[1][0]] + ds2 = [s2[0][1]-s2[0][0], s2[1][1]-s2[1][0]] + + A = matrix([[ds1[1], -ds1[0]], + [ds2[1], -ds2[0]]]) + B = matrix([[ds1[1]*s1[0][0]-ds1[0]*s1[1][0]], + [ds2[1]*s2[0][0]-ds2[0]*s2[1][0]]]) + + if linalg.det(A) == 0:#crossProduct(ds1, ds2) == 0: + return None + else: + intersection = linalg.solve(A,B) + if (intersection[0,0] >= s1[0][0] and intersection[0,0] <= s1[0][1] + and intersection[0,0] >= s2[0][0] and intersection[0,0] <= s2[0][1] + and intersection[1,0] >= s1[1][0] and intersection[1,0] <= s1[1][1] + and intersection[1,0] >= s2[1][0] and intersection[1,0] <= s2[1][1]): + return [intersection[0,0], intersection[1,0]] + else: + return None + +def crossProduct(l1, l2): + return l1[0]*l2[1]-l1[1]*l2[0] + +# file I/O + def openCheck(filename, option = 'r', quit = False): '''Open file filename in read mode by default and checks it is open