API reference¶
This reference is generated from source docstrings. The symbols listed here form the public API; other symbols are internal.
Stellar populations¶
ceridwen.ssps.SSPData
dataclass
¶
SSPData(
ssp_lgmet,
ssp_lg_age_gyr,
ssp_wave,
ssp_flux,
ssp_resolution=None,
resolution_source=None,
ssp_stellar_mass=None,
stellar_mass_source=None,
stellar_mass_refused=None,
isoc_type=None,
spec_library=None,
imf_type=None,
fsps_version=None,
fsps_kwargs=dict(),
wave_min=None,
wave_max=None,
schema_version=None,
log10_zsun=None,
zsun_nominal=None,
axis_meaning=None,
zsun_source=None,
chash=None,
refused_cells=(),
refused_reason=None,
zsun=None,
_chash_hint=None,
_extra_datasets=(),
)
Immutable container for the SSP interpolation grids plus static provenance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ssp_lgmet
|
array (n_met,) -- the grid's NATIVE metallicity axis, log10 Z: absolute Z for
|
BPASS, the FSPS label log10(zsun 10^[Fe/H]) for MIST/aMIST (not MIST's physical initial Z) |
required |
ssp_lg_age_gyr
|
array(n_ages) - -log10(age / Gyr)
|
|
required |
ssp_wave
|
(array(n_wave), Angstrom)
|
|
required |
ssp_flux
|
ndarray (n_met, n_ages, n_wave), L_sun/Hz per M_sun formed -- kept in HOST memory as a
|
read-only NumPy array (a JAX array given here is copied to the host); the CSP puts only its float32 copy on the device |
required |
ssp_resolution
|
ndarray (n_wave,), km/s -- library sigma_v(lambda) on ssp_wave, NaN where unknown; optional in memory, required by save()/load()
|
|
None
|
ssp_stellar_mass
|
ndarray (n_met, n_ages) or None -- surviving mass (stars + remnants) per
|
M_sun formed of each SSP, FSPS |
None
|
stellar_mass_source
|
str or None -- provenance of ``ssp_stellar_mass``
|
|
None
|
stellar_mass_refused
|
str or None -- why the file's table was refused at load (values
|
above |
None
|
zsun
|
float, init-only -- the grid's solar metallicity (mass fraction) when it is neither
|
recorded ( |
None
|
log10_zsun
|
float -- resolved: the grid's solar node (exact), so logzsol = ssp_lgmet - log10_zsun
|
|
None
|
axis_meaning
|
(feh, log_z_over_zsun)
|
|
"feh"
|
logzsol_axis
property
¶
The metallicity axis in logzsol = ssp_lgmet - log10_zsun (float64).
with_stellar_mass ¶
Return a copy carrying the surviving stellar-mass table mass (shape
ssp_flux.shape[:-1], M_sun per M_sun formed) with its provenance source.
Source code in ceridwen/ssps/ssp_data.py
require_stellar_mass ¶
The surviving stellar-mass table; ValueError saying how to get a grid with one.
Source code in ceridwen/ssps/ssp_data.py
with_resolution ¶
Return a copy carrying a library resolution curve from exactly one of sigma_v (km/s on ssp_wave, NaN where unknown) or segments.
Source code in ceridwen/ssps/ssp_data.py
display ¶
Print (or return as str when return_str) a summary of the grid and its provenance.
Source code in ceridwen/ssps/ssp_data.py
save ¶
Write grids, resolution curve and provenance attrs to HDF5 (overwrites); raises ValueError if ssp_resolution is None.
Source code in ceridwen/ssps/ssp_data.py
load
classmethod
¶
Load a grid from HDF5; raises ValueError if the file lacks ssp_resolution. flux_dtype casts the flux cube on read.
zsun supplies the grid's solar metallicity when it is neither recorded in the file nor in grid_metadata.CHASH_TABLE.
Source code in ceridwen/ssps/ssp_data.py
from_fsps
classmethod
¶
Build a grid from the SPS backend, attach the library resolution curve and record provenance.
Only library/IMF-defining kwargs (LIBRARY_IMF_KWARGS) are accepted.
The resolution curve is the element-wise maximum of the 2-pixel sampling
floor of ssp_wave and resolution_segments (if given, which then
require resolution_source). Raises ValueError otherwise.
Source code in ceridwen/ssps/ssp_data.py
ceridwen.ssps.SSPDataAfe
dataclass
¶
SSPDataAfe(
ssp_lgmet,
ssp_lg_age_gyr,
ssp_wave,
ssp_flux,
ssp_resolution=None,
resolution_source=None,
ssp_stellar_mass=None,
stellar_mass_source=None,
stellar_mass_refused=None,
isoc_type=None,
spec_library=None,
imf_type=None,
fsps_version=None,
fsps_kwargs=dict(),
wave_min=None,
wave_max=None,
schema_version=None,
log10_zsun=None,
zsun_nominal=None,
axis_meaning=None,
zsun_source=None,
chash=None,
refused_cells=(),
refused_reason=None,
zsun=None,
_chash_hint=None,
_extra_datasets=(),
*,
ssp_afe
)
Bases: SSPData
Immutable alpha-enhanced SSP grid: an SSPData whose flux cube has a leading [alpha/Fe] axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ssp_lgmet
|
jnp.ndarray (n_met,) -- native axis [Fe/H] + log10(Z_sun), the SAME on every [alpha/Fe]
|
plane (FSPS AFE_FLAG=1 loads isoc_feh_ |
required |
ssp_afe
|
jnp.ndarray (n_afe,), keyword-only -- [alpha/Fe] grid, strictly increasing
|
|
required |
ssp_lg_age_gyr
|
ndarray(n_ages) - -log10(age / Gyr)
|
|
required |
ssp_wave
|
ndarray(n_wave) - -Angstrom
|
|
required |
ssp_flux
|
np.ndarray (n_afe, n_met, n_ages, n_wave) -- Lsun / Hz per Msun formed; host NumPy,
|
read-only, as in |
required |
ssp_resolution
|
np.ndarray (n_wave,) or None -- sigma_v(lambda) [km/s] on ``ssp_wave``; required by save/load
|
|
None
|
ssp_stellar_mass
|
np.ndarray (n_afe, n_met, n_ages) or None -- surviving mass per M_sun formed (optional)
|
|
None
|
load
classmethod
¶
Load from HDF5; a 3-D grid without ssp_afe is promoted to n_afe = 1 at [alpha/Fe] = 0.
zsun as for :meth:SSPData.load.
Source code in ceridwen/ssps/ssp_data_afe.py
from_fsps
classmethod
¶
from_fsps(
save_to=None,
afe_values=None,
resolution_segments=None,
resolution_source=None,
**fsps_kwargs
)
Build the grid by looping get_spectrum(tage=0, zmet=i) over the [alpha/Fe] planes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
afe_values
|
array-like, optional -- [alpha/Fe] of each plane in ``afeindx`` order; defaults exist for n_afe 5 and 1 only
|
|
None
|
resolution_segments
|
list, optional -- documented library LSF segments, max-combined with the 2-pixel sampling floor
|
|
None
|
resolution_source
|
str, optional -- citation for ``resolution_segments``; each raises if given without the other
|
|
None
|
Source code in ceridwen/ssps/ssp_data_afe.py
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 | |
ceridwen.ssps.fetch_grid ¶
Return a local, checksum-verified path to the registry grid name,
downloading into :func:grid_cache_dir on first use (force re-downloads).
Source code in ceridwen/ssps/grid_fetch.py
ceridwen.ssps.available_grids ¶
Map of grid name -> one-line description.
Grid metallicity metadata¶
ceridwen.ssps.grid_metadata.logzsol_total ¶
Total metallicity [Z/H] (Z/X definition) from logzsol = [Fe/H] on an alpha grid.
ceridwen.ssps.grid_metadata.f_alpha ¶
[Z/H] - [Fe/H] at [alpha/Fe] = afe (jnp- and numpy-compatible, differentiable).
Source code in ceridwen/ssps/grid_metadata.py
ceridwen.ssps.grid_metadata.chash_arrays ¶
chash-v1 of a grid's arrays (see the module docstring).
Source code in ceridwen/ssps/grid_metadata.py
Composite stellar population (forward model)¶
ceridwen.csp.CSPBasis ¶
CSPBasis(
SSPData,
theta=None,
tiny_logt=-70,
zh_const=False,
add_neb=True,
init_neb_params=None,
nebemlineinspec=False,
add_dust=True,
add_diffuse_dust=True,
add_dust_emission=False,
add_igm=False,
igm_model="madau1995",
igm_factor=1.0,
sps_home=None,
init_dust_params=None,
diffuse_law="kriek_conroy",
verbose=True,
sfh_interp="step",
track_zred_age=False,
lookback_time=None,
sfh_per_bin=None,
fesc_geometry="runaway_bc",
duste_model="DL07",
cosmo=None,
gas_tied=False,
wavelength_support=False,
agn=None,
fixed=None,
**kwargs
)
Composite stellar population basis. predict(theta, observations) projects the model onto observations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
SSPData
|
SSPData -- SSP grids (wave, flux, ages, metallicities, optional resolution curve).
|
|
required |
theta
|
dict -- initial values; must contain "lookback_time" (Gyr, increasing, index 0 = today,
|
|
None
|
lookback_time
|
array -- shortcut for ``theta``: the node grid only, neutral initial values
|
(sfh = 1, metallicity = grid median). |
None
|
sfh_per_bin
|
bool or None -- with ``lookback_time=``, the shape of the default "sfh". "step"
|
always takes one SFR per bin (n_time-1,), as Prospector's FastStepBasis (False is refused); "linear" takes one per node (n_time,), or with True one per bin, mapped to nodes (interior nodes the mean of their two bins, the end nodes the end bins). |
None
|
zh_const
|
bool -- constant metallicity ("logzsol") or one metallicity per SFH bin
|
("logzsol_bins", constant within each bin). The removed per-node "logzsol_hist" entered only through its bin means 0.5*(zh[k] + zh[k+1]); "logzsol_bins" gives them directly. |
False
|
gas_tied
|
bool -- gas-phase metallicity follows the stellar one, gas_logz := logzsol (or
|
logzsol_bins[0], the youngest bin's), as Prospector ties them; "gas_logz" is then not a parameter. The two are the SAME NUMBER, not the same absolute Z: logzsol uses the SSP grid's Z_sun (e.g. 0.0185 for MIST) and gas_logz the CLOUDY grid's own reference (Byler+2017; its node set is 0.019- or 0.020-based), which is the FSPS/Prospector convention. |
False
|
add_neb
|
bool -- physics switches.
|
|
True
|
add_dust
|
bool -- physics switches.
|
|
True
|
add_diffuse_dust
|
bool -- physics switches.
|
|
True
|
add_dust_emission
|
bool -- physics switches.
|
|
True
|
add_igm
|
bool -- physics switches.
|
|
True
|
duste_model
|
(DL07, THEMIS)
|
Draine & Li (2007) or THEMIS (Jones et al. 2013, 2017), both from $SPS_HOME/dust/dustem
with FSPS's (qPAH, Umin) axes. THEMIS's |
'DL07'
|
sps_home
|
str -- data directory for the nebular and dust-emission grids; defaults to $SPS_HOME.
|
|
None
|
init_neb_params
|
dict -- forwarded to NebularModel / Dust. ``isoc_type`` is
|
taken from the SSP grid's provenance when recorded. |
None
|
init_dust_params
|
dict -- forwarded to NebularModel / Dust. ``isoc_type`` is
|
taken from the SSP grid's provenance when recorded. |
None
|
sfh_interp
|
(step, linear)
|
piecewise-linear (analytic log-age integral, small negative weights clipped) SFH. |
'step'
|
track_zred_age
|
bool -- with a sampled ``zred``, rescale the lookback grid so its oldest node
|
is the age of the Universe at that redshift, keeping the mass theta["sfh"] forms on the construction grid (the SFR is scaled by T_grid / age(zred)). |
False
|
fesc_geometry
|
(runaway_bc, picket)
|
'runaway_bc': a fraction frac_obrun of EVERY age row skips that row's age-bin attenuation
(the diffuse dust still applies); with several attenuated age bins old stars escape too.
The nebular ages emit a fraction frac_obrun of their LyC and power 1 - frac_obrun of the
nebular emission. 'picket': a fraction frac_obrun of the young light (the nebular grid's
ages, |
'runaway_bc'
|
cosmo
|
Cosmology -- required; used for the flux factor and for the age of the Universe.
|
|
None
|
nebemlineinspec
|
bool -- default of ``include_lines`` in ``get_spectrum`` only.
|
|
False
|
wavelength_support
|
bool -- opt-in (default False): ``predict`` synthesises only the model
|
pixels the observations read ( |
False
|
agn
|
ceridwen.agn.AGNConfig, True, a mode name, or None -- the AGN (Nenkova+08 torus,
|
Temple+21 disc, dust4 screen, narrow lines), off by default (None: every path
unchanged, byte for byte). |
None
|
Source code in ceridwen/csp/csp.py
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 | |
initialize_model_structure ¶
Validate theta (grid, sfh shape, metallicity key) and build theta_init / param_names.
Source code in ceridwen/csp/csp.py
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 | |
register_known_theta_keys ¶
Add keys that _warn_unknown_theta_keys must accept (model-level parameters consumed by transforms).
check_param_ranges ¶
Messages (and warnings) for metallicity / nebular parameters outside the interpolation grids, where the model clamps silently.
Source code in ceridwen/csp/csp.py
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 | |
set_attenuation_function ¶
Assign self.attenuate_dust(wave, theta) -> (attn_birthcloud (n_bins, n_wave), attn_diffuse (n_wave,)) as optical depths.
The attribute is a BOUND METHOD of this instance (one of _attenuate_*), not a closure
over self: a shallow copy whose stored bound methods are re-bound to the copy then
reads the COPY's dust models. The expressions are unchanged (bit-identical). It is set
only when dust is configured, so hasattr(csp, "attenuate_dust") keeps meaning
"this CSP attenuates" (model.py, _agn_galaxy_ldust).
Source code in ceridwen/csp/csp.py
get_spectrum_components ¶
(continuum, lines) on the rest-frame grid, unscaled (no mass, distance or IGM):
continuum is get_spectrum(include_lines=False) and lines the difference to the
full spectrum: the attenuated painted lines. With dust emission the dust re-emission of
the lines' absorbed energy is in continuum, as on every path.
Source code in ceridwen/csp/csp.py
predict ¶
{obs.name: prediction}: Photometry -> maggies (n_filters,), Spectrum -> F_nu [erg/s/cm^2/Hz]
on the observed pixels, Lines -> integrated fluxes (n_lines,). Observed-frame only when
theta carries zred.
kinematics (Kinematics or None) supplies sigma_gal / sigma_gas; broaden_photometry
applies them to the spectrum entering each Photometry's _broadener. The lines are not
painted on the model grid (only with _force_paint_lines, a reference path): Photometry
adds each line's flux through each filter (obs._line_photometry: delta lines, or
Gaussians of the gas width with broaden_photometry), Spectrum paints them on the
observed pixels and Lines reads them from the grid.
eline_system (ElineSystem of SedModel, line marginalisation): returns
(predictions, aux) with the fitted lines removed from every prediction and
aux = {"prior_mean": CLOUDY fluxes of the fitted lines, "cols": {obs.name: design}}.
Source code in ceridwen/csp/csp.py
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 | |
predict_line_fluxes ¶
Observed-frame fluxes of every nebular grid line (n_lines,), through the same weights, dust, escape, mass and distance factors as the spectrum.
Default: integrated fluxes [erg/s/cm^2] with the 1/(1+z) Jacobian, the IGM transmission
averaged over the line's painted profile and eline_scaling (the Lines observation). for_spectrum: the same
without eline_scaling (painted by the Spectrum projector). for_photometry: per-Hz
amplitudes with the full f_nu flux factor and no IGM (applied inside the photometric line
basis) and no eline_scaling.
Source code in ceridwen/csp/csp.py
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 | |
get_line_spec ¶
Painted line component alone on the rest-frame grid, scaled by mass, flux factor and IGM as in
predict, times eline_scaling (the Lines-observation aperture factor).
Source code in ceridwen/csp/csp.py
age_at ¶
Age of the Universe [Gyr] at redshift z under self.cosmo
(a float for a scalar, a JAX array otherwise).
Source code in ceridwen/csp/csp.py
display_sfh ¶
display_sfh(
theta=None,
ax=None,
*,
overlay_nodes=True,
show_bin_edges=False,
units="Gyr",
**plot_kwargs
)
Plot the SFH exactly as _ssp_weights interprets it (step: constant per bin; linear:
chords between nodes); theta defaults to theta_init, units in {"Gyr", "Myr", "yr"}.
Returns the axes.
Source code in ceridwen/csp/csp.py
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 | |
calculate_ssp_weights_const_zh ¶
calculate_ssp_weights_const_zh_step ¶
calculate_ssp_weights_var_zh ¶
calculate_ssp_weights_var_zh_step ¶
surviving_mass_fraction ¶
mfrac = M_surviving / M_formed of the population theta describes: the grid's
surviving-mass table weighted by the same SSP weights as the spectrum,
sum(W m) / sum(W). Post-processing only (PostProcess); needs a grid with
ssp_stellar_mass (SSP schema 3), else ValueError.
Source code in ceridwen/csp/csp.py
get_spectrum_dattn_nodem_neb ¶
Dust attenuation + nebular emission. include_lines None -> self.nebemlineinspec;
support (static slice): those model pixels only.
Source code in ceridwen/csp/csp.py
get_spectrum_dattn_dem_neb ¶
Dust attenuation + nebular emission + dust emission. The energy balance always counts
the lines' absorbed energy; include_lines only decides whether the attenuated lines are
in the output (False: attenuated continuum + the full dust emission).
Source code in ceridwen/csp/csp.py
get_spectrum_dattn_nodem_noneb ¶
Dust attenuation only (include_lines ignored); support: those pixels only.
Source code in ceridwen/csp/csp.py
get_spectrum_dattn_dem_noneb ¶
Dust attenuation + dust emission, no nebular (include_lines ignored).
Source code in ceridwen/csp/csp.py
get_spectrum_nodattn_nodem_noneb ¶
Stellar continuum only; support: those pixels only.
Source code in ceridwen/csp/csp.py
get_spectrum_nodattn_nodem_neb ¶
Nebular emission, no dust; support: those pixels only.
Source code in ceridwen/csp/csp.py
ceridwen.csp.CSPBasis_afe ¶
CSPBasis_afe(
SSPData,
theta=None,
tiny_logt=-70,
zh_const=False,
add_dust=True,
add_diffuse_dust=True,
add_dust_emission=False,
add_igm=False,
igm_model="madau1995",
igm_factor=1.0,
sps_home=None,
init_dust_params=None,
diffuse_law="kriek_conroy",
verbose=True,
sfh_interp="step",
track_zred_age=False,
lookback_time=None,
sfh_per_bin=None,
cosmo=None,
duste_model="DL07",
wavelength_support=False,
agn=None,
fixed=None,
**kwargs
)
Bases: CSPBasis
Composite stellar population basis with [alpha/Fe] interpolation and no nebular model.
Same constructor and interface as CSPBasis minus the nebular arguments; requires an
SSPDataAfe grid (4-D ssp_flux with an ssp_afe axis). theta["afe"] is
optional: absent, the plane closest to [alpha/Fe] = 0 is used. The SFH weights,
dust, projection, flux factor and cosmology are those of CSPBasis, and so are
wavelength_support (opt-in) and agn (see CSPBasis; L_bol and the dust-free
galaxy spectrum are taken at theta['afe'] like the flux cube).
Source code in ceridwen/csp/csp_afe.py
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 | |
initialize_model_structure ¶
CSPBasis.initialize_model_structure plus the optional scalar theta['afe'].
Source code in ceridwen/csp/csp_afe.py
check_param_ranges ¶
CSPBasis.check_param_ranges plus theta['afe'] against the [alpha/Fe] grid.
Source code in ceridwen/csp/csp_afe.py
logzsol_total ¶
[Z/H] = logzsol + f([alpha/Fe]) for this theta (Z/X definition; grid_metadata),
elementwise for a per-bin history (self.zh_key).
Source code in ceridwen/csp/csp_afe.py
refused_cells_logzsol ¶
[(logzsol_lo, logzsol_hi, afe_lo, afe_hi, reason)] of the refused interpolation cells.
Taken from the GRID (SSPData.refused_cells), which is filled from the metadata
table, from the file's own refused_cells_json provenance, or by the duplicate-
isochrone detection in SSPDataAfe.from_fsps -- so a re-saved, converted or freshly
built alpha grid keeps its refusals even when its content hash is not a table key.
Source code in ceridwen/csp/csp_afe.py
get_spectrum_components ¶
(continuum, zeros): no nebular model, so the line component is identically zero.
Source code in ceridwen/csp/csp_afe.py
get_line_spec ¶
get_spectrum_dattn_nodem_noneb ¶
Dust attenuation only (include_lines ignored); support: those pixels only.
Source code in ceridwen/csp/csp_afe.py
get_spectrum_dattn_dem_noneb ¶
Dust attenuation + dust emission (include_lines ignored).
Source code in ceridwen/csp/csp_afe.py
get_spectrum_nodattn_nodem_noneb ¶
Stellar continuum only; support: those pixels only.
Source code in ceridwen/csp/csp_afe.py
AGN¶
ceridwen.agn.AGNConfig
dataclass
¶
AGNConfig(
agn_mode=AGN_MODE_CORRECTED,
torus=None,
disk=None,
lines=None,
dust4_type=0,
tau_interp="linear",
agn_energy_balance=None,
torus_file=None,
torus_model="nenkova08",
polar_dust=False,
polar_law=None,
nlr_model="a42",
blr=False,
skirtor_R=None,
skirtor_file=None,
nlr_file=None,
blr_file=None,
)
Static AGN configuration, validated on construction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agn_mode
|
('corrected', 'fsps', 'prospector')
|
"corrected" is the physically consistent model; "fsps" and "prospector" reproduce those codes (defects included) for comparison with existing fits. |
"corrected"
|
torus
|
bool or None
|
Which components exist. |
None
|
disk
|
bool or None
|
Which components exist. |
None
|
lines
|
bool or None
|
Which components exist. |
None
|
dust4_type
|
(0, 1)
|
AGN screen: 0 none, 1 diffuse dust2 curve times a |
0
|
tau_interp
|
('linear', 'log')
|
Interpolation of the torus templates in |
"linear"
|
agn_energy_balance
|
bool or None
|
Re-emit the AGN light absorbed by the galaxy screen through DL07.
|
None
|
torus_file
|
str or None
|
Nenkova+08 template file; default
|
None
|
torus_model
|
('nenkova08', 'skirtor16')
|
Which torus |
"nenkova08"
|
polar_dust
|
bool
|
CIGALE's polar dust (extinction of the SKIRTOR disc and its grey-body re-emission).
Needs |
False
|
polar_law
|
('smc', 'calzetti', 'gaskell')
|
Extinction law of the polar dust; None = CIGALE's default ( |
"smc"
|
nlr_model
|
('a42', 'feltre16')
|
The narrow-line set |
"a42"
|
blr
|
bool
|
Broad lines with their own amplitude ( |
False
|
skirtor_R
|
float or None
|
Static ratio of outer to inner torus radius (a node of the SKIRTOR grid; None = the
component's default). Only with |
None
|
skirtor_file
|
str or None
|
Data files of the AGN2 components (default: under |
None
|
nlr_file
|
str or None
|
Data files of the AGN2 components (default: under |
None
|
blr_file
|
str or None
|
Data files of the AGN2 components (default: under |
None
|
Every
|
|
required |
energy_balance ¶
Resolved energy-balance switch for a CSP with/without dust emission.
Source code in ceridwen/agn/__init__.py
ceridwen.agn.torus.NenkovaTorus ¶
Bases: Component
Nenkova+08 torus: rest_spectrum = fagn * L_bol_star * T(agn_tau) [L_sun/Hz per
M_formed], before any attenuation. T integrates to 1 over frequency exactly in
"corrected" mode and to the FSPS/Prospector resampled value otherwise.
Attributes: templates (n_wave, 9) jnp float64, tau_grid (9,), native_integrals
(9,) = sum(T_j |w|) of the resampled columns before any renormalisation (on this grid),
file_integrals (9,) the trapezoid on the file's own 125 points (the "unity" of the
file header, 0.9993), dense_integrals (9,) the log-log SED on a dense log grid over
the whole template (0.989-0.996: the file's unity is a coarse-trapezoid artefact),
path.
Source code in ceridwen/agn/torus.py
template ¶
(n_wave,) T(agn_tau): unit-normalised SED shape (pure JAX).
Source code in ceridwen/agn/torus.py
ceridwen.agn.disk.TempleDisk ¶
Bases: Component
Accretion disc: fagn_bbb x Temple+21 template, normalised to the galaxy at 5500 A.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wave
|
(n_wave,) array
|
Rest-frame model wavelength grid [A], ascending. Static. |
required |
mode
|
('fsps', 'prospector', 'corrected')
|
Template resampling (see module docstring). |
"fsps"
|
template_file
|
str
|
Two-column (wave [A], F_nu) file; default the bundled |
None
|
Source code in ceridwen/agn/disk.py
norm_scale ¶
Prospector's scale = median(template / galaxy) over the 5500 A window,
and a bool that is False when the galaxy is not positive in every window pixel.
Source code in ceridwen/agn/disk.py
rest_spectrum ¶
(n_wave,) disc F_nu [units of ctx.gal_nodust_young_old], before attenuation.
Source code in ceridwen/agn/disk.py
ceridwen.agn.screen.AGNScreen ¶
Bases: Screen
Attenuation of the AGN disc: spec * diffuse_curve * exp(-(lam/5500)**dust4_index * dust4).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wave
|
(n_wave,) array
|
Rest-frame model grid [A]. Static. |
required |
dust4_type
|
(0, 1)
|
0: diffuse curve only ( |
0
|
Source code in ceridwen/agn/screen.py
dust4_transmission ¶
exp(-(lam/5500)**dust4_index * dust4) (all ones for dust4_type=0).
Source code in ceridwen/agn/screen.py
transmission ¶
attenuate ¶
ceridwen.agn.lines.AGNLines ¶
Bases: LineComponent
The AGN narrow-line set (static: 23 lines, fixed at setup).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
one of ``AGN_MODES`` -- selects the painter (see the module docstring)
|
|
required |
sps_home
|
FSPS directory holding ``data/emlines_info.dat`` (default ``$SPS_HOME``)
|
|
None
|
table_file
|
the ratio table (default ``data/richardson14_a42.csv``)
|
|
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
line_names |
tuple of FSPS names; ``line_wave`` (n,) vacuum rest wavelengths [A] from the
|
|
FSPS list in use; ``ratios`` (n,) L_line / L_Hbeta; ``fsps_index`` (n,) the rows of that list; |
|
|
``emlines_wave`` / ``emlines_names`` |
the whole FSPS list (for matching observed lines by name).
|
|
Source code in ceridwen/agn/lines.py
line_luminosity ¶
(n_lines,) agn_elum * ratio [L_sun per M_formed], in the order of line_names.
sigma_kms ¶
rows_for ¶
For each rest wavelength in wave_rest: the index of the AGN line it is, or -1.
Matched BY NAME: each wavelength is first resolved to the nearest line of the FSPS list
(within tol A, else ValueError, the tolerance of the nebular cube matching), and that
line's name is looked up in line_names. So two FSPS lines closer than tol (He I 3889
and H 8 3890) are never confused.
Source code in ceridwen/agn/lines.py
observed_fluxes ¶
(n_lines,) observed integrated fluxes [erg/s/cm^2]: line_luminosity * mass *
flux_factor_over_opz times transmission (n_lines,) when given. mass defaults to
10**theta['logmass'] (1 without it); flux_factor_over_opz is the CSP's
_flux_factor(theta) / (1 + z) (L_sun -> erg/s/cm^2), the factor its nebular lines use.
Source code in ceridwen/agn/lines.py
ceridwen.agn.hook.AGNHook ¶
Static AGN wiring for one CSP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AGNConfig
|
|
required |
wave
|
(n_wave,) rest-frame model grid [A]
|
|
required |
add_dust_emission
|
bool -- whether the CSP has DL07 (decides the energy balance)
|
|
required |
sps_home
|
str or None
|
|
None
|
Source code in ceridwen/agn/hook.py
filled ¶
The AGN theta keys, each from theta when present else its default (static).
provenance ¶
Static facts a result file should record (INT writes them into fit.py).
Source code in ceridwen/agn/hook.py
range_messages ¶
check_param_ranges messages for the AGN keys (setup-time, NumPy).
Source code in ceridwen/agn/hook.py
agn_transmission ¶
(n_wave,) T_agn of the reproduction modes (see the module docstring).
Source code in ceridwen/agn/hook.py
components ¶
(intrinsic, attenuated) (n_wave,) float64 sums over the continuum components.
Source code in ceridwen/agn/hook.py
galaxy_curve ¶
The galaxy-dust transmission the AGN2 parts see: the diffuse curve in "corrected", 1 in "cigale" (CIGALE adds the AGN after its dust attenuation modules).
Source code in ceridwen/agn/hook.py
nuclear_parts ¶
AGN2 continuum before the galaxy's dust, (n_wave,) float64 each: disk (SKIRTOR
disc, unattenuated), dust (SKIRTOR torus dust), polar_t (the polar-dust
transmission, ones without polar dust), polar_ir (its re-emission), nuclear =
disk * polar_t + dust + polar_ir. theta is the filled AGN theta.
A SKIRTOR class that composes the polar dust itself (CIGALE renormalises disc, dust and
grey body together and re-emits the angle-averaged absorption, NOTE_TORUS_contract)
defines nuclear_parts(theta, ctx, polar) returning the same keys; it is used as is.
Source code in ceridwen/agn/hook.py
__call__ ¶
(agn_continuum_rest (n_wave,) float64, agn_absorbed_lum scalar).
dust_emission: the CSP's DustEmission (needed when energy_balance);
dust_theta: its (qpah, umin, gamma) values; formed_mass: the formed mass of the
SFH in the units of ctx (sum of the SSP weights), which the AGN line luminosities
(per M_formed) are multiplied by before their absorbed part joins the balance.
Source code in ceridwen/agn/hook.py
line_dust_transmission ¶
(n_lines,) dust transmission of the AGN lines, or None. "corrected": the galaxy's
diffuse curve at each line (the narrow-line region lies outside the nuclear dust4
screen, so only the galaxy's diffuse dust acts on it). "fsps" / "prospector":
None, Prospector's AGNSpecModel attenuates its AGN lines by nothing.
Source code in ceridwen/agn/hook.py
line_set_transmission ¶
(n_lines,) float64 transmission of line set key ("nlr" / "blr") at its lines, or
None (no attenuation). theta: the filled AGN theta. The NLR keeps
line_dust_transmission (the a42 path is unchanged); the BLR sees the nuclear screen
(polar dust, or the dust4 power law) and, in "corrected", the galaxy's diffuse curve.
Source code in ceridwen/agn/hook.py
blr_absorbed ¶
Broad-line light the GALAXY's dust absorbs (joins DL07): L x T_nuc x (1 - T_gal) at each line ("corrected"; 0 otherwise). What the nuclear screen removes is not galaxy dust and is not re-emitted (the polar re-emission is fed by the disc only).
Source code in ceridwen/agn/hook.py
dust_response ¶
(mdust, tduste) of DL07 for an absorbed luminosity of exactly 1 L_sun (per
M_formed): the CSP's own compute_dust_emission on a one-pixel unit input.
Source code in ceridwen/agn/hook.py
Broadening¶
ceridwen.broadening.Kinematics
dataclass
¶
Galaxy velocity dispersions [km/s]; set once on the model, shared by all observations.
sigma_gal : float (fixed) or str (theta key of a free parameter). No default here; SedModel defaults to DEFAULT_KINEMATICS (300 km/s, stars and gas). sigma_gas : float, str, or TIED (= sigma_gal). sigma_max : largest value the compiled kernels support; free values are clipped to it.
validate_theta ¶
Free keys are in theta (a dict or a set of names); a bounded prior on a
free key stays within sigma_max; fixed widths are not also in theta.
Source code in ceridwen/broadening.py
resolve ¶
(sigma_gal, sigma_gas) as JAX scalars; branching on Python types only.
Source code in ceridwen/broadening.py
ceridwen.broadening.Instrument
dataclass
¶
Line-spread function of a spectrograph; unit and convention are in the constructor name.
Instrument.R_fwhm(2700) R = lambda/FWHM (datasheet)
Instrument.R_sigma(6358) R = lambda/sigma (same LSF as R_fwhm(2700))
Instrument.fwhm_aa(2.5) FWHM [A], observed frame
Instrument.sigma_aa(1.06) sigma [A], observed frame
Instrument.sigma_kms(47.0) sigma [km/s]
Instrument.fwhm_kms(111.0) FWHM [km/s]
Instrument.<any>(array, wave=obs_wave) per-pixel value on observed wavelengths
LSF scale (every constructor takes scale= and scale_range=): the instrumental
dispersion in force is s * sigma_inst(lambda), in the continuum kernel
(sigma_cont^2 = sigma_gal^2 + s^2 sigma_inst^2 - sigma_lib^2) and in the line width
(sigma_line^2 = sigma_gas^2 + s^2 sigma_inst^2) alike.
scale=1.0 (default) the nominal LSF; the code path is the one without a scale
scale=1.1 (float > 0) fixed: identical to building the Instrument with the width x 1.1
(folded into the static response at setup, no runtime cost)
scale="lsf_scale" sampled theta key (give it a prior and a free_param_init); the
continuum response weights are recomputed per call from the
static band geometry, exactly, for any wavelength dependence of
sigma_inst; values are clipped to the supported range
scale_range=(lo, hi) the range the compiled kernel supports for a sampled scale,
0 < lo < hi; default: the finite bounds of the key's prior.
Needed when the key is a transform.
Prospector's resolution_jitter_parameter (prospect/models/sedmodel.py:289-295,
a78d153) multiplies obs.resolution by the parameter too, but differs: (1) it rescales
the continuum only: the line widths are cached from the unscaled obs.resolution just
before (cache_eline_parameters, sedmodel.py:283, 575-583), so a jittered LSF broadens
the absorption features but not the emission lines; here both. (2) It overwrites
obs.padded_resolution in place on every call (state that outlives the call); here the
Instrument is immutable and the scale is a pure function argument (jit / vmap / grad).
(3) No validation: a value <= 0, or one that takes the instrument below the library,
fails an assert inside the likelihood call (observation.py:454); here a
non-positive scale, an unbounded or non-positive prior, or a prior beyond scale_range
raises at construction, and instrument-below-library pixels follow the usual rule (the
continuum stays at library resolution there, with the setup warning evaluated at the
lower end of the range).
sigma_kms_at ¶
sigma [km/s] at each observed wavelength (NumPy, setup only): the width in force
for a fixed scale (nominal x scale), the nominal width (scale 1) for a sampled
one, which the projector multiplies by theta[scale] per call.
Source code in ceridwen/broadening.py
ceridwen.broadening.DEFAULT_KINEMATICS
module-attribute
¶
ceridwen.broadening.SpectralProjector
dataclass
¶
SpectralProjector(
kinematics,
instrument,
subtract_library,
window,
J,
W,
paint,
line_idx,
sigma_inst_kms,
sigma_lib_kms,
sigma_fix_kms,
zred_range=None,
opz_ref=1.0,
wave_obs=None,
line_wave_rest=None,
line_sigma_table_kms=None,
inst_scale_key=None,
inst_scale_range=None,
scaled=None,
line_window=None,
)
Built once per Spectrum by setup_for_model; predict() is the per-likelihood call.
With zred_range the projector serves a sampled redshift: the log grid is the one of
the reference redshift extended at the same dv to cover every z in the range (so at
opz_ref it reproduces the fixed-z projector), the response is built at opz_ref and the model
is read at wave_log * opz_ref / opz per call (the sigma_gal kernel commutes with
the shift); the lines are painted at line_wave_rest * opz. The library width in
the fixed kernel is the one at opz_ref.
With a sampled instrument scale (Instrument(scale="<key>"), inst_scale_key) the
continuum weights come from scaled (a :class:ScaledResponse, band sized for the top
of inst_scale_range) per call, the lines are painted with s * sigma_inst, and
sigma_inst_kms / line_sigma_table_kms hold the NOMINAL (s = 1) widths; W and
sigma_fix_kms are then the values at the reference scale (1 clipped into the range).
A fixed scale is folded into sigma_inst_kms by Instrument.sigma_kms_at.
inst_scale ¶
The sampled LSF scale from theta clipped to inst_scale_range (a JAX
scalar), or None when the scale is fixed (the static response is used).
Source code in ceridwen/broadening.py
enable_line_windows ¶
Opt in to the windowed line basis in :meth:predict_with_line_basis (off by default:
on CPU it measured slower than the dense one; it targets GPUs). Each line profile is
then evaluated on a static window of +-40 of its largest sigma only; the values are
bitwise those of the dense :meth:line_basis (gradients agree to 1-2 ulp: the reverse
pass sums over the window): the bounds are Kinematics.sigma_max for a sampled
sigma_gas (Kinematics.resolve clips to it), the top of inst_scale_range and the
line centres over zred_range. A sampled redshift outside zred_range (beyond the
projector's support) truncates the lines; eline_delta_zred in theta always takes the
dense path. Call before the first trace: the setting is read when jit traces; a rebuilt
projector (SedModel.setup_observations, fitSED(observations=...)) starts with it
off again. Sets and returns line_window ((start, width), or None when a window would
cover the whole spectrum).
Source code in ceridwen/broadening.py
build
classmethod
¶
build(
kinematics,
instrument,
wave_model,
wave_obs,
zred,
lib_sigma_kms=None,
line_wave_rest=None,
subtract_library=True,
zred_range=None,
inst_scale_range=None,
)
wave_model rest-frame model grid [A]
wave_obs observed pixel centres [A]
zred fixed redshift, or the reference redshift inside zred_range
lib_sigma_kms SSPData.ssp_resolution on wave_model, NaN = unknown (or None)
line_wave_rest rest wavelengths of all model lines, in predict_line_fluxes order (or None)
zred_range (z_min, z_max) of a SAMPLED redshift (None: fixed at zred)
inst_scale_range (lo, hi) of a SAMPLED instrument scale when the Instrument carries no
scale_range (SedModel passes the prior bounds); the kernel band
and window margins are sized for hi
Source code in ceridwen/broadening.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 | |
continuum ¶
Continuum on the observed pixels; opz = 1 + z (traced) when free_z,
inst_scale (traced) when the instrument scale is sampled. transmission: a
callable T(rest wavelengths) (the IGM) applied after the sigma_gal kernel and before
the instrument, on the log grid; spec_rest is then the spectrum before the IGM.
Source code in ceridwen/broadening.py
line_basis ¶
(n_pix, n_kept) f_nu of UNIT-flux lines on the observed pixels, centred at
line_wave_rest * opz_line (traced), width sqrt(sigma_gas^2 + sigma_inst^2) with the
instrument width interpolated at the line (times inst_scale when given); the
painter's profile, one column per line.
Source code in ceridwen/broadening.py
predict_with_line_basis ¶
predict_with_line_basis(
spec_rest,
line_flux_obs_all,
theta,
fit_pos=None,
basis=None,
transmission=None,
)
(prediction, A): continuum plus the lines of line_flux_obs_all painted with
:meth:line_basis at (1 + zred + eline_delta_zred) (theta key, default 0), and the
unit-flux columns A (n_pix, len(fit_pos)) of the kept lines at positions fit_pos
(None when fit_pos is None).
Source code in ceridwen/broadening.py
has_agn_lines ¶
True when the painter of AGN line set key has been built.
setup_agn_lines ¶
setup_agn_lines(
agn_line_wave_rest,
*,
mode,
sf_line_wave_rest=None,
agn_sf_rows=None,
pixel_mask=None,
key="nlr"
)
Build the AGN-line painter for this projector (setup time, NumPy).
key: the line set ("nlr", the default, is stored where it always was; any other
set, e.g. "blr", only with mode="corrected", the nebular painter's profile with the
set's own width).
mode "corrected": the nebular painter's profile (Gaussian in ln lambda, unit area,
width sqrt(agn_eline_sigma^2 + sigma_inst^2) with the instrument at the line, times the
sampled instrument scale). "prospector" / "fsps": Prospector's AGNSpecModel painter
(:func:make_agn_line_painter_prospector), which needs every nebular line
(sf_line_wave_rest, rest A), the nebular row of each AGN line (agn_sf_rows) and
the Spectrum's pixel_mask.
Source code in ceridwen/broadening.py
agn_lines ¶
f_nu of the AGN lines on the observed pixels (add to :meth:predict):
line_flux_obs (n_agn,) observed integrated fluxes, sigma_agn_kms the set's width
(agn_eline_sigma, blr_sigma); centres at rest x (1 + zred +
eline_delta_zred). key: the line set (see :meth:setup_agn_lines).
Source code in ceridwen/broadening.py
ceridwen.broadening.PhotometricBroadener
dataclass
¶
sigma_gal broadening of spec_rest over the rest range the filters cover; pixels outside pass through.
Observations¶
ceridwen.observation.Photometry ¶
Bases: Observation
Broadband photometric observation; flux and uncertainty in AB maggies (1 maggie = 3631 Jy).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filters
|
list of str or Filter -- names are looked up in ``filter_directory`` when it is given,
|
otherwise in |
[]
|
filter_directory
|
str or path, optional -- directory of ``<name>.par`` files; only it is searched
|
|
None
|
upper_limit
|
bool array (n_filters,) -- True = one-sided (model > data only) chi-squared penalty
|
|
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
flux |
array (n_filters,), maggies (keyword argument)
|
|
uncertainty |
array (n_filters,), maggies -- 1-sigma (keyword argument)
|
|
mask |
bool array (n_filters,) -- True = used in the fit (keyword argument)
|
|
Source code in ceridwen/observation/photometry.py
model_support
property
¶
(lo, hi): the model-grid indices predict reads at the fixed redshift of
setup_for_model (the non-zero columns of _T, joined with the sigma_gal
broadener's window when there is one); None before setup. A Photometry projected at
a sampled redshift reads the whole grid (CSPBasis._support_for checks free_z).
set_filters ¶
Set the filter list from filter-name strings or Filter objects (read from
self.filter_directory when set).
Source code in ceridwen/observation/photometry.py
get_maggies ¶
Synthetic maggies, shape (n_filters,), of an F_nu spectrum on model_wave [Å]
(reference path; normalisation follows the input flux units).
Source code in ceridwen/observation/photometry.py
setup_for_model ¶
Precompute the (n_filters, n_wave) float32 projection matrix _T (F_nu -> maggies)
for the rest-frame grid wave_model [Å] observed at fixed zred; required before predict.
Source code in ceridwen/observation/photometry.py
setup_broadening ¶
Build the sigma_gal broadener over the rest range the filters cover (the
whole 912-25000 A window when free_z; None for Kinematics.none() or no
kinematics) and, when neb is given, the line term _line_photometry
(observation.line_photometry.LinePhotometry): each nebular line's flux through
each filter, without painting it, as a delta line without kinematics
(broaden_photometry=False) and as a Gaussian of the gas width with it. Call after
setup_for_model.
Source code in ceridwen/observation/photometry.py
predict ¶
Synthetic AB maggies, shape (n_filters,), as _T @ spectrum (F_nu on wave_model).
Source code in ceridwen/observation/photometry.py
predict_at_redshift ¶
Observer-frame AB maggies, shape (n_filters,), for a traced zred: spectrum_fnu_observed
must already be observer-frame F_nu (flux factor and IGM applied) on the rest-frame grid wave_rest [Å].
Source code in ceridwen/observation/photometry.py
chi_sq ¶
Chi-squared (float) over unmasked bands; upper-limit bands are penalised only when model > data.
Source code in ceridwen/observation/photometry.py
residuals ¶
Per-filter (data - model) / sigma, shape (n_filters,); masked bands NaN, upper-limit bands 0 when model < data.
Source code in ceridwen/observation/photometry.py
ceridwen.observation.Spectrum ¶
Spectrum(
wavelength=None,
flux=None,
uncertainty=None,
mask=slice(None),
noise=None,
name=None,
instrument=None,
subtract_library=True,
calibration=None,
logify_spectrum=False,
sky=None,
noise_floor=0.0,
zred_range=None,
marginalize_elines=False,
eline_prior_width=0.0,
elines_to_fit=None,
elines_to_fix=None,
elines_to_ignore=None,
polynomial_order=0,
polynomial_regularization=0.0,
polynomial_mode="profile",
polynomial_prior_sigma=None,
**kwargs
)
Bases: Observation
Spectroscopic observation on an observed-frame pixel grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wavelength
|
array-like (n_pix,), Å, vacuum, OBSERVED frame.
|
|
None
|
flux
|
array-like (n_pix,) -- same units as the model spectra
|
passed to |
None
|
uncertainty
|
array-like (n_pix,) -- same units as the model spectra
|
passed to |
None
|
mask
|
array-like of bool or slice -- True for pixels that are USED.
|
|
slice(None)
|
instrument
|
Instrument or None -- the spectrograph LSF; unit and convention
|
are the constructor name ( |
None
|
subtract_library
|
bool -- remove the SSP library resolution in quadrature
|
from the instrument width (default True; needs the grid's resolution curve). |
True
|
calibration
|
array-like (n_pix,) -- multiplicative model correction
|
(model * calibration ~ data), applied in chi_sq/residuals/log_likelihood. |
None
|
logify_spectrum
|
bool -- residuals in log-flux space.
|
|
False
|
sky
|
array-like (n_pix,) -- subtracted from data in chi_sq/residuals/
|
log_likelihood only (not in |
None
|
noise_floor
|
float -- fractional floor: sigma_eff^2 = sigma^2 + (floor*|model|)^2.
|
|
0.0
|
noise
|
GaussianProcess -- squared-exponential GP on the whitened residuals with FIXED
|
hyperparameters, used by |
None
|
zred_range
|
(z_min, z_max) -- support of a SAMPLED redshift; otherwise taken from
|
the finite bounds of the model's |
None
|
marginalize_elines
|
bool -- marginalise analytically over the fluxes of the nebular
|
lines in this spectrum (jointly with the model's Photometry and Lines), instead of
fixing them at the CLOUDY prediction; needs an |
False
|
eline_prior_width
|
float -- 0 (default): flat prior on each fitted line flux;
|
|
0.0
|
elines_to_fit
|
sequences of FSPS line names
|
( |
None
|
elines_to_fix
|
sequences of FSPS line names
|
( |
None
|
elines_to_ignore
|
sequences of FSPS line names
|
( |
None
|
polynomial_order
|
int -- 0 (default): no profiled calibration. M > 0: the likelihood
|
multiplies the model by |
0
|
polynomial_regularization
|
float or array (M+1,) -- ridge term reg_m^2 c_m^2 (default 0);
|
profile mode only. |
0.0
|
polynomial_mode
|
"profile" (default) or "marginalize" -- how the polynomial of
|
|
'profile'
|
polynomial_prior_sigma
|
float or array (M+1,) -- the prior widths s (finite, >= 0; 0 pins
|
a coefficient at 0); required with |
None
|
Notes
The galaxy's velocity dispersions are not a property of the observation:
they are set once on the model (SedModel(kinematics=Kinematics(...))).
Source code in ceridwen/observation/spectrum.py
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 | |
model_support
property
¶
(lo, hi): the model-grid indices the projector reads (its log-grid window, which
for a sampled redshift covers the whole zred_range); None before setup.
setup_for_model ¶
setup_for_model(
wave_model,
zred=0.0,
kinematics=None,
lib_resolution=None,
line_wave_rest=None,
zred_range=None,
inst_scale_range=None,
)
Build the projector from the rest-frame model grid wave_model [Å]
redshifted by (1 + zred) onto self.wavelength; call once, outside JIT.
kinematics : Kinematics -- galaxy widths (None = Kinematics.none())
lib_resolution : (wave_rest [Å], sigma_v [km/s]) -- SSP library
resolution curve on wave_model (NaN = unknown); used when
subtract_library and an instrument are set
line_wave_rest : (n_lines,) rest wavelengths of the nebular grid lines
in predict_line_fluxes order, or None (no lines painted)
zred_range : (z_min, z_max) -- for a SAMPLED redshift (default self.zred_range):
the projection is then read at theta['zred'] on every call and zred
is the reference redshift inside the range
inst_scale_range : (lo, hi) -- for an Instrument with a SAMPLED scale
(Instrument(..., scale="<key>")) and no scale_range of its own: the
range the kernel must support (SedModel passes the key's prior bounds)
Source code in ceridwen/observation/spectrum.py
predict ¶
Model F_nu on the observed pixels (n_pix,): the rest-frame CONTINUUM
spectrum (n_wave,) broadened by sigma_gal, the instrument LSF (library
width removed) and resampled, plus the emission lines painted from their
observed-frame integrated fluxes line_flux (all grid lines, or None)
with sigma_gas + instrument. theta supplies the free widths and, for a
projector built with zred_range, the redshift. transmission (a callable of the
rest wavelength, the IGM): applied after the galaxy's sigma_gal and before the
instrument; spectrum is then the continuum before the IGM.
Source code in ceridwen/observation/spectrum.py
synthetic_photometry ¶
Synthetic maggies (n_filters,) of this F_nu spectrum through
filterset; None if there is no data.
Source code in ceridwen/observation/spectrum.py
mask_wavelength_range ¶
Mask pixels with wavelength in [wave_min, wave_max] Å (inclusive).
Source code in ceridwen/observation/spectrum.py
mask_lines ¶
Mask +/- dv km/s around each rest-frame line wavelength [Å],
redshifted by (1 + zred) onto the observed grid. Pass zred (the source
redshift; 0.0 for rest-frame data): without it the rest wavelengths are masked on the
observed grid, with a warning.
Source code in ceridwen/observation/spectrum.py
chi_sq ¶
Sum of squared normalised residuals over unmasked pixels for
model_flux (n_pix,) on the observed grid: the DIAGONAL chi^2 (sigma_eff with the
noise floor only), without the GP of self.noise even when one is set.
Source code in ceridwen/observation/spectrum.py
residuals ¶
Per-pixel normalised residuals (n_pix,); masked pixels are NaN.
log_likelihood ¶
Gaussian log-likelihood of model_flux (n_pix,), including the
sigma_eff normalisation; with self.noise a GaussianProcess it is the full GP
likelihood (the value fitSED's GPGaussianLikelihood gives for the same fixed
hyperparameters and noise_floor), otherwise the diagonal one. Host-side floats,
for use after a fit; the samplers use the compiled likelihood.
Source code in ceridwen/observation/spectrum.py
fit_polynomial_calibration ¶
Weighted least-squares Chebyshev calibration P(lambda) with data ~ P * model_flux over unmasked pixels; returns (coeffs (order+1,), P * model_flux (n_pix,)).
Source code in ceridwen/observation/spectrum.py
ceridwen.observation.Lines ¶
Lines(
line_ind,
line_names=None,
wavelength=None,
name=None,
upper_limit=None,
components=None,
sigma_v=200.0,
**kwargs
)
Bases: Observation
Observed emission-line fluxes with line indices, rest wavelengths and uncertainties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line_ind
|
array-like of int -- indices of the observed lines in the SPS emission-line array
|
|
required |
line_names
|
list of str, optional -- one name per line; needed by ``mask_by_name`` / ``select_by_name``
|
|
None
|
wavelength
|
array-like of float, vacuum rest-frame Angstrom
|
|
None
|
components
|
list of sequences of float, optional -- per observed line, the vacuum rest wavelengths
|
[Angstrom] of all grid lines summed into that measurement (unresolved doublets); default one per line |
None
|
upper_limit
|
array-like of bool, optional -- True treats the line as a non-detection: chi^2 penalises
|
only model > data |
None
|
sigma_v
|
float, km/s -- Gaussian aperture width of ``predict`` (integration of a painted
|
spectrum); |
200.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
flux, uncertainty |
array-like of float, same units as the model prediction (typically
|
erg/s/cm^2) (keyword arguments) |
Source code in ceridwen/observation/lines.py
to_json ¶
Base JSON plus line_names and line_components.
agn_line_matrix ¶
(n_lines, n_agn) float64 NumPy 0/1 matrix: row k sums the AGN lines
(ceridwen.agn.lines.AGNLines) that observed line k holds, every component of a
blend included. Matched BY NAME: each component wavelength is resolved to the nearest line
of FSPS's list within 1 A (ValueError otherwise) and that name is looked up among the AGN
lines (AGNLines.rows_for); a line that is not an AGN line gets a zero row. Cached on the
observation (NumPy, so a first use inside a jit trace never caches a tracer), one entry per
line set (AGN2: the NLR and the BLR each have their own).
Source code in ceridwen/observation/lines.py
setup_for_model ¶
Record the model wavelength grid [Angstrom, rest, increasing], aperture sigma_v [km/s]
and redshift used to build the _W aperture matrix; must precede predict.
Source code in ceridwen/observation/lines.py
predict ¶
Return _W @ spectrum: Gaussian-aperture line fluxes, shape (n_lines,), from an F_nu
model spectrum; wave_model is unused, setup_for_model must have been called.
Source code in ceridwen/observation/lines.py
chi_sq ¶
Return chi^2 over unmasked lines; upper-limit lines are penalised only when model > data.
Source code in ceridwen/observation/lines.py
residuals ¶
Return per-line (data - model) / sigma, shape (n_lines,); masked lines NaN,
upper-limit lines with model <= data set to 0.
Source code in ceridwen/observation/lines.py
mask_by_name ¶
Set mask = False for lines whose name is in names; no-op without line_names.
Source code in ceridwen/observation/lines.py
select_by_name ¶
Return a new Lines containing only the named lines (KeyError on an unknown name).
Source code in ceridwen/observation/lines.py
Model¶
ceridwen.model.SedModel ¶
SedModel(
csp,
observations,
priors=None,
transforms=None,
free_param_init=None,
zred=0.0,
cosmo=None,
lumdist_mpc=None,
kinematics=None,
broaden_photometry=True,
)
Parameter manager and prediction layer: predict(theta) returns a dict keyed
by observation name, log_prob(theta) the summed log-prior on free parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
priors
|
dict[str, Prior] -- free-parameter name -> prior; absent names get a flat improper prior
|
|
None
|
transforms
|
dict[str, callable] -- derived CSP parameter name -> ``fn(free_theta)``; derived names leave the free set
|
|
None
|
free_param_init
|
dict[str, Array] -- initial values of the free parameters replacing derived ones
|
|
None
|
zred
|
float -- fixed redshift; zred = 0 without ``lumdist_mpc`` applies NO flux factor, so predictions
|
are L_sun/Hz x 10^logmass, not maggies |
0.0
|
cosmo
|
|
None
|
|
lumdist_mpc
|
float, Mpc -- explicit luminosity distance replacing D_L(zred) in the flux factor
|
|
None
|
kinematics
|
Kinematics -- the galaxy's stellar / gas velocity dispersions [km/s], fixed
|
(float) or sampled (theta key); default |
None
|
broaden_photometry
|
bool -- apply the kinematic broadening to the spectrum entering the
|
filters (default True; below 5e-4 mag for broad bands, per cent for a narrow band on a line) |
True
|
Source code in ceridwen/model/model.py
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 | |
setup_observations ¶
Build every observation's projection for this model's grid, redshift and
kinematics (called by __init__ and by fitSED when it replaces the
observations); drops the cached jitted predictors.
Source code in ceridwen/model/model.py
apply_transforms ¶
Return free_theta plus every derived parameter fn(free_theta).
Source code in ceridwen/model/model.py
predict ¶
Predictions keyed by observation name from the free-parameter dict. A fixed zred/lumdist_mpc is injected into the CSP theta here; without a 'zred' the CSP applies no flux factor and the outputs are not maggies.
Source code in ceridwen/model/model.py
predict_with_elines ¶
(predictions, aux) for the emission-line marginalisation: the predictions with
the fitted lines removed, and aux = {"prior_mean", "cols"} (their CLOUDY fluxes and
the per-observation design columns). Needs a Spectrum with marginalize_elines=True.
Source code in ceridwen/model/model.py
predict_jit ¶
predict_vmap ¶
Vectorised :meth:predict over a leading batch axis of every theta entry.
ln_prior ¶
Scalar sum of prior.logpdf(theta[p]) over registered priors.
Source code in ceridwen/model/model.py
log_prob ¶
summary ¶
Multi-line summary of parameters, transforms, observations and CSP setup.
Source code in ceridwen/model/model.py
latex ¶
A LaTeX table (booktabs) of the model: every free parameter with its prior, every
derived parameter with the transform and free parameters it is computed from, every
fixed parameter (a constant transform) with its value, and (settings) the fixed
model settings: SSP grid and IMF, SFH grid, dust laws, redshift, kinematics, the
observations, cosmology. table=False returns the tabular alone. Needs
\usepackage{booktabs} and amsmath.
Source code in ceridwen/model/model.py
display ¶
display(
ax=None,
figsize=None,
return_fig=False,
*,
predictive=True,
n_draws=64,
seed=0,
title=None
)
Draw the model: free parameters with their prior densities, the derived and fixed
parameters, the forward model's stages in the order they are applied, and the
observations; an edge joins each parameter to the transform or stage that reads it
(a transform's inputs are traced from its code). Below, predictive adds the 68 and
95 per cent range of n_draws prior draws pushed through the model, with the data
(it compiles the model once). With ax only the diagram is drawn, into it.
The figure uses smplotlib's Hershey fonts when smplotlib is installed (pip install
smplotlib; it is not imported, so other figures keep their style) and a serif face
otherwise. Returns (fig, ax) when return_fig.
Source code in ceridwen/model/model.py
ceridwen.model.transforms.logsfr_ratios_to_sfh ¶
Unit-mass SFH from logsfr_ratios[i] = log10(SFR[i]/SFR[i+1]), index 0 = today.
The length of sfh_times_yr (the lookback NODES in yr, e.g. csp.sfh_times) decides
what the SFR values are:
len(sfh_times_yr) == len(logsfr_ratios) + 2: one SFR per BIN, shape (n_time-1,), forsfh_interp="step". Normalised so sum_i SFR_i * dt_i = 1 Msun: withlogmassthe mass formed in bin i is 10**logmass * SFR_i * dt_i, which is Prospector's continuity SFH (prospect.models.transforms.logsfr_ratios_to_masses: ratios of adjacent BIN SFRs).len(sfh_times_yr) == len(logsfr_ratios) + 1: one SFR per NODE, shape (n_time,), forsfh_interp="linear"(FSPS's tabular SFH, linear between nodes); the trapezoidal integral is normalised to 1 Msun.
Without sfh_times_yr, sum(sfh) = 1.
Source code in ceridwen/model/transforms.py
Priors¶
ceridwen.priors ¶
Prior distributions for CERIDWEN models.
A clean, discoverable import path for the priors (implemented in
ceridwen.sampler.priors)::
from ceridwen.priors import Uniform, Normal, ClippedNormal, LogNormal, LogUniform, StudentT
Each prior exposes logpdf (also __call__), sample, unit_transform
(inverse CDF) and inverse_unit_transform (CDF); bounds gives the support.
Prior
dataclass
¶
Bases: ABC
Prior base class delegating to a TFP-JAX distribution; subclasses define
prior_params and implement tfp_dist().
Source code in ceridwen/sampler/priors.py
Uniform
dataclass
¶
Bases: Prior
Uniform distribution on [low, high].
Source code in ceridwen/sampler/priors.py
TopHat
dataclass
¶
Bases: Uniform
Alias of Uniform kept for backwards compatibility.
Source code in ceridwen/sampler/priors.py
Normal
dataclass
¶
Bases: Prior
Gaussian prior with parameters mean, sigma.
Source code in ceridwen/sampler/priors.py
MultivariateNormalPrior
dataclass
¶
Bases: Prior
Multivariate Gaussian prior.
Keyword arguments: mean (d,) and Sigma (d, d), the covariance matrix.
Source code in ceridwen/sampler/priors.py
ClippedNormal
dataclass
¶
Bases: Prior
Gaussian prior truncated to [low, high]; parameters mean, sigma, low, high.
Source code in ceridwen/sampler/priors.py
LogNormal
dataclass
¶
Bases: Prior
Log-normal prior; mode and sigma are the mean and std of ln(x).
Source code in ceridwen/sampler/priors.py
LogUniform ¶
Bases: Prior
Log-uniform (reciprocal, Jeffreys) prior on [mini, maxi], 0 < mini < maxi < inf.
pdf 1 / (x ln(maxi/mini)) on [mini, maxi] (-inf log-density outside),
CDF ln(x/mini) / ln(maxi/mini): uniform in log x, whatever the base.
Same parameter names and distribution as Prospector's LogUniform(mini, maxi)
(scipy.stats.reciprocal(mini, maxi)). The parameter itself (not its log) is
sampled; fitSED's NUTS path maps it to (mini, maxi) with a logit.
logpdf/cdf/ppf/sample are analytic jnp (exact, in the working float dtype,
jit/grad/vmap-safe); tfp_dist() gives the equivalent TFP distribution
(Exp of a Uniform(ln mini, ln maxi)) for interoperability.
Source code in ceridwen/sampler/priors.py
StudentT
dataclass
¶
Bases: Prior
Student's t prior with parameters mean, scale, df (degrees of freedom).
Source code in ceridwen/sampler/priors.py
Likelihood¶
ceridwen.likelihood.DiagonalGaussianLikelihood
dataclass
¶
Bases: LikelihoodBase
Gaussian log-likelihood with an independent (diagonal) noise model; with
noise_model.f_outlier set, the outlier mixture :func:lnlike_diag_outlier.
__call__ ¶
Return (lnl_total, LikelihoodOutput).
Source code in ceridwen/likelihood/likelihood.py
outlier_probability ¶
Per-datum probability of being an outlier (see :func:outlier_probability);
raises when the mixture is off.
Source code in ceridwen/likelihood/likelihood.py
make_lnprobfn ¶
Return a jitted log-posterior for one observation (needs .flux, .uncertainty,
.mask; honours sky and calibration as MultiObservationLikelihood does, and
refuses flagged upper limits).
Source code in ceridwen/likelihood/likelihood.py
ceridwen.likelihood.DiagonalGaussianLikelihoodWithUpperLimits
dataclass
¶
DiagonalGaussianLikelihoodWithUpperLimits(
noise_model=DiagonalNoiseModel(), poly_calibration=None
)
Bases: LikelihoodBase
Diagonal Gaussian log-likelihood honouring per-datum upper-limit flags
(one-sided penalty; reduces to :class:DiagonalGaussianLikelihood when no flags are set).
With noise_model.f_outlier set, the detections use the outlier mixture and the limits
keep the one-sided penalty (:func:lnlike_diag_outlier_with_upper_limits).
__call__ ¶
Return (lnl_total, LikelihoodOutput); is_upper_limit=None means all detections.
Source code in ceridwen/likelihood/likelihood.py
make_lnprobfn ¶
Return a jitted log-posterior using observations.upper_limit (all-False if absent);
honours sky and calibration as MultiObservationLikelihood does.
Source code in ceridwen/likelihood/likelihood.py
ceridwen.likelihood.MultiObservationLikelihood
dataclass
¶
Bases: LikelihoodBase
Sum of independent likelihoods over several observation keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
tuple of str -- observation keys, e.g. ``("phot", "spec", "lines")``
|
|
tuple()
|
likelihoods
|
tuple of LikelihoodBase -- one per key, same order
|
|
tuple()
|
__call__ ¶
Return (lnl_total, {key: LikelihoodOutput}); all inputs are dicts keyed like self.keys
(is_upper_limit only needs the keys whose likelihood honours upper limits).
Source code in ceridwen/likelihood/likelihood.py
make_lnprobfn ¶
Return a jitted log-posterior; observations and model.predict(theta) are dicts keyed
like self.keys. Each observation's sky, calibration and upper_limit are honoured
as in ceridwen.sampler.runner.run_sampler. In float32 mode the value is offset by
-loglike_offset(...) (a constant of the observations, see :func:float32_rescaling).
Source code in ceridwen/likelihood/likelihood.py
The outlier mixture is disabled by default (f_outlier=None, equivalent to 0).
See Outlier model to enable it.
ceridwen.likelihood.DiagonalNoiseModel
dataclass
¶
DiagonalNoiseModel(
use_jitter=False,
use_fractional=False,
use_data_fractional=False,
noise_floor=0.0,
use_error_scale=False,
f_outlier=None,
nsigma_outlier=50.0,
err_scale_key="log_err_scale",
jitter_key="log_jitter",
f_calib_key="log_f_calib",
f_data_key="log_f_data",
)
Bases: NoiseModelBase
Independent Gaussian noise: sigma_obs^2 (optionally rescaled by a common factor) plus optional (f_calib*|mu|)^2, (f_data*|y|)^2 and jitter^2 terms, nuisance parameters sampled in log space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_error_scale
|
bool -- multiply sigma_obs^2 by exp(params[err_scale_key])^2, a
|
common rescaling of the quoted uncertainties (the log-normalisation term keeps it from running away) |
False
|
use_jitter
|
bool -- add exp(params[jitter_key])^2 (data units)
|
|
False
|
use_fractional
|
bool -- add (exp(params[f_calib_key]) * |mu|)^2, model-anchored
|
|
False
|
use_data_fractional
|
bool -- add (exp(params[f_data_key]) * |y|)^2, data-anchored, needs ``data``
|
|
False
|
noise_floor
|
float -- fixed fractional floor on |mu|
|
|
0.0
|
f_outlier
|
None, float or str -- outlier mixture (Hogg, Bovy & Lang 2010): the fraction
|
of data drawn from a Gaussian |
None
|
nsigma_outlier
|
float or str -- width of the outlier Gaussian in units of sigma_eff,
|
fixed (default 50, Prospector's) or a theta key |
50.0
|
err_scale_key
|
str or float -- where each switched-on
|
term reads its (log) value: a theta key (default |
'log_err_scale'
|
jitter_key
|
str or float -- where each switched-on
|
term reads its (log) value: a theta key (default |
'log_err_scale'
|
f_calib_key
|
str or float -- where each switched-on
|
term reads its (log) value: a theta key (default |
'log_err_scale'
|
f_data_key
|
str or float -- where each switched-on
|
term reads its (log) value: a theta key (default |
'log_err_scale'
|
use_outlier
property
¶
True when the outlier mixture is on (static: it selects the likelihood kernel).
outlier_param_names
property
¶
theta keys of the sampled outlier parameters (empty when fixed or off).
nuisance_param_names
property
¶
Names of nuisance parameters expected in params at compute time.
outlier_params ¶
(f, nsigma) for the mixture kernel: the fixed values, or looked up in params.
Source code in ceridwen/likelihood/noise_model.py
compute ¶
Return NoiseModelOutput; params holds the theta keys err_scale_key /
jitter_key / f_calib_key / f_data_key of the switched-on terms (a float key
is a fixed value), data (observed y) required when use_data_fractional.
Source code in ceridwen/likelihood/noise_model.py
ceridwen.likelihood.lnlike_diag_outlier ¶
Outlier mixture (Hogg, Bovy & Lang 2010), Prospector's NoiseModel.lnlike branch
f_outlier > 0: per datum
lnl_i = logaddexp(log(1 - f) + lnp_good_i, log(f) + lnp_bad_i)
lnp_good_i = -0.5 chi_i^2 - log_det_i
lnp_bad_i = -0.5 chi_i^2 / nsigma^2 - log_det_i - log(nsigma)
with sigma_eff (inv_var, log_det) from the noise model after every term, as
Prospector uses its noise model's Sigma. As f -> 0 it tends to
:func:lnlike_diag_gaussian, NOT to Prospector's f_outlier == 0 value, whose
NoiseModel.lnlikelihood multiplies chi^2 by ln(2 pi) and drops n ln(2 pi).
lnl_pointwise holds the mixture terms (summing to lnl_total); chi and
residuals are those of the inlier Gaussian. Masked data contribute 0 with finite
gradients; the derivative in f is the exact (e^b - e^a)/L, finite at f = 0 unless a
datum sits beyond ~38 sigma (nsigma = 50) (then +inf: the likelihood rises that steeply).
Source code in ceridwen/likelihood/likelihood.py
ceridwen.likelihood.lnlike_diag_outlier_with_upper_limits ¶
:func:lnlike_diag_outlier on the detections and the one-sided penalty of
:func:lnlike_diag_gaussian_with_upper_limits (unchanged, no mixture) on data flagged
is_upper_limit. With no flags it equals :func:lnlike_diag_outlier.
Source code in ceridwen/likelihood/likelihood.py
ceridwen.likelihood.outlier_probability ¶
Per-datum posterior probability of belonging to the outlier component,
exp(log f + lnp_bad_i - lnl_i); 0 for masked data. A diagnostic: the sampled
likelihood never computes it.
Source code in ceridwen/likelihood/likelihood.py
ceridwen.likelihood.poly_calibration.PolynomialCalibration ¶
Static description of the profiled polynomial of one spectrum: the design matrix
A (n_pix, order+1) and the regularisation (scalar or one per coefficient). Hashable
(by value), so it can sit in a likelihood's static pytree data.
Source code in ceridwen/likelihood/poly_calibration.py
for_spectrum
classmethod
¶
From Spectrum(polynomial_order=..., polynomial_regularization=...); None when off
or when the polynomial is marginalised (polynomial_mode="marginalize", see
:class:~ceridwen.likelihood.poly_marginal.PolynomialMarginal).
Source code in ceridwen/likelihood/poly_calibration.py
solve ¶
(coefficients (order+1,), response (n_pix,)) maximising the likelihood; a
column-scaled normal-equation solve, differentiable in mu and inv_var.
Source code in ceridwen/likelihood/poly_calibration.py
calibrate ¶
mu times the profiled response (the noise model's weights at mu).
Source code in ceridwen/likelihood/poly_calibration.py
The spectral GP likelihood is disabled by default. fitSED enables it when you
provide log_gp_amp_spec and log_gp_length_spec, or
Spectrum(noise=GaussianProcess(...)). See GP likelihood.
ceridwen.likelihood.GPGaussianLikelihood ¶
Bases: LikelihoodBase
Gaussian likelihood of one spectrum with a squared-exponential GP on the whitened
residuals (:func:lnlike_gp_gaussian).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
noise_model
|
DiagonalNoiseModel -- gives sigma_eff (err_scale, jitter, f_calib, f_data,
|
noise_floor); its outlier mixture must be off |
None
|
sqdist
|
(n_pix, n_pix) -- :func:`gp_sqdist` of the observed-frame pixel wavelengths
|
|
None
|
log_amp
|
str or float -- ln a and ln l [ln Angstrom]: a theta key (sampled) or
|
a fixed value |
None
|
log_len
|
str or float -- ln a and ln l [ln Angstrom]: a theta key (sampled) or
|
a fixed value |
None
|
eps
|
float -- diagonal jitter (default ``GP_JITTER`` = 1e-6)
|
|
GP_JITTER
|
Source code in ceridwen/likelihood/gp_likelihood.py
gp_param_names
property
¶
theta keys of the sampled GP hyperparameters (empty when both are fixed).
gp_params ¶
(ln a, ln l): the fixed values, or looked up in params.
Source code in ceridwen/likelihood/gp_likelihood.py
__call__ ¶
Return (lnl_total, LikelihoodOutput).
Source code in ceridwen/likelihood/gp_likelihood.py
conditional_mean ¶
:func:gp_conditional_mean at params (data units, every pixel).
Source code in ceridwen/likelihood/gp_likelihood.py
make_lnprobfn ¶
Return a jitted log-posterior for one Spectrum (.flux, .uncertainty,
.mask).
Source code in ceridwen/likelihood/gp_likelihood.py
config ¶
JSON-able GP settings (stored in the result file's likelihood_json).
Source code in ceridwen/likelihood/gp_likelihood.py
ceridwen.likelihood.lnlike_gp_gaussian ¶
Return (lnl_total, LikelihoodOutput) of the GP likelihood (module docstring) for
the noise-model output inv_var = 1/sigma_eff^2 and log_det = ln sqrt(2 pi
sigma_eff^2). residuals and chi are those of :func:lnlike_diag_gaussian;
lnl_pointwise_i = -1/2 z_i^2 - ln L_ii - log_det_i with z = L^-1 r (the
Cholesky-ordered decomposition, summing exactly to lnl_total); masked entries 0.
Source code in ceridwen/likelihood/gp_likelihood.py
ceridwen.likelihood.gp_conditional_mean ¶
Posterior mean of the correlated GP component given the residuals, in DATA units
(sigma_eff * a^2 E K^-1 r), on every pixel (masked ones predicted from the unmasked);
mu + this is the model plus the GP's reading of the correlated residuals. A
diagnostic for plots: the sampled likelihood never computes it.
Source code in ceridwen/likelihood/gp_likelihood.py
ceridwen.observation.GaussianProcess ¶
Squared-exponential GP on normalised spectral residuals, with covariance K = I + a^2 SE(l) + jitter I.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amplitude
|
float, dimensionless -- kernel amplitude in units of the per-pixel sigma.
|
|
required |
length_scale
|
float, Å -- correlation length.
|
|
required |
jitter
|
float -- diagonal added for numerical stability.
|
|
1e-06
|
Source code in ceridwen/observation/gp.py
log_likelihood ¶
Full Gaussian log-likelihood of the normalised residuals under K, including the white-noise identity term and the -n/2 ln(2 pi) constant; do NOT add a separate -1/2 sum r^2 term.
Source code in ceridwen/observation/gp.py
ceridwen.likelihood.poly_marginal.PolyMarginalGaussianLikelihood
dataclass
¶
Bases: LikelihoodBase
Diagonal Gaussian likelihood of a spectrum with its calibration polynomial marginalised
analytically (:func:poly_marginal_loglike). No outlier mixture and no upper limits
(the marginal is exact only for a Gaussian likelihood).
__call__ ¶
Return (lnl_total, LikelihoodOutput) (see :func:poly_marginal_loglike).
Source code in ceridwen/likelihood/poly_marginal.py
conditional ¶
(mean (k,), cov (k, k), response (n,)): the conditional posterior of the
coefficients at the model mu and the response 1 + A mean.
Source code in ceridwen/likelihood/poly_marginal.py
make_lnprobfn ¶
Return a jitted log-posterior for one observation (.flux, .uncertainty, .mask).
Source code in ceridwen/likelihood/poly_marginal.py
ceridwen.likelihood.poly_marginal.PolynomialMarginal ¶
Static description of the marginalised polynomial of one spectrum: the design matrix
A (n_pix, order+1) and the prior widths sigma (order+1,). Hashable (by value), so
it can sit in a likelihood's static pytree data.
Source code in ceridwen/likelihood/poly_marginal.py
for_spectrum
classmethod
¶
From Spectrum(polynomial_mode="marginalize", ...); None otherwise.
Source code in ceridwen/likelihood/poly_marginal.py
ceridwen.likelihood.poly_marginal.poly_marginal_loglike ¶
Marginal ln-likelihood of the spectrum over the calibration coefficients.
y, mu : (n,) data and uncalibrated model; inv_var, log_det : (n,) from the noise model
(1/sigma_eff^2 and 0.5 ln(2 pi sigma_eff^2)); mask : (n,) bool, True = used;
A : (n, k) design; prior_sigma : (k,) prior widths s (>= 0, finite).
Returns (lnl_total, LikelihoodOutput), whose residuals / chi /
lnl_pointwise are those of the conditional-mean calibrated model mu (1 + A c_hat);
lnl_total = sum(lnl_pointwise) - 1/2 c_hat^T Lambda^-1 c_hat - 1/2 ln|P| (the prior and
Occam terms are global, not per pixel). With return_posterior also the conditional
mean (k,) and covariance (k, k) of the coefficients.
Source code in ceridwen/likelihood/poly_marginal.py
ceridwen.model.obs_params.check_names ¶
Validate every name of families in given against observations; return
{valid name: obs}. Raises ValueError for an ambiguous plain name, both spellings for one
observation, or a name that matches no observation.
Source code in ceridwen/model/obs_params.py
Fitting¶
ceridwen.fit.fitSED ¶
fitSED(
model,
observations=None,
output_dir=".",
*,
sampler="nested",
rng_key=None,
sampler_kwargs=None,
vi=None,
vi_kwargs=None,
filename="ceridwen_result.h5",
overwrite=True,
verbose=True,
optimize=False,
optimize_kwargs=None,
mfrac=None
)
Fit model to observations with sampler ("nested" or "nuts") and return the
SamplingResult; writes output_dir/filename (HDF5) and a .log with the same stem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observations
|
list[Observation] -- replaces ``model.observations`` and re-runs ``setup_for_model`` at ``model.zred``
|
|
None
|
sampler_kwargs
|
dict -- forwarded to the sampler adapter constructor. fitSED's nested
|
defaults are num_live=500 and num_inner_steps=30 (the adapter on its own, e.g. via run_sampler, uses 5 x the number of free dimensions); pass num_inner_steps to choose |
None
|
vi
|
None, 'tril', 'iaf', or a VI map -- NUTS-only variational preconditioning
|
|
None
|
vi_kwargs
|
dict -- forwarded to VI training / map constructor
|
|
None
|
optimize
|
bool -- first find the MAP with ``ceridwen.optimize.map_fit`` (L-BFGS from prior
|
draws); NUTS then starts its chains there. Nested sampling draws its live points from
the prior, so there the MAP is only recorded. Stored under |
False
|
optimize_kwargs
|
dict -- forwarded to ``map_fit`` (``n_starts``, ``rng_key``, ...); the
|
default |
None
|
mfrac
|
bool or None -- write ``/derived/mfrac`` (surviving / formed mass of every stored
|
sample, from the grid's surviving-mass table; |
None
|
Notes
Noise terms and the outlier mixture are switched on by the names the model samples (see
_likelihood_for); all outlier fractions default to 0 (off).
Source code in ceridwen/fit.py
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 | |
ceridwen.fit.load_result_h5 ¶
Rebuild a SamplingResult from a result HDF5 file (the forward model itself is not restored).
Source code in ceridwen/fit.py
ceridwen.fit.read_result_h5 ¶
Read a result HDF5 file into a nested dict with keys 'obs', 'model',
'samples', 'provenance', 'config' (precision: float64 / float32,
platform: the JAX backend the fit ran on), 'elines'
(when the fit marginalised the emission lines), 'map' (when it ran with
optimize=True) and 'derived' (read_derived_h5; when fitSED wrote
/derived/mfrac).
Source code in ceridwen/fit.py
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 | |
ceridwen.fit.read_provenance ¶
The /provenance group of a result file (JSON attrs decoded); {} for older files.
Source code in ceridwen/fit.py
ceridwen.fit.convert_result ¶
Convert a result file with absolute log10 Z metallicity to the logzsol convention, writing a NEW file.
ssp_grid is the grid the fit used (SSPData/SSPDataAfe or a path); its shape is
checked against the file, and every absolute metallicity (samples, theta_init, priors) is
shifted by -log10 Z_sun. Returns the new path. The input file is never modified.
Source code in ceridwen/fit.py
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 | |
ceridwen.fit.result_cosmology ¶
The Cosmology a result file was fitted with (/model attrs cosmo_*); KeyError if absent.
Source code in ceridwen/fit.py
ceridwen.resultfile.rebuild_model ¶
SedModel of the fit in path, from a CSP, observations and transforms you supply.
Taken from the file: priors, the free parameters and their theta_init, zred,
lumdist_mpc, kinematics and broaden_photometry. Not recorded, so supplied by you: the
CSP (built as for the fit, with the same grid and cosmology), the observation objects and
the transform callables (the file lists them as derived <- function name; the derived
names must match). Parameters fixed with CSPBasis(fixed=...) (stored as
name <- CSPBasis(fixed=[...])) come from the CSP, which must fix them to the same
values. With check (default) the rebuilt model is compared with the file by
:func:check_model_against_result and any difference raises a ValueError saying which.
Source code in ceridwen/resultfile.py
ceridwen.resultfile.check_model_against_result ¶
Compare model with the model recorded in the result file path.
Every recorded attribute and dataset of /model and /obs is compared exactly
(priors, parameter names and shapes, transform names, zred, kinematics, cosmology, grid
provenance and metallicity axes, the model wavelength grid, and every observation's data,
mask, filters and instrument, and the likelihood settings fitSED records per observation,
likelihood_json). theta_init values, and a record the file predates, are reported
as notes only.
Returns a :class:ResultComparison; with raise_on_difference a difference raises.
Source code in ceridwen/resultfile.py
ceridwen.resultfile.priors_from_result ¶
The prior objects of a result file, {name: Prior}, rebuilt from their serialisation.
Source code in ceridwen/resultfile.py
ceridwen.optimize.map_fit ¶
map_fit(
model,
n_starts=16,
rng_key=None,
*,
include_init=True,
max_steps=3000,
ftol=1e-12,
bounds=None,
lnprob=None
)
Maximise fitSED's log-posterior of model with L-BFGS from many starts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
SedModel -- every free parameter needs a prior (starts are prior draws)
|
|
required |
n_starts
|
int -- number of prior draws to start from (>= 1)
|
|
16
|
rng_key
|
PRNGKey -- draws the starts; default ``PRNGKey(0)``. Same key, same result.
|
|
None
|
include_init
|
bool -- also start from ``model.theta_init`` (as start 0), as Prospector's
|
|
True
|
max_steps
|
L-BFGS stopping rule (see the module docstring)
|
|
3000
|
ftol
|
L-BFGS stopping rule (see the module docstring)
|
|
3000
|
bounds
|
dict -- {name: (low, high)} for the logit map; default ``fit._detect_bounds(model)``
|
|
None
|
lnprob
|
callable -- a prebuilt ``build_lnprob(model)``, to share its compilation
|
|
None
|
Returns:
| Type | Description |
|---|---|
MAPResult -- ``.theta`` is usable as ``free_param_init``
|
|
Source code in ceridwen/optimize.py
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 | |
ceridwen.optimize.MAPResult
dataclass
¶
MAPResult(
theta,
lnp,
lnp_starts,
theta_starts,
n_steps,
grad_norm,
best_start,
wall_time,
bounds=dict(),
settings=dict(),
)
Result of :func:map_fit.
theta : dict -- best theta (constrained), shapes of model.theta_init (NumPy)
lnp : float -- ln posterior at theta
lnp_starts : (n,) -- final ln posterior of every start
theta_starts: dict -- the starting points, {name: (n, *shape)}
n_steps : (n,) -- L-BFGS iterations per start
grad_norm : (n,) -- final |grad| in the unconstrained space, per start
best_start : int -- index of the winning start
wall_time : float -- seconds, compile included
bounds : dict -- the bounds used for the logit map
settings : dict -- n_starts, include_init, max_steps, ftol, rng_key (key data) and
whether a custom lnprob was passed: what reproduces the run
ceridwen.sampler.run_sampler ¶
Build JIT loglike_fn (summed over observations, no prior) and
logprior_fn from model/likelihood and delegate to adapter.run.
theta_init (default model.theta_init) is the start handed to the adapter, e.g. a
MAP from ceridwen.optimize.map_fit; it must have the keys and shapes of
model.theta_init.
Source code in ceridwen/sampler/runner.py
ceridwen.sampler.nested.BlackJAXNestedSamplerAdapter ¶
BlackJAXNestedSamplerAdapter(
priors,
num_live=500,
num_inner_steps=None,
num_delete=None,
logZ_tol=-5.0,
verbose=True,
checkpoint_interval_s=1200.0,
checkpoint_dir=None,
resume_from=None,
slice_kernel="lanes",
)
Bases: SamplerAdapter
Nested-sampling adapter driving the NSS kernel with a Ceridwen SedModel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
priors
|
dict[str, Prior] -- every free parameter needs a proper prior
|
|
required |
num_inner_steps
|
int -- inner MCMC steps per iteration; default n_dims * 5
|
|
None
|
num_delete
|
int -- live points removed per iteration; default max(1, num_live // 5), must be < num_live
|
|
None
|
logZ_tol
|
float -- stop when ln(Z_live / Z) < logZ_tol; default -5
|
|
-5.0
|
checkpoint_interval_s
|
float -- seconds between checkpoints; <= 0 disables
|
|
1200.0
|
checkpoint_dir
|
str -- falls back to $CERIDWEN_CHECKPOINT_DIR, then $CERIDWEN_RESCUE_DIR, else off
|
|
None
|
resume_from
|
str -- a periodic checkpoint (``ns_checkpoint_<pid>.pkl``) to continue from
|
instead of starting afresh. The run continues with the saved live points, dead points and rng key, so it reproduces the uninterrupted run at the same key. The checkpoint must come from the same model: the settings, the parameter shapes and the log-likelihood of the saved live points are checked before sampling resumes. |
None
|
slice_kernel
|
('lanes', 'stock', 'carry')
|
|
"lanes"
|
Source code in ceridwen/sampler/nested.py
load_checkpoint
staticmethod
¶
Load a checkpoint/rescue pickle: {positions, loglikelihood, loglikelihood_birth, logZ, n_dead, partial}.
run ¶
Run nested sampling and return a SamplingResult; logprior_fn must be proper.
Source code in ceridwen/sampler/nested.py
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 | |
ceridwen.sampler.nuts.BlackJAXNUTSAdapter ¶
BlackJAXNUTSAdapter(
num_warmup=None,
num_samples=2000,
num_chains=4,
initial_step_size=None,
target_acceptance=0.95,
max_num_doublings=10,
dense_mass=None,
bounds=None,
vi=None,
vi_kwargs=None,
verbose=True,
)
Bases: SamplerAdapter
NUTS adapter with window adaptation; bounded (uniform-prior) parameters
are sampled in sigmoid/logit space, and an optional VI map (vi) whitens
the target before sampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_warmup
|
int -- adaptation steps per chain; default 1500 (200 with ``vi``)
|
|
None
|
num_samples
|
int -- post-warmup draws per chain
|
|
2000
|
initial_step_size
|
float -- leapfrog step before adaptation; default 0.01 (0.5 with ``vi``)
|
|
None
|
target_acceptance
|
float -- dual-averaging target
|
|
0.95
|
max_num_doublings
|
int -- max tree depth (2**n leapfrog steps)
|
|
10
|
dense_mass
|
bool -- full inverse mass matrix; default True (False with ``vi``)
|
|
None
|
bounds
|
dict -- name -> (low, high) for the logit map; None = no bounded parameters
|
(the adapter never sees the priors; fitSED passes fit._detect_bounds(model)) |
None
|
vi
|
None | 'tril' | 'iaf' | VariationalMap | TrainedMap -- variational preconditioning
|
|
None
|
vi_kwargs
|
dict -- map constructor kwargs plus ``num_steps``, ``batch_size``, ``lr0`` for training
|
|
None
|
Notes
One window_adaptation run is shared by all chains. Without vi every chain starts
from its end state and differs only by its rng key, so the printed split R-hat measures
mixing within that one run: it cannot detect a warmup that settled in one of several
modes. With vi the chains start from independent N(0, 1) draws in the whitened space
(no burn-in). The printed ESS is the sum of the per-chain ESS
(ceridwen.plotting._ess, the estimator of the diagnostic figure).
Source code in ceridwen/sampler/nuts.py
run ¶
Run NUTS (one warmup, then all chains) and return a SamplingResult in constrained space.
Source code in ceridwen/sampler/nuts.py
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 | |
Post-processing¶
ceridwen.postprocess.PostProcess ¶
PostProcess(
model,
result,
*,
n_samples=None,
seed=0,
windows_myr=DEFAULT_WINDOWS_MYR,
sfr=True,
ssfr=True,
uv=True,
ionizing=True,
predictions=True,
derived=None,
batch_size=256,
mfrac=None
)
Posterior post-processing of a fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
SedModel -- the model the samples were drawn with; parameter names must match the result's
|
|
required |
result
|
SamplingResult or path -- sampler output or the HDF5 file it was written to
|
|
required |
n_samples
|
int, optional -- equal-weight draws (default 2000 for weighted results, all for uniform)
|
|
None
|
windows_myr
|
sequence of float, Myr -- averaging windows W for ``sfrW`` / ``ssfrW``
|
|
DEFAULT_WINDOWS_MYR
|
derived
|
dict[str, callable] -- ``name -> f(SpectrumSample) -> float or 1-D array``, evaluated per draw
|
|
None
|
batch_size
|
int -- draws per compiled batch through the forward model
|
|
256
|
mfrac
|
bool or None -- surviving-mass block (``mfrac``, ``mass_surviving``,
|
|
None
|
Source code in ceridwen/postprocess.py
run ¶
Compute and return (and store in self.output) the nested dict of the module docstring.
Source code in ceridwen/postprocess.py
figures ¶
Write the summary, corner and sampling-diagnostic figures
(:mod:ceridwen.plotting) to outdir; returns their paths.
truths ({name: value}) marks injected values in mock tests.
Source code in ceridwen/postprocess.py
save ¶
Write self.output (running first if needed) as a flat .npz with '/'-joined keys.
Source code in ceridwen/postprocess.py
ceridwen.postprocess.SpectrumSample
dataclass
¶
SpectrumSample(
wave_rest,
full,
intrinsic,
dustfree,
theta,
zred,
logmass,
sfr,
lookback_gyr,
cosmo,
)
One posterior draw as handed to a derived function: rest-frame L_nu
[L_sun/Hz] x 10**logmass on wave_rest [A]; theta after the model transforms.
index_of ¶
mean_lnu ¶
Wavelength-averaged L_nu of spectrum over [lo, hi] A (trapezoid).
Source code in ceridwen/postprocess.py
luminosity ¶
int L_nu dnu over [lo, hi] A of spectrum [erg/s].
Source code in ceridwen/postprocess.py
ceridwen.postprocess.load_postprocess ¶
Rebuild the nested dict written by :meth:PostProcess.save.
Source code in ceridwen/postprocess.py
Figures¶
ceridwen.plotting.summary_figure ¶
summary_figure(
out,
model,
*,
title=None,
prior_draws=500,
params=None,
truths=None,
savepath=None,
figsize=(15, 11)
)
Summary page: SED with residuals (photometry and model in the same units, limited to
the observed wavelengths; the full width when there are no emission lines), emission
lines, the SFH (per-bin log10 SFR vs lookback time, posterior 16-84 % and median, prior
16-84 % at the median mass; a linear time axis for a uniform node grid, else log), and
1-D marginals of the fitted parameters (median,
16-84 %, best fit, prior 16-84 %). out is PostProcess.run()'s dict; model
the fitted SedModel; truths ({name: value or array}) marks injected values in
green, and draws the injected SFH when it gives the SFH parameters (e.g. logsfr_ratios).
Source code in ceridwen/plotting.py
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 | |
ceridwen.plotting.corner_figure ¶
Corner plot of all fitted parameters: 1-D marginals on the diagonal, 2-D
histograms with 1 and 2 sigma contours below; posterior median (blue, dashed),
maximum-likelihood sample (red) and, when given, truths (green) marked.
Source code in ceridwen/plotting.py
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 | |
ceridwen.plotting.diagnostic_figure ¶
Sampling diagnostics. Nested sampling: every parameter's dead points in
deletion order coloured by posterior weight, the log-likelihood run and the
cumulative evidence. MCMC: per-chain traces with split-R-hat and ESS (summed over chains;
without vi the NUTS chains share one warmup end state, so the R-hat is within-run
mixing only).
Source code in ceridwen/plotting.py
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 | |
ceridwen.plotting.make_figures ¶
Write summary, corner and diagnostic figures to outdir; returns their paths.
Source code in ceridwen/plotting.py
Dust, nebular, IGM, cosmology¶
ceridwen.dust.Dust ¶
Modular dust attenuation model: one attenuation law per age bin, parameters read from a plain theta dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bin_edges
|
list of (lo, hi), log10(Gyr) -- age range of each bin
|
|
[(-inf, -1.97)]
|
laws
|
list of str -- attenuation-law name per bin (see ``describe_attenuation_laws``)
|
|
['powerlaw']
|
Source code in ceridwen/dust/DustModel.py
ceridwen.dust.DiffuseDust ¶
Bases: Dust
Single-bin dust model covering all ages, with diffuse_-prefixed parameter names.
Source code in ceridwen/dust/DustModel.py
ceridwen.dust.DustEmission.DustEmission ¶
Dust emission templates ('DL07' or 'THEMIS') interpolated onto spec_lambda [Angstrom].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dust_file
|
str -- data root containing dust/dustem/
|
|
None
|
kwargs
|
duste_qpah, duste_umin, duste_gamma defaults
|
|
{}
|
Source code in ceridwen/dust/DustEmission.py
get_default_params ¶
Return dict of default dust-emission fit parameters.
Source code in ceridwen/dust/DustEmission.py
update_dust_params ¶
Set the default dust-emission parameters.
compute_dust_emission ¶
compute_dust_emission(
spec_attn,
spec_dustfree,
spec_lambda,
diffuse_curve,
duste_qpah,
duste_umin,
duste_gamma,
)
Return (spec_attn + dust emission, dust mass, dust emission); diffuse_curve is exp(-tau_diffuse).
Source code in ceridwen/dust/DustEmission.py
ceridwen.neb.NebularModel ¶
NebularModel(
cloudy_dust=False,
sps_home=None,
csp_lambda=None,
ssp_flux=None,
ssp_ages_lgyr=None,
isoc_type="mist",
nebnz=11,
nebnage=10,
nebnip=7,
smooth_velocity=True,
sigma_smooth=0.0,
res_floor_fwhm_px=2.0,
nebular_smooth_init=None,
**removed
)
Nebular continuum and lines from the CLOUDY cubes under <sps_home>/nebular.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cloudy_dust
|
bool -- CLOUDY grids with dust inside the H II region, ``ZAU_WD`` (True), or
|
without, |
False
|
csp_lambda
|
(nspec,) -- model wavelength grid [A].
|
|
None
|
ssp_flux
|
(n_z, n_age, n_wave) -- SSP L_nu [L_sun/Hz]; gives ``log_qq`` (n_z, n_age).
|
|
None
|
ssp_ages_lgyr
|
(n_age,) -- log10(age/yr) of the SSPs; ages inside both cubes are "young".
|
|
None
|
isoc_type
|
str -- ZAU file suffix.
|
|
'mist'
|
nebnz
|
int -- cube dimensions.
|
|
11
|
nebnage
|
int -- cube dimensions.
|
|
11
|
nebnip
|
int -- cube dimensions.
|
|
11
|
smooth_velocity
|
bool -- ``sigma_smooth`` in km/s (True) or A.
|
|
True
|
sigma_smooth
|
float -- intrinsic width of the painted lines (0: pixel floor only).
|
|
0.0
|
res_floor_fwhm_px
|
float -- minimum painted FWHM in local pixels (FSPS: 2 pixels per FWHM,
|
sigma = pixel x 2 / 2.355, |
2.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
nebem_cont |
(nspec, nz, nage, nu) - -log10(L_nu / Q)
|
|
nebem_line |
(nemline, nz, nage, nu) - -log10(L / Q)
|
|
nebem_line_pos |
(nemline,) -- rest wavelengths [A]
|
|
gaussnebarr |
(nspec, nemline) -- painted profiles including lambda^2/c
|
|
young_mask, young_idx |
the young ages over ``ssp_ages_lgyr``
|
|
Source code in ceridwen/neb/NebularGridModel.py
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 | |
compute_log_qq ¶
log10 Q [photons/s] for every SSP: (L_sun/h) * int_{lambda<912} L_nu / lambda dlambda (the working float dtype, float64 by default).
Source code in ceridwen/neb/NebularGridModel.py
line_profiles ¶
(nspec, nemline) NumPy profiles like gaussnebarr with width
sqrt(floor^2 + (lambda sigma_kms / c)^2): a line painted at the floor and then broadened.
Source code in ceridwen/neb/NebularGridModel.py
evaluate ¶
(cont (nspec,), lines (nspec,)) [L_sun/Hz] at one (logZ, logU, logage, logQ).
Source code in ceridwen/neb/NebularGridModel.py
evaluate_batch ¶
(n_z, n_young, nspec) nebular spectra at one (logZ_gas, logU) for the young SSP ages,
or (cont, lines) in that layout with return_components. The metallicity dependence
enters only through logqq_young; the per-age reference ref keeps 10**(...) in float32 range.
Source code in ceridwen/neb/NebularGridModel.py
evaluate_batch_factored ¶
(base (n_young, n_wave), scale (n_z, n_young)) with neb[z, y, w] == scale[z, y] * base[y, w]
(same arithmetic as evaluate_batch, not expanded). include_lines="both" returns
(base_continuum, base_with_lines, scale) from one evaluation.
Source code in ceridwen/neb/NebularGridModel.py
evaluate_batch_line_lum ¶
Line luminosities (n_z, n_young, nlines) [L_sun] at one (logZ_gas, logU), no painting.
Source code in ceridwen/neb/NebularGridModel.py
get_default_params ¶
ceridwen.igm ¶
Intergalactic-medium absorption models: transmission curves exp(-tau * factor)
on the rest-frame wavelength grid at a given source redshift.
IGMModel ¶
Bases: ABC
Abstract IGM attenuation model; subclasses implement tau(lam_rest, zred).
A model that reads theta keys of its own lists them in param_names; the CSP then passes
attenuation(..., params={key: scalar}) with those of the keys present in theta (and only
then, so a subclass with the three-argument attenuation keeps working).
Madau1995 ¶
Bases: IGMModel
Madau (1995) IGM attenuation: 17 Lyman-series lines, Ly-α metal blanketing and Lyman-continuum absorption; tau is capped at its short-wavelength peak and is zero at zred = 0.
MadauDampingDLA ¶
MadauDampingDLA(
Ob0=None,
cosmo=None,
x_HI=0.0,
zmin=5.0,
Y=0.25,
logN_HI=None,
z_dla=None,
b_kms=40.0,
)
Bases: Madau1995
Madau (1995) x IGM damping wing x damped Ly-alpha absorber (DLA).
attenuation = exp(-(igm_factor * tau_Madau + tau_damp(x_HI) + tau_DLA(logN_HI, z_dla)))
igm_factor scales the Madau forest only; the neutral fraction is its own parameter
(Prospector instead reads x_HI from igm_factor, sedmodel.py:824).
x_HI, logN_HI and z_dla are theta keys like igm_factor: the constructor
values are the defaults, and a theta entry (fixed or sampled) overrides them. A component
is evaluated when its constructor value switches it on or its key is in theta; otherwise it
is skipped, so MadauDampingDLA() is Madau1995 bit for bit, and so are x_HI = 0
and logN_HI = -inf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Ob0
|
float -- baryon density today; required for the damping wing (CERIDWEN's Cosmology
|
carries no Ob0, so it is not guessed). Planck18: 0.04897; WMAP9: 0.04628. |
None
|
cosmo
|
Cosmology or None -- supplies ``h`` and ``Om0``; ``None`` = the CSP's cosmology,
|
bound at |
None
|
x_HI
|
float -- IGM neutral fraction (> 1 mimics a local overdensity); 0 = no damping wing.
|
|
0.0
|
zmin
|
float -- lower redshift of the neutral IGM; no wing for ``zred <= zmin``.
|
|
5.0
|
Y
|
float -- helium mass fraction.
|
|
0.25
|
logN_HI
|
float or None -- DLA column [log10 cm^-2]; ``None`` = no DLA.
|
|
None
|
z_dla
|
float or None -- absorber redshift; ``None`` = the source redshift. No DLA for
|
|
None
|
b_kms
|
float -- Doppler parameter of the DLA [km/s].
|
|
40.0
|
Source code in ceridwen/igm.py
bind_cosmology ¶
Take h and Om0 from cosmo; a model already bound to a different
cosmology raises (the damping wing and the flux factor would disagree).
Source code in ceridwen/igm.py
tau_damp ¶
Damping-wing optical depth; params['x_HI'] overrides the constructor value.
Source code in ceridwen/igm.py
tau_dla ¶
DLA Voigt optical depth; params['logN_HI'] / params['z_dla'] override.
Source code in ceridwen/igm.py
attenuation ¶
exp(-(factor * tau_Madau + tau_damp + tau_DLA)): igm_factor scales the forest only.
Source code in ceridwen/igm.py
voigt_tau ¶
Optical depth of a Voigt line (Krogager 2018 normalisation) on wave_abs [A, absorber
rest frame] for a column density N [cm^-2]; Ly-alpha by default.
Source code in ceridwen/igm.py
tau_gp ¶
Gunn-Peterson optical depth, Miralda-Escude (1998) normalisation.
tau_damping ¶
Damping-wing optical depth of a uniformly neutral IGM (neutral fraction x_HI) between
zmin and zred (Miralda-Escude 1998; Totani et al. 2006), on the rest-frame grid.
Zero blueward of Ly-alpha and for zred <= zmin; masked with safe arguments so jit
and gradients stay finite.
Source code in ceridwen/igm.py
make_igm_model ¶
Return an :class:IGMModel from a registry name, an instance (as-is), or None (NoIGM).
Source code in ceridwen/igm.py
ceridwen.cosmology ¶
Flat LambdaCDM redshift helpers: :class:Cosmology presets, D_L(z), age(z)
and the maggies flux factor, JAX-native (differentiable in z) with an optional
scalar-only astropy backend.
Cosmology
dataclass
¶
Flat LambdaCDM cosmology with photons and effective neutrinos; the massive neutrino is folded into Om0 as cold matter. Defaults to Planck 2018.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
H0
|
(float, km / s / Mpc)
|
|
67.66
|
Om0
|
float -- cold matter today, EXCLUDING massive neutrinos.
|
|
0.30966
|
Tcmb0
|
(float, K)
|
|
2.7255
|
Neff
|
float -- effective number of neutrino species.
|
|
3.046
|
m_nu_ev_sum
|
float, eV -- sum of neutrino masses.
|
|
0.06
|
name
|
str -- label only; ignored in equality.
|
|
None
|
Onu0_massive_as_matter
property
¶
Massive-neutrino density today, treated as cold matter.
Onu0_relativistic
property
¶
Relativistic neutrino density today (Neff - 1 species).
is_planck18
property
¶
True when the parameters equal the Planck-2018 preset (name ignored).
wmap9
classmethod
¶
flat
classmethod
¶
Flat LCDM from H0 and Om0; radiation and neutrinos default to Planck 2018.
Source code in ceridwen/cosmology.py
from_name
classmethod
¶
Preset by name, case-insensitive (see available_cosmologies()).
Source code in ceridwen/cosmology.py
from_dict
classmethod
¶
Inverse of :meth:to_dict; also accepts cosmo_*-prefixed HDF5 attrs.
Source code in ceridwen/cosmology.py
to_dict ¶
age ¶
luminosity_distance ¶
from_astropy
classmethod
¶
Build from a flat astropy cosmology; a non-flat input raises.
Source code in ceridwen/cosmology.py
to_astropy ¶
Return the matching astropy.cosmology.FlatLambdaCDM (requires astropy).
Source code in ceridwen/cosmology.py
available_cosmologies ¶
resolve_cosmology ¶
E_of_z ¶
Dimensionless expansion rate E(z) = H(z)/H0; z is clamped to >= 0
so transient negative proposals cannot produce NaN.
Source code in ceridwen/cosmology.py
comoving_distance_mpc ¶
Line-of-sight comoving distance D_C(z) [Mpc].
Source code in ceridwen/cosmology.py
age_gyr ¶
Age of the Universe at z [Gyr], JAX-native and differentiable in z.
Source code in ceridwen/cosmology.py
luminosity_distance_mpc ¶
Luminosity distance D_L(z) [Mpc].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
('native', 'astropy')
|
'astropy' is scalar-z only. |
'native'
|
Source code in ceridwen/cosmology.py
flux_factor ¶
(1+z) / (4 pi D_L^2) with D_L in cm: converts rest-frame L_nu [erg/s/Hz] to observed F_nu [erg/s/cm^2/Hz].
Source code in ceridwen/cosmology.py
flux_factor_cgs ¶
Factor turning a CSP spectrum [L_sun/Hz/M_sun] into observed-frame F_nu [erg/s/cm^2/Hz] (cgs): (1+z) (10 pc / D_L)^2 times the 10 pc unit constant. z <= 0 is pinned to D_L = 10 pc. The AB-maggies photometry is obtained downstream by projecting this cgs spectrum through the filters (dividing by the 3631 Jy AB zero point); this factor itself is NOT maggies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
('native', 'astropy')
|
|
'native'
|
lumdist_mpc
|
float or Array, Mpc -- explicit D_L replacing D_L(z); the
|
(1+z) term still comes from z and the z <= 0 pin does not apply. |
None
|
Source code in ceridwen/cosmology.py
Spectrophotometric calibration¶
ceridwen.csp.spectrum_calibration.spectrum_calibration_factor ¶
Factor spectrum_scaling * (1 + spectrum_calib . P(x)) multiplying the MODEL spectrum
of obs (keys from :func:calibration_keys): a scalar (level only), an (n_pix,)
vector (shape term), or None if the spectrum has neither.
Source code in ceridwen/csp/spectrum_calibration.py
ceridwen.csp.spectrum_calibration.legendre_design_matrix ¶
(n_pix, order) float64 matrix of Legendre P_1..P_order on the pixel wavelengths
mapped affinely onto [-1, 1] (range over ALL pixels, masked or not; no P_0 term).