-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathprofiles.py
2034 lines (1751 loc) · 77.8 KB
/
profiles.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
import warnings
import pyccl
from ..background import h_over_h0, sigma_critical
from ..power import sigmaM
from ..pyutils import resample_array, _fftlog_transform
from ..base import CCLHalosObject, UnlockInstance, unlock_instance
from .concentration import Concentration
from .massdef import MassDef
import numpy as np
from scipy.special import sici, erf, gamma, gammainc
class HaloProfile(CCLHalosObject):
""" This class implements functionality associated to
halo profiles. You should not use this class directly.
Instead, use one of the subclasses implemented in CCL
for specific halo profiles, or write your own subclass.
`HaloProfile` classes contain methods to compute halo
profiles in real (3D) and Fourier spaces, as well as the
projected (2D) profile and the cumulative mean surface
density.
A minimal implementation of a `HaloProfile` subclass
should contain a method `_real` that returns the
real-space profile as a function of cosmology,
comoving radius, mass and scale factor. The default
functionality in the base `HaloProfile` class will then
allow the automatic calculation of the Fourier-space
and projected profiles, as well as the cumulative
mass density, based on the real-space profile using
FFTLog to carry out fast Hankel transforms. See the
CCL note for details. Alternatively, you can implement
a `_fourier` method for the Fourier-space profile, and
all other quantities will be computed from it. It is
also possible to implement specific versions of any
of these quantities if one wants to avoid the FFTLog
calculation.
"""
is_number_counts = False
def __init__(self):
# Check that at least one of (`_real`, `_fourier`) exist.
if not (hasattr(self, "_real") or hasattr(self, "_fourier")):
raise TypeError(
f"Can't instantiate class {self.__class__.__name__} "
"with no methods _real or _fourier")
self.precision_fftlog = {'padding_lo_fftlog': 0.1,
'padding_lo_extra': 0.1,
'padding_hi_fftlog': 10.,
'padding_hi_extra': 10.,
'large_padding_2D': False,
'n_per_decade': 100,
'extrapol': 'linx_liny',
'plaw_fourier': -1.5,
'plaw_projected': -1.}
__eq__ = object.__eq__
__hash__ = object.__hash__ # TODO: remove once __eq__ is replaced.
@unlock_instance(mutate=True)
def update_precision_fftlog(self, **kwargs):
""" Update any of the precision parameters used by
FFTLog to compute Hankel transforms. The available
parameters are:
Args:
padding_lo_fftlog (float): when computing a Hankel
transform we often need to extend the range of the
input (e.g. the r-range for the real-space profile
when computing the Fourier-space one) to avoid
aliasing and boundary effects. This parameter
controls the factor by which we multiply the lower
end of the range (e.g. a value of 0.1 implies that
we will extend the range by one decade on the
left). Note that FFTLog works in logarithmic
space. Default value: 0.1.
padding_hi_fftlog (float): same as `padding_lo_fftlog`
for the upper end of the range (e.g. a value of
10 implies extending the range by one decade on
the right). Default value: 10.
n_per_decade (float): number of samples of the
profile taken per decade when computing Hankel
transforms.
padding_lo_extra (float): when computing the projected
2D profile or the 2D cumulative density,
sometimes two Hankel transforms are needed (from
3D real-space to Fourier, then from Fourier to
2D real-space). This parameter controls the k range
of the intermediate transform. The logic here is to
avoid the range twice by `padding_lo_fftlog` (which
can be overkill and slow down the calculation).
Default value: 0.1.
padding_hi_extra (float): same as `padding_lo_extra`
for the upper end of the range. Default value: 10.
large_padding_2D (bool): if set to `True`, the
intermediate Hankel transform in the calculation of
the 2D projected profile and cumulative mass
density will use `padding_lo_fftlog` and
`padding_hi_fftlog` instead of `padding_lo_extra`
and `padding_hi_extra` to extend the range of the
intermediate Hankel transform.
extrapol (string): type of extrapolation used in the
uncommon scenario that FFTLog returns a profile on a
range that does not cover the intended output range.
Pass `linx_liny` if you want to extrapolate linearly
in the profile and `linx_logy` if you want to
extrapolate linearly in its logarithm.
Default value: `linx_liny`.
plaw_fourier (float): FFTLog is able to perform more
accurate Hankel transforms by prewhitening its arguments
(essentially making them flatter over the range of
integration to avoid aliasing). This parameter
corresponds to a guess of what the tilt of the profile
is (i.e. profile(r) = r^tilt), which FFTLog uses to
prewhiten it. This parameter is used when computing the
real <-> Fourier transforms. The methods
`_get_plaw_fourier` allows finer control over this
parameter. The default value allows for a slightly faster
(but potentially less accurate) FFTLog transform. Some
level of experimentation with this parameter is
recommended when implementing a new profile.
Default value: -1.5.
plaw_projected (float): same as `plaw_fourier` for the
calculation of the 2D projected and cumulative density
profiles. Finer control can be achieved with the
`_get_plaw_projected`. The default value allows for a
slightly faster (but potentially less accurate) FFTLog
transform. Some level of experimentation with this
parameter is recommended when implementing a new profile.
Default value: -1.
"""
self.precision_fftlog.update(kwargs)
def _get_plaw_fourier(self, cosmo, a):
""" This controls the value of `plaw_fourier` to be used
as a function of cosmology and scale factor.
Args:
cosmo (:class:`~pyccl.core.Cosmology`): a Cosmology object.
a (float): scale factor.
Returns:
float: power law index to be used with FFTLog.
"""
return self.precision_fftlog['plaw_fourier']
def _get_plaw_projected(self, cosmo, a):
""" This controls the value of `plaw_projected` to be
used as a function of cosmology and scale factor.
Args:
cosmo (:class:`~pyccl.core.Cosmology`): a Cosmology object.
a (float): scale factor.
Returns:
float: power law index to be used with FFTLog.
"""
return self.precision_fftlog['plaw_projected']
def _get_prefactor(self, cosmo, a, hmc):
"""
Add a pre-factor for the total power spectra that depends
only on the scale factor.
Args:
cosmo (:class:`~pyccl.core.Cosmology`): a Cosmology object.
a (float): scale factor.
hmc (:class:`~pyccl.halos.HMCalculator`): halo
model calculator object.
Returns:
float or array_like: pre-factor value.
"""
return 1.
def real(self, cosmo, r, M, a, mass_def=None):
""" Returns the 3D real-space value of the profile as a
function of cosmology, radius, halo mass and scale factor.
Args:
cosmo (:class:`~pyccl.core.Cosmology`): a Cosmology object.
r (float or array_like): comoving radius in Mpc.
M (float or array_like): halo mass in units of M_sun.
a (float): scale factor.
mass_def (:class:`~pyccl.halos.massdef.MassDef`):
a mass definition object.
Returns:
float or array_like: halo profile. The shape of the
output will be `(N_M, N_r)` where `N_r` and `N_m` are
the sizes of `r` and `M` respectively. If `r` or `M`
are scalars, the corresponding dimension will be
squeezed out on output.
"""
if getattr(self, '_real', None):
f_r = self._real(cosmo, r, M, a, mass_def)
elif getattr(self, '_fourier', None):
f_r = self._fftlog_wrap(cosmo, r, M, a, mass_def,
fourier_out=False)
return f_r
def fourier(self, cosmo, k, M, a, mass_def):
""" Returns the Fourier-space value of the profile as a
function of cosmology, wavenumber, halo mass and
scale factor.
.. math::
\\rho(k)=\\frac{1}{2\\pi^2} \\int dr\\, r^2\\,
\\rho(r)\\, j_0(k r)
Args:
cosmo (:class:`~pyccl.core.Cosmology`): a Cosmology object.
k (float or array_like): comoving wavenumber in Mpc^-1.
M (float or array_like): halo mass in units of M_sun.
a (float): scale factor.
mass_def (:class:`~pyccl.halos.massdef.MassDef`):
a mass definition object.
Returns:
float or array_like: halo profile. The shape of the
output will be `(N_M, N_k)` where `N_k` and `N_m` are
the sizes of `k` and `M` respectively. If `k` or `M`
are scalars, the corresponding dimension will be
squeezed out on output.
"""
if getattr(self, '_fourier', None):
f_k = self._fourier(cosmo, k, M, a, mass_def)
elif getattr(self, '_real', None):
f_k = self._fftlog_wrap(cosmo, k, M, a, mass_def, fourier_out=True)
return f_k
def projected(self, cosmo, r_t, M, a, mass_def):
""" Returns the 2D projected profile as a function of
cosmology, radius, halo mass and scale factor.
.. math::
\\Sigma(R)= \\int dr_\\parallel\\,
\\rho(\\sqrt{r_\\parallel^2 + R^2})
Args:
cosmo (:class:`~pyccl.core.Cosmology`): a Cosmology object.
r (float or array_like): comoving radius in Mpc.
M (float or array_like): halo mass in units of M_sun.
a (float): scale factor.
mass_def (:class:`~pyccl.halos.massdef.MassDef`):
a mass definition object.
Returns:
float or array_like: halo profile. The shape of the
output will be `(N_M, N_r)` where `N_r` and `N_m` are
the sizes of `r` and `M` respectively. If `r` or `M`
are scalars, the corresponding dimension will be
squeezed out on output.
"""
if getattr(self, '_projected', None):
s_r_t = self._projected(cosmo, r_t, M, a, mass_def)
else:
s_r_t = self._projected_fftlog_wrap(cosmo, r_t, M,
a, mass_def,
is_cumul2d=False)
return s_r_t
def cumul2d(self, cosmo, r_t, M, a, mass_def):
""" Returns the 2D cumulative surface density as a
function of cosmology, radius, halo mass and scale
factor.
.. math::
\\Sigma(<R)= \\frac{2}{R^2} \\int dR'\\, R'\\,
\\Sigma(R')
Args:
cosmo (:class:`~pyccl.core.Cosmology`): a Cosmology object.
r (float or array_like): comoving radius in Mpc.
M (float or array_like): halo mass in units of M_sun.
a (float): scale factor.
mass_def (:class:`~pyccl.halos.massdef.MassDef`):
a mass definition object.
Returns:
float or array_like: halo profile. The shape of the
output will be `(N_M, N_r)` where `N_r` and `N_m` are
the sizes of `r` and `M` respectively. If `r` or `M`
are scalars, the corresponding dimension will be
squeezed out on output.
"""
if getattr(self, '_cumul2d', None):
s_r_t = self._cumul2d(cosmo, r_t, M, a, mass_def)
else:
s_r_t = self._projected_fftlog_wrap(cosmo, r_t, M,
a, mass_def,
is_cumul2d=True)
return s_r_t
def convergence(self, cosmo, r, M, a_lens, a_source, mass_def):
""" Returns the convergence as a function of cosmology,
radius, halo mass and the scale factors of the source
and the lens.
.. math::
\\kappa(R) = \\frac{\\Sigma(R)}{\\Sigma_{\\mathrm{crit}}},\\
where :math:`\\Sigma(R)` is the 2D projected surface mass density.
Args:
cosmo (:class:`~pyccl.core.Cosmology`): A Cosmology object.
r (float or array_like): comoving radius in Mpc.
M (float or array_like): halo mass in units of M_sun.
a_lens (float): scale factor of lens.
a_source (float or array_like): scale factor of source.
If array_like, it must have the same shape as `r`.
mass_def (:class:`~pyccl.halos.massdef.MassDef`):
a mass definition object.
Returns:
float or array_like: convergence \
:math:`\\kappa`
"""
Sigma = self.projected(cosmo, r, M, a_lens, mass_def) / a_lens**2
Sigma_crit = sigma_critical(cosmo, a_lens, a_source)
return Sigma / Sigma_crit
def shear(self, cosmo, r, M, a_lens, a_source, mass_def):
""" Returns the shear (tangential) as a function of cosmology,
radius, halo mass and the scale factors of the
source and the lens.
.. math::
\\gamma(R) = \\frac{\\Delta\\Sigma(R)}{\\Sigma_{\\mathrm{crit}}} =
\\frac{\\overline{\\Sigma}(< R) -
\\Sigma(R)}{\\Sigma_{\\mathrm{crit}}},\\
where :math:`\\overline{\\Sigma}(< R)` is the average surface density
within R.
Args:
cosmo (:class:`~pyccl.core.Cosmology`): A Cosmology object.
r (float or array_like): comoving radius in Mpc.
M (float or array_like): halo mass in units of M_sun.
a_lens (float): scale factor of lens.
a_source (float or array_like): source's scale factor.
If array_like, it must have the same shape as `r`.
mass_def (:class:`~pyccl.halos.massdef.MassDef`):
a mass definition object.
Returns:
float or array_like: shear \
:math:`\\gamma`
"""
Sigma = self.projected(cosmo, r, M, a_lens, mass_def)
Sigma_bar = self.cumul2d(cosmo, r, M, a_lens, mass_def)
Sigma_crit = sigma_critical(cosmo, a_lens, a_source)
return (Sigma_bar - Sigma) / (Sigma_crit * a_lens**2)
def reduced_shear(self, cosmo, r, M, a_lens, a_source, mass_def):
""" Returns the reduced shear as a function of cosmology,
radius, halo mass and the scale factors of the
source and the lens.
.. math::
g_t (R) = \\frac{\\gamma(R)}{(1 - \\kappa(R))},\\
where :math: `\\gamma(R)` is the shear and `\\kappa(R)` is the
convergence.
Args:
cosmo (:class:`~pyccl.core.Cosmology`): A Cosmology object.
r (float or array_like): comoving radius in Mpc.
M (float or array_like): halo mass in units of M_sun.
a_lens (float): scale factor of lens.
a_source (float or array_like): source's scale factor.
If array_like, it must have the same shape as `r`.
mass_def (:class:`~pyccl.halos.massdef.MassDef`):
a mass definition object.
Returns:
float or array_like: reduced shear \
:math:`g_t`
"""
convergence = self.convergence(cosmo, r, M, a_lens, a_source, mass_def)
shear = self.shear(cosmo, r, M, a_lens, a_source, mass_def)
return shear / (1.0 - convergence)
def magnification(self, cosmo, r, M, a_lens, a_source, mass_def):
""" Returns the magnification for input parameters.
.. math::
\\mu (R) = \\frac{1}{\\left[(1 - \\kappa(R))^2 -
\\vert \\gamma(R) \\vert^2 \\right]]},\\
where :math: `\\gamma(R)` is the shear and `\\kappa(R)` is the
convergence.
Args:
cosmo (:class:`~pyccl.core.Cosmology`): A Cosmology object.
r (float or array_like): comoving radius in Mpc.
M (float or array_like): halo mass in units of M_sun.
a_lens (float): scale factor of lens.
a_source (float or array_like): source's scale factor.
If array_like, it must have the same shape as `r`.
mass_def (:class:`~pyccl.halos.massdef.MassDef`):
a mass definition object.
Returns:
float or array_like: magnification\
:math:`\\mu`
"""
convergence = self.convergence(cosmo, r, M, a_lens, a_source, mass_def)
shear = self.shear(cosmo, r, M, a_lens, a_source, mass_def)
return 1.0 / ((1.0 - convergence)**2 - np.abs(shear)**2)
def _fftlog_wrap(self, cosmo, k, M, a, mass_def,
l=0,
fourier_out=False,
large_padding=True):
# This computes the 3D Hankel transform
# \rho(k) = 4\pi \int dr r^2 \rho(r) j_l(k r)
# if fourier_out == True, and
# \rho(r) = \frac{1}{2\pi^2} \int dk k^2 \rho(k) j_l(k r)
# otherwise.
# Select which profile should be the input
if fourier_out:
p_func = self._real
else:
p_func = self._fourier
k_use = np.atleast_1d(k)
M_use = np.atleast_1d(M)
lk_use = np.log(k_use)
nM = len(M_use)
# k/r ranges to be used with FFTLog and its sampling.
if large_padding:
k_min = self.precision_fftlog['padding_lo_fftlog'] * np.amin(k_use)
k_max = self.precision_fftlog['padding_hi_fftlog'] * np.amax(k_use)
else:
k_min = self.precision_fftlog['padding_lo_extra'] * np.amin(k_use)
k_max = self.precision_fftlog['padding_hi_extra'] * np.amax(k_use)
n_k = (int(np.log10(k_max / k_min)) *
self.precision_fftlog['n_per_decade'])
r_arr = np.geomspace(k_min, k_max, n_k)
p_k_out = np.zeros([nM, k_use.size])
# Compute real profile values
p_real_M = p_func(cosmo, r_arr, M_use, a, mass_def)
# Power-law index to pass to FFTLog.
plaw_index = self._get_plaw_fourier(cosmo, a)
# Compute Fourier profile through fftlog
k_arr, p_fourier_M = _fftlog_transform(r_arr, p_real_M,
3, l, plaw_index)
lk_arr = np.log(k_arr)
for im, p_k_arr in enumerate(p_fourier_M):
# Resample into input k values
p_fourier = resample_array(lk_arr, p_k_arr, lk_use,
self.precision_fftlog['extrapol'],
self.precision_fftlog['extrapol'],
0, 0)
p_k_out[im, :] = p_fourier
if fourier_out:
p_k_out *= (2 * np.pi)**3
if np.ndim(k) == 0:
p_k_out = np.squeeze(p_k_out, axis=-1)
if np.ndim(M) == 0:
p_k_out = np.squeeze(p_k_out, axis=0)
return p_k_out
def _projected_fftlog_wrap(self, cosmo, r_t, M, a, mass_def,
is_cumul2d=False):
# This computes Sigma(R) from the Fourier-space profile as:
# Sigma(R) = \frac{1}{2\pi} \int dk k J_0(k R) \rho(k)
r_t_use = np.atleast_1d(r_t)
M_use = np.atleast_1d(M)
lr_t_use = np.log(r_t_use)
nM = len(M_use)
# k/r range to be used with FFTLog and its sampling.
r_t_min = self.precision_fftlog['padding_lo_fftlog'] * np.amin(r_t_use)
r_t_max = self.precision_fftlog['padding_hi_fftlog'] * np.amax(r_t_use)
n_r_t = (int(np.log10(r_t_max / r_t_min)) *
self.precision_fftlog['n_per_decade'])
k_arr = np.geomspace(r_t_min, r_t_max, n_r_t)
sig_r_t_out = np.zeros([nM, r_t_use.size])
# Compute Fourier-space profile
if getattr(self, '_fourier', None):
# Compute from `_fourier` if available.
p_fourier = self._fourier(cosmo, k_arr, M_use,
a, mass_def)
else:
# Compute with FFTLog otherwise.
lpad = self.precision_fftlog['large_padding_2D']
p_fourier = self._fftlog_wrap(cosmo,
k_arr,
M_use, a,
mass_def,
fourier_out=True,
large_padding=lpad)
if is_cumul2d:
# The cumulative profile involves a factor 1/(k R) in
# the integrand.
p_fourier *= 2 / k_arr[None, :]
# Power-law index to pass to FFTLog.
if is_cumul2d:
i_bessel = 1
plaw_index = self._get_plaw_projected(cosmo, a) - 1
else:
i_bessel = 0
plaw_index = self._get_plaw_projected(cosmo, a)
# Compute projected profile through fftlog
r_t_arr, sig_r_t_M = _fftlog_transform(k_arr, p_fourier,
2, i_bessel,
plaw_index)
lr_t_arr = np.log(r_t_arr)
if is_cumul2d:
sig_r_t_M /= r_t_arr[None, :]
for im, sig_r_t_arr in enumerate(sig_r_t_M):
# Resample into input r_t values
sig_r_t = resample_array(lr_t_arr, sig_r_t_arr,
lr_t_use,
self.precision_fftlog['extrapol'],
self.precision_fftlog['extrapol'],
0, 0)
sig_r_t_out[im, :] = sig_r_t
if np.ndim(r_t) == 0:
sig_r_t_out = np.squeeze(sig_r_t_out, axis=-1)
if np.ndim(M) == 0:
sig_r_t_out = np.squeeze(sig_r_t_out, axis=0)
return sig_r_t_out
class HaloProfileGaussian(HaloProfile):
""" Gaussian profile
.. math::
\\rho(r) = \\rho_0\\, e^{-(r/r_s)^2}
Args:
r_scale (:obj:`function`): the width of the profile.
The signature of this function should be
`f(cosmo, M, a, mdef)`, where `cosmo` is a
:class:`~pyccl.core.Cosmology` object, `M` is a halo mass in
units of M_sun, `a` is the scale factor and `mdef`
is a :class:`~pyccl.halos.massdef.MassDef` object.
rho0 (:obj:`function`): the amplitude of the profile.
It should have the same signature as `r_scale`.
"""
__repr_attrs__ = ("r_s", "rho_0", "precision_fftlog",)
name = 'Gaussian'
def __init__(self, r_scale, rho0):
self.rho_0 = rho0
self.r_s = r_scale
super(HaloProfileGaussian, self).__init__()
self.update_precision_fftlog(padding_lo_fftlog=0.01,
padding_hi_fftlog=100.,
n_per_decade=10000)
def _real(self, cosmo, r, M, a, mass_def):
r_use = np.atleast_1d(r)
M_use = np.atleast_1d(M)
# Compute scale
rs = self.r_s(cosmo, M_use, a, mass_def)
# Compute normalization
rho0 = self.rho_0(cosmo, M_use, a, mass_def)
# Form factor
prof = np.exp(-(r_use[None, :] / rs[:, None])**2)
prof = prof * rho0[:, None]
if np.ndim(r) == 0:
prof = np.squeeze(prof, axis=-1)
if np.ndim(M) == 0:
prof = np.squeeze(prof, axis=0)
return prof
class HaloProfilePowerLaw(HaloProfile):
""" Power-law profile
.. math::
\\rho(r) = (r/r_s)^\\alpha
Args:
r_scale (:obj:`function`): the correlation length of
the profile. The signature of this function
should be `f(cosmo, M, a, mdef)`, where `cosmo`
is a :class:`~pyccl.core.Cosmology` object, `M` is a halo mass
in units of M_sun, `a` is the scale factor and
`mdef` is a :class:`~pyccl.halos.massdef.MassDef` object.
tilt (:obj:`function`): the power law index of the
profile. The signature of this function should
be `f(cosmo, a)`.
"""
__repr_attrs__ = ("r_s", "tilt", "precision_fftlog",)
name = 'PowerLaw'
def __init__(self, r_scale, tilt):
self.r_s = r_scale
self.tilt = tilt
super(HaloProfilePowerLaw, self).__init__()
def _get_plaw_fourier(self, cosmo, a):
# This is the optimal value for a pure power law
# profile.
return self.tilt(cosmo, a)
def _get_plaw_projected(self, cosmo, a):
# This is the optimal value for a pure power law
# profile.
return -3 - self.tilt(cosmo, a)
def _real(self, cosmo, r, M, a, mass_def):
r_use = np.atleast_1d(r)
M_use = np.atleast_1d(M)
# Compute scale
rs = self.r_s(cosmo, M_use, a, mass_def)
tilt = self.tilt(cosmo, a)
# Form factor
prof = (r_use[None, :] / rs[:, None])**tilt
if np.ndim(r) == 0:
prof = np.squeeze(prof, axis=-1)
if np.ndim(M) == 0:
prof = np.squeeze(prof, axis=0)
return prof
class HaloProfileNFW(HaloProfile):
""" Navarro-Frenk-White (astro-ph:astro-ph/9508025) profile.
.. math::
\\rho(r) = \\frac{\\rho_0}
{\\frac{r}{r_s}\\left(1+\\frac{r}{r_s}\\right)^2}
where :math:`r_s` is related to the spherical overdensity
halo radius :math:`R_\\Delta(M)` through the concentration
parameter :math:`c(M)` as
.. math::
R_\\Delta(M) = c(M)\\,r_s
and the normalization :math:`\\rho_0` is
.. math::
\\rho_0 = \\frac{M}{4\\pi\\,r_s^3\\,[\\log(1+c) - c/(1+c)]}
By default, this profile is truncated at :math:`r = R_\\Delta(M)`.
Args:
c_M_relation (:obj:`Concentration`): concentration-mass
relation to use with this profile.
fourier_analytic (bool): set to `True` if you want to compute
the Fourier profile analytically (and not through FFTLog).
Default: `True`.
projected_analytic (bool): set to `True` if you want to
compute the 2D projected profile analytically (and not
through FFTLog). Default: `False`.
cumul2d_analytic (bool): set to `True` if you want to
compute the 2D cumulative surface density analytically
(and not through FFTLog). Default: `False`.
truncated (bool): set to `True` if the profile should be
truncated at :math:`r = R_\\Delta` (i.e. zero at larger
radii.
"""
__repr_attrs__ = ("cM", "fourier_analytic", "projected_analytic",
"cumul2d_analytic", "truncated", "precision_fftlog",)
name = 'NFW'
def __init__(self, c_M_relation,
fourier_analytic=True,
projected_analytic=False,
cumul2d_analytic=False,
truncated=True):
if not isinstance(c_M_relation, Concentration):
raise TypeError("c_M_relation must be of type `Concentration`")
self.cM = c_M_relation
self.truncated = truncated
self.fourier_analytic = fourier_analytic
self.projected_analytic = projected_analytic
self.cumul2d_analytic = cumul2d_analytic
if fourier_analytic:
self._fourier = self._fourier_analytic
if projected_analytic:
if truncated:
raise ValueError("Analytic projected profile not supported "
"for truncated NFW. Set `truncated` or "
"`projected_analytic` to `False`.")
self._projected = self._projected_analytic
if cumul2d_analytic:
if truncated:
raise ValueError("Analytic cumuative 2d profile not supported "
"for truncated NFW. Set `truncated` or "
"`cumul2d_analytic` to `False`.")
self._cumul2d = self._cumul2d_analytic
super(HaloProfileNFW, self).__init__()
self.update_precision_fftlog(padding_hi_fftlog=1E2,
padding_lo_fftlog=1E-2,
n_per_decade=1000,
plaw_fourier=-2.)
def _get_cM(self, cosmo, M, a, mdef=None):
return self.cM.get_concentration(cosmo, M, a, mdef_other=mdef)
def _norm(self, M, Rs, c):
# NFW normalization from mass, radius and concentration
return M / (4 * np.pi * Rs**3 * (np.log(1+c) - c/(1+c)))
def _real(self, cosmo, r, M, a, mass_def):
r_use = np.atleast_1d(r)
M_use = np.atleast_1d(M)
# Comoving virial radius
R_M = mass_def.get_radius(cosmo, M_use, a) / a
c_M = self._get_cM(cosmo, M_use, a, mdef=mass_def)
R_s = R_M / c_M
x = r_use[None, :] / R_s[:, None]
prof = 1./(x * (1 + x)**2)
if self.truncated:
prof[r_use[None, :] > R_M[:, None]] = 0
norm = self._norm(M_use, R_s, c_M)
prof = prof[:, :] * norm[:, None]
if np.ndim(r) == 0:
prof = np.squeeze(prof, axis=-1)
if np.ndim(M) == 0:
prof = np.squeeze(prof, axis=0)
return prof
def _fx_projected(self, x):
def f1(xx):
x2m1 = xx * xx - 1
return 1 / x2m1 + np.arccosh(1 / xx) / np.fabs(x2m1)**1.5
def f2(xx):
x2m1 = xx * xx - 1
return 1 / x2m1 - np.arccos(1 / xx) / np.fabs(x2m1)**1.5
xf = x.flatten()
return np.piecewise(xf,
[xf < 1, xf > 1],
[f1, f2, 1./3.]).reshape(x.shape)
def _projected_analytic(self, cosmo, r, M, a, mass_def):
r_use = np.atleast_1d(r)
M_use = np.atleast_1d(M)
# Comoving virial radius
R_M = mass_def.get_radius(cosmo, M_use, a) / a
c_M = self._get_cM(cosmo, M_use, a, mdef=mass_def)
R_s = R_M / c_M
x = r_use[None, :] / R_s[:, None]
prof = self._fx_projected(x)
norm = 2 * R_s * self._norm(M_use, R_s, c_M)
prof = prof[:, :] * norm[:, None]
if np.ndim(r) == 0:
prof = np.squeeze(prof, axis=-1)
if np.ndim(M) == 0:
prof = np.squeeze(prof, axis=0)
return prof
def _fx_cumul2d(self, x):
def f1(xx):
sqx2m1 = np.sqrt(np.fabs(xx * xx - 1))
return np.log(0.5 * xx) + np.arccosh(1 / xx) / sqx2m1
def f2(xx):
sqx2m1 = np.sqrt(np.fabs(xx * xx - 1))
return np.log(0.5 * xx) + np.arccos(1 / xx) / sqx2m1
xf = x.flatten()
omln2 = 0.3068528194400547 # 1-Log[2]
f = np.piecewise(xf,
[xf < 1, xf > 1],
[f1, f2, omln2]).reshape(x.shape)
return 2 * f / x**2
def _cumul2d_analytic(self, cosmo, r, M, a, mass_def):
r_use = np.atleast_1d(r)
M_use = np.atleast_1d(M)
# Comoving virial radius
R_M = mass_def.get_radius(cosmo, M_use, a) / a
c_M = self._get_cM(cosmo, M_use, a, mdef=mass_def)
R_s = R_M / c_M
x = r_use[None, :] / R_s[:, None]
prof = self._fx_cumul2d(x)
norm = 2 * R_s * self._norm(M_use, R_s, c_M)
prof = prof[:, :] * norm[:, None]
if np.ndim(r) == 0:
prof = np.squeeze(prof, axis=-1)
if np.ndim(M) == 0:
prof = np.squeeze(prof, axis=0)
return prof
def _fourier_analytic(self, cosmo, k, M, a, mass_def):
M_use = np.atleast_1d(M)
k_use = np.atleast_1d(k)
# Comoving virial radius
R_M = mass_def.get_radius(cosmo, M_use, a) / a
c_M = self._get_cM(cosmo, M_use, a, mdef=mass_def)
R_s = R_M / c_M
x = k_use[None, :] * R_s[:, None]
Si2, Ci2 = sici(x)
P1 = M_use / (np.log(1 + c_M) - c_M / (1 + c_M))
if self.truncated:
Si1, Ci1 = sici((1 + c_M[:, None]) * x)
P2 = np.sin(x) * (Si1 - Si2) + np.cos(x) * (Ci1 - Ci2)
P3 = np.sin(c_M[:, None] * x) / ((1 + c_M[:, None]) * x)
prof = P1[:, None] * (P2 - P3)
else:
P2 = np.sin(x) * (0.5 * np.pi - Si2) - np.cos(x) * Ci2
prof = P1[:, None] * P2
if np.ndim(k) == 0:
prof = np.squeeze(prof, axis=-1)
if np.ndim(M) == 0:
prof = np.squeeze(prof, axis=0)
return prof
class HaloProfileEinasto(HaloProfile):
""" Einasto profile (1965TrAlm...5...87E).
.. math::
\\rho(r) = \\rho_0\\,\\exp(-2 ((r/r_s)^\\alpha-1) / \\alpha)
where :math:`r_s` is related to the spherical overdensity
halo radius :math:`R_\\Delta(M)` through the concentration
parameter :math:`c(M)` as
.. math::
R_\\Delta(M) = c(M)\\,r_s
and the normalization :math:`\\rho_0` is the mean density
within the :math:`R_\\Delta(M)` of the halo. The index
:math:`\\alpha` depends on halo mass and redshift, and we
use the parameterization of Diemer & Kravtsov
(arXiv:1401.1216).
By default, this profile is truncated at :math:`r = R_\\Delta(M)`.
Args:
c_M_relation (:obj:`Concentration`): concentration-mass
relation to use with this profile.
truncated (bool): set to `True` if the profile should be
truncated at :math:`r = R_\\Delta` (i.e. zero at larger
radii.
alpha (float, 'cosmo'): Set the Einasto alpha parameter or set to
'cosmo' to calculate the value from cosmology. Default: 'cosmo'
"""
__repr_attrs__ = ("cM", "truncated", "alpha", "precision_fftlog",)
name = 'Einasto'
def __init__(self, c_M_relation, truncated=True, alpha='cosmo'):
if not isinstance(c_M_relation, Concentration):
raise TypeError("c_M_relation must be of type `Concentration`")
self.cM = c_M_relation
self.truncated = truncated
self.alpha = alpha
super(HaloProfileEinasto, self).__init__()
self.update_precision_fftlog(padding_hi_fftlog=1E2,
padding_lo_fftlog=1E-2,
n_per_decade=1000,
plaw_fourier=-2.)
def update_parameters(self, alpha=None):
"""Update any of the parameters associated with this profile.
Any parameter set to ``None`` won't be updated.
Arguments
---------
alpha : float, 'cosmo'
Profile shape parameter. Set to
'cosmo' to calculate the value from cosmology
"""
if alpha is not None and alpha != self.alpha:
self.alpha = alpha
def _get_cM(self, cosmo, M, a, mdef=None):
return self.cM.get_concentration(cosmo, M, a, mdef_other=mdef)
def _get_alpha(self, cosmo, M, a, mdef):
if self.alpha == 'cosmo':
mdef_vir = MassDef('vir', 'matter')
Mvir = mdef.translate_mass(cosmo, M, a, mdef_vir)
sM = sigmaM(cosmo, Mvir, a)
nu = 1.686 / sM
alpha = 0.155 + 0.0095 * nu * nu
else:
alpha = np.full_like(M, self.alpha)
return alpha
def _norm(self, M, Rs, c, alpha):
# Einasto normalization from mass, radius, concentration and alpha
return M / (np.pi * Rs**3 * 2**(2-3/alpha) * alpha**(-1+3/alpha)
* np.exp(2/alpha)
* gamma(3/alpha) * gammainc(3/alpha, 2/alpha*c**alpha))
def _real(self, cosmo, r, M, a, mass_def):
r_use = np.atleast_1d(r)
M_use = np.atleast_1d(M)
# Comoving virial radius
R_M = mass_def.get_radius(cosmo, M_use, a) / a
c_M = self._get_cM(cosmo, M_use, a, mdef=mass_def)
R_s = R_M / c_M
alpha = self._get_alpha(cosmo, M_use, a, mass_def)
norm = self._norm(M_use, R_s, c_M, alpha)
x = r_use[None, :] / R_s[:, None]
prof = norm[:, None] * np.exp(-2. * (x**alpha[:, None] - 1) /
alpha[:, None])
if self.truncated:
prof[r_use[None, :] > R_M[:, None]] = 0
if np.ndim(r) == 0:
prof = np.squeeze(prof, axis=-1)
if np.ndim(M) == 0:
prof = np.squeeze(prof, axis=0)
return prof
class HaloProfileHernquist(HaloProfile):
""" Hernquist (1990ApJ...356..359H).
.. math::
\\rho(r) = \\frac{\\rho_0}
{\\frac{r}{r_s}\\left(1+\\frac{r}{r_s}\\right)^3}
where :math:`r_s` is related to the spherical overdensity
halo radius :math:`R_\\Delta(M)` through the concentration
parameter :math:`c(M)` as
.. math::
R_\\Delta(M) = c(M)\\,r_s
and the normalization :math:`\\rho_0` is the mean density
within the :math:`R_\\Delta(M)` of the halo.
By default, this profile is truncated at :math:`r = R_\\Delta(M)`.
Args:
c_M_relation (:obj:`Concentration`): concentration-mass
relation to use with this profile.
fourier_analytic (bool): set to `True` if you want to compute
the Fourier profile analytically (and not through FFTLog).
Default: `False`.
projected_analytic (bool): set to `True` if you want to
compute the 2D projected profile analytically (and not
through FFTLog). Default: `False`.
cumul2d_analytic (bool): set to `True` if you want to
compute the 2D cumulative surface density analytically
(and not through FFTLog). Default: `False`.
truncated (bool): set to `True` if the profile should be
truncated at :math:`r = R_\\Delta` (i.e. zero at larger
radii.
"""
__repr_attrs__ = ("cM", "fourier_analytic", "projected_analytic",
"cumul2d_analytic", "truncated", "precision_fftlog",)
name = 'Hernquist'
def __init__(self, c_M_relation,
truncated=True,
fourier_analytic=False,
projected_analytic=False,
cumul2d_analytic=False):
if not isinstance(c_M_relation, Concentration):
raise TypeError("c_M_relation must be of type `Concentration`")
self.cM = c_M_relation
self.truncated = truncated
self.fourier_analytic = fourier_analytic
self.projected_analytic = projected_analytic
self.cumul2d_analytic = cumul2d_analytic
if fourier_analytic: