chiark / gitweb /
helixish: bugfixes
[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 dbg
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):
95           nonlocal railway_r
96           return pq + railway_r * [-dpq[1], dpq[0]]
97
98         railway_CP = railway_CPQ([0,0,0],       dp_plane)
99         railway_QP = railway_CPQ(q_plane[0:2], -dq_plane)
100         railway_midpt = 0.5 * (railway_CP + railway_QP)
101
102         best_st = None
103         def railway_ST(C, start, end):
104           nonlocal 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)
109         try_t = railway_ST(railway_CP, midpt, q_plane)
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
118     else: # twoarcs algorithm is not well defined
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,
161         universal_newlines=True,
162       )
163
164     findcurve_input = np.hstack((findcurve_target,
165                                  findcurve_start,
166                                  [findcurve_epsilon]))
167     dbg('RUNNING FINDCURVE', *findcurve_input)
168     print(*findcurve_input, file=findcurve_subproc.stdin)
169     findcurve_subproc.stdin.flush()
170
171     while True:
172       l = findcurve_subproc.stdout.readline()
173       l = l.rstrip()
174       dbg('GOT ', l)
175       l = eval(l)
176       if l is None: break
177
178     hc.findcurve_result = l[0:5]
179     hc.func = symbolic.get_python(something)
180     hc.threshold = l[0]**2
181     hc.total_dist = hc.threshold + l[1]**2
182
183   def point_at_t(hc, normalised_parameter):
184     dist = normalised_parameter * hc.total_dist
185     ours = [p for p in findcurve_result]
186     if dist <= hc.threshold:
187       ours[0] = sqrt(dist)
188       ours[1] = 0
189     else:
190       ours[1] = sqrt(dist - hc.threshold)
191     return hc.func(*ours)