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