Skip to main content

MgeFit: Multi-Gaussian Expansion Fitting

Project description

MgeFit: Multi-Gaussian Expansion Fitting of Galactic Images

MgeFit is a Python implementation of the robust and efficient Multi-Gaussian Expansion (MGE) fitting algorithm for galactic images of Cappellari (2002).

The MGE parameterization is useful in the construction of realistic dynamical models of galaxies (see JAM modelling), for PSF deconvolution of images, for the correction and estimation of dust absorption effects, or for galaxy photometry.


If you use this software for your research, please cite Cappellari (2002). The BibTeX entry for the paper is:

    author = {{Cappellari}, M.},
    title = {Efficient multi-Gaussian expansion of galaxies},
    journal = {MNRAS},
    eprint = {arXiv:astro-ph/0201430}
    year = {2002},
    volume = {333},
    pages = {400-410},
    doi = {10.1046/j.1365-8711.2002.05412.x}


install with:

pip install mgefit

Without writing access to the global site-packages directory, use:

pip install --user mgefit

Usage Examples

To learn how to use the MgeFit package, copy, modify and run the example programs in the mgefit/examples directory. It can be found within the main MgeFit package installation folder inside site-packages. The detailed documentation is contained in the docstring of each file, or for the main procedure on PyPi.

mge_fit_sectors Purpose

Approximates the surface brightness of a galaxy with a Multi-Gaussian Expansion (MGE) model, using the robust and automated fitting method of

Cappellari (2002)

The measurements are taken along sectors with a previous call to the procedure sectors_photometry in the MgeFit package . All measurements within this program are in the instrumental units of pixels and counts. This routine fits MGE models with constant position angle and common center.

Calling Sequence

from mgefit.mge_fit_sectors import mge_fit_sectors

m = mge_fit_sectors(self, radius, angle, counts, eps,
         bulge_disk=False, fignum=1, linear=False, negative=False,
         ngauss=None, normpsf=1., outer_slope=4, plot=False, qbounds=None,
         quiet=False, rbounds=None, scale=1., sigmapsf=0., sol=0)

total_counts, sigma, q_obs = m.sol  # assign the solution to variables
print(m.sol.T)  # Print a table of best-fitting MGE parameters

Example programs are in the mgefit/examples directory. It can be found within the main MgeFit package installation folder inside site-packages.

A PDF manual readme_mge_fit_sectors.pdf is contained in the main installation directory mgefit of the package inside site-packages.

Input Parameters

radius: array_like with shape (n,)
Vector containing the radius of the surface brightness measurements, taken from the galaxy center. This is given in units of PIXELS (!) of the image. When fitting multiple images simultaneously this is in pixels units of the high-resolution image.
angle: array_like with shape (n,)
Vector containing the polar angle of the surface brightness measurements, measured from the galaxy major axis (in degrees).
counts: array_like with shape (n,)
Vector containing the surface brightness measurements in COUNTS/PIXEL (!) at the polar coordinates specified by the vectors radius and angle. When fitting multiple images simultaneously this is in counts/pixels units of the high-resolution image.
Crude estimate for the galaxy characteristic ellipticity eps = 1 - b/a = 1 - q'

Optional Keywords


Set bulge_disk=True to perform a non-parametric bulge/disk decomposition using MGE. When bulge_disk=True the Gaussians are divided into two sets, each with a unique axial ratio. The two sets are meant to describe and model the contribution of bulge and disks in spiral or lenticular galaxies, or nuclear disk in ellipticals.

When this keyword is set one should increase ngauss. One should also either set qbounds=None or specify four elements in qbounds for the even/odd Gaussians.

Optional number to assign to the plotting window.
Set this keyword to start with the fully linear algorithm and then optimize the fit with the nonlinear method [see Section 3.4 of Cappellari (2002) for details]. Nowadays using this keyword instroduces a small speed panelty but produces more robust fits and is always reccomended.
Set this keyword to allow for negative Gaussians in the fit. Use this only if everything else didn’t work or if there is clear evidence that negative Gaussians are actually needed. Negative Gaussians are needed e.g. when fitting a boxy bulge.
Maximum number of Gaussians allowed in the MGE fit. Typical values are in the range 10-20 when linear=False (default: ngauss=12) and 20**2-40**2 when linear=True (default: ngauss=30**2=900).
normpsf: array_like with shape (q,)
This is optional if only a scalar is given for sigmapsf, otherwise it must contain the normalization of each MGE component of the PSF, whose sigma is given by sigmapsf. The vector needs to have the same number of elements as sigmapsf and it must be normalized as normpsf.sum() = 1 (default: normpsf=1).
This scalar forces the surface brightness profile of the MGE model to decrease at least as fast as R**(-outer_slope) at the largest measured radius (Default: outer_slope=2).
Set plot=True to plot the best-fitting MGE profiles.

