### Import Libraries for Redback Example Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/pre_executed/redback_example.html Imports necessary libraries for using the redback package with LightCurveLynx. Ensure bilby and redback are installed separately. ```python import numpy as np import matplotlib.pyplot as plt from redback import model_library from redback.priors import get_priors from lightcurvelynx.astro_utils.passbands import PassbandGroup from lightcurvelynx.math_nodes.np_random import NumpyRandomFunc from lightcurvelynx.math_nodes.ra_dec_sampler import ObsTableRADECSampler from lightcurvelynx.obstable.opsim import OpSim from lightcurvelynx.simulate import simulate_lightcurves from lightcurvelynx.survey_info import SurveyInfo from lightcurvelynx.models.redback_models import RedbackWrapperModel from lightcurvelynx.utils.extrapolate import ConstantPadding from lightcurvelynx.utils.plotting import plot_lightcurves from lightcurvelynx import _LIGHTCURVELYNX_BASE_DATA_DIR # Reset the matplotlib configuration plt.rcParams.update(plt.rcParamsDefault) # Set the seed so we don't get different results each time we run the notebook. np.random.seed(42) ``` -------------------------------- ### Install Project Dependencies Source: https://lightcurvelynx.readthedocs.io/en/latest/contributing.html Install the project in editable mode with development dependencies and set up pre-commit hooks for code quality checks. ```bash >> pip install -e .'[dev]' >> pre-commit install ``` -------------------------------- ### Environment Setup Messages Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/pre_executed/redback_example.html Displays messages related to optional package installations and the versions of bilby and redback being used. ```text No module named 'lalsimulation' lalsimulation is not installed. Some EOS based models will not work. Please use bilby eos or pass your own EOS generation class to the model swifttools not available. You will not be able to download Swift afterglow data via API. 10:00 bilby INFO : Running bilby version: 2.8.0 10:00 redback INFO : Running redback version: 1.16.0 ``` -------------------------------- ### Check EzTaoX and JAX Installation Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/eztaox_models.html Ensures that the necessary EzTaoX and JAX packages are installed before proceeding. Raises an ImportError if either is missing, providing installation instructions. ```python if importlib.util.find_spec("eztaox") is None: # pragma: no cover raise ImportError( "The EzTaoX package is required to use the EzTaoXWrapperModel. " "Please install it from https://github.com/LSST-AGN-Variability/EzTaoX" ) if importlib.util.find_spec("jax") is None: # pragma: no cover raise ImportError( "JAX is required to use the EzTaoXWrapperModel class, please " "install with `pip install jax` or `conda install conda-forge::jax`" ) ``` -------------------------------- ### Construct LSSTObsTable from CCDVisit Table (File Example) Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/obstable/lsst_obstable/index.html Example of constructing an LSSTObsTable from a CCDVisit table read from a file using a utility function. ```python from lightcurvelynx.utils.io_utils import read_sqlite_table table = read_sqlite_table("path_to_file.db", sql_query="SELECT * FROM observations") ``` -------------------------------- ### Install All Optional Dependencies with Pip Source: https://lightcurvelynx.readthedocs.io/en/latest/index.html Installs LightCurveLynx along with all optional dependencies using pip. This is useful for accessing extended functionalities. ```bash python -m pip install 'lightcurvelynx[all]' ``` -------------------------------- ### Install LightCurveLynx with Pip Source: https://lightcurvelynx.readthedocs.io/en/latest/index.html Installs LightCurveLynx and its dependencies using pip. It's recommended to use a virtual environment. ```bash # Create a virtual environment python3 -m venv ~/envs/lightcurvelynx # Activate it source ~/envs/lightcurvelynx/bin/activate # Install from PyPI python -m pip install lightcurvelynx ``` -------------------------------- ### Initialize SALT2ColorLaw Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/astro_utils/salt2_color_law.html Initializes the SALT2ColorLaw object with wavelength bounds and coefficients. Requires JAX to be installed. ```python import numpy as np try: import jax.numpy as jnp except ImportError as err: raise ImportError( "JAX is required to use the SALT2ColorLaw class, please " "install with `pip install jax` or `conda install conda-forge::jax`" ) from err # Constants used in SALT2ColorLaw computations _SALT2CL_B = 4302.57 _SALT2CL_V = 5428.55 _WAVESCALE = 1.0 / (_SALT2CL_V - _SALT2CL_B) class SALT2ColorLaw: def __init__(self, wave_min, wave_max, coeffs): coeffs = np.array(coeffs) num_coeffs = min(len(coeffs), 6) padded_coeffs = np.zeros(7) padded_coeffs[1 : (num_coeffs + 1)] = np.array(coeffs)[0:num_coeffs] padded_coeffs[0] = 1.0 - np.sum(padded_coeffs) self.coeffs = jnp.asarray(padded_coeffs) self.scaled_wave_min = (wave_min - _SALT2CL_B) * _WAVESCALE self.scaled_wave_max = (wave_max - _SALT2CL_B) * _WAVESCALE self.exponents = jnp.arange(1, 8, 1) self.value_at_min = jnp.sum(self.coeffs * jnp.power(self.scaled_wave_min, self.exponents)) self.value_at_max = jnp.sum(self.coeffs * jnp.power(self.scaled_wave_max, self.exponents)) dcoeffs = jnp.arange(2, 8, 1) * self.coeffs[1:7] dexponents = jnp.arange(1, 7, 1) self.deriv_at_min = jnp.sum(dcoeffs * jnp.power(self.scaled_wave_min, dexponents)) + self.coeffs[0] self.deriv_at_max = jnp.sum(dcoeffs * jnp.power(self.scaled_wave_max, dexponents)) + self.coeffs[0] ``` -------------------------------- ### Construct LSSTObsTable from CCDVisit Table (RSP Example) Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/obstable/lsst_obstable/index.html Example of constructing an LSSTObsTable from a CCDVisit table obtained via the LSST Science Platform (RSP) TAP service. ```python from lsst.rsp import get_tap_service service = get_tap_service("tap") table = service.search("SELECT * FROM dp1.CcdVisit").to_table().to_pandas() ``` -------------------------------- ### Build Documentation Locally Source: https://lightcurvelynx.readthedocs.io/en/latest/contributing.html Build the project's documentation locally by navigating to the docs directory and running the make html command. This is useful for verifying changes to documentation files. ```bash cd docs make html ``` -------------------------------- ### BilbyPriorNode Initialization Example Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/math_nodes/bilby_priors/index.html Demonstrates how to initialize the BilbyPriorNode with a prior dictionary and an optional seed. The prior dictionary maps parameter names to their distributions. ```python prior = BilbyPriorNode(prior=prior_dict, seed=123) ``` -------------------------------- ### BasicMathNode Initialization Example Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/math_nodes/basic_math_node.html Instantiate BasicMathNode with an expression and input variables. The expression uses standard mathematical operators and functions, with variables matching the provided kwargs. ```python my_node = BasicMathNode( "redshift + 10.0 * sin(phase)", redshift=host.redshift, phase=source.phase, ) ``` -------------------------------- ### Generate Redback Simulation Output Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/pre_executed/wrapping_redback.html Calls a redback model with specified parameters and sets output_format to 'sncosmo_source' to get a queryable SED grid. Ensure redback and its dependencies are installed. ```python rb_result = rb_model( np.linspace(-200, 200, 1000), # times redshift=0.01, mej=0.05, vej=0.2, kappa=1.0, output_format="sncosmo_source", ) print(rb_result) ``` -------------------------------- ### Add Dust Extinction using dust_extinction package Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/adding_effects.html Use ExtinctionEffect with the 'dust_extinction' backend to model dust extinction. Requires the 'dust_extinction' package to be installed. This example links a dust map to the model to provide 'ebv' values for the extinction calculation. ```python import importlib if importlib.util.find_spec("dust_extinction") is None: print("Skipping dust extinction example since dust_extinction is not installed.") states2 = None else: from lightcurvelynx.astro_utils.dustmap import ConstantHemisphereDustMap, DustmapWrapper from lightcurvelynx.effects.extinction import ExtinctionEffect model2 = ConstantSEDModel( brightness=100.0, ra=45.0, dec=20.0, redshift=0.0, node_label="object", ) # Create a dust map that pulls ebv values using the object's (RA, dec) values. dust_map = ConstantHemisphereDustMap(north_ebv=0.8, south_ebv=0.5) dust_map_node = DustmapWrapper( dust_map, ra=model2.ra, dec=model2.dec, node_label="dust_map", ) # Create an add an extinction effect. ext_effect = ExtinctionEffect( extinction_model="CCM89", ebv=dust_map_node, frame="rest", r_v=3.1, backend="dust_extinction", ) model2.add_effect(ext_effect) # Sample the model. times = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) wavelengths = np.array([7000.0, 5200.0]) states2 = model2.sample_parameters(num_samples=3) model2.evaluate_sed(times, wavelengths, states2) ``` -------------------------------- ### Initialize BilbyPriorNode with a dictionary Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/math_nodes/bilby_priors.html Demonstrates how to initialize the BilbyPriorNode by passing a dictionary of priors. Ensure the 'bilby' package is installed. ```python from lightcurvelynx.math_nodes.bilby_priors import BilbyPriorNode from bilby.core.prior import PriorDict prior_dict = PriorDict({ "mass_1": bilby.prior.Uniform(10, 50, name="mass_1"), "mass_2": bilby.prior.Uniform(10, 50, name="mass_2") }) prior_node = BilbyPriorNode(prior=prior_dict) ``` -------------------------------- ### Add Dust Extinction using extinction package Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/adding_effects.html Use ExtinctionEffect with the 'extinction' backend to model dust extinction. Requires the 'extinction' package to be installed. This example demonstrates creating an ExtinctionEffect with a specific extinction model ('calzetti00') and linking it to a dust map. ```python import importlib if importlib.util.find_spec("extinction") is None: print("Skipping extinction example since extinction is not installed.") states3 = None else: from lightcurvelynx.astro_utils.dustmap import ConstantHemisphereDustMap, DustmapWrapper from lightcurvelynx.effects.extinction import ExtinctionEffect model3 = ConstantSEDModel( brightness=100.0, ra=45.0, dec=20.0, redshift=0.0, node_label="object", ) # Create a dust map that pulls ebv values using the object's (RA, dec) values. dust_map = ConstantHemisphereDustMap(north_ebv=0.8, south_ebv=0.5) dust_map_node = DustmapWrapper( dust_map, ra=model3.ra, dec=model3.dec, node_label="dust_map", ) # Create an add an extinction effect. ext_effect = ExtinctionEffect( extinction_model="calzetti00", ebv=dust_map_node, frame="rest", r_v=3.1, backend="extinction", ) model3.add_effect(ext_effect) # Sample the model. times = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) wavelengths = np.array([7000.0, 5200.0]) states3 = model3.sample_parameters(num_samples=3) model3.evaluate_sed(times, wavelengths, states3) print(states3) ``` -------------------------------- ### get Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/sncosmo_models.html Get the value of a specific parameter. ```APIDOC ## get ### Description Get the value of a specific parameter. ### Method GET (assumed) ### Endpoint /get (assumed) ### Parameters #### Query Parameters - **name** (str) - Required - The name of the parameter. - **kwargs** (dict) - Optional - Additional keyword arguments, not used in this method. ### Response #### Success Response (200) - **Parameter Value** (any) - The parameter value. ``` -------------------------------- ### Instantiate and Use FunctionNode Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/base_models/index.html Demonstrates how to create a FunctionNode with a function and its arguments, and how to call it to get a value. Arguments must be defined during instantiation. ```python >>> my_func = TDFunc(random.randint, a=1, b=10) >>> value1 = my_func() # Sample from default range >>> value2 = my_func(b=20) # Sample from extended range ``` ```python my_func = TDFunc(random.randint, a=1) value1 = my_func(b=10.0) ``` -------------------------------- ### Initialize SinWaveModel with Random Parameters Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/introduction.html Demonstrates initializing a SinWaveModel with fixed and randomly sampled parameters using NumpyRandomFunc. Use this to define a simulated astronomical source with varying properties. ```python from lightcurvelynx.math_nodes.np_random import NumpyRandomFunc from lightcurvelynx.models.basic_models import SinWaveModel model = SinWaveModel( brightness=2000.0, amplitude=200.0, frequency=NumpyRandomFunc("uniform", low=0.01, high=0.1), t0=NumpyRandomFunc("uniform", low=0.0, high=10.0), ra=NumpyRandomFunc("normal", loc=200.5, scale=0.01), dec=NumpyRandomFunc("normal", loc=-50.0, scale=0.01), node_label="sin_wave_model", ) ``` -------------------------------- ### Install LightCurveLynx with Conda Source: https://lightcurvelynx.readthedocs.io/en/latest/index.html Installs LightCurveLynx and its dependencies using conda. It's recommended to use a virtual environment. ```bash # Create a virtual environment conda create -p lightcurvelynx python=3.12 # Activate it conda activate lightcurvelynx # Install from conda-forge channel conda install conda-forge::lightcurvelynx ``` -------------------------------- ### Install Optional Dependencies with Conda Source: https://lightcurvelynx.readthedocs.io/en/latest/index.html Installs LightCurveLynx and specific optional dependencies like pzflow and sncosmo using conda. ```bash conda install conda-forge::lightcurvelynx conda-forge::pzflow conda-forge::sncosmo ``` -------------------------------- ### Setup Simulation with Saturation Thresholds Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/saturation.html This code sets up the necessary components for a simulation, including passbands, fake observation data, and custom saturation thresholds. It then initializes an OpSim object with these parameters and creates a SurveyInfo object. ```python import numpy as np from lightcurvelynx.astro_utils.passbands import PassbandGroup from lightcurvelynx.astro_utils.mag_flux import mag2flux from lightcurvelynx.obstable.opsim import OpSim from lightcurvelynx.survey_info import SurveyInfo # Usually we would not hardcode the path to the passband files, but for this demo we will use a relative path # to the test data directory so that we do not have to download the files. table_dir = "../../tests/lightcurvelynx/data/passbands" passband_group = PassbandGroup.from_preset(preset="LSST", table_dir=table_dir) # Generate fake observation data for testing. num_times = 200 times = 60676.0 + np.arange(num_times) * 0.25 # 200 observations spaced 0.25 days apart obsdata = { "time": times, "ra": np.full(num_times, 0.0), "dec": np.full(num_times, -10.0), "filter": np.tile(["r", "g", "i", "z"], num_times // 4), "zp": np.full(num_times, 1.0), "seeing": np.full(num_times, 1.12), "skybrightness": np.full(num_times, 24.0), "exptime": np.full(num_times, 15.0), "nexposure": np.full(num_times, 2), } # Define saturation thresholds for each passband. These are not the actual LSST saturation thresholds, # but exagerated values for demonstration purposes. saturation_thresholds = { "u": 14.0, "g": 15.0, "r": 16.0, "i": 17.0, "z": 22.0, "y": 19.0, } for f, lim in saturation_thresholds.items(): print(f"Saturation threshold for {f}-band: {lim} mag = {mag2flux(lim):.2e} nJy") opsim = OpSim(obsdata, saturation_mags=saturation_thresholds) print(f"Created OpSim with {len(opsim)} observations.") survey_info = SurveyInfo(obstable=opsim, passbands=passband_group, survey_name="LSST") ``` -------------------------------- ### Install Project Dependencies (macOS) Source: https://lightcurvelynx.readthedocs.io/en/latest/contributing.html On macOS, ensure single quotes are used around '.[dev]' when installing development dependencies. ```bash $ pip install -e '.[dev]' ``` -------------------------------- ### PassbandGroup Initialization with Passband Objects Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/astro_utils/passbands.html Demonstrates how to initialize a PassbandGroup with existing Passband objects. This is useful when you have already created Passband instances and want to group them. ```python pb1 = Passband(survey='LSST', filter_name='u', table_path='path/to/u.txt') pb2 = Passband(survey='LSST', filter_name='g', table_path='path/to/g.txt') passband_group = PassbandGroup([pb1, pb2]) ``` -------------------------------- ### Instantiate and Sample Toy AGN Model Parameters Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/adding_models.html This snippet shows how to instantiate the custom ToyAGN model, defining the 'blackhole_mass' using a Gaussian distribution from NumpyRandomFunc. It then samples the model's parameters and prints the results, illustrating the generated blackhole mass and derived accretion rate. ```python agn_model = ToyAGN( blackhole_mass=NumpyRandomFunc( "normal", loc=1000.0 * constants.M_sun.cgs.value, scale=50.0 * constants.M_sun.cgs.value ), node_label="toy_agn", ) samples = agn_model.sample_parameters(num_samples=5) print(samples) ``` -------------------------------- ### Create SIMSEDModel from Directory Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/pre_executed/snana_example.html Loads SED templates from a specified directory and configures source parameters like RA, Dec, start time (t0), redshift, and cosmology. Requires the SIMSEDModel class and sampler nodes. ```python # We create the sampling area using a MOC that covers the region observed in the OpSim. coverage_moc = opsim_db.build_moc(radius=1.0) # 1 degree radius around each field center ra_dec_sampler = ApproximateMOCSampler(coverage_moc) # Use a uniform sampler for the starting time (t0) of activity. All events will # start within the first 20 days of the survey (between MJD 61406 and 61426). time_sampler = NumpyRandomFunc("uniform", low=61406, high=61426, node_label="time_sampler") source = SIMSEDModel.from_dir( # The directory containing the SIMSED files. _LIGHTCURVELYNX_BASE_DATA_DIR / "model_files" / "SIMSED.SNIbc-MOSFIT", # The other parameters for the model. ra=ra_dec_sampler.ra, dec=ra_dec_sampler.dec, t0=time_sampler, node_label="source", redshift=NumpyRandomFunc("uniform", low=0.1, high=0.6), cosmology=Planck18, ) ``` -------------------------------- ### Get Maximum Supported Phase Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/lightcurve_template_model.html Gets the maximum supported phase of the model for a given filter in days. Raises an error if the filter is not provided. ```python def maxphase(self, filter=None, **kwargs): """Get the maximum supported phase of the model (for this filter) in days. Parameters ---------- filter : str The name of the filter (required). An error is raised if no value is provided. graph_state : GraphState, optional An object mapping graph parameters to their values. If provided, the function will use the graph state to compute the maximum wavelength. **kwargs : dict Additional keyword arguments, not used in this method. Returns ------- maximum : float or None The maximum phase of the model (in days) or None if the model does not have a defined maximum phase. """ if filter is None: raise ValueError("Filter must be provided to compute maxphase.") if self.lightcurves.has_time_bounds: return self.lightcurves.max_times[filter] else: return None ``` -------------------------------- ### PassbandGroup Initialization with Dictionary Parameters Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/astro_utils/passbands.html Shows how to initialize a PassbandGroup using dictionaries that define passband parameters. This method is convenient when passband data is not yet loaded into Passband objects. ```python passband_group = PassbandGroup([ {'survey': 'LSST', 'filter_name': 'u', 'table_path': 'path/to/u.txt'}, {'survey': 'LSST', 'filter_name': 'g', 'table_path': 'path/to/g.txt'} ]) ``` -------------------------------- ### Get Minimum Supported Phase Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/lightcurve_template_model.html Gets the minimum supported phase of the model for a given filter in days. Raises an error if the filter is not provided. ```python def minphase(self, filter=None, **kwargs): """Get the minimum supported phase of the model (for this filter) in days. Parameters ---------- filter : str The name of the filter (required). An error is raised if no value is provided. **kwargs : dict Additional keyword arguments, not used in this method. Returns ------- minphase : float or None The minimum phase of the model (in days) or None if the model does not have a defined minimum phase. """ if filter is None: raise ValueError("Filter must be provided to compute minphase.") if self.lightcurves.has_time_bounds: return self.lightcurves.min_times[filter] else: return None ``` -------------------------------- ### Initialize SALT2JaxModel Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/salt2_jax.html Initializes the SALT2JaxModel with parameters and loads necessary data files for spectral templates and color correction. Specify model directory and filenames if not using defaults. ```python from pathlib import Path from astropy import units as u from citation_compass import CiteClass from lightcurvelynx.astro_utils.salt2_color_law import SALT2ColorLaw from lightcurvelynx.astro_utils.unit_utils import flam_to_fnu from lightcurvelynx.models.physical_model import SEDModel class SALT2JaxModel(SEDModel, CiteClass): """A SALT2 model implemented with JAX for it can use auto-differentiation. The model is defined in (Guy J., 2007) as:: flux(time, wave) = x0 * [M0(time, wave) + x1 * M1(time, wave)] * exp(c * CL(wave)) where ``x0``, ``x1``, and ``c`` are given parameters, ``M0`` is the average spectral sequence, ``M1`` is the first compoment to describe variability, and ``CL`` is the average color correction law. We use the formulation in sncosmo where CL is defined such that:: flux(time, wave) = x0 * [M0(time, wave) + x1 * M1(time, wave)] * 10 ** (-0.4 * c * CL(wave)) This class is based on the sncosmo implementation at: https://github.com/sncosmo/sncosmo/blob/v2.10.1/sncosmo/models.py The wrapped sncosmo version in sncosmo_models.py is faster and should be used when auto-differentiation is not needed. Parameterized values include: * c - The SALT2 c parameter. * dec - The object's declination in degrees. [from BasePhysicalModel] * distance - The object's luminosity distance in pc. [from BasePhysicalModel] * period - The period of the source, in days. * ra - The object's right ascension in degrees. [from BasePhysicalModel] * redshift - The object's redshift. [from BasePhysicalModel] * t0 - The t0 of the zero phase, date. [from BasePhysicalModel] * x0 - The SALT2 x0 parameter. * x1 - The SALT2 x1 parameter. References ---------- * SALT2: Guy J., 2007 - https://doi.org/10.48550/arXiv.astro-ph/0701828 * sncosmo - https://zenodo.org/records/14714968 Attributes ---------- _m0_model : BicubicInterpolator The interpolator for the m0 parameter. _m1_model : BicubicInterpolator The interpolator for the m1 parameter. _colorlaw : SALT2ColorLaw The data to apply the color law. Parameters ---------- x0 : parameter The SALT2 x0 parameter. x1 : parameter The SALT2 x1 parameter. c : parameter The SALT2 c parameter. model_dir : str The path for the model file directory. Default: "" m0_filename : str The file name for the m0 model component. Default: "salt2_template_0.dat" m1_filename : str The file name for the m1 model component. Default: "salt2_template_1.dat" cl_filename : str The file name of the color law correction coefficients. Default: "salt2_color_correction.dat", **kwargs : dict, optional Any additional keyword arguments. """ # A class variable for the units so we are not computing them each time. _FLAM_UNIT = u.erg / u.second / u.cm**2 / u.AA def __init__( self, x0=None, x1=None, c=None, model_dir="", m0_filename="salt2_template_0.dat", m1_filename="salt2_template_1.dat", cl_filename="salt2_color_correction.dat", **kwargs, ): super().__init__(**kwargs) # Add the model specific parameters. self.add_parameter("x0", x0, description="The SALT2 x0 parameter.", **kwargs) self.add_parameter("x1", x1, description="The SALT2 x1 parameter.", **kwargs) self.add_parameter("c", c, description="The SALT2 c parameter.", **kwargs) # Load the data files. from lightcurvelynx.utils.bicubic_interp import BicubicInterpolator model_path = Path(model_dir) self._m0_model = BicubicInterpolator.from_grid_file( model_path / m0_filename, scale_factor=1e-12, ) self._m1_model = BicubicInterpolator.from_grid_file( model_path / m1_filename, scale_factor=1e-12, ) # Use the default color correction values. self._colorlaw = SALT2ColorLaw.from_file(model_path / cl_filename) ``` -------------------------------- ### Infer Component Start Time for Roman HLTDS Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/obstable/roman_obstable.html Infers the start time for each survey component (PC, EC1, CC, EC2) for both North and South fields. It uses survey start time, cadence, field time offsets, and delays after components. This is useful for scheduling and time-critical observations. ```python def infer_component_start_time(self, field_time_offset=None, after_component_delay_time=None): """ Infer the start time of each survey commponent for Roman HLTDS. Parameters ---------- field_time_offset: tuple or ndarray The time offset for the north and south field. after_component_delay_time: dict The delay time after each survey component. """ if field_time_offset is None: field_time_offset = self.safe_get_survey_value("field_time_offset") if after_component_delay_time is None: after_component_delay_time = self.safe_get_survey_value("after_component_delay_time") ##separate north and south north_field = self._table.dec > 0 south_field = self._table.dec < 0 nepoch = {} survey_start_time = self.safe_get_survey_value("survey_start_time") cadence = self.safe_get_survey_value("cadence") field_time_offset = self.safe_get_survey_value("field_time_offset") component_start_time = self.safe_get_survey_value("component_start_time") for field_name, field, time_offset in zip( ["North", "South"], [north_field, south_field], field_time_offset, strict=True ): table = self._table.loc[field] nepoch[field_name] = {} for component in ["PC", "EC1", "CC", "EC2"]: nepoch[field_name][component] = len( table.loc[component == table.SURVEY_COMPONENT].PASS.unique() ) component_start_time[field_name] = {} t = survey_start_time + time_offset component_start_time[field_name]["PC"] = t t += nepoch[field_name]["PC"] * cadence["PC"] + after_component_delay_time["PC"] component_start_time[field_name]["EC1"] = t t += nepoch[field_name]["EC1"] * cadence["EC1"] + after_component_delay_time["EC1"] component_start_time[field_name]["CC"] = t t += nepoch[field_name]["CC"] * cadence["CC"] + after_component_delay_time["CC"] component_start_time[field_name]["EC2"] = t self.survey_values["component_start_time"] = component_start_time self.survey_values["after_component_delay_time"] = after_component_delay_time self.survey_values["field_time_offset"] = field_time_offset ``` -------------------------------- ### Instantiate and Describe Model Parameters Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/adding_models.html Creates an instance of the SinModel and displays its settable parameters, including inherited ones like 'ra', 'dec', 'redshift', 't0', and 'distance', along with model-specific parameters 'brightness' and 'frequency'. ```python model = SinModel(brightness=15.0, frequency=1.0, t0=0.0) model.describe_params() ``` -------------------------------- ### Install Jupyter Kernel for LightCurveLynx Source: https://lightcurvelynx.readthedocs.io/en/latest/index.html Installs the necessary ipykernel package and registers a new Jupyter kernel named 'lightcurvelynx'. This allows running LightCurveLynx within Jupyter Notebooks. ```bash >> python3 -m pip install ipykernel >> python3 -m ipykernel install --user --name=lightcurvelynx ``` -------------------------------- ### infer_component_start_time Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/obstable/roman_obstable.html Infers the start time of each survey component for Roman HLTDS. It calculates these times based on survey start time, cadence, field time offsets, and delays between components. ```APIDOC ## infer_component_start_time ### Description Infer the start time of each survey component for Roman HLTDS. ### Method This is a method within a class, not a direct API endpoint. ### Parameters * **field_time_offset** (tuple or ndarray) - Optional - The time offset for the north and south field. * **after_component_delay_time** (dict) - Optional - The delay time after each survey component. ### Returns None. Updates internal survey values. ``` -------------------------------- ### Initialize StaticBandfluxModel with Multiple Bandflux Mappings Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/static_sed_model.html Shows how to initialize StaticBandfluxModel with a list of bandflux mappings. Weights can optionally be provided to influence random selection. ```python bandflux_mappings = [{"F090W": 1.0, "F150W": 0.8}, {"F090W": 0.9, "F150W": 0.9}] weights = np.array([0.7, 0.3]) model = StaticBandfluxModel(bandflux_values=bandflux_mappings, weights=weights) print(model.bandflux_values) ``` -------------------------------- ### Load PyLIMA Model Class Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/pylima_models.html Loads a pyLIMA model class dynamically by its name. Requires the pyLIMA package to be installed. Handles potential import errors by providing installation instructions. ```python def _load_pylima_model_class(model_name): """Load a pyLIMA model class by name. Parameters ---------- model_name : str The name of the pyLIMA model type to load. E.g., 'PSPL' Returns ------- model_class : class The pylima model class. """ try: from pyLIMA import models except ImportError as err: # pragma: no cover raise ImportError( "The pyLIMA package is required to use the PyLIMAWrapperModel. Please install it. " "See https://pylima.readthedocs.io/en/latest/ for instructions." ) from err # The package and the class uses different naming conventions with the # package having '_model' suffix and the class having 'model' suffix. model_package = getattr(models, f"{model_name}_model") model_class = getattr(model_package, f"{model_name}model") return model_class ``` -------------------------------- ### Sample GraphState Parameters Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/introduction.html Generates 3 sample parameter sets using the `sample_parameters` method and prints the resulting GraphState object. This is useful for creating initial data for light curve generation. ```python state = model.sample_parameters(num_samples=3) print(state) ``` -------------------------------- ### RandomMultiObjectModel.maxwave() Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/models/multi_object_model/index.html Get the maximum wavelength of the model. ```APIDOC ## maxwave(_graph_state =None_) ### Description Get the maximum wavelength of the model. ### Parameters #### Optional Parameters - **graph_state** (GraphState) - An object mapping graph parameters to their values. If provided, the function will use the graph state to compute the maximum wavelength. ### Returns - **maxwave** (float or None) - The maximum wavelength of the model (in angstroms) or None if the model does not have a defined maximum wavelength. ``` -------------------------------- ### RandomMultiObjectModel.minwave() Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/models/multi_object_model/index.html Get the minimum wavelength of the model. ```APIDOC ## minwave(_graph_state =None_) ### Description Get the minimum wavelength of the model. ### Parameters #### Optional Parameters - **graph_state** (GraphState) - An object mapping graph parameters to their values. If provided, the function will use the graph state to compute the minimum wavelength. ### Returns - **minwave** (float or None) - The minimum wavelength of the model (in angstroms) or None if the model does not have a defined minimum wavelength. ``` -------------------------------- ### Chaining Computations with BasicMathNode Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/sampling.html Illustrates how to create complex relationships between parameters by chaining computations. This example uses `BasicMathNode` to define the source's brightness as a function of the host's brightness and another random variable. ```python # Create a host galaxy with a random brightness. host = ConstantSEDModel( brightness=NumpyRandomFunc("uniform", low=1.0, high=5.0), node_label="host", ) # Create the brightness of the source as a uniformly sampled foreground brightness # added to the 80% of the host's brightness (background). source_brightness = BasicMathNode( "0.8 * val1 + val2", val1=host.brightness, val2=NumpyRandomFunc("uniform", low=1.0, high=2.0), node_label="plus_80percent", ) source = ConstantSEDModel( brightness=source_brightness, node_label="source", ) state = source.sample_parameters(num_samples=10) print(f"Host Brightness: {state['host']['brightness']}") print(f"Source Brightness: {state['source']['brightness']}") ``` -------------------------------- ### Load SALT2ColorLaw from File Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/astro_utils/salt2_color_law.html Creates a SALT2ColorLaw object by loading coefficients and wavelength bounds from a specified file. Supports version 1 files. ```python class SALT2ColorLaw: # ... (previous code) ... @classmethod def from_file(cls, filename): with open(filename, mode="r") as f: data = f.read().split() num_coeff = int(data[0]) coeffs = np.array(data[1 : (1 + num_coeff)], dtype=float) wave_min = 3000.0 wave_max = 7000.0 for i in range(1 + num_coeff, len(data), 2): if "min_lambda" in data[i]: wave_min = float(data[i + 1]) elif "max_lambda" in data[i]: wave_max = float(data[i + 1]) elif "version" in data[i]: version = int(data[i + 1]) if version != 1: raise RuntimeError(f"Unsupported version {version}.") return SALT2ColorLaw(wave_min, wave_max, coeffs) ``` -------------------------------- ### maxwave Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/sncosmo_models.html Get the maximum wavelength of the model. ```APIDOC ## maxwave ### Description Get the maximum wavelength of the model. ### Method GET (assumed) ### Endpoint /maxwave (assumed) ### Parameters #### Query Parameters - **kwargs** (dict) - Optional - Additional keyword arguments, not used in this method. ### Response #### Success Response (200) - **maxwave** (float or None) - The maximum wavelength of the model (in angstroms) or None if the model does not have a defined maximum wavelength. ``` -------------------------------- ### minwave Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/sncosmo_models.html Get the minimum wavelength of the model. ```APIDOC ## minwave ### Description Get the minimum wavelength of the model. ### Method GET (assumed) ### Endpoint /minwave (assumed) ### Parameters #### Query Parameters - **kwargs** (dict) - Optional - Additional keyword arguments, not used in this method. ### Response #### Success Response (200) - **minwave** (float or None) - The minimum wavelength of the model (in angstroms) or None if the model does not have a defined minimum wavelength. ``` -------------------------------- ### Initialize Sncosmo Extinction Wrapper Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/effects/extinction.html Initializes a wrapper for the sncosmo extinction package. Requires the model name and optionally R(V). Raises an error if the 'extinction' package is not installed or if an invalid model name is provided. ```python import extinction # noqa: F401 # ... inside __init__ method ... if model_name not in dir(extinction): raise KeyError(f"Invalid extinction model '{model_name}' from extinction package.") self.extinction_fn = getattr(extinction, model_name) self.model_name = model_name # Check that we either have r_v set or that the model does not need it. if model_name == "fm07": if r_v is not None and np.abs(r_v - 3.1) > 1e-8: raise ValueError("The fm07 extinction model requires r_v to be fixed at 3.1.") self.r_v = 3.1 elif r_v is not None and np.isscalar(r_v): self.r_v = float(r_v) else: # pragma: no cover raise ValueError(f"The {model_name} extinction model requires a numeric r_v parameter.") ``` -------------------------------- ### maxwave Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/models/gopreaux_models/index.html Get the maximum supported wavelength of the model. ```APIDOC ## maxwave(_** kwargs_) ### Description Get the maximum supported wavelength of the model. ### Parameters ****kwargs** (_dict_) – Additional keyword arguments, not used in this method. ### Returns * **maximum** – The maximum wavelength of the model (in angstroms) or None if the model does not have a defined maximum wavelength. ### Return type float or None ``` -------------------------------- ### minwave Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/models/gopreaux_models/index.html Get the minimum supported wavelength of the model. ```APIDOC ## minwave(_** kwargs_) ### Description Get the minimum supported wavelength of the model. ### Parameters ****kwargs** (_dict_) – Additional keyword arguments, not used in this method. ### Returns * **minwave** – The minimum wavelength of the model (in angstroms) or None if the model does not have a defined minimum wavelength. ### Return type float or None ``` -------------------------------- ### Initialize Bandflux Sampler Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/static_sed_model.html Sets up a sampler to select bandflux mappings based on provided weights. This parameter is not allowed to have a gradient. ```python all_inds = [i for i in range(len(self.bandflux_values))] self._sampler_node = GivenValueSampler(all_inds, weights=weights) self.add_parameter("selected_idx", value=self._sampler_node, allow_gradient=False) ``` -------------------------------- ### Sample Parameters from ModelDAGNode Source: https://lightcurvelynx.readthedocs.io/en/latest/notebooks/pre_executed/modeldag_sampling.html Initializes a ModelDAGNode and samples its parameters. The sampled state is then printed. ```python from lightcurvelynx.math_nodes.modeldag_node import ModelDAGNode node = ModelDAGNode(model, node_label="test") state = node.sample_parameters(num_samples=5) print(state) ``` -------------------------------- ### maxphase Source: https://lightcurvelynx.readthedocs.io/en/latest/autoapi/lightcurvelynx/models/gopreaux_models/index.html Get the maximum supported phase of the model in days. ```APIDOC ## maxphase(_** kwargs_) ### Description Get the maximum supported phase of the model in days. ### Parameters ****kwargs** (_dict_) – Additional keyword arguments, not used in this method. ### Returns * **maximum** – The maximum phase of the model (in days) or None if the model does not have a defined maximum phase. ### Return type float or None ``` -------------------------------- ### Initialize SncosmoWrapperModel Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/sncosmo_models.html Instantiate the SncosmoWrapperModel by providing the name of the sncosmo source model and any necessary parameters. Ensure the 'sncosmo' package is installed. ```python from lightcurvelynx.models.sncosmo_models import SncosmoWrapperModel # Example initialization with a SALT2 model salt2_model = SncosmoWrapperModel("salt2", color="0.0",வதற்கு="0.0") # Example initialization with a custom model # custom_model = SncosmoWrapperModel("my_custom_source", param1=1.0, param2=2.0) ``` -------------------------------- ### wave_bounds Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/astro_utils/passbands.html Get the minimum and maximum wavelength for this group of passbands. ```APIDOC ## wave_bounds ### Description Get the minimum and maximum wavelength for this group. ### Returns - **min_wave** (float) - The minimum wavelength. - **max_wave** (float) - The maximum wavelength. ``` -------------------------------- ### get_value_per_row Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/obstable/obs_table.html Get the values for each row from the table or survey values (defaults). ```APIDOC ## get_value_per_row (key, *, indices=None, default=None) ### Description Get the values for each row from the table or survey values (defaults). ### Parameters #### Path Parameters - **key** (str) - Required - The name of the column to retrieve. - **indices** (numpy.ndarray) - Optional - The indices of the rows for which to retrieve values. If None, retrieve all rows. Default: None - **default** (any) - Optional - The default value to use if the key is not found in the table or survey values. This can be None to indicate missing values. Default: None ### Returns - **numpy.ndarray** - The values for each row in the table. ``` -------------------------------- ### Initialize Lightcurve Template Model Parameters Source: https://lightcurvelynx.readthedocs.io/en/latest/_modules/lightcurvelynx/models/lightcurve_template_model.html Sets up parameters for selecting a light curve and its baseline values. It handles cases where indices or weights are provided, and initializes baseline parameters for each filter. ```python # Either choose from the indices (in order) if indices is not None: if weights is not None: raise ValueError("Cannot provide both 'weights' and 'indices' parameters.") if isinstance(indices, list | np.ndarray): indices = np.asarray(indices) if np.any((indices < 0) | (indices >= len(lightcurves))): raise ValueError("Indices must be between 0 and the number of light curves.") indices_sampler = GivenValueList(indices) else: # Assume it is already a parameter or sampler. indices_sampler = indices else: all_inds = np.arange(len(lightcurves)) indices_sampler = GivenValueSampler(all_inds, weights=weights) self.add_parameter( "selected_lightcurve", value=indices_sampler, allow_gradient=False, description="Index of the light curve selected for sampling.", ) # Assemble a list of baseline values for each filter across all light curves. # Create a parameter to track the baseline values for the selected light curve. The node # will automatically fill in the correct baseline value based on the index given by # the selected_lightcurve parameter. for fltr in self.filters: baselines = [lc.baseline.get(fltr, 0.0) for lc in lightcurves] baseline_selector = GivenValueSelector(baselines, self.selected_lightcurve) self.add_parameter( f"baseline_{fltr}", value=baseline_selector, allow_gradient=False, description=f"Baseline value for filter {fltr} from the selected light curve.", ) ```