chiark / gitweb /
helixish: Introduce matmultiply and augmatmultiply
[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 from moedebug import dbg
9 from moenp import *
10
11 from math import atan2
12
13 import symbolic
14
15 def augment(v): return np.append(v, 1)
16 def augment0(v): return np.append(v, 0)
17 def unaugment(v): return v[0:3]
18
19 def matmultiply(mat,vect):
20   # both are "array"s
21   # we would prefer to write   mat @ vect
22   # but that doesn't work in Python 2
23   return np.array((vect * np.matrix(mat).T))[0,:]
24
25 def augmatmultiply(mat,unaugvect):
26   return unaugment(matmultiply(mat, augment(unaugvect)))
27
28 findcurve_subproc = None
29
30 class HelixishCurve():
31   def __init__(hc, cp):
32     symbolic.calculate()
33
34     p = cp[0]
35     q = cp[3]
36     dp = unit_v(cp[1]-cp[0])
37     dq = unit_v(cp[3]-cp[2])
38
39     dbg('HelixishCurve __init__', cp)
40
41     # the initial attempt
42     #   - solve in the plane containing dP and dQ
43     #   - total distance normal to that plane gives mu
44     #   - now resulting curve is not parallel to dP at P
45     #     nor dQ at Q, so tilt it
46     #   - [[ pick as the hinge point the half of the curve
47     #     with the larger s or t ]] not yet implemented
48     #   - increase the other distance {t,s} by a bodge factor
49     #     approx distance between {Q,P} and {Q,P}' due to hinging
50     #     but minimum is 10% of (wlog) {s,t} [[ not quite like this ]]
51
52     dPQplane_normal = np.cross(dp, dq)
53     if (np.linalg.norm(dPQplane_normal) < 1E6):
54       dPQplane_normal += [0, 0, 1E5]
55     dPQplane_normal = unit_v(dPQplane_normal)
56
57     dPQplane_basis = np.column_stack((np.cross(dp, dPQplane_normal),
58                                       dp,
59                                       dPQplane_normal,
60                                       p));
61     dbg(dPQplane_basis)
62     dPQplane_basis = np.vstack((dPQplane_basis, [0,0,0,1]))
63     dbg(dPQplane_basis)
64     dPQplane_into = np.linalg.inv(dPQplane_basis)
65
66     dp_plane = augmatmultiply(dPQplane_into, dp)
67     dq_plane = augmatmultiply(dPQplane_into, dq)
68     q_plane  = augmatmultiply(dPQplane_into, q)
69     dist_pq_plane = np.linalg.norm(q_plane)
70
71     # two circular arcs of equal maximum possible radius
72     # algorithm courtesy of Simon Tatham (`Railway problem',
73     # pers.comm. to ijackson@chiark 23.1.2004)
74     railway_angleoffset = atan2(*q_plane[0:2])
75     railway_theta =                      tau/4 - railway_angleoffset
76     railway_phi   = atan2(*dq_plane[0:2]) - railway_angleoffset
77     railway_cos_theta = cos(railway_theta)
78     railway_cos_phi   = cos(railway_phi)
79     if railway_cos_theta**2 + railway_cos_phi**2 > 1E6:
80       railway_roots = np.roots([
81         2 * (1 + cos(railway_theta - railway_phi)),
82         2 * (railway_cos_theta - railway_cos_phi),
83         -1
84         ])
85       for railway_r in railway_roots:
86         def railway_CPQ(pq, dpq):
87           nonlocal railway_r
88           return pq + railway_r * [-dpq[1], dpq[0]]
89
90         railway_CP = railway_CPQ([0,0,0],       dp_plane)
91         railway_QP = railway_CPQ(q_plane[0:2], -dq_plane)
92         railway_midpt = 0.5 * (railway_CP + railway_QP)
93
94         best_st = None
95         def railway_ST(C, start, end):
96           nonlocal railway_r
97           delta = atan2(*(end - C)[0:2]) - atan2(start - C)[0:2]
98           s = delta * railway_r
99
100         try_s = railway_ST(railway_CP, [0,0], midpt)
101         try_t = railway_ST(railway_CP, midpt, q_plane)
102         try_st = try_s + try_t
103         if best_st is None or try_st < best_st:
104           start_la = 1/r
105           start_s = try_s
106           start_t = try_t
107           best_st = try_st
108           start_mu = q_plane[2] / (start_s + start_t)
109
110     else: # twoarcs algorithm is not well defined
111       start_la = 0.1
112       start_s = dist_pq_plane * .65
113       start_t = dist_pq_plane * .35
114       start_mu = 0.05
115
116     bodge = max( q_plane[2] * mu,
117                  (start_s + start_t) * 0.1 )
118     start_s += 0.5 * bodge
119     start_t += 0.5 * bodge
120     start_kappa = 0
121     start_gamma = 1
122
123     tilt = atan(mu)
124     tilt_basis = np.array([
125       1,     0,           0,         0,
126       0,   cos(tilt), -sin(tilt),    0,
127       0,   sin(tilt),  cos(tilt),    0,
128       0,     0,           0,         1,
129     ])
130     findcurve_basis = augmatmultiply(dPQplane_basis, tilt_basis)
131     findcurve_into = np.linalg.inv(findcurve_basis)
132
133     q_findcurve = unaugment(findcurve_into, augment(q))
134     dq_findcurve = unaugment(findcurve_into, augment0(dq))
135
136     findcurve_target = np.concatenate(q_findcurve, dq_findcurve)
137     findcurve_start = (sqrt(start_s), sqrt(start_t), start_la,
138                        start_mu, start_gamma, start_kappa)
139     
140     findcurve_epsilon = dist_pq_plane * 0.01
141
142     if findcurve_subproc is None:
143       findcurve_subproc = subprocess.Popen(
144         ['./findcurve'],
145         bufsize=1,
146         stdin=subprocess.PIPE,
147         stdout=subprocess.PIPE,
148         stderr=None,
149         close_fds=False,
150         restore_signals=True,
151         universal_newlines=True,
152       )
153
154     findcurve_input = np.hstack((findcurve_target,
155                                  findcurve_start,
156                                  [findcurve_epsilon]))
157     dbg('RUNNING FINDCURVE', *findcurve_input)
158     print(findcurve_subproc.stdin, *findcurve_input)
159     findcurve_subproc.stdin.flush()
160
161     while True:
162       l = findcurve_subproc.stdout.readline()
163       l = l.rstrip()
164       dbg('GOT ', l)
165       l = eval(l)
166       if l is None: break
167
168     hc.findcurve_result = l[0:5]
169     hc.func = symbolic.get_python(something)
170     hc.threshold = l[0]**2
171     hc.total_dist = hc.threshold + l[1]**2
172
173   def point_at_t(hc, normalised_parameter):
174     dist = normalised_parameter * hc.total_dist
175     ours = [p for p in findcurve_result]
176     if dist <= hc.threshold:
177       ours[0] = sqrt(dist)
178       ours[1] = 0
179     else:
180       ours[1] = sqrt(dist - hc.threshold)
181     return hc.func(*ours)