Debian Codegraph @

gavo/stc/spherc.py

raw
1 """
2 Spherical sky coordinates and helpers.
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 # XXX TODO: Replace the actual transformations performed here with
12 # stuff from astropy.
13
14 import functools
15 from math import sin, cos
16 import math
17
18 import numpy
19 from numpy import linalg as la
20
21 from gavo.stc import common
22 from gavo.stc import sphermath
23 from gavo.stc import times
24 from gavo.stc import units
25 from gavo.utils import DEG, ARCSEC
26 from gavo.utils import mathtricks
27
28
29 ############### Basic definitions for transforms
30
31 # Finding transformation sequences: This, in principle, is a standard
32 # graph problem. However, we have lots of underspecified transforms,
33 # which makes building a Dijkstrable graph somewhat inconvenient. So,
34 # instead of striving for an optimal shortest path, we go for a
35 # greedy search with some heuristics. The most nonstandard feature is
36 # that nodes are built ad-hoc and noncircularity of the paths through
37 # the "virtual" graph is checked on these ad-hoc nodes.
38
39 # The nodes in the graph are triples of (system, equinox, refpos). The
40 # vertices are triples (fromNode, toNode, transform generator).
41 # Transform generators are functions
42 #
43 # f(fromNode, toNode) -> (function or matrix)
44 #
45 # The arguments are node triples, the result either a function taking
46 # and returning 6-vectors or numpy matrices. These functions may
47 # assume that only "appropriate" values are passed in as nodes, i.e.,
48 # they are not assumed to check that the are actually able to produce
49 # the requested transformation.
50
51 class _Wildcard(object):
52 """is an object that compares equal to everything.
53
54 This is used for underspecification of transforms, see SAME and
55 ANYVAL below.
56 """
57 def __init__(self, name):
58 self.name = name
59
60 def __repr__(self):
61 return self.name
62
63 def __ne__(self, other): return False
64 def __eq__(self, other): return True
65
66
67 SAME = _Wildcard("SAME")
68 ANYVAL = _Wildcard("ANYVAL")
69
70 def _specifyTrafo(trafo, fromTuple, toTuple):
71 """fills in underspecified values in trafo from fromTuple and toTuple.
72
73 The rules are: In the source, both SAME and ANYVAL are filled from
74 fromTuple. In the destination, SAME is filled from fromTuple,
75 ANYVAL is filled from toTuple.
76
77 The function returns a new transformation triple.
78 """
79 src, dst, tgen = trafo
80 newSrc, newDst = [], []
81 for ind, val in enumerate(src):
82 if val is SAME or val is ANYVAL:
83 newSrc.append(fromTuple[ind])
84 else:
85 newSrc.append(val)
86 for ind, val in enumerate(dst):
87 if val is SAME:
88 newDst.append(fromTuple[ind])
89 elif val is ANYVAL:
90 newDst.append(toTuple[ind])
91 else:
92 newDst.append(val)
93 return tuple(newSrc), tuple(newDst), tgen
94
95
96 def _makeFindPath(transforms):
97 """returns a function for path finding in the virtual graph
98 defined by transforms.
99
100 Each transform is a triple of (fromNode, toNode, transformFactory).
101
102 There's quite a bit of application-specific heuristics built in
103 here, so there's little you can do with this code outside of
104 STC transforms construction.
105 """
106 def findPath(fromTuple, toTuple, path=()):
107 """returns a sequence of transformation triples that lead from
108 fromTuple to toTuple.
109
110 fromTuple and toTuple are node triples (i.e., (system, equinox,
111 refpoint)).
112
113 The returned path is not guaranteed to be the shortest or even
114 the numerically most stable. It is the result of a greedy
115 search for a cycle free path between the two "non-virtual" nodes.
116 To keep the paths reasonable, we apply the heuristic that
117 transformations keeping the system are preferable.
118
119 The simple heuristics sometimes need help; e.g., the transformations
120 below add explicit transformations to j2000 and b1950; you will always
121 need this if your transformations include "magic" values for otherwise
122 underspecified items.
123 """
124 seenSystems = set(c[0] for c in path) | set(c[1] for c in path)
125 candidates = [_specifyTrafo(t, fromTuple, toTuple)
126 for t in transforms if t[0]==fromTuple]
127 # sort operations within the same reference system to the start
128 candidates = [c for c in candidates if c[1][0]==toTuple[0]] + [
129 c for c in candidates if c[1]!=toTuple[0]]
130 for cand in candidates:
131 srcSystem, dstSystem, tgen = cand
132 # Ignore identities or trafos leading to cycles
133 if srcSystem==dstSystem or dstSystem in seenSystems:
134 continue
135 if dstSystem==toTuple: # If we are done, return result
136 return path+(cand,)
137 else:
138 # Do the depth-first search
139 np = findPath(dstSystem, toTuple, path+(cand,))
140 if np:
141 return np
142 return findPath
143
144
145 def tupleMin(t1, t2):
146 """returns the element-wise minimum of two tuples:
147 """
148 return tuple(min(i1, i2) for i1, i2 in zip(t1, t2))
149
150
151 def tupleMax(t1, t2):
152 """returns the element-wise maximum of two tuples:
153 """
154 return tuple(max(i1, i2) for i1, i2 in zip(t1, t2))
155
156
157 ############### Computation of precession matrices.
158
159 def prec_IAU1976(fromEquinox, toEquinox):
160 """returns the precession angles in the IAU 1976 system.
161
162 The expressions are those of Lieske, A&A 73, 282.
163
164 This function is for the precTheory argument of getPrecMatrix.
165 """
166 # time differences have to be in julian centuries
167 # capital T in Lieske
168 fromDiff = times.getSeconds(fromEquinox-times.dtJ2000)/common.secsPerJCy
169 # lowercase T in Lieske
170 toDiff = times.getSeconds(toEquinox-fromEquinox)/common.secsPerJCy
171
172 # Lieske's expressions yield arcsecs, fix below
173 zeta = toDiff*(2306.2181+1.39656*fromDiff-0.000139*fromDiff**2
174 )+toDiff**2*(0.30188-0.000344*fromDiff
175 )+toDiff**3*0.017998
176 z = toDiff*(2306.2181+1.39656*fromDiff-0.000139*fromDiff**2
177 )+toDiff**2*(1.09468+0.000066*fromDiff
178 )+toDiff**3*0.018203
179 theta = toDiff*(2004.3109-0.85330*fromDiff-0.000217*fromDiff**2
180 )-toDiff**2*(0.42665+0.000217*fromDiff
181 )-toDiff**3*0.041833
182 return zeta*ARCSEC, z*ARCSEC, theta*ARCSEC
183
184
185 _dtB1850 = times.bYearToDateTime(1850)
186
187 def prec_Newcomb(fromEquinox, toEquinox):
188 """returns the precession angles for the newcomp
189
190 This function is for the precTheory argument of getPrecMatrix.
191
192 The expressions are Kinoshita's (1975)'s (SAOSR 364)
193 This is somewhat at odds with Yallop's choice of Andoyer in the FK4-FK5
194 machinery below, but that really shouldn't matter.
195 """
196 # time differences have to be in tropical centuries
197 T = times.getSeconds(fromEquinox-_dtB1850)/(common.tropicalYear*86400*100)
198 t = times.getSeconds(toEquinox-fromEquinox)/(common.tropicalYear*86400*100)
199
200 polyVal = 2303.5548+(1.39720+0.000059*T)*T
201 zeta = (polyVal+(0.30242-0.000269*T+0.017996*t)*t)*t
202 z = (polyVal+(1.09478+0.000387*T+0.018324*t)*t)*t
203 theta = (2005.1125+(-0.85294-0.000365*T)*T
204 +(-0.42647-0.000365*T-0.041802*t)*t)*t
205 return zeta*ARCSEC, z*ARCSEC, theta*ARCSEC
206
207
208 def getPrecMatrix(fromEquinox, toEquinox, precTheory):
209 """returns a precession matrix in the IAU(1976) system.
210
211 fromEquinox and toEquinox are datetimes (in case of doubt, TT).
212
213 precTheory(fromEquinox, toEquinox) -> zeta, z, theta computes the
214 precession angles. Defined in this module are prec_IAU1976 and
215 prec_Newcomb, but you can provide your own. The angles must all be
216 in rad.
217 """
218 zeta, z, theta = precTheory(fromEquinox, toEquinox)
219 return numpy.dot(
220 numpy.dot(mathtricks.getRotZ(-z), mathtricks.getRotY(theta)),
221 mathtricks.getRotZ(-zeta))
222
223
224 _nullMatrix = numpy.zeros((3,3))
225 def threeToSix(matrix):
226 """returns a 6-matrix from a 3-matrix suitable for precessing our
227 6-vectors.
228 """
229 return numpy.concatenate((
230 numpy.concatenate( (matrix, _nullMatrix), 1),
231 numpy.concatenate( (_nullMatrix, matrix ), 1)))
232
233 def _getFullPrecMatrix(fromNode, toNode, precTheory):
234 """returns a full 6x6 matrix for transforming positions and proper motions.
235
236 This only works for proper equatorial coordinates in both STC values.
237
238 precTheory is a function returning precession angles.
239 """
240 return threeToSix(getPrecMatrix(fromNode[1], toNode[1], precTheory))
241
242
243 def _getNewcombPrecMatrix(fromNode, toNode, sixTrans):
244 return _getFullPrecMatrix(fromNode, toNode, prec_Newcomb)
245
246 def _getIAU1976PrecMatrix(fromNode, toNode, sixTrans):
247 return _getFullPrecMatrix(fromNode, toNode, prec_IAU1976)
248
249
250 ############### FK4-FK5 system transformation
251 # This follows the prescription of Yallop et al, AJ 97, 274
252
253 # Transformation matrix according to Yallop
254 _fk4ToFK5MatrixYallop = numpy.array([
255 [0.999925678186902, -0.011182059642247, -0.004857946558960,
256 0.000002423950176, -0.000000027106627, -0.000000011776558],
257 [0.011182059571766, 0.999937478448132, -0.000027176441185,
258 0.000000027106627, 0.000002723978783, -0.000000000065874],
259 [0.004857946721186, -0.000027147426489, 0.9999881997387700,
260 0.000000011776559, -0.000000000065816, 0.000002424101735],
261 [-0.000541652366951, -0.237968129744288, 0.436227555856097,
262 0.999947035154614, -0.011182506121805, -0.004857669684959],
263 [0.237917612131583, -0.002660763319071, -0.008537771074048,
264 0.011182506007242, 0.999958833818833, -0.000027184471371],
265 [-0.436111276039270, 0.012259092261564, 0.002119110818172,
266 0.004857669948650, -0.000027137309539, 1.000009560363559]])
267
268 # Transformation matrix according to SLALIB-F
269 _fk4ToFK5MatrixSla = numpy.transpose(numpy.array([
270 [+0.9999256782, +0.0111820610, +0.0048579479,
271 -0.000551, +0.238514, -0.435623],
272 [-0.0111820611, +0.9999374784, -0.0000271474,
273 -0.238565, -0.002667, +0.012254],
274 [-0.0048579477, -0.0000271765, +0.9999881997,
275 +0.435739, -0.008541, +0.002117],
276 [+0.00000242395018, +0.00000002710663, +0.00000001177656,
277 +0.99994704, +0.01118251, +0.00485767],
278 [-0.00000002710663, +0.00000242397878, -0.00000000006582,
279 -0.01118251, +0.99995883, -0.00002714],
280 [-0.00000001177656, -0.00000000006587, +0.00000242410173,
281 -0.00485767, -0.00002718, +1.00000956]]))
282
283 # Inverse transformation matrix according to SLALIB-F
284 _fk5ToFK4Matrix = numpy.transpose(numpy.array([
285 [+0.9999256795, -0.0111814828, -0.0048590040,
286 -0.000551, -0.238560, +0.435730],
287 [+0.0111814828, +0.9999374849, -0.0000271557,
288 +0.238509, -0.002667, -0.008541],
289 [+0.0048590039, -0.0000271771, +0.9999881946,
290 -0.435614, +0.012254, +0.002117],
291 [-0.00000242389840, +0.00000002710544, +0.00000001177742,
292 +0.99990432, -0.01118145, -0.00485852],
293 [-0.00000002710544, -0.00000242392702, +0.00000000006585,
294 +0.01118145, +0.99991613, -0.00002716],
295 [-0.00000001177742, +0.00000000006585, -0.00000242404995,
296 +0.00485852, -0.00002717, +0.99996684]]))
297
298
299
300 # Positional correction due to E-Terms, in rad (per tropical century in the
301 # case of Adot, which is ok for sphermath._svPosUnit (Yallop et al, loc cit, p.
302 # 276)). We ignore the difference between tropical and julian centuries.
303 _b1950ETermsPos = numpy.array([-1.62557e-6, -0.31919e-6, -0.13843e-6])
304 _b1950ETermsVel = numpy.array([1.245e-3, -1.580e-3, -0.659e-3])
305 _yallopK = common.secsPerJCy/(units.oneAU/1e3)
306 _yallopKSla = 21.095;
307 _pcPerCyToKmPerSec = units.getRedshiftConverter("pc", "cy", "km", "s")
308
309 # An SVConverter to bring 6-vectors to the spherical units Yallop prescribes.
310 _yallopSVConverter = sphermath.SVConverter((0,0,0), ("rad", "rad", "arcsec"),
311 (0,0,0), ("arcsec", "arcsec", "km"), ("cy", "cy", "s"))
312
313
314 def _svToYallop(sv, yallopK):
315 """returns r and rdot vectors suitable for Yallop's recipe from our
316 6-vectors.
317 """
318 (alpha, delta, prlx), (pma, pmd, rv) = _yallopSVConverter.from6(sv)
319
320 yallopR = numpy.array([cos(alpha)*cos(delta),
321 sin(alpha)*cos(delta), sin(delta)])
322 yallopRd = numpy.array([
323 -pma*sin(alpha)*cos(delta)-pmd*cos(alpha)*sin(delta),
324 pma*cos(alpha)*cos(delta)-pmd*sin(alpha)*sin(delta),
325 pmd*cos(delta)])+yallopK*rv*prlx*yallopR
326 return yallopR, yallopRd, (rv, prlx)
327
328
329 def _yallopToSv(yallop6, yallopK, rvAndPrlx):
330 """returns a 6-Vector from a yallop-6 vector.
331
332 rvAndPrlx is the third item of the return value of _svToYallop.
333 """
334 rv, prlx = rvAndPrlx
335 x,y,z,xd,yd,zd = yallop6
336 rxy2 = x**2+y**2
337 r = math.sqrt(z**2+rxy2)
338 if rxy2==0:
339 raise common.STCValueError("No spherical proper motion on poles.")
340 alpha = math.atan2(y, x)
341 if alpha<0:
342 alpha += 2*math.pi
343 delta = math.atan2(z, math.sqrt(rxy2))
344 pma = (x*yd-y*xd)/rxy2
345 pmd = (zd*rxy2-z*(x*xd+y*yd))/r/r/math.sqrt(rxy2)
346 if abs(prlx)>1/sphermath.defaultDistance:
347 rv = numpy.dot(yallop6[:3], yallop6[3:])/yallopK/prlx/r
348 prlx = prlx/r
349 return _yallopSVConverter.to6((alpha, delta, prlx), (pma, pmd, rv))
350
351
352 def fk4ToFK5(sixTrans, svfk4):
353 """returns an FK5 2000 6-vector for an FK4 1950 6-vector.
354
355 The procedure used is described in Yallop et al, AJ 97, 274. E-terms
356 of aberration are always removed from proper motions, regardless of
357 whether the objects are within 10 deg of the pole.
358 """
359 if sixTrans.slaComp:
360 transMatrix = _fk4ToFK5MatrixSla
361 yallopK = _yallopKSla
362 else:
363 transMatrix = _fk4ToFK5MatrixYallop
364 yallopK = _yallopK
365 yallopR, yallopRd, rvAndPrlx = _svToYallop(svfk4, yallopK)
366
367 # Yallop's recipe starts here
368 if not sixTrans.slaComp: # include Yallop's "small terms" in PM
369 yallopVE = (yallopRd-_b1950ETermsVel
370 +numpy.dot(yallopR, _b1950ETermsVel)*yallopR
371 +numpy.dot(yallopRd, _b1950ETermsPos)*yallopR
372 +numpy.dot(yallopRd, _b1950ETermsPos)*yallopRd)
373 else:
374 yallopVE = (yallopRd-_b1950ETermsVel
375 +numpy.dot(yallopR, _b1950ETermsVel)*yallopR)
376
377 yallop6 = numpy.concatenate((yallopR-(_b1950ETermsPos-
378 numpy.dot(yallopR, _b1950ETermsPos)*yallopR),
379 yallopVE))
380 cnv = numpy.dot(transMatrix, yallop6)
381 return _yallopToSv(cnv, yallopK, rvAndPrlx)
382
383
384 def fk5ToFK4(sixTrans, svfk5):
385 """returns an FK4 1950 6-vector for an FK5 2000 6-vector.
386
387 This is basically a reversal of fk4ToFK5, except we're always operating
388 in slaComp mode here.
389
390 """
391 yallopR, yallopRd, rvAndPrlx = _svToYallop(svfk5, _yallopKSla)
392
393 # first apply rotation...
394 cnv = numpy.dot(_fk5ToFK4Matrix,
395 numpy.concatenate((yallopR, yallopRd)))
396 # ... then handle E-Terms; direct inversion of Yallop's equations is
397 # troublesome, so I basically follow what slalib does.
398 yallopR, yallopRd = cnv[:3], cnv[3:]
399 spatialCorr = numpy.dot(yallopR, _b1950ETermsPos)*yallopR
400 newRMod = sphermath.vabs(yallopR+_b1950ETermsPos*
401 sphermath.vabs(yallopR)-spatialCorr)
402 newR = yallopR+_b1950ETermsPos*newRMod-spatialCorr
403 newRd = yallopRd+_b1950ETermsVel*newRMod-numpy.dot(
404 yallopR, _b1950ETermsVel)*yallopR
405
406 return _yallopToSv(numpy.concatenate((newR, newRd)),
407 _yallopKSla, rvAndPrlx)
408
409
410 ############### Galactic coordinates
411
412 _galB1950pole = (192.25*DEG, 27.4*DEG)
413 _galB1950zero = (265.6108440311*DEG, -28.9167903484*DEG)
414
415 _b1950ToGalTrafo = sphermath.computeTransMatrixFromPole(
416 _galB1950pole, _galB1950zero)
417 _b1950ToGalMatrix = threeToSix(_b1950ToGalTrafo)
418
419 # For convenience, a ready-made matrix, taken basically from SLALIB
420 _galToJ2000Matrix = threeToSix(numpy.transpose(numpy.array([
421 [-0.054875539695716, -0.873437107995315, -0.483834985836994],
422 [ 0.494109453305607, -0.444829589431879, 0.746982251810510],
423 [-0.867666135847849, -0.198076386130820, 0.455983795721093]])))
424
425
426 ############### Supergalactic coordinates
427
428 _galToSupergalTrafo = sphermath.computeTransMatrixFromPole(
429 (47.37*DEG, 6.32*DEG), (137.37*DEG, 0))
430 _galToSupergalMatrix = threeToSix(_galToSupergalTrafo)
431
432
433 ############### Ecliptic coordinates
434
435 def _getEclipticMatrix(epoch):
436 """returns the rotation matrix from equatorial to ecliptic at datetime epoch.
437
438 Strictly, epoch should be a TDB.
439 """
440 t = times.getSeconds(epoch-times.dtJ2000)/common.secsPerJCy
441 obliquity = (84381.448+(-46.8150+(-0.00059+0.001813*t)*t)*t)*ARCSEC
442 return mathtricks.getRotX(obliquity)
443
444 def _getFromEclipticMatrix(fromNode, toNode, sixTrans):
445 return threeToSix(numpy.transpose(_getEclipticMatrix(fromNode[1])))
446
447 def _getToEclipticMatrix(fromNode, toNode, sixTrans):
448 emat = _getEclipticMatrix(fromNode[1])
449 return threeToSix(emat)
450
451
452 ############### ICRS a.k.a. Hipparcos
453 # This is all parallel to IAU sofa, i.e. no zonal corrections, etc.
454 # From FK5hip
455
456 def cross(vec1, vec2):
457 """returns the cross product of two 3-vectors.
458
459 This should really be somewhere else...
460 """
461 return numpy.array([
462 vec1[1]*vec2[2]-vec1[2]*vec2[1],
463 vec1[2]*vec2[0]-vec1[0]*vec2[2],
464 vec1[0]*vec2[1]-vec1[1]*vec2[0],
465 ])
466
467 # Compute transformation from orientation of FK5
468 _fk5ToICRSMatrix = sphermath.getMatrixFromEulerVector(
469 numpy.array([-19.9e-3, -9.1e-3, 22.9e-3])*ARCSEC)
470 _icrsToFK5Matrix = numpy.transpose(_fk5ToICRSMatrix)
471
472 # Spin of FK5 in FK5 system
473 _fk5SpinFK5 = numpy.array([-0.30e-3, 0.60e-3, 0.70e-3])*ARCSEC/365.25
474 # Spin of FK5 in ICRS
475 _fk5SpinICRS = numpy.dot(_fk5ToICRSMatrix, _fk5SpinFK5)
476
477 def fk5ToICRS(sixTrans, svFk5):
478 """returns a 6-vector in ICRS for a 6-vector in FK5 J2000.
479 """
480 spatial = numpy.dot(_fk5ToICRSMatrix, svFk5[:3])
481 vel = numpy.dot(_fk5ToICRSMatrix,
482 svFk5[3:]+cross(svFk5[:3], _fk5SpinFK5))
483 return numpy.concatenate((spatial, vel))
484
485
486 def icrsToFK5(sixTrans, svICRS):
487 """returns a 6-vector in FK5 J2000 for an ICRS 6-vector.
488 """
489 spatial = numpy.dot(_icrsToFK5Matrix, svICRS[:3])
490 corrForSpin = svICRS[3:]-cross(svICRS[:3], _fk5SpinICRS)
491 vel = numpy.dot(_icrsToFK5Matrix, corrForSpin)
492 return numpy.concatenate((spatial, vel))
493
494
495 ############### Reference positions
496 # XXX TODO: We don't transform anything here. Yet. This will not
497 # hurt for moderate accuracy requirements in the stellar and
498 # extragalactic regime but makes this library basically useless for
499 # solar system work.
500
501 def _transformRefpos(sixTrans, sixVec):
502 return sixVec
503
504
505 ############### Top-level code
506
507
508 def _Constant(val):
509 """returns a transform factory always returning val.
510 """
511 return lambda fromSTC, toSTC, sixTrans: val
512
513
514 # transforms are triples of fromNode, toNode, transform factory. Due to
515 # the greedy nature of your "virtual graph" searching, it's generally a
516 # good idea to put more specific transforms further up.
517
518 _findTransformsPath = _makeFindPath([
519 (("FK4", times.dtB1950, SAME), ("FK5", times.dtJ2000, SAME),
520 _Constant(fk4ToFK5)),
521 (("FK5", times.dtJ2000, SAME), ("FK4", times.dtB1950, SAME),
522 _Constant(fk5ToFK4)),
523 (("FK5", times.dtJ2000, SAME), ("GALACTIC_II", ANYVAL, SAME),
524 _Constant(la.inv(_galToJ2000Matrix))),
525 (("GALACTIC_II", ANYVAL, SAME), ("FK5", times.dtJ2000, SAME),
526 _Constant(_galToJ2000Matrix)),
527 (("FK4", times.dtB1950, SAME), ("GALACTIC_II", ANYVAL, SAME),
528 _Constant(_b1950ToGalMatrix)),
529 (("GALACTIC_II", ANYVAL, SAME), ("FK4", times.dtB1950, SAME),
530 _Constant(la.inv(_b1950ToGalMatrix))),
531 (("GALACTIC_II", ANYVAL, SAME), ("SUPER_GALACTIC", ANYVAL, SAME),
532 _Constant(_galToSupergalMatrix)),
533 (("SUPER_GALACTIC", ANYVAL, SAME), ("GALACTIC_II", ANYVAL, SAME),
534 _Constant(la.inv(_galToSupergalMatrix))),
535 (("FK5", ANYVAL, SAME), ("FK5", times.dtJ2000, SAME),
536 _getIAU1976PrecMatrix),
537 (("FK4", ANYVAL, SAME), ("FK4", times.dtB1950, SAME),
538 _getNewcombPrecMatrix),
539 (("FK5", ANYVAL, SAME), ("FK5", ANYVAL, SAME),
540 _getIAU1976PrecMatrix),
541 (("FK4", ANYVAL, SAME), ("FK4", ANYVAL, SAME),
542 _getNewcombPrecMatrix),
543 (("ECLIPTIC", SAME, SAME), ("FK5", SAME, SAME),
544 _getFromEclipticMatrix),
545 (("FK5", SAME, SAME), ("ECLIPTIC", SAME, SAME),
546 _getToEclipticMatrix),
547 (("FK5", times.dtJ2000, SAME), ("ICRS", ANYVAL, SAME),
548 _Constant(fk5ToICRS)),
549 (("ICRS", ANYVAL, SAME), ("FK5", times.dtJ2000, SAME),
550 _Constant(icrsToFK5)),
551 ((SAME, SAME, ANYVAL), (SAME, SAME, ANYVAL),
552 _Constant(_transformRefpos)),
553 ])
554
555
556 _precessionFuncs = set([_getNewcombPrecMatrix, _getIAU1976PrecMatrix])
557
558 def _contractPrecessions(toContract):
559 """contracts the precessions in toContract.
560
561 No checks done. This is only intended as a helper for _simplifyPath.
562 """
563 return toContract[0][0], toContract[-1][1], toContract[0][-1]
564
565
566 def _simplifyPath(path):
567 """tries to simplify path by contracting multiple consecutive precessions.
568
569 These come in since our path finding algorithm sucks. This is mainly
570 done for numerical reasons since the matrices would be contracted for
571 computation anyway.
572 """
573 # Sorry about this complex mess. Maybe we want a more general optimization
574 # framework.
575 if path is None:
576 return path
577 newPath, toContract = [], []
578 curPrecFunc = None
579 for t in path:
580 if curPrecFunc:
581 if t[-1] is curPrecFunc:
582 toContract.append(t)
583 else:
584 newPath.append(_contractPrecessions(toContract))
585 if t[-1] in _precessionFuncs:
586 curPrecFunc, toContract = t[-1], [t]
587 else:
588 curPrecFunc, toContract = None, []
589 newPath.append(t)
590 else:
591 if t[-1] in _precessionFuncs:
592 curPrecFunc = t[-1]
593 toContract = [t]
594 else:
595 newPath.append(t)
596 if toContract:
597 newPath.append(_contractPrecessions(toContract))
598 return newPath
599
600 def _contractMatrices(ops):
601 """combines consecutive numpy.matrix instances in the sequence
602 ops by dot-multiplying them.
603 """
604 newSeq, curMat = [], None
605 for op in ops:
606 if isinstance(op, numpy.ndarray):
607 if curMat is None:
608 curMat = op
609 else:
610 curMat = numpy.dot(curMat, op)
611 else:
612 if curMat is not None:
613 newSeq.append(curMat)
614 curMat = None
615 newSeq.append(op)
616 if curMat is not None:
617 newSeq.append(curMat)
618 return newSeq
619
620
621 def _pathToFunction(trafoPath, sixTrans):
622 """returns a function encapsulating all operations contained in
623 trafoPath.
624
625 The function receives and returns a 6-vector. trafoPath is altered.
626 """
627 trafoPath.reverse()
628 steps = _contractMatrices([factory(srcTrip, dstTrip, sixTrans)
629 for srcTrip, dstTrip, factory in trafoPath])
630 expr = []
631 for index, step in enumerate(steps):
632 if isinstance(step, numpy.ndarray):
633 expr.append("numpy.dot(steps[%d], "%index)
634 else:
635 expr.append("steps[%d](sixTrans, "%index)
636 vars = {"steps": steps, "numpy": numpy}
637 exec(("def transform(sv, sixTrans): return %s"%
638 "".join(expr)+"sv"+(")"*len(expr))), vars)
639 return vars["transform"]
640
641
642 def nullTransform(sv, sixTrans):
643 return sv
644
645
646 @functools.lru_cache()
647 def getTrafoFunction(srcTriple, dstTriple, sixTrans):
648 """returns a function that transforms 6-vectors from the system
649 described by srcTriple to the one described by dstTriple.
650
651 The triples consist of (system, equinox, refpoint).
652
653 If no transformation function can be produced, the function raises
654 an STCValueError.
655
656 sixTrans is a sphermath.SVConverter instance, used here for communication
657 of input details and user preferences.
658 """
659 # special case the identity since it's indistingishable from a failed
660 # search otherwise
661 if srcTriple==dstTriple:
662 return nullTransform
663 trafoPath = _simplifyPath(_findTransformsPath(srcTriple, dstTriple))
664 if trafoPath is None:
665 raise common.STCValueError("Cannot find a transform from %s to %s"%(
666 srcTriple, dstTriple))
667 return _pathToFunction(trafoPath, sixTrans)