galfits.galaxy

Module for galaxy modeling including multi-component stellar populations, nebular emission, and spatially resolved properties.

Galaxy Classes

class galfits.galaxy.Galaxy(regionz, z=0.0, ebv_G=0.0, name='undefined', currentage=13.8, wave_temp=None)[source]

Bases: object

Galaxy object for modeling multi-component stellar populations and nebular emission.

The Galaxy class represents a galaxy as a collection of subcomponents (e.g., bulge, disk) each with its own structural profile, stellar population properties (age, metallicity, star formation history), and dust attenuation. It handles spatially resolved modeling including radial gradients in stellar population parameters.

Parameters:
  • regionz (float) – Redshift of the region being modeled (can differ from galaxy redshift for cosmological calculations).

  • z (float, optional) – Redshift of the galaxy. Default is 0.

  • ebv_G (float, optional) – Galactic foreground extinction E(B-V) in magnitudes. Default is 0.

  • name (str, optional) – Name identifier for the galaxy. Default is ‘undefined’.

  • currentage (float, optional) – Current age of the universe at the galaxy’s redshift in Gyr. Default is 13.8.

  • wave_temp (array_like, optional) – Wavelength template for high-resolution spectral modeling. Default is None.

name

Galaxy identifier.

Type:

str

Nsub

Number of subcomponents in the galaxy.

Type:

int

subnames

Names of all subcomponents.

Type:

list

subCs

Structural parameters for each subcomponent (Sersic, exponential, etc.).

Type:

dict

Nebular

Nebular emission model object if initialized.

Type:

ISM or None

ageparams

Age distribution parameters for each subcomponent.

Type:

dict

Zparams

Metallicity distribution parameters for each subcomponent.

Type:

dict

f_cont

Continuous star formation fraction parameters for each subcomponent.

Type:

dict

Avparams

Dust extinction parameters for each subcomponent.

Type:

dict

logMlist

Log stellar mass for each subcomponent (log10(M/Msun)).

Type:

dict

mass_map

2D spatial mass distribution for each subcomponent.

Type:

dict

SFR_map

2D star formation rate maps for each subcomponent.

Type:

dict

redshift

Galaxy redshift.

Type:

float

ebv_G

Galactic extinction.

Type:

float

rnorm

Normalization factor for cosmological distance effects.

Type:

float

Re

Effective radius for defining radial maps (kpc).

Type:

float

massimg

Total 2D stellar mass map summed over all components.

Type:

array_like

currentage

Current age of universe (Gyr).

Type:

float

Examples

>>> from galfits import Galaxy
>>> gal = Galaxy(regionz=0.1, z=0.1, name='NGC1234')
>>> gal.add_subC('bulge', logM=10.5, Sparams={'type': 'sersic', ...},
...              ageparam={'type': 'const', 'paradic': {'value': 8.0}},
...              Zparam={'type': 'const', 'paradic': {'value': 0.02}},
...              f_cont={'type': 'const', 'paradic': {'value': 0.1}},
...              Avparam={'type': 'const', 'paradic': {'value': 0.5}})

Notes

The Galaxy class uses JAX for efficient computation and supports:

  • Multiple structural components (Sersic, exponential, Ferrer, etc.)

  • Radial gradients in stellar population properties

  • Nebular emission (continuum and lines)

  • Dust attenuation with various attenuation curves

  • Star formation histories (constant, exponential, burst, binned)

  • Energy balance between absorbed starlight and dust emission

See also

AGN

AGN modeling class for active galactic nuclei.

ISM

Interstellar medium and nebular emission modeling.

__init__(regionz, z=0.0, ebv_G=0.0, name='undefined', currentage=13.8, wave_temp=None)[source]

Initialize a Galaxy object.

Parameters:
  • regionz (float) – Redshift of the region being modeled.

  • z (float, optional) – Galaxy redshift. Default is 0.

  • ebv_G (float, optional) – Galactic foreground extinction E(B-V). Default is 0.

  • name (str, optional) – Galaxy name identifier. Default is ‘undefined’.

  • currentage (float, optional) – Current age of universe in Gyr. Default is 13.8.

  • wave_temp (array_like, optional) – Wavelength grid for spectral templates. Default is None.

add_arbsubC(Pro_names, mass_map, ageparam, Zparam, f_cont, Avparam, sigmaparam={'paradic': {'value': 100}, 'type': 'const'}, arbi_para={'func': 'Users'})[source]

To add a subcomponent for a galaxy object

Pro_names: the name of the profiles e.g. = “sersic” “coresersic” “brokenexp” “moffat” “ferrer” “king” “pointsource”

params: a dictionary of the parameters for this subcomponent e.g. for sersic: {‘xcen’: 50.0, ‘ycen’: 50.0, ‘frac’: 0.704, ‘re’: 10.0, ‘nser’: 3.0, ‘ang’: -32.70422048691768, ‘axrat’: 1.0, ‘box’: 0.0, ‘convolve’: False}

ageparam: a dictionary of the age dsitribution parameters for this subcomponent e.g. {‘type’: ‘linear’, ‘paradic’: {‘k’: -0.05, ‘b’: 9.0}}

{‘type’: ‘const’, ‘paradic’: {‘value’: 5.0}}

Zparam: a dictionary of the matallicity dsitribution parameters for this subcomponent e.g. {‘type’: ‘linear’, ‘paradic’: {‘k’: 0.0, ‘b’: 0.02}}

f_cont: a dictionary of the fraction of starformation dsitribution parameters for this subcomponent between [0.,1.], fraction of starformation

add_subC(Pro_names, logM, Sparams, ageparam, Zparam, f_cont, Avparam, logU=-3, sigma=150.0, SFH='conti', Avbump=3, agnbin=[], SEDmode=0, table_model=None)[source]

Add a subcomponent (e.g., bulge, disk) to the galaxy model.

This method adds a structural and stellar population component to the galaxy. Each component has its own spatial profile, stellar mass, age distribution, metallicity, dust extinction, and star formation history.

Parameters:
  • Pro_names (str) – Name identifier for the subcomponent (e.g., ‘bulge’, ‘disk’, ‘bar’).

  • logM (float) – Log10 of total stellar mass for this component in solar masses.

  • Sparams (dict) –

    Structural parameters dictionary with keys:

    • ’type’ : str - Profile type (‘sersic’, ‘ferrer’, ‘edgeondisk’, etc.)

    • ’paradic’ : dict - Profile-specific parameters

    Example for Sersic: {‘type’: ‘sersic’, ‘paradic’: {‘xcen’: 0.0, ‘ycen’: 0.0, ‘Re’: 2.0,

    ’n’: 4.0, ‘ang’: 45.0, ‘axrat’: 0.7}}

  • ageparam (dict) –

    Age distribution parameters:

    • ’type’ : str - Distribution type (‘const’, ‘linear’, ‘exp’, ‘bins’)

    • ’paradic’ : dict - Type-specific parameters

    Example: {‘type’: ‘const’, ‘paradic’: {‘value’: 8.0}} for 8 Gyr uniform age

  • Zparam (dict) – Metallicity distribution parameters (same structure as ageparam). Example: {‘type’: ‘const’, ‘paradic’: {‘value’: 0.02}} for solar metallicity

  • f_cont (dict) – Continuous star formation fraction parameters (same structure). Values between 0 (all stars formed instantaneously) and 1 (continuous SF). Example: {‘type’: ‘const’, ‘paradic’: {‘value’: 0.1}}

  • Avparam (dict) – V-band dust extinction parameters in magnitudes (same structure). Example: {‘type’: ‘const’, ‘paradic’: {‘value’: 0.5}}

  • logU (float, optional) – Log10 of ionization parameter for nebular emission. Default is -3.

  • sigma (float, optional) – Velocity dispersion in km/s for kinematic modeling. Default is 150.

  • SFH (str, optional) – Star formation history type: ‘conti’ (continuous), ‘burst’, ‘bins’. Default is ‘conti’.

  • Avbump (float, optional) – Strength of the 2175 Angstrom extinction feature. Default is 3.

  • agnbin (list, optional) – Age bins for non-parametric SFH (when SFH=’bins’). Default is [].

  • SEDmode (int or str, optional) –

    SED components to include:

    • 0 : stars + nebular (default)

    • 1 : stars only

    • 2 : nebular only

    • 3 : dust only

    • 4 : stars + nebular + dust

    • ’T’ : table model

  • table_model (object, optional) – Custom table-based SED model. Default is None.