This can be either a two or a four elements vector.

If qbounds has two elements, it gives the minimum and maximum axial ratio q allowed in the MGE fit.

If qbounds has four elements [[qMin1, qMax1], [qMin2, qMax2]], then the first two elements give the limits on q for the even Gaussians, while the last two elements give the limits on q for the odd Gaussians. In this way qbounds can be used to perform disk/bulges decompositions in a way similar to the bulge_disk keyword.

Set quiet = True to suppress printed output.
Two elements vector giving the minimum and maximum sigma allowed in the MGE fit. This is in the same PIXELS units as radius.
The pixel scale in arcsec/pixels. This is only used for the scale on the plots. It has no influence on the output. (default: 1)
sigmapsf: array_like with shape (q,)
Scalar giving the sigma of the PSF, or vector with the sigma of an MGE model for the circular PSF. This is in the same PIXELS units as radius. When fitting multiple images simultaneously this is the PSF of the high-resolution image [see pg. 406 of Cappellari (2002) for details]. (Default: no convolution)
If this keyword has at least 6 elements in input, the sigma and q_obs will be used as starting point for the optimization. This is useful for testing but is never needed otherwise. The format is described in the Output Parameters below.

Output Parameters

Stored as attributes of the MgeFit class:

sol: array_like with shape (3, ngauss)

Array with the best-fitting MGE solution:

  • sol[0] = total_counts of the Gaussian components;
  • sol[1] = sigma is the dispersion of the best-fitting Gaussians in pixels;
  • sol[2] = q_obs, is the observed axial ratio [q’ in the notation of Cappellari (2002)] of the best-fitting Gaussian components.

The relation below gives the Gaussian peak surface brightness surf:

total_counts, q_obs, sigma = m.sol  # Assign the solution to variables
surf = total_counts/(2*np.pi*q_obs*sigma**2)
Mean absolute deviation between the fitted MGE and the data expressed as a fraction. Good fits to high S/N images can reach values of absdev < 0.02 = 2%.


Other/Proprietary License

Copyright (c) 1999-2021 Michele Cappellari

This software is provided as is without any warranty whatsoever. Permission to use, for non-commercial purposes is granted. Permission to modify for personal or internal use is granted, provided this copyright and disclaimer are included in all copies of the software. All other rights are reserved. In particular, redistribution of the code is not allowed.


V5.0.14: MC, Oxford, 24 June 2021

  • Formatted documentation as reStructuredText.

V5.0.13: MC, Oxford, 1 October 2020

  • With negative=True use Numpy linalg.lstsq instead of Scipy for a better default in the criterion for rank deficiency. Fixed ignoring negative weights in output with negative=True.

V5.0.12: MC, Oxford, 1 October 2018

  • Fixed clock DeprecationWarning in Python 3.7. Use SciPy 1.1 maxiter keyword in nnls.

V5.0.11: MC, Oxford, 12 May 2018

  • Dropped legacy Python 2.7 support.

V5.0.10: MC, Oxford, 17 April 2018

  • Changed imports for mgefit package.

V5.0.9: MC, Oxford, 21 November 2017

  • changed sigmapsf and normpsf keywords to lowercase.

V5.0.8: MC, Oxford, 25 May 2017

  • _fitfunc() does not return unused status any more, for consistency with the corresponding change to cap_mpfit.

V5.0.7: MC, Oxford, 14 February 2017

  • Make plot() callable after the program terminates. Included fignum keyword and removed obsolete debug keyword. Use line colors from current color cycle.

V5.0.6: MC, Oxford, 24 January 2017

  • Improved labelling for Matplotlib 2.0.

V5.0.5: MC, Oxford, 18 June 2015

  • Fixed plotting issue when combining profiles from multiple images. Thanks to Arianna Picotti (MPIA) for the bug report with examples. Only plot profiles for the best-fitting MGE.

V5.0.4: MC, Atlantic Ocean, 6 June 2015

  • Fully broadcast _fitfunc.

V5.0.3: MC, Atlantic Ocean, 28 March 2015

  • Make sure qbounds is a Numpy array. Include absdev in the class attributes. Nicely format printed solution.

V5.0.2: MC, Oxford, 24 September 2014

  • Improved plotting.

V5.0.1: MC, Oxford, 25 May 2014

  • Support both Python 2.7 and Python 3.

V5.0.0: MC, Aspen Airport, 8 February 2014

  • Translated from IDL into Python.

