### Install Prospector (Development) Source: https://github.com/bd-j/prospector/blob/main/README.md Follow these steps to clone the latest development version of Prospector from GitHub and install it. ```bash cd git clone https://github.com/bd-j/prospector cd prospector python -m pip install . ``` -------------------------------- ### Setup Working Directory Source: https://github.com/bd-j/prospector/blob/main/demo/tutorial.rst Copy necessary demo files to your working directory. This prepares the environment for running Prospector fits. ```shell cd cp /demo/demo_* . ``` -------------------------------- ### Verify Prospector Installation Source: https://github.com/bd-j/prospector/blob/main/doc/installation.md After installation, you can verify the installation by importing the prospect module and printing its version. ```python import prospect print(prospect.__version__) ``` -------------------------------- ### Run Prospector Fit with Emcee Source: https://github.com/bd-j/prospector/blob/main/demo/tutorial.rst Command-line example to run a Prospector fit on object number 0 using emcee after an initial optimization. ```shell ``` -------------------------------- ### Run Prospector with Emcee Sampler Source: https://github.com/bd-j/prospector/blob/main/doc/usage.md Example of running a fit using the emcee sampler with a specified number of walkers. ```shell python parameter_file.py --emcee --nwalkers=128 ``` -------------------------------- ### Run Prospector with Dynesty Sampler Source: https://github.com/bd-j/prospector/blob/main/doc/usage.md Example of running a fit using the dynesty nested sampler with a specified target number of effective samples. ```shell python parameter_file.py --nested_sampler dynesty --nested_target_n_effective 512 ``` -------------------------------- ### Get a Source with Prospector Source: https://github.com/bd-j/prospector/blob/main/doc/quickstart.md Instantiate a CSPSpecBasis object to generate galaxy spectra using FSPS. Check which spectral and isochrone libraries are being used. ```python from prospect.sources import CSPSpecBasis sps = CSPSpecBasis(zcontinuous=1) print(sps.ssp.libraries) ``` -------------------------------- ### Install Released Version of Prospector Source: https://github.com/bd-j/prospector/blob/main/doc/installation.md Use pip to install the latest released version of Prospector. This is the recommended method for general use. ```shell python -m pip install astro-prospector ``` -------------------------------- ### Build a Model with Prospector Source: https://github.com/bd-j/prospector/blob/main/doc/quickstart.md Get default parameters for a parametric SFH, add nebular emission parameters, and fix redshift. Adjust the prior distribution for stellar mass. ```python from prospect.models.templates import TemplateLibrary from prospect.models import SpecModel model_params = TemplateLibrary["parametric_sfh"] model_params.update(TemplateLibrary["nebular"]) model_params["zred"]["init"] = obs["redshift"] from prospect.models import priors model_params["mass"]["prior"] = priors.LogUniform(mini=1e6, maxi=1e13) model = SpecModel(model_params) assert len(model.free_params) == 5 print(model) ``` -------------------------------- ### Running Prospector with MPI from Command Line Source: https://github.com/bd-j/prospector/blob/main/doc/usage.md Examples of how to execute a Prospector Python script using MPI from the command line. Use 'mpirun' to specify the number of processors and the desired sampling method (--emcee or --nested_sampler dynesty). ```shell mpirun -np python parameter_file.py --emcee ``` ```shell mpirun -np python parameter_file.py --nested_sampler dynesty ``` -------------------------------- ### Prospector Argument Parser Setup Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Use this snippet to set up a command-line argument parser for Prospector. It includes default arguments and demonstrates how to add custom arguments for specific model parameters. ```python from prospect import prospect_args # - Parser with default arguments - parser = prospect_args.get_parser() # - Add custom arguments - parser.add_argument('--add_duste', action="store_true", help="If set, add dust emission to the model.") parser.add_argument('--ldist', type=float, default=10, help=("Luminosity distance in Mpc. Defaults to 10" "(for case of absolute mags)")) args, _ = parser.parse_known_args() cli_run_params = vars(args) print(cli_run_params) ``` -------------------------------- ### Get Prospector Help Information Source: https://github.com/bd-j/prospector/blob/main/doc/usage.md Command to display available command-line options and help information for Prospector. ```shell python parameter_file.py --help ``` -------------------------------- ### Install Development Version of Prospector Source: https://github.com/bd-j/prospector/blob/main/doc/installation.md Install the latest development version of Prospector and its dependencies into a conda environment. This process involves cloning repositories, setting environment variables, creating and activating a conda environment, and then installing Prospector locally. ```shell # change this if you want to install elsewhere; # or, copy and run this script in the desired location CODEDIR=$PWD cd $CODEDIR # Clone FSPS to get data files git clone git@github.com:cconroy20/fsps export SPS_HOME="$PWD/fsps" # Create and activate environment (here named 'prospector') git clone git@github.com:bd-j/prospector.git cd prospector conda env create -f environment.yml -n prospector conda activate prospector # Install latest development version of prospector python -m pip uninstall astro-prospector python -m pip install . echo "Add 'export SPS_HOME=$SPS_HOME' to your .bashrc" # To use prospector activate the conda environment conda activate prospector ``` -------------------------------- ### Instantiate and Print Prospect Model Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb This snippet demonstrates how to instantiate the `SedModel` using the `build_model` function with specified run parameters and then prints the model object, its initial free parameter vector, and its parameter dictionary. ```python run_params["object_redshift"] = 0.0 run_params["fixed_metallicity"] = None run_params["add_duste"] = True ``` ```python model = build_model(**run_params) print(model) print("\nInitial free parameter vector theta:\n {}".format(model.theta)) print("Initial parameter dictionary:\n{}".format(model.params)) ``` -------------------------------- ### Display command-line help Source: https://github.com/bd-j/prospector/blob/main/demo/tutorial.rst This command displays the full list of available command-line options for the demo_params.py script. ```shell python demo_params.py --help ``` -------------------------------- ### Initialize Prospector Fitting Ingredients Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Prepare the necessary components for Prospector fitting, including observations, spectral synthesis objects, and the model. This step is crucial before initiating any fitting procedures. ```python from prospect.fitting import fit_model # Here we will run all our building functions obs = build_obs(**run_params) sps = build_sps(**run_params) model = build_model(**run_params) # For fsps based sources it is useful to # know which stellar isochrone and spectral library # we are using print(sps.ssp.libraries) ``` -------------------------------- ### Configure and Run Minimization Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Sets up run parameters for minimization using Levenberg-Marquardt and initiates the fitting process. Ensure `lnprobfn` supports returning chi values. ```python # --- start minimization ---- run_params["dynesty"] = False run_params["emcee"] = False run_params["optimize"] = True run_params["min_method"] = 'lm' # We'll start minimization from "nmin" separate places, # the first based on the current values of each parameter and the # rest drawn from the prior. Starting from these extra draws # can guard against local minima, or problems caused by # starting at the edge of a prior (e.g. dust2=0.0) run_params["nmin"] = 2 output = fit_model(obs, model, sps, lnprobfn=lnprobfn, **run_params) print("Done optmization in {}s".format(output["optimization"][1])) ``` -------------------------------- ### Configure emcee Sampling Parameters Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Set up parameters for emcee sampling, including optimization flags, number of walkers, iterations, and burn-in rounds. Ensure `run_params` dictionary is initialized before use. ```python # Set this to False if you don't want to do another optimization # before emcee sampling (but note that the "optimization" entry # in the output dictionary will be (None, 0.) in this case) # If set to true then another round of optmization will be performed # before sampling begins and the "optmization" entry of the output # will be populated. run_params["optimize"] = False run_params["emcee"] = True run_params["dynesty"] = False # Number of emcee walkers run_params["nwalkers"] = 128 # Number of iterations of the MCMC sampling run_params["niter"] = 512 # Number of iterations in each round of burn-in # After each round, the walkers are reinitialized based on the # locations of the highest probablity half of the walkers. run_params["nburn"] = [16, 32, 64] ``` -------------------------------- ### List Available Template Parameter Sets Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Displays all available pre-packaged parameter sets from the `TemplateLibrary`. Use this to explore options before building a custom model. ```python from prospect.models.templates import TemplateLibrary # Look at all the prepackaged parameter sets TemplateLibrary.show_contents() ``` -------------------------------- ### Run emcee Sampling and Print Time Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Initiates the model fitting process using the configured parameters and prints the time taken for sampling. Assumes `obs`, `model`, `sps`, and `lnprobfn` are defined. ```python output = fit_model(obs, model, sps, lnprobfn=lnprobfn, **run_params) print('done emcee in {0}s'.format(output["sampling"][1])) ``` -------------------------------- ### Prospector Citation Source: https://github.com/bd-j/prospector/blob/main/README.md This BibTeX entry should be used when citing the Prospector paper in academic publications. Ensure dependencies are also cited as per installation instructions. ```bibtex @ARTICLE{2021ApJS..254...22J, author = {{Johnson}, Benjamin D. and {Leja}, Joel and {Conroy}, Charlie and {Speagle}, Joshua S.}, title = "{Stellar Population Inference with Prospector}", journal = {\apjs}, keywords = {Galaxy evolution, Spectral energy distribution, Astronomy data modeling, 594, 2129, 1859, Astrophysics - Astrophysics of Galaxies, Astrophysics - Instrumentation and Methods for Astrophysics}, year = 2021, month = jun, volume = {254}, number = {2}, eid = {22}, pages = {22}, doi = {10.3847/1538-4365/abef67}, archivePrefix = {arXiv}, eprint = {2012.01426}, primaryClass = {astro-ph.GA}, adsurl = {https://ui.adsabs.harvard.edu/abs/2021ApJS..254...22J}, adsnote = {Provided by the SAO/NASA Astrophysics Data System} } ``` -------------------------------- ### Get SPS Object from Results Source: https://github.com/bd-j/prospector/blob/main/doc/output.md Retrieves the SPS (Stellar Population Synthesis) object from the Prospector results dictionary. This object is used for generating SEDs. ```python sps = reader.get_sps(res) ``` -------------------------------- ### Get Spectrum and SED with CSPSpecBasis Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Calls the `get_spectrum` method on an SPS object to generate a spectrum and SED for given parameters. This method can accept any FSPS parameter as a keyword argument. ```python sps = build_sps(**run_params) help(sps.get_spectrum) ``` -------------------------------- ### Define a Model Parameter Source: https://github.com/bd-j/prospector/blob/main/doc/models.md Example of defining a single model parameter with its properties like length, initial value, prior, and units. This structure is used to configure model objects. ```python mass = dict(N=1, init=1e9, isfree=True, prior= priors.LogUniform(mini=1e7, maxi=1e12), units="M$_│$ of stars formed.", init_disp=1e8) model_params = dict(mass=mass) ``` -------------------------------- ### Explore and Use Prospector Parameter Templates Source: https://github.com/bd-j/prospector/blob/main/doc/models.md Use TemplateLibrary to view available parameter sets, inspect their contents, and retrieve them for model customization. Instantiate a model using the retrieved parameters. ```python from prospect.models.templates import TemplateLibrary # Show all pre-defined parameter sets TemplateLibrary.show_contents() # Show details on the "parameteric" set of parameters TemplateLibrary.describe("parametric_sfh") # Simply print all parameter specifications in "parametric_sfh" print(TemplateLibrary["parametric_sfh"]) # Actually get a copy of one of the predefined sets model_params = TemplateLibrary["parametric_sfh"] # This dictionary can be updated or modified, to expand the model. model_params.update(TemplateLibrary["nebular"]) # Instantiate a model object from prospect.models import SpecModel model = SpecModel(model_params) ``` -------------------------------- ### MPI Parallelization Command Source: https://github.com/bd-j/prospector/blob/main/doc/advanced.md Use this command to parallelize emcee sampling over multiple processors. Ensure mpi4py is installed against your MPI implementation. The optimal number of walkers is recommended to be 2*N*(N_p-1). ```bash mpirun -np python ``` ```bash mpirun -np python mpi_hello_world.py ``` -------------------------------- ### Build Prospector Model with Nebular Emission Source: https://github.com/bd-j/prospector/blob/main/demo/tutorial.rst Instantiate a SpecModel with parameters from TemplateLibrary, including nebular emission. Free parameters must have associated priors. ```python from prospect.models import SpecModel model_params = TemplateLibrary["parametric_sfh"] # Turn on nebular emission and add associated parameters model_params.update(TemplateLibrary["nebular"]) model_params["gas_logu"]["isfree"] = True model = SpecModel(model_params) print(model) ``` -------------------------------- ### Inspect fit_model Function Signature Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Use the `help()` function to understand the parameters and capabilities of the `fit_model` function. This is useful for configuring optimization, MCMC, or dynesty sampling. ```python from prospect.fitting import fit_model help(fit_model) ``` -------------------------------- ### Python Code for MPI Parallelized Fit Source: https://github.com/bd-j/prospector/blob/main/doc/usage.md This Python script demonstrates how to set up and run a Prospector fit using MPI. It includes importing necessary libraries, configuring MPI communication via schwimmbad, preparing the model and data, and executing the fit in parallel. Ensure mpi4py and schwimmbad are installed. ```python if __name__ == "__main__": import time from prospect.fitting import fit_model from prospect.io import write_results as writer from prospect import prospect_args # Get the default argument parser parser = prospect_args.get_parser() # Add custom arguments that controll the build methods parser.add_argument("--custom_argument_1", ...) # Parse the supplied arguments, convert to a dictionary, and add this file for logging purposes args = parser.parse_args() run_params = vars(args) run_params["param_file"] = __file__ # Build the fit ingredients on each process obs, model, sps, noise = build_all(**run_params) run_params["sps_libraries"] = sps.ssp.libraries # Set up MPI communication try: import mpi4py from mpi4py import MPI from schwimmbad import MPIPool mpi4py.rc.threads = False mpi4py.rc.recv_mprobe = False comm = MPI.COMM_WORLD size = comm.Get_size() withmpi = comm.Get_size() > 1 except ImportError: print('Failed to start MPI; are mpi4py and schwimmbad installed? Proceeding without MPI.') withmpi = False # Evaluate SPS over logzsol grid in order to get necessary data in cache/memory # for each MPI process. Otherwise, you risk creating a lag between the MPI tasks # caching SSPs which can slow down the parallelization if (withmpi) & ('logzsol' in model.free_params): dummy_obs = dict(filters=None, wavelength=None) logzsol_prior = model.config_dict["logzsol"]['prior'] lo, hi = logzsol_prior.range logzsol_grid = np.around(np.arange(lo, hi, step=0.1), decimals=2) sps.update(**model.params) # make sure we are caching the correct IMF / SFH / etc for logzsol in logzsol_grid: model.params["logzsol"] = np.array([logzsol]) _ = model.predict(model.theta, obs=dummy_obs, sps=sps) # ensure that each processor runs its own version of FSPS # this ensures no cross-over memory usage from prospect.fitting import lnprobfn from functools import partial lnprobfn_fixed = partial(lnprobfn, sps=sps) if withmpi: run_params["using_mpi"] = True with MPIPool() as pool: # The dependent processes will run up to this point in the code if not pool.is_master(): pool.wait() sys.exit(0) nprocs = pool.size # The parent process will oversee the fitting output = fit_model(obs, model, sps, noise, pool=pool, queue_size=nprocs, lnprobfn=lnprobfn_fixed, **run_params) else: # without MPI we don't pass the pool output = fit_model(obs, model, sps, noise, lnprobfn=lnprobfn_fixed, **run_params) # Set up an output file and write ts = time.strftime("%y%b%d-%H.%M", time.localtime()) hfile = f"{args.outfile}_worker{comm.rank()}_{ts}_mcmc.h5" writer.write_hdf5(hfile, run_params=run_params, model=model, obs=obs, output["sampling"], output["optimization"], sps=sps ) try: hfile.close() except(AttributeError): pass ``` -------------------------------- ### Set Run Parameters for Data Generation Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Define a dictionary to hold meta-parameters controlling the `build_obs` function, such as signal-to-noise ratio and luminosity distance. ```python run_params = {} run_params["snr"] = 10.0 run_params["ldist"] = 10.0 ``` -------------------------------- ### Run Model Fitting with Dynesty Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Execute the model fitting process using the configured run parameters, which now include dynesty settings. The sampling time is printed upon completion. ```python output = fit_model(obs, model, sps, lnprobfn=lnprobfn, **run_params) print('done dynesty in {0}s'.format(output["sampling"][1])) ``` -------------------------------- ### Accessing and Plotting Prospector Output Source: https://github.com/bd-j/prospector/blob/main/doc/tutorial.md This snippet demonstrates how to select model parameters, generate model spectra and photometry, and plot the observed and modeled SED. It also shows how to calculate and plot the residuals. ```python # Choose the walker and iteration number by hand. walker, iteration = 0, -1 if res["chain"].ndim > 2: # if you used emcee for the inference theta = res['chain'][walker, iteration, :] else: # if you used dynesty theta = res['chain'][iteration, :] # Or get a fair sample from the posterior from prospect.plotting.utils import sample_posterior theta = sample_posterior(res["chain"], weights=res.get("weights", None), nsample=1)[0,:] # Get the modeled spectra and photometry. # These have the same shape as the obs['spectrum'] and obs['maggies'] arrays. (spec, phot), mfrac = model.predict(theta, obs=res['obs'], sps=sps) # mfrac is the ratio of the surviving stellar mass to the formed mass (the ``"mass"`` parameter). # Plot the model SED import matplotlib.pyplot as pl wave = [f.wave_effective for f in res['obs']['filters']] sedfig, sedax = pl.subplots() sedax.plot(wave, res['obs']['maggies'], '-o', label='Observations') sedax.plot(wave, phot, '-o', label='Model at {},{}'.format(walker, iteration)) sedax.set_ylabel("Maggies") sedax.set_xlabel("wavelength") sedax.set_xscale('log') # Plot residuals for this walker and iteration chifig, chiax = pl.subplots() chi = (res['obs']['maggies'] - phot) / res['obs']['maggies_unc'] chiax.plot(wave, chi, 'o') chiax.set_ylabel("Chi") chiax.set_xlabel("wavelength") chiax.set_xscale('log') ``` -------------------------------- ### Show Default Prospector Arguments Source: https://github.com/bd-j/prospector/blob/main/doc/faq.md Use this to view the default settings for Prospector, which can be helpful for understanding configuration options. ```python from prospect.utils import prospect_args prospect_args.show_default_args() ``` -------------------------------- ### Check Prospector and dependency versions Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Prints the versions of numpy, scipy, h5py, fsps, and prospect to ensure compatibility. This is useful for debugging and reproducibility. ```python vers = (np.__version__, scipy.__version__, h5py.__version__, fsps.__version__, prospect.__version__) print("numpy: {}\nscipy: {}\nh5py: {}\nfsps: {}\nprospect: {}".format(*vers)) ``` -------------------------------- ### Import Prospect Library Source: https://github.com/bd-j/prospector/blob/main/README.md This is the standard Python import statement to begin using the Prospector library in your scripts. ```python import prospect ``` -------------------------------- ### Implement Logarithmic Transformation for SF Timescale Source: https://github.com/bd-j/prospector/blob/main/doc/models.md Set up a parameter transformation to sample in the logarithm of the SF timescale (`logtau`) instead of the timescale itself (`tau`). The `tau` parameter is fixed and depends on `logtau`. ```python def delogify(logtau=0, **extras): return 10**logtau model_params["tau"]["isfree"] = False model_params["tau"]["depends_on"] = delogify model_params["logtau"] = dict(N=1, init=0, isfree=True, prior=priors.TopHat(mini=-1, maxi=1)) ``` -------------------------------- ### Configure Dynesty for Nested Sampling Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Set parameters to enable and configure dynamic nested sampling using dynesty. Ensure other sampling methods like emcee are disabled. ```python run_params["dynesty"] = True run_params["optmization"] = False run_params["emcee"] = False run_params["nested_method"] = "rwalk" run_params["nlive_init"] = 400 run_params["nlive_batch"] = 200 run_params["nested_dlogz_init"] = 0.05 run_params["nested_posterior_thresh"] = 0.05 run_params["nested_maxcall"] = int(1e7) ``` -------------------------------- ### Prepare observation data for Prospector Source: https://github.com/bd-j/prospector/blob/main/doc/quickstart.md Convert SDSS magnitudes to maggies, calculate flux uncertainties, load filter curves using sedpy, and create Prospector Photometry and Spectrum objects. The redshift is also stored. ```python from sedpy.observate import load_filters from prospect.observation import Photometry, Spectrum filters = load_filters([f"sdss_{b}0" for b in bands]) maggies = np.array([10**(-0.4 * cat[0][f"cModelMag_{b}"]) for b in bands]) magerr = np.array([cat[0][f"cModelMagErr_{b}"] for b in bands]) magerr = np.hypot(magerr, 0.05) pdat = Photometry(filters=filters, flux=maggies, uncertainty=magerr*maggies/1.086, name=f'sdss_phot_specobjID{cat[0]["specObjID"]}') sdat = Spectrum(wavelength=None, flux=None, mask=None, uncertainty=None) observations = [sdat, pdat] for obs in observations: obs.redshift = shdus[2].data[0]["z"] ``` -------------------------------- ### Import Prospector core packages Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Imports the main packages used by Prospector: fsps for stellar population synthesis, sedpy for spectral calculations, and prospect for likelihood evaluations and parameter sampling. ```python import fsps import sedpy import prospect ``` -------------------------------- ### Instantiate and Use a Prior Distribution Source: https://github.com/bd-j/prospector/blob/main/doc/api/models_api.md Instantiate a Prior object and use it to calculate the ln-prior-probability of a given value. The `param` argument specifies the parameter name, and `value` is the variable for which to calculate the probability. ```python ln_prior_prob = Prior(param=par)(value) ``` -------------------------------- ### Run nested sampling fit with Dynesty Source: https://github.com/bd-j/prospector/blob/main/demo/tutorial.rst This command runs a nested sampling fit using the 'dynesty' sampler for object ID 0, saving output to demo_obj0_dynesty. ```shell python demo_params.py --objid=0 --nested_sampler dynesty \ --outfile=demo_obj0_dynesty ``` -------------------------------- ### Build Prospect SedModel Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Use this function to construct a prospect.models.SedModel object. Customize parameters like redshift, luminosity distance, metallicity, and dust properties. It supports adding dust emission and fixing metallicity or redshift. ```python def build_model(object_redshift=None, ldist=10.0, fixed_metallicity=None, add_duste=False, **extras): """Build a prospect.models.SedModel object :param object_redshift: (optional, default: None) If given, produce spectra and observed frame photometry appropriate for this redshift. Otherwise, the redshift will be zero. :param ldist: (optional, default: 10) The luminosity distance (in Mpc) for the model. Spectra and observed frame (apparent) photometry will be appropriate for this luminosity distance. :param fixed_metallicity: (optional, default: None) If given, fix the model metallicity (:math:`log(Z/Z_sun)`) to the given value. :param add_duste: (optional, default: False) If `True`, add dust emission and associated (fixed) parameters to the model. :returns model: An instance of prospect.models.SedModel """ from prospect.models.sedmodel import SedModel from prospect.models.templates import TemplateLibrary from prospect.models import priors # Get (a copy of) one of the prepackaged model set dictionaries. # This is, somewhat confusingly, a dictionary of dictionaries, keyed by parameter name model_params = TemplateLibrary["parametric_sfh"] # Now add the lumdist parameter by hand as another entry in the dictionary. # This will control the distance since we are setting the redshift to zero. # In `build_obs` above we used a distance of 10Mpc to convert from absolute to apparent magnitudes, # so we use that here too, since the `maggies` are appropriate for that distance. model_params["lumdist"] = {"N": 1, "isfree": False, "init": ldist, "units":"Mpc"} # Let's make some changes to initial values appropriate for our objects and data model_params["zred"]["init"] = 0.0 model_params["dust2"]["init"] = 0.05 model_params["logzsol"]["init"] = -0.5 model_params["tage"]["init"] = 13. model_params["mass"]["init"] = 1e8 # These are dwarf galaxies, so lets also adjust the metallicity prior, # the tau parameter upward, and the mass prior downward model_params["dust2"]["prior"] = priors.TopHat(mini=0.0, maxi=2.0) model_params["tau"]["prior"] = priors.LogUniform(mini=1e-1, maxi=1e2) model_params["mass"]["prior"] = priors.LogUniform(mini=1e6, maxi=1e10) # If we are going to be using emcee, it is useful to provide a # minimum scale for the cloud of walkers (the default is 0.1) model_params["mass"]["disp_floor"] = 1e6 model_params["tau"]["disp_floor"] = 1.0 model_params["tage"]["disp_floor"] = 1.0 # Change the model parameter specifications based on some keyword arguments if fixed_metallicity is not None: # make it a fixed parameter model_params["logzsol"]["isfree"] = False #And use value supplied by fixed_metallicity keyword model_params["logzsol"]['init'] = fixed_metallicity if object_redshift is not None: # make sure zred is fixed model_params["zred"]['isfree'] = False # And set the value to the object_redshift keyword model_params["zred"]['init'] = object_redshift if add_duste: # Add dust emission (with fixed dust SED parameters) # Since `model_params` is a dictionary of parameter specifications, # and `TemplateLibrary` returns dictionaries of parameter specifications, # we can just update `model_params` with the parameters described in the # pre-packaged `dust_emission` parameter set. model_params.update(TemplateLibrary["dust_emission"]) # Now instantiate the model object using this dictionary of parameter specifications model = SedModel(model_params) return model ``` -------------------------------- ### Generate and Plot Model SED Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Generates the model SED at initial parameter values and plots it alongside observed photometry and filter transmission curves. Ensure 'model', 'obs', and 'sps' objects are properly initialized before use. ```python # Generate the model SED at the initial value of theta theta = model.theta.copy() initial_spec, initial_phot, initial_mfrac = model.sed(theta, obs=obs, sps=sps) title_text = ','.join(["{}={}".format(p, model.params[p][0]) for p in model.free_params]) a = 1.0 + model.params.get('zred', 0.0) # cosmological redshifting # photometric effective wavelengths wphot = obs["phot_wave"] # spectroscopic wavelengths if obs["wavelength"] is None: # *restframe* spectral wavelengths, since obs["wavelength"] is None wspec = sps.wavelengths wspec *= a #redshift them else: wspec = obs["wavelength"] # establish bounds xmin, xmax = np.min(wphot)*0.8, np.max(wphot)/0.8 temp = np.interp(np.linspace(xmin,xmax,10000), wspec, initial_spec) ymin, ymax = temp.min()*0.8, temp.max()/0.4 figure(figsize=(16,8)) # plot model + data loglog(wspec, initial_spec, label='Model spectrum', lw=0.7, color='navy', alpha=0.7) errorbar(wphot, initial_phot, label='Model photometry', marker='s',markersize=10, alpha=0.8, ls='', lw=3, markerfacecolor='none', markeredgecolor='blue', markeredgewidth=3) errorbar(wphot, obs['maggies'], yerr=obs['maggies_unc'], label='Observed photometry', marker='o', markersize=10, alpha=0.8, ls='', lw=3, ecolor='red', markerfacecolor='none', markeredgecolor='red', markeredgewidth=3) title(title_text) # plot Filters for f in obs['filters']: w, t = f.wavelength.copy(), f.transmission.copy() t = t / t.max() t = 10**(0.2*(np.log10(ymax/ymin)))*t * ymin loglog(w, t, lw=3, color='gray', alpha=0.7) # prettify xlabel('Wavelength [A]') ylabel('Flux Density [maggies]') xlim([xmin, xmax]) ylim([ymin, ymax]) legend(loc='best', fontsize=20) tight_layout() ``` -------------------------------- ### Build and Visualize Observational Data Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Builds an observation dictionary using run parameters and plots the observed photometry along with the data intended for fitting and filter transmissions. Requires `build_obs` function and `numpy`, `matplotlib.pyplot`. ```python # Build the obs dictionary using the meta-parameters obs = build_obs(**run_params) # Look at the contents of the obs dictionary print("Obs Dictionary Keys:\n\n{}\\n".format(obs.keys())) print("--------\nFilter objects:\n") print(obs["filters"]) # --- Plot the Data ---- # This is why we stored these... wphot = obs["phot_wave"] # establish bounds xmin, xmax = np.min(wphot)*0.8, np.max(wphot)/0.8 ymin, ymax = obs["maggies"].min()*0.8, obs["maggies"].max()/0.4 figure(figsize=(16,8)) # plot all the data plot(wphot, obs['maggies'], label='All observed photometry', marker='o', markersize=12, alpha=0.8, ls='', lw=3, color='slateblue') # overplot only the data we intend to fit mask = obs["phot_mask"] errorbar(wphot[mask], obs['maggies'][mask], yerr=obs['maggies_unc'][mask], label='Photometry to fit', marker='o', markersize=8, alpha=0.8, ls='', lw=3, ecolor='tomato', markerfacecolor='none', markeredgecolor='tomato', markeredgewidth=3) # plot Filters for f in obs['filters']: w, t = f.wavelength.copy(), f.transmission.copy() t = t / t.max() t = 10**(0.2*(np.log10(ymax/ymin)))*t * ymin loglog(w, t, lw=3, color='gray', alpha=0.7) # prettify xlabel('Wavelength [A]') ylabel('Flux Density [maggies]') xlim([xmin, xmax]) ylim([ymin, ymax]) xscale("log") yscale("log") legend(loc='best', fontsize=20) tight_layout() ``` -------------------------------- ### Import posterior sampling packages Source: https://github.com/bd-j/prospector/blob/main/demo/InteractiveDemo.ipynb Imports external packages commonly used for posterior sampling in Prospector, specifically emcee and dynesty. ```python import emcee import dynesty ```