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