### Install MultiNest on Intel Mac Source: https://github.com/accarnall/bagpipes/blob/master/docs/index.rst Provides a sequence of commands to clone the MultiNest repository, install necessary dependencies like gcc49 using Homebrew, set the library path, compile MultiNest, and install it system-wide. This is for users on Intel-based Macs. ```bash git clone https://github.com/JohannesBuchner/MultiNest brew install gcc49 export DYLD_LIBRARY_PATH="/usr/local/bin/gcc-4.9:$DYLD_LIBRARY_PATH" cd MultiNest/build cmake .. make sudo make install cd ../.. rm -r MultiNest ``` -------------------------------- ### Install MultiNest on Apple Silicon Mac Source: https://github.com/accarnall/bagpipes/blob/master/docs/index.rst Provides a sequence of commands to clone the MultiNest repository, install dependencies like gcc and cmake using Homebrew, set the DYLD_LIBRARY_PATH for Apple Silicon Macs, compile MultiNest, and install it system-wide. It includes a note on checking and updating the gcc version path. ```bash git clone https://github.com/JohannesBuchner/MultiNest brew install gcc cmake export DYLD_LIBRARY_PATH="/opt/homebrew/bin/gcc-13:$DYLD_LIBRARY_PATH" cd MultiNest/build cmake .. make sudo make install cd ../.. rm -r MultiNest ``` -------------------------------- ### Access Predicted Observables from Maximum Likelihood Model Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 1 - Extracting the maximum likelihood model.ipynb This code demonstrates how to access the predicted observables (photometry) and stellar mass for the generated maximum likelihood model galaxy object. ```python import numpy as np # Assuming 'max_like_model_galaxy' is a generated pipes.model_galaxy object # Print the photometry of the maximum likelihood model print(max_like_model_galaxy.photometry) # Print the stellar mass of the maximum likelihood model print(max_like_model_galaxy.sfh.stellar_mass) ``` -------------------------------- ### Perform basic catalogue fitting with Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 6 - Fitting catalogues of data.ipynb Fits the first three objects from the Guo et al. catalogue using Bagpipes. It initializes the `fit_catalogue` class with object IDs, fitting instructions, and a data loading function, then starts the fitting process. ```python IDs = np.arange(1, 4) fit_cat = pipes.fit_catalogue(IDs, fit_instructions, load_goodss, spectrum_exists=False, cat_filt_list=goodss_filt_list, run="guo_cat") fit_cat.fit(verbose=False) ``` -------------------------------- ### Install Bagpipes using pip Source: https://github.com/accarnall/bagpipes/blob/master/docs/index.rst Installs the Bagpipes Python package and its dependencies. This is the primary method for obtaining the code. ```bash pip install bagpipes ``` -------------------------------- ### Run Bagpipes Fit and Plot Results (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 1 - Extracting the maximum likelihood model.ipynb Executes a Bagpipes fit using the prepared galaxy data and fit instructions, then plots the posterior spectrum. The fit can be run with verbose output. The primary dependency is the Bagpipes library. ```python fit = pipes.fit(galaxy, fit_info, run="advanced_1") fit.fit(verbose=False) fig = fit.plot_spectrum_posterior(save=False, show=True) ``` -------------------------------- ### Load and Prepare GOODS South Galaxy Photometry (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 1 - Extracting the maximum likelihood model.ipynb Loads and prepares photometry data for a GOODS South galaxy from a catalogue file. It handles flux and error calculations, enforces signal-to-noise ratios, and formats the data for use with Bagpipes. Dependencies include NumPy and Astropy. ```python import numpy as np import bagpipes as pipes from astropy.io import fits def load_goodss(ID): """ Load CANDELS GOODS South photometry from the Guo et al. (2013) catalogue. """ # load up the relevant columns from the catalogue. cat = np.loadtxt("hlsp_candels_hst_wfc3_goodss-tot-multiband_f160w_v1-1photom_cat.txt", usecols=(10, 13, 16, 19, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 11, 14, 17, 20, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56)) # Find the correct row for the object we want. row = int(ID) - 1 # Extract the object we want from the catalogue. fluxes = cat[row, :15] fluxerrs = cat[row, 15:] # Turn these into a 2D array. photometry = np.c_[fluxes, fluxerrs] # blow up the errors associated with any missing fluxes. for i in range(len(photometry)): if (photometry[i, 0] == 0.) or (photometry[i, 1] <= 0): photometry[i,:] = [0., 9.9*10**99.] # Enforce a maximum SNR of 20, or 10 in the IRAC channels. for i in range(len(photometry)): if i < 10: max_snr = 20. else: max_snr = 10. if photometry[i, 0]/photometry[i, 1] > max_snr: photometry[i, 1] = photometry[i, 0]/max_snr return photometry goodss_filt_list = np.loadtxt("filters/goodss_filt_list.txt", dtype="str").tolist() galaxy = pipes.galaxy("17433", load_goodss, spectrum_exists=False, filt_list=goodss_filt_list) # Now make a fit instructions dictionary, the details aren't important for this example. dblplaw = {} dblplaw["tau"] = (0., 15.) dblplaw["alpha"] = (0.01, 1000.) dblplaw["beta"] = (0.01, 1000.) dblplaw["alpha_prior"] = "log_10" dblplaw["beta_prior"] = "log_10" dblplaw["massformed"] = (1., 15.) dblplaw["metallicity"] = (0.1, 2.5) dust = {} dust["type"] = "Calzetti" dust["Av"] = (0., 2.) nebular = {} nebular["logU"] = -3. fit_info = {} fit_info["redshift"] = (0., 10.) fit_info["dblplaw"] = dblplaw fit_info["dust"] = dust fit_info["nebular"] = nebular ``` -------------------------------- ### Setting up a Galaxy Model with Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 3 - Variable spectral resolution.ipynb This Python code snippet initializes a galaxy model using the Bagpipes library. It defines parameters for a star-forming galaxy at redshift 3, including metallicity, age, and nebular emission properties. It utilizes NumPy for numerical operations and Matplotlib for plotting. ```python import numpy as np import matplotlib.pyplot as plt import bagpipes as pipes from astropy.io import fits nebular = {} nebular["logU"] = -2. constant = {} constant["massformed"] = 9. constant["metallicity"] = 0.2 constant["age_min"] = 0. constant["age_max"] = 0.1 model_comp = {} model_comp["constant"] = constant model_comp["nebular"] = nebular model_comp["t_bc"] = 0.01 model_comp["redshift"] = 3. ``` -------------------------------- ### Generate and Plot Maximum Likelihood Model Components Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 1 - Extracting the maximum likelihood model.ipynb This snippet shows how to update the `fit.fitted_model.model_components` dictionary using the maximum likelihood parameters and then generate a `pipes.model_galaxy` object. Finally, it plots the resulting maximum likelihood model. ```python import numpy as np import pipes # Assuming 'fit' is a pre-existing Bagpipes fit object, 'max_like_index' is determined, # and 'goodss_filt_list' is defined # Update model components with maximum likelihood parameters fit.fitted_model._update_model_components(fit.results["samples2d"][max_like_index, :]) max_like_model_components = fit.fitted_model.model_components print(max_like_model_components) # Generate a new model_galaxy object for the maximum likelihood model max_like_model_galaxy = pipes.model_galaxy(max_like_model_components, filt_list=goodss_filt_list, spec_wavs=np.arange(6000., 10000., 5.)) # Plot the maximum likelihood model fig = max_like_model_galaxy.plot() ``` -------------------------------- ### Retrieve Maximum Likelihood Model Parameters Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 1 - Extracting the maximum likelihood model.ipynb This code retrieves the parameter values associated with the maximum likelihood index from the `fit.results['samples2d']` array. These parameters define the maximum likelihood model. ```python import numpy as np # Assuming 'fit' is a pre-existing Bagpipes fit object and 'max_like_index' is determined # Extract the parameter values at the maximum likelihood index max_like_params = fit.results["samples2d"][max_like_index, :] print(max_like_params) ``` -------------------------------- ### Extract Log-Likelihood and Index from Bagpipes Fit Results Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 1 - Extracting the maximum likelihood model.ipynb This snippet demonstrates how to access the log-likelihood values stored in the `fit.results` dictionary and use `numpy.argmax` to find the index corresponding to the highest likelihood. It's essential for identifying the best-fit parameters within the posterior distribution. ```python import numpy as np # Assuming 'fit' is a pre-existing Bagpipes fit object # Print the type and length of the log-likelihood array print(type(fit.results["lnlike"]), len(fit.results["lnlike"])) # Find the index of the maximum log-likelihood value max_like_index = np.argmax(fit.results["lnlike"]) print(max_like_index) ``` -------------------------------- ### Define photometric filter list (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 1 - Making model galaxies.ipynb Creates a list of filter curves required for calculating photometric fluxes. The `filt_list` contains paths to filter curve files, where each file should have wavelengths in Angstroms and relative transmission values. This example uses filters from the CANDELS GOODS South catalogue. ```python goodss_filt_list = ["filters/VIMOS_U", "filters/f435w", "filters/f606w", "filters/f775w", "filters/f850lp", "filters/f098m", "filters/f105w", "filters/f125w", "filters/f160w", "filters/ISAAC_Ks", "filters/HAWKI_K", "filters/IRAC1", "filters/IRAC2", "filters/IRAC3", "filters/IRAC4"] ``` ```python goodss_filt_list = np.loadtxt("filters/goodss_filt_list.txt", dtype="str") ``` -------------------------------- ### Creating and Plotting a Bagpipes Galaxy Model Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 3 - Variable spectral resolution.ipynb This Python snippet shows how to create a galaxy model using Bagpipes with specified model components and wavelength data. It then plots the resulting model spectrum. The `spec_wavs` parameter is used to define the wavelengths for which the spectrum is calculated. ```python prism_wavs = np.loadtxt("nirspec_prism_pipeline_output_wavs.txt") model = pipes.model_galaxy(model_comp, spec_wavs=prism_wavs) fig = model.plot() ``` -------------------------------- ### Get Spectroscopic Observations Source: https://github.com/accarnall/bagpipes/blob/master/docs/model_galaxies.rst This code snippet shows how to obtain model spectroscopy by providing an array of desired wavelength sampling in Angstroms via the `spec_wavs` keyword argument. The output spectrum is stored in `model.spectrum`, which is a two-column array of wavelengths and spectral fluxes. ```python import bagpipes as pipes import numpy as np obs_wavs = np.arange(2500., 7500., 5.) model = pipes.model_galaxy(model_components, spec_wavs=obs_wavs) model.plot() ``` -------------------------------- ### Fit and Plot Galaxy SFH Posterior with Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 2 - The Leja2019 non-parametric continuity SFH Model.ipynb Demonstrates how to perform a Bagpipes fit using the defined 'fit_instructions' and then visualize the posterior distributions for the galaxy's spectrum and star formation history. This involves creating a 'fit' object and calling its plotting methods. ```python fit = pipes.fit(galaxy, fit_instructions, run="advanced_2") fit.fit(verbose=False) fig = fit.plot_spectrum_posterior(save=False, show=True) fig = fit.plot_sfh_posterior(save=False, show=True) ``` -------------------------------- ### Define Continuity Model Parameters in Python Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 2 - The Leja2019 non-parametric continuity SFH Model.ipynb Sets up the 'continuity' dictionary with parameters like 'massformed', 'metallicity', and 'bin_edges' for the continuity SFH model. It then iterates to define 'dsfr' parameters and their priors, assigning them to the 'fit_instructions' for Bagpipes. ```python continuity = {} continuity["massformed"] = (0., 13.) continuity["metallicity"] = (0.01, 5.) continuity["metallicity_prior"] = "log_10" continuity["bin_edges"] = [0., 10., 100., 250., 500., 1000., 2500., 5000., 5500.] for i in range(1, len(continuity["bin_edges"])-1): continuity["dsfr" + str(i)] = (-10., 10.) continuity["dsfr" + str(i) + "_prior"] = "student_t" #continuity["dsfr" + str(i) + "_prior_scale"] = 0.3 # Defaults to this value as in Leja19, but can be set #continuity["dsfr" + str(i) + "_prior_df"] = 2 # Defaults to this value as in Leja19, but can be set fit_instructions["continuity"] = continuity ``` -------------------------------- ### Bagpipes FSPS Loading Warning Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 2 - The Leja2019 non-parametric continuity SFH Model.ipynb This output indicates that the FSPS (Flexible Stellar Population Synthesis) library failed to load, which means only the GP-SFH (Gaussian Process - Stellar Formation History) module will be available for modeling in Bagpipes. This might limit the types of stellar population models that can be used. ```text Starting dense_basis. Failed to load FSPS, only GP-SFH module will be available. ``` -------------------------------- ### Loading and Plotting Spectral Resolving Power Curve Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 3 - Variable spectral resolution.ipynb This Python code demonstrates how to load a spectral resolving power (R_curve) from a FITS file and plot it. The curve is expected to have wavelengths in Angstroms and corresponding R values. This functionality is crucial for modeling spectra with variable resolution, such as those from JWST NIRSpec. ```python hdul = fits.open("jwst_nirspec_prism_disp.fits") model_comp["R_curve"] = np.c_[10000*hdul[1].data["WAVELENGTH"], hdul[1].data["R"]] plt.plot(model_comp["R_curve"][:, 0], model_comp["R_curve"][:, 1]) plt.xlabel("Wavelength/ \AA") plt.ylabel("Spectral resolving power") plt.show() ``` -------------------------------- ### Load GOODSS Photometry Data with Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 2 - The Leja2019 non-parametric continuity SFH Model.ipynb This Python code defines a function to load UltraVISTA photometry data for a given object ID from a catalogue file. It handles flux and error extraction, missing flux imputation, and enforces maximum signal-to-noise ratios for different wavelength channels. This function is used to prepare data for the Bagpipes library. ```python import numpy as np import bagpipes as pipes from astropy.io import fits def load_goodss(ID): """ Load UltraVISTA photometry from catalogue. """ # load up the relevant columns from the catalogue. cat = np.loadtxt("hlsp_candels_hst_wfc3_goodss-tot-multiband_f160w_v1-1photom_cat.txt", usecols=(10, 13, 16, 19, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 11, 14, 17, 20, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56)) # Find the correct row for the object we want. row = int(ID) - 1 # Extract the object we want from the catalogue. fluxes = cat[row, :15] fluxerrs = cat[row, 15:] # Turn these into a 2D array. photometry = np.c_[fluxes, fluxerrs] # blow up the errors associated with any missing fluxes. for i in range(len(photometry)): if (photometry[i, 0] == 0.) or (photometry[i, 1] <= 0): photometry[i,:] = [0., 9.9*10**99.] # Enforce a maximum SNR of 20, or 10 in the IRAC channels. for i in range(len(photometry)): if i < 10: max_snr = 20. else: max_snr = 10. if photometry[i, 0]/photometry[i, 1] > max_snr: photometry[i, 1] = photometry[i, 0]/max_snr return photometry goodss_filt_list = np.loadtxt("filters/goodss_filt_list.txt", dtype="str").tolist() galaxy = pipes.galaxy("17433", load_goodss, spectrum_exists=False, filt_list=goodss_filt_list) # Now make a basic fit instructions dictionary. dust = {} dust["type"] = "Calzetti" dust["eta"] = 2. dust["Av"] = (0., 4.) nebular = {} nebular["logU"] = -3. fit_instructions = {} fit_instructions["dust"] = dust fit_instructions["nebular"] = nebular fit_instructions["t_bc"] = 0.01 fit_instructions["redshift"] = 1.05 ``` -------------------------------- ### Define Bagpipes Fit Instructions Dictionary in Python Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Creates a fit instructions dictionary for the Bagpipes library. This dictionary specifies the parameters to be fitted, their prior ranges, and the models to be used, such as exponential star-formation histories and dust attenuation curves. ```python exp = {} # Tau-model star-formation history component exp["age"] = (0.1, 15.) # Vary age between 100 Myr and 15 Gyr. In practice # the code automatically limits this to the age of # the Universe at the observed redshift. exp["tau"] = (0.3, 10.) # Vary tau between 300 Myr and 10 Gyr exp["massformed"] = (1., 15.) # vary log_10(M*/M_solar) between 1 and 15 exp["metallicity"] = (0., 2.5) # vary Z between 0 and 2.5 Z_oldsolar dust = {} # Dust component dust["type"] = "Calzetti" # Define the shape of the attenuation curve dust["Av"] = (0., 2.) # Vary Av between 0 and 2 magnitudes fit_instructions = {} # The fit instructions dictionary fit_instructions["redshift"] = (0., 10.) # Vary observed redshift from 0 to 10 fit_instructions["exponential"] = exp fit_instructions["dust"] = dust ``` -------------------------------- ### Initialize Bagpipes Galaxy and Fit - Python Source: https://github.com/accarnall/bagpipes/blob/master/docs/fit_instructions.rst Shows the integration of fit_instructions with the Bagpipes library to load observational data for a galaxy and perform a model fit. It includes importing the library, defining a filter list, a data loading function, and the galaxy and fit objects. ```python import bagpipes as pipes eg_filt_list = ["list", "of", "filters"] def load_data(ID, filtlist): # Do some stuff to load up data for the object with the correct ID number return spectrum, photometry ID_number = "0001" galaxy = pipes.galaxy(ID_number, load_data, filt_list=eg_filt_list) fit = pipes.fit(galaxy, fit_instructions) ``` -------------------------------- ### Run Bagpipes Fit and Display Results in Python Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Initializes a Bagpipes fit object with a galaxy and fit instructions, then runs the MultiNest sampler to fit the data. Finally, it prints a summary of the posterior percentiles for the fitted parameters. ```python fit = pipes.fit(galaxy, fit_instructions) fit.fit(verbose=False) ``` -------------------------------- ### Define Bagpipes model components dictionary (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 1 - Making model galaxies.ipynb Sets up the `model_components` dictionary, which specifies the physical parameters of the galaxy model. This includes the star-formation history (tau model), dust model (Calzetti), and redshift. Dependencies include the `bagpipes` and `numpy` libraries. ```python import bagpipes as pipes import numpy as np exp = {} exp["age"] = 3. # Gyr exp["tau"] = 0.75 # Gyr exp["massformed"] = 9. # log_10(M*/M_solar) exp["metallicity"] = 0.5 # Z/Z_oldsolar dust = {} dust["type"] = "Calzetti" # Define the shape of the attenuation curve dust["Av"] = 0.2 # magnitudes model_components = {} model_components["redshift"] = 1.0 # Observed redshift model_components["exponential"] = exp model_components["dust"] = dust ``` -------------------------------- ### Define Fit Instructions with Parameter Ranges - Python Source: https://github.com/accarnall/bagpipes/blob/master/docs/fit_instructions.rst Demonstrates how to create a fit_instructions dictionary to specify prior ranges for galaxy model parameters like age, metallicity, and redshift. Parameters can be varied within a defined range. ```python burst = {} burst["age"] = (0., 15.) # Vary age from 0 to 15 Gyr burst["metallicity"] = (0., 2.5) # Vary metallicity from 0 to 2.5 Solar burst["massformed"] = (0., 13.) # Vary log_10(mass formed) from 0 to 13 fit_instructions = {} fit_instructions["burst"] = burst # Add the burst sfh component to the fit fit_instructions["redshift"] = (0., 10.) # Vary observed redshift from 0 to 10 ``` -------------------------------- ### Fit spectroscopic data with Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 5 - Fitting spectroscopic data.ipynb This code snippet demonstrates how to initiate the fitting process for spectroscopic data using the Bagpipes library. It takes a galaxy object, fitting instructions, and specifies the 'spectroscopy' run mode. ```python fit = pipes.fit(galaxy, fit_instructions, run="spectroscopy") fit.fit(verbose=False) ``` -------------------------------- ### Generate model spectrum with specified wavelengths (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 1 - Making model galaxies.ipynb Generates a model galaxy spectrum and an output spectroscopic observation by providing an array of wavelengths using the `spec_wavs` keyword argument to the `pipes.model_galaxy` function. The resulting spectrum can then be plotted. ```python model = pipes.model_galaxy(model_components, filt_list=goodss_filt_list, spec_wavs=np.arange(5000., 10000., 5.)) fig = model.plot() ``` -------------------------------- ### Get Photometric Observations using filter curves Source: https://github.com/accarnall/bagpipes/blob/master/docs/model_galaxies.rst This code snippet demonstrates how to obtain predictions for photometric observations by defining a list of filter curves. The filter curve files should contain wavelengths in Angstroms in their first column and relative transmission values in their second. The resulting photometry is accessible as `model.photometry`. ```python import bagpipes as pipes import numpy as np uvista_filt_list = ["uvista/CFHT_u.txt", "uvista/CFHT_g.txt", "uvista/CFHT_r.txt", "uvista/CFHT_i+i2.txt", "uvista/CFHT_z.txt", "uvista/subaru_z", "uvista/VISTA_Y.txt", "uvista/VISTA_J.txt", "uvista/VISTA_H.txt", "uvista/VISTA_Ks.txt", "uvista/IRAC1", "uvista/IRAC2"] model = pipes.model_galaxy(model_components, filt_list=uvista_filt_list) model.plot() ``` -------------------------------- ### Define Fit Instructions with Fixed and Mirrored Parameters - Python Source: https://github.com/accarnall/bagpipes/blob/master/docs/fit_instructions.rst Illustrates how to set up fit_instructions where some parameters are fixed to specific values, while others mirror the values of different parameters. This allows for complex relationships between model components. ```python burst1 = {} burst1["age"] = 0.1 # Fix age to 0.1 Gyr burst1["metallicity"] = (0., 2.5) # Vary metallicity from 0 to 2.5 Solar burst1["massformed"] = (0., 13.) # Vary log_10(mass formed) from 0 to 13 burst2 = {} burst2["age"] = 1.0 # Fix the age to 1.0 Gyr burst2["metallicity"] = "burst1:metallicity" # Mirror burst1:metallicity burst2["massformed"] = (0., 13.) # Vary log_10(mass formed) from 0 to 13 fit_instructions = {} fit_instructions["burst1"] = burst1 # Add the burst1 sfh component to the fit fit_instructions["burst2"] = burst2 # Add the burst2 sfh component to the fit fit_instructions["redshift"] = (0., 10.) # Vary observed redshift from 0 to 10 ``` -------------------------------- ### Analyzing Redshift Effects on Spectral Lines Source: https://github.com/accarnall/bagpipes/blob/master/examples/Further Examples 3 - Variable spectral resolution.ipynb This Python loop iteratively adjusts the redshift of the galaxy model and plots the resulting spectrum. It highlights how changes in redshift affect the resolution of spectral lines, such as the Hbeta and [OIII] lines, demonstrating the impact of variable spectral resolution. ```python for i in range(4): print("Redshift", model_comp["redshift"]) model = pipes.model_galaxy(model_comp, spec_wavs=prism_wavs) fig, ax = model.plot(show=False) ax[0].axvline(5007*(1+model_comp["redshift"])) fig = plt.show() model_comp["redshift"] += 2 ``` -------------------------------- ### List Posterior Samples (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Retrieves a list of all available posterior sample names from the fit object. This is useful for understanding what quantities are calculated by default. ```python list(fit.posterior.samples) ``` -------------------------------- ### Managing Fitting Runs Source: https://github.com/accarnall/bagpipes/blob/master/docs/fitting_galaxies.rst This section explains the 'run' keyword argument, which allows users to manage multiple fitting runs for different models or configurations without overwriting previous results. Outputs are saved in subdirectories based on the provided run name. ```APIDOC ## The `run` Keyword Argument The `run` keyword argument allows users to manage different fitting configurations. By specifying a `run` name, all outputs (posterior samples and plots) will be saved into a subdirectory within ``pipes/posterior/`` and ``pipes/plots/`` corresponding to that run name. ### Purpose * Facilitates fitting a series of different models to data. * Allows switching between fitting runs without deleting previous output posteriors. ### Usage When calling the `fit` method, include the `run` keyword argument: ```python fit(galaxy, fit_instructions, run='my_new_run') ``` This will save outputs to ``pipes/posterior/my_new_run/`` and ``pipes/plots/my_new_run/``. ### Resuming or Overwriting Fits * If a fit with the same `run` name already exists, the code will load the previous results by default, preventing refitting. * To start over for a specific run, delete the corresponding output file (e.g., ``pipes/posterior//.h5``) or change the `run` name. ``` -------------------------------- ### Configure Velocity Dispersion in Bagpipes Fit Instructions Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 5 - Fitting spectroscopic data.ipynb This code snippet shows how to set the velocity dispersion parameters within the 'fit_instructions' dictionary for Bagpipes, specifying a log-uniform prior. ```python fit_instructions["veldisp"] = (1., 1000.) #km/s fit_instructions["veldisp_prior"] = "log_10" ``` -------------------------------- ### Initialize Bagpipes Galaxy Object with Photometry Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 2 - Loading observational data.ipynb This Python code initializes a Bagpipes galaxy object using a specific object ID, the custom `load_goodss` function, and a pre-defined filter list. It also specifies that no spectroscopic data is available (`spectrum_exists=False`). The resulting galaxy object can then be used for further analysis and plotting within Bagpipes. ```python goodss_filt_list = np.loadtxt("filters/goodss_filt_list.txt", dtype="str") galaxy = pipes.galaxy("17433", load_goodss, spectrum_exists=False, filt_list=goodss_filt_list) fig = galaxy.plot() ``` -------------------------------- ### Plot Star Formation History Posterior (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Generates and displays a plot of the posterior star formation history. 'save=False' and 'show=True' ensure the plot is displayed. ```python fig = fit.plot_sfh_posterior(save=False, show=True) ``` -------------------------------- ### Loading Both Photometry and Spectroscopy with Bagpipes in Python Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 2 - Loading observational data.ipynb Defines a function to load both spectroscopic and photometric data for a galaxy. It then creates a Bagpipes galaxy object, providing the combined data loading function and a filter list for photometry. The resulting plot displays both spectrum and photometry. ```python def load_both(ID): spectrum = load_vandels_spec(ID) phot = load_goodss(ID) return spectrum, phot galaxy = pipes.galaxy("017433", load_both, filt_list=goodss_filt_list) fig = galaxy.plot() ``` -------------------------------- ### Define Charlot & Fall Dust Model and Nebular Parameters in Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 5 - Fitting spectroscopic data.ipynb This snippet initializes dictionaries for dust properties using the Charlot & Fall (2001) model and nebular emission parameters, suitable for Bagpipes spectral fitting. ```python dblplaw = {} dblplaw["tau"] = (0., 15.) dblplaw["alpha"] = (0.01, 1000.) dblplaw["beta"] = (0.01, 1000.) dblplaw["alpha_prior"] = "log_10" dblplaw["beta_prior"] = "log_10" dblplaw["massformed"] = (1., 15.) dblplaw["metallicity"] = (0.1, 2.) dblplaw["metallicity_prior"] = "log_10" nebular = {} nebular["logU"] = -3. dust = {} dust["type"] = "CF00" dust["eta"] = 2. dust["Av"] = (0., 2.0) dust["n"] = (0.3, 2.5) dust["n_prior"] = "Gaussian" dust["n_prior_mu"] = 0.7 dust["n_prior_sigma"] = 0.3 fit_instructions = {} fit_instructions["redshift"] = (0.75, 1.25) fit_instructions["t_bc"] = 0.01 fit_instructions["redshift_prior"] = "Gaussian" fit_instructions["redshift_prior_mu"] = 0.9 fit_instructions["redshift_prior_sigma"] = 0.05 fit_instructions["dblplaw"] = dblplaw fit_instructions["nebular"] = nebular fit_instructions["dust"] = dust ``` -------------------------------- ### Generate and plot model galaxy spectrum (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 1 - Making model galaxies.ipynb Generates a model galaxy spectrum using the defined `model_components` and `filt_list`. It then creates plots for the overall model spectrum and the star-formation history. This function requires the `bagpipes` library. ```python model = pipes.model_galaxy(model_components, filt_list=goodss_filt_list) fig = model.plot() fig = model.sfh.plot() ``` -------------------------------- ### Calculate Posterior Median Specific Star-Formation Rate (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Calculates the median of the posterior distribution for the specific star-formation rate (sfr). This involves log-transforming sfr and subtracting stellar mass, requiring 'numpy'. ```python print(np.median(np.log10(fit.posterior.samples["sfr"]) - fit.posterior.samples["stellar_mass"])) ``` -------------------------------- ### Plotting spectroscopic fit results in Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 5 - Fitting spectroscopic data.ipynb This snippet shows how to generate various plots from a fitted Bagpipes object, including the spectrum posterior, calibration, star formation history posterior, and corner plots. These plots aid in visualizing and understanding the fitting results. ```python fig = fit.plot_spectrum_posterior(save=False, show=True) fig = fit.plot_calibration(save=False, show=True) fig = fit.plot_sfh_posterior(save=False, show=True) fig = fit.plot_corner(save=False, show=True) ``` -------------------------------- ### Test Bagpipes Data Loading Function Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 2 - Loading observational data.ipynb This Python code snippet demonstrates how to call the `load_goodss` function with a specific object ID ('17433') and print the returned photometric data. This is used to verify the correct loading and formatting of observational data before passing it to the Bagpipes analysis pipeline. ```python print(load_goodss("17433")) ``` -------------------------------- ### Plot Corner Diagram (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Generates and displays a corner plot showing pairwise posterior distributions of parameters. 'save=False' and 'show=True' display the plot. ```python fig = fit.plot_corner(save=False, show=True) ``` -------------------------------- ### Define Maximum Likelihood Polynomial in Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 5 - Fitting spectroscopic data.ipynb This snippet demonstrates how to define a 'polynomial_max_like' dictionary for Bagpipes, specifying the order for maximum likelihood polynomial fitting to spectral data, as an alternative to full Bayesian fitting. ```python mlpoly = {} mlpoly["type"] = "polynomial_max_like" mlpoly["order"] = 2 ``` -------------------------------- ### Running Bagpipes with MPI Parallelization Source: https://github.com/accarnall/bagpipes/blob/master/docs/fitting_catalogues.rst Demonstrates how to run Bagpipes fitting scripts using MPI for parallel processing. This command allows for distributed computation across multiple processes. ```bash mpirun/mpiexec -n nproc python fit_with_bagpipes.py ``` -------------------------------- ### Integrating Spectroscopic Data with Bagpipes in Python Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 2 - Loading observational data.ipynb Creates a Bagpipes galaxy object using VANDELS spectroscopic data. It specifies that photometry does not exist and uses the `load_vandels_spec` function for data loading. The output is a plot showing the spectroscopic data. ```python galaxy = pipes.galaxy("017433", load_vandels_spec, photometry_exists=False) fig = galaxy.plot() ``` -------------------------------- ### Loading VANDELS Spectroscopic Data in Python Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 2 - Loading observational data.ipynb Loads spectroscopic data from a VANDELS survey FITS file for a given ID. It extracts wavelength, flux, and error, applies a wavelength mask, and then bins the data using the `bin` function. Requires the `astropy.io.fits` module. ```python def load_vandels_spec(ID): """ Loads VANDELS spectroscopic data from file. """ hdulist = fits.open("VANDELS_CDFS_" + ID + ".fits") spectrum = np.c_[hdulist[1].data["WAVE"][0], hdulist[1].data["FLUX"][0], hdulist[1].data["ERR"][0]] mask = (spectrum[:,0] < 9250.) & (spectrum[:,0] > 5250.) return bin(spectrum[mask], 2) ``` -------------------------------- ### Configure Bagpipes for Double Power-Law Model with Nebular Emission Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 4 - Fitting more complex models to photometry.ipynb Sets up the fitting parameters for Bagpipes, including a double power-law star-formation history, dust properties (Calzetti law), and nebular emission. It also defines priors for various parameters, including redshift. ```python dblplaw = {} dblplaw["tau"] = (0., 15.) # Vary the time of peak star-formation between # the Big Bang at 0 Gyr and 15 Gyr later. In # practice the code automatically stops this # exceeding the age of the universe at the # observed redshift. dblplaw["alpha"] = (0.01, 1000.) # Vary the falling power law slope from 0.01 to 1000. dblplaw["beta"] = (0.01, 1000.) # Vary the rising power law slope from 0.01 to 1000. dblplaw["alpha_prior"] = "log_10" # Impose a prior which is uniform in log_10 of the dblplaw["beta_prior"] = "log_10" # parameter between the limits which have been set # above as in Carnall et al. (2017). dblplaw["massformed"] = (1., 15.) dblplaw["metallicity"] = (0., 2.5) dust = {} dust["type"] = "Calzetti" dust["Av"] = (0., 2.) nebular = {} nebular["logU"] = -3. fit_info = {} # The fit instructions dictionary fit_info["redshift"] = (0., 10.) # Vary observed redshift from 0 to 10 fit_info["redshift_prior"] = "Gaussian" # From looking at the spectrum in Example 2 it's fit_info["redshift_prior_mu"] = 1.0 # clear that this object is at around z = 1. We'll fit_info["redshift_prior_sigma"] = 0.25 # include that information with a broad Gaussian # prior centred on redshift 1. Parameters of priors # are passed starting with "parameter_prior_". fit_info["dblplaw"] = dblplaw fit_info["dust"] = dust fit_info["nebular"] = nebular ``` -------------------------------- ### Fit object with a specific run in Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 4 - Fitting more complex models to photometry.ipynb Initializes a fitting process in Bagpipes, specifying a unique 'run' name to save the output posterior and plots separately. This prevents overwriting results from previous fits. ```python fit = pipes.fit(galaxy, fit_info, run="dblplaw_sfh") fit.fit(verbose=False) fig = fit.plot_spectrum_posterior(save=False, show=True) ``` -------------------------------- ### Calculate Posterior Median Stellar Mass (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Calculates the median of the posterior distribution for stellar mass. Requires the 'numpy' library for median calculation. ```python print(np.median(fit.posterior.samples["stellar_mass"])) ``` -------------------------------- ### Apply Gaussian Prior with Limits to Redshift - Python Source: https://github.com/accarnall/bagpipes/blob/master/docs/fit_instructions.rst Demonstrates applying a Gaussian prior to the redshift parameter, while also enforcing the prior to be within a specified range. This ensures the fitted redshift is physically plausible and follows a specific distribution. ```python fit_instructions["redshift"] = (0., 1.) fit_instructions["redshift_prior"] = "Gaussian" fit_instructions["redshift_prior_mu"] = 0.7 fit_instructions["redshift_prior_sigma"] = 0.2 ``` -------------------------------- ### Configure White Scaled Noise Model in Bagpipes Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 5 - Fitting spectroscopic data.ipynb This code sets up a 'white_scaled' noise model for Bagpipes, allowing a multiplicative scaling factor to be fitted to spectroscopic uncertainties, with a log-uniform prior for the scaling parameter. ```python noise = {} noise["type"] = "white_scaled" noise["scaling"] = (1., 10.) noise["scaling_prior"] = "log_10" fit_instructions["noise"] = noise ``` -------------------------------- ### Fit Catalogue with Varying Filter Lists (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 6 - Fitting catalogues of data.ipynb Illustrates fitting a catalogue where each object has a different set of filters. The `cat_filt_list` is a list of filter lists, and `vary_filt_list` must be set to True. Requires NumPy and Bagpipes. ```python import numpy as np import bagpipes as pipes # Assuming IDs, fit_instructions, and load_goodss are defined # Assuming goodss_filt_list is defined list_of_filt_lists = [goodss_filt_list] * 10 redshifts = np.ones(IDs.shape) cat_fit = pipes.fit_catalogue(IDs, fit_instructions, load_goodss, spectrum_exists=False, cat_filt_list=list_of_filt_lists, run="guo_cat_vary_filt_list", redshifts=redshifts, redshift_sigma=0.05, vary_filt_list=True) ``` -------------------------------- ### Fitting Observational Data Source: https://github.com/accarnall/bagpipes/blob/master/docs/fitting_galaxies.rst This section details the 'fit' class used for fitting observational data. It outlines the required inputs, including a galaxy object and a fit_instructions dictionary, and explains how to run the nested sampling algorithm to obtain posterior probability distributions. ```APIDOC ## Introduction to Fitting Observational Data This section describes fitting observational data using the ``fit`` class. It provides links to example notebooks for quick-start guides and advanced options. ### Key Concepts * **fit class**: The primary class for fitting observational data. * **galaxy object**: Represents the observational data for a galaxy. * **fit_instructions dictionary**: Contains instructions for the model fitting process, including parameter fixing, fitting, and prior specifications. ### Resources * `Third iPython notebook example `_ * `Fourth iPython notebook example `_ ``` -------------------------------- ### Load and Prepare CANDELS GOODS South Photometry in Python Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Loads photometric data for a galaxy from the CANDELS GOODS South catalogue. It handles flux and error extraction, missing data, and enforces maximum signal-to-noise ratios. This function is designed to be used with the bagpipes library. ```python import numpy as np import bagpipes as pipes import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline from astropy.io import fits def load_goodss(ID): """ Load CANDELS GOODS South photometry from the Guo et al. (2013) catalogue. """ # load up the relevant columns from the catalogue. cat = np.loadtxt("hlsp_candels_hst_wfc3_goodss-tot-multiband_f160w_v1-1photom_cat.txt", usecols=(10, 13, 16, 19, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 11, 14, 17, 20, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56)) # Find the correct row for the object we want. row = int(ID) - 1 # Extract the object we want from the catalogue. fluxes = cat[row, :15] fluxerrs = cat[row, 15:] # Turn these into a 2D array. photometry = np.c_[fluxes, fluxerrs] # blow up the errors associated with any missing fluxes. for i in range(len(photometry)): if (photometry[i, 0] == 0.) or (photometry[i, 1] <= 0): photometry[i,:] = [0., 9.9*10**99.] # Enforce a maximum SNR of 20, or 10 in the IRAC channels. for i in range(len(photometry)): if i < 10: max_snr = 20. else: max_snr = 10. if photometry[i, 0]/photometry[i, 1] > max_snr: photometry[i, 1] = photometry[i, 0]/max_snr return photometry goodss_filt_list = np.loadtxt("filters/goodss_filt_list.txt", dtype="str") galaxy = pipes.galaxy("17433", load_goodss, spectrum_exists=False, filt_list=goodss_filt_list) fig = galaxy.plot() ``` -------------------------------- ### Plot Spectrum Posterior (Python) Source: https://github.com/accarnall/bagpipes/blob/master/examples/Example 3 - Fitting photometric data with a simple model.ipynb Generates and displays a plot of the posterior spectrum. Setting 'save=False' and 'show=True' displays the plot instead of saving it. ```python fig = fit.plot_spectrum_posterior(save=False, show=True) ```