MicroLIA_Sim.microlensing
Attributes
Classes
Container specifying parameter requirements for a microlensing model. |
|
Base class for extended-lens photometric microlensing models in pyLIMA. |
|
Extended-lens microlensing model using an NFW-like enclosed-mass profile. |
|
Extended-lens microlensing model using a boson-star enclosed-mass profile. |
Functions
|
Convert AB magnitude(s) to flux density in nanoJanskys (nJy). |
|
Convert flux density in nanoJanskys (nJy) to AB magnitude(s). |
|
Convert AB magnitude(s) to flux density in nanoJanskys (nJy) using pyLIMA. |
|
Convert flux density in nanoJanskys (nJy) to AB magnitude(s) using pyLIMA. |
|
Return parameter bounds for the extended-lens timescale parameter |
|
Return a human-readable description of parameter requirements for a model. |
|
Normalize a user-supplied model type string to its identifier. |
|
Normalize a |
|
Validate and normalize model-specific parameters. |
|
Validate and normalize parallax parameters for pyLIMA. |
|
Validate photometric inputs for simulated multi-band light curves. |
|
Load a 1D extended-lens mass-function table and build spline interpolants. |
|
Load and cache mass-function spline tables for extended-lens models (NFW / BS). |
|
Compute photometric magnification for an extended lens via root finding. |
|
Evaluate the dimensionless enclosed-mass function for the NFW extended lens. |
|
Evaluate the derivative of the NFW enclosed-mass function with respect to |
|
Evaluate the dimensionless enclosed-mass function for the boson-star (BS) extended lens. |
|
Evaluate the derivative of the boson-star (BS) enclosed-mass function with respect to |
|
Construct an adaptive Julian Date (JD) time grid centered on a microlensing event. |
|
Compute per-band source and blend fluxes (nJy) from magnitude-based inputs. |
|
Simulate a noise-free ("perfect") multi-band microlensing light curve with pyLIMA. |
|
Write multi-band light curves to a single tab-delimited text file. |
|
Plot multi-band light curves in AB magnitudes versus MJD. |
Module Contents
- MicroLIA_Sim.microlensing.mag2nJy(mag: float | numpy.ndarray) float | numpy.ndarray[source]
Convert AB magnitude(s) to flux density in nanoJanskys (nJy).
This uses the module-level
ZERO_POINT(set to 31.4 by default as the AB definition is zp=8.9 for 1 Jy) and the standard AB magnitude relation.
- MicroLIA_Sim.microlensing.flux2mag(flux_njy: float | numpy.ndarray) float | numpy.ndarray[source]
Convert flux density in nanoJanskys (nJy) to AB magnitude(s).
This uses the module-level
ZERO_POINT(set to 31.4 by default as the AB definition is zp=8.9 for 1 Jy) and the inverse AB relation. Note that to avoid log of zero or negative flux issues, flux values are clipped to a minimum of1e-10nJy prior to conversion.
- MicroLIA_Sim.microlensing.abmag_to_njy(mag: float | numpy.ndarray) float | numpy.ndarray[source]
Convert AB magnitude(s) to flux density in nanoJanskys (nJy) using pyLIMA.
This calls
pyLIMA.toolbox.brightness_transformation.magnitude_to_flux. Note that in this pipeline, the pyLIMA brightness transformation module is configured at import time by overwriting its module-levelZERO_POINTandEXPOSURE_TIMEso the conversion is always in the same calibrated physical units.
- MicroLIA_Sim.microlensing.njy_to_abmag(flux_njy: float | numpy.ndarray) float | numpy.ndarray[source]
Convert flux density in nanoJanskys (nJy) to AB magnitude(s) using pyLIMA.
This calls
pyLIMA.toolbox.brightness_transformation.flux_to_magnitude. In this pipeline, the pyLIMA brightness transformation module is configured at import time by overwriting its module-levelZERO_POINTandEXPOSURE_TIMEso the conversion is always in the same calibrated physical units.
- MicroLIA_Sim.microlensing.t_m_boundaries(event=None, model=None)[source]
Return parameter bounds for the extended-lens timescale parameter
t_m.This function is assigned to
pyLIMA.priors.parameters_boundaries.t_m_boundariesfor pyLIMA compatability, and is used only when sampling/validating the extended dark object models.
- class MicroLIA_Sim.microlensing.ModelSpec[source]
Container specifying parameter requirements for a microlensing model.
This dataclass describes which entries are required/optional in the user-facing
model_paramsdictionary for each supported model type. It also supports alias mapping (to accommodate alternate naming conventions, just in case) and defaults for optional parameters.- defaults[source]
Default values injected into
model_paramswhen missing. Only applies to keys listed inoptional(or otherwise expected by the model wrapper).- Type:
dict of str to Any
- aliases[source]
Mapping from alias key -> canonical key. If an alias is provided and the canonical key is missing, the alias value is copied to the canonical key. Intended to tolerate common synonyms and/or upstream naming changes.
- Type:
dict of str to str
- MicroLIA_Sim.microlensing.describe_model_requirements(model_type: str) str[source]
Return a human-readable description of parameter requirements for a model.
This helper summarizes the required and optional
model_paramskeys for the requested model type, and includes any defaults, aliases, notes, and an example (when available). It is primarily used to generate informative error messages.
- MicroLIA_Sim.microlensing._normalize_model_type(model_type: str) str[source]
Normalize a user-supplied model type string to its identifier.
Normalization is case-insensitive and trims whitespace. A small set of common variants are mapped to supported canonical names (e.g.,
"FSPLarge"->"FSPL").
- MicroLIA_Sim.microlensing.normalize_model_params(model_type: str, model_params: dict | None) dict[str, Any][source]
Normalize a
model_paramsdictionary for a given model type.This function applies alias mappings (e.g.,
sep->s) when canonical keys are absent and removes alias keys when both alias and canonical are present (to avoid duplicates). It also injects default values for missing optional parameters defined inMODEL_SPECS.- Parameters:
- Returns:
A new dictionary containing normalized model parameters.
- Return type:
dict of str to Any
- MicroLIA_Sim.microlensing.validate_model_params(model_type: str, model_params: dict[str, Any] | None) dict[str, Any][source]
Validate and normalize model-specific parameters.
This enforces (1) required keys for the requested model, and (2) rejection of unknown keys to catch typos early. It also applies alias mappings and default values via
normalize_model_params().- Parameters:
- Returns:
Normalized
model_paramsdictionary with aliases applied and defaults injected (when defined inMODEL_SPECS).- Return type:
dict of str to Any
- MicroLIA_Sim.microlensing.validate_parallax(parallax_params: dict | None) dict | None[source]
Validate and normalize parallax parameters for pyLIMA.
Parallax is represented by the North/East components of the microlensing parallax vector:
piENandpiEE.- Parameters:
parallax_params (dict or None) – Parallax parameter dictionary. If provided, it must contain both keys
"piEN"and"piEE". If None, parallax is treated as disabled.- Returns:
If
parallax_paramsis None, returns None. Otherwise returns a new dict{"piEN": float(...), "piEE": float(...)}.- Return type:
dict or None
- MicroLIA_Sim.microlensing.validate_photometry(*, bands: tuple[str, Ellipsis], source_mags: dict[str, float] | None, blend_mags: dict[str, float] | None, blend_g: dict[str, float] | float | None) None[source]
Validate photometric inputs for simulated multi-band light curves.
This checks that
source_magsis a non-empty dict and provides an AB magnitude for every requested band inbands. It also checks that blending is specified in exactly one way, eitherblend_mags(explicit blend magnitudes per band) orblend_g(blend-to-source flux ratio), but not both. Also, ifblend_magsis provided, it includes all requested bands, and ifblend_gis a dict, it includes all requested bands (a single scalar is allowed and applies to all bands).- Parameters:
bands (tuple of str) – Photometric band names that will be simulated (e.g.,
("g", "r", "i")).source_mags (dict of str to float or None) – Source AB magnitudes per band. Must include every band in
bands.blend_mags (dict of str to float or None) – Blend-only AB magnitudes per band. If provided, must include every band in
bands. Mutually exclusive withblend_g.blend_g (dict of str to float, float, or None) – Blend-to-source flux ratio
g = f_blend / f_source. May be a scalar applied to all bands or a per-band dictionary. Mutually exclusive withblend_mags.
- Returns:
This function returns None if validation passes.
- Return type:
None
- MicroLIA_Sim.microlensing.load_and_interpolate_mass_function(csv_path_or_name: str | None = None, drop_row: int | None = None, base_dir: str | None = None)[source]
Load a 1D extended-lens mass-function table and build spline interpolants.
The input CSV is expected to contain two columns with no header – a column 0:
t(dimensionless coordinate; may be stored as strings that can be evaluated to floats), and a column 1:mt(dimensionless enclosed-mass function evaluated att)For numerical stability and symmetry, the table is mirrored to negative
tby reversing the original arrays and negatingt. Optionally, one row in the mirrored half may be dropped (useful when the original table includes an endpoint that would be duplicated by the mirroring). Ifdrop_rowis None, a point(t=0, mt=0)is appended to the mirrored half before concatenation.The function returns a cubic B-spline interpolant
m_inner(t)and its derivativedm_inner(t)as callable objects suitable for the extended-lens magnification calculation.- Parameters:
csv_path_or_name (str) – Path to the CSV file, or a filename to be joined with
base_dir. This file is saved in the package’s data directory and will be loaded when this is None! This should really never be set by the user…drop_row (int or None, optional) – If provided, drops this row index from the mirrored (negative-
t) half before concatenation. If None, appends(0, 0)to the mirrored half instead. Default is None.base_dir (str or None, optional) – If provided and
csv_path_or_nameis a relative path, the file path is constructed asos.path.join(base_dir, csv_path_or_name). Default is None. This should really never be set by the user…
- Returns:
(m_inner, dm_inner), where both entries are callable spline objects. If loading or interpolation fails, returns(None, None).- Return type:
- MicroLIA_Sim.microlensing.load_custom_extended_lens_tables(nfw_csv_path: str | None = None, boson_csv_path: str | None = None, *, nfw_drop_row: int = 0, base_dir: str | None = None) None[source]
Load and cache mass-function spline tables for extended-lens models (NFW / BS).
NOTE: The csv_path_or_name and base_dir SHOULD JUST BE NONE ALWAYS! End user should not be updating this table manually (unless it’s our team with an updated file!)
- Parameters:
nfw_csv_path (str or None) – Path (or filename) to the NFW mass-function CSV. If None, the NFW tables are not loaded/modified.
boson_csv_path (str or None) – Path (or filename) to the boson-star (BS) mass-function CSV. If None, the BS tables are not loaded/modified.
nfw_drop_row (int, optional) – Row index to drop from the mirrored half of the NFW table before concatenation. Default is 0 (matching the original pipeline behavior).
base_dir (str or None, optional) – Base directory prepended to relative paths for both CSV inputs. Default is None.
- Returns:
This function returns None, it only updates module-level spline objects and flags.
- Return type:
None
- MicroLIA_Sim.microlensing.calculate_magnification(tau, beta, t_m, m, dm)[source]
Compute photometric magnification for an extended lens via root finding.
This routine evaluates the magnification for an extended (non-point) lens model by solving a 1D lens equation for each impact parameter
u(t). For each time sample, the method first computes the instantaneous impact parameteru_tfrom the source trajectory coordinates (tau,beta). It then finds all real roots of the extended-lens lens equation (image positions) on a fixed 1D scan interval by detecting sign changes and refining each root withscipy.optimize.root_scalar. It then computes the signed magnification contribution for each image using the Jacobian factors that depend on the enclosed-mass functionm(t, t_m)and its derivativedm(t, t_m). The total magnification that is returned is then the sum of absolute image magnifications.- Parameters:
tau (array-like) – Dimensionless trajectory coordinate along the direction of motion (as returned by pyLIMA’s trajectory builder).
beta (array-like) – Dimensionless trajectory coordinate perpendicular to the direction of motion.
t_m (float) – Extended-lens characteristic scale.
m (callable) – Enclosed-mass function for the model. Must accept
(t, t_m)and returnm(t, t_m)evaluated elementwise for array-liket.dm (callable) – Derivative of the enclosed-mass function with respect to
t. Must accept(t, t_m)and returndm(t, t_m)evaluated elementwise for array-liket.
- Returns:
Array of magnifications with the same length as the computed impact-parameter array. If no roots are found for a given time sample, the magnification is set to 1.0 (i.e., no lensing).
- Return type:
numpy.ndarray
- MicroLIA_Sim.microlensing.m_nfw(t, t_m)[source]
Evaluate the dimensionless enclosed-mass function for the NFW extended lens.
- Parameters:
- Returns:
Enclosed-mass function value(s)
m(t, t_m). The return type matches the shape oft.- Return type:
float or numpy.ndarray
- MicroLIA_Sim.microlensing.dm_nfw(t, t_m)[source]
Evaluate the derivative of the NFW enclosed-mass function with respect to
t.
- MicroLIA_Sim.microlensing.m_boson(t, t_m)[source]
Evaluate the dimensionless enclosed-mass function for the boson-star (BS) extended lens.
- Parameters:
- Returns:
Enclosed-mass function value(s)
m(t, t_m). The return type matches the shape oft.- Return type:
float or numpy.ndarray
- MicroLIA_Sim.microlensing.dm_boson(t, t_m)[source]
Evaluate the derivative of the boson-star (BS) enclosed-mass function with respect to
t.
- class MicroLIA_Sim.microlensing.ExtendedLensModel[source]
Bases:
pyLIMA.models.PSPL_model.PSPLmodelBase class for extended-lens photometric microlensing models in pyLIMA.
This class subclasses pyLIMA’s
PSPLmodelbut replaces the point-lens magnification with an extended-lens magnification computed from a model-specific enclosed-mass functionm(t, t_m)and its derivativedm(t, t_m).Subclasses must provide a
model_mass_functionsproperty returning the pair(m, dm)callables used bycalculate_magnification(). In this pipeline, concrete subclasses includeNFWmodelandBSmodel.- paczynski_model_parameters()[source]
Define the ordered set of core photometric parameters for the extended lens.
This extends the standard Paczyński parameterization by including the additional extended-lens scale parameter
t_m. The returned mapping is used to build pyLIMA’s internal parameter dictionary ordering.- Returns:
Mapping from parameter name to index in the ordered pyLIMA parameter vector. The base ordering is:
{"t0": 0, "u0": 1, "tE": 2, "t_m": 3}.- Return type:
dict of str to int
- define_pyLIMA_standard_parameters()[source]
Construct pyLIMA’s standard parameter dictionary for this extended-lens model.
This method builds the full parameter set expected by pyLIMA by starting from the extended Paczyński parameters (
t0,u0,tE,t_m) and then adding any relevant astrometric, second-order, and per-telescope flux parameters using pyLIMA helper methods.The resulting dictionary is stored in
self.pyLIMA_standards_dictionnaryas anOrderedDictsorted by the assigned parameter indices. The parameter boundaries are set to(0, +inf)for all parameters as default.- Returns:
This method updates instance attributes used internally by pyLIMA.
- Return type:
None
- model_magnification(telescope, pyLIMA_parameters, return_impact_parameter=False)[source]
Compute the photometric magnification for an extended lens at telescope epochs.
The source trajectory is computed using pyLIMA’s trajectory machinery and then passed to
calculate_magnification(), along with the extended-lens scale parametert_mand the model-specific mass-function callables.- Parameters:
telescope (object) – pyLIMA telescope object containing timestamps and (after simulation) a
lightcurveattribute.pyLIMA_parameters (dict-like) – pyLIMA parameter container/dictionary with at least the key
"t_m", along with the usual microlensing parameters needed to compute the trajectory.return_impact_parameter (bool, optional) – Included for API compatibility with pyLIMA. This implementation ignores the flag and always returns the magnification array.
- Returns:
Array of magnifications evaluated at the telescope timestamps. If the telescope has no lightcurve attached (
telescope.lightcurve is None), returns None.- Return type:
numpy.ndarray or None
- class MicroLIA_Sim.microlensing.NFWmodel[source]
Bases:
ExtendedLensModelExtended-lens microlensing model using an NFW-like enclosed-mass profile.
- class MicroLIA_Sim.microlensing.BSmodel[source]
Bases:
ExtendedLensModelExtended-lens microlensing model using a boson-star enclosed-mass profile.
- MicroLIA_Sim.microlensing.build_time_grid_jd(*, t0_mjd: float, tE_days: float, window_size_days: float = 4000.0, peak_width_factor: float = 5.0, step_dense_days: float = 0.1, step_sparse_days: float = 10.0) numpy.ndarray[source]
Construct an adaptive Julian Date (JD) time grid centered on a microlensing event.
The grid is sampled densely near the event peak and sparsely in the wings, with a dense “core” region (
t0 plus/minus (peak_width_factor * tE), sampled everystep_dense_days) and sparse wings (outside the core region out tot0 plus/minus window_size_days, sampled everystep_sparse_days).This is primarily used when the user does not provide an explicit cadence and wants a “perfect” (noise-free) model.
- Parameters:
t0_mjd (float) – Event time of maximum magnification in Modified Julian Date (MJD).
tE_days (float) – Einstein timescale
tEin days.window_size_days (float, optional) – Half-width of the full time window around
t0(in days). The grid spans[t0 - window_size_days, t0 + window_size_days]in JD. Default is 4000.0.peak_width_factor (float, optional) – Sets the half-width of the densely sampled core as
peak_width_factor * tE_days. Default is 5.0.step_dense_days (float, optional) – Step size (days) in the densely sampled core region. Default is 0.1.
step_sparse_days (float, optional) – Step size (days) in the sparsely sampled wings. Default is 10.0.
- Returns:
1D array of timestamps in Julian Date (JD), sorted in ascending order.
- Return type:
numpy.ndarray
- MicroLIA_Sim.microlensing._compute_fsource_fblend_for_band(*, band: str, source_mag: float, blend_mags: dict[str, float] | None, blend_g: dict[str, float] | float | None) tuple[float, float][source]
Compute per-band source and blend fluxes (nJy) from magnitude-based inputs.
This helper converts the photometric inputs for a single band into the
(fsource, fblend)values expected by pyLIMA. It supports two mutually exclusive blending conventions:blend_mags(physical blending): -source_magis the source-only AB magnitude in this band. -blend_mags[band]is the blend-only AB magnitude in this band.blend_g(blend ratio method): -source_magis the total baseline AB magnitude in this band (source + blend). -blend_gdefines the flux ratiog = f_blend / f_source(either a scalar applied to all bands or a per-band dict).
If neither blending input is provided, the blend flux is set to 0 and the source flux is computed directly from
source_mag.- Parameters:
band (str) – Band label (e.g.,
"g","r","i"). Used to indexblend_magsor dict-styleblend_gwhen provided.source_mag (float) – AB magnitude in the specified band. Interpretation depends on blending mode: source-only if
blend_magsis provided, otherwise total baseline ifblend_gis provided, otherwise source-only with no blend.blend_mags (dict of str to float or None) – Blend-only AB magnitudes per band. If provided, must contain
band.blend_g (dict of str to float, float, or None) – Blend-to-source flux ratio
g = f_blend / f_source. May be a scalar or per-band dictionary. If a dict is provided, it must containband.
- Returns:
(fsource_njy, fblend_njy)in nJy.- Return type:
- MicroLIA_Sim.microlensing.simulate_perfect_event(*, model_type: str, ra: float, dec: float, t0_mjd: float, u0: float, tE: float, bands: tuple[str, Ellipsis] = ('u', 'g', 'r', 'i', 'z', 'y'), time_grid_jd: numpy.ndarray | None = None, model_params: dict | None = None, parallax_params: dict | None = None, source_mags: dict[str, float] | None = None, blend_mags: dict[str, float] | None = None, blend_g: dict[str, float] | float | None = None) dict[str, pandas.DataFrame][source]
Simulate a noise-free (“perfect”) multi-band microlensing light curve with pyLIMA.
This function constructs a pyLIMA
Eventwith one simulated telescope per band, evaluates the selected microlensing model on a user-specified (or automatically generated) time grid, and returns per-band light curves in both magnitude and flux (nJy). No observational noise is added; the intent is for downstream code to resample to a survey cadence and inject noise separately.- Parameters:
model_type (str) – Microlensing model identifier. Supported values are the keys of
MODEL_SPECS(e.g.,"PSPL","FSPL","USBL","NFW","BS"). The value is normalized via_normalize_model_type.ra (float) – Right ascension of the event in degrees.
dec (float) – Declination of the event in degrees.
t0_mjd (float) – Time of maximum magnification in Modified Julian Date (MJD).
u0 (float) – Impact parameter at closest approach (dimensionless).
tE (float) – Einstein timescale in days.
bands (tuple of str, optional) – Photometric bands to simulate. One pyLIMA telescope is created per band. Default is
("u", "g", "r", "i", "z", "y").time_grid_jd (numpy.ndarray or None, optional) – Array of timestamps in Julian Date (JD). If None, an adaptive grid is generated with
build_time_grid_jd(). Default is None.model_params (dict or None, optional) – Model-specific parameters. Requirements depend on
model_typeand are enforced byvalidate_model_params(). Examples: - FSPL:{"rho": 1e-3}- USBL:{"s": 1.15, "q": 1e-3, "rho": 1e-3, "alpha": 0.4, "origin": "center_of_mass"}- NFW/BS:{"t_m": 3.0}parallax_params (dict or None, optional) – Parallax parameters
{"piEN": ..., "piEE": ...}. If None, parallax is disabled. Validated byvalidate_parallax().source_mags (dict of str to float or None, optional) – Source magnitudes per band in AB mag. Must include all requested
bands. Interpretation depends on blending mode (seeblend_mags/blend_g).blend_mags (dict of str to float or None, optional) – Blend-only magnitudes per band in AB mag (physical blending). If provided, must include all requested
bands. Mutually exclusive withblend_g.blend_g (dict of str to float, float, or None, optional) – Blend ratio method with
g = f_blend / f_source. May be a scalar applied to all bands or a per-band dict. If provided,source_magsare interpreted as total baseline magnitudes (source + blend). Mutually exclusive withblend_mags.
- Returns:
Mapping
band -> lightcurve. Each DataFrame contains columns:mjd: timestamps in MJDflux_njy: flux density in nJy (derived from model magnitudes)mag: AB magnitudes from pyLIMA
Rows are sorted by
mjdwithin each band.- Return type:
dict of str to pandas.DataFrame
- MicroLIA_Sim.microlensing.write_lightcurves_txt(lightcurves: dict[str, pandas.DataFrame], output_file: str, *, meta: dict | None = None) None[source]
Write multi-band light curves to a single tab-delimited text file.
- Parameters:
lightcurves (dict of str to pandas.DataFrame) – Mapping
band -> DataFrame. Each DataFrame must contain the columns"mjd","mag", and"flux_njy".output_file (str) – Path to the output text file.
meta (dict or None, optional) – Optional metadata to include as comment lines at the top of the file. Default is None.
- Returns:
This function writes a file and returns None.
- Return type:
None
- MicroLIA_Sim.microlensing.plot_lightcurves_mag(lightcurves: dict[str, pandas.DataFrame], *, title: str | None = None, invert_mag: bool = True)[source]
Plot multi-band light curves in AB magnitudes versus MJD.
- Parameters:
lightcurves (dict of str to pandas.DataFrame) – Mapping
band -> DataFrame. Each DataFrame must contain the columns"mjd"and"mag".title (str or None, optional) – Optional plot title. Default is None.
invert_mag (bool, optional) – If True, invert the y-axis so smaller magnitudes plot higher. Default is True.
- Returns:
Displays a Matplotlib figure and returns None.
- Return type:
None