chiark / gitweb /
more debugging
[moebius3.git] / helixish.py
1
2 from __future__ import print_function
3
4 import numpy as np
5 from numpy import cos, sin
6
7 import sys
8 import subprocess
9
10 from moedebug import *
11 from moenp import *
12
13 from math import atan2, atan, sqrt
14
15 import symbolic
16
17 findcurve_subproc = None
18
19 class HelixishCurve():
20   def __init__(hc, cp):
21     symbolic.calculate()
22
23     p = cp[0]
24     q = cp[3]
25     dp = unit_v(cp[1]-cp[0])
26     dq = unit_v(cp[3]-cp[2])
27
28     dbg('HelixishCurve __init__', cp)
29     dbg(dp, dq)
30
31     #vdbg().arrow(p,dp)
32     #vdbg().arrow(q,dq)
33
34     # the initial attempt
35     #   - solve in the plane containing dP and dQ
36     #   - total distance normal to that plane gives mu
37     #   - now resulting curve is not parallel to dP at P
38     #     nor dQ at Q, so tilt it
39     #   - [[ pick as the hinge point the half of the curve
40     #     with the larger s or t ]] not yet implemented
41     #   - increase the other distance {t,s} by a bodge factor
42     #     approx distance between {Q,P} and {Q,P}' due to hinging
43     #     but minimum is 10% of (wlog) {s,t} [[ not quite like this ]]
44
45     dPQplane_normal = np.cross(dp, dq)
46
47     if np.linalg.norm(dPQplane_normal) < 1E-6:
48       dbg('dPQplane_normal small')
49       dPQplane_normal = np.cross([1,0,0], dp)
50     if np.linalg.norm(dPQplane_normal) < 1E-6:
51       dbg('dPQplane_normal small again')
52       dPQplane_normal = np.cross([0,1,0], dp)
53
54     dPQplane_normal = unit_v(dPQplane_normal)
55
56     dPQplane_basis = np.column_stack((np.cross(dp, dPQplane_normal),
57                                       dp,
58                                       dPQplane_normal,
59                                       p));
60     #dbg(dPQplane_basis)
61     dPQplane_basis = np.vstack((dPQplane_basis, [0,0,0,1]))
62     dbg(dPQplane_basis)
63
64     #for ax in range(0,3):
65     #  vdbg().arrow(dPQplane_basis[0:3,3], dPQplane_basis[0:3,ax])
66
67     dPQplane_into = np.linalg.inv(dPQplane_basis)
68     dbg(dPQplane_into)
69
70     p_plane_check = augmatmultiply(dPQplane_into, p)
71     dp_plane = augmatmultiply(dPQplane_into, dp, augwith=0)
72     dq_plane = augmatmultiply(dPQplane_into, dq, augwith=0)
73     q_plane  = augmatmultiply(dPQplane_into, q)
74     dist_pq_plane = np.linalg.norm(q_plane)
75
76     vdbg_plane = MatrixVisdebug(vdbg(), dPQplane_basis)
77
78     dbg('plane:', p_plane_check, dp_plane, dq_plane, q_plane)
79     vdbg_plane.arrow(p_plane_check, dp_plane)
80     vdbg_plane.arrow(q_plane,       dq_plane)
81
82     # two circular arcs of equal maximum possible radius
83     # algorithm courtesy of Simon Tatham (`Railway problem',
84     # pers.comm. to ijackson@chiark 23.1.2004)
85     railway_angleoffset = atan2(*q_plane[0:2])
86     railway_theta =                      tau/4 - railway_angleoffset
87     railway_phi   = atan2(*dq_plane[0:2]) - railway_angleoffset
88     railway_cos_theta = cos(railway_theta)
89     railway_cos_phi   = cos(railway_phi)
90     if railway_cos_theta**2 + railway_cos_phi**2 > 1E6:
91       railway_roots = np.roots([
92         2 * (1 + cos(railway_theta - railway_phi)),
93         2 * (railway_cos_theta - railway_cos_phi),
94         -1
95         ])
96       for railway_r in railway_roots:
97         def railway_CPQ(pq, dpq, railway_r):
98           return pq + railway_r * [-dpq[1], dpq[0]]
99
100         railway_CP = railway_CPQ([0,0,0],       dp_plane, railway_r)
101         railway_QP = railway_CPQ(q_plane[0:2], -dq_plane, railway_r)
102         railway_midpt = 0.5 * (railway_CP + railway_QP)
103
104         best_st = None
105         def railway_ST(C, start, end, railway_r):
106           delta = atan2(*(end - C)[0:2]) - atan2(start - C)[0:2]
107           s = delta * railway_r
108
109         try_s = railway_ST(railway_CP, [0,0], midpt, railway_r)
110         try_t = railway_ST(railway_CP, midpt, q_plane, railway_r)
111         try_st = try_s + try_t
112         if best_st is None or try_st < best_st:
113           start_la = 1/r
114           start_s = try_s
115           start_t = try_t
116           best_st = try_st
117           start_mu = q_plane[2] / (start_s + start_t)
118       dbg(' ok twoarcs')
119
120     else: # twoarcs algorithm is not well defined
121       dbg(' no twoarcs')
122       start_la = 0.1
123       start_s = dist_pq_plane * .65
124       start_t = dist_pq_plane * .35
125       start_mu = 0.05
126
127     bodge = max( q_plane[2] * start_mu,
128                  (start_s + start_t) * 0.1 )
129     start_s += 0.5 * bodge
130     start_t += 0.5 * bodge
131     start_kappa = 0
132     start_gamma = 1
133
134     tilt = atan(start_mu)
135     tilt_basis = np.array([
136       [ 1,     0,           0,         0 ],
137       [ 0,   cos(tilt),  sin(tilt),    0 ],
138       [ 0,  -sin(tilt),  cos(tilt),    0 ],
139       [ 0,     0,           0,         1 ],
140     ])
141     findcurve_basis = matmatmultiply(dPQplane_basis, tilt_basis)
142     findcurve_into = np.linalg.inv(findcurve_basis)
143
144     q_findcurve = augmatmultiply(findcurve_into, q)
145     dq_findcurve = augmatmultiply(findcurve_into, dq, augwith=0)
146
147     findcurve_target = np.hstack((q_findcurve, dq_findcurve))
148     findcurve_start = (sqrt(start_s), sqrt(start_t), start_la,
149                        start_mu, start_gamma, start_kappa)
150     
151     findcurve_epsilon = dist_pq_plane * 0.01
152
153     global findcurve_subproc
154     if findcurve_subproc is None:
155       dbg('STARTING FINDCURVE')
156       findcurve_subproc = subprocess.Popen(
157         ['./findcurve'],
158         bufsize=1,
159         stdin=subprocess.PIPE,
160         stdout=subprocess.PIPE,
161         stderr=None,
162         close_fds=False,
163         # restore_signals=True, // want python2 compat, nnng
164         universal_newlines=True,
165       )
166
167     findcurve_input = np.hstack((findcurve_target,
168                                  findcurve_start,
169                                  [findcurve_epsilon]))
170
171     def dbg_fmt_params(fcp):
172       return (('s=%10.7f t=%10.7f sh=%10.7f'
173                +' st=%10.7f la=%10.7f mu=%10.7f ga=%10.7f ka=%10.7f')
174               %
175               (( fcp[0]**2, fcp[1]**2 ) + tuple(fcp)))
176
177     #dbg('>> ' + ' '.join(map(str,findcurve_input)))
178
179     dbg(('RUNNING FINDCURVE' +
180          '                                             ' +
181          ' target Q=[%10.7f %10.7f %10.7f] dQ=[%10.7f %10.7f %10.7f]')
182         %
183         tuple(findcurve_input[0:6]))
184     dbg(('%s  initial') % dbg_fmt_params(findcurve_input[6:12]))
185
186     print(*findcurve_input, file=findcurve_subproc.stdin)
187     findcurve_subproc.stdin.flush()
188
189     hc.func = symbolic.get_python()
190     commentary = ''
191
192     while True:
193       l = findcurve_subproc.stdout.readline()
194       l = l.rstrip()
195       dbg('<< ', l)
196       if not l: vdbg().crashing('findcurve EOF')
197       if not l.startswith('['):
198         commentary += ' '
199         commentary += l
200         continue
201
202       l = eval(l)
203       if not l: break
204
205       dbg(('%s Q=[%10.7f %10.7f %10.7f] dQ=[%10.7f %10.7f %10.7f]%s')
206           %
207           (( dbg_fmt_params(l[0:6]), ) + tuple(l[6:12]) + (commentary,) ))
208       commentary = ''
209
210       hc.findcurve_result = l[0:6]
211       hc.threshold = l[0]**2
212       hc.total_dist = hc.threshold + l[1]**2
213       #vdbg().curve( hc.point_at_t )
214
215   def point_at_t(hc, normalised_parameter):
216     dist = normalised_parameter * hc.total_dist
217     ours = list(hc.findcurve_result)
218     if dist <= hc.threshold:
219       ours[0] = sqrt(dist)
220       ours[1] = 0
221     else:
222       ours[1] = sqrt(dist - hc.threshold)
223     asmat = hc.func(*ours)
224     p = asmat[:,0]
225     return p