LensModel
The LensModel module is the interface between the user and the lens modeling engine of LensFactory.jl. All user inputs are specified through a YAML file. The input YAML is divided into multiple sections. The overall structure of the input YAML file is given below.
LensFactory.LensModel.read_input — Function
read_input(input_filename::AbstractString)Reads the input YAML file and constructs a ModelConfig struct containing all the necessary information for lens modeling and sampling. For details on the expected structure of the input YAML file, please refer to Example - 2.
Arguments
input_filename::AbstractString: Path to the input YAML file.
Returns
ModelConfig::ModelConfig: A struct containing the observation details, cosmology, lens configuration, source configuration, parameter definitions, and sampling configuration.
LensFactory.LensModel.fit_model — Function
fit_model(model::ModelConfig; save::Bool=true, file_name::Union{String, Nothing}=nothing)Performs lens model fitting using the given model.
Arguments
model::ModelConfig: The lens model configuration containing the observation, lens, source, and sampler details.save::Bool=true: Whether to save the MCMC results to a JLD2 file (default: true)file_name::Union{String, Nothing}=nothing: The name of the JLD2 file to save results. If no name is provided then a name will be generated based on the lens name and current date (i.e., LensName_DDMMYYYY.jld2).
Returns
chains::Array{Float64, 3}: The MCMC chains containing sampled parameter valueslog_posterior::Matrix{Float64}: The log-posterior values corresponding to each sample in the chains
LensFactory.LensModel.free_parameter_names — Function
free_parameter_names(model::ModelConfig)Get a vector of tuples containing the owner and name of each free parameter in the model.
Arguments
model::ModelConfig: The lens model configuration containing the observation, lens, source, and sampler details.
Returns
Vector{Tuple{Symbol, Symbol}}: A vector of tuples containing the owner and name of each free parameter.
LensFactory.LensModel.get_best_fit_parameters — Function
get_best_fit_parameters(results; chains=nothing, burn_in::Float64=0.2, with_errors::Bool=false, thin::Int64=1, print_table::Bool=false)Get the best-fit parameters from the optimization or MCMC results.
Arguments
results::Union{Vector{@NamedTuple{θ::Vector{Float64}, f::Float64}}, Matrix{Float64}}: The optimization or MCMC results.- If
results::Vector{@NamedTuple{θ::Vector{Float64}, f::Float64}}: It is assumed to be from the optimizer results, where each element is a named tuple containing the parameter vector (θ) and the χ² values (f). - If
results::Matrix{Float64}: It is assumed to be the χ² matrix corresponding to MCMC chains.
- If
Keyword Arguments
chains::Union{Array{Float64, 3}, Nothing}=nothing: MCMC chains. The dimensions should be(n_steps, n_chains, n_parameters). This is only required whenresultsis aMatrix{Float64}.burn_in::Float64=0.2: The fraction of MCMC chains to discard as burn-in (default: 0.2).with_errors::Bool=false: Iftrue, then also return 1-sigma uncertainties for best-fit parameters. But it will only work ifchainsare provided.thin::Int64=1: The thinning factor to apply to the MCMC chains while calculating parameter uncertainties.print_table::Bool=false: Iftrue, then print the best-fit parameters along with [-1σ, +1σ] and [-2σ, +2σ] ranges in a table format. This option is only available whenwith_errors=true.
Returns
best_θ::Vector{Float64}: Best-fit parameter values.log_posterior::Float64: Log-posterior value corresponding to the best-fit parameters.lower_err::Vector{Float64}: Lower 1-sigma uncertainties (only ifwith_errors=true).upper_err::Vector{Float64}: Upper 1-sigma uncertainties (only ifwith_errors=true).
LensFactory.LensModel.get_cosmology — Function
get_cosmology(data_jld2::JLD2.JLDFile; burn_in::Float64=0.2, thin::Int64=1, with_errors::Bool=false)Extract the cosmology corresponding to the best-fit model. If with_errors=true, the cosmology is also constructed for every post-burn-in (thinned) posterior sample, excluding the best-fit sample, so that uncertainties on cosmology-dependent quantities can be derived from the sample distribution. Note that the sampled cosmologies only differ from the best-fit one if cosmological parameters are free in the fit.
Arguments
data_jld2::JLD2.JLDFile: JLD2 data file containing the fit results.
Keyword Arguments
burn_in::Float64=0.2: The fraction of MCMC chains to discard as burn-in. Set to 0.0 when the input file was produced byerror_models, as those samples are already post-burn-in.thin::Int64=1: The thinning factor applied (per chain) when selecting posterior samples. Only used whenwith_errors=true.with_errors::Bool=false: Iftrue, also return the cosmology for every posterior sample.
Returns
- If
with_errors=false:cosmo_best: Cosmology corresponding to the best-fit parameters.
- If
with_errors=true:cosmo_best: Cosmology corresponding to the best-fit parameters.cosmo_samples::Vector: Cosmology for each posterior sample (best fit excluded).
LensFactory.LensModel.get_adis — Function
get_adis(data_jld2::JLD2.JLDFile, source_id::Int64; burn_in::Float64=0.2)Calculate the distance ratio adis = Dls/Dos of source `sourceidfor the best-fit model stored indata_jld2`. If the source redshift (or the distance ratio itself) is a free parameter of the fit, or if any cosmological parameter is free, the returned value corresponds to the best-fit sample. Otherwise, it is simply the fixed input value.
Arguments
data_jld2::JLD2.JLDFile: JLD2 data file containing the fit results.source_id::Int64: Index of the source, as ordered in the input file.
Keyword Arguments
burn_in::Float64=0.2: The fraction of MCMC chains to discard as burn-in while determining the best-fit model. Set to 0.0 when the input file was produced byerror_models, as those samples are already post-burn-in.
Returns
adis::Float64: Distance ratio Dls/Dos of the requested source.
LensFactory.LensModel.get_best_model — Function
get_best_model(model::ModelConfig, chains::Array{Float64, 3}, logL::Matrix{Float64})Get the best-fit lens model based on the MCMC results stored in chains and logL. The best-fit parameters are determined by the minimum log-likelihood in logL.
Arguments
model::ModelConfig: The lens model configuration used for the MCMC fit.chains::Array{Float64, 3}: The MCMC chains containing the sampled parameter values. The dimensions should be (nsteps, nchains, n_parameters).logL::Matrix{Float64}: The log-likelihood values corresponding to each sample in the MCMC chains. The dimensions should be (nsteps, nsteps).
Returns
best_model: Best-fit lens model constructed using the best-fit parameters.logL: Log-likelihoohood correspodning to best-fit lens model.
LensFactory.LensModel.get_potential — Function
get_potential(best_model::Lenses.AbstractLens, θx::T, θy::T;
reference::Tuple{Float64, Float64} = (0.0, 0.0)) where T <: Union{Real, ROA}get_potential(data_jld2::JLD2.JLDFile, θx::T, θy::T;
burn_in::Float64 = 0.2,
thin::Int64 = 1,
with_errors::Bool = false) where T <: Union{Real, ROA}Calculate the lensing potential at the given coordinates (θx, θy) for the best-fit model. If with_errors=true, the potential is also calculated for every post-burn-in (thinned) posterior sample, excluding the best-fit sample, so that uncertainties can be derived from the sample distribution.
Arguments
data_jld2: JLD2 data file containing the fit results or the best-fit lens model.θx: x-coordinates (RA in degrees).θy: y-coordinates (DEC in degrees).
Keyword Arguments
burn_in = 0.2: The fraction of MCMC chains to discard as burn-in. Set to 0.0 when the input file was produced byerror_models, as those samples are already post-burn-in.thin = 1: The thinning factor applied (per chain) when selecting posterior samples. Only used whenwith_errors = true.with_errors = false: Iftrue, also return the potential for every posterior sample.
Returns
- If
with_errors=false:ψ_best: Lensing potential at the input coordinates for the best-fit model.
- If
with_errors=true:ψ_best: Lensing potential at the input coordinates for the best-fit model.ψ_samples::Vector: Lensing potential for each posterior sample (best fit excluded), where each element has the same shape asθx.
LensFactory.LensModel.get_deflection — Function
get_deflection(best_model::Lenses.AbstractLens, θx::T, θy::T;
reference::Tuple{Float64, Float64}=(0.0, 0.0)) where T <: Union{Real, ROA}get_deflection(data_jld2::JLD2.JLDFile, θx::T, θy::T;
burn_in::Float64 = 0.2,
thin::Int64 = 1,
with_errors::Bool = false) where T <: Union{Real, ROA}Calculate the lensing deflection at the given coordinates (θx, θy) for the best-fit model. If with_errors=true, the deflection is also calculated for every post-burn-in (thinned) posterior sample, excluding the best-fit sample, so that uncertainties can be derived from the sample distribution.
Arguments
data_jld2: JLD2 data file containing the fit results.θx: x-coordinates (RA in degrees).θy: y-coordinates (DEC in degrees).
Keyword Arguments
burn_in=0.2: The fraction of MCMC chains to discard as burn-in. Set to 0.0 when the input file was produced byerror_models, as those samples are already post-burn-in.thin=1: The thinning factor applied (per chain) when selecting posterior samples. Only used whenwith_errors=true.with_errors=false: Iftrue, also return the deflection for every posterior sample.
Returns
- If
with_errors=false:αx: x-component of the deflection angle (in arcseconds).αy: y-component of the deflection angle (in arcseconds).
- If
with_errors=true:(αx_best, αy_best): Deflection components for the best-fit model.(αx_samples, αy_samples): Vectors with deflection components for each posterior sample (best fit excluded), where each element has the same shape asθx.
LensFactory.LensModel.get_jacobian — Function
get_jacobian(best_model::Lenses.AbstractLens, θx::T, θy::T; unit::Symbol=:RA_DEC) where T <: Union{Real, ROA}get_jacobian(data_jld2::JLD2.JLDFile, θx::T, θy::T;
burn_in::Float64 = 0.2,
thin::Int64 = 1,
with_errors::Bool = false) where T <: Union{Real, ROA}Calculate the Jacobian (i.e., deformation tensor) at the given coordinates (θx, θy) for the best-fit model. If with_errors=true, the Jacobian is also calculated for every post-burn-in (thinned) posterior sample, excluding the best-fit sample, so that uncertainties can be derived from the sample distribution.
Arguments
data_jld2::JLD2.JLDFile: JLD2 data file containing the fit results.θx: x-coordinates (RA in degrees).θy: y-coordinates (DEC in degrees).
Keyword Arguments
burn_in::Float64=0.2: The fraction of MCMC chains to discard as burn-in. Set to 0.0 when the input file was produced byerror_models, as those samples are already post-burn-in.thin::Int64=1: The thinning factor applied (per chain) when selecting posterior samples. Only used whenwith_errors=true.with_errors::Bool=false: Iftrue, also return the Jacobian for every posterior sample.
Returns
- If
with_errors=false:ψxx: xx-component of the jacobian.ψyy: yy-component of the jacobian.ψxy: xy-component of the jacobian.
- If
with_errors=true:(ψxx_best, ψyy_best, ψxy_best): Jacobian components for the best-fit model.(ψxx_samples, ψyy_samples, ψxy_samples): Vectors with Jacobian components for each posterior sample (best fit excluded), where each element has the same shape asθx.
LensFactory.LensModel.get_magnification_image — Function
get_magnification_image(best_model::Lenses.AbstractLens, θx::T, θy::T, adis::Real;
reference::Tuple{Float64, Float64} = (0.0, 0.0)) where T <: Union{Real, ROA}get_magnification_image(data_jld2::JLD2.JLDFile, θx::T, θy::T, z_s::Float64;
burn_in::Float64 = 0.2,
thin::Int64 = 1,
with_errors::Bool = false) where T <: Union{RV, ROA}Calculate the magnification at the given coordinates (θx, θy) for a source at redshift z_s using the best-fit model. If with_errors=true, the magnification is also calculated for every post-burn-in (thinned) posterior sample, excluding the best-fit sample, so that uncertainties can be derived from the sample distribution.
Since the magnification depends on the angular-diameter distance ratio D_ls/D_os, both the lens model and the cosmology are rebuilt from the same parameter vector for every posterior sample. This preserves the correlations between lens and cosmological parameters in the posterior.
Arguments
data_jld2::JLD2.JLDFile: JLD2 data file containing the fit results.θx: x-coordinates (RA in degrees).θy: y-coordinates (DEC in degrees).z_s::Float64: Source redshift.
Keyword Arguments
burn_in::Float64=0.2: The fraction of MCMC chains to discard as burn-in. Set to 0.0 when the input file was produced byerror_models, as those samples are already post-burn-in.thin::Int64=1: The thinning factor applied (per chain) when selecting posterior samples. Only used whenwith_errors=true.with_errors::Bool=false: Iftrue, also return the magnification for every posterior sample.
Returns
- If
with_errors=false:μ_best: Magnification at the input coordinates for the best-fit model.
- If
with_errors=true:μ_best: Magnification at the input coordinates for the best-fit model.μ_samples::Vector: Magnification for each posterior sample (best fit excluded), where each element has the same shape asθx.
LensFactory.LensModel.get_source_position — Function
get_source_position(data_jld2::JLD2.JLDFile, source_id::Int64, knot_id;
burn_in::Float64 = 0.2,
unit::Symbol = :arcsec)Calculate the weighted source position of knot knot_id of source source_id for the best-fit lens model stored in data_jld2.
Arguments
data_jld2::JLD2.JLDFile: JLD2 data file containing the fit results.source_id::Int64: Index of the source, as ordered in the input file.knot_id::Int64: Index of the knot within that source, as ordered in the input file.
Keyword Arguments
burn_in::Float64=0.2: The fraction of MCMC chains to discard as burn-in while determining the best-fit lens model. Set to 0.0 when the input file was produced byerror_models, as those samples are already post-burn-in.unit::Symbol=:arcsec: Unit of the returned source position.:arcsec: Arcseconds relative to the reference position of the model.:RA_DEC: RA/Dec in degrees.
Returns
β::NTuple{2, Float64}: Weighted source position of the requested knot.
LensFactory.LensModel.predict_image — Function
predict_image(jld2_file::JLD2.JLDFile, θx::T, θy::T, z_s::Float64; unit::Symbol=:RA_DEC) where T <: Union{Real, Vector{Float64}}Predict counter-image positions, magnifications and time delays based on the best-fit lens model. The function can take either a single observed image or multiple observed images of the same system. If multiple images are provided then the function will calculate the barycentric source position and then predict the counter-image positions, magnifications and time delays.
Arguments
data_jld2::JLD2.JLDFile: JLD2 data file containing the fit results.θx: x-coordinate(s) of the observed image position(s).θy: y-coordinate(s) of the observed image position(s).z_s::Float64: Source redshift.
Keyword Arguments
unit::Symbol=:RA_DEC: Unit of the input coordinates.:RA_DEC: (θx, θy) are assumed to be in RA/DEC (in degrees).:arcsec: (θx, θy) are assumed to be in arcseconds.
Returns
nothing: Prints the counter-image positions, magnifications and time delays in a table format. The table is sorted based on the time delay and at the end also contains the best-fit model predicted source position.
LensFactory.LensModel.save_best_fits — Function
save_best_fits(file_name::String; save_potential::Bool=true, save_deflection::Bool=true, save_kappa::Bool=true, save_gamma::Bool=true)Save fits files for the best-fit model based on the MCMC results stored in file_name. The user can choose which lensing quantities to save by setting the corresponding boolean flags.
Arguments
file_name::String: Path to the JLD2 file containing the MCMC results
Keyword Arguments
save_potential::Bool=true: Whether to save the lensing potential as potential.fitssave_deflection::Bool=true: Whether to save the deflection angles as alpha_x.fits and alpha_y.fitssave_kappa::Bool=true: Whether to save the convergence map as kappa.fitssave_gamma::Bool=true: Whether to save the shear maps as gamma1.fits and gamma2.fits
Returns
nothing: Saves FITS files to disk
LensFactory.LensModel.get_best_fit_rms — Function
get_best_fit_rms(model::ModelConfig, chains::Array{Float64, 3}, logL::Matrix{Float64}; burn_in::Float64=0.2)Calculate the RMS of the best-fit model based on the MCMC results stored in chains and logL. The function prints a table showing the RMS for each knot image, as well as a global total RMS. If
Arguments
model::ModelConfig: The lens model configuration used for the MCMC fit.chains::Array{Float64, 3}: The MCMC chains containing the sampled parameter values. The dimensions should be (nsteps, nchains, n_parameters).logL::Matrix{Float64}: The logL values corresponding to each sample in the MCMC chains. The dimensions should be (nsteps, nsteps).
Keyword Arguments
burn_in::Float64=0.2: The fraction of MCMC chains to discard as burn-in while determining best-fit lens model.
Returns
nothing: Prints a table to the console with the RMS for each knot image, as well as total RMS.
LensFactory.LensModel.error_models — Function
error_models(data_jld2::JLD2.JLDFile;
n_samples:: Int64 = 1000,
burn_in::Float64 = 0.2,
out_file::String = "")Extracts posterior samples and best-fit values from the MCMC chains stored in a JLD2 file.
Arguments
data_jld2::JLD2.JLDFile: Path to the JLD2 file containing the MCMC results.
Keyword Arguments
n_samples = 1000: The number of posterior samples to extract.burn_in = 0.2: The fraction of MCMC steps to discard as burn-in (default: 20%).out_file = "": Optional path to save the extracted posterior samples and best-fit values to a new JLD2 file. If empty, the file will be named"err_post_<Date>_<Time>.jld2".
Returns
nothing: Saves error models in a JLD2 file.
LensFactory.LensModel.get_AIC — Function
get_AIC(model::ModelConfig, chains::Array{Float64,3}, logL::Matrix{Float64};
burn_in::Float64 = 0.2)Compute the Akaike Information Criterion (AIC) for a fitted LensFactory model.
\[ \rm{AIC} = -2 \ln L + 2 k\]
Arguments
model: ModelConfig fromread_inputlogL: Log-likelihood matrix of shape (nsteps, nchains) fromfit_model
Keyword Arguments
burn_in: Fraction of chain to discard as burn-in
Returns
Float64: The AIC value for the model.
LensFactory.LensModel.get_BIC — Function
get_BIC(model::ModelConfig, chains::Array{Float64,3}, logL::Matrix{Float64}, n_data::Int;
burn_in::Float64 = 0.2)Compute the Bayesian Information Criterion (BIC) for a fitted LensFactory model.
\[ \rm{BIC} = -2 \ln L + k \ln(n)\]
Arguments
model: ModelConfig fromread_inputlogL: Log-likelihood matrix of shape (nsteps, nchains) fromfit_modeln_data: Total number of observed constraintsburn_in: Fraction of chain to discard as burn-in (default 0.2)