Notes

Multiple subcomponents can be added to represent complex galaxy morphologies. Each component contributes independently to the total SED and surface brightness distribution. Radial gradients are supported for age, Z, f_cont, and Av.

The method automatically updates internal tracking of whether all parameters are constant (for computational optimization).

Examples

>>> gal.add_subC('bulge', logM=10.5,
...              Sparams={'type': 'sersic', 'paradic': {'xcen': 0, 'ycen': 0,
...                       'Re': 1.0, 'n': 4.0, 'ang': 0, 'axrat': 0.8}},
...              ageparam={'type': 'const', 'paradic': {'value': 10.0}},
...              Zparam={'type': 'const', 'paradic': {'value': 0.02}},
...              f_cont={'type': 'const', 'paradic': {'value': 0.05}},
...              Avparam={'type': 'const', 'paradic': {'value': 0.3}})

See also

update_subC_para

Update parameters of an existing subcomponent.

fix_loose_subC

Fix or free parameters for fitting.

cal_dynamics(paradic=None)[source]
fiducial_sed(wavelength, apertures=None, nebularpar=None)[source]

Compute the integrated spectral energy distribution (SED) of the galaxy.

This method generates the total galaxy SED by summing contributions from all subcomponents, including stellar continuum, nebular emission (continuum and lines), and dust emission. It handles energy balance between absorbed starlight and dust re-emission when enabled.

Parameters:
  • wavelength (array_like) – Observed-frame wavelength grid in Angstroms.

  • apertures (array_like, optional) – Aperture correction factors for each component (fractional flux within aperture). Shape should be (n_components,). Default is None (no correction).

  • nebularpar (dict, optional) –

    Dictionary of nebular and dust emission parameters. Required if nebular emission or dust is enabled. Keys include:

    • ’logMdust_{component}’ : float - Log dust mass (computed if energy balance)

    • ’qPAH_{component}’ : float - PAH mass fraction (0-1)

    • ’Umin_{component}’ : float - Minimum radiation field intensity

    • ’alphad_{component}’ : float - Power-law slope for radiation field

    • ’gammad_{component}’ : float - Fraction of dust in power-law component

    • Additional line parameters if separate line modeling

Returns:

sed – Total galaxy SED at observed wavelengths in units of 10^-38 erg/s/cm²/Å, including distance normalization (rnorm factor).

Return type:

array_like

Notes

The SED computation process:

  1. For each component:

    1. Get stellar population parameters at center (age, Z, f_cont, Av)

    2. Compute stellar continuum from population synthesis models

    3. Add dust emission (either fixed or via energy balance)

    4. Compute nebular continuum from H II region models

    5. Apply table models if specified

    6. Apply aperture correction if provided

  2. Add emission lines (if separate line modeling):

    • Gaussian line profiles from Line_Emitter

  3. Redshift and extinction:

    • Transform from rest-frame to observed-frame

    • Apply Galactic foreground extinction

    • Apply distance normalization

Energy balance mode:

When enabled, dust luminosity equals absorbed stellar luminosity:

\[L_{dust} = \int (L_{\star,intrinsic} - L_{\star,attenuated}) d\lambda\]

This ensures physical consistency between dust attenuation and emission.

The returned SED includes: - Stellar continuum (attenuated) - Nebular continuum (free-free, free-bound, two-photon) - Emission lines (if withline=False in ISM) - Dust continuum (MIR to FIR) - Custom table models

Examples

>>> wavelength = np.arange(1000, 50000, 10)  # Å
>>> sed = gal.fiducial_sed(wavelength)
>>> # With aperture correction (50% of flux)
>>> apertures = [0.5, 0.5]  # For 2 components
>>> sed_aper = gal.fiducial_sed(wavelength, apertures=apertures)
>>> # Plot
>>> import matplotlib.pyplot as plt
>>> plt.loglog(wavelength, sed)
>>> plt.xlabel('Wavelength [Å]')
>>> plt.ylabel(r'$F_\lambda$ [$10^{-38}$ erg/s/cm²/Å]')

See also

generate_SED

Compute photometry in multiple bands.

fiducial_sed_3D

Compute SED with velocity broadening.

get_component_SED

Get individual component SEDs.

fiducial_sed_3D(wavelength, apertures=None, nebularpar=None)[source]

this function to fit star only

fix_loose_subC(Pro_names, lmfit_params, fix=True, structure=True, SED=True, norm=True)[source]

Lock or unlock fitting parameters for a sub-component.

Controls which parameters of a sub-component are allowed to vary during lmfit optimization. Enables staged fitting strategies (e.g., fit structure first, then SED properties).

Parameters:
  • Pro_names (str) – Sub-component name (e.g., ‘disk’, ‘bulge’).

  • lmfit_params (lmfit.Parameters) – Parameter object from lmfit containing all model parameters.

  • fix (bool, optional) – If True, lock parameters (set vary=False); if False, unlock them (set vary=True). Default: True.

  • structure (bool, optional) – Apply to structural parameters (Sérsic n, Re, q, PA, etc.). Default: True.

  • SED (bool, optional) – Apply to SED parameters (age, Z, Av, f_cont gradients). Default: True.

  • norm (bool, optional) – Apply to normalization parameter (logM). Default: True.

Returns:

Modifies lmfit_params in place.

Return type:

None

Notes

Common fitting strategies:

  1. Sequential fitting: Lock SED, fit structure → Lock structure, fit SED

  2. Normalization control: Lock logM to preserve flux while adjusting gradients

  3. Freezing components: Lock entire component when adding new ones

Parameter categories:

  • structure: Morphological parameters defining spatial distribution

  • SED: Spectral properties that vary spatially (age(r), Z(r), Av(r), f_cont(r))

  • norm: Total stellar mass (scales overall brightness)

This method is essential for stable multi-component fitting where simultaneous optimization of all parameters can lead to degeneracies.

See also

update_subC_para

Update parameter values from dictionary

add_subC

Add new sub-component with initial parameters

Examples

>>> # Stage 1: Fit morphology with fixed SED
>>> galaxy.fix_loose_subC('disk', params, fix=True, structure=False, SED=True)
>>> fitter.fit()
>>> # Stage 2: Fit SED with fixed morphology
>>> galaxy.fix_loose_subC('disk', params, fix=True, structure=True, SED=False)
>>> fitter.fit()
>>> # Stage 3: Unlock everything for joint fit
>>> galaxy.fix_loose_subC('disk', params, fix=False)
>>> fitter.fit()
generate_SED(resps, pardict=None)[source]
generate_SEDIFU(wavelength, nebularpar=None)[source]

Generate full 3D spectral datacube (IFU forward model).

Computes spatially resolved spectroscopy by combining stellar population SEDs with spatial gradients in age, metallicity, and attenuation. Produces synthetic IFU datacube matching observations from JWST/NIRSpec, VLT/MUSE, etc.

