synference.library¶
File containing Synthesizer library generation and galaxy creation utilities.
Functions
- synference.library.calculate_MUV(galaxy, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))[source]¶
Calculate the absolute MUV magnitude of a galaxy.
- Parameters:
galaxy (Galaxy) – The galaxy object containing stellar spectra.
cosmo (Cosmology, optional) – The cosmology to use for redshift calculations, by default Planck18.
Returns
-------
dict – Dictionary containing the MUV magnitude for each stellar spectrum in the galaxy.
- synference.library.calculate_Ndot_ion(galaxy, emission_model_key='total', ionisation_energy=unyt_quantity(13.6, 'eV'), limit=100)[source]¶
Calculate the ionizing photon production rate (Ndot_ion) of a galaxy.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
emission_model_key – The key for the emission model to use (default is ‘total’).
ionisation_energy – The ionisation energy threshold (default is 13.6 eV).
limit – An upper bound on the number of subintervals used in the integration adaptive algorithm.
- Returns:
The ionizing photon production rate (Ndot_ion) as a unyt_quantity in s^-1.
- synference.library.calculate_agn_fraction(galaxy, total_em_key='total', agn_em_key='agn_attenuated', min_wav_rest=unyt_quantity(1, 'μm'), max_wav_rest=unyt_quantity(30, 'μm'))[source]¶
Compute the fraction of the total luminosity in a given wavelength range due to the AGN.
- Parameters:
galaxy (Galaxy) – The Galaxy object containing the spectra.
total_em_key (str) – The key for the total emission model in the galaxy.
agn_em_key (str) – The key for the AGN emission model in the galaxy.
min_wav_rest (float) – The minimum rest-frame wavelength (in unyt units) for the integration.
max_wav_rest (float) – The maximum rest-frame wavelength (in unyt units) for the integration.
Returns
-------
float – The fraction of the total luminosity in the specified wavelength range due to the AGN.
- synference.library.calculate_balmer_decrement(galaxy, emission_model_key='total')[source]¶
Measures the Balmer decrement a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model_key (
str) – The key for the emission model to use (default is ‘total’).
- Return type:
float- Returns:
The Balmer decrement as a float.
- synference.library.calculate_beta(galaxy, emission_model_key='total')[source]¶
Measures the beta index of a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model_key (
str) – The key for the emission model to use (default is ‘total’).
- Return type:
float- Returns:
The beta index as a float.
- synference.library.calculate_burstiness(galaxy)[source]¶
Calculate the burstiness parameter of a galaxy.
Burstiness is defined as the ratio of the SFR averaged over the last 10 Myr to the SFR averaged over the last 100 Myr.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.- Returns:
The burstiness parameter as a dimensionless float.
- synference.library.calculate_colour(galaxy, filter1, filter2, emission_model_key='total', rest_frame=False)[source]¶
Measures the colour of a galaxy between two filters (filter1 - filter2).
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.filter1 (
str) – The first filter code (e.g., ‘JWST/NIRCam.F444W’).filter2 (
str) – The second filter code (e.g., ‘JWST/NIRCam.F115W’).emission_model_key (
str) – The key for the emission model to use (default is ‘total’).rest_frame (
bool) – Whether to use the rest frame (default is False).
- Return type:
float- Returns:
The colour of the galaxy as a float.
- synference.library.calculate_d4000(galaxy, emission_model_key='total')[source]¶
Measures the D4000 index of a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model_key (
str) – The key for the emission model to use (default is ‘total’).
- Return type:
float- Returns:
The D4000 index as a float.
- synference.library.calculate_flux_weighted_age(galaxy, spectra_type='total', filter_code='JWST/NIRCam.F444W')[source]¶
Calculate the flux-weighted age of the stars in the galaxy.
- synference.library.calculate_line_ew(galaxy, emission_model, line='Ha', emission_model_key='total')[source]¶
Measures the rest-frame equivalent widths of specific emission lines in a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model – An instance of a synthesizer.emission_models.EmissionModel.
line – The name of the emission line to measure (default is ‘Ha’).
emission_model_key – The key for the emission model to use (default is ‘total’).
- Returns:
A dictionary with line names as keys and their equivalent widths as values.
- synference.library.calculate_line_flux(galaxy, emission_model, line='Ha', emission_model_key='total', cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))[source]¶
Measures the equivalent widths of specific emission lines in a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model – An instance of a synthesizer.emission_models.EmissionModel.
line – The name of the emission line to measure (default is ‘Ha’).
emission_model_key – The key for the emission model to use (default is ‘total’).
cosmo – An instance of astropy.cosmology.Cosmology (default is Planck18).
- Returns:
A dictionary with line names as keys and their equivalent widths as values.
- synference.library.calculate_line_luminosity(galaxy, emission_model, line='Ha', emission_model_key='total')[source]¶
Measures the luminosity of specific emission lines in a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model – An instance of a synthesizer.emission_models.EmissionModel.
line – The name of the emission line to measure (default is ‘Ha’).
emission_model_key – The key for the emission model to use (default is ‘total’).
- Returns:
A dictionary with line names as keys and their luminosities as values.
- synference.library.calculate_lum_weighted_age(galaxy, spectra_type='total', filter_code='V')[source]¶
Calculate the luminosity-weighted age of the stars in the galaxy.
- synference.library.calculate_mass_weighted_age(galaxy)[source]¶
Calculate the mass-weighted age of the stars in the galaxy.
- synference.library.calculate_ml(galaxy, emission_model_key)[source]¶
Calculate M/L ratio (in solar units).
- synference.library.calculate_muv(galaxy, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))[source]¶
Calculate the apparent mUV magnitude of a galaxy.
- Parameters:
galaxy (Galaxy) – The galaxy object containing stellar spectra.
cosmo (Cosmology, optional) – The cosmology to use for redshift calculations, by default Planck18.
Returns
-------
dict – Dictionary containing the MUV magnitude for each stellar spectrum in the galaxy.
- synference.library.calculate_sfh_quantile(galaxy, quantile=0.5, norm=False, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))[source]¶
Calculate the lookback time at which a certain fraction of the total mass is formed.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
quantile – The fraction of total mass formed (default is 0.5 for median).
norm – If True then the age is as a fraction of the age of the universe at the redshift of the galaxy.
cosmo – Cosmology object to use for age calculations, default is Planck18.
- Returns:
The lookback time in Myr at which the specified fraction of total mass is formed.
- synference.library.calculate_sfr(galaxy, timescale=unyt_quantity(10, 'Myr'))[source]¶
Calculate the star formation rate (SFR) of a galaxy over a specified timescale.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
timescale – The timescale over which to calculate the SFR (default is 10 Myr).
- Returns:
The star formation rate as a float.
- synference.library.calculate_surviving_mass(galaxy, grid)[source]¶
Calculate the surviving mass of the stellar population in a galaxy.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
grid (
Grid) – An instance of synthesizer.grid.Grid containing the SPS grid.
- Returns:
The surviving mass as a unyt_quantity in Msun.
- synference.library.calculate_xi_ion0(galaxy, emission_model, emission_model_key='total')[source]¶
Calculate the ionizing photon production efficiency (xi_ion) of a galaxy.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
emission_model – An instance of a synthesizer.emission_models.EmissionModel.
emission_model_key – The key for the emission model to use (default is ‘total’).
- Returns:
The ionizing photon production efficiency (xi_ion) as a unyt_quantity in Hz/erg.
- synference.library.create_galaxy(sfh, redshift, metal_dist, grid, log_stellar_masses=9, **galaxy_kwargs)[source]¶
Create a new galaxy with the specified parameters.
- Return type:
Type[Galaxy]
- synference.library.draw_from_hypercube(param_ranges, N=1000000.0, model=<class 'scipy.stats._qmc.LatinHypercube'>, rng=None, unlog_keys=None)[source]¶
Draw N samples from a hypercube defined by the parameter ranges.
- Parameters:
N (int) – Number of samples to draw.
param_ranges (dict, optional) – Dictionary where keys are parameter names and values are tuples (min, max). Can be unyt_quantities for units.
model (Type[qmc], optional) – The sampling model to use, by default LatinHypercube.
rng (Optional[np.random.Generator], optional) – Random number generator to use for sampling, by default None.
unlog_keys (Optional[List[str]], optional) – List of keys in param_ranges that should be unlogged (i.e., raised to power of 10). Units will be preserved even if this doesn’t really make sense (e.g. Msun).
Returns
-------
dict – Dictionary where keys are parameter names and values are arrays of sampled values.
-------
- synference.library.generate_emission_models(emission_model, varying_params, grid, fixed_params=None)[source]¶
Generate a grid of emission models based on varying parameters.
- Parameters:
emission_model (Type[EmissionModel]) – The emission model class to instantiate. E.g., TotalEmission or PacmanEmission
varying_params (dict) – Dictionary of varying parameters for emission model. Each parameter should have: - ‘prior’: scipy.stats distribution - ‘min’: minimum value - ‘max’: maximum value - ‘size’: number of samples to draw - ‘units’: unyt unit (optional) - ‘name’: parameter name for constructor (optional, defaults to the key)
grid (Grid) – Grid object containing the SPS grid.
fixed_params (dict, optional) – Dictionary of fixed parameters for the emission model. Each parameter should have: - ‘value’: fixed value - ‘units’: unyt unit (optional) - ‘name’: parameter name for constructor (optional, defaults to the key)
- synference.library.generate_metallicity_distribution(zmet_dist, zmet={'max': 0.3, 'min': -3, 'prior': 'loguniform', 'size': 6, 'units': None})[source]¶
Generate a grid of metallicity distributions based on prior distributions.
- Parameters:
zmet_dist (Type[ZDist]) – The metallicity distribution class to instantiate. E.g., ZDist.DeltaConstant or ZDist.Normal
z (dict) – Dictionary of prior distributions for zmet parameters. Each parameter should have: - ‘prior’: scipy.stats distribution - ‘min’: minimum value - ‘max’: maximum value - ‘size’: number of samples to draw - ‘units’: unyt unit (optional) - ‘name’: parameter name for constructor (optional, defaults to the key)
- synference.library.generate_random_DB_sfh(Nparam=3, tx_alpha=5, redshift=6, logmass=8, logsfr=-1, seed=None)[source]¶
Generate a random Dense Basis SFH.
This function generates a random star formation history (SFH) using a dense basis representation. It creates a star formation history with a specified number of parameters, a Dirichlet distribution for the time series, and allows for customization of the log mass and log SFR.
- Parameters:
size (int, optional) – Number of SFHs to generate, by default 1
Nparam (int, optional) – Number of parameters for the SFH, by default 3
tx_alpha (float, optional) – Concentration parameter for the Dirichlet distribution, by default 5
redshift (float, optional) – Redshift of the SFH, by default 6
logmass (float, optional) – Logarithm of the stellar mass in solar masses, by default 8
logsfr (float, optional) – Logarithm of the star formation rate in solar masses per year, by default -1
Returns
-------
SFH.DenseBasis – A DenseBasis SFH object with the generated parameters.
np.ndarray – An array of time series parameters for the SFH.
- synference.library.generate_sfh_basis(sfh_type, sfh_param_names, sfh_param_arrays, redshifts, sfh_param_units=None, max_redshift=20, calculate_min_age=False, min_age_frac=0.001, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897), iterate_redshifts=False)[source]¶
Generate a grid of SFHs based on parameter arrays and redshifts.
- Parameters:
sfh_type (Type[SFH]) – The star formation history class to instantiate
sfh_param_names (List[str]) – List of parameter names for SFH constructor
sfh_param_arrays (List[np.ndarray]) – List of parameter arrays for SFH constructor. Should have the same length in the first dimension as sfh_param_names. if values are lambda functions the input will be the max age given max_redshift.
redshifts (Union[Dict[str, Any], float]) – Either a single redshift value, an array of redshifts, or a dictionary with: ‘prior’: scipy.stats distribution ‘min’: minimum redshift ‘max’: maximum redshift ‘size’: number of redshift samples
max_redshift (float, optional) – Maximum possible redshift to consider for age calculations, by default 15
cosmo (Type[Cosmology], optional) – Cosmology to use for age calculations, by default Planck18
calculate_min_age (bool, optional) – If True, calculate the lookback time at which only min_age_frac of total mass is formed, by default True
min_age_frac (float, optional) – Fraction of total mass formed to calculate the minimum age, by default 0.001
iterate_redshifts (bool, optional) – If True, iterate over redshifts and create SFH for each, by default True If False, assume input redshift SFH param array is a 1:1 mapping of redshift to SFH parameters.
Returns
-------
Tuple[List[SFH] – List of SFH objects with parameters drawn from the priors Array of parameter combinations, where the first column is redshift followed by SFH parameters
np.ndarray] – List of SFH objects with parameters drawn from the priors Array of parameter combinations, where the first column is redshift followed by SFH parameters
- Return type:
Tuple[List[Type[Common]],ndarray]
- synference.library.generate_sfh_grid(sfh_type, sfh_priors, redshift, max_redshift=15, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))[source]¶
Generate a grid of SFHs based on prior distributions.
This function creates a grid of SFH models by combining possible parameter values, which can depend explicitly on the redshift. It first draws redshifts, calculates maximum stellar ages at each redshift, and then creates parameter combinations within valid ranges.
- Parameters:
sfh_type (Type[SFH]) – The star formation history class to instantiate
sfh_priors (Dict[str, Dict[str, Any]]) – Dictionary of prior distributions for SFH parameters. Each parameter should have: - ‘prior’: scipy.stats distribution - ‘min’: minimum value - ‘max’: maximum value - ‘size’: number of samples to draw - ‘units’: astropy unit (optional) - ‘name’: parameter name for SFH constructor (optional, defaults to the key) - ‘depends_on’: special flag if parameter depends on redshift (‘max_redshift’)
redshift (Union[Dict[str, Any], float]) – Either a single redshift value or a dictionary with: - ‘prior’: scipy.stats distribution - ‘min’: minimum redshift - ‘max’: maximum redshift - ‘size’: number of redshift samples
max_redshift (float, optional) – Maximum possible redshift to consider for age calculations, by default 15
cosmo (Type[Cosmology], optional) – Cosmology to use for age calculations, by default Planck18
Returns
-------
Tuple[List[SFH] –
List of SFH objects with parameters drawn from the priors
- Array of parameter combinations, where the first column is redshift followed
by SFH parameters
np.ndarray] –
List of SFH objects with parameters drawn from the priors
- Array of parameter combinations, where the first column is redshift followed
by SFH parameters
Notes
-----
'depends_on' (For parameters that depend on redshift (marked with)
on (the maximum allowed value will be dynamically adjusted based)
redshift. (the age of the universe at that)
- Return type:
Tuple[List[Type[Common]],ndarray]
- synference.library.load_hypercube_from_npy(file_path)[source]¶
Load a hypercube from a .npy file.
- Parameters:
file_path (str) – Path to the .npy file containing the hypercube data.
Returns
-------
np.ndarray – Array of shape (N, M) containing the loaded hypercube data.
- synference.library.locate_sed(galaxy, emission_model_key)[source]¶
Locate the SED in the galaxy based on the emission model key.
- synference.library.test_out_of_distribution(observed_photometry, simulated_photometry, sigma_threshold=5.0)[source]¶
Identifies and removes samples from a dataset that are out-of-distribution.
The function calculates the Mahalanobis distance for each simulated sample to the mean of the observed samples, accounting for the covariance between filters. Samples with a distance greater than the specified sigma_threshold are considered outliers and are removed.
- Parameters:
observed_photometry (np.ndarray) – The reference dataset, expected to have a shape of (N_filters, N_obs_samples).
simulated_photometry (np.ndarray) – The dataset to be filtered, expected to have a shape of (N_filters, N_sim_samples).
sigma_threshold (float, optional) – The number of standard deviations (in Mahalanobis distance) to use as the outlier threshold. Defaults to 5.0.
- Returns:
A NumPy array containing the filtered simulated photometry. The shape will be (N_filters, N_inliers).
A 1D NumPy array containing the indices of the rows (samples) that were identified as outliers and removed from the original simulated_photometry.
- Return type:
Tuple[np.ndarray, np.ndarray]
Classes
- class synference.library.CombinedBasis(bases, log_stellar_masses, redshifts, base_emission_model_keys, combination_weights, out_name='combined_basis', out_dir='/opt/hostedtoolcache/Python/3.10.19/x64/lib/python3.10/libraries', log_base_masses=9, draw_parameter_combinations=False)[source]¶
Class to create a photometry array from Synthesizer pipeline outputs.
This class combines multiple GalaxyBasis objects, processes them, and saves the output to HDF5 files. The simplest operation is a single base, where we would provide a single GalaxyBasis object and this class will handle running the Synthesizer pipeline, processing the output and saving the results. The reason this is seperated is because we can combine multiple bases.
So when the GalaxyBasis is run, we determine photometry/spectra with a filler mass (normalization). Then this class will renormalize the photometry/spectra to the total stellar masses provided, and optionally weight them by the combination of bases. This is done so that you can have a case where there is e.g. two bases with different SPS grids, and we can build a galaxy where 15% of the mass is from the first base, and 85% is from the second base. It can also allow flexiblity when generating galaxies in the pipeline, as the stellar mass dimension could be neglected in e.g. the LHC and applied afterwards.
- create_full_library(override_instrument=None, save=True, overload_out_name='', overwrite=False, spectral_mode=False)[source]¶
Create a complete grid of SEDs by combining galaxy bases.
This method handles both single-base and multi-base scenarios, properly scaling according to masses and weights. It constructs a grid without sampling, generating the full set of combinations for all specified parameters.
- Parameters:
override_instrument (Instrument, optional) – If provided, use these filters instead of those in the bases
save (bool, default=True) – Whether to save the library to disk
overload_out_name (str, default='') – Custom filename for saving the library
overwrite (bool, default=False) – Whether to overwrite existing files
- Return type:
None
- create_library(override_instrument=None, save=True, overload_out_name='', overwrite=False)[source]¶
Creates a library of SEDs for the given Synthesizer outputs.
This method assumes each input on CombinedBasis, (redshift, mass, and varying parameters) should be combined (e.g. sampling every combination of redshift, mass, and varying parameters) to create the library. The ‘create_full_library’ method instead assumes that the input parameters are already combined, and does not sample every combination. Generally the ‘create_full_library’ method is more useful for the case where you have predrawn parameters randomly or from a prior or Latin Hypercube.
- Parameters:
override_instrument (Instrument, optional) – If provided, overrides the instrument used for the library.
save (bool, optional) – If True, saves the library to a file.
overload_out_name (str, optional) – If provided, overrides the output name for the library.
overwrite (bool, optional) – If True, overwrites the existing library file if it exists.
Returns
-------
dict – A dictionary containing the library of SEDs, photometry, and properties.
-----------
- Return type:
dict
- create_spectral_grid(save=True, overload_out_name='', overwrite=False)[source]¶
Creates a parameter grid for spectroscopic observations.
Wrapper for create_full_library, but specifically for spectroscopic outputs, to match e.g. NIRSpec IFU, or DESI etc. The only spectral sampling currently supported is the one used in the instrument/grid combination.
- Parameters:
save (bool, optional) – If True, saves the library to a file.
overload_out_name (str, optional) – If provided, overrides the output name for the library.
overwrite (bool, optional) – If True, overwrites the existing grid file if it exists.
Returns
-------
dict – A dictionary containing the library of SEDs, photometry, and properties.
- Return type:
dict
- load_bases(load_spectra=False)[source]¶
Load the processed bases from the output directory.
- Parameters:
load_spectra (bool) – If True, load the observed spectra from the output files. If False, only load the properties and photometry.
Returns
-------
dict – A dictionary with the base model names as keys and a dictionary of properties, observed spectra, wavelengths, and observed photometry.
- Return type:
dict
- load_library_from_file(file_path)[source]¶
Load the library from a file.
- Parameters:
file_path (str) – Path to the HDF5 file containing the library data.
Returns
-------
dict – Dictionary containing the library data.
- Return type:
dict
- plot_galaxy_from_library(index, show=True, save=False, override_filter_codes=[])[source]¶
Plot a galaxy at a grid index.
- Parameters:
index (int) – Index of the galaxy in the library.
show (bool, optional) – If True, shows the plot. Defaults to True.
save (bool, optional) – If True, saves the plot. Defaults to False.
- process_bases(n_proc=6, overwrite=False, verbose=False, batch_size=40000, multi_node=False, galaxies_mask=None, spectra_to_save=None, em_lines_to_save=None, **extra_analysis_functions)[source]¶
Process the bases and save the output to files.
- Parameters:
n_proc (int) – Number of processes to use for the pipeline.
overwrite (bool or list of bools) – If True, overwrite the existing files. If False, skip the files that already exist. If a list of bools is provided, it should have the same length as the number of bases.
extra_analysis_functions (dict) – Extra analysis functions to add to the pipeline. The keys should be the names of the functions, and the values should be the functions themselves, or a tuple of (function, args). The function should take a Galaxy object as the first argument, and the args should be the arguments to pass to the function. The function should return a single value, an array of values, or a dictionary of values (with the same keys for all galaxies).
- Return type:
None
- save_library(library_dict, overload_out_name='', overwrite=False, library_params_to_save=['model_name'])[source]¶
Save the library to a file.
- Parameters:
library_dict (dict) – Dictionary containing the library data. Expected keys are ‘photometry’, ‘parameters’, ‘parameter_names’, and ‘filter_codes’.
out_name (str, optional) – Name of the output file, by default ‘grid.hdf5’
- Return type:
None
- class synference.library.GalaxyBasis(model_name, redshifts, grid, emission_model, sfhs, metal_dists, log_stellar_masses=None, galaxy_params=None, alt_parametrizations=None, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897), instrument=None, redshift_dependent_sfh=False, params_to_ignore=None, build_library=False)[source]¶
Class to create a basis of galaxies with different SFHs, redshifts, and parameters.
It can support two modes of operation.
The first case in the simplest - you have some set of priors controlling e.g. mass, redshift, SFH parameters, and metallicity distribution parameters, which you draw randomly or from a Latin hypercube, and then you create a galaxy for each set of parameters. So if you are drawing 1000 galaxies, you would pass in 1000 redshifts, 1000 SFHs, 1000 metallicity distributions, and 1000 sets of galaxy parameters.
If however you are sampling on a grid, or want dependent priors, you can instead pass in a few basis SFHs, redshifts, and metallicity distributions, and then the class will generate a library of galaxies by combining every combination of SFH, redshift, and metallicity distributions. This can reduce the number of galaxies created.
- create_galaxies_optimized(fixed_params, varying_param_names, log_base_masses, galaxies_mask=None, n_proc=28, batch_size=None)[source]¶
Optimized version with reduced serialization overhead.
- create_galaxy(sfh, redshift, metal_dist, log_stellar_masses=9, grid=None, **galaxy_kwargs)[source]¶
Create a galaxy from parameters.
- Return type:
Type[Galaxy]
Parameters:¶
sfh: SFH model class, e.g. SFH.LogNormal redshift: redshift of the galaxy metal_dist: metallicity distriution of the galaxy log_stellar_masses: float or list of floats, log10 stellar mass in solar masses grid: Grid object, if None use self.grid galaxy_kwargs: additional keyword arguments to pass to the Galaxy class
Returns:¶
: Type[Galaxy] Galaxy object created with the specified parameters.
- create_mock_library(out_name, log_stellar_masses=None, emission_model_key='total', out_dir='/opt/hostedtoolcache/Python/3.10.19/x64/lib/python3.10/libraries', n_proc=6, overwrite=False, verbose=False, batch_size=40000, parameter_transforms_to_save=None, cat_type='photometry', compile_grid=True, multi_node=False, spectra_to_save=None, em_lines_to_save=None, **extra_analysis_functions)[source]¶
Convenience method which calls CombinedBasis.
This is a convenience method which allows you to not have to pass a GalaxyBasis into CombinedBasis, and instead just call this method which will run the components for you.
- Parameters:
out_name (str) – Name of the output file to save the mock catalog.
log_stellar_masses (np.ndarray, optional) – Array of log stellar masses to use for the mock catalog, Units of log10(M sun), by default None. If None, uses the stellar_masses set in the GalaxyBasis.
emission_model_key (str, optional) – Emission model key to use for the mock catalog, by default “total”.
out_dir (str, optional) – Directory to save the output file, by default “library_folder”. If “library_folder”, saves to the Synthesizer grids directory.
n_proc (int, optional) – Number of processes to use for the pipeline, by default 6.
overwrite (Union[bool, List[bool]], optional) – If True, overwrites the output file if it exists, by default False. If a list, must be the same length as bases.
verbose (bool, optional) – If True, prints verbose output during processing, by default False.
batch_size (int, optional) – Size of each batch of galaxies to process, by default 40,000.
parameter_transforms_to_save (Dict[str: (str, callable)], optional) – Dictionary of parameter transforms to save in the output file. Only used for for saving with the simulator to allow reconstruction of the model later. Lambda functions cannot be used here. Should be a dictionary where keys are the parameter names in the model, and the values are a tuple. The tuple should be (str, callable), where the str is the new parameter name to save, and the callable is the function which takes the model parameters and returns the new parameter value. It can also be (List[str], callable) if the function returns multiple values. (e.g. converting one parameter to many.) Finally, if you are adding a new parameter which is not in the model, you can a direct str: callable pair, which will add a new parameter to the model based on the callable function.
compile_grid (bool, optional) – If True, compiles the library after processing, by default True.
multi_node (bool, optional) – If True, runs the processing in parallel across multiple nodes, by default False. Will only enable this, script still needs to be run with slurm or similar.
cat_type (str, optional) – Type of catalog to create, either “photometry” or “spectra”, by default “photometry”.
spectra_to_save (Optional[list], optional) – List of spectra types to save, by default None. If None, saves only the root spectra.
extra_analysis_functions (dict, optional) – Additional analysis functions to add to the pipeline. Each should have the argument name as the key, and the value should be a tuple of the function and its parameters.
- plot_galaxy(idx, save=True, log_stellar_mass=9, emission_model_keys=['total'], out_dir='./')[source]¶
Plot the galaxy with the given index.
- process_base(out_name, log_stellar_masses=None, emission_model_key='total', out_dir='/opt/hostedtoolcache/Python/3.10.19/x64/lib/python3.10/libraries', n_proc=6, overwrite=False, verbose=False, batch_size=40000, multi_node=False, spectra_to_save=None, em_lines_to_save=None, **extra_analysis_functions)[source]¶
Run pipeline for this base.
Implements functionality of CombinedBasis.process_bases for a single base. This is a convenience method to allow the GalaxyBasis to be run seperately.
- process_galaxies(galaxies, out_name='auto', out_dir='internal', n_proc=4, verbose=1, save=True, emission_model_keys=None, batch_galaxies=True, batch_size=40000, overwrite=False, multi_node=False, spectra_to_save=None, em_lines_to_save=None, igm=<class 'synthesizer.emission_models.transformers.igm.Inoue14'>, **extra_analysis_functions)[source]¶
Processes galaxies through Synthesizer pipeline.
- Parameters:
galaxies (List[Type[Galaxy]]) – List of Galaxy objects to process.
out_name (str, optional) – Name of the output file to save the pipeline results, by default “auto”. If “auto”, uses the model_name.
out_dir (str, optional) – Directory to save the output file, by default “internal”. If “internal”, saves to the Synthesizer grids directory.
n_proc (int, optional) – Number of processes to use for parallel processing, by default 4.
verbose (int, optional) – Verbosity level for the pipeline, by default 1.
save (bool, optional) – If True, saves the pipeline results to disk, by default True.
emission_model_keys (List[str], optional) – List of emission model keys to save spectra for, by default None. If None, saves all spectra.
batch_galaxies (bool, optional) – If True, processes galaxies in batches, by default True. If False, processes all galaxies in a single batch.
batch_size (int, optional) – Size of each batch of galaxies to process, by default 40,000.
spectra_to_save (list, optional) – List of spectra types to save, by default None. If None, saves only the root spectra.
em_lines_to_save (list, optional) – List of emission lines to save, by default None.
extra_analysis_functions (dict, optional) – Additional analysis functions to add to the pipeline. Should be a dictionary where keys are function names and values are tuples of the function and its parameters.
Returns
-------
Pipeline – The pipeline object after processing the galaxies.
- Return type:
Pipeline
- process_priors(prior_dict)[source]¶
Process priors from dictionary.
- Parameters:
prior_dict (Dict[str, Any]) – Dictionary containing prior information. Must contain: - ‘prior’: scipy.stats distribution - ‘size’: number of samples to draw - ‘units’: unyt unit (optional) - other parameters required by the distribution
- Return type:
unyt_array
- class synference.library.GalaxySimulator(sfh_model, zdist_model, grid, instrument, emission_model, emission_model_key, emitter_params=None, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0. , 0. , 0.06] eV>, Ob0=0.04897), param_order=None, param_units=None, param_transforms=None, out_flux_unit='nJy', required_keys=['redshift', 'log_mass'], extra_functions=None, normalize_method=None, output_type='photo_fnu', include_phot_errors=False, depths=None, depth_sigma=5, noise_models=None, fixed_params=None, photometry_to_remove=None, ignore_params=None, ignore_scatter=False, return_type='array', device='cpu')[source]¶
Class for simulating photometry/spectra of galaxies.
This class is designed to work with a grid of galaxies, an instrument, and an emission model. It can simulate photometry and spectra based on the provided star formation history (SFH) and metallicity distribution (ZDist) models. The class can also handle uncertainties in the photometry using an empirical uncertainty model. It supports various configurations such as normalization methods, output types, and inclusion of photometric errors. It can also apply noise models to the simulated photometry.
- classmethod from_library(library_path, override_synthesizer_grid_dir=True, override_emission_model=None, **kwargs)[source]¶
Create a GalaxySimulator from a library file.
This method reads a grid file in HDF5 format, extracts the necessary components such as the grid, instrument, cosmology, SFH model, and emission model, and then instantiates a GalaxySimulator object.
- Parameters:
library_path (str) – Path to the library file in HDF5 format.
override_synthesizer_grid_dir (Union[None, str], optional) – If provided, this directory will override the synthesizer grid directory specified in the library file. This is useful for using a model on a different computer or environment where the grid directory is not the same as the one used to create the library file. If True, and the library_dir saved in the file does not exist, it will check for a synthesizer_grid_DIR environment variable and use that as the library directory. If a string is provided, it will use that as the grid directory.
override_emission_model (Union[None, EmissionModel], optional) – If provided, this emission model will override the one in the library file.
**kwargs (dict) – Additional keyword arguments to pass to the GalaxySimulator constructor.
Returns
-------
GalaxySimulator – An instance of GalaxySimulator initialized with the library data.
- simulate(params)[source]¶
Simulate photometry from the given parameters.
- Parameters:
params (dict or array-like) – Dictionary of parameters or an array-like object with the parameters in the order specified by self.param_order. If self.param_order is None, params must be a dictionary.
Returns
-------
dict – Dictionary of photometry outputs. Keys are the output types specified in self.output_type. Values are the corresponding photometry arrays.
- update_photo_filters(photometry_to_remove=None, photometry_to_add=None)[source]¶
Update the photometric filters used in the simulation.
This method allows you to modify the set of photometric filters used in the simulation by removing or adding specific filters. It updates the instrument’s filter collection accordingly.
- Parameters:
photometry_to_remove (list, optional) – List of filter codes to remove from the current set of filters. If None, no filters will be removed.
photometry_to_add (list, optional) – List of filter codes to add to the current set of filters. If None, no filters will be added.
- class synference.library.LibraryCreator(model_name, parameter_names, parameter_grid, observation_grid, observation_names, observation_units, parameter_units=None, supplementary_parameters=None, supplementary_parameter_units=None, supplementary_parameter_names=None, compresslevel=4, out_folder='.', overwrite=False)[source]¶
Class to create libraries for Synference simulations.
Allows creation of a library from parameter and observation arrays without using Synthesizer.
- Parameters:
model_name (str) – Name of the model/library.
parameter_names (List[str]) – List of parameter names.
parameter_grid (np.ndarray) – 2D array of shape (N_parameters, N_samples) containing parameter values.
observation_grid (np.ndarray) – 2D array of shape (N_observations, N_samples) containing observation values
observation_units (Union[str, unyt_quantity]) – Units of the observations (e.g., ‘AB’, ‘Jy’, etc.).
parameter_units (List[Union[str, unyt_array]], optional) – List of units for each parameter. If None, parameters are assumed to be dimensionless.
supplementary_parameters (np.ndarray, optional) – 2D array of shape (N_supplementary_parameters, N_samples) containing supplementary parameter values.
supplementary_parameter_units (List[Union[str, unyt_array]], optional) – List of units for each supplementary parameter.
supplementary_parameter_names (List[str], optional) – List of names for each supplementary parameter.
compresslevel (int, optional) – Compression level for HDF5 datasets (0-9). Default is 4.
- class synference.library.SUPP_FUNCTIONS[source]¶
A class to hold supplementary functions for galaxy analysis.
- calculate_MUV(cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))¶
Calculate the absolute MUV magnitude of a galaxy.
- Parameters:
galaxy (Galaxy) – The galaxy object containing stellar spectra.
cosmo (Cosmology, optional) – The cosmology to use for redshift calculations, by default Planck18.
Returns
-------
dict – Dictionary containing the MUV magnitude for each stellar spectrum in the galaxy.
- calculate_Ndot_ion(emission_model_key='total', ionisation_energy=unyt_quantity(13.6, 'eV'), limit=100)¶
Calculate the ionizing photon production rate (Ndot_ion) of a galaxy.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
emission_model_key – The key for the emission model to use (default is ‘total’).
ionisation_energy – The ionisation energy threshold (default is 13.6 eV).
limit – An upper bound on the number of subintervals used in the integration adaptive algorithm.
- Returns:
The ionizing photon production rate (Ndot_ion) as a unyt_quantity in s^-1.
- calculate_agn_fraction(total_em_key='total', agn_em_key='agn_attenuated', min_wav_rest=unyt_quantity(1, 'μm'), max_wav_rest=unyt_quantity(30, 'μm'))¶
Compute the fraction of the total luminosity in a given wavelength range due to the AGN.
- Parameters:
galaxy (Galaxy) – The Galaxy object containing the spectra.
total_em_key (str) – The key for the total emission model in the galaxy.
agn_em_key (str) – The key for the AGN emission model in the galaxy.
min_wav_rest (float) – The minimum rest-frame wavelength (in unyt units) for the integration.
max_wav_rest (float) – The maximum rest-frame wavelength (in unyt units) for the integration.
Returns
-------
float – The fraction of the total luminosity in the specified wavelength range due to the AGN.
- calculate_balmer_decrement(emission_model_key='total')¶
Measures the Balmer decrement a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model_key (
str) – The key for the emission model to use (default is ‘total’).
- Return type:
float- Returns:
The Balmer decrement as a float.
- calculate_beta(emission_model_key='total')¶
Measures the beta index of a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model_key (
str) – The key for the emission model to use (default is ‘total’).
- Return type:
float- Returns:
The beta index as a float.
- calculate_burstiness()¶
Calculate the burstiness parameter of a galaxy.
Burstiness is defined as the ratio of the SFR averaged over the last 10 Myr to the SFR averaged over the last 100 Myr.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.- Returns:
The burstiness parameter as a dimensionless float.
- calculate_colour(filter1, filter2, emission_model_key='total', rest_frame=False)¶
Measures the colour of a galaxy between two filters (filter1 - filter2).
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.filter1 (
str) – The first filter code (e.g., ‘JWST/NIRCam.F444W’).filter2 (
str) – The second filter code (e.g., ‘JWST/NIRCam.F115W’).emission_model_key (
str) – The key for the emission model to use (default is ‘total’).rest_frame (
bool) – Whether to use the rest frame (default is False).
- Return type:
float- Returns:
The colour of the galaxy as a float.
- calculate_d4000(emission_model_key='total')¶
Measures the D4000 index of a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model_key (
str) – The key for the emission model to use (default is ‘total’).
- Return type:
float- Returns:
The D4000 index as a float.
- calculate_flux_weighted_age(spectra_type='total', filter_code='JWST/NIRCam.F444W')¶
Calculate the flux-weighted age of the stars in the galaxy.
- calculate_line_ew(emission_model, line='Ha', emission_model_key='total')¶
Measures the rest-frame equivalent widths of specific emission lines in a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model – An instance of a synthesizer.emission_models.EmissionModel.
line – The name of the emission line to measure (default is ‘Ha’).
emission_model_key – The key for the emission model to use (default is ‘total’).
- Returns:
A dictionary with line names as keys and their equivalent widths as values.
- calculate_line_flux(emission_model, line='Ha', emission_model_key='total', cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))¶
Measures the equivalent widths of specific emission lines in a galaxy.
- Parameters:
galaxy (
Galaxy) – An instance of a synthesizer.parametric.Galaxy object.emission_model – An instance of a synthesizer.emission_models.EmissionModel.
line – The name of the emission line to measure (default is ‘Ha’).
emission_model_key – The key for the emission model to use (default is ‘total’).
cosmo – An instance of astropy.cosmology.Cosmology (default is Planck18).
- Returns:
A dictionary with line names as keys and their equivalent widths as values.
- calculate_lum_weighted_age(spectra_type='total', filter_code='V')¶
Calculate the luminosity-weighted age of the stars in the galaxy.
- calculate_mass_weighted_age()¶
Calculate the mass-weighted age of the stars in the galaxy.
- calculate_muv(cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))¶
Calculate the apparent mUV magnitude of a galaxy.
- Parameters:
galaxy (Galaxy) – The galaxy object containing stellar spectra.
cosmo (Cosmology, optional) – The cosmology to use for redshift calculations, by default Planck18.
Returns
-------
dict – Dictionary containing the MUV magnitude for each stellar spectrum in the galaxy.
- calculate_sfh_quantile(quantile=0.5, norm=False, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))¶
Calculate the lookback time at which a certain fraction of the total mass is formed.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
quantile – The fraction of total mass formed (default is 0.5 for median).
norm – If True then the age is as a fraction of the age of the universe at the redshift of the galaxy.
cosmo – Cosmology object to use for age calculations, default is Planck18.
- Returns:
The lookback time in Myr at which the specified fraction of total mass is formed.
- calculate_sfr(timescale=unyt_quantity(10, 'Myr'))¶
Calculate the star formation rate (SFR) of a galaxy over a specified timescale.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
timescale – The timescale over which to calculate the SFR (default is 10 Myr).
- Returns:
The star formation rate as a float.
- calculate_surviving_mass(grid)¶
Calculate the surviving mass of the stellar population in a galaxy.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
grid (
Grid) – An instance of synthesizer.grid.Grid containing the SPS grid.
- Returns:
The surviving mass as a unyt_quantity in Msun.
- calculate_xi_ion0(emission_model, emission_model_key='total')¶
Calculate the ionizing photon production efficiency (xi_ion) of a galaxy.
- Parameters:
galaxy – An instance of a synthesizer.parametric.Galaxy object.
emission_model – An instance of a synthesizer.emission_models.EmissionModel.
emission_model_key – The key for the emission model to use (default is ‘total’).
- Returns:
The ionizing photon production efficiency (xi_ion) as a unyt_quantity in Hz/erg.