galfits.gsfit

galfits.gsfit.gradient_clipping(gradients, max_norm)[source]
class galfits.gsfit.gsfitter(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: object

Multi-band SED and image fitting engine for galaxies, AGN, and stars.

The gsfitter class provides a unified framework for fitting galaxy models to multi-wavelength photometric and spectroscopic data. It supports simultaneous fitting of structural parameters, stellar populations, and nebular emission using various optimization and sampling algorithms including gradient descent, nested sampling, and MCMC.

Parameters:
  • GSdata (GSData object, optional) – Multi-band imaging and spectroscopic data to fit. Should contain photometric images, error maps, PSFs, and optionally spectra. Default is None.

  • model_list (list, optional) – List of model objects (Galaxy, AGN, Star) to fit to the data. Default is [].

  • mtype_list (list of str, optional) – Type identifier for each model (‘galaxy’, ‘agn’, ‘star’). Must have same length as model_list. Default is [].

  • lmParameters (lmfit.Parameters, optional) – Parameter object defining all fit parameters with bounds, initial values, and constraints. Default is None.

  • g_prior (list of tuples, optional) – Gaussian priors on parameters. Each tuple: (param_name, mean, std). Default is [].

  • wight_spec (float, optional) – Relative weight for spectroscopic data vs. photometric data in chi-squared. Default is 1.0.

GSdata

Data object containing observations.

Type:

GSData

model_list

All model objects being fit.

Type:

list

gmodel_list

Galaxy model objects only.

Type:

list

psfmodel_list

Point source (AGN, star) model objects.

Type:

list

lmParameters

Parameter definitions with bounds and constraints.

Type:

lmfit.Parameters

theta0

Initial parameter values for free parameters.

Type:

array_like

ndim

Number of free parameters.

Type:

int

varnames

Names of free parameters.

Type:

list

pardict

Dictionary of all parameter values.

Type:

dict

gprior

Boolean mask indicating which parameters have Gaussian priors.

Type:

array_like

lnprior(theta)

Compute log-prior probability.

lnlike(theta)

Compute log-likelihood given data.

lnprob(theta)[source]

Compute log-posterior probability.

run_lmfit(**kwargs)

Perform least-squares optimization using lmfit.

run_dynesty(**kwargs)

Perform nested sampling using dynesty.

run_jaxopt(**kwargs)

Perform gradient-based optimization using JAX.

Notes

The fitting process:

  1. Forward Model: For given parameters:

    • Generate mass maps for each galaxy component

    • Compute SEDs for each component

    • Create model images in each band

    • Convolve with PSFs

    • Generate model spectra if available

  2. Likelihood: Compare to data:

    \[\chi^2 = \sum_{bands} \frac{(I_{data} - I_{model})^2}{\sigma^2} + w_{spec} \sum_{\lambda} \frac{(F_{data} - F_{model})^2}{\sigma_{spec}^2}\]
  3. Optimization/Sampling: Find best-fit or posterior distribution

The class uses JAX for automatic differentiation, enabling efficient gradient-based optimization. It supports:

  • Multi-component galaxy decomposition (bulge+disk+bar)

  • Simultaneous galaxy + AGN fitting

  • Spatially resolved stellar population gradients

  • Nebular emission modeling

  • Energy balance dust emission

Examples

>>> from galfits import gsfitter, GSData, Galaxy, AGN
>>> # Setup data
>>> data = GSData()
>>> data.add_image('sdss_r', image, error, psf)
>>> # Setup models
>>> gal = Galaxy(z=0.1, name='gal')
>>> gal.add_subC('bulge', logM=10.5, ...)
>>> agn = AGN(z=0.1, name='agn')
>>> # Setup fitter
>>> fitter = gsfitter(GSdata=data,
...                   model_list=[gal, agn],
...                   mtype_list=['galaxy', 'agn'],
...                   lmParameters=params)
>>> # Run fit
>>> result = fitter.run_lmfit(method='least_squares')

See also

GSData

Data container for multi-band observations.

Galaxy

Galaxy model class.

AGN

AGN model class.

Set_Update_Constraints(UC_func=None)[source]
blackmcmc(algo='NUTS', num_warmup=1000, iniscale=0.1, r_step=0.1, num_samples=1000, num_chains=2, num_steps=1)[source]
cal_model_image(pardict=None, ndisagn=False, wrange=[0.85, 1.15])[source]
cal_residual(theta)[source]
chisq_fit()[source]
evolution_strategies(num_generations=10000, popsize=10, seed=9527, inisize=0.4, verbose=True, method='CMA_ES', bayesian=False, logsigmainits=-3, early_stop_threshold=None, early_stop_patience=50, calsigma=False, es_params=None)[source]

Evolution Strategies for global optimization using Evosax.

Derivative-free optimization that evolves a population of solutions toward the global minimum. Excellent for multi-modal problems and when gradients are unavailable or unreliable. Uses CMA-ES (Covariance Matrix Adaptation) by default.

Parameters:
  • num_generations (int, default=10000) – Maximum number of generations (iterations) to evolve population. Each generation evaluates popsize solutions.

  • popsize (int, default=10) –

    Population size (number of candidate solutions per generation). Larger = better exploration but slower. Recommended:

    • Simple problems: 10-20

    • Complex/multi-modal: 20-50

    • High-dimensional (>20 params): 50-100

  • seed (int, default=9527) – Random seed for reproducibility.

  • inisize (float, default=0.4) – Initial search range in logit-transformed space. Larger = wider exploration, smaller = local search.

  • verbose (bool, default=True) – Whether to show progress bar during evolution.

  • method (str, default='CMA_ES') –

    Evolution strategy algorithm. Options:

    • ’CMA_ES’: Covariance Matrix Adaptation (best for most problems)

    • ’Sep_CMA_ES’: Separable CMA-ES (faster for high-D, no correlations)

    • ’OpenES’: OpenAI’s Evolution Strategy (simpler, faster)

    • ’PGPE’: Policy Gradients with Parameter Exploration

  • bayesian (bool, default=False) – Whether to include Gaussian prior terms in fitness function.

  • logsigmainits (float, default=-3) – Log10 of initial standard deviation for parameter search. -3 means σ=0.001 in logit space.

  • early_stop_threshold (float or None) – Fitness (chi-squared) threshold for early termination. Stops if best fitness < threshold.

  • early_stop_patience (int, default=50) – Number of generations without improvement before early stopping.

  • calsigma (bool, default=False) – Whether to calculate parameter uncertainties after optimization.

  • es_params (dict or None) –

    Algorithm-specific parameters to override defaults. For CMA-ES:

    • ’elite_ratio’: Fraction of top performers to use (default: 0.4)

    • ’use_negative_weights’: Use negative weights (default: True)

    • ’std_init’, ‘std_min’, ‘std_max’: Adaptation limits

Returns:

Dictionary containing:

  • ’best_theta’array_like

    Best-fit parameter values across all generations

  • ’uncertainty’array_like

    Parameter uncertainties (if calsigma=True)

  • ’chisq’float

    Best chi-squared value achieved

  • ’fitness_history’array_like

    Best fitness per generation (for convergence diagnostics)

  • ’state’ES state object

    Final evolution strategy state (population, covariance, etc.)

Return type:

dict

Notes

CMA-ES algorithm overview:

  1. Initialize population around starting point

  2. Evaluate fitness (chi-squared) for all candidates

  3. Select elite candidates (top 40% by default)

  4. Update search distribution (mean + covariance matrix)

  5. Adapt step size based on success rate

  6. Generate new population from updated distribution

  7. Repeat until convergence or max generations

Advantages over gradient methods:

  • Finds global minimum (not trapped in local minima)

  • No derivatives needed (works with non-smooth chi-squared)

  • Automatically adapts search direction and scale

  • Robust to noise and parameter correlations

When to use:

  • Initial exploration with poor starting guess

  • Multi-component models with degenerate solutions

  • When optimizer gets stuck in local minimum

  • Before nested sampling to find good starting point

Performance comparison:

  • vs optimizer: 10-100× slower, but finds global minimum

  • vs nested_sampling: 2-5× faster, but no full posterior

  • vs grid search: 100-1000× more efficient

Examples

>>> # Basic global optimization
>>> result = fitter.evolution_strategies(
...     num_generations=5000,
...     popsize=20,
...     method='CMA_ES'
... )
>>>
>>> # Large parameter space with custom settings
>>> result = fitter.evolution_strategies(
...     num_generations=10000,
...     popsize=50,
...     inisize=0.8,  # wider search
...     es_params={'elite_ratio': 0.3}
... )
>>>
>>> # Quick exploration then refine with optimizer
>>> es_result = fitter.evolution_strategies(num_generations=3000)
>>> opt_result = fitter.optimizer(num_steps=2000)

See also

optimizer

Local gradient-based optimization

nested_sampling

Bayesian posterior sampling

evolution_strategies_multi

Multi-start ES for very hard problems

References

Hansen & Ostermeier 2001, Evolutionary Computation, 9, 159 (CMA-ES) Salimans et al. 2017, arXiv:1703.03864 (OpenES)

evolution_strategies_multi(num_starts=10, num_generations=8000, popsize=20, seed=42, calsigma=False, std_init=0.05, std_min=1e-06, std_max=1.0, elite_ratio=0.4, NsGPU=10, bayesian=False)[source]

Multi-start Evolution Strategies optimization using Sep_CMA_ES.

This follows the same multi-device batching structure as GalfitS: - pmap over devices - vmap over NsGPU starts per device - repeat loops until all starts are processed

Notes (per your requirement): - Starting points are drawn randomly in the parameter space (theta). - ES hyperparameters (std_init/std_min/std_max/elite_ratio, etc.) are fixed and NOT varied across starting points.

Parameters:
  • num_starts – Total number of starting points.

  • NsGPU – Number of starting points per device per loop.

evolution_strategies_theta(num_generations=10000, popsize=20, seed=9527, verbose=True, method='Sep_CMA_ES', bayesian=False, early_stop_threshold=None, early_stop_patience=500, calsigma=False, es_params=None)[source]

Evolution Strategies optimization with hard box-constraints via clipping.

Parameters:

num_generationsint

Maximum number of generations to run

popsizeint

Population size for the evolutionary algorithm

seedint

Random seed for reproducibility

verbosebool

Whether to show progress information

methodstr

ES algorithm to use - supported options: ‘CMA_ES’, ‘OpenES’, ‘PGPE’, ‘SimpleGA’, ‘DES’, etc. Any algorithm available in evosax.algorithms can be specified

bayesianbool

Whether to add Gaussian priors in logpdf

early_stop_thresholdfloat

Fitness threshold for early stopping

early_stop_patienceint

Maximum generations without improvement before stopping

calsigmabool

Whether to estimate parameter uncertainties (Fisher or MCMC)

es_paramsdict

Override default algorithm settings

flowmc(n_chains=80, r_step=0.1, n_layer=10, n_hidden=128, n_loop_training=30, n_loop_production=10, n_local_steps=100, n_global_steps=10, num_epochs=5, learning_rate=0.005, momentum=0.9, batch_size=5000, max_samples=5000, iniscale=0.5, use_global=True, bejit=True, sampler='GRW', n_leapfrog=1, inverse_metric=1)[source]
get_model(name)[source]
jaxopt(method='scipy', maxiter=1000, tol=0.0001, **kwargs)[source]
jaxopt_zgrid(Z_grid, method='scipy', scipymethod='L-BFGS-B', maxiter=1000, tol=0.0001, bayesian=False, **solver_kwargs)[source]
Parameters:
  • method (str)

  • maxiter (int)

  • tol (float)

  • bayesian (bool)

jnesty_nested_sampling(maxiters=1000000, dlogz=0.02, nlive=500, bound='multi', rwalk_K=None, target_acceptance=0.5, queue_size=None, device='gpu', verbose=True, workplace=None, jnesty_kwargs={})[source]

Nested sampling using JNesty for Bayesian parameter estimation.

GPU-accelerated nested sampling with JAX. Computes full posterior distributions, parameter uncertainties, and Bayesian evidence.

Parameters:
  • maxiters (int, default=1000000) – Maximum number of iterations.

  • dlogz (float, default=0.02) – Convergence threshold on delta_logZ.

  • nlive (int, default=500) – Number of live points.

  • bound (str, default='none') – Bounding method: ‘multi’ (recommended), ‘single’, or ‘none’.

  • rwalk_K (int or None, default=None) – Random walk steps per iteration. Auto-tuned if None.

  • target_acceptance (float, default=0.5) – Target acceptance rate for scale adaptation.

  • queue_size (int or None, default=None) – Number of parallel queue entries for GPU likelihood evals. Auto-set to 8 for bound=’multi’ (Dynesty default).

  • device (str, default='gpu') – Device: ‘gpu’ or ‘cpu’.

  • verbose (bool, default=True) – Whether to show progress during sampling.

  • jnesty_kwargs (dict, default={}) – Additional keyword arguments passed to jnesty.NestedSampler.

Returns:

Dictionary with ‘fitresu’, ‘samples’, ‘best_theta’, ‘uncertainty’, ‘theta’, ‘param_errors’, ‘sampler’.

Return type:

dict

lnprob(theta)[source]

Compute log-posterior probability (for MCMC/nested sampling).

Combines log-prior and log-likelihood following Bayes’ theorem: log P(θ|D) = log P(D|θ) + log P(θ) + const

Parameters:

theta (array_like) – Parameter vector (free parameters only).

Returns:

Log-posterior probability.

Return type:

float

Notes

Used by dynesty nested sampling and MCMC samplers. Not used by lmfit (uses chi-squared) or jaxopt (uses loss).

loglike(theta)[source]

Compute log-likelihood from data-model residuals.

Assumes Gaussian errors: log L = -0.5 Σ(residual²). JIT-compiled for performance.

Parameters:

theta (array_like) – Parameter vector.

Returns:

Log-likelihood (negative chi-squared / 2).

Return type:

float

logprior(theta)[source]

Compute log-prior probability with soft bounds and Gaussian priors.

Combines uniform priors (with smooth boundaries) and Gaussian priors for specified parameters. Uses sigmoid transitions at bounds to avoid hard cutoffs that cause gradient issues.

Parameters:

theta (array_like) – Parameter vector.

Returns:

Log-prior probability.

Return type:

float

Notes

For parameters without Gaussian priors: P(θ) = Uniform(min, max) with smooth sigmoid transitions. For parameters with priors: P(θ) = N(μ, σ).

loose_fix_pars(loose_list=[], fix_list=[], g_prior=[])[source]
mcmc(algo='NUTS', num_warmup=1000, iniscale=0.1, r_step=0.1, num_samples=1000, num_chains=2, num_steps=1, dense_mass=False, seed=0)[source]
minimize(method='scipy', scipymethod='L-BFGS-B', maxiter=1000, tol=0.0001, constrain=False, **kwargs)[source]
nested_sampling(dynamical=False, maxiters=1000, dlogz=0.02, workers=1, nlive=150, sample_method='slice', bound='multi', queue_size=None, progress=True, dynesty_kwargs={})[source]

Nested sampling for Bayesian parameter estimation using Dynesty.

Computes full posterior distributions, parameter uncertainties, and Bayesian evidence. Explores multi-modal posteriors more robustly than MCMC. Recommended for final publication-quality uncertainties.

Parameters:
  • dynamical (bool, default=False) –

    Whether to use dynamic nested sampling. Dynamic mode adaptively allocates live points to maximize posterior resolution.

    • False: Static nested sampling (faster, less accurate)

    • True: Dynamic nested sampling (slower, better uncertainties)

  • maxiters (int, default=1000) – Maximum number of likelihood evaluations. Increase for complex multi-component models or tight convergence.

  • dlogz (float, default=0.02) – Target evidence tolerance for termination. Smaller = more accurate but slower. Typical range: 0.01-0.5.

  • workers (int, default=1) – Number of parallel processes for likelihood evaluation. Set to cpu_count() for maximum speed.

  • nlive (int, default=150) –

    Number of live points. More points = better posterior resolution but slower. Recommended:

    • Simple models (1-5 params): 50-100

    • Moderate models (5-15 params): 150-300

    • Complex models (>15 params): 300-500

  • sample_method (str, default='slice') –

    Sampling algorithm for new live points. Options:

    • ’slice’: Slice sampling (robust, recommended)

    • ’rwalk’: Random walk (fast but may struggle with correlations)

    • ’unif’: Uniform sampling (for simple/low-D problems)

  • bound (str, default='multi') –

    Bounding method to constrain live point proposals. Options:

    • ’multi’: Multiple ellipsoids (handles multi-modal posteriors)

    • ’single’: Single ellipsoid (for unimodal posteriors)

    • ’balls’: Overlapping balls (robust but slower)

  • queue_size (int or None) – Size of parallel queue. Auto-set if None.

  • progress (bool, default=True) – Whether to show progress bar during sampling.

  • dynesty_kwargs (dict, default={}) – Additional keyword arguments passed to dynesty.DynamicNestedSampler.

Returns:

Dictionary containing:

  • ’fitresu’dynesty.results.Results

    Full dynesty results object with evidence, samples, weights

  • ’samples’array_like, shape (n_samples, n_params)

    Posterior samples (weighted by evidence)

  • ’best_theta’array_like

    Posterior mean parameter values

  • ’uncertainty’array_like

    Posterior standard deviations

Return type:

dict

Notes

Nested sampling algorithm:

  1. Initialize nlive points uniformly in prior

  2. Find point with lowest likelihood

  3. Replace with new point from prior with L > L_min

  4. Repeat until evidence converges (ΔlogZ < dlogz)

Advantages over MCMC:

  • Computes Bayesian evidence for model comparison

  • Handles multi-modal posteriors naturally

  • No burn-in required

  • Better for high-dimensional problems (>10 params)

When to use:

  • Final parameter uncertainties for publication

  • Model comparison (evidence ratios)

  • Multi-component fits with degeneracies

  • After optimizer to explore parameter space

Performance tips:

  • Use workers > 1 for CPU parallelization

  • Start with dynamical=False for quick exploration

  • Use dynamical=True for final uncertainties

  • Increase nlive if posterior is multi-modal

Examples

>>> # Quick nested sampling
>>> result = fitter.nested_sampling(nlive=100, dlogz=0.1)
>>> print(f"logZ = {result['fitresu'].logz[-1]:.2f}")
>>>
>>> # Publication-quality with parallelization
>>> result = fitter.nested_sampling(
...     dynamical=True,
...     nlive=300,
...     dlogz=0.01,
...     workers=8
... )
>>> samples = result['samples']
>>>
>>> # Model comparison
>>> result1 = fitter1.nested_sampling()
>>> result2 = fitter2.nested_sampling()
>>> delta_logZ = result1['fitresu'].logz[-1] - result2['fitresu'].logz[-1]
>>> print(f"Bayes factor: {jnp.exp(delta_logZ):.2f}")

See also

optimizer

Fast local optimization

evolution_strategies

Global optimization without full posterior

References

Skilling 2006, Bayesian Analysis, 1, 833 Speagle 2020, MNRAS, 493, 3132 (dynesty paper)

optimizer(num_steps=1000, learning_rate=0.001, gtransformation=False, calsigma=False, optimizer='adam', debugmode=False, clip=5.0, bayesian=False)[source]

Gradient-based optimization using JAX and Optax optimizers.

Performs chi-squared minimization using automatic differentiation for fast, local optimization. Supports Adam, SGD, AdaBelief, and Adamax optimizers with optional gradient clipping and Bayesian priors.

Parameters:
  • num_steps (int, default=1000) – Number of optimization steps (gradient updates).

  • learning_rate (float, default=1e-3) – Step size for parameter updates. Smaller = more stable, slower.

  • gtransformation (bool, default=False) – Whether to apply gradient clipping based on parameter step sizes. Recommended for SGD to prevent divergence.

  • calsigma (bool, default=False) – Whether to calculate parameter uncertainties after optimization. Uses Fisher information matrix approximation.

  • optimizer (str, default='adam') –

    Optimizer algorithm to use. Options:

    • ’adam’: Adaptive moment estimation (recommended for most cases)

    • ’sgd’: Stochastic gradient descent (requires gtransformation=True)

    • ’adabelief’: AdaBelief optimizer (adaptive learning rate)

    • ’adamax’: Adamax variant (more robust to sparse gradients)

  • debugmode (bool, default=False) – Whether to save optimization trace and detect NaN parameters.

  • clip (float, default=5.) – Maximum absolute value for logit-transformed parameters. Prevents extreme parameter values.

  • bayesian (bool, default=False) – Whether to include Gaussian prior terms in loss function. Uses g_prior list from initialization.

Returns:

Dictionary containing:

  • ’best_theta’array_like

    Best-fit parameter values

  • ’uncertainty’array_like

    Parameter uncertainties (if calsigma=True)

  • ’chisq’float

    Final chi-squared value

  • ’trace’list of arrays

    Parameter evolution (if debugmode=True)

Return type:

dict

Notes

Optimization strategy:

Parameters are transformed to unconstrained space via logit transform:

\[u = \frac{\theta - \theta_{\rm min}}{\theta_{\rm max} - \theta_{\rm min}}\]
\[{\rm logit}(u) = \log\left(\frac{u}{1-u}\right)\]

This ensures parameters stay within bounds without penalty terms.

Optimizer comparison:

  • Adam: Best for most problems, adapts learning rate per parameter

  • SGD: Fastest but needs careful tuning, use with gtransformation=True

  • AdaBelief: Good for noisy data, adapts to gradient magnitude

  • Adamax: More stable for problems with sparse/large gradients

When to use:

  • Initial fits: Use optimizer with ~1000-5000 steps

  • After nested sampling: Refine best-fit with optimizer(num_steps=500)

  • Multi-component models: May need 10000+ steps for convergence

Examples

>>> # Basic optimization
>>> result = fitter.optimizer(num_steps=2000, learning_rate=1e-3)
>>>
>>> # With uncertainties
>>> result = fitter.optimizer(num_steps=5000, calsigma=True)
>>> print(result['uncertainty'])
>>>
>>> # With Bayesian priors
>>> result = fitter.optimizer(bayesian=True, num_steps=3000)

See also

evolution_strategies

Global optimization for multi-modal problems

nested_sampling

Full posterior sampling

optimizer_multi(num_starts=10, num_steps=15000, learning_rate=0.0001, optimizer='adamw', use_schedule=True, bayesian=False, calsigma=False, warmup_steps=1000, decay_steps=10000, seed=42, NsGPU=10)[source]

Multi-start optimizer that scales across all available GPUs.

Logic: - Detect NGPU automatically - Each loop launches NGPU devices in parallel (pmap) - Each device runs NsGPU starting points in parallel (vmap) - Repeat loops until NGPU * NsGPU * n_loops >= num_starts

If no GPU is available, it falls back to CPU devices (typically 1).

optimizer_zgrid(Z_grid, num_steps=1000, learning_rate=0.001, calsigma=False, optimizer='adam', bayesian=False)[source]
paracall(lfparam)[source]
plot_jnesty_diagnostics(result, save_dir='./')[source]

Plot JNesty diagnostic figures.

Parameters:
  • result (dict) – Results dictionary from jnesty_nested_sampling()

  • save_dir (str, default='./') – Directory to save plots

Returns:

List of file paths to saved plots

Return type:

list

ptranform(u)[source]

transform the unit cube to the prior u: unit cube, [0,1] array, shape = (ndim,) bounds: for uniform prior (gprior = False), prior bounds, [min, max], shape = (ndim,2) for gaussian prior (gprior = True), prior center and stddev, [cen, wid], shape = (ndim,2)

set_wight_spec(wight_spec)[source]
update_parameter(theta)[source]
class galfits.gsfit.imagefitter_SED(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: gsfitter

SED-based multi-band image fitter.

Simultaneously fits galaxy morphology and SED by generating full spectral datacubes (IFU). More accurate than photometry-only fitting but computationally expensive. Recommended for science-grade SED constraints.

Inherits all optimization methods from gsfitter.

See also

imagefitter_phot

Faster photometry-only fitting

sedfitter

Photometric SED fitting without imaging

cal_model_image(pardict=None, ndisagn=False, wrange=[0.85, 1.15])[source]
cal_residual(theta)[source]
class galfits.gsfit.imagefitter_SED_allconst(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: gsfitter

SED-based multi-band image fitter optimized for constant SEDs.

cal_model_image(pardict=None, ndisagn=False, wrange=[0.85, 1.15])[source]
cal_residual(theta)[source]
class galfits.gsfit.imagefitter_SED_allconstNV(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: gsfitter

SED-based multi-band image fitter optimized for constant SEDs natively evaluated per image frame.

cal_model_image(pardict=None, ndisagn=False, wrange=[0.85, 1.15])[source]
cal_residual(theta)[source]
class galfits.gsfit.imagefitter_phot(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: gsfitter

Photometry-based multi-band image fitter.

Optimized for fitting multi-wavelength imaging without SED modeling. Uses band-specific normalization parameters instead of full SED computation. Faster than imagefitter_SED for pure morphology fitting.

Inherits all optimization methods from gsfitter.

See also

imagefitter_SED

Full SED-based image fitting

mbifitter

Image + grism fitting

cal_model_image(pardict=None, ndisagn=False, wrange=[0.85, 1.15])[source]
cal_residual(theta)[source]
galfits.gsfit.logit(p)[source]
class galfits.gsfit.mbifitter(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: gsfitter

Multi-band image fitter with grism spectroscopy support.

Extends gsfitter to simultaneously fit multi-wavelength imaging and slitless grism spectra. Handles WCS shifts, PSF convolution, and dispersed spectral data.

Inherits all methods from gsfitter (optimizer, nested_sampling, evolution_strategies) with specialized residual calculation for combined image + grism fitting.

See also

imagefitter_phot

Photometry-only image fitting

imagefitter_SED

SED-based image fitting

vdfitter

Spectroscopy-only fitting

cal_model_image(pardict=None, ndisagn=False, wrange=[0.85, 1.15])[source]
cal_residual(theta)[source]
class galfits.gsfit.mesfitter(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: gsfitter

cal_model_image(pardict=None)[source]
cal_residual(theta)[source]

fourier sersic model to be added

class galfits.gsfit.sedfitter(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: gsfitter

Photometric SED fitter without spatial information. (with optional spectroscopy)

Fits multi-band photometry to galaxy and AGN SED models. Fastest fitting mode - uses integrated photometry without morphology. Ideal for large surveys or unresolved sources.

Inherits all optimization methods from gsfitter.

See also

imagefitter_SED

SED fitting with resolved morphology

vdfitter

Spectroscopic fitting

cal_model_image(pardict=None, ndisagn=False, wrange=[0.85, 1.15])[source]
cal_residual(theta)[source]
galfits.gsfit.sigmoid(x)[source]
class galfits.gsfit.simage_fitter(image, PSF, mask=None, error=None)[source]

Bases: object

fit the image data with different profiles

fit_with_model(modelnames, theta0s, bounds, num_steps=3000, learning_rate=0.001)[source]

fit the image with a give composite model

Parameters:
  • modelnames (list) – list of model names

  • theta0s (list) – list of initial parameters

  • ['sersic' (when the modelnames is)

  • 'ferrer'

  • ...]

  • [[x1 (the theta0s should be)

  • y1

  • q1

  • PA1

  • Re1

  • n1

  • logL1]

  • [x2

  • y2

  • q2

  • PA2

  • R_out2

  • a2

  • beta2

  • logL2]

  • ...]

get_modelimage(modelnames, thetas)[source]

get the model image with the given parameters

Parameters:
  • modelnames (list) – list of model names

  • theta (list) – list of parameters

  • ['sersic' (when the modelnames is)

  • 'ferrer'

  • ...]

  • [[x1 (the theta should be)

  • y1

  • q1

  • PA1

  • Re1

  • n1

  • L1]

  • [x2

  • y2

  • q2

  • PA2

  • R_out2

  • a2

  • beta2

  • L2]

  • ...]

update_image(image)[source]
galfits.gsfit.soft_bound(x, bound, steepness)[source]
class galfits.gsfit.vdfitter(GSdata=None, model_list=[], mtype_list=[], lmParameters=None, g_prior=[], f_cont_t_adj_priors=None, wight_spec=1.0)[source]

Bases: gsfitter

Spectroscopy-only fitter for velocity dispersion and emission lines.

Fits galaxy and AGN spectra without spatial information. Uses fiducial SEDs with aperture weighting. Optimized for extracting spectroscopic parameters (line fluxes, kinematics, continuum).

Inherits all optimization methods from gsfitter.

See also

mbifitter

Combined imaging + spectroscopy

sedfitter

Photometric SED fitting

cal_model_image(pardict=None, ndisagn=False, wrange=[0.85, 1.15])[source]
cal_residual(theta)[source]