/
coords.py
2645 lines (2365 loc) · 82.5 KB
/
coords.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################################################################
#
# coords: module for coordinate transformations between the equatorial
# and Galactic coordinate frame
#
#
# Main included functions:
# radec_to_lb
# lb_to_radec
# radec_to_custom
# custom_to_radec
# lbd_to_XYZ
# XYZ_to_lbd
# rectgal_to_sphergal
# sphergal_to_rectgal
# vrpmllpmbb_to_vxvyvz
# vxvyvz_to_vrpmllpmbb
# pmrapmdec_to_pmllpmbb
# pmllpmbb_to_pmrapmdec
# pmrapmdec_to_custom
# custom_to_pmrapmdec
# cov_pmrapmdec_to_pmllpmbb
# cov_dvrpmllbb_to_vxyz
# XYZ_to_galcenrect
# XYZ_to_galcencyl
# galcenrect_to_XYZ
# galcencyl_to_XYZ
# rect_to_cyl
# cyl_to_rect
# rect_to_cyl_vec
# cyl_to_rect_vec
# vxvyvz_to_galcenrect
# vxvyvz_to_galcencyl
# galcenrect_to_vxvyvz
# galcencyl_to_vxvyvz
# dl_to_rphi_2d
# rphi_to_dl_2d
# Rz_to_coshucosv
# Rz_to_uv
# uv_to_Rz
# Rz_to_lambdanu
# Rz_to_lambdanu_jac
# Rz_to_lambdanu_hess
# lambdanu_to_Rz
#
##############################################################################
#############################################################################
# Copyright (c) 2010 - 2020, Jo Bovy
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
# WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#############################################################################
from functools import wraps
import numpy
from ..util import _rotate_to_arbitrary_vector
from ..util._optional_deps import _APY_LOADED
from ..util.config import __config__
_APY_COORDS = __config__.getboolean("astropy", "astropy-coords")
_APY_COORDS *= _APY_LOADED
_DEGTORAD = numpy.pi / 180.0
if _APY_LOADED:
import astropy.coordinates as apycoords
from astropy import units
_K = (
(1.0 * units.mas / units.yr)
.to(units.km / units.s / units.kpc, equivalencies=units.dimensionless_angles())
.value
)
else:
_K = 4.74047
# numpy 1.14 einsum bug causes astropy conversions to fail in py2.7 -> turn off
if _APY_COORDS:
ra, dec = numpy.array([192.25 * _DEGTORAD]), numpy.array([27.4 * _DEGTORAD])
c = apycoords.SkyCoord(
ra * units.rad, dec * units.rad, equinox="B1950", frame="fk4"
)
# This conversion fails bc of einsum bug
try:
c = c.transform_to(apycoords.Galactic)
except TypeError: # pragma: no cover
_APY_COORDS = False
def scalarDecorator(func):
"""Decorator to return scalar outputs as a set"""
@wraps(func)
def scalar_wrapper(*args, **kwargs):
if numpy.array(args[0]).shape == ():
scalarOut = True
newargs = ()
for ii in range(len(args)):
newargs = newargs + (numpy.array([args[ii]]),)
args = newargs
else:
scalarOut = False
result = func(*args, **kwargs)
if scalarOut:
out = ()
for ii in range(result.shape[1]):
out = out + (result[0, ii],)
return out
else:
return result
return scalar_wrapper
def degreeDecorator(inDegrees, outDegrees):
"""
Decorator to transform angles from and to degrees if necessary
Parameters
----------
inDegrees : list
List specifying indices of angle arguments (e.g., [0,1])
outDegrees : list
Same as inDegrees, but for function return
Returns
-------
function
Wrapped function
Notes
-----
- ____-__-__ - Written - Bovy
- 2019-03-02 - speedup - Nathaniel Starkman (UofT)
"""
# (modified) old degree decorator
def wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
isdeg = kwargs.get("degree", False)
if isdeg:
args = [
arg * numpy.pi / 180 if i in inDegrees else arg
for i, arg in enumerate(args)
]
out = func(*args, **kwargs)
if isdeg:
for i in outDegrees:
out[:, i] *= 180.0 / numpy.pi
return out
return wrapped
return wrapper
@scalarDecorator
@degreeDecorator([0, 1], [0, 1])
def radec_to_lb(ra, dec, degree=False, epoch=2000.0):
"""
Transform from equatorial coordinates to Galactic coordinates
Parameters
----------
ra : float or numpy.ndarray
Right ascension
dec : float or numpy.ndarray
Declination
degree : bool, optional
If True, ra and dec are given in degree and l and b will be as well
epoch : float, optional
Epoch of ra,dec (right now only 2000.0 and 1950.0 are supported when not using astropy's transformations internally; when internally using astropy's coordinate transformations, epoch can be None for ICRS, 'JXXXX' for FK5, and 'BXXXX' for FK4)
Returns
-------
tuple or numpy.ndarray
Galactic longitude and latitude
Notes
-----
- 2009-11-12 - Written - Bovy (NYU)
- 2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
- 2016-05-13 - Added support for using astropy's coordinate transformations and for non-standard epochs - Bovy (UofT)
"""
if _APY_COORDS:
epoch, frame = _parse_epoch_frame_apy(epoch)
c = apycoords.SkyCoord(
ra * units.rad, dec * units.rad, equinox=epoch, frame=frame
)
c = c.transform_to(apycoords.Galactic)
return numpy.array([c.l.to(units.rad).value, c.b.to(units.rad).value]).T
# First calculate the transformation matrix T
theta, dec_ngp, ra_ngp = get_epoch_angles(epoch)
T = numpy.dot(
numpy.array(
[
[numpy.cos(theta), numpy.sin(theta), 0.0],
[numpy.sin(theta), -numpy.cos(theta), 0.0],
[0.0, 0.0, 1.0],
]
),
numpy.dot(
numpy.array(
[
[-numpy.sin(dec_ngp), 0.0, numpy.cos(dec_ngp)],
[0.0, 1.0, 0.0],
[numpy.cos(dec_ngp), 0.0, numpy.sin(dec_ngp)],
]
),
numpy.array(
[
[numpy.cos(ra_ngp), numpy.sin(ra_ngp), 0.0],
[-numpy.sin(ra_ngp), numpy.cos(ra_ngp), 0.0],
[0.0, 0.0, 1.0],
]
),
),
)
# Whether to use degrees and scalar input is handled by decorators
XYZ = numpy.array(
[numpy.cos(dec) * numpy.cos(ra), numpy.cos(dec) * numpy.sin(ra), numpy.sin(dec)]
)
galXYZ = numpy.dot(T, XYZ)
galXYZ[2][galXYZ[2] > 1.0] = 1.0
galXYZ[2][galXYZ[2] < -1.0] = -1.0
b = numpy.arcsin(galXYZ[2])
l = numpy.arctan2(galXYZ[1] / numpy.cos(b), galXYZ[0] / numpy.cos(b))
l[l < 0.0] += 2.0 * numpy.pi
out = numpy.array([l, b])
return out.T
@scalarDecorator
@degreeDecorator([0, 1], [0, 1])
def lb_to_radec(l, b, degree=False, epoch=2000.0):
"""
Transform from Galactic coordinates to equatorial coordinates
Parameters
----------
l : float or numpy.ndarray
Galactic longitude
b : float or numpy.ndarray
Galactic latitude
degree : bool, optional
If True, l and b are given in degree and ra and dec will be as well
epoch : float, optional
Epoch of ra,dec (right now only 2000.0 and 1950.0 are supported when not using astropy's transformations internally; when internally using astropy's coordinate transformations, epoch can be None for ICRS, 'JXXXX' for FK5, and 'BXXXX' for FK4)
Returns
-------
tuple or numpy.ndarray
Right ascension and declination
Notes
-----
- 2010-04-07 - Written - Bovy (NYU)
- 2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
- 2016-05-13 - Added support for using astropy's coordinate transformations and for non-standard epochs - Bovy (UofT)
"""
if _APY_COORDS:
epoch, frame = _parse_epoch_frame_apy(epoch)
c = apycoords.SkyCoord(l * units.rad, b * units.rad, frame="galactic")
if not epoch is None and "J" in epoch:
c = c.transform_to(apycoords.FK5(equinox=epoch))
elif not epoch is None and "B" in epoch:
c = c.transform_to(apycoords.FK4(equinox=epoch))
else:
c = c.transform_to(apycoords.ICRS)
return numpy.array([c.ra.to(units.rad).value, c.dec.to(units.rad).value]).T
# First calculate the transformation matrix T'
theta, dec_ngp, ra_ngp = get_epoch_angles(epoch)
T = numpy.dot(
numpy.array(
[
[numpy.cos(ra_ngp), -numpy.sin(ra_ngp), 0.0],
[numpy.sin(ra_ngp), numpy.cos(ra_ngp), 0.0],
[0.0, 0.0, 1.0],
]
),
numpy.dot(
numpy.array(
[
[-numpy.sin(dec_ngp), 0.0, numpy.cos(dec_ngp)],
[0.0, 1.0, 0.0],
[numpy.cos(dec_ngp), 0.0, numpy.sin(dec_ngp)],
]
),
numpy.array(
[
[numpy.cos(theta), numpy.sin(theta), 0.0],
[numpy.sin(theta), -numpy.cos(theta), 0.0],
[0.0, 0.0, 1.0],
]
),
),
)
# Whether to use degrees and scalar input is handled by decorators
XYZ = numpy.array(
[numpy.cos(b) * numpy.cos(l), numpy.cos(b) * numpy.sin(l), numpy.sin(b)]
)
eqXYZ = numpy.dot(T, XYZ)
dec = numpy.arcsin(eqXYZ[2])
ra = numpy.arctan2(eqXYZ[1], eqXYZ[0])
ra[ra < 0.0] += 2.0 * numpy.pi
return numpy.array([ra, dec]).T
@scalarDecorator
@degreeDecorator([0, 1], [])
def lbd_to_XYZ(l, b, d, degree=False):
"""
Transform from spherical Galactic coordinates to rectangular Galactic coordinates (works with vector inputs)
Parameters
----------
l : float or numpy.ndarray
Galactic longitude (rad)
b : float or numpy.ndarray
Galactic latitude (rad)
d : float or numpy.ndarray
Distance (arbitrary units)
degree : bool, optional
If True, l and b are in degrees. Default is False.
Returns
-------
tuple or numpy.ndarray
[X,Y,Z] in whatever units d was in. For vector inputs [:,3]
Notes
-----
- 2009-10-24 - Written - Bovy (NYU)
- 2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
"""
# Whether to use degrees and scalar input is handled by decorators
return numpy.array(
[
d * numpy.cos(b) * numpy.cos(l),
d * numpy.cos(b) * numpy.sin(l),
d * numpy.sin(b),
]
).T
def rectgal_to_sphergal(X, Y, Z, vx, vy, vz, degree=False):
"""
Transform phase-space coordinates in rectangular Galactic coordinates to spherical Galactic coordinates (can take vector inputs)
Parameters
----------
X : float or numpy.ndarray
Component towards the Galactic Center (kpc)
Y : float or numpy.ndarray
Component in the direction of Galactic rotation (kpc)
Z : float or numpy.ndarray
Component towards the North Galactic Pole (kpc)
vx : float or numpy.ndarray
Velocity towards the Galactic Center (km/s)
vy : float or numpy.ndarray
Velocity in the direction of Galactic rotation (km/s)
vz : float or numpy.ndarray
Velocity towards the North Galactic Pole (km/s)
degree : bool, optional
If True, return l and b in degrees. Default is False.
Returns
-------
tuple or numpy.ndarray
[l,b,d,vr,pmll x cos(b),pmbb] in (rad,rad,kpc,km/s,mas/yr,mas/yr). For vector inputs [:,6]
Notes
-----
- 2009-10-25 - Written - Bovy (NYU)
"""
lbd = XYZ_to_lbd(X, Y, Z, degree=degree)
vrpmllpmbb = vxvyvz_to_vrpmllpmbb(vx, vy, vz, X, Y, Z, XYZ=True)
if numpy.array(X).shape == ():
return numpy.array(
[lbd[0], lbd[1], lbd[2], vrpmllpmbb[0], vrpmllpmbb[1], vrpmllpmbb[2]]
)
else:
out = numpy.zeros((len(X), 6))
out[:, 0:3] = lbd
out[:, 3:6] = vrpmllpmbb
return out
def sphergal_to_rectgal(l, b, d, vr, pmll, pmbb, degree=False):
"""
Transform phase-space coordinates in spherical Galactic coordinates to rectangular Galactic coordinates (can take vector inputs)
Parameters
----------
l : float or numpy.ndarray
Galactic longitude
b : float or numpy.ndarray
Galactic latitude
d : float or numpy.ndarray
Distance (kpc)
vr : float or numpy.ndarray
Line-of-sight velocity (km/s)
pmll : float or numpy.ndarray
Proper motion in the Galactic longitude direction (mu_l * cos(b)) (mas/yr)
pmbb : float or numpy.ndarray
Proper motion in the Galactic latitude (mas/yr)
degree : bool, optional
If True, l and b are in degrees. Default is False.
Returns
-------
tuple or numpy.ndarray
[X,Y,Z,vx,vy,vz] in (kpc,kpc,kpc,km/s,km/s,km/s). For vector inputs [:,6]
Notes
-----
- 2009-10-25 - Written - Bovy (NYU)
"""
XYZ = lbd_to_XYZ(l, b, d, degree=degree)
vxvyvz = vrpmllpmbb_to_vxvyvz(vr, pmll, pmbb, l, b, d, XYZ=False, degree=degree)
if numpy.array(l).shape == ():
return numpy.array([XYZ[0], XYZ[1], XYZ[2], vxvyvz[0], vxvyvz[1], vxvyvz[2]])
else:
out = numpy.zeros((len(l), 6))
out[:, 0:3] = XYZ
out[:, 3:6] = vxvyvz
return out
@scalarDecorator
@degreeDecorator([3, 4], [])
def vrpmllpmbb_to_vxvyvz(vr, pmll, pmbb, l, b, d, XYZ=False, degree=False):
"""
Transform velocities in the spherical Galactic coordinate frame to the rectangular Galactic coordinate frame (can take vector inputs)
Parameters
----------
vr : float or numpy.ndarray
Line-of-sight velocity (km/s)
pmll : float or numpy.ndarray
Proper motion in the Galactic longitude direction (mu_l * cos(b)) (mas/yr)
pmbb : float or numpy.ndarray
Proper motion in the Galactic latitude (mas/yr)
l : float or numpy.ndarray
Galactic longitude
b : float or numpy.ndarray
Galactic latitude
d : float or numpy.ndarray
Distance (kpc)
XYZ : bool, optional
If True, then l,b,d is actually X,Y,Z (rectangular Galactic coordinates). Default is False.
degree : bool, optional
If True, l and b are in degrees. Default is False.
Returns
-------
tuple or numpy.ndarray
[vx,vy,vz] in (km/s,km/s,km/s). For vector inputs [:,3]
Notes
-----
- 2009-10-24 - Written - Bovy (NYU)
- 2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
"""
# Whether to use degrees and scalar input is handled by decorators
if XYZ: # undo the incorrect conversion that the decorator did
if degree:
l *= 180.0 / numpy.pi
b *= 180.0 / numpy.pi
lbd = XYZ_to_lbd(l, b, d, degree=False)
l = lbd[:, 0]
b = lbd[:, 1]
d = lbd[:, 2]
R = numpy.zeros((3, 3, len(l)))
R[0, 0] = numpy.cos(l) * numpy.cos(b)
R[1, 0] = -numpy.sin(l)
R[2, 0] = -numpy.cos(l) * numpy.sin(b)
R[0, 1] = numpy.sin(l) * numpy.cos(b)
R[1, 1] = numpy.cos(l)
R[2, 1] = -numpy.sin(l) * numpy.sin(b)
R[0, 2] = numpy.sin(b)
R[2, 2] = numpy.cos(b)
invr = numpy.array(
[
[vr, vr, vr],
[d * pmll * _K, d * pmll * _K, d * pmll * _K],
[d * pmbb * _K, d * pmbb * _K, d * pmbb * _K],
]
)
return (R.T * invr.T).sum(-1)
@scalarDecorator
@degreeDecorator([3, 4], [])
def vxvyvz_to_vrpmllpmbb(vx, vy, vz, l, b, d, XYZ=False, degree=False):
"""
Transform velocities in the rectangular Galactic coordinate frame to the spherical Galactic coordinate frame (can take vector inputs)
Parameters
----------
vx : float or numpy.ndarray
Velocity towards the Galactic Center (km/s)
vy : float or numpy.ndarray
Velocity in the direction of Galactic rotation (km/s)
vz : float or numpy.ndarray
Velocity towards the North Galactic Pole (km/s)
l : float or numpy.ndarray
Galactic longitude
b : float or numpy.ndarray
Galactic latitude
d : float or numpy.ndarray
Distance (kpc)
XYZ : bool, optional
If True, then l,b,d is actually X,Y,Z (rectangular Galactic coordinates). Default is False.
degree : bool, optional
If True, l and b are in degrees. Default is False.
Returns
-------
tuple or numpy.ndarray
[vr,pmll x cos(b),pmbb] in (km/s,mas/yr,mas/yr). For vector inputs [:,3]
Notes
-----
- 2009-10-24 - Written - Bovy (NYU)
- 2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
"""
# Whether to use degrees and scalar input is handled by decorators
if XYZ: # undo the incorrect conversion that the decorator did
if degree:
l *= 180.0 / numpy.pi
b *= 180.0 / numpy.pi
lbd = XYZ_to_lbd(l, b, d, degree=False)
l = lbd[:, 0]
b = lbd[:, 1]
d = lbd[:, 2]
R = numpy.zeros((3, 3, len(l)))
R[0, 0] = numpy.cos(l) * numpy.cos(b)
R[0, 1] = -numpy.sin(l)
R[0, 2] = -numpy.cos(l) * numpy.sin(b)
R[1, 0] = numpy.sin(l) * numpy.cos(b)
R[1, 1] = numpy.cos(l)
R[1, 2] = -numpy.sin(l) * numpy.sin(b)
R[2, 0] = numpy.sin(b)
R[2, 2] = numpy.cos(b)
invxyz = numpy.array([[vx, vx, vx], [vy, vy, vy], [vz, vz, vz]])
vrvlvb = (R.T * invxyz.T).sum(-1)
vrvlvb[:, 1] /= d * _K
vrvlvb[:, 2] /= d * _K
return vrvlvb
@scalarDecorator
@degreeDecorator([], [0, 1])
def XYZ_to_lbd(X, Y, Z, degree=False):
"""
Transform from rectangular Galactic coordinates to spherical Galactic coordinates (works with vector inputs)
Parameters
----------
X : float or numpy.ndarray
Component towards the Galactic Center (in kpc; though this obviously does not matter))
Y : float or numpy.ndarray
Component in the direction of Galactic rotation (in kpc)
Z : float or numpy.ndarray
Component towards the North Galactic Pole (kpc)
degree : bool, optional
If True, return l and b in degrees (default is False)
Returns
-------
tuple or numpy.ndarray
[l,b,d] in (rad or degree,rad or degree,kpc); for vector inputs [:,3]
Notes
-----
- 2009-10-24 - Written - Bovy (NYU)
- 2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
"""
# Whether to use degrees and scalar input is handled by decorators
d = numpy.sqrt(X**2.0 + Y**2.0 + Z**2.0)
b = numpy.arcsin(Z / d)
l = numpy.arctan2(Y, X)
l[l < 0.0] += 2.0 * numpy.pi
out = numpy.empty((len(d), 3))
out[:, 0] = l
out[:, 1] = b
out[:, 2] = d
return out
@scalarDecorator
@degreeDecorator([2, 3], [])
def pmrapmdec_to_pmllpmbb(pmra, pmdec, ra, dec, degree=False, epoch=2000.0):
"""
Rotate proper motions in (ra,dec) into proper motions in (l,b)
Parameters
----------
pmra : float or numpy.ndarray
Proper motion in ra (multiplied with cos(dec)) (mas/yr)
pmdec : float or numpy.ndarray
Proper motion in dec (mas/yr)
ra : float or numpy.ndarray
Right ascension
dec : float or numpy.ndarray
Declination
degree : bool, optional
If True, ra and dec are given in degrees (default=False)
epoch : float, optional
Epoch of ra,dec (right now only 2000.0 and 1950.0 are supported when not using astropy's transformations internally; when internally using astropy's coordinate transformations, epoch can be None for ICRS, 'JXXXX' for FK5, and 'BXXXX' for FK4)
Returns
-------
tuple or numpy.ndarray
[pmll x cos(b),pmbb] in (mas/yr,mas/yr). For vector inputs [:,2]
Notes
-----
- 2010-04-07 - Written - Bovy (NYU)
- 2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
"""
theta, dec_ngp, ra_ngp = get_epoch_angles(epoch)
# Whether to use degrees and scalar input is handled by decorators
dec[dec == dec_ngp] += 10.0**-16 # deal w/ pole.
sindec_ngp = numpy.sin(dec_ngp)
cosdec_ngp = numpy.cos(dec_ngp)
sindec = numpy.sin(dec)
cosdec = numpy.cos(dec)
sinrarangp = numpy.sin(ra - ra_ngp)
cosrarangp = numpy.cos(ra - ra_ngp)
# These were replaced by Poleski (2013)'s equivalent form that is better at the poles
# cosphi= (sindec_ngp-sindec*sinb)/cosdec/cosb
# sinphi= sinrarangp*cosdec_ngp/cosb
cosphi = sindec_ngp * cosdec - cosdec_ngp * sindec * cosrarangp
sinphi = sinrarangp * cosdec_ngp
norm = numpy.sqrt(cosphi**2.0 + sinphi**2.0)
cosphi /= norm
sinphi /= norm
return (
numpy.array([[cosphi, -sinphi], [sinphi, cosphi]]).T
* numpy.array([[pmra, pmra], [pmdec, pmdec]]).T
).sum(-1)
@scalarDecorator
@degreeDecorator([2, 3], [])
def pmllpmbb_to_pmrapmdec(pmll, pmbb, l, b, degree=False, epoch=2000.0):
"""
Rotate proper motions in (l,b) into proper motions in (ra,dec)
Parameters
----------
pmll : float or numpy.ndarray
Proper motion in l (multiplied with cos(b)) (mas/yr)
pmbb : float or numpy.ndarray
Proper motion in b (mas/yr)
l : float or numpy.ndarray
Galactic longitude
b : float or numpy.ndarray
Galactic latitude
degree : bool, optional
If True, l and b are given in degrees (default=False)
epoch : float, optional
Epoch of ra,dec (right now only 2000.0 and 1950.0 are supported when not using astropy's transformations internally; when internally using astropy's coordinate transformations, epoch can be None for ICRS, 'JXXXX' for FK5, and 'BXXXX' for FK4)
Returns
-------
tuple or numpy.ndarray
[pmra x cos(dec),pmdec] in (mas/yr,mas/yr). For vector inputs [:,2]
Notes
-----
- 2010-04-07 - Written - Bovy (NYU)
- 2014-06-14 - Re-written w/ numpy functions for speed and w/ decorators for beauty - Bovy (IAS)
"""
theta, dec_ngp, ra_ngp = get_epoch_angles(epoch)
# Whether to use degrees and scalar input is handled by decorators
radec = lb_to_radec(l, b, degree=False, epoch=epoch)
ra = radec[:, 0]
dec = radec[:, 1]
dec[dec == dec_ngp] += 10.0**-16 # deal w/ pole.
sindec_ngp = numpy.sin(dec_ngp)
cosdec_ngp = numpy.cos(dec_ngp)
sindec = numpy.sin(dec)
cosdec = numpy.cos(dec)
sinrarangp = numpy.sin(ra - ra_ngp)
cosrarangp = numpy.cos(ra - ra_ngp)
# These were replaced by Poleski (2013)'s equivalent form that is better at the poles
# cosphi= (sindec_ngp-sindec*sinb)/cosdec/cosb
# sinphi= sinrarangp*cosdec_ngp/cosb
cosphi = sindec_ngp * cosdec - cosdec_ngp * sindec * cosrarangp
sinphi = sinrarangp * cosdec_ngp
norm = numpy.sqrt(cosphi**2.0 + sinphi**2.0)
cosphi /= norm
sinphi /= norm
return (
numpy.array([[cosphi, sinphi], [-sinphi, cosphi]]).T
* numpy.array([[pmll, pmll], [pmbb, pmbb]]).T
).sum(-1)
def cov_pmrapmdec_to_pmllpmbb(cov_pmradec, ra, dec, degree=False, epoch=2000.0):
"""
Propagate the proper motions errors through the rotation from (ra,dec) to (l,b)
Parameters
----------
cov_pmradec : numpy.ndarray
Uncertainty covariance matrix of the proper motion in ra (multiplied with cos(dec)) and dec [2,2] or [:,2,2]
ra : float or numpy.ndarray
Right ascension
dec : float or numpy.ndarray
Declination
degree : bool, optional
If True, ra and dec are given in degrees (default=False)
epoch : float, optional
Epoch of ra,dec (right now only 2000.0 and 1950.0 are supported when not using astropy's transformations internally; when internally using astropy's coordinate transformations, epoch can be None for ICRS, 'JXXXX' for FK5, and 'BXXXX' for FK4)
Returns
-------
numpy.ndarray
covar_pmllbb [2,2] or [:,2,2] [pmll here is pmll x cos(b)]
Notes
-----
- 2010-04-12 - Written - Bovy (NYU)
- 2020-09-21 - Adapted for array input - Mackereth (UofT)
"""
scalar = not hasattr(ra, "__iter__")
if scalar:
cov_pmradec = cov_pmradec[numpy.newaxis, :, :]
theta, dec_ngp, ra_ngp = get_epoch_angles(epoch)
if degree:
sindec_ngp = numpy.sin(dec_ngp)
cosdec_ngp = numpy.cos(dec_ngp)
sindec = numpy.sin(dec * _DEGTORAD)
cosdec = numpy.cos(dec * _DEGTORAD)
sinrarangp = numpy.sin(ra * _DEGTORAD - ra_ngp)
cosrarangp = numpy.cos(ra * _DEGTORAD - ra_ngp)
else:
sindec_ngp = numpy.sin(dec_ngp)
cosdec_ngp = numpy.cos(dec_ngp)
sindec = numpy.sin(dec)
cosdec = numpy.cos(dec)
sinrarangp = numpy.sin(ra - ra_ngp)
cosrarangp = numpy.cos(ra - ra_ngp)
# These were replaced by Poleski (2013)'s equivalent form that is better at the poles
# cosphi= (sindec_ngp-sindec*sinb)/cosdec/cosb
# sinphi= sinrarangp*cosdec_ngp/cosb
cosphi = sindec_ngp * cosdec - cosdec_ngp * sindec * cosrarangp
sinphi = sinrarangp * cosdec_ngp
norm = numpy.sqrt(cosphi**2.0 + sinphi**2.0)
cosphi /= norm
sinphi /= norm
P = numpy.zeros([len(cov_pmradec), 2, 2])
P[:, 0, 0] = cosphi
P[:, 0, 1] = sinphi
P[:, 1, 0] = -sinphi
P[:, 1, 1] = cosphi
out = numpy.einsum(
"aij,ajk->aik", P, numpy.einsum("aij,jka->aik", cov_pmradec, P.T)
)
if scalar:
return out[0]
else:
return out
def cov_dvrpmllbb_to_vxyz(
d, e_d, e_vr, pmll, pmbb, cov_pmllbb, l, b, plx=False, degree=False
):
"""
Propagate distance, radial velocity, and proper motion uncertainties to Galactic coordinates
Parameters
----------
d : float or numpy.ndarray
Distance [kpc, as/mas for plx]
e_d : float or numpy.ndarray
Distance uncertainty [kpc, [as/mas] for plx]
e_vr : float or numpy.ndarray
Low velocity uncertainty [km/s]
pmll : float or numpy.ndarray
Proper motion in l (*cos(b)) [ [as/mas]/yr ]
pmbb : float or numpy.ndarray
Proper motion in b [ [as/mas]/yr ]
cov_pmllbb : numpy.ndarray
Uncertainty covariance for proper motion [pmll is pmll x cos(b)] [:,2,2]
l : float or numpy.ndarray
Galactic longitude
b : float or numpy.ndarray
Galactic latitude
plx : bool, optional
If True, d is a parallax, and e_d is a parallax uncertainty (default=False)
degree : bool, optional
If True, l and b are given in degree (default=False)
Returns
-------
numpy.ndarray
cov(vx,vy,vz) [3,3] or [:,3,3]
Notes
-----
- 2010-04-12 - Written - Bovy (NYU)
- 2020-09-21 - Adapted for array input - Mackereth (UofT)
"""
if plx:
d = 1.0 / d
e_d *= d**2.0
if degree:
l *= _DEGTORAD
b *= _DEGTORAD
scalar = not hasattr(d, "__iter__")
if scalar:
cov_pmllbb = cov_pmllbb[numpy.newaxis, :, :]
ndata = len(cov_pmllbb)
M = numpy.zeros((ndata, 2, 3))
M[:, 0, 0] = pmll
M[:, 1, 0] = pmbb
M[:, 0, 1] = d
M[:, 1, 2] = d
M = _K * M
cov_dpmllbb = numpy.zeros((ndata, 3, 3))
cov_dpmllbb[:, 0, 0] = e_d**2.0
cov_dpmllbb[:, 1:3, 1:3] = cov_pmllbb
cov_vlvb = numpy.einsum(
"aij,ajk->aik", M, numpy.einsum("aij,jka->aik", cov_dpmllbb, M.T)
)
if scalar:
cov_vlvb = cov_vlvb[0]
cov_vrvlvb = numpy.zeros((ndata, 3, 3))
cov_vrvlvb[:, 0, 0] = e_vr**2.0
cov_vrvlvb[:, 1:3, 1:3] = cov_vlvb
R = numpy.zeros((ndata, 3, 3))
R[:, 0, 0] = numpy.cos(l) * numpy.cos(b)
R[:, 0, 1] = numpy.sin(l) * numpy.cos(b)
R[:, 0, 2] = numpy.sin(b)
R[:, 1, 0] = -numpy.sin(l)
R[:, 1, 1] = numpy.cos(l)
R[:, 2, 0] = -numpy.cos(l) * numpy.sin(b)
R[:, 2, 1] = -numpy.sin(l) * numpy.sin(b)
R[:, 2, 2] = numpy.cos(b)
out = numpy.einsum("ija,ajk->aik", R.T, numpy.einsum("aij,ajk->aik", cov_vrvlvb, R))
if scalar:
return out[0]
else:
return out
def cov_vxyz_to_galcencyl(cov_vxyz, phi, Xsun=1.0, Zsun=0.0):
"""
Propagate uncertainties in vxyz to galactocentric cylindrical coordinates
Parameters
----------
cov_vxyz : numpy.ndarray
Uncertainty covariance in U,V,W [3,3] or [:,3,3]
phi : float or numpy.ndarray
Angular position of star in Galactocentric cylindrical coords [rad]
Xsun : float, optional
Cylindrical distance to the GC (can be array of same length as R) [kpc]
Zsun : float, optional
Sun's height above the midplane (can be array of same length as R) [kpc]
Returns
-------
numpy.ndarray
cov(vR,vT,vz) [3,3] or [:,3,3]
Notes
-----
- 2018-03-22 - Written - Mackereth (LJMU)
- 2020-09-21- Moved to coords.py - Mackereth (UofT)
"""
cov_galcenrect = cov_vxyz_to_galcenrect(cov_vxyz, Xsun=Xsun, Zsun=Zsun)
cov_galcencyl = cov_galcenrect_to_galcencyl(cov_galcenrect, phi)
return cov_galcencyl
def cov_vxyz_to_galcenrect(cov_vxyz, Xsun=1.0, Zsun=0.0):
"""
Propagate uncertainties in vxyz to galactocentric rectangular coordinates
Parameters
----------
cov_vxyz : numpy.ndarray
Uncertainty covariance in U,V,W [3,3] or [:,3,3]
Xsun : float, optional
Cylindrical distance to the GC (can be array of same length as R) [kpc]
Zsun : float, optional
Sun's height above the midplane (can be array of same length as R) [kpc]
Returns
-------
numpy.ndarray
cov(vx,vy,vz) [3,3] or [:,3,3]
Notes
-----
- 2018-03-22 - Written - Mackereth (LJMU)
- 2020-09-21- Moved to coords.py - Mackereth (UofT)
"""
scalar = cov_vxyz.ndim < 3
if scalar:
cov_vxyz = cov_vxyz[numpy.newaxis, :, :]
dgc = numpy.sqrt(Xsun**2.0 + Zsun**2.0)
costheta, sintheta = Xsun / dgc, Zsun / dgc
R = numpy.array(
[[costheta, 0.0, -sintheta], [0.0, 1.0, 0.0], [sintheta, 0.0, costheta]]
)
R = numpy.ones([len(cov_vxyz), 3, 3]) * R
out = numpy.einsum("ija,ajk->aik", R.T, numpy.einsum("aij,ajk->aik", cov_vxyz, R))
if scalar:
return out[0]
else:
return out
def cov_galcenrect_to_galcencyl(cov_galcenrect, phi):
"""
Propagate uncertainties in galactocentric rectangular to galactocentric cylindrical coordinates
Parameters
----------
cov_galcenrect : numpy.ndarray
Uncertainty covariance in vx,vy,vz [3,3] or [:,3,3]
phi : float or numpy.ndarray
Angular position of star in Galactocentric cylindrical coords [rad]
Returns
-------
numpy.ndarray
cov(vR,vT,vz) [3,3] or [:,3,3]
Notes
-----
- 2018-03-22 - Written - Mackereth (LJMU)
- 2020-09-21- Moved to coords.py - Mackereth (UofT)
"""
scalar = cov_galcenrect.ndim < 3
if scalar:
cov_galcenrect = cov_galcenrect[numpy.newaxis, :, :]
cosphi = numpy.cos(phi)
sinphi = numpy.sin(phi)
R = numpy.zeros([len(cov_galcenrect), 3, 3])
R[:, 0, 0] = cosphi
R[:, 0, 1] = sinphi
R[:, 1, 0] = -sinphi
R[:, 1, 1] = cosphi
R[:, 2, 2] = 1.0
out = numpy.einsum(
"aij,ajk->aik", R, numpy.einsum("aij,jka->aik", cov_galcenrect, R.T)
)
if scalar:
return out[0]
else:
return out
@scalarDecorator
def XYZ_to_galcenrect(X, Y, Z, Xsun=1.0, Zsun=0.0, _extra_rot=True):
"""
Transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates.
Parameters
----------
X : float or numpy.ndarray
X coordinate.
Y : float or numpy.ndarray
Y coordinate.
Z : float or numpy.ndarray
Z coordinate.
Xsun : float or numpy.ndarray, optional
Cylindrical distance to the Galactic center (default is 1.0).
Zsun : float or numpy.ndarray, optional
Sun's height above the midplane (default is 0.0).