chiark / gitweb /
helixish: remember to transform back from findcurve basis (!)
[moebius3.git] / helixish.py
index 850b225985874f5835489b0f6cb35ab6a8cb502e..27485eac5e965293e7311976f39466fef807ca08 100644 (file)
@@ -5,26 +5,15 @@ import numpy as np
 from numpy import cos, sin
 
 import sys
-from moedebug import dbg
+import subprocess
+
+from moedebug import *
 from moenp import *
 
-from math import atan2
+from math import atan2, atan, sqrt
 
 import symbolic
 
-def augment(v): return np.append(v, 1)
-def augment0(v): return np.append(v, 0)
-def unaugment(v): return v[0:3]
-
-def matmultiply(mat,vect):
-  # both are "array"s
-  # we would prefer to write   mat @ vect
-  # but that doesn't work in Python 2
-  return np.array((vect * np.matrix(mat).T))[0,:]
-
-def augmatmultiply(mat,unaugvect):
-  return unaugment(matmultiply(mat, augment(unaugvect)))
-
 findcurve_subproc = None
 
 class HelixishCurve():
@@ -37,6 +26,10 @@ class HelixishCurve():
     dq = unit_v(cp[3]-cp[2])
 
     dbg('HelixishCurve __init__', cp)
+    dbg(dp, dq)
+
+    #vdbg().arrow(p,dp)
+    #vdbg().arrow(q,dq)
 
     # the initial attempt
     #   - solve in the plane containing dP and dQ
@@ -50,96 +43,181 @@ class HelixishCurve():
     #     but minimum is 10% of (wlog) {s,t} [[ not quite like this ]]
 
     dPQplane_normal = np.cross(dp, dq)
-    if (np.linalg.norm(dPQplane_normal) < 1E6):
-      dPQplane_normal += [0, 0, 1E5]
+
+    if np.linalg.norm(dPQplane_normal) < 1E-6:
+      dbg('dPQplane_normal small')
+      dPQplane_normal = np.cross([1,0,0], dp)
+    if np.linalg.norm(dPQplane_normal) < 1E-6:
+      dbg('dPQplane_normal small again')
+      dPQplane_normal = np.cross([0,1,0], dp)
+
     dPQplane_normal = unit_v(dPQplane_normal)
 
+    vdbg().arrow([0,0,0], dPQplane_normal, color=(1,1,0))
+
     dPQplane_basis = np.column_stack((np.cross(dp, dPQplane_normal),
                                       dp,
                                       dPQplane_normal,
                                       p));
-    dbg(dPQplane_basis)
+    #dbg(dPQplane_basis)
     dPQplane_basis = np.vstack((dPQplane_basis, [0,0,0,1]))
     dbg(dPQplane_basis)
+    
+    vdbg().basis(dPQplane_basis)
+
     dPQplane_into = np.linalg.inv(dPQplane_basis)
+    dbg(dPQplane_into)
 
-    dp_plane = augmatmultiply(dPQplane_into, dp)
-    dq_plane = augmatmultiply(dPQplane_into, dq)
+    p_plane_check = augmatmultiply(dPQplane_into, p)
+    dp_plane = augmatmultiply(dPQplane_into, dp, augwith=0)
+    dq_plane = augmatmultiply(dPQplane_into, dq, augwith=0)
     q_plane  = augmatmultiply(dPQplane_into, q)
