Debian Codegraph @

third_party/spiro/curves/clothoid.py

raw symbols SCIP
1 from math import *
2 import cornu
3
4 def mod_2pi(th):
5 u = th / (2 * pi)
6 return 2 * pi * (u - floor(u + 0.5))
7
8 # Given clothoid k(s) = k0 + k1 s, compute th1 - th0 of chord from s = -.5
9 # to .5.
10 def compute_dth(k0, k1):
11 if k1 < 0:
12 return -compute_dth(k0, -k1)
13 elif k1 == 0:
14 return 0
15 sqrk1 = sqrt(2 * k1)
16 t0 = (k0 - .5 * k1) / sqrk1
17 t1 = (k0 + .5 * k1) / sqrk1
18 (y0, x0) = cornu.eval_cornu(t0)
19 (y1, x1) = cornu.eval_cornu(t1)
20 chord_th = atan2(y1 - y0, x1 - x0)
21 return mod_2pi(t1 * t1 - chord_th) - mod_2pi(chord_th - t0 * t0)
22
23 def compute_chord(k0, k1):
24 if k1 == 0:
25 if k0 == 0:
26 return 1
27 else:
28 return sin(k0 * .5) / (k0 * .5)
29 sqrk1 = sqrt(2 * abs(k1))
30 t0 = (k0 - .5 * k1) / sqrk1
31 t1 = (k0 + .5 * k1) / sqrk1
32 (y0, x0) = cornu.eval_cornu(t0)
33 (y1, x1) = cornu.eval_cornu(t1)
34 return hypot(y1 - y0, x1 - x0) / abs(t1 - t0)
35
36 # Given th0 and th1 at endpoints (measured from chord), return k0
37 # and k1 such that the clothoid k(s) = k0 + k1 s, evaluated from
38 # s = -.5 to .5, has the tangents given
39 def solve_clothoid(th0, th1, verbose = False):
40 k0 = th0 + th1
41
42 # initial guess
43 k1 = 6 * (th1 - th0)
44 error = (th1 - th0) - compute_dth(k0, k1)
45 if verbose:
46 print k0, k1, error
47
48 k1_old, error_old = k1, error
49 # second guess based on d(dth)/dk1 ~ 1/6
50 k1 += 6 * error
51 error = (th1 - th0) - compute_dth(k0, k1)
52 if verbose:
53 print k0, k1, error
54
55 # secant method
56 for i in range(10):
57 if abs(error) < 1e-9: break
58 k1_old, error_old, k1 = k1, error, k1 + (k1_old - k1) * error / (error - error_old)
59 error = (th1 - th0) - compute_dth(k0, k1)
60 if verbose:
61 print k0, k1, error
62
63 return k0, k1
64
65 if __name__ == '__main__':
66 print solve_clothoid(.06, .05, True)