-
Notifications
You must be signed in to change notification settings - Fork 1
/
mercurius.py
2251 lines (1902 loc) · 130 KB
/
mercurius.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script for running MultiNest fits on dust FIR SEDs.
Joris Witstok, 17 November 2021
"""
import os, sys, shutil
from mock import patch
if __name__ == "__main__":
print("Python", sys.version)
import numpy as np
rng = np.random.default_rng(seed=9)
import math
from scipy.stats import gamma, norm
from scipy.special import erf
from scipy.ndimage import gaussian_filter
from pymultinest.solve import Solver
from emcee import EnsembleSampler
import corner
import matplotlib
if __name__ == "__main__":
print("Matplotlib", matplotlib.__version__, "(backend: " + matplotlib.get_backend() + ')')
from matplotlib import pyplot as plt
import seaborn as sns
sns.set_style("ticks")
from aux.star_formation import SFR_L
from aux.infrared_luminosity import T_CMB_obs, inv_CMB_heating, CMB_correction, Planck_func, calc_FIR_SED
from aux.legend_handler import BTuple, BTupleHandler
# Import astropy cosmology, given H0 and Omega_matter
from astropy.cosmology import FLRW, FlatLambdaCDM
wl_CII = 157.73617000e-6 # m
nu_CII = 299792458.0 / wl_CII # Hz
# Dust mass absorption coefficient at frequency nu_star
# nu_star = 2998.0e9 # Hz
# k_nu_star = 52.2 # cm^2/g
# Values for dust ejected from SNe after reverse shock destruction from Hirashita et al. (2014): https://ui.adsabs.harvard.edu/abs/2014MNRAS.443.1704H/abstract
wl_star = wl_CII
nu_star = nu_CII # Hz
k_nu_star = 8.94 # cm^2/g (other values range from ~5 to ~30)
# Prior range on the dust emissivity, beta
beta_range = [1, 5]
# Solar luminosity in erg/s
L_sun_ergs = 3.828e26 * 1e7
# Solar mass in g
M_sun_g = 1.989e33
T_dusts_global = np.arange(20, 120, 10)
beta_IRs_global = np.arange(1.5, 2.05, 0.1)
dust_cmap = sns.color_palette("inferno", as_cmap=True)
dust_norm = matplotlib.colors.Normalize(vmin=0, vmax=T_dusts_global[-1])
def log_prob_Gauss(x, mu, cov):
# Simple logarithmic probability function for Gaussian distribution
diff = x - mu
return -0.5 * np.dot(diff, np.linalg.solve(cov, diff))
def mcmc_sampler(means, cov, n_dim=2, n_steps=10000, nwalkers=32):
print("Running {:d}-dimensional MCMC sampler with {:d} walkers performing {:d} steps on function...".format(n_dim, nwalkers, n_steps))
# Set up walkers and initial positions
p0 = rng.normal(loc=means, scale=np.sqrt(np.diagonal(cov)), size=(nwalkers, n_dim))
sampler = EnsembleSampler(nwalkers, n_dim, log_prob_Gauss, args=[means, cov])
sampler.run_mcmc(p0, n_steps, progress=True)
tau = sampler.get_autocorr_time()
print("\nAutocorrelation times:", *tau)
tau_max = math.ceil(0.5*np.max(tau))
# Throw away a few times this number of steps as “burn-in”, discard the initial 3 tau_max,
# and thin by about half the autocorrelation time (15 steps), and flatten the chain
flat_samples = sampler.get_chain(discard=3*tau_max, thin=int(0.5*tau_max), flat=True)
return flat_samples
class lcoord_funcs:
def __init__(self, rowi, coli, z):
self.rowi = rowi
self.coli = coli
self.z = z
def lamrf2lamobs(self, l_emit):
# From micron to mm
return l_emit / 1e3 * (1.0 + self.z)
def lamobs2lamrf(self, l_obs):
# From mm to micron
return l_obs * 1e3 / (1.0 + self.z)
def lamrf2nuobs(self, l_emit):
# From micron to GHz
return 299792.458 / l_emit / (1.0 + self.z)
def nuobs2lamrf(self, nu_obs):
# From GHz to micron
return 299792.458 / nu_obs * (1.0 + self.z)
def nuobs2lamobs(self, nu_obs):
# From GHz to mm
return 299.792458 / nu_obs
def lamobs2nuobs(self, l_obs):
# From mm to GHz
return 299.792458 / l_obs
def FIR_SED_spectrum(theta, z, D_L, l0_dict, lambda_emit=None):
logM_dust = theta[0]
T_dust = theta[1]
beta_IR = theta[2]
if l0_dict.get("cont_area_kpc2") is not None:
# Dust area in kpc^2 converted to cm^2 (1 kpc = 3.085677e21 cm)
l0_dict["cont_area_cm2"] = l0_dict["cont_area_kpc2"] * 3.085677e21**2
if l0_dict["assumption"] == "fixed":
optically_thick_lambda_0 = l0_dict["value"]
elif l0_dict["assumption"] == "self-consistent":
# Dust mass surface density in g/cm^2
Sigma_dust = 10**logM_dust * M_sun_g / l0_dict["cont_area_cm2"]
# Compute the wavelength where the optical depth, τ = κ_nu Σ, becomes 1 (κ in cm^2/g, Σ in g/cm^2)
# κ_nu is given by κ_nu = κ_nu_star * (nu/nu_star)**beta_IR; κ Σ becomes 1 when (nu/nu_star)**beta_IR = 1/(κ_nu_star Σ)
nu_0 = nu_star / (Sigma_dust * k_nu_star)**(1.0/beta_IR) # Hz
optically_thick_lambda_0 = 299792458.0 * 1e6 / nu_0 # micron (nu_0 is in Hz)
# Compute FIR SED fluxes only at the given (rest-frame) wavelengths
lambda_emit, S_nu_emit = calc_FIR_SED(z=z, beta_IR=beta_IR, T_dust=T_dust,
optically_thick_lambda_0=optically_thick_lambda_0,
return_spectrum=True, lambda_emit=lambda_emit)
nu_emit = 299792458.0 * 1e6 / lambda_emit # Hz (lambda is in micron)
# Flux density needs to be corrected for observing against the the CMB (NB: can be negative if T_dust < T_CMB), and then normalised
CMB_correction_factor = CMB_correction(z=z, nu0_emit=nu_emit, T_dust=T_dust)
if np.all(CMB_correction_factor < 0):
# No normalisation possible (T_dust < T_CMB) so 0 likelihood
return -np.inf
# Normalise fluxes using dust mass
# S_nu in Jy, 1e-26 = W/m^2/Hz/Jy, D_L in cm, κ_nu in cm^2/g, Planck_func in W/m^2/Hz, M_sun = 1.989e33 g
nu_ref = nu_CII # Hz
k_nu = k_nu_star * (nu_ref/nu_star)**beta_IR
# Compute (properly normalised) FIR SED flux at the reference (rest-frame) frequency, given the dust mass (NB: uncorrected for CMB effects)
if l0_dict.get("value", -1) is None:
# Compute flux density in optically thin limit, assuming 1 - exp(-τ) ~ τ = κ_nu Σ_dust
S_nu_emit_norm_ref = 10**logM_dust * M_sun_g * k_nu * Planck_func(nu_ref, T_dust) / D_L**2 * 1e26
else:
assert l0_dict["assumption"] == "self-consistent" or l0_dict.get("value", None)
# Compute flux density in general opacity case (see Jones et al. 2020), first computing the optical depth τ;
# convert M_dust from units of M_sun to g, κ_nu is in cm^2/g, area is in cm^2
if l0_dict["assumption"] == "self-consistent":
tau = 10**logM_dust * M_sun_g * k_nu / l0_dict["cont_area_cm2"]
else:
# Compute the optical depth from the fixed value of lambda_0
nu_0 = 299792458.0 * 1e6 / optically_thick_lambda_0 # Hz (lambda_0 is in micron)
tau = (nu_ref/nu_0)**beta_IR
# Calculate the dust surface area in cm^2 required to achieve the fixed lambda_0, given the dust mass
l0_dict["cont_area_cm2"] = 10**logM_dust * M_sun_g * k_nu / tau
Sigma_dust = 10**logM_dust * M_sun_g / l0_dict["cont_area_cm2"]
S_nu_emit_norm_ref = (1.0 - np.exp(-tau)) * Planck_func(nu_ref, T_dust) * l0_dict["cont_area_cm2"] / D_L**2 * 1e26
# Compute unnormalised FIR SED flux specifically for the reference (rest-frame) frequency (NB: also uncorrected for CMB effects)
S_nu_emit_ref = calc_FIR_SED(z=z, beta_IR=beta_IR, T_dust=T_dust,
optically_thick_lambda_0=optically_thick_lambda_0,
return_spectrum=True, lambda_emit=299792458.0 * 1e6 / nu_ref)[1]
# Compute the normalisation of the spectrum by the ratio of the two
# NB: both are uncorrected for CMB effects, but this correction cancels out
norm = S_nu_emit_norm_ref / S_nu_emit_ref
# Normalise emitted flux density and observed, CMB-corrected flux density;
# NB: S_nu_obs needs a factor (1+z) compared to emitted one
S_nu_emit *= norm # Jy
S_nu_obs = S_nu_emit * CMB_correction_factor * (1.0+z) # Jy
return (lambda_emit, nu_emit, S_nu_emit, S_nu_obs)
class MN_FIR_SED_solver(Solver):
def __init__(self, z, D_L, l0_dict, fluxes, flux_errs, uplims, wls,
fixed_T_dust=None, fixed_beta=None, fit_uplims=True, uplim_nsig=None, M_star=np.nan, T_max=150.0, **solv_kwargs):
print("Initialising MultiNest Solver object...")
self.z = z
self.D_L = D_L
self.l0_dict = l0_dict
self.T_CMB = T_CMB_obs * (1.0 + self.z) # K
self.fluxes = fluxes
self.flux_errs = flux_errs
self.uplims = uplims
self.wls = wls
self.fixed_T_dust = fixed_T_dust
self.fixed_beta = fixed_beta
self.fit_uplims = fit_uplims
if uplim_nsig is None:
assert not np.any(self.uplims)
else:
self.uplim_nsig = uplim_nsig
self.set_prior(M_star=M_star, T_max=T_max)
if solv_kwargs["verbose"]:
super().__init__(**solv_kwargs)
else:
devnull = open(os.devnull, 'w')
with patch("sys.stderr", devnull):
super().__init__(**solv_kwargs)
def set_prior(self, M_star, T_max):
if np.isnan(M_star):
logM_dust_range = [4, 12]
else:
logM_dust_range = [4, np.log10(M_star)]
T_dust_range = [self.T_CMB, T_max]
self.cube_range = [logM_dust_range]
if not self.fixed_T_dust:
self.cube_range.append(T_dust_range)
if not self.fixed_beta:
self.cube_range.append(beta_range)
self.cube_range = np.array(self.cube_range)
def Prior(self, cube):
assert hasattr(self, "cube_range")
# Scale the input unit cube to apply uniform priors across all parameters (except the temperature)
for di in range(len(cube)):
if (self.fixed_T_dust and di == 1) or di == 2:
# Use a normal distribution for the dust emissivity (prior belief: beta likely around 1.8)
cube[di] = norm.ppf(cube[di], loc=1.8, scale=0.25)
elif not self.fixed_T_dust and di == 1:
# Use a gamma distribution for the dust temperature (prior belief: unlikely to be near CMB or extremely high temperature)
cube[di] = gamma.ppf(cube[di], a=1.5, loc=0, scale=self.cube_range[di, 0]/0.5) + self.cube_range[di, 0]
else:
cube[di] = cube[di] * (self.cube_range[di, 1] - self.cube_range[di, 0]) + self.cube_range[di, 0]
return cube
def LogLikelihood(self, cube):
theta = (cube[0], self.fixed_T_dust if self.fixed_T_dust else cube[1],
self.fixed_beta if self.fixed_beta else (cube[1] if self.fixed_T_dust else cube[2]))
model_fluxes = FIR_SED_spectrum(theta=theta, z=self.z, D_L=self.D_L, l0_dict=self.l0_dict, lambda_emit=self.wls)[3]
# Calculate the log likelihood given both detections and upper limits according to the formalism in Sawicki et al. (2012):
# first part is a regular normalised least-squares sum, second part is integrating the Gaussian probability up to the 1σ detection limit
# (see Sawicki et al. 2012 for details: https://ui.adsabs.harvard.edu/abs/2012PASP..124.1208S/abstract)
ll = -0.5 * np.nansum(((self.fluxes[~self.uplims] - model_fluxes[~self.uplims])/self.flux_errs[~self.uplims])**2)
if np.any(self.uplims) and self.fit_uplims:
sigma_uplims = self.fluxes[self.uplims]/self.uplim_nsig
ll += np.nansum( np.log( np.sqrt(np.pi) / 2.0 * (1.0 + erf((sigma_uplims - model_fluxes[self.uplims]) / (np.sqrt(2.0) * sigma_uplims))) ) )
return ll
class FIR_SED_fit:
def __init__(self, l0_list, analysis, mnrfol, fluxdens_unit="muJy", l_min=None, l_max=None,
fixed_T_dust=None, fixed_beta=None, fid_T_dust=50.0, cosmo=None,
T_lolim=False, T_uplim=False,
obj_color=None, l0_linestyles=None, pformat=None, dpi=None, mpl_style=None, verbose=True):
"""Class `FIR_SED_fit` for interacting with the fitting and plotting routines of `mercurius`.
Parameters
----------
l0_list : list
A list of opacity model classifiers. Entries can be `None` for an optically thin model,
`"self-consistent"` for a self-consistent opacity model, or a float setting a fixed
value of `lambda_0`, the wavelength in micron setting the SED's transition point between
optically thin and thick.
analysis : bool
Controls whether figures are made with slightly more detail (`True`) or (`False`).
mnrfol : str
Name of the folder used for saving results of SED fits.
fluxdens_unit : str, optional
Unit of flux density in figures, by default `"muJy"`.
l_min : {None, float}, optional
Value in micron of the lower rest-frame wavelength bound in figures.
Default is `None`, which results in `50.0`.
l_max : {None, float}, optional
Value in micron of the upper rest-frame wavelength bound in figures.
Default is `None`, which results in `300.0`.
fixed_T_dust : {`None`, float}, optional
Fixed value of the dust temperature, or `None` if variable (default).
fixed_beta : {`None`, float}, optional
Fixed value of the dust emissivity beta, or `None` if variable (default).
fid_T_dust : float, optional
Fiducial value of the dust temperature in Kelvin, set to `50.0` by default
(overridden by `fixed_T_dust` if specified).
cosmo : instance of astropy.cosmology.FLRW, optional
Custom cosmology (see `astropy` documentation for details).
T_lolim : bool, optional
Retrieve a lower limit (95% confidence) of the dust temperature? (Default: `False`.)
T_uplim : bool, optional
Retrieve an upper limit (95% confidence) of the dust temperature? (Default: `False`.)
obj_color : {`None`, tuple, str}, optional
A custom `matplotlib` colour highlighting the name of the object in figures (see
`matplotlib` documentation on how to specify colours). Default is `None`: no
colour is used.
l0_linestyles : dict, optional
Dictionary for custom `matplotlib` linestyles for each opacity model in figures (see
`matplotlib` documentation on how to specify linestyles). Default is
`{None: '--', "self-consistent": '-', 100.0: '-.', 200.0: ':'}`.
pformat : str, optional
Extension to be used for saving figures. Default is `None`, which sets the format to
`".png"` (i.e. PNG image) if `analysis` is `True`, otherwise it is `".pdf"` (i.e. PDF).
dpi : {int, float}, optional
Quality to be used for saving figures. Default is `None`, which sets `dpi` to `150`.
mpl_style : str, optional
Path to custom `matplotlib` style file. Default is `None`, in which case no
custom file is used.
verbose : bool, optional
Controls whether progress updates and results are printed. Default is `True`.
"""
if verbose:
print("\nInitialising FIR SED fitting object...")
self.l0_list = l0_list
self.analysis = analysis
self.mnrfol = mnrfol
if fluxdens_unit:
assert fluxdens_unit in ["Jy", "mJy", "muJy", "nJy"]
self.fluxdens_unit = fluxdens_unit
# Setting this unit converter to 1 won't change any of the units, so flux density spectra are in Jy;
# setting it to 1e3 will change the units of flux density spectra to mJy, 1e6 to μJy, etc.
self.fd_conv = {"Jy": 1, "mJy": 1e3, "muJy": 1e6, "nJy": 1e9}[fluxdens_unit]
else:
self.fd_conv = 1
if l_min is None:
# Plot from rest-frame wavelength of 50 μm
self.l_min = 50 # micron
else:
self.l_min = l_min
if l_max is None:
# Plot to rest-frame wavelength of 300 μm
self.l_max = 500 # micron
else:
self.l_max = l_max
self.set_fixed_values(fixed_T_dust, fixed_beta)
self.fid_T_dust = fid_T_dust
if verbose:
print("Chosen fiducial values T_dust = {:.0f} K,".format(self.fixed_T_dust if self.fixed_T_dust else self.fid_T_dust), end=' ')
print(("β = {:.2g}".format(self.fixed_beta) if self.fixed_beta else "(β is freely varying)") + "...")
if cosmo is None:
self.cosmo = FlatLambdaCDM(H0=70.0, Om0=0.300)
else:
assert isinstance(cosmo, FLRW)
self.cosmo = cosmo
self.T_lolim = T_lolim
self.T_uplim = T_uplim
self.fresh_calculation = {l0: False for l0 in self.l0_list}
self.obj_color = obj_color
if l0_linestyles is None:
self.l0_linestyles = {None: '--', "self-consistent": '-', 100.0: '-.', 200.0: ':'}
else:
self.l0_linestyles = l0_linestyles
if pformat is None:
self.pformat = ".png" if self.analysis else ".pdf"
else:
self.pformat = pformat
if dpi is None:
self.dpi = 150
else:
self.dpi = dpi
if mpl_style is not None:
# Load style file
plt.style.use(mpl_style)
self.verbose = verbose
if self.verbose:
print("Initialisation done!")
def set_fixed_values(self, fixed_T_dust, fixed_beta):
"""Function for changing the fixed values of the dust temperature and emissivity.
Parameters
----------
fixed_T_dust : float
Fixed value of the dust temperature in Kelvin.
fixed_beta : {`None`, float}
Fixed value of the dust emissivity beta, or `None` if variable.
"""
self.fixed_T_dust = float(fixed_T_dust) if fixed_T_dust else None
self.T_dust_str = "_T_dust_{:.1f}".format(self.fixed_T_dust) if self.fixed_T_dust else ''
self.fixed_beta = float(fixed_beta) if fixed_beta else None
self.beta_str = "beta_{:.1f}".format(self.fixed_beta) if self.fixed_beta else "vary_beta"
def set_data(self, obj, z,
lambda_emit_vals, S_nu_vals, S_nu_errs, cont_uplims, lambda_emit_ranges=None, cont_excludes=None, uplim_nsig=3.0,
obj_M=np.nan, obj_M_lowerr=np.nan, obj_M_uperr=np.nan, SFR_UV=np.nan, SFR_UV_err=np.nan,
cont_area=None, cont_area_uplim=False, reference=None):
"""Function for setting the photometric data of the object.
Parameters
----------
obj : str
Object name.
z : float
Redshift of the object.
lambda_emit_vals : array_like
Values of the rest-frame wavelengths in microns.
S_nu_vals : array_like
Values of the flux density in Jy.
S_nu_errs : array_like
Values of the flux density uncertainty in Jy.
cont_uplims : array_like
Boolean array indicating which data points are upper limits.
lambda_emit_ranges : {`None`, array_like}, optional
Lower and upper wavelength bounds given as an offset from the main wavelength values
(for visualisation only). Needs to be shape (N, 2) for N photometric data points.
Default is `None`, in which case bounds will not be shown.
cont_excludes : {`None`, array_like}, optional
Boolean array indicating which data points are ignored in the fitting process.
Default is `None` where none of the data are excluded.
uplim_nsig : float, optional
How many sigma is an upper limit given as? Default: `3.0`.
obj_M : float, optional
Stellar mass of object, in units of solar masses. Default: `np.nan` (i.e. unknown).
obj_M_lowerr : float, optional
Lower error on the stellar mass of the object, in units of solar masses.
Default: `np.nan` (i.e. unknown).
obj_M_uperr : float, optional
Upper error on the stellar mass of the object, in units of solar masses.
Default: `np.nan` (i.e. unknown).
SFR_UV : float, optional
The object's star formation rate (SFR) in the UV. Default: `np.nan` (i.e. unknown).
SFR_UV_err : float, optional
Uncertainty on the object's star formation rate (SFR) in the UV.
Default: `np.nan` (i.e. unknown).
cont_area : {`None`, float}, optional
Area of the dust emission in square kiloparsec, to be used in the self-consistent
opacity model. Default: `None` (i.e. unknown).
cont_area_uplim : bool, optional
Indicates whether the area is an upper limit. Default: `False`.
"""
if self.verbose:
print("\nSetting photometric data points and other properties of {}...".format(obj))
self.obj = obj
self.obj_fn = self.obj.replace(' ', '_')
self.z = z
self.D_L = self.cosmo.luminosity_distance(self.z).to("cm").value
self.obj_M = obj_M
self.obj_M_lowerr = obj_M_lowerr
self.obj_M_uperr = obj_M_uperr
self.SFR_UV = SFR_UV
self.SFR_UV_err = SFR_UV_err
valid_fluxes = np.isfinite(np.asarray(S_nu_vals))
if cont_excludes is None:
self.cont_excludes = np.tile(False, np.sum(valid_fluxes))
else:
self.cont_excludes = np.asarray(cont_excludes)[valid_fluxes]
if self.verbose:
if np.any(cont_uplims):
print("Upper limits present ({:d}/{:d} data points), will be taken into account...".format(np.sum(cont_uplims), len(cont_uplims)))
if np.any(self.cont_excludes):
print("Excluded photometry present ({:d}/{:d} data points), will not be taken into account...".format(np.sum(self.cont_excludes), len(self.cont_excludes)))
if np.any(~valid_fluxes):
print("Warning: invalid fluxes present ({:d}/{:d} data points), will be ignored...".format(np.sum(~valid_fluxes), len(valid_fluxes)))
self.lambda_emit_vals = np.asarray(lambda_emit_vals)[valid_fluxes]
wl_order = np.argsort(self.lambda_emit_vals)
self.lambda_emit_vals = self.lambda_emit_vals[wl_order]
self.cont_excludes = self.cont_excludes[wl_order]
if lambda_emit_ranges is None:
self.lambda_emit_ranges = np.tile(np.nan, (np.sum(valid_fluxes), 2))
else:
self.lambda_emit_ranges = np.asarray(lambda_emit_ranges)[valid_fluxes][wl_order]
self.S_nu_vals = np.asarray(S_nu_vals)[valid_fluxes][wl_order]
self.S_nu_errs = np.asarray(S_nu_errs)[valid_fluxes][wl_order]
self.cont_uplims = np.asarray(cont_uplims)[valid_fluxes][wl_order]
self.all_uplims = np.all(self.cont_uplims[~self.cont_excludes])
self.uplim_nsig = uplim_nsig
if self.verbose:
header = "Wavelength (μm)\tFlux ({unit})\tError ({unit})\tUpper limit?\tExclude?".format(unit=self.fluxdens_unit.replace("mu", 'μ'))
data_str = "{{:{0}.5g}}\t{{:{1}.5g}}\t{{:{2}}}\t{{:{3}}}\t{{:{4}}}".format(*["<{:d}".format(len(h)) for h in header.split('\t')])
print('', header, *[data_str.format(wl, f*self.fd_conv, 'N/A' if u else "{:.5g}".format(e*self.fd_conv), str(u), str(exc)) \
for wl, f, e, u, exc in zip (self.lambda_emit_vals, self.S_nu_vals, self.S_nu_errs, self.cont_uplims, self.cont_excludes)], sep='\n')
self.valid_cont_area = cont_area is not None and np.isfinite(cont_area) and cont_area > 0.0
self.cont_area = cont_area
self.cont_area_uplim = cont_area_uplim
self.reference = reference
# Combined detections for object
self.n_meas = self.lambda_emit_vals.size
self.cont_det = ~self.cont_uplims * ~self.cont_excludes
def fit_data(self, pltfol=None, fit_uplims=True, return_samples=False, save_results=True, lambda_emit=None,
n_live_points=400, evidence_tolerance=0.5, sampling_efficiency=0.8, max_iter=0,
force_run=False, skip_redundant_calc=False, ann_size="small", mnverbose=False):
"""Function for fitting the photometric data of the object with greybody spectra for
all opacity models set in `l0_list`.
Parameters
----------
pltfol : str, optional
Path to folder in which a corner plot of the results is saved. Default is
`None`, so that no corner plot is saved.
fit_uplims : bool, optional
Include upper limits in the fitting routine?
return_samples : bool, optional
Return samples directly? Default: `False`.
save_results : bool, optional
Save results produced by MultiNest after a run and save resulting samples
in compressed NumPy format (used for plotting afterwards)? Default: `True`.
lambda_emit : array_like, optional
Values in micron to be used as the rest-frame wavelengths in results,
including the (F)IR luminosities. Default is `None`, which will default
to a linearly spaced array of 10,000 points ranging between 4 and 1100
micron in the function `calc_FIR_SED` (located in
`mercurius/aux/infrared_luminosity.py`).
n_live_points : int, optional
Number of live points used in the MultiNest run. See the `pymultinest`
documentation for details.
evidence_tolerance : float, optional
Evidence tolerance value used in the MultiNest run. See the `pymultinest`
documentation for details.
sampling_efficiency : float, optional
Sampling efficiency value used in the MultiNest run. See the `pymultinest`
documentation for details.
max_iter : int, optional
Maximum number of iterations of the MultiNest run. See the `pymultinest`
documentation for details.
force_run : bool, optional
Force a new run of the fitting routine, even if previous results are found.
skip_redundant_calc : bool, optional
Entirely skip the data fitting (including the calculation of ) if results
are already present?
ann_size : float or {'xx-small', 'x-small', 'small', 'medium',
'large', 'x-large', 'xx-large'}, optional
Argument used by `matplotlib.text.Text` for the font size of the annotation.
Default: `"small"`.
mnverbose : bool, optional
Controls whether the main output of the `pymultinest` solver is shown.
Returns
----------
flat_samples : tuple
If `return_samples` is set to `True`, a tuple containing two lists is returned:
one of arrays containing N samples of various parameters and one of the
parameter names (the exact parameters depending on whether the dust temperature and
emissivity are varied).
"""
if self.all_uplims:
print("Warning: only upper limits for {} specified! No MultiNest fit performed...".format(self.obj))
return np.ones((2, 0)) if return_samples else 1
if not return_samples and not save_results:
print("Warning: results neither returned nor saved...")
# Set percentiles to standard ±1σ confidence intervals around the median value
percentiles = [0.5*(100-68.2689), 50, 0.5*(100+68.2689)]
for l0 in self.l0_list:
# Without knowing the source's area, can only fit an optically thin SED or one with fixed lambda_0
if l0 == "self-consistent" and not self.valid_cont_area:
print("\nWithout a valid area, cannot run MultiNest fit with a self-consistent lambda_0 for {}...".format(self.obj))
continue
l0_dict = {"cont_area_kpc2": self.cont_area}
if l0 == "self-consistent":
l0_dict["assumption"] = l0
else:
l0_dict["assumption"] = "fixed"
l0_dict["value"] = l0
l0_str, l0_txt = self.get_l0string(l0)
# Run fit on data
n_dim = 3 - bool(self.fixed_T_dust) - bool(self.fixed_beta)
samples_fname = self.mnrfol + "{}_MN_FIR_SED_flat_samples{}_{}{}.npz".format(self.obj_fn, self.T_dust_str, self.beta_str, l0_str)
if not force_run and skip_redundant_calc and os.path.isfile(samples_fname):
print("\nResults already present: skipping {:d}-dimensional MultiNest fit".format(n_dim),
"with {}".format("T_dust = {:.1f} K".format(self.fixed_T_dust) if self.fixed_T_dust else "varying T_dust"),
"and {}{}".format("β = {:.1f}".format(self.fixed_beta) if self.fixed_beta else "varying β", l0_txt),
"for {}...".format(self.obj))
continue
obtain_MN_samples = force_run or not os.path.isfile(samples_fname)
omnrfol = self.mnrfol + "MultiNest_{}/".format(self.obj)
if not os.path.exists(omnrfol):
os.makedirs(omnrfol)
if obtain_MN_samples:
if self.verbose:
print("\nRunning {:d}-dimensional MultiNest fit".format(n_dim),
"with {}".format("T_dust = {:.1f} K".format(self.fixed_T_dust) if self.fixed_T_dust else "varying T_dust"),
"and {}{}".format("β = {:.1f}".format(self.fixed_beta) if self.fixed_beta else "varying β", l0_txt),
"for {}...".format(self.obj))
currentdir = os.getcwd()
try:
os.chdir(omnrfol)
MN_solv = MN_FIR_SED_solver(z=self.z, D_L=self.D_L, l0_dict=l0_dict,
fluxes=self.S_nu_vals[~self.cont_excludes], flux_errs=self.S_nu_errs[~self.cont_excludes],
uplims=self.cont_uplims[~self.cont_excludes], wls=self.lambda_emit_vals[~self.cont_excludes],
fixed_T_dust=self.fixed_T_dust, fixed_beta=self.fixed_beta, fit_uplims=fit_uplims, uplim_nsig=self.uplim_nsig,
n_dims=n_dim, outputfiles_basename="MN", n_live_points=n_live_points,
evidence_tolerance=evidence_tolerance, sampling_efficiency=sampling_efficiency, max_iter=max_iter,
resume=False, verbose=mnverbose and self.verbose)
except Exception as e:
os.chdir(currentdir)
raise RuntimeError("error occurred while running MultiNest fit...\n{}".format(e))
os.chdir(currentdir)
if not save_results:
shutil.rmtree(omnrfol)
# Note results are also saved as MNpost_equal_weights.dat; load with np.loadtxt(omnrfol + "MNpost_equal_weights.dat")[:, :n_dim]
flat_samples = MN_solv.samples
del MN_solv
if save_results:
# Save results
np.savez_compressed(samples_fname, flat_samples=flat_samples)
if self.verbose:
print("\nFreshly calculated MultiNest samples with {}".format("T_dust = {:.1f} K".format(self.fixed_T_dust) if self.fixed_T_dust else "varying T_dust"),
"{}{}".format("β = {:.1f}".format(self.fixed_beta) if self.fixed_beta else "varying β", l0_txt),
"for {}!\nNumber of samples: {:d}, array size: {:.2g} MB".format(self.obj, flat_samples.shape[0], flat_samples.nbytes/1e6))
else:
# Read in samples from the MN run
flat_samples = np.load(samples_fname)["flat_samples"]
if self.verbose:
print("\nFreshly loaded MultiNest samples with {}".format("T_dust = {:.1f} K".format(self.fixed_T_dust) if self.fixed_T_dust else "varying T_dust"),
"{}{}".format("β = {:.1f}".format(self.fixed_beta) if self.fixed_beta else "varying β", l0_txt),
"for {}!\nNumber of samples: {:d}, array size: {:.2g} MB".format(self.obj, flat_samples.shape[0], flat_samples.nbytes/1e6))
rdict = {}
n_samples = flat_samples.shape[0]
logM_dust_samples = flat_samples[:, 0]
if self.fixed_T_dust:
T_dust, rdict["T_dust_lowerr"], rdict["T_dust_uperr"] = self.fixed_T_dust, np.nan, np.nan
flat_samples = np.insert(flat_samples, 1, np.tile(T_dust, n_samples), axis=1)
if self.fixed_beta:
beta_IR, rdict["beta_IR_lowerr"], rdict["beta_IR_uperr"] = self.fixed_beta, np.nan, np.nan
flat_samples = np.insert(flat_samples, 2, np.tile(beta_IR, n_samples), axis=1)
# There is at least one detection, so set upper limits to False
rdict["M_dust_uplim"] = False
rdict["L_IR_uplim"] = False
if not self.fixed_beta:
# Calculate percentiles of dust emissivity, masking any non-finite values
beta_samples = flat_samples[:, 2]
beta_perc = np.percentile(beta_samples[np.isfinite(beta_samples)], percentiles, axis=0)
beta_IR, rdict["beta_IR_lowerr"], rdict["beta_IR_uperr"] = beta_perc[1], *np.diff(beta_perc)
rdict["beta_IR"] = beta_IR
M_dust_perc = np.percentile(10**logM_dust_samples, percentiles, axis=0)
rdict["M_dust"], rdict["M_dust_lowerr"], rdict["M_dust_uperr"] = M_dust_perc[1], *np.diff(M_dust_perc)
if self.valid_cont_area:
# Dust mass surface density in M_sun/pc^2 (area in kpc^2 converted to pc^2 by multiplying by (10^3)^2)
Sigma_dust_samples = 10**logM_dust_samples / (self.cont_area * 1e6)
Sigma_dust_perc = np.percentile(Sigma_dust_samples, percentiles, axis=0)
rdict["Sigma_dust"], rdict["Sigma_dust_lowerr"], rdict["Sigma_dust_uperr"] = Sigma_dust_perc[1], *np.diff(Sigma_dust_perc)
# Convert from M_sun/pc^2 to g/cm^2 (1 pc = 3.085677e18 cm)
Sigma_dust_samples *= M_sun_g / (3.085677e18)**2
# Compute the wavelength where the optical depth, τ ~ κ_nu Σ, becomes 1 (κ in cm^2/g, Σ in g/cm^2)
# κ_nu is given by κ_nu = κ_nu_star * (nu/nu_star)**beta_IR; κ Σ becomes 1 when (nu/nu_star)**beta_IR = 1/(κ_nu_star Σ)
nu_0_samples = nu_star / (Sigma_dust_samples * k_nu_star)**(1.0/beta_IR) # Hz
del Sigma_dust_samples
lambda_0_samples = 299792458.0 * 1e6 / nu_0_samples # micron (nu_0 is in Hz)
lambda_0_perc = np.percentile(lambda_0_samples, percentiles, axis=0)
rdict["lambda_0"], rdict["lambda_0_lowerr"], rdict["lambda_0_uperr"] = lambda_0_perc[1], *np.diff(lambda_0_perc)
del nu_0_samples
else:
rdict["Sigma_dust"], rdict["Sigma_dust_lowerr"], rdict["Sigma_dust_uperr"] = np.nan, np.nan, np.nan
rdict["lambda_0"], rdict["lambda_0_lowerr"], rdict["lambda_0_uperr"] = np.nan, np.nan, np.nan
if np.isnan(self.obj_M):
dust_frac_perc = np.tile(np.nan, len(percentiles))
else:
if np.isnan(self.obj_M_lowerr) or np.isnan(self.obj_M_uperr):
dust_frac_samples = 10**logM_dust_samples/self.obj_M
else:
M_star_samples = mcmc_sampler([self.obj_M], [[(0.5*(self.obj_M_lowerr+self.obj_M_uperr))**2]],
n_dim=1, n_steps=2500, nwalkers=32)[:, 0]
dust_frac_samples = np.clip(10**logM_dust_samples/rng.choice(M_star_samples, size=logM_dust_samples.size, replace=True), 0, 1)
del M_star_samples
dust_frac_perc = np.percentile(dust_frac_samples, percentiles, axis=0)
del dust_frac_samples
rdict["dust_frac"], rdict["dust_frac_lowerr"], rdict["dust_frac_uperr"] = dust_frac_perc[1], *np.diff(dust_frac_perc)
rdict["dust_yield_AGB"], rdict["dust_yield_AGB_lowerr"], rdict["dust_yield_AGB_uperr"] = 29 * np.array([rdict["dust_frac"],
rdict["dust_frac_lowerr"], rdict["dust_frac_uperr"]])
rdict["dust_yield_SN"], rdict["dust_yield_SN_lowerr"], rdict["dust_yield_SN_uperr"] = 84 * np.array([rdict["dust_frac"],
rdict["dust_frac_lowerr"], rdict["dust_frac_uperr"]])
if self.fixed_T_dust:
T_lim = np.nan
if self.T_lolim:
rdict["T_lolim"] = T_lim
elif self.T_uplim:
rdict["T_uplim"] = T_lim
else:
# Calculate percentiles of dust emissivity, masking any non-finite values
T_dust_samples = flat_samples[:, 1]
T_perc = np.percentile(T_dust_samples, percentiles, axis=0)
T_dust, rdict["T_dust_lowerr"], rdict["T_dust_uperr"] = T_perc[1], *np.diff(T_perc)
if self.T_lolim:
rdict["T_lolim"] = np.percentile(T_dust_samples, 5)
T_lim = rdict["T_lolim"]
elif self.T_uplim:
rdict["T_uplim"] = np.percentile(T_dust_samples, 95)
T_lim = rdict["T_uplim"]
else:
T_lim = np.nan
dcolor = dust_cmap(dust_norm(T_dust))
rdict["T_dust"] = T_dust
rdict["T_dust_z0"] = inv_CMB_heating(self.z, T_dust, beta_IR)
rdict["T_dust_z0_lowerr"], rdict["T_dust_z0_uperr"] = np.abs(np.sort(inv_CMB_heating(self.z, np.array([T_dust-rdict["T_dust_lowerr"], T_dust+rdict["T_dust_uperr"]]), beta_IR) - rdict["T_dust_z0"]))
if self.T_lolim:
rdict["T_lolim_z0"] = inv_CMB_heating(self.z, rdict["T_lolim"], beta_IR)
elif self.T_uplim:
rdict["T_uplim_z0"] = inv_CMB_heating(self.z, rdict["T_uplim"], beta_IR)
# Get the normalised spectrum for the best-fit parameters
data = [logM_dust_samples]
if not self.fixed_T_dust:
data.append(T_dust_samples)
if not self.fixed_beta:
data.append(beta_samples)
H, edges = np.histogramdd(data, bins=50, range=[np.percentile(d, [5, 95]) for d in data])
argmax = np.unravel_index(gaussian_filter(H, 3).argmax(), H.shape)
rdict["theta_ML"] = np.array([np.mean([edges[ai][a:a+2]]) for ai, a in enumerate(argmax)])
if self.fixed_T_dust:
rdict["theta_ML"] = np.insert(rdict["theta_ML"], 1, self.fixed_T_dust)
if self.fixed_beta:
rdict["theta_ML"] = np.insert(rdict["theta_ML"], 2, self.fixed_beta)
# rdict["theta_ML"] = [np.log10(rdict["M_dust"]), T_dust, beta_IR]
lambda_emit, nu_emit, rdict["S_nu_emit"], rdict["S_nu_obs"] = FIR_SED_spectrum(theta=rdict["theta_ML"],
z=self.z, D_L=self.D_L, l0_dict=l0_dict, lambda_emit=lambda_emit)
rdict["lambda_emit"] = lambda_emit
rdict["nu_emit"] = nu_emit
S_nu_emit_samples = np.array([FIR_SED_spectrum(theta=sample, z=self.z, D_L=self.D_L,
l0_dict=l0_dict, lambda_emit=lambda_emit)[2] for sample in flat_samples])
# Loop over samples of S_nu_emit to find uncertainty of L_IR
L_IR_Lsun_samples = []
L_FIR_Lsun_samples = []
lambda_IR = (lambda_emit > 8.0) * (lambda_emit < 1000.0)
lambda_FIR = (lambda_emit > 42.5) * (lambda_emit < 122.5)
for S_nu_emit in S_nu_emit_samples:
# Calculate the integrated IR luminosity between 8 and 1000 μm (integrate Jy over Hz, so convert result to erg/s/cm^2;
# 1 Jy = 10^-23 erg/s/cm^2/Hz)
F_IR = np.trapz(S_nu_emit[lambda_IR][np.argsort(nu_emit[lambda_IR])], x=np.sort(nu_emit[lambda_IR])) * 1e-23
F_FIR = np.trapz(S_nu_emit[lambda_FIR][np.argsort(nu_emit[lambda_FIR])], x=np.sort(nu_emit[lambda_FIR])) * 1e-23
L_IR_Lsun_samples.append(F_IR * 4.0 * np.pi * self.D_L**2 / L_sun_ergs) # L_sun
L_FIR_Lsun_samples.append(F_FIR * 4.0 * np.pi * self.D_L**2 / L_sun_ergs) # L_sun
# Wien's displacement law to find the observed (after correction for CMB attenuation) peak temperature
T_peak_samples = np.array([2.897771955e3/lambda_emit[np.argmax(S_nu_emit)] for S_nu_emit in S_nu_emit_samples])
T_perc = np.percentile(T_peak_samples, percentiles)
rdict["T_peak_val"], rdict["T_peak_lowerr"], rdict["T_peak_uperr"] = T_perc[1], *np.diff(T_perc)
if self.T_lolim:
rdict["T_peak_lolim"] = np.percentile(T_peak_samples, 5)
rdict["T_peak"] = rdict["T_peak_lolim"]
rdict["T_peak_err"] = np.nan
rdict["T_peak_constraint"] = "lolim"
elif self.T_uplim:
rdict["T_peak_uplim"] = np.percentile(T_peak_samples, 95)
rdict["T_peak"] = rdict["T_peak_uplim"]
rdict["T_peak_err"] = np.nan
rdict["T_peak_constraint"] = "uplim"
else:
rdict["T_peak"] = rdict["T_peak_val"]
rdict["T_peak_err"] = [[rdict["T_peak_lowerr"]], [rdict["T_peak_uperr"]]]
rdict["T_peak_constraint"] = "range"
del S_nu_emit_samples
S_nu_obs_samples = np.array([FIR_SED_spectrum(theta=sample, z=self.z, D_L=self.D_L,
l0_dict=l0_dict, lambda_emit=lambda_emit)[3] for sample in flat_samples])
del flat_samples
S_nu_obs_median = np.median(S_nu_obs_samples, axis=0)
rdict["S_nu_obs_lowerr"] = S_nu_obs_median - np.percentile(S_nu_obs_samples, 0.5*(100-68.2689), axis=0)
rdict["S_nu_obs_uperr"] = np.percentile(S_nu_obs_samples, 0.5*(100+68.2689), axis=0) - S_nu_obs_median
del S_nu_obs_samples
L_IR_perc = np.percentile(L_IR_Lsun_samples, percentiles)
rdict["L_IR_Lsun"], rdict["L_IR_Lsun_lowerr"], rdict["L_IR_Lsun_uperr"] = L_IR_perc[1], *np.diff(L_IR_perc)
L_FIR_perc = np.percentile(L_FIR_Lsun_samples, percentiles)
rdict["L_FIR_Lsun"], rdict["L_FIR_Lsun_lowerr"], rdict["L_FIR_Lsun_uperr"] = L_FIR_perc[1], *np.diff(L_FIR_perc)
rdict["SFR_IR"] = SFR_L(rdict["L_IR_Lsun"] * L_sun_ergs, band="TIR")
rdict["SFR_IR_err"] = SFR_L(np.array([rdict["L_IR_Lsun_lowerr"], rdict["L_IR_Lsun_uperr"]]) * L_sun_ergs, band="TIR")
rdict["SFR"] = self.SFR_UV + rdict["SFR_IR"]
rdict["SFR_err"] = np.sqrt(np.tile(self.SFR_UV_err, 2)**2 + (rdict["SFR_IR"]/3.0 if rdict["L_IR_uplim"] else rdict["SFR_IR_err"])**2)
main_names = ["logM_dust"]
if self.analysis:
names = ["logM_dust", "logL_IR", "logL_FIR"]
data = [logM_dust_samples, np.log10(L_IR_Lsun_samples), np.log10(L_FIR_Lsun_samples)]
labels = [r"$\log_{10} \left( M_\mathrm{dust} \, (\mathrm{M_\odot}) \right)$", r"$\log_{10} \left( L_\mathrm{IR} \, (\mathrm{L_\odot}) \right)$",
r"$\log_{10} \left( L_\mathrm{FIR} \, (\mathrm{L_\odot}) \right)$"]
else:
names = ["logM_dust", "logL_IR"]
data = [logM_dust_samples, np.log10(L_IR_Lsun_samples)]
labels = [r"$\log_{10} \left( M_\mathrm{dust} \, (\mathrm{M_\odot}) \right)$", r"$\log_{10} \left( L_\mathrm{IR} \, (\mathrm{L_\odot}) \right)$"]
del logM_dust_samples, L_IR_Lsun_samples, L_FIR_Lsun_samples
extra_dim = len(names) - len(main_names)
n_bins = max(50, n_samples//500)
bins = [n_bins] * len(names)
if not self.fixed_T_dust:
names.append("T_dust")
main_names.append("T_dust")
data.append(T_dust_samples)
bins.append(n_bins)
labels.append(r"$T_\mathrm{dust} \, (\mathrm{K})$")
if self.analysis:
extra_dim += 1
names.append("T_peak")
data.append(T_peak_samples)
bins.append(n_bins)
labels.append(r"$T_\mathrm{peak} \, (\mathrm{K})$")
del T_dust_samples, T_peak_samples
if l0 == "self-consistent":
extra_dim += 1
names.insert(1, "lambda_0")
data.insert(1, lambda_0_samples)
del lambda_0_samples
bins.insert(1, n_bins)
labels.insert(1, r"$\lambda_0$")
if not self.fixed_beta:
names.append("beta")
main_names.append("beta")
data.append(beta_samples)
del beta_samples
bins.append(n_bins)
labels.append(r"$\beta_\mathrm{IR}$")
# Deselect non-finite data for histograms
select_data = np.product([np.isfinite(d) for d in data], axis=0).astype(bool)
if not np.any(select_data):
print("Warning: MultiNest fit of {} resulted in non-finite parameters...".format(self.obj))
return np.ones((2, 0)) if return_samples else 1
data = [d[select_data] for d in data]
ranges = []
for n, d in zip(names, data):
if n in ["logM_dust", "logL_IR", "logL_FIR"]:
ranges.append((0.99*math.floor(np.min(d)), 1.01*math.ceil(np.max(d))))
elif n in ["T_dust", "T_peak"]:
if np.percentile(d, 99) < 40:
ranges.append((math.floor(T_CMB_obs*(1.0+self.z))-5, math.ceil(np.percentile(d, 99.5))+5))
else:
ranges.append((-5, math.ceil(np.percentile(d, 99.5))+5))
elif n in ["lambda_0"]:
ranges.append((-5, math.ceil(np.percentile(d, 99.5))+5))
elif n in ["beta"]:
ranges.append((0.75, 5.25))
if pltfol:
cfig = corner.corner(np.transpose(data), labels=labels, bins=bins, range=ranges,
quantiles=[0.5*(1-0.682689), 0.5, 0.5*(1+0.682689)], smooth=0.5, smooth1d=0.5,
color=dcolor, show_titles=True, title_kwargs=dict(size="small"))
text = self.obj
if self.reference:
text += " ({})".format(self.reference.replace('(', '').replace(')', ''))
size = "medium"
else:
size = "large"
text += '\n' + r"$z = {:.6g}$, $T_\mathrm{{ CMB }} = {:.2f} \, \mathrm{{ K }}$".format(self.z, T_CMB_obs*(1.0+self.z))
if self.analysis:
if not np.isnan(self.obj_M):
text += '\n' + r"$M_* = {:.1f}_{{-{:.1f}}}^{{+{:.1f}}} \cdot 10^{{{:d}}} \, \mathrm{{M_\odot}}$".format(self.obj_M/10**math.floor(np.log10(self.obj_M)),
self.obj_M_lowerr/10**math.floor(np.log10(self.obj_M)), self.obj_M_uperr/10**math.floor(np.log10(self.obj_M)), math.floor(np.log10(self.obj_M)))
if not np.isnan(self.SFR_UV):
text += r", $\mathrm{{ SFR_{{UV}} }} = {:.0f}{}".format(self.SFR_UV, r'' if np.isnan(self.SFR_UV_err) else r" \pm {:.0f}".format(self.SFR_UV_err)) + \
r" \, \mathrm{{M_\odot yr^{{-1}}}}$"
cfig.suptitle(text, size=size)
# Extract the axes
axes_c = np.array(cfig.axes).reshape((n_dim+extra_dim, n_dim+extra_dim))
# Loop over the histograms
for ri in range(n_dim+extra_dim):
for ci in range(ri):
axes_c[ri, ci].vlines(np.percentile(data[ci], percentiles), ymin=0, ymax=1,
transform=axes_c[ri, ci].get_xaxis_transform(), linestyles=['--', '-', '--'], color="grey")
axes_c[ri, ci].hlines(np.percentile(data[ri], percentiles), xmin=0, xmax=1,
transform=axes_c[ri, ci].get_yaxis_transform(), linestyles=['--', '-', '--'], color="grey")
axes_c[ri, ci].plot(np.percentile(data[ci], 50), np.percentile(data[ri], 50), color="grey", marker='s', mfc="None", mec="grey")
if self.analysis:
if names[ri] in main_names and names[ci] in main_names:
axes_c[ri, ci].plot(rdict["theta_ML"][main_names.index(names[ci])], rdict["theta_ML"][main_names.index(names[ri])],
color='k', marker='o', mfc="None", mec='k', mew=1.5)
if "T_peak" in names:
ax_c = axes_c[names.index("T_peak"), names.index("T_dust")]
ax_c.plot(np.linspace(-10, 200, 10), np.linspace(-10, 200, 10), linestyle='--', color="lightgrey", alpha=0.6)
if "T_dust" in names:
for ax_c in axes_c[names.index("T_dust"), :names.index("T_dust")]:
ax_c.axhline(T_CMB_obs*(1.0+self.z), linestyle=':', color='k', alpha=0.6)
for ai, ax_c in enumerate(axes_c[names.index("T_dust"):, names.index("T_dust")]):
ax_c.axvline(T_CMB_obs*(1.0+self.z), linestyle=':', color='k', alpha=0.6)
if ai == 0:
ax_c.annotate(text=r"$T_\mathrm{{ CMB }} (z = {:.6g})$".format(self.z), xy=(T_CMB_obs*(1.0+self.z), 0.5), xytext=(-2, 0),
xycoords=ax_c.get_xaxis_transform(), textcoords="offset points", rotation="vertical",
va="center", ha="right", size="xx-small", alpha=0.8).set_bbox(dict(boxstyle="Round, pad=0.05", facecolor='w', edgecolor="None", alpha=0.8))
if self.T_lolim or self.T_uplim:
ax_c.axvline(T_lim, color="grey", alpha=0.6)
ax_c.annotate(text=("Lower" if self.T_lolim else "Upper") + " limit (95% conf.)", xy=(T_lim, 1), xytext=(2, -4),
xycoords=ax_c.get_xaxis_transform(), textcoords="offset points", rotation="vertical",
va="top", ha="left", size="xx-small", alpha=0.8).set_bbox(dict(boxstyle="Round, pad=0.05", facecolor='w', edgecolor="None", alpha=0.8))
if "T_peak" in names:
for ax_c in axes_c[names.index("T_peak"), :names.index("T_peak")]:
ax_c.axhline(T_CMB_obs*(1.0+self.z), linestyle=':', color='k', alpha=0.6)
for ai, ax_c in enumerate(axes_c[names.index("T_peak"):, names.index("T_peak")]):
ax_c.axvline(T_CMB_obs*(1.0+self.z), linestyle=':', color='k', alpha=0.6)
if ai == 0:
ax_c.annotate(text=r"$T_\mathrm{{ CMB }} (z = {:.6g})$".format(self.z), xy=(T_CMB_obs*(1.0+self.z), 0.5), xytext=(-2, 0),
xycoords=ax_c.get_xaxis_transform(), textcoords="offset points", rotation="vertical",
va="center", ha="right", size="xx-small", alpha=0.8).set_bbox(dict(boxstyle="Round, pad=0.05", facecolor='w', edgecolor="None", alpha=0.8))
if self.T_lolim or self.T_uplim:
ax_c.axvline(rdict["T_peak"], color="grey", alpha=0.6)
ax_c.annotate(text=("Lower" if self.T_lolim else "Upper") + " limit (95% conf.)", xy=(rdict["T_peak"], 1), xytext=(2, -4),
xycoords=ax_c.get_xaxis_transform(), textcoords="offset points", rotation="vertical",
va="top", ha="left", size="xx-small", alpha=0.8).set_bbox(dict(boxstyle="Round, pad=0.05", facecolor='w', edgecolor="None", alpha=0.8))
if self.analysis:
self.annotate_results(rdict, [axes_c[0, -1], axes_c[1, -1]], ax_type="corner", ann_size=ann_size)
cfig.savefig(pltfol + "Corner_MN_" + self.obj_fn + self.get_mstring(l0_list=[l0], single_plot=False) + self.pformat,
dpi=self.dpi, bbox_inches="tight")
# plt.show()
plt.close(cfig)