-    dist_pq_plane = np.linalg.norm(q_plane)
+    dist_pq_plane = np.linalg.norm(q_plane[0:2])
+
+    vdbg_plane = MatrixVisdebug(vdbg(), dPQplane_basis)
+
+    dbg('plane p', p_plane_check, 'dp', dp_plane, 'dq', dq_plane,
+        'q', q_plane, 'dist_pq_plane', dist_pq_plane)
+    vdbg_plane.arrow(p_plane_check, dp_plane)
+    vdbg_plane.arrow(q_plane,       dq_plane)
+
+    railway_inplane_basis_x = np.hstack((q_plane[0:2], [0]))
+    railway_inplane_basis = np.column_stack((
+      railway_inplane_basis_x,
+      -np.cross([0,0,1], railway_inplane_basis_x),
+      [0,0,1],
+      [0,0,0],
+    ))
+    #dbg('railway_inplane_basis\n', railway_inplane_basis)
+    railway_inplane_basis = np.vstack((railway_inplane_basis,
+                                       [0,0,0,1]))
+    dbg('railway_inplane_basis\n', railway_inplane_basis)
+    railway_basis = matmatmultiply(dPQplane_basis, railway_inplane_basis)
+    dbg('railway_basis\n', railway_basis)
+    vdbg().basis(railway_basis, hue=(1,0,1))
+    vdbg_railway = MatrixVisdebug(vdbg(), railway_basis)
 
     # two circular arcs of equal maximum possible radius
     # algorithm courtesy of Simon Tatham (`Railway problem',
     # pers.comm. to ijackson@chiark 23.1.2004)
     railway_angleoffset = atan2(*q_plane[0:2])
-    railway_theta =                      tau/4 - railway_angleoffset
-    railway_phi   = atan2(*dq_plane[0:2]) - railway_angleoffset
+    # these two angles are unconventional: clockwise from north
+    railway_theta = tau/4 - (atan2(*dp_plane[0:2]) - railway_angleoffset)
+    railway_phi   = tau/4 - (atan2(*-dq_plane[0:2]) - railway_angleoffset)
     railway_cos_theta = cos(railway_theta)
     railway_cos_phi   = cos(railway_phi)
-    if railway_cos_theta**2 + railway_cos_phi**2 > 1E6:
-      railway_roots = np.roots([
+
+    dbg('railway:', railway_theta, railway_phi, railway_angleoffset)
+
+    def vdbg_railway_angle(start, angle, **kw):
+      vdbg_railway.arrow(start, [sin(angle), cos(angle), 0], **kw)
+    vdbg_railway_angle([0, 0, 0.1], railway_theta, color=(1, 0.5, 0))
+    vdbg_railway_angle([1, 0, 0.1], railway_phi,   color=(1, 0.5, 0))
+    vdbg_railway_angle([1, 0, 0.1], 0,             color=(1, 1.00, 0))
+    vdbg_railway_angle([1, 0, 0.1], tau/4,         color=(1, 0.75, 0))
+
+    if railway_cos_theta**2 + railway_cos_phi**2 > 1E-6:
+      railway_polynomial = [
         2 * (1 + cos(railway_theta - railway_phi)),
         2 * (railway_cos_theta - railway_cos_phi),
-        -1
-        ])
-      for railway_r in railway_roots:
-        def railway_CPQ(pq, dpq):
-          nonlocal railway_r
-          return pq + railway_r * [-dpq[1], dpq[0]]
-
-        railway_CP = railway_CPQ([0,0,0],       dp_plane)
-        railway_QP = railway_CPQ(q_plane[0:2], -dq_plane)
+        -1,
+        ]
+      railway_roots = np.roots(railway_polynomial)
+      dbg('railway poly, roots:', railway_polynomial, railway_roots)
+
+      #vdbg_railway.circle([0,0,0], [0,0, dist_pq_plane], color=(.5,0,0))
+      #vdbg_railway.circle([1,0,0], [0,0, 0.05], color=(.5,0,0))
+      #vdbg().circle(p, dPQplane_normal * dist_pq_plane, color=(.5,.5,0))
+
+      for railway_r_pq1 in railway_roots:
+        # roots for r are calculated based on coordinates where
+        # Q is at (1,0) but our PQ distance is different
+        railway_r = railway_r_pq1 * dist_pq_plane
+        dbg(' twoarcs root r_pq1=', railway_r_pq1, 'r=',railway_r,
+            railway_polynomial[0] * railway_r_pq1 * railway_r_pq1 +
+            railway_polynomial[1] * railway_r_pq1                 +
+            railway_polynomial[2]
+        )
+
+        vdbg_railway.circle([0,0,0], [0,0, railway_r], color=(1,0,0))
+        #vdbg().circle(p, dPQplane_normal * railway_r, color=(1,1,0))
+
+        def railway_CPQ(pq, dpq, railway_r):
+          CPQ = pq + railway_r * np.array([-dpq[1], dpq[0]])
+          dbg('railway_CPQ', railway_r, pq, dpq, CPQ)
+          vdbg_plane.circle( np.hstack((CPQ, [0])),
+                             [0, 0, railway_r],
+                             color = (1,1,1) )
+          #vdbg_plane.circle( np.hstack(( 2*np.asarray(pq) - CPQ, [0])),
+          #                   [0, 0, railway_r],
+          #                   color = (.5,.5,.5) )
+          return CPQ
+
+        railway_CP = railway_CPQ([0,0],         dp_plane, railway_r)
+        railway_QP = railway_CPQ(q_plane[0:2], -dq_plane, railway_r)
         railway_midpt = 0.5 * (railway_CP + railway_QP)
 
         best_st = None
