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