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