Parameters:
  • wavelength (array_like) – Observed-frame wavelength grid in Angstroms. Length N_λ.

  • nebularpar (dict, optional) –

    Nebular and dust emission parameters. Required if dust emission or table models are enabled. Expected keys:

    • ’logMdust_{comp}’: Log10 dust mass for each component

    • ’qPAH_{comp}’, ‘Umin_{comp}’, ‘alphad_{comp}’, ‘gammad_{comp}’: DL14 parameters

    • Additional keys for table models if configured

Returns:

tot_IFU – Synthetic IFU datacube in 10^38 erg/s/Å units. Axes: [spatial_y, spatial_x, wavelength].

Return type:

array_like, shape (ny, nx, nλ)

Notes

Algorithm overview:

  1. For each sub-component:

    1. Compute spatial maps of age(x,y), Z(x,y), Av(x,y), f_cont(x,y)

    2. Generate stellar SED at each spaxel: SED(λ | age, Z, Av, f_cont)

    3. Add nebular continuum and emission lines

    4. Add dust emission (if enabled)

    5. Apply IGM absorption and Galactic extinction

    6. Weight by stellar mass map

  2. Sum all components

Performance optimization:

  • If allconstant=True: Parameters uniform across galaxy, compute once

  • If allconstant=False: Uses JAX vmap for parallel spaxel computation

  • JIT compilation provides ~10-100× speedup on GPU

The function respects energy balance: if energy_balance[comp]=True, dust luminosity equals absorbed stellar light.

Output datacube can be compared directly to observed IFU data or convolved with instrumental line-spread function (LSF) and point-spread function (PSF) for realistic simulations.

Memory usage:

For 100×100 spaxels, 1000 wavelength points: ~40 MB (float32)

See also

generate_image

2D imaging (integrated over wavelength)

generate_SED

1D spectrum (integrated over space)

get_component_SED

Extract individual component spectra

Examples

>>> # Generate IFU cube for JWST/NIRSpec
>>> wave = jnp.linspace(10000, 50000, 2000)  # 1-5 μm
>>> cube = galaxy.generate_SEDIFU(wave)
>>> print(f"Cube shape: {cube.shape}")
Cube shape: (100, 100, 2000)
>>> # Extract spaxel spectrum at galaxy center
>>> center_y, center_x = ny//2, nx//2
>>> central_spec = cube[center_y, center_x, :]
>>> plt.plot(wave, central_spec)
>>> # With dust emission
>>> dust_params = {'logMdust_disk': 7.0, 'qPAH_disk': 3.5,
...                'Umin_disk': 1.0, 'alphad_disk': 2.0, 'gammad_disk': 0.1}
>>> cube = galaxy.generate_SEDIFU(wave, nebularpar=dust_params)
generate_SFR_map(inte_step=10)[source]
generate_dynamicalIFU(wavelength, impsf, allconst=True, nebularpar=None)[source]
generate_group_image(wavelength, resps, respbounds, respnorms, nebularpar=None)[source]
generate_image(band, impsf, resp, noSED=False, nebularpar=None)[source]

Generate a 2D photometric image in a specified filter band.

This method creates a synthetic image of the galaxy in a photometric band by: 1. Computing the SED for each subcomponent 2. Integrating through the filter transmission curve 3. Creating spatially resolved flux maps 4. Convolving with the PSF 5. Adding nebular emission if present

Parameters:
  • band (str) – Name of the photometric band (e.g., ‘sdss_r’, ‘hst_f814w’).

  • impsf (array_like) – 2D PSF image for convolution.

  • resp (array_like, shape (N, 2)) – Filter response curve with columns [wavelength, transmission].

  • noSED (bool, optional) – If True, skip SED calculation and use direct normalization parameters. Default is False.

  • nebularpar (dict, optional) –

    Dictionary of nebular and dust emission parameters. Required if including nebular emission or dust. Keys include:

    • ’logMdust_{component}’ : Log dust mass

    • ’qPAH_{component}’ : PAH fraction

    • ’Umin_{component}’ : Minimum radiation field

    • ’alphad_{component}’ : Power-law slope

    • ’gammad_{component}’ : Fraction in power-law

    • ’logNorm_{component}_{band}’ : Direct normalization (if noSED=True)

Returns:

image – Synthetic 2D image in the specified band, PSF-convolved and in units of 1e-38 erg/s/cm²/Å (or normalized counts if noSED=True).

Return type:

array_like, shape (ny, nx)

Notes

The image generation process:

  1. For each subcomponent:

    • Compute central SED (stellar + dust if enabled)

    • Integrate through filter to get flux per unit mass

    • Multiply by 2D mass map

    • Add nebular continuum and lines

  2. Sum all components

  3. Convolve with PSF

  4. Apply distance normalization (rnorm factor)

If energy balance is enabled for a component, the dust mass is computed from the attenuated stellar light.

For spatially resolved models with gradients, the central (r=0) SED is computed and assumed representative of the whole component (gradient corrections are applied elsewhere).

Examples

>>> import numpy as np
>>> # Assume gal is a Galaxy object with added components
>>> resp = np.loadtxt('filters/sdss_r')  # [wavelength, transmission]
>>> psf = np.ones((5, 5)) / 25  # Simple flat PSF
>>> image = gal.generate_image('sdss_r', psf, resp)

See also

generate_subcomponent_image

Generate image for a single component.

fiducial_sed

Compute integrated SED.

generate_SEDIFU

Generate 3D data cube.

generate_image_allconstNV(band_index, flux_dict, nebflux_dict)[source]
generate_image_fromIFU(IFU, wavefull, resp, respbound)[source]
generate_mass_map(shape, transpar, aperturemask=[])[source]

Generate 2D stellar mass distribution maps for all galaxy components.

This method creates spatially resolved stellar mass maps for each subcomponent (bulge, disk, etc.) based on their structural profiles. It handles coordinate transformations from sky to pixel coordinates and supports various profile types including Sersic, exponential, Ferrer, edge-on disks, and Fourier-mode perturbations.

Parameters:
  • shape (tuple of int) – Output image shape (ny, nx) in pixels.

  • transpar (dict) –

    Coordinate transformation parameters containing:

    • ’pixsc’ : float - Pixel scale in arcsec/pixel

    • ’x0’, ‘y0’ : float - Reference pixel coordinates

    • ’x0shift’, ‘y0shift’ : float - Additional pixel offsets

    • ’dxra’, ‘dxdec’, ‘dyra’, ‘dydec’ : float - WCS transformation matrix

    • ’delta_ang’ : float - Position angle offset in degrees

  • aperturemask (list of array_like, optional) – List of boolean masks defining apertures for flux measurement. Each mask should have shape matching output image. Default is [].

Returns:

  • image (array_like, shape (ny, nx)) – Total 2D stellar mass map summed over all components, in units of 10^6 M_sun.

  • apertures (list of lists) – Aperture fractions for each component and aperture. Structure: apertures[i][j] = fraction of component j’s mass within aperture i. Empty list if no aperture masks provided.

Notes

Supported profile types:

  • ‘sersic’: Standard Sersic profile (bulges, ellipticals)

  • ‘ferrer’: Ferrer profile with truncation (bars)

  • ‘GauRing’: Gaussian ring (resonance rings)

  • ‘edgeondisk’: Edge-on disk with vertical structure

  • ‘sersic_f’: Sersic + Fourier modes (spiral arms)

  • ‘sersic_bf’: Sersic + broken Fourier modes

  • ‘sersic_rf’: Sersic + ring Fourier modes

  • ‘sersic_b’: Broken/truncated Sersic

  • ‘sersic_r’: Sersic ring

  • ‘const’: Constant surface brightness

The method also computes:

  • Individual mass maps stored in self.mass_map[component_name]

  • Radial distance map (self.r_map) based on reference component

  • Effective radius (self.Re) for gradient calculations

  • Total mass image (self.massimg)

Mass maps account for:

  • Ellipticity and position angle

  • Coordinate transformation to pixel space

  • Proper normalization to total mass