-        def railway_ST(C, start, end):
-          nonlocal railway_r
-          delta = atan2(*(end - C)[0:2]) - atan2(start - C)[0:2]
+        def railway_ST(C, start, end, railway_r):
+          delta = atan2(*(end - C)[0:2]) - atan2(*(start - C)[0:2])
+          dbg('railway_ST C', C, 'start', start, 'end', end, 'delta', delta)
+          if delta < 0: delta += tau
           s = delta * railway_r
+          dbg('railway_ST delta', delta, 'r', railway_r, 's', s)
+          return s
+
+        try_s = railway_ST(railway_CP, [0,0], railway_midpt, railway_r)
+        try_t = railway_ST(railway_CP, railway_midpt, q_plane[0:2], railway_r)
+        dbg('try_s, _t', try_s, try_t)
 
-        try_s = railway_ST(railway_CP, [0,0], midpt)
-        try_t = railway_ST(railway_CP, midpt, q_plane)
         try_st = try_s + try_t
         if best_st is None or try_st < best_st:
-          start_la = 1/r
+          start_la = 1/railway_r
           start_s = try_s
           start_t = try_t
           best_st = try_st
           start_mu = q_plane[2] / (start_s + start_t)
+      dbg(' ok twoarcs')
 
     else: # twoarcs algorithm is not well defined
+      dbg(' no twoarcs')
       start_la = 0.1
       start_s = dist_pq_plane * .65
       start_t = dist_pq_plane * .35
       start_mu = 0.05
 
