17 import numpy
as np, math
19 from math_tools
import general_math
as gen
26 Find theta and phi that minimize function:
27 f(theta, phi) = ( a*cos(theta)*cos(phi) - x0 )^2 + ( b*sin(theta)*cos(phi) - y0 )^2 + ( c*sin(phi) - z0 )^2
29 The method is numerical using the Hessian matrix.
30 The iterations start from theta_0 and phi_0
37 if gen.equal(x0, 0.0)
and gen.equal(y0, 0.0)
and gen.equal(z0, 0.0):
42 t0 = np.array([math.pi/2, 0.0])
44 t0 = np.array([0.0, math.pi/2])
49 t0 = np.array([math.pi/2, 0.0])
51 t0 = np.array([0.0, math.pi/2])
57 s = ssign/math.sqrt(x0*x0/a2 + y0*y0/b2 + z0*z0/c2)
58 the = math.atan2(a*y0, b*x0)
59 phi = math.atan2(z0*s/c, s*math.sqrt(x0*x0/a2 + y0*y0/b2))
60 assert gen.equal(a*math.cos(the)*math.cos(phi), x0*s)
61 assert gen.equal(b*math.sin(the)*math.cos(phi), y0*s)
62 assert gen.equal(c*math.sin(phi), z0*s)
63 t0 = np.array([the,phi])
72 while stay
and (cnt < max_iter):
87 df[0] = 0.5*(b2 - a2)*s2t*cf2 + cf*(a*x0*st - b*y0*ct)
88 df[1] = - 0.5*s2f*(a2*ct2 + b2*st2 - c2) + sf*(a*x0*ct + b*y0*st) - c*z0*cf
90 stay =
not gen.equal(np.linalg.norm(df), 0.0)
92 H[0,0] = (b2 - a2)*c2t*cf2 + cf*(a*x0*ct + b*y0*st)
93 H[0,1] = 0.5*(a2 - b2)*s2t*s2f - sf*(a*x0*st - b*y0*ct)
95 H[1,1] = - c2f*(a2*ct2 + b2*st2 - c2) + cf*(a*x0*ct + b*y0*st) + c*z0*sf
97 t = t - np.dot(np.linalg.inv(H), df)
102 print 'iteration:', cnt,
' cost function value:', (a*ct*cf - x0)**2 + (b*st*cf - y0)**2 + (c*sf - z0)**2,
' norm(div_f):', np.linalg.norm(df)