Package: mgefit
The MgeFit PackageMgeFit: Multi-Gaussian Expansion Fitting of Galactic ImagesMgeFit is a Python implementation of the robust and efficient Multi-Gaussian
Expansion (MGE) fitting algorithm for galactic images ofCappellari (2002).The MGE parameterization is useful in the construction of realistic dynamical
models of galaxies (seeJAM modelling),
for PSF deconvolution of images, for the correction and estimation of dust
absorption effects, or for galaxy photometry.ContentsThe MgeFit PackageAttributionInstallationUsage Examplesmge_fit_sectorsPurposeCalling SequenceInput ParametersOptional KeywordsOutput Parametersmge_fit_1dPurposeCalling SequenceInput ParametersOptional KeywordsOutput ParametersExamplefind_galaxyPurposeCalling SequenceInput ParametersOptional KeywordsOutput ParametersExampleLicenseChangelogAttributionIf you use this software for your research, please citeCappellari (2002).
The BibTeX entry for the paper is:@Article{Cappellari2002,
    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}
}Installationinstall with:pip install mgefitWithout writing access to the globalsite-packagesdirectory, use:pip install --user mgefitTo upgrade MgeFit to the latest version use:pip install --upgrade mgefitUsage ExamplesTo learn how to use theMgeFitpackage, copy, modify and run
the example programs in themgefit/examplesdirectory.
It can be found within the mainMgeFitpackage installation folder
insidesite-packages.
The detailed documentation is contained in the docstring of each file,
or for the main procedure onPyPi.mge_fit_sectorsPurposeApproximates the surface brightness of a galaxy with a Multi-Gaussian Expansion
(MGE) model, using the robust and automated fitting method ofCappellari (2002).The measurements are taken along sectors with a previous call to the
proceduresectors_photometryin theMgeFitpackage .
All measurements within this program are in the instrumental units ofpixelsandcounts. This routine fits MGE models with constant position angle and
common center.Calling Sequencefrommgefit.mge_fit_sectorsimportmge_fit_sectorsm=mge_fit_sectors(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 variablesprint(m.sol.T)# Print a table of best-fitting MGE parametersExample programs are in themgefit/examplesdirectory.
It can be found within the mainMgeFitpackage installation folder
insidesite-packages.A PDF manualreadme_mge_fit_sectors.pdfis contained in the main
installation directorymgefitof the package insidesite-packages.Input Parametersradius: 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 vectorsradiusandangle.
When fitting multiple images simultaneously this is in counts/pixels units
of the high-resolution image.eps:Crude estimate for the galaxy characteristic ellipticityeps = 1 - b/a = 1 - q'Optional Keywordsbulge_disk:Setbulge_disk=Trueto perform a non-parametric bulge/disk
decomposition using MGE. Whenbulge_disk=Truethe 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 increasengauss.
One should also either setqbounds=Noneor specify four
elements inqboundsfor the even/odd Gaussians.fignum:Optional number to assign to the plotting window.linear:Set this keyword to start with the fully linear algorithm
and then optimize the fit with the nonlinear method
[see Section 3.4 ofCappellari (2002)for details].
Nowadays using this keyword instroduces a small speed panelty but
produces more robust fits and is always reccomended.negative: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.ngauss:Maximum number of Gaussians allowed in the MGE fit.
Typical values are in the range 10-20 whenlinear=False(default:ngauss=12) and20**2-40**2whenlinear=True(default:ngauss=30**2=900).normpsf: array_like with shape (p,)This is optional if only a scalar is given forsigmapsf, otherwise it
must contain the normalization of each MGE component of the PSF, whose
sigma is given bysigmapsf. The vector needs to have the same number of
elements assigmapsfand it must be normalized asnormpsf.sum() = 1(default:normpsf=1).outer_slope:This scalar forces the surface brightness profile of
the MGE model to decrease at least as fast asR**(-outer_slope)at the largest measured radius (Default:outer_slope=2).plot:Setplot=Trueto plot the best-fitting MGE profiles.qbounds:This can be either a two or a four elements vector.Ifqboundshas two elements, it gives the minimum and maximum
axial ratioqallowed in the MGE fit.Ifqboundshas four elements[[qMin1, qMax1], [qMin2, qMax2]],
then the first two elements give the limits onqfor the even
Gaussians, while the last two elements give the limits onqfor the
odd Gaussians. In this wayqboundscan be used to perform disk/bulges
decompositions in a way similar to thebulge_diskkeyword.quiet:Setquiet = Trueto suppress printed output.rbounds:Two elements vector giving the minimum and maximumsigmaallowed in the MGE fit. This is in the same PIXELS units asradius.scale:The pixel scale in arcsec/pixels. This isonlyused for the scale on
the plots. It has no influence on the output. (default: 1)sigmapsf: array_like with shape (p,)Scalar giving thesigmaof the PSF, or vector with thesigmaof an
MGE model for the circular PSF. This is in the same PIXELS units asradius.
When fitting multiple images simultaneously this is the PSF of the
high-resolution image [see pg. 406 ofCappellari (2002)for details].
(Default: no convolution)sol: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 ParametersStored as attributes of theMgeFitclass:.sol: array_like with shape (3, ngauss)Array with the best-fitting MGE solution:.sol[0]: array_like with shape (ngauss)total_countsof the Gaussian components;.sol[1]: array_like with shape (ngauss)sigmais the dispersion of the best-fitting Gaussians in pixels;.sol[2]: array_like with shape (ngauss)q_obsis the observed axial ratio of the best-fitting
Gaussian components [q’ in the notation ofCappellari (2002)].The relation below gives the Gaussians peak surface brightnesssurf:total_counts, q_obs, sigma = m.sol  # Assign MGE solution to variables
surf = total_counts/(2*np.pi*q_obs*sigma**2)absdev:Mean absolute deviation between the fitted MGE and the
data expressed as a fraction. Good fits to high S/N images
can reach values ofabsdev < 0.02 = 2%.mge_fit_1dPurposeApproximates the 1-dim radial profile of the density or surface-brightness
of a galaxy with a Multi-Gaussian Expansion (MGE) model, using the robust
and automated fitting method ofCappellari (2002).Calling Sequencep=mge_fit_1d(x,y,negative=False,ngauss=12,rbounds=None,inner_slope=2,outer_slope=3,quiet=False,fignum=1)total_counts,sigma=p.sol# Assign the solution to variablesprint(m.sol.T)# Print a table of best-fitting MGE parametersSee usage example at the end of this file.Input Parametersx: array_like with shape (n,)Vector of the logarithmically sampled (Important!)
abscissa for the profile that has to be fitted.y: array_like with shape (n,)Ordinate of the profile evaluated at the abscissax.Optional Keywordsngauss:Number of Gaussian on want to fit. Typical values are 10-20.negative:Setnegative=Trueto allow for negative Gaussians in the fit.
Use this only if there is clear evidence that negative Gaussians
are actually needed e.g. to fit a radially increasing profile.inner_slope:This scalar forces the surface brightness profile of the MGE model to
decrease asR**(-inner_slope)at the smallest measured radius
(Default:inner_slope=2). The default is generally ok, but it can
be changed e.g. to allow for steeper inner profiles.outer_slope:This scalar forces the surface brightness profile of the MGE model to
decrease asR^(**outer_slope)at the largest measured radius
(Default:outer_slope=3). The default is generally ok, but it can
be changed e.g. to allow for a sharper outer truncation.rbounds:Two elements vector giving the minimum and maximum sigma allowed in the
MGE fit. This is in the same units ofx. With this keyword,inner_slopeandouter_slopeare ignored.quiet:Setquiet=Trueto suppress plots and printed output.Output ParametersStored as attributes of themge_fit_1dclass:.sol: array_like with shape (2, ngauss)Contains an array with the best-fitting solution:.sol[0]: array_like with shape (ngauss)TotalCounts(area under the 1-dim curve) of the Gaussians..sol[1]: array_like with shape (ngauss)sigma, is the dispersion of the Gaussians in units ofx.IMPORTANT: Given theTotalCountsdefinition:If the fit was done to the projected surface density profile(Msun/pc^2)the Gaussians peak surface densities(Msun/pc^2)are given by:surf = TotalCounts/(np.sqrt(2*np.pi)*Sigma)If the fit was done to the intrinsic density profile(Msun/pc^3)the Gaussians peak densities(Msun/pc^3)are still given by:dens = TotalCounts/(np.sqrt(2*np.pi)*Sigma)In either case, one can convert between densities in(Msun/pc^3)and surface densities in(Msun/pc^2)using the formula:dens = surf/(np.sqrt(2*np.pi)*Sigma)This is eq. (6) of the filereadme_mge_fit_sectors.pdfcontained in the main installation directorymgefitof the
package insidesite-packages.ExampleThe sequence of commands below was used to generate the
one-dimensional MGE fit of Fig.3 inCappellari (2002)importnumpyasnpfrommgefit.mge_fit_1dimportmge_fit_1dn=300# Number of sampled pointsR=np.geomspace(0.01,300,n)# radii must be logarithmically sampledrho=(1+R)**(-4)p=mge_fit_1d(R,rho,ngauss=16)find_galaxyPurposeFind the largest region of connected pixels (after smoothing)
lying above a given intensity level of the image.
This is useful to automatically identify the location and orientation of
a galaxy in an image, assuming it is the largest positive fluctuation.
The conventions used by this routine are the same as for the rest
of theMgeFit``package.This procedure uses the weighted first and second moments of the intensity
distribution for the computation of the galaxy center and position angle.Calling Sequencefrommgefit.find_galaxyimportfind_galaxyf=find_galaxy(img,binning=5,fraction=0.1,level=None,nblob=1,plot=False,quiet=False)print('Ellipticity:%.3f'%f.eps)Input ParametersImg: array_like with shape (nr, nc)The galaxy images as a 2-dim array.Optional Keywordsbinning: float, optionalpixel scale for the image smoothing applied before selection.fraction: float, optionalThis corresponds (approximately) to the fraction[0 < fraction < 1]of the image pixels that one wants to consider
to estimate galaxy parameters (defaultfraction = 0.1 = 10%)level: float, optionalLevel above which to select pixels to consider in the
estimate of the galaxy parameters. This is an alternative
to the use of thefractionkeyword.nblob: int, optionalIfnblob=1(default) the procedure selects the largest feature
in the image, ifnblob=2the second largest is selected, and so
on for increasing values ofnblob. This is useful when the
galaxy is not the largest feature in the image.plot: boolean, optionalsetplot=Trueto display an image in the current graphic window
showing the pixels used in the computation of the moments.quiet: boolean, optionalSetquiet = Trueto suppress printed output.Output ParametersStored as attributes of thefind_galaxyclass:.eps:The galaxy “average” ellipticityEps = 1 - b/a = 1 - q'..pa:Standard astronomical PA measured counter-clockwise from the imageYaxis (assumed to coincide with North). Note:f.pa = 270 - f.theta..theta:Position angle measured clock-wise from the imageXaxis..majoraxis:Maximum distance of any of the the selected pixels from(xmed, ymed).
For a standar galaxy surface brightness this corresponds to the
major axis of the selected isophote..xpeak:First index (row) inImg, of the pixel containing the galaxy center.
To be precise this coordinate represents the first index of the brightest
pixels within a 40x40 pixels box centered on the galaxy average center.IMPORTANT: The brightest galaxy pixel is the elementImg[xpeak, ypeak].
In the plot produced byfind_galaxy, the brightest pixel has
coordinates(Ypeak, Xpeak), with the two coordinates swapped!.ypeak:Second index (column) in Img, of the brightest galaxy pixel..xmed:Xcoordinate of luminosity weighted galaxy center..ymed:Ycoordinate of luminosity weighted galaxy center.ExampleThe command below locates the position and orientation of a galaxy
in the imageImg``and produces a plot showing the obtained results
and the region of the image used in the computation:f=find_galaxy(img,plot=True)print(f'Ellipticity:{f.eps:.3f}')The command below only uses 2% of the image pixels to estimate
the intensity weighted moments and show the results:f=find_galaxy(img,fraction=0.02,plot=True)print(f'Coordinates of the peak intensity:{f.xpeak}{f.xpeak}')LicenseOther/Proprietary LicenseCopyright (c) 1999-2023 Michele CappellariThis 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.ChangelogV5.0.15: MC, Oxford, 31 March 2023mge_print_contours,mge_print_contours_twist: New keywordminlevel.mge_print_contours,mge_print_contours_twist: Analytic integral of the central pixel.mge_fit_examples: Updated to useminlevelkeyword.Included documentation of more functions on PyPi.V5.0.14: MC, Oxford, 24 June 2021Formatted documentation as reStructuredText.V5.0.13: MC, Oxford, 1 October 2020Withnegative=Trueuse Numpy linalg.lstsq instead of Scipy
for a better default in the criterion for rank deficiency.
Fixed ignoring negative weights in output withnegative=True.V5.0.12: MC, Oxford, 1 October 2018Fixed clock DeprecationWarning in Python 3.7.
Use SciPy 1.1maxiterkeyword innnls.V5.0.11: MC, Oxford, 12 May 2018Dropped legacy Python 2.7 support.V5.0.10: MC, Oxford, 17 April 2018Changed imports for mgefit package.V5.0.9: MC, Oxford, 21 November 2017changedsigmapsfandnormpsfkeywords 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 2017Make plot() callable after the program terminates.
Includedfignumkeyword and removed obsoletedebugkeyword.
Use line colors from current color cycle.V5.0.6: MC, Oxford, 24 January 2017Improved labelling for Matplotlib 2.0.V5.0.5: MC, Oxford, 18 June 2015Fixed 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 2015Fully broadcast _fitfunc.V5.0.3: MC, Atlantic Ocean, 28 March 2015Make sure qbounds is a Numpy array. Include absdev in the class attributes.
Nicely format printed solution.V5.0.2: MC, Oxford, 24 September 2014Improved plotting.V5.0.1: MC, Oxford, 25 May 2014Support both Python 2.7 and Python 3.V5.0.0: MC, Aspen Airport, 8 February 2014Translated from IDL into Python.V4.1.3: MC, Oxford, 23 January 2013Explained optional usage of SOL in input.
Removed stop when MPFIT reports over/underflow.V4.1.2: MC, Oxford, 24 April 2012Small change to the treatment of the innermost unresolved Gaussians.V4.1.1: MC, Oxford, 12 November 2010Added keyword /QUIET.V4.1.0: MC, Oxford, 22 April 2010Allow QBOUNDS to have four elements, to perform bulge/disk
decompositions similarly to the /BULGE_DISK option.V4.0.1: MC, Oxford, 6 June 2009Added output keyword ABSDEV. Fixed display not being updated
while iterating under Windows.V4.0.0: MC, Windhoek, 5 October 2008Added /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 2008Force 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 2008Use more robust la_least_squares (IDL 5.6) instead of SVDC with
/NEGATIVE keyword.V3.9.3: MC, Leiden, 18 October 2005Changed axes labels in plots.V3.9.2: MC, Leiden, 11 October 2005Print iterations of the longer part at the end, not of the
short “Gaussian cleaning” part.V3.9.1: MC, Leiden, 1 May 2005Replaced LOGRANGE keyword in example with the new MAGRANGE.V3.9.0: MC, Leiden, 23 October 2004Allow 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 2004Make 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 2004Force 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 2004Use updated calling sequence for BVLS.V3.7.5: MC, Leiden 23 July 2003Corrected small bug introduced in V3.73. Thanks to Arend Sluis.V3.7.4: MC, Leiden, 9 May 2003Use N_ELEMENTS instead of KEYWORD_SET to test
non-logical keywords.V3.7.3: MC, Leiden, 7 March 2003Force 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 2002Added ERRMSG keyword to MPFIT call.V3.7.1: MC, Leiden 20 May 2002Added compilation options.V3.7.0: MC, Leiden, 23 February 2002Added explicit stepsize (STEP) of numerical derivative in
parinfo structure, after suggestion by Craig B. Markwardt.V3.6.0: MC, Leiden, 23 October 2001Modified implementation of /NEGATIVE keyword.V3.5.0: MC, Leiden, 8 October 2001Updated documentation.V3.4.0: MC, Leiden, 20 September 2001Added /FASTNORM keywordV3.3.0: MC, Leiden, 26 July 2001Added MGE PSF convolution, central pixel integration and changed
program input parameters to make it independent from SECTORS_PHOTOMETRYV3.2.0: MC, Leiden, 8 July 2001Graphical changes: always show about 7 sectors on the screen,
and print plots with shared axes.V3.1.0: MC, Leiden, 27 April 2001More robust definition of err in FITFUNC_MGE_SECTORS.V3.0.0: MC, Padova, July 2000Significant changes.V2.0.0: MC, Leiden, January 2000Major revisions.V1.0.0: Padova, February 1999First implementation by Michele Cappellari.