chiark / gitweb /
helixish: fixes
[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, 1)
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
81     dp_plane = augmatmultiply(dPQplane_into, dp, augwith=0)
82     dq_plane = augmatmultiply(dPQplane_into, dq, augwith=0)
83     q_plane  = augmatmultiply(dPQplane_into, q)
84     dist_pq_plane = np.linalg.norm(q_plane)
85
86     # two circular arcs of equal maximum possible radius
87     # algorithm courtesy of Simon Tatham (`Railway problem',
88     # pers.comm. to ijackson@chiark 23.1.2004)
89     railway_angleoffset = atan2(*q_plane[0:2])
90     railway_theta =                      tau/4 - railway_angleoffset
91     railway_phi   = atan2(*dq_plane[0:2]) - railway_angleoffset
92     railway_cos_theta = cos(railway_theta)
93     railway_cos_phi   = cos(railway_phi)
94     if railway_cos_theta**2 + railway_cos_phi**2 > 1E6:
95       railway_roots = np.roots([
96         2 * (1 + cos(railway_theta - railway_phi)),
97         2 * (railway_cos_theta - railway_cos_phi),
98         -1
99         ])
100       for railway_r in railway_roots:
101         def railway_CPQ(pq, dpq, railway_r):
102           return pq + railway_r * [-dpq[1], dpq[0]]
103
104         railway_CP = railway_CPQ([0,0,0],       dp_plane, railway_r)
105         railway_QP = railway_CPQ(q_plane[0:2], -dq_plane, railway_r)
106         railway_midpt = 0.5 * (railway_CP + railway_QP)
107
108         best_st = None
109         def railway_ST(C, start, end, railway_r):
110           delta = atan2(*(end - C)[0:2]) - atan2(start - C)[0:2]
111           s = delta * railway_r
112
113         try_s = railway_ST(railway_CP, [0,0], midpt, railway_r)
114         try_t = railway_ST(railway_CP, midpt, q_plane, railway_r)
115         try_st = try_s + try_t
116         if best_st is None or try_st < best_st:
117           start_la = 1/r
118           start_s = try_s
119           start_t = try_t
120           best_st = try_st
121           start_mu = q_plane[2] / (start_s + start_t)
122       dbg(' ok twoarcs')
123
124     else: # twoarcs algorithm is not well defined
125       dbg(' no twoarcs')
126       start_la = 0.1
127       start_s = dist_pq_plane * .65
128       start_t = dist_pq_plane * .35
129       start_mu = 0.05
130
131     bodge = max( q_plane[2] * start_mu,
132                  (start_s + start_t) * 0.1 )
133     start_s += 0.5 * bodge
134     start_t += 0.5 * bodge
135     start_kappa = 0
136     start_gamma = 1
137
138     tilt = atan(start_mu)
139     tilt_basis = np.array([
140       [ 1,     0,           0,         0 ],
141       [ 0,   cos(tilt), -sin(tilt),    0 ],
142       [ 0,   sin(tilt),  cos(tilt),    0 ],
143       [ 0,     0,           0,         1 ],
144     ])
145     findcurve_basis = matmatmultiply(dPQplane_basis, tilt_basis)
146     findcurve_into = np.linalg.inv(findcurve_basis)
147
148     q_findcurve = augmatmultiply(findcurve_into, q)
149     dq_findcurve = augmatmultiply(findcurve_into, dq, augwith=0)
150
151     findcurve_target = np.hstack((q_findcurve, dq_findcurve))
152     findcurve_start = (sqrt(start_s), sqrt(start_t), start_la,
153                        start_mu, start_gamma, start_kappa)
154     
155     findcurve_epsilon = dist_pq_plane * 0.01
156
157     global findcurve_subproc
158     if findcurve_subproc is None:
159       dbg('STARTING FINDCURVE')
160       findcurve_subproc = subprocess.Popen(
161         ['./findcurve'],
162         bufsize=1,
163         stdin=subprocess.PIPE,
164         stdout=subprocess.PIPE,
165         stderr=None,
166         close_fds=False,
167         # restore_signals=True, // want python2 compat, nnng
168         universal_newlines=True,
169       )
170
171     findcurve_input = np.hstack((findcurve_target,
172                                  findcurve_start,
173                                  [findcurve_epsilon]))
174
175     dbg(('RUNNING FINDCURVE                           ' +
176          ' target Q=[%5.2f %5.2f %5.2f] dQ=[%5.2f %5.2f %5.2f]')
177         %
178         tuple(findcurve_input[0:6]))
179     dbg(('s=%5.2f t=%5.2f la=%5.2f mu=%5.2f ga=%5.2f ka=%5.2f  initial')
180         %
181         (( findcurve_input[6]**2, findcurve_input[7]**2 ) +
182          tuple(findcurve_input[8:12])))
183
184     print(*findcurve_input, file=findcurve_subproc.stdin)
185     findcurve_subproc.stdin.flush()
186
187     hc.func = symbolic.get_python()
188
189     while True:
190       l = findcurve_subproc.stdout.readline()
191       l = l.rstrip()
192       #dbg('GOT ', l)
193       if not l: vdbg().crashing('findcurve EOF')
194       l = eval(l)
195       if l is None: break
196
197       dbg(('s=%5.2f t=%5.2f la=%5.2f mu=%5.2f ga=%5.2f ka=%5.2f' +
198            ' Q=[%5.2f %5.2f %5.2f] dQ=[%5.2f %5.2f %5.2f]')
199           %
200           (( l[0]**2, l[1]**2 ) + tuple(l[2:12])))
201
202       hc.findcurve_result = l[0:6]
203       hc.threshold = l[0]**2
204       hc.total_dist = hc.threshold + l[1]**2
205       vdbg().curve( hc.point_at_t )
206
207   def point_at_t(hc, normalised_parameter):
208     dist = normalised_parameter * hc.total_dist
209     ours = list(hc.findcurve_result)
210     if dist <= hc.threshold:
211       ours[0] = sqrt(dist)
212       ours[1] = 0
213     else:
214       ours[1] = sqrt(dist - hc.threshold)
215     asmat = hc.func(*ours)
216     p = asmat[:,0]
217     return p