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