chiark / gitweb /
helixish: debugging output
[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     vdbg().basis(dPQplane_basis)
65
66     dPQplane_into = np.linalg.inv(dPQplane_basis)
67     dbg(dPQplane_into)
68
69     p_plane_check = augmatmultiply(dPQplane_into, p)
70     dp_plane = augmatmultiply(dPQplane_into, dp, augwith=0)
71     dq_plane = augmatmultiply(dPQplane_into, dq, augwith=0)
72     q_plane  = augmatmultiply(dPQplane_into, q)
73     dist_pq_plane = np.linalg.norm(q_plane)
74
75     vdbg_plane = MatrixVisdebug(vdbg(), dPQplane_basis)
76
77     dbg('plane p', p_plane_check, 'dp', dp_plane, 'dq', dq_plane, 'q', q_plane)
78     vdbg_plane.arrow(p_plane_check, dp_plane)
79     vdbg_plane.arrow(q_plane,       dq_plane)
80
81     # two circular arcs of equal maximum possible radius
82     # algorithm courtesy of Simon Tatham (`Railway problem',
83     # pers.comm. to ijackson@chiark 23.1.2004)
84     railway_angleoffset = atan2(*q_plane[0:2])
85     railway_theta = atan2(*dp_plane[0:2]) - railway_angleoffset
86     railway_phi   = atan2(*dq_plane[0:2]) - railway_angleoffset
87     railway_cos_theta = cos(railway_theta)
88     railway_cos_phi   = cos(railway_phi)
89
90     railway_inplane_basis_x = np.hstack((q_plane[0:2], [0]))
91     railway_inplane_basis = np.column_stack((
92       railway_inplane_basis_x,
93       np.cross([0,0,1], railway_inplane_basis_x),
94       [0,0,1],
95       [0,0,0],
96     ))
97     #dbg('railway_inplane_basis\n', railway_inplane_basis)
98     railway_inplane_basis = np.vstack((railway_inplane_basis,
99                                        [0,0,0,1]))
100     dbg('railway_inplane_basis\n', railway_inplane_basis)
101     railway_basis = matmatmultiply(dPQplane_basis, railway_inplane_basis)
102     dbg('railway_basis\n', railway_basis)
103     vdbg().basis(railway_basis, hue=(1,0,1))
104     dbg('railway:', railway_theta, railway_phi, railway_angleoffset)
105
106     if railway_cos_theta**2 + railway_cos_phi**2 > 1E-6:
107       railway_roots = np.roots([
108         2 * (1 + cos(railway_theta - railway_phi)),
109         2 * (railway_cos_theta - railway_cos_phi),
110         -1
111         ])
112       for railway_r in railway_roots:
113         dbg(' twoarcs root r=',railway_r)
114
115         def railway_CPQ(pq, dpq, railway_r):
116           CPQ = pq + railway_r * np.array([-dpq[1], dpq[0]])
117           dbg('railway_CPQ', railway_r, pq, dpq, CPQ)
118           return CPQ
119
120         railway_CP = railway_CPQ([0,0],         dp_plane, railway_r)
121         railway_QP = railway_CPQ(q_plane[0:2], -dq_plane, railway_r)
122         railway_midpt = 0.5 * (railway_CP + railway_QP)
123
124         best_st = None
125         def railway_ST(C, start, end, railway_r):
126           delta = atan2(*(end - C)[0:2]) - atan2(*(start - C)[0:2])
127           s = delta * railway_r
128           dbg('railway_ST', C, start, end, railway_r, s)
129           return s
130
131         try_s = railway_ST(railway_CP, [0,0], railway_midpt, railway_r)
132         try_t = railway_ST(railway_CP, railway_midpt, q_plane[0:2], railway_r)
133         dbg('try_s, _t', try_s, try_t)
134         if try_s < 0 or try_t < 0:
135           continue
136
137         try_st = try_s + try_t
138         if best_st is None or try_st < best_st:
139           start_la = 1/railway_r
140           start_s = try_s
141           start_t = try_t
142           best_st = try_st
143           start_mu = q_plane[2] / (start_s + start_t)
144       dbg(' ok twoarcs')
145
146     else: # twoarcs algorithm is not well defined
147       dbg(' no twoarcs')
148       start_la = 0.1
149       start_s = dist_pq_plane * .65
150       start_t = dist_pq_plane * .35
151       start_mu = 0.05
152
153     bodge = max( q_plane[2] * start_mu,
154                  (start_s + start_t) * 0.1 )
155     start_s += 0.5 * bodge
156     start_t += 0.5 * bodge
157     start_kappa = 0
158     start_gamma = 1
159
160     tilt = atan(start_mu)
161     tilt_basis = np.array([
162       [ 1,     0,           0,         0 ],
163       [ 0,   cos(tilt),  sin(tilt),    0 ],
164       [ 0,  -sin(tilt),  cos(tilt),    0 ],
165       [ 0,     0,           0,         1 ],
166     ])
167     findcurve_basis = matmatmultiply(dPQplane_basis, tilt_basis)
168     findcurve_into = np.linalg.inv(findcurve_basis)
169
170     for ax in range(0,3):
171       vdbg().arrow(findcurve_basis[0:3,3], findcurve_basis[0:3,ax])
172
173     q_findcurve = augmatmultiply(findcurve_into, q)
174     dq_findcurve = augmatmultiply(findcurve_into, dq, augwith=0)
175
176     findcurve_target = np.hstack((q_findcurve, dq_findcurve))
177     findcurve_start = (sqrt(start_s), sqrt(start_t), start_la,
178                        start_mu, start_gamma, start_kappa)
179     
180     findcurve_epsilon = dist_pq_plane * 0.01
181
182     global findcurve_subproc
183     if findcurve_subproc is None:
184       dbg('STARTING FINDCURVE')
185       findcurve_subproc = subprocess.Popen(
186         ['./findcurve'],
187         bufsize=1,
188         stdin=subprocess.PIPE,
189         stdout=subprocess.PIPE,
190         stderr=None,
191         close_fds=False,
192         # restore_signals=True, // want python2 compat, nnng
193         universal_newlines=True,
194       )
195
196     findcurve_input = np.hstack((findcurve_target,
197                                  findcurve_start,
198                                  [findcurve_epsilon]))
199
200     def dbg_fmt_params(fcp):
201       return (('s=%10.7f t=%10.7f sh=%10.7f'
202                +' st=%10.7f la=%10.7f mu=%10.7f ga=%10.7f ka=%10.7f')
203               %
204               (( fcp[0]**2, fcp[1]**2 ) + tuple(fcp)))
205
206     #dbg('>> ' + ' '.join(map(str,findcurve_input)))
207
208     dbg(('RUNNING FINDCURVE' +
209          '                                             ' +
210          ' target Q=[%10.7f %10.7f %10.7f] dQ=[%10.7f %10.7f %10.7f]')
211         %
212         tuple(findcurve_input[0:6]))
213     dbg(('%s  initial') % dbg_fmt_params(findcurve_input[6:12]))
214
215     print(*findcurve_input, file=findcurve_subproc.stdin)
216     findcurve_subproc.stdin.flush()
217
218     hc.func = symbolic.get_python()
219     commentary = ''
220
221     while True:
222       l = findcurve_subproc.stdout.readline()
223       l = l.rstrip()
224       dbg('<< ', l)
225       if not l: vdbg().crashing('findcurve EOF')
226       if not l.startswith('['):
227         commentary += ' '
228         commentary += l
229         continue
230
231       l = eval(l)
232       if not l: break
233
234       dbg(('%s Q=[%10.7f %10.7f %10.7f] dQ=[%10.7f %10.7f %10.7f]%s')
235           %
236           (( dbg_fmt_params(l[0:6]), ) + tuple(l[6:12]) + (commentary,) ))
237       commentary = ''
238
239       hc.findcurve_result = l[0:6]
240       hc.threshold = l[0]**2
241       hc.total_dist = hc.threshold + l[1]**2
242       #vdbg().curve( hc.point_at_t )
243
244   def point_at_t(hc, normalised_parameter):
245     dist = normalised_parameter * hc.total_dist
246     ours = list(hc.findcurve_result)
247     if dist <= hc.threshold:
248       ours[0] = sqrt(dist)
249       ours[1] = 0
250     else:
251       ours[1] = sqrt(dist - hc.threshold)
252     asmat = hc.func(*ours)
253     p = asmat[:,0]
254     return p