-    bodge = max( q_plane[2] * mu,
+    bodge = max( q_plane[2] * start_mu,
                  (start_s + start_t) * 0.1 )
     start_s += 0.5 * bodge
     start_t += 0.5 * bodge
     start_kappa = 0
     start_gamma = 1
 
-    tilt = atan(mu)
+    tilt = atan(start_mu)
     tilt_basis = np.array([
-      1,     0,           0,         0,
-      0,   cos(tilt), -sin(tilt),    0,
-      0,   sin(tilt),  cos(tilt),    0,
-      0,     0,           0,         1,
+      [ 1,     0,           0,         0 ],
+      [ 0,   cos(tilt),  sin(tilt),    0 ],
+      [ 0,  -sin(tilt),  cos(tilt),    0 ],
+      [ 0,     0,           0,         1 ],
     ])
-    findcurve_basis = augmatmultiply(dPQplane_basis, tilt_basis)
+    findcurve_basis = matmatmultiply(dPQplane_basis, tilt_basis)
     findcurve_into = np.linalg.inv(findcurve_basis)
 
-    q_findcurve = unaugment(findcurve_into, augment(q))
-    dq_findcurve = unaugment(findcurve_into, augment0(dq))
+    for ax in range(0,3):
+      vdbg().arrow(findcurve_basis[0:3,3], findcurve_basis[0:3,ax])
+
+    q_findcurve = augmatmultiply(findcurve_into, q)
+    dq_findcurve = augmatmultiply(findcurve_into, dq, augwith=0)
 
-    findcurve_target = np.concatenate(q_findcurve, dq_findcurve)
+    findcurve_target = np.hstack((q_findcurve, dq_findcurve))
     findcurve_start = (sqrt(start_s), sqrt(start_t), start_la,
                        start_mu, start_gamma, start_kappa)
     
     findcurve_epsilon = dist_pq_plane * 0.01
 
+    global findcurve_subproc
     if findcurve_subproc is None:
+      dbg('STARTING FINDCURVE')
       findcurve_subproc = subprocess.Popen(
         ['./findcurve'],
         bufsize=1,
@@ -147,35 +225,68 @@ class HelixishCurve():
         stdout=subprocess.PIPE,
         stderr=None,
         close_fds=False,
-        restore_signals=True,
+        # restore_signals=True, // want python2 compat, nnng
         universal_newlines=True,
       )
 
     findcurve_input = np.hstack((findcurve_target,
                                  findcurve_start,
                                  [findcurve_epsilon]))
-    dbg('RUNNING FINDCURVE', *findcurve_input)
-    print(findcurve_subproc.stdin, *findcurve_input)
+
+    def dbg_fmt_params(fcp):
+      return (('s=%10.7f t=%10.7f sh=%10.7f'
+               +' st=%10.7f la=%10.7f mu=%10.7f ga=%10.7f ka=%10.7f')
+              %
+              (( fcp[0]**2, fcp[1]**2 ) + tuple(fcp)))
+
+    #dbg('>> ' + ' '.join(map(str,findcurve_input)))
+
+    dbg(('RUNNING FINDCURVE' +
+         '                                             ' +
+         ' target Q=[%10.7f %10.7f %10.7f] dQ=[%10.7f %10.7f %10.7f]')
+        %
+        tuple(findcurve_input[0:6]))
+    dbg(('%s  initial') % dbg_fmt_params(findcurve_input[6:12]))
+
+    print(*findcurve_input, file=findcurve_subproc.stdin)
     findcurve_subproc.stdin.flush()
 
+    hc.func = symbolic.get_python()
+    hc.findcurve_basis = findcurve_basis
+    commentary = ''
+
     while True:
       l = findcurve_subproc.stdout.readline()
       l = l.rstrip()
-      dbg('GOT ', l)
+      dbg('<< ', l)
+      if not l: vdbg().crashing('findcurve EOF')
+      if not l.startswith('['):
+        commentary += ' '
+        commentary += l
+        continue
+
       l = eval(l)
-      if l is None: break
+      if not l: break
+
+      dbg(('%s Q=[%10.7f %10.7f %10.7f] dQ=[%10.7f %10.7f %10.7f]%s')
+          %
+          (( dbg_fmt_params(l[0:6]), ) + tuple(l[6:12]) + (commentary,) ))
+      commentary = ''
 
-    hc.findcurve_result = l[0:5]
-    hc.func = symbolic.get_python(something)
-    hc.threshold = l[0]**2
-    hc.total_dist = hc.threshold + l[1]**2
+      hc.findcurve_result = l[0:6]
+      hc.threshold = l[0]**2
+      hc.total_dist = hc.threshold + l[1]**2
+      #vdbg().curve( hc.point_at_t )
 
   def point_at_t(hc, normalised_parameter):
     dist = normalised_parameter * hc.total_dist
-    ours = [p for p in findcurve_result]
+    ours = list(hc.findcurve_result)
     if dist <= hc.threshold:
       ours[0] = sqrt(dist)
       ours[1] = 0
     else:
       ours[1] = sqrt(dist - hc.threshold)
-    return hc.func(*ours)
+    asmat = hc.func(*ours)
+    p = asmat[:,0]
+    p = augmatmultiply(hc.findcurve_basis, p)
+    return p