chiark / gitweb /
python2 compat for helixish
[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, 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
116     else: # twoarcs algorithm is not well defined
117       start_la = 0.1
118       start_s = dist_pq_plane * .65
119       start_t = dist_pq_plane * .35
120       start_mu = 0.05
121
122     bodge = max( q_plane[2] * start_mu,
123                  (start_s + start_t) * 0.1 )
124     start_s += 0.5 * bodge
125     start_t += 0.5 * bodge
126     start_kappa = 0
127     start_gamma = 1
128
129     tilt = atan(start_mu)
130     tilt_basis = np.array([
131       [ 1,     0,           0,         0 ],
132       [ 0,   cos(tilt), -sin(tilt),    0 ],
133       [ 0,   sin(tilt),  cos(tilt),    0 ],
134       [ 0,     0,           0,         1 ],
135     ])
136     findcurve_basis = matmatmultiply(dPQplane_basis, tilt_basis)
137     findcurve_into = np.linalg.inv(findcurve_basis)
138
139     q_findcurve = augmatmultiply(findcurve_into, q)
140     dq_findcurve = augmatmultiply(findcurve_into, dq, augwith=0)
141
142     findcurve_target = np.hstack((q_findcurve, dq_findcurve))
143     findcurve_start = (sqrt(start_s), sqrt(start_t), start_la,
144                        start_mu, start_gamma, start_kappa)
145     
146     findcurve_epsilon = dist_pq_plane * 0.01
147
148     global findcurve_subproc
149     if findcurve_subproc is None:
150       dbg('STARTING FINDCURVE')
151       findcurve_subproc = subprocess.Popen(
152         ['./findcurve'],
153         bufsize=1,
154         stdin=subprocess.PIPE,
155         stdout=subprocess.PIPE,
156         stderr=None,
157         close_fds=False,
158         # restore_signals=True, // want python2 compat, nnng
159         universal_newlines=True,
160       )
161
162     findcurve_input = np.hstack((findcurve_target,
163                                  findcurve_start,
164                                  [findcurve_epsilon]))
165     dbg('RUNNING FINDCURVE', *findcurve_input)
166     print(*findcurve_input, file=findcurve_subproc.stdin)
167     findcurve_subproc.stdin.flush()
168
169     while True:
170       l = findcurve_subproc.stdout.readline()
171       l = l.rstrip()
172       dbg('GOT ', l)
173       l = eval(l)
174       if l is None: break
175
176     hc.findcurve_result = l[0:5]
177     hc.func = symbolic.get_python(something)
178     hc.threshold = l[0]**2
179     hc.total_dist = hc.threshold + l[1]**2
180
181   def point_at_t(hc, normalised_parameter):
182     dist = normalised_parameter * hc.total_dist
183     ours = [p for p in findcurve_result]
184     if dist <= hc.threshold:
185       ours[0] = sqrt(dist)
186       ours[1] = 0
187     else:
188       ours[1] = sqrt(dist - hc.threshold)
189     return hc.func(*ours)