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