Examples

>>> shape = (100, 100)  # 100x100 pixel image
>>> transpar = {'pixsc': 0.1, 'x0': 50, 'y0': 50,
...             'x0shift': 0, 'y0shift': 0,
...             'dxra': -1, 'dxdec': 0, 'dyra': 0, 'dydec': 1,
...             'delta_ang': 0}
>>> mass_map, aps = gal.generate_mass_map(shape, transpar)
>>> print(f"Total mass: {np.sum(mass_map):.2e} × 10^6 M_sun")

See also

generate_image

Generate observed photometric images.

generate_SFR_map

Generate star formation rate maps.

add_subC

Add structural components to the galaxy.

generate_subcomponent_image(band, impsf, key, resp, noSED=False, nebularpar=None)[source]
get_SFH()[source]
get_component_SED(wavelength, apertures=None, highres=False, nebularpar=None)[source]

Extract individual component SEDs (stellar, nebular, dust) for each sub-component.

Decomposes total galaxy SED into constituent parts, allowing analysis of stellar continuum, nebular emission, and dust contributions separately. Useful for spectral fitting diagnostics and physical interpretation.

Parameters:
  • wavelength (array_like) – Observed-frame wavelength grid in Angstroms.

  • apertures (list of array_like, optional) – Aperture correction factors for each sub-component [0, 1]. If provided, must have length equal to number of sub-components. Each element is 2D array matching image shape. Default: None (no correction).

  • highres (bool, optional) – If True, use high-resolution templates with velocity dispersion convolution. Default: False (use standard resolution).

  • nebularpar (dict, optional) – Nebular and dust parameters when not using defaults. Required if sedmodelist includes dust emission (index 2) or table models. Expected keys: ‘logMdust_{comp}’, ‘qPAH_{comp}’, ‘Umin_{comp}’, ‘alphad_{comp}’, ‘gammad_{comp}’ for each component.

Returns:

  • flist (list of array_like) – List of component SEDs in observed frame (10^38 erg/s/Å). Each element is 1D array matching wavelength grid.

  • compnames (list of str) – Component names corresponding to flist entries. Format: ‘{galaxy_name}{comp_name}_{type}’ where type is:

    • ’_star’: Stellar continuum

    • ’_ISM’: Nebular continuum (if withline=False) or continuum+lines

    • ’_dust’: Dust emission (if enabled)

    • ’_table’: Custom table model (if configured)

    • ’_nebulines’: Separate nebular lines (if withline=False)

Notes

Component ordering in flist matches order of components in self.subCs. If sedmodelist flags are 0 for a component type, it’s excluded from output.

The function applies:

  1. Stellar population SED with attenuation

  2. Nebular emission (continuum and/or lines)

  3. Dust emission (if energy_balance or explicitly enabled)

  4. Custom table models (if configured)

  5. IGM absorption and Galactic extinction

  6. Aperture corrections (if provided)

For high-resolution mode (highres=True), stellar SEDs are convolved with velocity dispersion kernel before output.

See also

generate_SED

Total integrated SED

generate_SEDIFU

Full 3D spectral datacube

fiducial_sed

Component SEDs at fiducial position

Examples

>>> # Extract component SEDs
>>> wave = jnp.linspace(3000, 9000, 1000)
>>> seds, names = galaxy.get_component_SED(wave)
>>> # Plot stellar vs nebular
>>> for sed, name in zip(seds, names):
...     if '_star' in name:
...         plt.plot(wave, sed, label=name)
...     elif '_ISM' in name:
...         plt.plot(wave, sed, label=name, linestyle='--')
>>> # With aperture corrections
>>> apertures = [disk_aperture, bulge_aperture]
>>> seds, names = galaxy.get_component_SED(wave, apertures=apertures)
get_eazy_lognorms(Pro_names, pardict)[source]
make_nebular(obsspec, lines_narrow=[], withline=True, nnarrow=1, strict=0.01, D3=False)[source]

Initialize nebular emission module and calibrate line templates.

Creates ISM object for nebular continuum and emission lines, optionally calibrating line profiles from observed spectrum. Supports both direct template usage and data-driven line fitting.

Parameters:
  • obsspec (list of array_like) – Observed spectrum as [wavelength, flux] in observed frame. Used for line template calibration when withline=False. Wavelength in Angstroms, flux arbitrary units.

  • lines_narrow (list of str, optional) – Names of narrow emission lines to model separately (e.g., [‘[OIII]5007’, ‘[NII]6584’]). These get distinct kinematic components. Default: [] (no narrow lines).

  • withline (bool, optional) – If True, use pre-computed line templates from CLOUDY models. If False, fit line templates directly to obsspec. Default: True.

  • nnarrow (int, optional) – Number of narrow-line kinematic components (e.g., 1 for single, 2 for outflow+disk). Default: 1.

  • strict (float, optional) – Strictness parameter for line fitting (0-1). Lower values allow more flexible line ratios. Default: 0.01.

  • D3 (bool, optional) – If True, use 3D photoionization grids (spatially resolved). If False, use integrated templates. Default: False.

Returns:

params – Initialized parameters for line fitting (if withline=False). None otherwise.

Return type:

lmfit.Parameters or None

Notes

Three operational modes:

  1. Pre-computed lines (withline=True, D3=False): Uses CLOUDY line templates indexed by Z and logU. Fast, physically motivated line ratios.

  2. Data-driven lines (withline=False, D3=False): Fits Gaussian profiles to observed lines in obsspec. Flexible for unusual line ratios or kinematics. Returns initialized parameters for subsequent fitting.

  3. 3D photoionization (D3=True): Spatially resolved nebular emission from 3D CLOUDY grids. Most sophisticated but computationally expensive.

The ISM object is stored as self.Nebular and used by generate_SED(), generate_image(), and generate_SEDIFU() to add nebular emission.

Narrow lines (lines_narrow) are treated as separate kinematic component with independent velocity and width, useful for modeling forbidden lines from extended narrow-line regions distinct from BLR.

See also

ISM

Nebular emission class

generate_SED

Uses self.Nebular to add emission lines

Examples

>>> # Mode 1: Use CLOUDY templates
>>> galaxy.make_nebular(obsspec=None, withline=True)
>>> # Mode 2: Fit lines to observed spectrum
>>> wave_obs = jnp.linspace(4000, 9000, 1000)
>>> flux_obs = observed_flux  # User's data
>>> params = galaxy.make_nebular([wave_obs, flux_obs], withline=False,
...                              lines_narrow=['[OIII]5007', '[NII]6584'])
>>> # Mode 3: 3D photoionization for IFU
>>> galaxy.make_nebular(obsspec=None, D3=True)
process_subc_SED(wavelength, resps, respbounds, respnorms, nebularpar=None)[source]
reset_info(paradic, z=0.0, ebv_G=0.0)[source]

Update galaxy redshift and distance-dependent properties.

This method updates the galaxy’s redshift, galactic extinction, and recalculates distance-dependent quantities including the luminosity distance normalization and the physical scale at the galaxy’s redshift.

Parameters:
  • paradic (dict) – Parameter dictionary that will be updated with the new scale factor. The key ‘scale_{name}’ will be added/updated with kpc per arcsec at z.

  • z (float, optional) – New galaxy redshift. Default is 0.

  • ebv_G (float, optional) – New galactic foreground extinction E(B-V). Default is 0.

Notes

This method updates:

  • rnorm : Luminosity distance normalization factor

  • redshift : Galaxy redshift

  • ebv_G : Galactic extinction

  • paradic[‘scale_{name}’] : Physical scale (kpc/arcsec)

  • currentage : Age of universe at redshift z

The normalization factor accounts for the difference between the region redshift and the galaxy redshift: rnorm = (D_L(z_region)/D_L(z_galaxy))^2

update_subC_para(Pro_names, pardict)[source]

Update all parameters for a specific sub-component from parameter dictionary.

Synchronizes internal parameter storage with values from a flat parameter dictionary (e.g., from lmfit fitting results). Updates structural parameters, SED parameters (age, metallicity, attenuation, SFH), and normalization.

Parameters:
  • Pro_names (str) – Sub-component name (e.g., ‘disk’, ‘bulge’, ‘comp1’).

  • pardict (dict) –

    Flat parameter dictionary with keys following naming convention:

    • Structure: ‘{Pro_names}_{param}’ (e.g., ‘disk_n’, ‘disk_Re’)

    • Age: ‘{Pro_names}_age_{param}’ (e.g., ‘disk_age_value’)

    • Metallicity: ‘{Pro_names}_Z_{param}’ (e.g., ‘disk_Z_value’)

    • Attenuation: ‘{Pro_names}_Av_{param}’ (e.g., ‘disk_Av_value’)

    • SFH: ‘{Pro_names}_f_cont_{param}’ (e.g., ‘disk_f_cont_value’)

    • Normalization: ‘logM_{Pro_names}’, ‘logU_{Pro_names}’, ‘AVbump_{Pro_names}’

    • Optional: ‘sigma_{Pro_names}’ (velocity dispersion)

Returns:

Updates internal dictionaries in place.

Return type:

None

Notes

This method is typically called during iterative fitting to apply parameter updates from the optimizer. It:

  1. Updates structural parameters (Sérsic index, effective radius, etc.)

  2. Updates SED gradient parameters (age, Z, Av, f_cont profiles)

  3. Resets mass map to force regeneration

  4. Updates global parameters (mass, ionization parameter, UV bump, σ)

The mass_map is set to 0 to flag that it needs regeneration with new parameters via generate_mass_map().

Parameter naming follows hierarchical convention to avoid conflicts when multiple components exist (e.g., ‘disk’ vs ‘bulge’).

See also

fix_loose_subC

Lock/unlock parameters in lmfit

generate_mass_map

Regenerate spatial mass distribution

Examples

>>> galaxy = Galaxy(...)
>>> galaxy.add_subC('disk', ...)
>>> # After fitting, update with new parameters
>>> params = {'disk_n': 1.5, 'disk_Re': 3.0, 'logM_disk': 10.5,
...          'disk_age_value': 1.0, 'disk_Z_value': 0.02, ...}
>>> galaxy.update_subC_para('disk', params)
class galfits.galaxy.ISM(withlines=True, lines=[], nnarrow=1, prefix='nb', D3=False)[source]

Bases: object

Interstellar medium model for nebular emission (continuum and lines).

The ISM class handles nebular emission from ionized gas, including both continuum emission (free-free, free-bound, two-photon) and emission lines (H, He, metals). It can model emission from both narrow-line regions (NLR) and broad-line regions (BLR) in AGN.

Parameters:
  • withlines (bool, optional) – If True, nebular lines are included in the continuum model (single component). If False, lines are modeled separately with the Line_Emitter. Default is True.

  • lines (list, optional) – List of emission line dictionaries for separate line modeling. Each dict should have ‘name’ and ‘wave’ keys. Default is [].

  • nnarrow (int, optional) – Number of kinematic components for narrow lines. Default is 1.

  • prefix (str, optional) – Prefix for parameter names (e.g., ‘nb’ for narrow, ‘bb’ for broad). Default is ‘nb’.

  • D3 (bool, optional) – If True, use 3D modeling for spatially resolved IFU data. Default is False.

withline

Whether lines are included in continuum.

Type:

bool

D3

Whether 3D modeling is enabled.

Type:

bool

nnarrow

Number of kinematic components.

Type:

int

lineemit

Line emitter object for separate line modeling.

Type:

Line_Emitter or None

Examples

>>> from galfits.galaxy import ISM
>>> from galfits import emission_lines as EL
>>> # Simple continuum + lines (integrated in SED models)
>>> ism_simple = ISM(withlines=True)
>>>
>>> # Separate line modeling for kinematics
>>> lines = [EL.Ha, EL.NII_6583, EL.OIII_5007]
>>> ism_lines = ISM(withlines=False, lines=lines, nnarrow=2)

Notes

The ISM class provides two modes:

  1. withlines=True: Nebular continuum and lines are computed together from photoionization models. Suitable for broadband SED fitting.

  2. withlines=False: Lines are modeled separately as Gaussians with adjustable kinematics. Suitable for spectroscopic fitting where line profiles contain kinematic information.

Nebular continuum includes: - Free-free emission (Bremsstrahlung) - Free-bound emission (recombination continua) - Two-photon emission - Balmer continuum

The emission depends on ionization parameter (U), metallicity (Z), and dust extinction (Av).

See also

Line_Emitter

Handles kinematic modeling of emission lines.

Galaxy.make_nebular

Initialize nebular emission for a Galaxy object.

__init__(withlines=True, lines=[], nnarrow=1, prefix='nb', D3=False)[source]
generate_continuum(wave, logU, Z, Av)[source]
generate_line(wave, pardict)[source]
generate_line3D(wave3D, pardict, massmap, SFRmap, sigmap)[source]
model_initialized(restspec, strict=0.01)[source]
model_initialized_3D()[source]
class galfits.galaxy.Line_Emitter(lines=[], ncomp=1, prefix='b')[source]

Bases: object

Emission line profile modeler for kinematic analysis.

This class models emission lines as Gaussian profiles with multiple kinematic components. It handles line ratios, velocity offsets, and widths, making it suitable for spectroscopic fitting of galaxies and AGN where line profiles contain kinematic information (rotation, outflows, etc.).

Parameters:
  • lines (list) –

    List of emission line dictionaries. Each dictionary should contain:

    • ’name’ : str - Line identifier (e.g., ‘Ha’, ‘OIII_5007’)

    • ’wave’ : float - Rest wavelength in Angstroms

  • ncomp (int, optional) – Number of kinematic components (e.g., 1=single component, 2=core+wing). Default is 1.

  • prefix (str, optional) – Prefix for parameter names to distinguish different line regions (e.g., ‘b’ for broad, ‘n’ for narrow). Default is ‘b’.

lines

List of emission line dictionaries.

Type:

list

ncomp

Number of kinematic components.

Type:

int

prefix

Parameter name prefix.

Type:

str

nprefix

Reference line for tying kinematics across multiple lines.

Type:

dict or None

Notes

The Line_Emitter models each line as a sum of Gaussian components:

\[F(\lambda) = \sum_{i=1}^{N_{comp}} \frac{A_i}{\sqrt{2\pi}\sigma_i} \exp\left(-\frac{(\lambda - \lambda_{c,i})^2}{2\sigma_i^2}\right)\]

Where: - A_i is the integrated line flux - λ_c,i is the line center (can be offset from rest wavelength) - σ_i is the Gaussian width (related to velocity dispersion)

Key features:

  • Automatic line ratio constraints (e.g., [OIII]5007/4959 = 2.98)

  • Tied kinematics across lines (same velocity, dispersion)

  • Multiple kinematic components (narrow + broad)

  • Support for 3D IFU modeling with spatially varying kinematics

Examples

>>> from galfits.galaxy import Line_Emitter
>>> from galfits import emission_lines as EL
>>> lines = [EL.Ha, EL.NII_6583, EL.NII_6549, EL.SII_6717, EL.SII_6731]
>>> emitter = Line_Emitter(lines=lines, ncomp=2, prefix='n')
>>> # Initialize parameters from an observed spectrum
>>> params = emitter.model_initialized(restspec, narrow=True)

See also

ISM

Parent class that uses Line_Emitter for nebular modeling.

__init__(lines=[], ncomp=1, prefix='b')[source]
get_3Dflux(wave3D, pardict, massmap, SFRmap, sigmap)[source]
model_initialized(restspec, narrow=False, strict=0.01, broader=12000.0, bcentershift=0.0, havespec=True)[source]
model_initialized_3D(logLs0=None, initfac=1, varyfrac=False, varysig=False)[source]

AGN and Stellar Classes

class galfits.galaxy.AGN(regionz, logM_BH=8.0, logLedd=-1.0, astar=0.0, Av=0.0, z=0.0, ebv_G=0.0, torus=False, prefix='')[source]

Bases: object

Active Galactic Nucleus (AGN) spectral and imaging model.

Comprehensive AGN modeling including accretion disk continuum, broad and narrow emission lines, FeII emission, Balmer continuum, torus emission, and hot dust. Supports multiple disk models and custom table models.

Parameters:
  • regionz (float) – Redshift of the observed region (may differ from AGN redshift for gravitationally lensed systems).

  • logM_BH (float, optional) – Log10 of black hole mass in solar masses (default: 8.0). Range typically [5, 10].

  • logLedd (float, optional) – Log10 of Eddington ratio L_bol/L_Edd (default: -1.0). Range typically [-3, 0] for type 1 AGN.

  • astar (float, optional) – Black hole spin parameter (0 = Schwarzschild, 0.998 = maximal). Default: 0.0. Range [0, 0.998].

  • Av (float, optional) – V-band attenuation in magnitudes (default: 0.0).

  • z (float, optional) – AGN redshift (default: 0.0).

  • ebv_G (float, optional) – Galactic E(B-V) color excess for foreground extinction (default: 0.0).

  • torus (bool, optional) – If True, include CAT3D torus emission model (default: False).

  • prefix (str, optional) – Name prefix for parameters (default: ‘’). Used to distinguish multiple AGN components.

logM_BH

Black hole mass (log10 M_sun).

Type:

float

logLedd

Eddington ratio (log10 L_bol/L_Edd).

Type:

float

astar

Spin parameter.

Type:

float

Av

Internal dust attenuation.

Type:

float

redshift

AGN redshift.

Type:

float

ebv_G

Galactic extinction.

Type:

float

BLR

Broad-line region emission model.

Type:

Line_Emitter or None

NLR

Narrow-line region emission model.

Type:

Line_Emitter or None

FeII

Include FeII emission if True.

Type:

bool

BaC

Include Balmer continuum if True.

Type:

bool

sedModel

SED model type: ‘TD’ (thin disk), ‘SP’ (single power-law), ‘BP’ (broken power-law), ‘SBD’ (starburst disk), ‘table’, ‘NP’ (non-parametric).

Type:

str

torus

Include torus emission if True.

Type:

bool

hotdust

Include hot dust blackbody if True.

Type:

bool

table_model

Custom SED table model if configured.

Type:

TableModel or None

rnorm

Normalization factor for flux scaling: (D_L,region / D_L,AGN)^2.

Type:

float

reset_BH(logM_BH, logLedd, astar, Av)[source]

Update black hole parameters.

reset_info(z, ebv_G)[source]

Update redshift and Galactic extinction.

change_SED(sedmodel)[source]

Switch between disk models.

set_full_model(obsspec, lines_broad, lines_narrow, par_tot, ...)[source]

Initialize BLR, NLR, FeII, and BaC from observed spectrum.

generate_image(posi, shape, band, psfimage, resp, ...)[source]

Create 2D AGN image in specified band.

fiducial_sed(wavelength, pardict, delta)[source]

Generate AGN SED at given parameters.

get_component_SED(wavelength, pardict, delta)[source]

Extract individual SED components (disk, BLR, NLR, FeII, etc.).

Notes

The AGN class is designed to be combined with Galaxy class for host-AGN decomposition. It handles both unresolved (point source) and resolved (extended NLR) emission.

SED models:

  • ‘TD’: Thin accretion disk (Shakura-Sunyaev with relativistic corrections)

  • ‘SP’: Single power-law (λ^-α)

  • ‘BP’: Broken power-law (different slopes UV vs optical)

  • ‘SBD’: Starburst disk (optically thick, dust-obscured)

  • ‘table’: Custom table model

  • ‘NP’: Non-parametric (directly fit fluxes in bands)

Emission components:

  • Accretion disk continuum

  • Broad-line region (BLR): H, He recombination lines with FWHM ~ 1000-10000 km/s

  • Narrow-line region (NLR): Forbidden lines with FWHM ~ 100-500 km/s

  • FeII emission: Complex blended iron transitions

  • Balmer continuum: Recombination continuum from BLR

  • Torus: IR emission from dusty torus (1-100 μm)

  • Hot dust: Near-IR blackbody (1-3 μm)

Examples

>>> # Create AGN with thin disk model
>>> agn = AGN(regionz=2.0, logM_BH=8.5, logLedd=-0.5, astar=0.7,
...           z=2.0, ebv_G=0.03, torus=True, prefix='agn')
>>> # Initialize emission line models from observed spectrum
>>> wave_obs = jnp.linspace(3000, 9000, 1000)
>>> flux_obs = observed_spectrum
>>> lines_broad = ['Ha', 'Hb', 'MgII2798']
>>> lines_narrow = ['[OIII]5007', '[NII]6584']
>>> params = lmfit.Parameters()
>>> agn.set_full_model([wave_obs, flux_obs], lines_broad, lines_narrow,
...                    params, addFeII=True, addBaC=True)
>>> # Generate SED
>>> wave = jnp.logspace(2, 5, 1000)
>>> pardict = {param.name: param.value for param in params.values()}
>>> sed = agn.fiducial_sed(wave, pardict)
>>> # Generate point-source image
>>> posi = [50.0, 50.0]  # pixel coordinates
>>> shape = (100, 100)
>>> img = agn.generate_image(posi, shape, 'F200W', psf, response)

See also

Galaxy

Host galaxy modeling

Line_Emitter

Emission line fitting

cat3Dtorus

AGN torus emission

get_AGN_SED

Thin disk SED interpolation

References

__init__(regionz, logM_BH=8.0, logLedd=-1.0, astar=0.0, Av=0.0, z=0.0, ebv_G=0.0, torus=False, prefix='')[source]

galaxy object is initialed from a given mass

change_SED(sedmodel)[source]
fiducial_sed(wavelength, pardict=None, delta=0.0)[source]

Computes the AGN spectral energy distribution (SED) at rest-frame wavelengths given a set of model parameters.

Parameters:

wavelengthnumpy.ndarray

Array of wavelengths in Angstroms.

pardictdict, optional

Dictionary of model parameters. If None, the default parameters are used.

deltafloat, optional

2175 bump strength. Default is 0.

Returns:

agnsednumpy.ndarray

Array of AGN SED values in units of 1e38 erg/s/A at the observer frame.

generate_IFU(wavelength, posi, shape, psfimage, LSF_FWHM=1.6, GaussianLSF=True, transpar=None, pardict=None)[source]
generate_SED(resps, pardict=None)[source]
generate_grism_IFU(wavelength, posi, shape, psfimage, pardict=None, transpar=None)[source]
generate_image(posi, shape, band, psfimage, resp, transpar=None, pardict=None, psfimscale=1.0)[source]

Parameters: shape: (y,x) of the output image

band: band of the output image

{psftype: [psfparams]}: a dict, the point spread function eg. {‘psf’: [{‘xcen’:50, ‘ycen’:50}]} stands for a point sources which have same shape as the empirical PSF

{‘moffat’: [{‘xcen’:50, ‘ycen’:50, ‘fwhm’:3., ‘con’:’5.’}]}

get_component_SED(wavelength, pardict=None, delta=0.0)[source]

Returns the spectral energy distribution (SED) of the galaxy’s components at a given wavelength.

Parameters:
  • wavelength (float) – The wavelength at which to calculate the SED.

  • pardict (dict, optional) – A dictionary of parameters for the SED model. Defaults to None.

  • delta (float, optional) – 2175 A bump amplitude. Defaults to 0.

Returns:

A tuple containing two lists. The first list contains the SEDs of the galaxy’s components at the given wavelength. The second list contains the names of the components.

Return type:

tuple

reset_BH(logM_BH, logLedd, astar, Av)[source]
reset_info(z=0.0, ebv_G=0.0)[source]

reset the z of a agn object

set_full_model(obsspec, lines_broad, lines_narrow, par_tot, addFeII=True, addBaC=True, nbroad=2, nnarrow=1, strict=0.01, broader=12000.0, havespec=False, **kwargs)[source]

set the BLR NLR models for the AGN component

obsspec: observed optical spectrum [wave,flux]

it is used to make an initial guess

lines_broad: list

a line list in BLR

lines_narrow: list

a line list in NLR


class galfits.galaxy.Star(prefix='', useSED=True)[source]

Bases: object

Point-source stellar object for foreground/companion star modeling.

Models individual stars as unresolved point sources using either synthetic stellar atmosphere models (PHOENIX) or non-parametric flux measurements. Used for fitting foreground stars, bright companions, or calibration stars in galaxy images.

Parameters:
  • prefix (str, optional) – Name prefix for parameters (default: ‘’). Use to distinguish multiple stars.

  • useSED (bool, optional) – If True, use PHOENIX stellar atmosphere models; if False, use non-parametric flux measurements per band (default: True).

name

Star name (same as prefix).

Type:

str

prefix

Parameter name prefix.

Type:

str

sedModel

SED model type: ‘PHOENIX’ (synthetic spectra) or ‘NP’ (non-parametric).

Type:

str

bandslist

List of photometric bands for non-parametric mode.

Type:

list

generate_image(posi, shape, band, psfimage, pardict, resp, ...)[source]

Create 2D star image as PSF-convolved point source.

fiducial_sed(wavelength, pardict)[source]

Generate stellar SED from atmosphere model or interpolation.

generate_SED(resps, pardict)[source]

Compute multi-band photometry from SED.

Notes

PHOENIX mode (useSED=True):

  • Uses pre-computed stellar atmosphere grids

  • Parameters: Teff (temperature), logg (surface gravity), logZ (metallicity)

  • Valid ranges: Teff [3000, 12000] K, logg [-0.5, 5.5], logZ [-4, 1]

  • Normalization: logL38 (log10 of luminosity in 10^38 erg/s)

Non-parametric mode (useSED=False):

  • Directly fit flux in each photometric band

  • Parameters: {prefix}_{band}_logL for each band

  • Interpolates between bands for SED

  • Flexible but requires many bands for good spectral coverage

The Star class is typically used in combination with Galaxy/AGN classes for full scene modeling. Stars appear as point sources (convolved with PSF) while galaxies are extended.

Examples

>>> # Create foreground star with PHOENIX model
>>> star = Star(prefix='star1', useSED=True)
>>> params = {'star1_logL38': 0.5,  # L = 3.16e38 erg/s
...           'star1_Teff': 5800,    # Solar temperature
...           'star1_logg': 4.5,     # Solar gravity
...           'star1_logZ': 0.0}     # Solar metallicity
>>> # Generate SED
>>> wave = jnp.linspace(3000, 10000, 1000)
>>> sed = star.fiducial_sed(wave, params)
>>> # Generate point-source image
>>> posi = [75.0, 120.0]  # pixel coordinates
>>> shape = (200, 200)
>>> img = star.generate_image(posi, shape, 'F200W', psf, params, response)
>>> # Non-parametric mode for calibration star
>>> star_cal = Star(prefix='cal', useSED=False)
>>> star_cal.bandslist = ['F150W', 'F200W', 'F277W', 'F356W']
>>> params_cal = {'cal_F150W_logL': 2.0, 'cal_F200W_logL': 2.1,
...               'cal_F277W_logL': 2.2, 'cal_F356W_logL': 2.3}

See also

AGN

Point-source AGN modeling

Galaxy

Extended galaxy modeling

get_stellar_sed

PHOENIX SED interpolation

References

__init__(prefix='', useSED=True)[source]
fiducial_sed(wavelength, pardict=None)[source]
generate_SED(resps, pardict=None)[source]
generate_image(posi, shape, band, psfimage, pardict, resp, transpar=None, psfimscale=1.0)[source]

Utility Classes

class galfits.galaxy.switch(value)[source]

Bases: object

Switch-case statement implementation for Python.

This class provides switch-case functionality similar to C/C++ for Python. It allows cleaner handling of multiple conditional branches compared to chained if-elif statements.

Parameters:

value (any) – The value to match against in case statements.

value

The value being switched on.

Type:

any

fall

Flag indicating if a case has been matched (enables fall-through behavior).

Type:

bool

Examples

>>> for case in switch(value):
...     if case('option1'):
...         # Handle option1
...         break
...     if case('option2', 'option3'):
...         # Handle option2 or option3
...         break
...     if case():  # default case
...         # Handle default
...         break

Notes

The switch class mimics C-style switch statements. Once a match is found, subsequent cases will also match (fall-through) unless break is used. An empty case() serves as the default case.

__init__(value)[source]
match(*args)[source]

Indicate whether or not to enter a case suite.

Parameters:

*args (any) – Values to match against. If empty, acts as default case.

Returns:

True if this case should execute, False otherwise.

Return type:

bool

Helper Functions

galfits.galaxy.indentify_xy(x, y)[source]

Identity transformation for coordinate systems.

This function serves as a placeholder that returns coordinates unchanged. It is used when no coordinate transformation is needed between (RA, Dec) offsets and pixel coordinates.

Parameters:
  • x (float or array_like) – X-coordinate (typically RA offset in arcseconds or pixel position).

  • y (float or array_like) – Y-coordinate (typically Dec offset in arcseconds or pixel position).

Returns:

  • x (float or array_like) – Unchanged x-coordinate.

  • y (float or array_like) – Unchanged y-coordinate.

See also

coordinates_transfer

Applies affine transformation to convert from sky to pixel coordinates.

coordinates_transfer_inverse

Inverse transformation from pixel to sky coordinates.

galfits.galaxy.coordinates_transfer(x, y, kwargs)[source]

Transform coordinates from sky offsets (RA, Dec) to pixel coordinates.

This function applies an affine transformation to convert from celestial coordinate offsets (in arcseconds) to pixel coordinates in the image plane. The transformation accounts for rotation, scale, and pixel offset.

Parameters:
  • x (float or array_like) – RA offset from reference position (in arcseconds).

  • y (float or array_like) – Dec offset from reference position (in arcseconds).

  • kwargs (dict) –

    Dictionary containing transformation parameters:

    • ’x0’float

      Reference x-pixel coordinate.

    • ’y0’float

      Reference y-pixel coordinate.

    • ’x0shift’float

      Additional x-offset in pixels.

    • ’y0shift’float

      Additional y-offset in pixels.

    • ’dxra’float

      Change in x-pixel per RA offset (pixel/arcsec).

    • ’dxdec’float

      Change in x-pixel per Dec offset (pixel/arcsec).

    • ’dyra’float

      Change in y-pixel per RA offset (pixel/arcsec).

    • ’dydec’float

      Change in y-pixel per Dec offset (pixel/arcsec).

Returns:

  • xp (float or array_like) – Transformed x-coordinate in pixels.

  • yp (float or array_like) – Transformed y-coordinate in pixels.

Notes

The transformation follows:

\[ \begin{align}\begin{aligned}x_p = x_0 + x_{0,shift} + x \cdot dx_{RA} + y \cdot dx_{Dec}\\y_p = y_0 + y_{0,shift} + x \cdot dy_{RA} + y \cdot dy_{Dec}\end{aligned}\end{align} \]

See also

coordinates_transfer_inverse

Inverse transformation from pixel to sky coordinates.

indentify_xy

Identity transformation (no coordinate conversion).

galfits.galaxy.coordinates_transfer_inverse(xp, yp, kwargs)[source]

Transform coordinates from pixel space back to sky offsets (RA, Dec).

This function applies the inverse affine transformation to convert from pixel coordinates back to celestial coordinate offsets (in arcseconds). It inverts the transformation performed by coordinates_transfer.

Parameters:
  • xp (float or array_like) – X-coordinate in pixels.

  • yp (float or array_like) – Y-coordinate in pixels.

  • kwargs (dict) –

    Dictionary containing transformation parameters (same as coordinates_transfer):

    • ’x0’float

      Reference x-pixel coordinate.

    • ’y0’float

      Reference y-pixel coordinate.

    • ’dxra’float

      Change in x-pixel per RA offset (pixel/arcsec).

    • ’dxdec’float

      Change in x-pixel per Dec offset (pixel/arcsec).

    • ’dyra’float

      Change in y-pixel per RA offset (pixel/arcsec).

    • ’dydec’float

      Change in y-pixel per Dec offset (pixel/arcsec).

Returns:

  • x (float or array_like) – RA offset from reference position (in arcseconds).

  • y (float or array_like) – Dec offset from reference position (in arcseconds).

Notes

The inverse transformation solves the linear system:

\[ \begin{align}\begin{aligned}x = \frac{(x_p - x_0) \cdot dy_{Dec} - (y_p - y_0) \cdot dx_{Dec}}{dx_{RA} \cdot dy_{Dec} - dy_{RA} \cdot dx_{Dec}}\\y = \frac{(x_p - x_0) \cdot dy_{RA} - (y_p - y_0) \cdot dx_{RA}}{dy_{RA} \cdot dx_{Dec} - dx_{RA} \cdot dy_{Dec}}\end{aligned}\end{align} \]

See also

coordinates_transfer

Forward transformation from sky to pixel coordinates.

galfits.galaxy.SFR_to_Ha(SFR, Z)[source]

Convert star formation rate to H-alpha luminosity.

This function converts a star formation rate (SFR) to H-alpha line luminosity using metallicity-dependent calibration factors. The conversion accounts for the fact that H-alpha emissivity depends on the gas-phase metallicity.

Parameters:
  • SFR (float or array_like) – Star formation rate in solar masses per year (M_sun/yr).

  • Z (float or array_like) – Gas-phase metallicity (mass fraction, not log). Should be in range [0.0001, 0.05].

Returns:

L – H-alpha luminosity in units of 10^38 erg/s.

Return type:

float or array_like

Notes

The conversion uses metallicity-dependent calibration factors interpolated from a grid spanning Z = [0.0001, 0.0004, 0.004, 0.008, 0.02, 0.05]. The calibration is based on nebular emission models and follows:

\[L_{H\alpha} = \frac{SFR}{10^{K(Z)}}\]

where K(Z) is the metallicity-dependent conversion factor in units of log(erg/s/(M_sun/yr)).

References

The conversion factors are derived from photoionization models similar to those in Kennicutt (1998) and Kennicutt & Evans (2012), adjusted for metallicity.

galfits.galaxy.Cal_map(r, type, paradic)[source]

Calculate spatially-resolved parameter maps using various functional forms.

This function computes physical parameter distributions (e.g., age, metallicity, star formation history) as a function of radius using different mathematical profiles. It supports linear, exponential, constant, and rotation curve profiles.

Parameters:
  • r (float or array_like) – Radial distance or normalized radius (units depend on the chosen profile type).

  • type (str) –

    Type of radial profile to use. Options are:

    • ’linear’ : Linear interpolation between inner and outer values

    • ’exp’ : Exponential decay profile

    • ’const’ : Constant value (no radial dependence)

    • ’arctan’ : Arctangent profile (typically used for rotation curves)

  • paradic (dict) –

    Dictionary of parameters specific to the chosen profile type:

    For ‘linear’:
    • ’in’ : float - Value at r=0 (inner region)

    • ’out’ : float - Value at r=1 (outer region)

    For ‘exp’:
    • ’in’ : float - Value at r=0

    • ’out’ : float - Asymptotic value at large r

    • ’k’ : float - Scale length for exponential decay

    For ‘const’:
    • ’value’ : float - Constant value at all radii

    For ‘arctan’:
    • ’r0’ : float - Reference radius

    • ’rt’ : float - Turnover radius scale

    • ’v0’ : float - Velocity offset

    • ’vc’ : float - Characteristic velocity

Returns:

result – The computed parameter value(s) at the given radius/radii.

Return type:

float or array_like

Raises:

ValueError – If an unrecognized profile type is specified.

Notes

Profile equations:

  • Linear: \(f(r) = f_{in}(1-r) + f_{out} \cdot r\)

  • Exponential: \(f(r) = (f_{in} - f_{out}) e^{-r/k} + f_{out}\)

  • Constant: \(f(r) = c\)

  • Arctangent: \(f(r) = v_0 + \frac{2v_c}{\pi} \arctan\left(\frac{r-r_0}{r_t}\right)\)

The arctangent profile is commonly used to model rotation curves of galaxies.

See also

Cal_gradient_map

Calculate gradient correction maps for spatially varying SEDs.

galfits.galaxy.Cal_gradient_map(r_grid, r_map, method, type, paradic, flux_band, f2, interX, ax, **kwargs)[source]

Calculate flux correction maps for spatially varying stellar population parameters.

This function computes how the integrated flux in a photometric band changes as a function of stellar population parameters (age, metallicity, dust extinction, or star formation history) across the galaxy. This is used to correct for gradient effects when fitting spatially resolved observations.

Parameters:
  • r_grid (array_like) – Radial grid points at which to evaluate the parameter gradients (typically normalized radii from 0 to 1).

  • r_map (array_like) – 2D map of radial distances for each pixel in the image.

  • method (str) –

    The parameter whose gradient is being calculated. Options:

    • ’age’ : Stellar population age gradient

    • ’f_cont’ : Continuous star formation fraction gradient

    • ’Z’ : Metallicity gradient

    • ’Av’ : Dust extinction gradient

  • type (str) – Functional form of the gradient (see Cal_map for options).

  • paradic (dict) – Parameters defining the gradient profile (see Cal_map for structure).

  • flux_band (float) – Reference flux in the photometric band for normalization.

  • f2 (callable) – Filter transmission function f2(wavelength).

  • interX (array_like) – Wavelength grid for SED integration (in Angstroms).

  • ax (float) – Normalization factor for the filter (integral of transmission curve).

  • **kwargs (dict) –

    Additional parameters needed for SED calculation:

    • ’f_cont_zero’ : float - Reference star formation fraction

    • ’age_zero’ : float - Reference age (Gyr)

    • ’Z_zero’ : float - Reference metallicity (mass fraction)

    • ’Av_zero’ : float - Reference extinction (magnitudes)

Returns:

gradient_map – 2D map of flux correction factors relative to the central value. Shape matches r_map. Values near 1.0 indicate similar flux to center.

Return type:

ndarray

Raises:

ValueError – If an unrecognized method is specified.

Notes

The function works by:

  1. Computing SEDs at different radii with varying parameters

  2. Integrating these SEDs through the filter bandpass

  3. Creating a flux ratio map relative to the central flux

  4. Interpolating this onto the full 2D radial map

This is essential for accurate photometric modeling when stellar populations vary spatially within galaxies.

See also

Cal_map

Calculate parameter values as a function of radius.