V4.1.3: MC, Oxford, 23 January 2013

  • Explained optional usage of SOL in input. Removed stop when MPFIT reports over/underflow.

V4.1.2: MC, Oxford, 24 April 2012

  • Small change to the treatment of the innermost unresolved Gaussians.

V4.1.1: MC, Oxford, 12 November 2010

  • Added keyword /QUIET.

V4.1.0: MC, Oxford, 22 April 2010

  • Allow QBOUNDS to have four elements, to perform bulge/disk decompositions similarly to the /BULGE_DISK option.

V4.0.1: MC, Oxford, 6 June 2009

  • Added output keyword ABSDEV. Fixed display not being updated while iterating under Windows.

V4.0.0: MC, Windhoek, 5 October 2008

  • Added /BULGE_DISK keyword to perform non-parametric bulge/disks decompositions using MGE. Updated MPFIT to version v1.52 2008/05/04, to fix a bug with the required parinfo.tied mechanism. In the new version of MPFIT, which I again renamed MGE_MPFIT, I implemented my previous important modification to improve convergence with MGE_FIT_SECTORS.

V3.9.5: MC, Oxford, 24 September 2008

  • Force Gaussians smaller than the PSF, which have a degenerate axial ratio, to have the same axial ratio as the mean of the first two well determined Gaussians.

V3.9.4: MC, Oxford, 16 May 2008

  • Use more robust la_least_squares (IDL 5.6) instead of SVDC with /NEGATIVE keyword.

V3.9.3: MC, Leiden, 18 October 2005

  • Changed axes labels in plots.

V3.9.2: MC, Leiden, 11 October 2005

  • Print iterations of the longer part at the end, not of the short “Gaussian cleaning” part.

V3.9.1: MC, Leiden, 1 May 2005

  • Replaced LOGRANGE keyword in example with the new MAGRANGE.

V3.9.0: MC, Leiden, 23 October 2004

  • Allow forcing the outer slope of the surface brightness profile of the MGE model to decrease at least as R**-n at the largest measured radius (cfr. version 3.8). Clean the solution at the end of the nonlinear fit as already done in the /LINEAR implementation. It’s almost always redundant, but quick.

V3.8.1: MC, Vicenza, 23 August 2004

  • Make sure this routine uses the Nov/2000 version of Craig Markwardt MPFIT which was renamed MGE_MPFIT to prevent potential conflicts with more recent versions of the same routine.

V3.8.0: MC, Leiden, 8 May 2004

  • Force the surface brightness of the MGE model to decrease at least as R**-2 at the largest measured radius.

V3.7.6: MC, Leiden, 20 March 2004

  • Use updated calling sequence for BVLS.

V3.7.5: MC, Leiden 23 July 2003

  • Corrected small bug introduced in V3.73. Thanks to Arend Sluis.

V3.7.4: MC, Leiden, 9 May 2003

  • Use N_ELEMENTS instead of KEYWORD_SET to test non-logical keywords.

V3.7.3: MC, Leiden, 7 March 2003

  • Force the input parameters to the given bounds if they fall outside the required range before starting the fit. After feedback from Remco van den Bosch.

V3.7.2: MC, Leiden, 13 October 2002

  • Added ERRMSG keyword to MPFIT call.

V3.7.1: MC, Leiden 20 May 2002

  • Added compilation options.

V3.7.0: MC, Leiden, 23 February 2002

  • Added explicit stepsize (STEP) of numerical derivative in parinfo structure, after suggestion by Craig B. Markwardt.

V3.6.0: MC, Leiden, 23 October 2001

  • Modified implementation of /NEGATIVE keyword.

V3.5.0: MC, Leiden, 8 October 2001

  • Updated documentation.

V3.4.0: MC, Leiden, 20 September 2001

  • Added /FASTNORM keyword

V3.3.0: MC, Leiden, 26 July 2001

  • Added MGE PSF convolution, central pixel integration and changed program input parameters to make it independent from SECTORS_PHOTOMETRY

V3.2.0: MC, Leiden, 8 July 2001

  • Graphical changes: always show about 7 sectors on the screen, and print plots with shared axes.

V3.1.0: MC, Leiden, 27 April 2001

  • More robust definition of err in FITFUNC_MGE_SECTORS.

V3.0.0: MC, Padova, July 2000

  • Significant changes.

V2.0.0: MC, Leiden, January 2000

  • Major revisions.

V1.0.0: Padova, February 1999

  • First implementation by Michele Cappellari.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mgefit-5.0.14.tar.gz (11.5 MB view hashes)

Uploaded source

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page