Debian Codegraph @

gavo/stc/sphermath.py

raw
1 """
2 Spherical geometry and related helper functions.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import math
12 import types
13
14 import numpy
15
16 from gavo.stc import common
17 from gavo.stc import units
18 from gavo.utils import mathtricks
19
20 from gavo.utils.mathtricks import cartToSpher, spherToCart #noflake
21
22 # filled in for distances not given, in rad (units also insert this for
23 # parallaxes too small)
24 defaultDistance = units.maxDistance*units.onePc/units.oneAU
25
26 # Units spherical coordinates have to be in for transformation to/from
27 # 6-vectors; this is all done in the bowels of SVConverter
28 _svPosUnit = ("rad", "rad", "AU")
29 _svVPosUnit = ("rad", "rad", "AU")
30 _svVTimeUnit = ("d", "d", "d")
31 # Light speed in AU/d
32 _lightAUd = 86400.0/499.004782
33
34
35 def getMatrixFromEulerAngles(z1, x, z2):
36 """returns a 3-rotation matrix for the z-x-z Euler angles.
37
38 There are some functions to obtain such angles below.
39 """
40 return numpy.dot(
41 numpy.dot(mathtricks.getRotZ(z2),
42 mathtricks.getRotX(x)),
43 mathtricks.getRotZ(z1))
44
45
46 def getEulerAnglesFromMatrix(matrix):
47 """returns zxz Euler angles from a rotation matrix.
48
49 This is improvised, and someone should look up a numerically sound way
50 to do this.
51 """
52 # while I cannot see why, this clearly is broken in some way.
53 z1 = math.atan2(matrix[2,0], -matrix[2,1])
54 z2 = math.atan2(matrix[0,2], matrix[1,2])
55 x = math.atan2(math.sqrt(matrix[2,0]**2+matrix[2,1]**2), matrix[2,2])
56 return z1, x, z2
57
58
59 def getMatrixFromEulerVector(eulerVector):
60 """returns a rotation matrix for an Euler vector.
61
62 An euler vector gives the rotation axis, its magnitude the angle in rad.
63
64 This function is a rip-off of SOFA's rv2m.
65
66 eulerVector is assumed to be a numpy array.
67 """
68 x, y, z = eulerVector
69 phi = math.sqrt(x**2+y**2+z**2)
70 sp, cp = math.sin(phi), math.cos(phi)
71 f = 1-cp
72 if phi!=0:
73 x, y, z = eulerVector/phi
74 return numpy.array([
75 [x**2*f+cp, x*y*f+z*sp, x*z*f-y*sp],
76 [y*x*f-z*sp, y**2*f+cp, y*z*f+x*sp],
77 [z*x*f+y*sp, z*y*f-x*sp, z**2*f+cp]])
78
79
80 def computeTransMatrixFromPole(poleCoo, longZeroCoo, changeHands=False):
81 """returns a transformation matrix to transform from the reference
82 system into a rotated system.
83
84 The rotated system is defined by its pole, the spherical coordinates
85 at which it has longitude zero and whether or not it is right handed.
86
87 All angles are in rad.
88 """
89 # when moving from numpy here, replace this with the like-named
90 # function from utils.mathtricks.
91 x = spherToCart(*longZeroCoo)
92 z = spherToCart(*poleCoo)
93 if abs(numpy.dot(x, z))>1e-5:
94 raise common.STCValueError("%s and %s are not valid pole/zero points for"
95 " a rotated coordinate system"%(poleCoo, longZeroCoo))
96 y = (z[1]*x[2]-z[2]*x[1], z[2]*x[0]-z[0]*x[2], z[0]*x[1]-z[1]*x[0])
97 if changeHands:
98 y = (-y[0], -y[1], -y[2])
99 return numpy.array([x,y,z])
100
101
102 def vabs(naVec):
103 return math.sqrt(numpy.dot(naVec, naVec))
104
105
106 def _ensureSphericalFrame(coo):
107 """raises an error if coo's frame is not suitable for holding spherical
108 coordinates.
109 XXX TODO: assert spatial and vel coos have the same frame, etc.
110 """
111 if not coo.frame.isSpherical():
112 raise common.STCValueError("%s is not a valid frame for transformable"
113 " spherical coordinates."%(coo.frame))
114
115
116 ############## Code for handling relativistic correction in 6-Vector conversion
117 # Warning: This has massive issues with numerics. Don't use.
118
119 def _pleaseEinsteinToSpher(sv):
120 """undoes relativistic corrections from 6-vector sv.
121
122 This follows sofa's pvstar. sv is changed in place.
123 """
124 radialProj, radialV, tangentialV = _decomposeRadial(sv[:3], sv[3:])
125 betaRadial = radialProj/_lightAUd
126 betaTangential = vabs(tangentialV)/_lightAUd
127
128 d = 1.0+betaRadial
129 w = 1.0-betaRadial**2-betaTangential**2
130 if d==0.0 or w<0:
131 return
132 delta = math.sqrt(w)-1.0
133 if betaRadial==0:
134 radialV = (betaRadial-delta)/(betaRadial*d)*radialV
135 sv[3:] = 1/d*radialV
136
137
138 def _decomposeRadial(r, rd):
139 """returns the components of rd radial and tangential to r.
140 """
141 rUnit = r/vabs(r)
142 radialProj = numpy.dot(rUnit, rd)
143 radialVector = radialProj*rUnit
144 tangentialVector = rd-radialVector
145 return radialProj, radialVector, tangentialVector
146
147
148 def _solveStumpffEquation(betaR, betaT, maxIter=100):
149 """returns the solution of XXX.
150
151 If the solution fails to converge within maxIter iterations, it
152 raises an STCError.
153 """
154 curEstR, curEstT = betaR, betaT
155 od, odel, odd, oddel = 0, 0, 0, 0
156 for i in range(maxIter):
157 d = 1.+curEstT
158 delta = math.sqrt(1.-curEstR**2-curEstT**2)-1.0
159 curEstR = d*betaR+delta
160 curEstT = d*betaT
161 if i: # check solution so far after at least one iteration
162 dd = abs(d-od)
163 ddel = abs(delta-odel)
164 if dd==odd and ddel==oddel:
165 break
166 odd = dd
167 oddel = ddel
168 od = d
169 odel = delta
170 else:
171 raise common.STCError(
172 "6-vector relativistic correction failed to converge")
173 return curEstR, curEstT, d, delta
174
175
176 def _pleaseEinsteinFromSpher(sv):
177 """applies relativistic corrections to the 6-vector sv.
178
179 This follows sofa's starpv. sv is changed in place.
180 """
181 radialProj, radialV, tangentialV = _decomposeRadial(sv[:3], sv[3:])
182 betaRadial = radialProj/_lightAUd
183 betaTangential = vabs(tangentialV)/_lightAUd
184
185 betaSR, betaST, d, delta = _solveStumpffEquation(betaRadial, betaTangential)
186 # replace old velocity with velocity in inertial system
187 if betaSR!=0:
188 radialV = (d+delta/betaSR)*radialV
189 sv[3:] = radialV+(d*tangentialV)
190
191 ################# End relativistic code.
192
193 class SVConverter:
194 """A container for the conversion from spherical coordinates
195 to 6-Vectors.
196
197 You create one with an example of your data; these are values
198 and units of STC objects, and everything may be None if it's
199 not given.
200
201 The resulting object has methods to6 taking values
202 like the one provided by you and returning a 6-vector, and from6
203 returning a pair of such values.
204
205 Further, the converter has the attributes distGiven,
206 posdGiven, and distdGiven signifying whether these items are
207 expected or valid on return. If posVals is None, no transforms
208 can be computed.
209
210 The relativistic=True constructior argument requests that the
211 transformation be Lorentz-invariant. Do not use that, though,
212 since there are unsolved numerical issues.
213
214 The slaComp=True constructor argument requests that some
215 operations exterior to the construction are done as slalib does
216 them, rather than alternative approaches.
217 """
218 posGiven = distGiven = posdGiven = distdGiven = True
219 defaultDistance = units.maxDistance*units.onePc/units.oneAU
220
221 def __init__(self, posVals, posUnit, velVals=None, velSUnit=None,
222 velTUnit=None, relativistic=False, slaComp=False):
223 self.relativistic, self.slaComp = relativistic, slaComp
224 self._determineFeatures(posVals, velVals)
225 self._computeUnitConverters(posUnit, velSUnit, velTUnit)
226 self._makeTo6()
227 self._makeFrom6()
228
229 def _determineFeatures(self, posVals, velVals):
230 if posVals is None:
231 # No position has been given; that is possible if only "wiggles"
232 # were specified. We'd have to transform those, too, but we
233 # don't for now.
234 self.distGiven = self.posdGiven = False
235 self._velDefault = None
236 return
237
238 if len(posVals)==2:
239 self.distGiven = False
240 if velVals is None:
241 self.posdGiven = False
242 self._velDefault = None
243 else:
244 if len(velVals)==2:
245 self.distdGiven = False
246 self._velDefault = (0,0)
247 else:
248 self._velDefault = (0,0,0)
249
250 def _computeUnitConverters(self, posUnit, velSUnit, velTUnit):
251 dims = len(posUnit)
252 self.toSVUnitsPos = units.getVectorConverter(posUnit,
253 _svPosUnit[:dims])
254 self.fromSVUnitsPos = units.getVectorConverter(posUnit,
255 _svPosUnit[:dims], True)
256 if self.posdGiven:
257 dims = len(velSUnit)
258 self.toSVUnitsVel = units.getVelocityConverter(velSUnit, velTUnit,
259 _svVPosUnit[:dims], _svVTimeUnit[:dims])
260 self.fromSVUnitsVel = units.getVelocityConverter(velSUnit, velTUnit,
261 _svVPosUnit[:dims], _svVTimeUnit[:dims], True)
262
263 def _makeTo6(self):
264 velDefault = ""
265 if not self.posdGiven:
266 velDefault = "=None"
267 code = ["def to6(self, pos, vel%s):"%velDefault]
268 code.append(" pos = self.toSVUnitsPos(pos)")
269 if self.posdGiven:
270 code.append(" vel = self.toSVUnitsVel(vel)")
271 if not self.distGiven:
272 code.append(" pos = pos+(defaultDistance,)")
273 if self.posdGiven:
274 if not self.distdGiven:
275 code.append(" vel = vel+(0,)")
276 else:
277 code.append(" vel = (0,0,0)")
278 code.append(" (alpha, delta, r), (alphad, deltad, rd) = pos, vel")
279 code.append(" sa, ca = math.sin(alpha), math.cos(alpha)")
280 code.append(" sd, cd = math.sin(delta), math.cos(delta)")
281 code.append(" x, y = r*cd*ca, r*cd*sa")
282 code.append(" w = r*deltad*sd-cd*rd")
283 code.append(" res = numpy.array([x, y, r*sd,"
284 " -y*alphad-w*ca, x*alphad-w*sa, r*deltad*cd+sd*rd])")
285 if self.relativistic:
286 code.append(" _pleaseEinsteinFromSpher(res)")
287 code.append(" return res")
288 l = locals()
289 exec("\n".join(code), globals(), l)
290 self.to6 = types.MethodType(l["to6"], self)
291
292 def _makeFrom6(self):
293 code = ["def from6(self, sv):"]
294 if self.relativistic:
295 code.append(" _pleaseEinsteinFromSpher(sv)")
296 code.append(" pos, vel = self._svToSpherRaw(sv)")
297 if not self.distGiven:
298 code.append(" pos = pos[:2]")
299 code.append(" pos = self.fromSVUnitsPos(pos)")
300 if self.posdGiven:
301 if not self.distdGiven:
302 code.append(" vel = vel[:2]")
303 code.append(" vel = self.fromSVUnitsVel(vel)")
304 else:
305 code.append(" vel = None")
306 code.append(" return pos, vel")
307 l = locals()
308 exec("\n".join(code), globals(), l)
309 self.from6 = types.MethodType(l["from6"], self)
310
311 def _svToSpherRaw(self, sv):
312 """returns spherical position and velocity vectors for the cartesian
313 6-vector sv.
314
315 This is based on SOFA's pv2s.
316 """
317 x, y, z, xd, yd, zd = sv
318 rInXY2 = x**2+y**2
319 r2 = rInXY2+z**2
320 rw = rTrue = math.sqrt(r2)
321
322 if rTrue==0.: # pos is null: use velocity for position
323 x, y, z = sv[3:]
324 rInXY2 = x**2+y**2
325 r2 = rInXY2+z**2
326 rw = math.sqrt(r2)
327
328 rInXY = math.sqrt(rInXY2)
329 xyp = x*xd+y*yd
330 radialVel = 0
331 if rw!=0:
332 radialVel = xyp/rw+z*zd/rw
333
334 if rInXY2!=0.:
335 theta = math.atan2(y, x)
336 if abs(theta)<1e-12: # null out to avoid wrapping to 2 pi
337 theta = 0
338 if theta<0:
339 theta += 2*math.pi
340 posValues = (theta, math.atan2(z, rInXY), rTrue)
341 velValues = ((x*yd-y*xd)/rInXY2, (zd*rInXY2-z*xyp)/(r2*rInXY), radialVel)
342 else:
343 phi = 0
344 if z!=0:
345 phi = math.atan2(z, rInXY)
346 posValues = (0, phi, rTrue)
347 velValues = (0, 0, radialVel)
348 return posValues, velValues
349
350 def getPlaceTransformer(self, sixTrafo):
351 """returns a function that transforms 2- or 3-spherical coordinates
352 using the 6-vector transformation sixTrafo.
353
354 Regardless of whether we expect distances, the returned function always
355 returns vectors of the same dimensionality as were passed in.
356
357 This is used when transforming areas.
358 """
359 def sTrafo(pos):
360 make2 = len(pos)==2
361 if self.distGiven and make2:
362 pos = pos+(defaultDistance,)
363 res, _ = self.from6(sixTrafo(self.to6(pos, self._velDefault), self))
364 if make2:
365 res = res[:2]
366 return res
367 return sTrafo
368
369 def getVelocityTransformer(self, sixTrafo, basePos):
370 """returns a function that transforms velocities using sixTrafos
371 at basePos.
372
373 This is used when transforming velocity intervals.
374 """
375 def sTrafo(vel):
376 return self.from6(sixTrafo(self.to6(basePos, vel), self))[1]
377 return sTrafo
378
379 @classmethod
380 def fromSTC(cls, stc, **kwargs):
381 """returns a new 6-vector transform for coordinates in STC.
382 """
383 pos, vel, posUnit, velUnitS, velUnitT = (None,)*5
384 if stc.place:
385 pos = stc.place.value
386 posUnit = stc.place.unit
387 if pos is None: # if areas are there, fake a position of their
388 if stc.areas: # dimensionality
389 pos = (0,)*stc.place.frame.nDim
390 if stc.velocity:
391 vel = stc.velocity.value
392 velUnitS = stc.velocity.unit
393 velUnitT = stc.velocity.velTimeUnit
394 return cls(pos, posUnit, vel, velUnitS, velUnitT, **kwargs)
395
396
397 def toSpherical(threeVec):
398 """returns spherical coordinates for a cartesian 3-vector.
399
400 threeVec needs not be normalized.
401 """
402 rho = math.sqrt(threeVec[0]**2+threeVec[1]**2)
403 long = math.atan2(threeVec[1], threeVec[0])
404 lat = math.atan2(threeVec[2], rho)
405 return long, lat
406
407
408 def toThreeVec(long, lat):
409 """returns a cartesian 3-vector for longitude and latitude.
410 """
411 return (math.cos(lat)*math.cos(long),
412 math.cos(lat)*math.sin(long),
413 math.sin(lat))