/
diskdf.py
3235 lines (2973 loc) · 109 KB
/
diskdf.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
###############################################################################
# diskdf.py: module that interprets (E,Lz) pairs in terms of a
# distribution function (following Dehnen 1999)
#
# This module contains the following classes:
#
# diskdf - top-level class that represents a distribution function
# dehnendf - inherits from diskdf, implements Dehnen's 'new' DF
# shudf - inherits from diskdf, implements Shu's DF
# DFcorrection - class that represents corrections to the input Sigma(R)
# and sigma_R(R) to get closer to the targets
###############################################################################
_EPSREL = 10.0**-14.0
_NSIGMA = 4.0
_INTERPDEGREE = 3
_RMIN = 10.0**-10.0
_MAXD_REJECTLOS = 4.0
_PROFILE = False
import copy
import os
import os.path
import pickle
import numpy
import scipy
numpylog = (
numpy.lib.scimath.log
) # somehow, this code produces log(negative), which scipy (now numpy.lib.scimath.log) implements as log(|negative|) + i pi while numpy gives NaN and we want the scipy behavior; not sure where the log(negative) comes from though! I think it's for sigma=0 DFs (this test fails with numpy.log) where the DF eval has a log(~zero) that can be slightly negative because of numerical precision issues
from scipy import integrate, interpolate, optimize, stats
from ..actionAngle import actionAngleAdiabatic
from ..orbit import Orbit
from ..potential import PowerSphericalPotential
from ..util import conversion, quadpack, save_pickles
from ..util.ars import ars
from ..util.conversion import (
_APY_LOADED,
_APY_UNITS,
physical_conversion,
potential_physical_input,
surfdens_in_msolpc2,
)
from .df import df
from .surfaceSigmaProfile import expSurfaceSigmaProfile, surfaceSigmaProfile
if _APY_LOADED:
from astropy import units
# scipy version
from packaging.version import parse as parse_version
_SCIPY_VERSION = parse_version(scipy.__version__)
_SCIPY_VERSION_BREAK = parse_version("0.9")
_CORRECTIONSDIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data")
_DEGTORAD = numpy.pi / 180.0
class diskdf(df):
"""Class that represents a disk DF"""
def __init__(
self,
dftype="dehnen",
surfaceSigma=expSurfaceSigmaProfile,
profileParams=(1.0 / 3.0, 1.0, 0.2),
correct=False,
beta=0.0,
ro=None,
vo=None,
**kwargs
):
"""
Initialize a DF
Parameters
----------
dftype : str, optional
'dehnen' or 'corrected-dehnen', 'shu' or 'corrected-shu'
surfaceSigma : instance or class name of the target surface density and sigma_R profile, optional
(default: both exponential)
profileParams : tuple, optional
parameters of the surface and sigma_R profile: (xD,xS,Sro) where
* xD - disk surface mass scalelength / Ro
* xS - disk velocity dispersion scalelength / Ro
* Sro - disk velocity dispersion at Ro (/vo)
Directly given to the 'surfaceSigmaProfile class, so could be anything that class takes
beta : float, optional
power-law index of the rotation curve
correct : bool, optional
correct the DF (i.e., DFcorrection kwargs are also given)
ro : float or Quantity, optional
Distance scale for translation into internal units (default from configuration file).
vo : float or Quantity, optional
Velocity scale for translation into internal units (default from configuration file).
**kwargs : dict, optional
DFcorrection kwargs (except for those already specified)
Notes
-----
- 2010-03-10 - Written - Bovy (NYU)
"""
df.__init__(self, ro=ro, vo=vo)
self._dftype = dftype
if isinstance(surfaceSigma, surfaceSigmaProfile):
self._surfaceSigmaProfile = surfaceSigma
else:
if _APY_LOADED and isinstance(profileParams[0], units.Quantity):
newprofileParams = (
conversion.parse_length(profileParams[0], ro=self._ro),
conversion.parse_length(profileParams[1], ro=self._ro),
conversion.parse_velocity(profileParams[2], vo=self._vo),
)
self._roSet = True
self._voSet = True
profileParams = newprofileParams
self._surfaceSigmaProfile = surfaceSigma(profileParams)
self._beta = beta
self._gamma = numpy.sqrt(2.0 / (1.0 + self._beta))
if (
correct
or "corrections" in kwargs
or "rmax" in kwargs
or "niter" in kwargs
or "npoints" in kwargs
):
self._correct = True
# Load corrections
self._corr = DFcorrection(
dftype=self.__class__,
surfaceSigmaProfile=self._surfaceSigmaProfile,
beta=beta,
**kwargs
)
else:
self._correct = False
self._psp = PowerSphericalPotential(
normalize=1.0, alpha=2.0 - 2.0 * self._beta
).toPlanar()
# Setup aA objects for frequency and rap,rperi calculation
self._aA = actionAngleAdiabatic(pot=self._psp, gamma=0.0)
return None
@physical_conversion("phasespacedensity2d", pop=True)
def __call__(self, *args, **kwargs):
"""
Evaluate the distribution function
Parameters
----------
*args : tuple
Either:
1) Orbit instance or list:
a) Orbit instance alone: use initial condition
b) Orbit instance + t: call the Orbit instance (for list, each instance is called at t)
2) E,L - energy (/vo^2; or can be Quantity) and angular momentun (/ro/vo; or can be Quantity)
3) array vxvv [3/4,nt] [must be in natural units /vo,/ro; use Orbit interface for physical-unit input]
marginalizeVperp : bool, optional
marginalize over perpendicular velocity (only supported with 1a) for single orbits above)
marginalizeVlos : bool, optional
marginalize over line-of-sight velocity (only supported with 1a) for single orbits above)
nsigma : float, optional
number of sigma to integrate over when marginalizing
**kwargs: dict, optional
scipy.integrate.quad keywords
Returns
-------
float or numpy.ndarray
value of DF
Notes
-----
- 2010-07-10 - Written - Bovy (NYU)
"""
if isinstance(args[0], Orbit):
if len(args[0]) > 1:
raise RuntimeError(
"Only single-object Orbit instances can be passed to DF instances at this point"
) # pragma: no cover
if len(args) == 1:
if kwargs.pop("marginalizeVperp", False):
return self._call_marginalizevperp(args[0], **kwargs)
elif kwargs.pop("marginalizeVlos", False):
return self._call_marginalizevlos(args[0], **kwargs)
else:
return numpy.real(
self.eval(
*vRvTRToEL(
args[0].vR(use_physical=False),
args[0].vT(use_physical=False),
args[0].R(use_physical=False),
self._beta,
self._dftype,
)
)
)
else:
no = args[0](args[1])
return numpy.real(
self.eval(
*vRvTRToEL(
no.vR(use_physical=False),
no.vT(use_physical=False),
no.R(use_physical=False),
self._beta,
self._dftype,
)
)
)
elif isinstance(args[0], list) and isinstance(args[0][0], Orbit):
if numpy.any([len(no) > 1 for no in args[0]]):
raise RuntimeError(
"Only single-object Orbit instances can be passed to DF instances at this point"
) # pragma: no cover
# Grab all of the vR, vT, and R
vR = numpy.array([o.vR(use_physical=False) for o in args[0]])
vT = numpy.array([o.vT(use_physical=False) for o in args[0]])
R = numpy.array([o.R(use_physical=False) for o in args[0]])
return numpy.real(
self.eval(*vRvTRToEL(vR, vT, R, self._beta, self._dftype))
)
elif isinstance(args[0], numpy.ndarray) and not (
hasattr(args[0], "isscalar") and args[0].isscalar
):
# Grab all of the vR, vT, and R
vR = args[0][1]
vT = args[0][2]
R = args[0][0]
return numpy.real(
self.eval(*vRvTRToEL(vR, vT, R, self._beta, self._dftype))
)
else:
return numpy.real(self.eval(*args))
def _call_marginalizevperp(self, o, **kwargs):
"""Call the DF, marginalizing over perpendicular velocity"""
# Get l, vlos
l = o.ll(obs=[1.0, 0.0, 0.0], ro=1.0) * _DEGTORAD
vlos = o.vlos(ro=1.0, vo=1.0, obs=[1.0, 0.0, 0.0, 0.0, 0.0, 0.0])
R = o.R(use_physical=False)
phi = o.phi(use_physical=False)
# Get local circular velocity, projected onto the los
vcirc = R**self._beta
vcirclos = vcirc * numpy.sin(phi + l)
# Marginalize
alphalos = phi + l
if not "nsigma" in kwargs or ("nsigma" in kwargs and kwargs["nsigma"] is None):
nsigma = _NSIGMA
else:
nsigma = kwargs["nsigma"]
kwargs.pop("nsigma", None)
sigmaR2 = self.targetSigma2(R, use_physical=False)
sigmaR1 = numpy.sqrt(sigmaR2)
# Use the asymmetric drift equation to estimate va
va = (
sigmaR2
/ 2.0
/ R**self._beta
* (
1.0 / self._gamma**2.0
- 1.0
- R * self._surfaceSigmaProfile.surfacemassDerivative(R, log=True)
- R * self._surfaceSigmaProfile.sigma2Derivative(R, log=True)
)
)
if numpy.fabs(va) > sigmaR1:
va = 0.0 # To avoid craziness near the center
if numpy.fabs(numpy.sin(alphalos)) < numpy.sqrt(1.0 / 2.0):
cosalphalos = numpy.cos(alphalos)
tanalphalos = numpy.tan(alphalos)
return (
integrate.quad(
_marginalizeVperpIntegrandSinAlphaSmall,
-self._gamma * va / sigmaR1 - nsigma,
-self._gamma * va / sigmaR1 + nsigma,
args=(
self,
R,
cosalphalos,
tanalphalos,
vlos - vcirclos,
vcirc,
sigmaR1 / self._gamma,
),
**kwargs
)[0]
/ numpy.fabs(cosalphalos)
* sigmaR1
/ self._gamma
)
else:
sinalphalos = numpy.sin(alphalos)
cotalphalos = 1.0 / numpy.tan(alphalos)
return (
integrate.quad(
_marginalizeVperpIntegrandSinAlphaLarge,
-nsigma,
nsigma,
args=(
self,
R,
sinalphalos,
cotalphalos,
vlos - vcirclos,
vcirc,
sigmaR1,
),
**kwargs
)[0]
/ numpy.fabs(sinalphalos)
* sigmaR1
)
def _call_marginalizevlos(self, o, **kwargs):
"""Call the DF, marginalizing over line-of-sight velocity"""
# Get d, l, vperp
l = o.ll(obs=[1.0, 0.0, 0.0], ro=1.0) * _DEGTORAD
vperp = o.vll(ro=1.0, vo=1.0, obs=[1.0, 0.0, 0.0, 0.0, 0.0, 0.0])
R = o.R(use_physical=False)
phi = o.phi(use_physical=False)
# Get local circular velocity, projected onto the perpendicular
# direction
vcirc = R**self._beta
vcircperp = vcirc * numpy.cos(phi + l)
# Marginalize
alphaperp = numpy.pi / 2.0 + phi + l
if not "nsigma" in kwargs or ("nsigma" in kwargs and kwargs["nsigma"] is None):
nsigma = _NSIGMA
else:
nsigma = kwargs["nsigma"]
kwargs.pop("nsigma", None)
sigmaR2 = self.targetSigma2(R, use_physical=False)
sigmaR1 = numpy.sqrt(sigmaR2)
# Use the asymmetric drift equation to estimate va
va = (
sigmaR2
/ 2.0
/ R**self._beta
* (
1.0 / self._gamma**2.0
- 1.0
- R * self._surfaceSigmaProfile.surfacemassDerivative(R, log=True)
- R * self._surfaceSigmaProfile.sigma2Derivative(R, log=True)
)
)
if numpy.fabs(va) > sigmaR1:
va = 0.0 # To avoid craziness near the center
if numpy.fabs(numpy.sin(alphaperp)) < numpy.sqrt(1.0 / 2.0):
cosalphaperp = numpy.cos(alphaperp)
tanalphaperp = numpy.tan(alphaperp)
# we can reuse the VperpIntegrand, since it is just another angle
return (
integrate.quad(
_marginalizeVperpIntegrandSinAlphaSmall,
-self._gamma * va / sigmaR1 - nsigma,
-self._gamma * va / sigmaR1 + nsigma,
args=(
self,
R,
cosalphaperp,
tanalphaperp,
vperp - vcircperp,
vcirc,
sigmaR1 / self._gamma,
),
**kwargs
)[0]
/ numpy.fabs(cosalphaperp)
* sigmaR1
/ self._gamma
)
else:
sinalphaperp = numpy.sin(alphaperp)
cotalphaperp = 1.0 / numpy.tan(alphaperp)
# we can reuse the VperpIntegrand, since it is just another angle
return (
integrate.quad(
_marginalizeVperpIntegrandSinAlphaLarge,
-nsigma,
nsigma,
args=(
self,
R,
sinalphaperp,
cotalphaperp,
vperp - vcircperp,
vcirc,
sigmaR1,
),
**kwargs
)[0]
/ numpy.fabs(sinalphaperp)
* sigmaR1
)
@potential_physical_input
@physical_conversion("velocity2", pop=True)
def targetSigma2(self, R, log=False):
"""
Evaluate the target Sigma_R^2(R)
Parameters
----------
R : float or Quantity
Radius at which to evaluate.
log : bool, optional
If True, return the log (default: False).
Returns
-------
float
Target Sigma_R^2(R).
Notes
-----
- 2010-03-28 - Written - Bovy (NYU)
"""
return self._surfaceSigmaProfile.sigma2(R, log=log)
@potential_physical_input
@physical_conversion("surfacedensity", pop=True)
def targetSurfacemass(self, R, log=False):
"""
Evaluate the target surface mass at R.
Parameters
----------
R : float or Quantity
Radius at which to evaluate.
log : bool, optional
If True, return the log (default: False).
Returns
-------
float or Quantity
Target surface mass at R.
Notes
-----
- 2010-03-28 - Written - Bovy (NYU)
"""
return self._surfaceSigmaProfile.surfacemass(R, log=log)
@physical_conversion("surfacedensitydistance", pop=True)
def targetSurfacemassLOS(self, d, l, log=False, deg=True):
"""
Evaluate the target surface mass along the line of sight given Galactic longitude and distance.
Parameters
----------
d : float or Quantity
Distance along the line of sight.
l : float or Quantity
Galactic longitude in degrees, unless deg=False.
deg : bool, optional
If False, l is in radians. Default is True.
log : bool, optional
If True, return the logarithm of the surface mass. Default is False.
Returns
-------
float or Quantity
Surface mass times distance.
Notes
-----
- 2011-03-23 - Written - Bovy (NYU)
"""
# Calculate R and phi
if _APY_LOADED and isinstance(l, units.Quantity):
lrad = conversion.parse_angle(l)
elif deg:
lrad = l * _DEGTORAD
else:
lrad = l
d = conversion.parse_length(d, ro=self._ro)
R, phi = _dlToRphi(d, lrad)
if log:
return self._surfaceSigmaProfile.surfacemass(R, log=log) + numpylog(d)
else:
return self._surfaceSigmaProfile.surfacemass(R, log=log) * d
@physical_conversion("surfacedensitydistance", pop=True)
def surfacemassLOS(
self, d, l, deg=True, target=True, romberg=False, nsigma=None, relative=None
):
"""
Evaluate the surface mass along the line of sight (LOS) given Galactic longitude and distance.
Parameters
----------
d : float or Quantity
Distance along the line of sight.
l : float or Quantity
Galactic longitude (in deg, unless deg=False).
nsigma : float, optional
Number of sigma to integrate the velocities over.
target : bool, optional
If True, use target surfacemass (default).
romberg : bool, optional
If True, use a romberg integrator (default: False).
deg : bool, optional
If False, l is in radians.
relative : bool, optional
If True, return d.
Returns
-------
float
Sigma(d,l) x d
Notes
-----
- 2011-03-24 - Written - Bovy (NYU)
"""
# Calculate R and phi
if _APY_LOADED and isinstance(l, units.Quantity):
lrad = conversion.parse_angle(l)
elif deg:
lrad = l * _DEGTORAD
else:
lrad = l
d = conversion.parse_length(d, ro=self._ro)
R, phi = _dlToRphi(d, lrad)
if target:
if relative:
return d
else:
return self.targetSurfacemass(R, use_physical=False) * d
else:
return (
self.surfacemass(
R,
romberg=romberg,
nsigma=nsigma,
relative=relative,
use_physical=False,
)
* d
)
@physical_conversion("position", pop=True)
def sampledSurfacemassLOS(self, l, n=1, maxd=None, target=True):
"""
Sample a distance along the line of sight
Parameters
----------
l : float or Quantity
Galactic longitude.
n : int, optional
Number of distances to sample.
maxd : float or Quantity, optional
Maximum distance to consider (for the rejection sampling).
target : bool, optional
If True, sample from the 'target' surface mass density, rather than the actual surface mass density (default=True).
Returns
-------
list
List of samples.
Notes
-----
- 2011-03-24 - Written - Bovy (NYU)
"""
# First calculate where the maximum is
if target:
minR = optimize.fmin_bfgs(
lambda x: -self.targetSurfacemassLOS(
x, l, use_physical=False, deg=False
),
0.0,
disp=False,
)[0]
maxSM = self.targetSurfacemassLOS(minR, l, deg=False, use_physical=False)
else:
minR = optimize.fmin_bfgs(
lambda x: -self.surfacemassLOS(x, l, deg=False, use_physical=False),
0.0,
disp=False,
)[0]
maxSM = self.surfacemassLOS(minR, l, deg=False, use_physical=False)
# Now rejection-sample
l = conversion.parse_angle(l)
maxd = conversion.parse_length(maxd, ro=self._ro)
if maxd is None:
maxd = _MAXD_REJECTLOS
out = []
while len(out) < n:
# sample
prop = numpy.random.random() * maxd
if target:
surfmassatprop = self.targetSurfacemassLOS(
prop, l, deg=False, use_physical=False
)
else:
surfmassatprop = self.surfacemassLOS(
prop, l, deg=False, use_physical=False
)
if surfmassatprop / maxSM > numpy.random.random(): # accept
out.append(prop)
return numpy.array(out)
@potential_physical_input
@physical_conversion("velocity", pop=True)
def sampleVRVT(self, R, n=1, nsigma=None, target=True):
"""
Sample a radial and azimuthal velocity at R
Parameters
----------
R : float or Quantity
Galactocentric distance.
n : int, optional
Number of distances to sample.
nsigma : float, optional
Number of sigma to rejection-sample on.
target : bool, optional
If True, sample using the 'target' sigma_R rather than the actual sigma_R (default=True).
Returns
-------
list
List of samples.
Notes
-----
- 2011-03-24 - Written - Bovy (NYU)
"""
# Determine where the max of the v-distribution is using asymmetric drift
maxVR = 0.0
maxVT = optimize.brentq(_vtmaxEq, 0.0, R**self._beta + 0.2, (R, self))
maxVD = self(Orbit([R, maxVR, maxVT]))
# Now rejection-sample
if nsigma == None:
nsigma = _NSIGMA
out = []
if target:
sigma = numpy.sqrt(self.targetSigma2(R, use_physical=False))
else:
sigma = numpy.sqrt(self.sigma2(R, use_physical=False))
while len(out) < n:
# sample
vrg, vtg = numpy.random.normal(), numpy.random.normal()
propvR = vrg * nsigma * sigma
propvT = vtg * nsigma * sigma / self._gamma + maxVT
VDatprop = self(Orbit([R, propvR, propvT]))
if VDatprop / maxVD > numpy.random.uniform() * numpy.exp(
-0.5 * (vrg**2.0 + vtg**2.0)
): # accept
out.append(numpy.array([propvR, propvT]))
return numpy.array(out)
def sampleLOS(
self,
los,
n=1,
deg=True,
maxd=None,
nsigma=None,
targetSurfmass=True,
targetSigma2=True,
):
"""
Sample along a given LOS
Parameters
----------
los : float or Quantity
Line of sight Galactic longitude.
n : int, optional
Number of distances to sample.
deg : bool, optional
If False, los is in radians.
maxd : float or Quantity, optional
Maximum distance to consider (for the rejection sampling).
nsigma : float, optional
Number of sigma to integrate the velocities over.
targetSurfmass : bool, optional
If True, use target surface mass (default=True).
targetSigma2 : bool, optional
If True, use target sigma_R^2 (default=True).
Returns
-------
list
List of Orbits sampled.
Notes
-----
- target=False uses target distribution for derivatives (this is a detail)
- 2011-03-24 - Written - Bovy (NYU)
"""
if _APY_LOADED and isinstance(los, units.Quantity):
l = conversion.parse_angle(los)
elif deg:
l = los * _DEGTORAD
else:
l = los
out = []
# sample distances
ds = self.sampledSurfacemassLOS(
l, n=n, maxd=maxd, target=targetSurfmass, use_physical=False
)
for ii in range(int(n)):
# Calculate R and phi
thisR, thisphi = _dlToRphi(ds[ii], l)
# sample velocities
vv = self.sampleVRVT(
thisR, n=1, nsigma=nsigma, target=targetSigma2, use_physical=False
)[0]
if self._roSet and self._voSet:
out.append(
Orbit([thisR, vv[0], vv[1], thisphi], ro=self._ro, vo=self._vo)
)
else:
out.append(Orbit([thisR, vv[0], vv[1], thisphi]))
return out
@potential_physical_input
@physical_conversion("velocity", pop=True)
def asymmetricdrift(self, R):
"""
Estimate the asymmetric drift (vc-mean-vphi) from an approximation to the Jeans equation.
Parameters
----------
R : float or Quantity
Radius at which to calculate the asymmetric drift.
Returns
-------
float
Asymmetric drift at R.
Notes
-----
- 2011-04-02 - Written - Bovy (NYU).
"""
sigmaR2 = self.targetSigma2(R, use_physical=False)
return (
sigmaR2
/ 2.0
/ R**self._beta
* (
1.0 / self._gamma**2.0
- 1.0
- R * self._surfaceSigmaProfile.surfacemassDerivative(R, log=True)
- R * self._surfaceSigmaProfile.sigma2Derivative(R, log=True)
)
)
@potential_physical_input
@physical_conversion("surfacedensity", pop=True)
def surfacemass(self, R, romberg=False, nsigma=None, relative=False):
"""
Calculate the surface-mass at R by marginalizing over velocity
Parameters
----------
R : float or Quantity
Radius at which to calculate the surfacemass density.
romberg : bool, optional
If True, use a romberg integrator (default: False)
nsigma : float, optional
Number of sigma to integrate the velocities over
relative : bool, optional
If True, return the relative surface mass at R (default: False)
Returns
-------
float
Surface mass at R
Notes
-----
- 2011-03-XX - Bovy (NYU)
"""
if nsigma == None:
nsigma = _NSIGMA
logSigmaR = self.targetSurfacemass(R, log=True, use_physical=False)
sigmaR2 = self.targetSigma2(R, use_physical=False)
sigmaR1 = numpy.sqrt(sigmaR2)
logsigmaR2 = numpylog(sigmaR2)
if relative:
norm = 1.0
else:
norm = numpy.exp(logSigmaR)
# Use the asymmetric drift equation to estimate va
va = (
sigmaR2
/ 2.0
/ R**self._beta
* (
1.0 / self._gamma**2.0
- 1.0
- R * self._surfaceSigmaProfile.surfacemassDerivative(R, log=True)
- R * self._surfaceSigmaProfile.sigma2Derivative(R, log=True)
)
)
if numpy.fabs(va) > sigmaR1:
va = 0.0 # To avoid craziness near the center
if romberg:
return numpy.real(
bovy_dblquad(
_surfaceIntegrand,
self._gamma * (R**self._beta - va) / sigmaR1 - nsigma,
self._gamma * (R**self._beta - va) / sigmaR1 + nsigma,
lambda x: 0.0,
lambda x: nsigma,
[R, self, logSigmaR, logsigmaR2, sigmaR1, self._gamma],
tol=10.0**-8,
)
/ numpy.pi
* norm
)
else:
return (
integrate.dblquad(
_surfaceIntegrand,
self._gamma * (R**self._beta - va) / sigmaR1 - nsigma,
self._gamma * (R**self._beta - va) / sigmaR1 + nsigma,
lambda x: 0.0,
lambda x: nsigma,
(R, self, logSigmaR, logsigmaR2, sigmaR1, self._gamma),
epsrel=_EPSREL,
)[0]
/ numpy.pi
* norm
)
@potential_physical_input
@physical_conversion("velocity2surfacedensity", pop=True)
def sigma2surfacemass(self, R, romberg=False, nsigma=None, relative=False):
"""
Calculate the product sigma_R^2 x surface-mass at R by marginalizing over velocity.
Parameters
----------
R : float or Quantity
Radius at which to calculate the sigma_R^2 x surfacemass density.
romberg : bool, optional
If True, use a romberg integrator (default: False).
nsigma : float, optional
Number of sigma to integrate the velocities over.
relative : bool, optional
If True, return the relative density (default: False).
Returns
-------
float
Sigma_R^2 x surface-mass at R.
Notes
-----
- 2010-03-XX - Written - Bovy (NYU).
"""
if nsigma == None:
nsigma = _NSIGMA
logSigmaR = self.targetSurfacemass(R, log=True, use_physical=False)
sigmaR2 = self.targetSigma2(R, use_physical=False)
sigmaR1 = numpy.sqrt(sigmaR2)
logsigmaR2 = numpylog(sigmaR2)
if relative:
norm = 1.0
else:
norm = numpy.exp(logSigmaR + logsigmaR2)
# Use the asymmetric drift equation to estimate va
va = (
sigmaR2
/ 2.0
/ R**self._beta
* (
1.0 / self._gamma**2.0
- 1.0
- R * self._surfaceSigmaProfile.surfacemassDerivative(R, log=True)
- R * self._surfaceSigmaProfile.sigma2Derivative(R, log=True)
)
)
if numpy.fabs(va) > sigmaR1:
va = 0.0 # To avoid craziness near the center
if romberg:
return numpy.real(
bovy_dblquad(
_sigma2surfaceIntegrand,
self._gamma * (R**self._beta - va) / sigmaR1 - nsigma,
self._gamma * (R**self._beta - va) / sigmaR1 + nsigma,
lambda x: 0.0,
lambda x: nsigma,
[R, self, logSigmaR, logsigmaR2, sigmaR1, self._gamma],
tol=10.0**-8,
)
/ numpy.pi
* norm
)
else:
return (
integrate.dblquad(
_sigma2surfaceIntegrand,
self._gamma * (R**self._beta - va) / sigmaR1 - nsigma,
self._gamma * (R**self._beta - va) / sigmaR1 + nsigma,
lambda x: 0.0,
lambda x: nsigma,
(R, self, logSigmaR, logsigmaR2, sigmaR1, self._gamma),
epsrel=_EPSREL,
)[0]
/ numpy.pi
* norm
)
def vmomentsurfacemass(self, *args, **kwargs):
"""
Calculate the an arbitrary moment of the velocity distribution at R times the surfacmass
Parameters
----------
R: float or Quantity
Galactocentric radius at which to calculate the moment.
n: int
vR^n in the moment
m: int
vT^m in the moment
nsigma : int, optional
number of sigma to integrate the velocities over
romberg : bool, optional
If True, use a romberg integrator (default: False)
deriv : str, optional
Calculates derivative of the moment wrt R or phi (default: None)
Returns
-------
float or Quantity
<vR^n vT^m x surface-mass> at R (no support for units)
Notes
-----
- 2011-03-30 - Written - Bovy (NYU)
"""
use_physical = kwargs.pop("use_physical", True)
ro = kwargs.pop("ro", None)
if ro is None and hasattr(self, "_roSet") and self._roSet:
ro = self._ro
ro = conversion.parse_length_kpc(ro)
vo = kwargs.pop("vo", None)
if vo is None and hasattr(self, "_voSet") and self._voSet:
vo = self._vo
vo = conversion.parse_velocity_kms(vo)
if use_physical and not vo is None and not ro is None:
fac = surfdens_in_msolpc2(vo, ro) * vo ** (args[1] + args[2])
if _APY_UNITS:
u = (
units.Msun
/ units.pc**2
* (units.km / units.s) ** (args[1] + args[2])
)
out = self._vmomentsurfacemass(*args, **kwargs)
if _APY_UNITS:
return units.Quantity(out * fac, unit=u)
else:
return out * fac
else:
return self._vmomentsurfacemass(*args, **kwargs)
def _vmomentsurfacemass(
self, R, n, m, romberg=False, nsigma=None, relative=False, phi=0.0, deriv=None
):
"""Non-physical version of vmomentsurfacemass, otherwise the same"""
# odd moments of vR are zero
if isinstance(n, int) and n % 2 == 1:
return 0.0
if nsigma == None:
nsigma = _NSIGMA
logSigmaR = self.targetSurfacemass(R, log=True, use_physical=False)
sigmaR2 = self.targetSigma2(R, use_physical=False)
sigmaR1 = numpy.sqrt(sigmaR2)
logsigmaR2 = numpylog(sigmaR2)
if relative:
norm = 1.0
else:
norm = numpy.exp(logSigmaR + logsigmaR2 * (n + m) / 2.0) / self._gamma**m
# Use the asymmetric drift equation to estimate va
va = (
sigmaR2
/ 2.0
/ R**self._beta
* (
1.0 / self._gamma**2.0
- 1.0
- R * self._surfaceSigmaProfile.surfacemassDerivative(R, log=True)
- R * self._surfaceSigmaProfile.sigma2Derivative(R, log=True)
)
)
if numpy.fabs(va) > sigmaR1:
va = 0.0 # To avoid craziness near the center
if deriv is None:
if romberg: