gsf package

Submodules

gsf.basic_func module

class gsf.basic_func.Basic(MB)

Bases: object

Z2NZ(Z)

Critical function to infer NZ from Z.

class gsf.basic_func.Basic_tau(MB)

Bases: object

Z2NZ(Z, tau, age)

Critical function to infer NZ from Z.

gsf.fitting module

gsf.function module

gsf.function.SFH_cons(t0, tau, A, tt=None, minsfr=1e-10)
gsf.function.SFH_dec(t0, tau, A, tt=None, minsfr=1e-10)
gsf.function.SFH_del(t0, tau, A, tt=None, minsfr=1e-10)

SFH

gsf.function.apply_dust(yy, xx, nr, Av, dust_model=0)
xxfloat array

RF Wavelength

gsf.function.calc_Dn4(x0, y0, z0, lam_b_low=3750, lam_b_hig=3950, lam_r_low=4050, lam_r_hig=4250, is_fnu=False)

Parameters

x0, y0float arrays

wavelength and flux

z0float

redshift

gsf.function.check_line(data, wave, wht, model)
gsf.function.check_line_cz(ycont, xcont, wycont, model, zgal)
gsf.function.check_line_cz_man(ycont, xcont, wycont, model, zgal, LW=[2800, 3347, 3727, 3799, 3836, 3869, 4102, 4341, 4861, 4960, 5008, 5175, 6563, 6717, 6731], norder=5.0)

Parameters

LW

List for emission lines to be masked.

Returns

wht

Processed weight, where wavelength at line exists is masked.

ypoly

Fitted continuum flux.

gsf.function.check_line_man(data, xcont, wht, model, zgal, LW=[2800, 3347, 3727, 3799, 3836, 3869, 4102, 4341, 4861, 4960, 5008, 5175, 6563, 6717, 6731], lsig=1.5)

Parameters

lsigfloat

which sigma to detect lines.

gsf.function.check_rejuv(age, SF, MS, SFMS_50, lm_old=10.0, delMS=0.2)

A Function to check rejuvenation.

Parameters

delMSfloat

Scatter around the Main Sequence. 0.2 dex, in default.

gsf.function.data_int(lmobs, lmtmp, ftmp)

Parameters

lmobs

Observed wavelength.

lmtmp, ftmp:

Those to be interpolated.

gsf.function.delta(x, A)
gsf.function.detect_line(xcont, ycont, wycont, zgal)
gsf.function.detect_line_man(xcont, ycont, wycont, zgal, LW, model)
gsf.function.dust_calz(lm, fl, Av: float, nr, Rv: float = 4.05, lmlimu: float = 3.115, f_Alam: bool = False)

Parameters

lmfloat array

wavelength, at RF.

flfloat array

fnu

Avfloat

in mag

nrint array

index, to be used for sorting.

Rvfloat

from Calzetti+00

lmlimufloat

Upper limit. 2.2 in Calz+00

gsf.function.dust_gen(lm, fl, Av, nr, Rv=4.05, gamma=-0.05, Eb=3.0, lmlimu=3.115, lmv=0.5, f_Alam=False)

For general purpose (Noll+09). This function is much better than previous, but is hard to impliment for the current version. A difference from dust_gen is Eb is defined as a function of gamma.

Parameters

lmfloat array

wavelength, at RF.

flfloat array

fnu

Avfloat

in mag

nrint array

index, to be used for sorting.

Rv

from Calzetti+00

gamma :

gamma.

Eb:

Eb

gsf.function.dust_kc(lm, fl, Av, nr, Rv=4.05, gamma=0, lmlimu=3.115, lmv=0.5, f_Alam=False)

Dust model by Kriek&Conroy13

Parameters

lmfloat array

RF Wavelength.

flfloat array

in fnu

Avfloat

in mag

nrint array

index, to be used for sorting.

Rvfloat

from Calzetti+00

gammafloat

See Eq.1

gsf.function.dust_mw(lm, fl, Av, nr, Rv=3.1, f_Alam=False)

Parameters

lmfloat array

wavelength, at RF, in AA.

flfloat array

fnu

Avfloat

mag

nrint array

index, to be used for sorting.

Rvfloat

3.1 for MW.

gsf.function.fil_fwhm(band0, DIR)

Parameters

f0 :

in fnu

gsf.function.filconv(band0, l0, f0, DIR, fw=False, f_regist=True, MB=None)

Parameters

f0float array

Flux for spectrum, in fnu

l0float array

Wavelength for spectrum, in AA (that matches filter response curve’s.)

f_registbool

If True, read filter response curves and register those to MB.

gsf.function.filconv_cen(band0, l0, f0, DIR='FILT/')

Convolution of templates with filter response curves.

Parameters

gsf.function.filconv_fast(filts, band, l0, f0, fw=False)

Parameters

filts, band

From MB.filts and MB.band, respectively.

f0:

Flux for spectrum, in fnu

l0:

Wavelength for spectrum, in AA (that matches filter response curve’s.)

gsf.function.fit_spec(lm, fobs, eobs, ftmp)

Fitting. (Not sure)

gsf.function.fit_specphot(lm, fobs, eobs, ftmp, fbb, ebb, ltmp_bb, ftmp_bb)
gsf.function.flamtonu(lam, flam, m0set=25.0, m0=-48.6)

Converts from Flam to Fnu, with mag zeropoint of m0set.

gsf.function.fnutolam(lam, fnu, m0set=25.0, m0=-48.6, has_unit=False)

Converts from Fnu to Flam, from mag zeropoint of m0set (to -48.6).

Parameters

m0setfloat

current magzp.

m0float

target magzp. The default, -48.6, is for flam (erg/s/cm2/lambda).

gsf.function.fnutonu(fnu, m0set=25.0, m0input=-48.6, has_unit=False)

Converts from Fnu (cgs) to Fnu (m0=m0set)

Parameters

fnufloat array

flux in cgs, with magnitude zero point of m0input.

m0setfloat

Target mag zero point.

m0inputfloat

Original value for magzp. If erg/s/cm2/Hz, -48.6.

gsf.function.func_tmp(xint, eobs, fmodel)
gsf.function.gaus(x, a, x0, sigma)
gsf.function.gauss(x, A, sig)
gsf.function.get_Fint(lmtmp, ftmp, lmin=1400, lmax=1500)

Parameters

lmtmp

Rest frame wave (AA)

ftmp :

Fnu ()

Returns

integrated flux.

gsf.function.get_Fuv(lmtmp, ftmp, lmin=1400, lmax=1500)

Get RF UV (or any wavelength) flux density.

Parameters

lmtmpfloat array

Rest-frame wavelength, in AA.

ftmpfloat array

Fnu

Returns

Flux density estimated over lmin:lmax. Not integrated sum.

gsf.function.get_SFMS(red, age, mass, IMF=1, get_param=False)

Gets SFMS at age ago from z=red.

Parameters

redfloat

Observed redshift

agearray

lookback time, in Gyr.

massarray

stellar mass (array) at each age, in Msun (not logM).

Returns

SFR, in logMsun/yr.

Notes

From Speagle+14 Eq28. Chabrier IMF, in default

gsf.function.get_chi2(fy, ey, wht3, ysump, ndim_eff, SNlim=1.0, f_chind=True, f_exclude=False, xbb=None, x_ex=None)
gsf.function.get_fit(x, y, xer, yer, nsfh: str = 'Del.')
gsf.function.get_ind(wave, flux)

Gets Lick index for input

Returns

equivalent width

gsf.function.get_input()

Gets a default dictionary for input params.

gsf.function.get_leastsq(MB, ZZtmp, fneld, age, fit_params, residual, fy, ey, wht, ID0, chidef=None, Zbest=0, f_keep=False, f_only_spec=False)

Get initial parameters at various Z

gsf.function.get_uvbeta(lm, flam, zbes, lam_blue=1650, lam_red=2300, return_results=False)

Purpose

get UV beta_lambda slope.

Parameters

lmfloat array

in lambda

flamfloat array

in flambda

gsf.function.loadcpkl(cpklfile)

Load cpkl files.

gsf.function.moffat(xx, A, x0, gamma, alp)
gsf.function.printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r', emojis=[''])

Call in a loop to create terminal progress bar.

Parameters

iterationint

current iteration

totalint

total iterations

prefixstr

prefix string

suffixstr

suffix string

decimalsint

positive number of decimals in percent complete

lengthint

character length of bar

fillstr

bar fill character

printEndstr

end character

gsf.function.print_err(msg, exit=False, details=None)
gsf.function.read_input(parfile)

Gets info from param file.

Returns

inputsdict

Input dictionary.

gsf.function.savecpkl(data, cpklfile, verbose=True)

Save data into cpklfile.

gsf.function.str2bool(v)
gsf.function.write_input(inputs, file_out='gsf.input')

Gets an ascii format param file.

Returns

file_out

gsf.function_class module

class gsf.function_class.Func(MB, dust_model: int = 0)

Bases: object

The list of (possible) Func attributes is given below:

Attributes

get_template(par, f_Alog: bool = True, nprec: int = 1, f_val: bool = False, lib_all: bool = False, f_nrd: bool = False, f_apply_dust: bool = True, f_IGM=True, deltaz_lim=0.1, f_neb=False, EBVratio: float = 2.27, f_agn=False)

Makes model template for a given parameter set, par.

Parameters

nprecint

Precision when redshift is refined.

f_apply_dustbool

Apply dust attenuation to nebular emission.

EBVratiofloat

E(B-V)_neb / E(B-V)_st. Useful table in https://iopscience.iop.org/article/10.3847/1538-4357/aba35e/pdf

f_nebbool

Expect to explore nebular template or not.

Notes

This function is only used in plot_sed.py. Common function for mebular and nonnebular temlates.

get_template_single(A00, Av, nmodel, Z, zgal, lib, logU=None, AGNTAU=None, f_apply_dust=True, EBVratio=2.27)

Parameters

EBVratiofloat

E(B-V)_neb / E(B-V)_st. Useful table in https://iopscience.iop.org/article/10.3847/1538-4357/aba35e/pdf

Notes

This function is only used in plot_sed.py. Common function for mebular and nonnebular temlates.

get_total_flux(par, f_Alog=True, lib_all=True, pp=0, lib=None, f_get_Mtot=False, f_check_limit=True)

get total flux for a given set of parameter.

Parameters

parlibrary

contains parameters. Needs to include: [‘Z’,’A’]

Returns

nr, xx, yyfloat arrays

xx is OBSERVED wavelength at z=MB.zgal

get_total_flux_agn(par, f_Alog=True, lib_all=True, lib=None)

get total flux for a given set of parameter.

Parameters

parlibrary

contains parameters

get_total_flux_neb(par, f_Alog=True, lib_all=True, lib=None)

get total flux for a given set of parameter.

Parameters

parlibrary

contains parameters

open_spec_dust_fits(fall: int = 0)

Loads dust template in obs range.

open_spec_fits(fall: int = 0, orig: bool = False, f_neb=False, f_agn=False)

Load template in obs range.

Parameters

fallint

If 1, returns full spectra.

origbool

If True, returns the original spectra.

Returns

lib : float array

tmp04_dust(par, nprec=1, return_full=False)

Makes model template with a given param setself. Also dust attenuation.

class gsf.function_class.Func_tau(MB, dust_model: int = 0)

Bases: object

get_template(par, f_Alog=True, nprec=1, f_val=False, check_bound=False, lib_all=False, lib=None, f_nrd=False, f_apply_dust=True, f_neb=False, deltaz_lim=0.1)

Makes model template with a given param set. Also dust attenuation.

Parameters:

nprecint

Precision when redshift is refined.

get_total_flux(par, f_Alog=True, lib_all=True, pp=0, lib=None, f_get_Mtot=False, f_check_limit=True)
get_total_flux_agn(par, f_Alog=True, lib_all=True, pp=0, lib=None, f_get_Mtot=False, f_check_limit=True)
get_total_flux_neb(par, f_Alog=True, lib_all=True, pp=0, lib=None, f_get_Mtot=False, f_check_limit=True)
open_spec_dust_fits(fall: int = 0)

Load dust template in obs range.

open_spec_fits(fall=0, orig=False, f_neb=False, f_agn=False)

Loads template in obs range.

tmp04_dust(par, nprec=1)

Makes model template with a given param setself. Also dust attenuation.

gsf.function_igm module

gsf.function_igm.dijkstra_igm_abs(xtmp, ytmp, zin, cosmo=None, xLL=1216.0, ckms=300000.0, R_b1=1.0, delta_v_0=600, alpha_x=1.0, x_HI=None, verbose=False, zend=5, zstart=8)

Purpose

Apply IMG-attenuation of Dijikstra (2014). https://www.cambridge.org/core/services/aop-cambridge-core/content/view/S1323358014000332

Parameters

xtmpfloat array

Rest-frame wavelength, in AA.

ytmpfloat array

flux, in f_lambda.

zin

target redshift of IGM application

R_b1float

Bubble size, in Mpc

Returns

IGM attenuated flux.

gsf.function_igm.get_H(x, a)

Voigt function

gsf.function_igm.get_XI(z, zend=5, zstart=8)

Very simplified model.

gsf.function_igm.get_column(zin, cosmo, Mpc_cm=3.08568025e+24, z_r=6.0, delz=0.1)

Returns

HI column density of IGM at zin, in cm^-2.

gsf.function_igm.get_dtdz(z, zs, dtdzs)
gsf.function_igm.get_nH(z)

Purpose

Get HI density by using Cen & Haiman 2000.

Returns

HI density in IGM, in cm^-3

gsf.function_igm.get_sig_lya(lam_o, z_s, T=10000.0, c=3e+18)

Parameters

lam_ofloat array

Observed wavelength, in AA.

gsf.function_igm.madau_igm_abs(xtmp, ytmp, zin, cosmo=None, xLL=1216.0)

Purpose

Apply IMG-attenuation of Madau (1995) of zin to the input flux.

Parameters

xtmpfloat array

Rest-frame wavelength, in AA.

ytmpfloat array

flux, in f_lambda.

zin : target redshift of IGM application

Returns

IGM attenuated flux.

gsf.function_igm.masongronke_igm_abs(xtmp, ytmp, zin, cosmo=None, xLL=1216.0, c=3e+18, ckms=300000.0, zobs=6, xLLL=1400)

Purpose

Parameters

xtmpfloat array

Rest-frame wavelength, in AA.

ytmpfloat array

flux, in f_lambda.

zin : target redshift of IGM application

Returns

IGM attenuated flux.

gsf.gsf module

gsf.maketmp_filt module

gsf.maketmp_filt.check_library(MB, af, nround=3)

Check library if it has a consistency setup as input file.

Returns

flag : bool

gsf.maketmp_filt.convolve_templates(wave, spec, LSF, boundary='extend', f_prism=False, file_res=None, redshift=None, f_diff_conv=False)
file_resstr

From the official jdocs.

gsf.maketmp_filt.get_LSF(inputs, DIR_EXTR, ID, lm, wave_repr=4000, c=3e+18, sig_temp_def=50.0, redshift=None)

Load Morphology params, and returns LSF

Parameters

lmfloat array

wavelength array for the observed spectrum, in AA.

Returns

LSF

gsf.maketmp_filt.get_spectrum_draine(lambda_d, DL, zbest, numin, numax, ndmodel, DIR_DUST='./DL07spec/', phi=0.055, m0set=25.0)

Parameters

lambda_darray

Wavelength array, in AA.

phifloat

Eq.34 of Draine & Li 2007. (default: 0.055g/(ergs/s))

DLfloat

in cm.

Returns

Interpolated dust emission in Fnu of m0=25.0. In units of Fnu/Msun

Notes

umins = [‘0.10’, ‘0.15’, ‘0.20’, ‘0.30’, ‘0.40’, ‘0.50’, ‘0.70’, ‘0.80’, ‘1.00’, ‘1.20’, ‘1.50’, ‘2.00’, ‘2.50’, ‘3.00’, ‘4.00’, ‘5.00’, ‘7.00’, ‘8.00’, ‘10.0’, ‘12.0’, ‘15.0’, ‘20.0’, ‘25.0’] umaxs = [‘1e3’, ‘1e4’, ‘1e5’, ‘1e6’, ‘1e7’]

gsf.maketmp_filt.maketemp(MB, ebblim=10000000000.0, lamliml=0.0, lamlimu=50000.0, ncolbb=10000, tau_lim=0.001, tmp_norm=10000000000.0, nthin=1, delwave=0, lammax=300000, f_IGM=True)

Make SPECTRA at given z and filter set. Also, after v1.8, through this function library and data are register to the main class object, MB.

Parameters

inputsstr

Configuration file.

zbestfloat

Best redshift at this iteration. Templates are generated based on this reshift.

Zarray

Stellar phase metallicity in logZsun.

agearray

Age, in Gyr.

fnebint

flag for adding nebular emissionself.

tmp_normfloat

Normalization of the stored templated. i.e. each template is in units of tmp_norm [Lsun].

gsf.maketmp_filt.maketemp_tau(MB, ebblim=10000000000.0, lamliml=0.0, lamlimu=50000.0, ncolbb=10000, tau_lim=0.001, f_IGM=True, nthin=1, tmp_norm=10000000000.0, delwave=0, lammax=300000)

Make SPECTRA at given z and filter set.

Parameters

inputsstr

Configuration file.

zbest :float

Best redshift at this iteration. Templates are generated based on this reshift.

Zarray

Stellar phase metallicity in logZsun.

agearray

Age, in Gyr.

fnebint

flag for adding nebular emissionself.

f_IGMbool

IGM attenuation. Madau.

nthinint

Thinning templates.

lammaxfloat

Maximum wavelength in RF.

gsf.maketmp_filt.sim_spec(lmin, fin, sn)

SIMULATION of SPECTRA.

Parameters

sn : float array

Returns

frand : float array

erand : float array

get_spectrum_draine()

gsf.maketmp_filt.smooth_template_diff(waves, fluxes, Rs, Rs_template, f_diff_conv=False)

from Gina’s code Parameters ———- wave, flux, Rs: arrays

All have the same size.

sigma_templatefloat

Sigma of the template spectrum, in km/s

Notes

fsps templates have a resolution of ~2.5A FWHM from 3750AA - 7200AA restframe, and much lower (R~200 or so, but not actually well defined) outside this range.

gsf.maketmp_z0 module

gsf.maketmp_z0.make_tmp_z0(MB, lammin=100, lammax=160000, tau_lim=0.001, force_no_neb=False, Zforce=None, f_mp=True, smooth_uv=False)

This is for the preparation of default template, with FSPS, at z=0. Should be run before SED fitting.

Parameters

gsf.fitting.Mainbodyclass

Mainbody class, that contains attributes.

lamminfloat, optional

Minimum value of the rest-frame wavelength of the template, in AA.

lammaxfloat, optional

Maximum value of the rest-frame wavelength of the template, in AA.

tau_limfloat, optional

Maximum value of tau of the template, in Gyr. Tau smaller than this value would be approximated by SSP.

force_no_nebbool

Turn this on that you are very much sure do not want to include emission line templates, maybe to save some time running z0 module.

f_mpbool

Multiprocessing.

smooth_uvbool

Experimental - smoothing stellar spectra at rf-UV, as they look wiggling…

gsf.maketmp_z0.make_tmp_z0_bpass(MB, lammin=100, lammax=160000, Zforce=None, Zsun=0.02)

This is for the preparation of default template, with BPASS templates, at z=0. Should be run before SED fitting.

Parameters

gsf.fitting.Mainbodyclass

Mainbody class, that contains attributes.

lamminfloat, optional

Minimum value of the rest-frame wavelength of the template, in AA.

lammaxfloat, optional

Maximum value of the rest-frame wavelength of the template, in AA.

DIR_BPASSstr, optional

Path to the ditectory where BPASS templates are storesd.

BPASS_verstr, optional

Version of BPASS. Used to identify template files.

Zsunfloat, optional

Metallicity of templates, in units of absolute value (e.g. Zsun=0.02 for BPASS).

gsf.maketmp_z0.smooth_spectrum(wave, flux, wmin=0, wmax=1750, sigma=30, verbose=False)
wavefloat array

in AA

sigmafloat

in AA

gsf.maketmp_z0_tau module

gsf.maketmp_z0_tau.get_lognorm(t, ltau0, T0=-10)
gsf.maketmp_z0_tau.make_tmp_z0(MB, lammin=100, lammax=160000, Zforce=None)

This is for the preparation of default template, with FSPS, at z=0. Should be run before SED fitting.

Parameters

gsf.fitting.Mainbodyclass

Mainbody class, that contains attributes.

lamminfloat, optional

Minimum value of the rest-frame wavelength of the template, in AA.

lammaxfloat, optional

Maximum value of the rest-frame wavelength of the template, in AA.

tau_limfloat, optional

Maximum value of tau of the template, in Gyr. Tau smaller than this value would be approximated by SSP.

gsf.minimizer module

Simple minimizer is a wrapper around scipy.leastsq, allowing a user to build a fitting model as a function of general purpose Fit Parameters that can be fixed or varied, bounded, and written as a simple expression of other Fit Parameters.

The user sets up a model in terms of instance of Parameters and writes a function-to-be-minimized (residual function) in terms of these Parameters.

Original copyright:

Copyright (c) 2011 Matthew Newville, The University of Chicago

See LICENSE for more complete authorship information and license.

exception gsf.minimizer.AbortFitException(msg)

Bases: MinimizerException

Raised when a fit is aborted by the user.

class gsf.minimizer.Candidate(params, score)

Bases: tuple

property params

Alias for field number 0

property score

Alias for field number 1

class gsf.minimizer.Minimizer(userfcn, params, fcn_args=None, fcn_kws=None, iter_cb=None, scale_covar=True, nan_policy='raise', reduce_fcn=None, calc_covar=True, **kws)

Bases: object

A general minimizer for curve fitting and optimization.

ampgo(params=None, **kws)

Find the global minimum of a multivariate function using AMPGO.

AMPGO stands for ‘Adaptive Memory Programming for Global Optimization’ and is an efficient algorithm to find the global minimum.

Parameters

paramsParameters, optional

Contains the Parameters for the model. If None, then the Parameters used to initialize the Minimizer object are used.

**kwsdict, optional

Minimizer options to pass to the ampgo algorithm, the options are listed below:

local: str (default is 'L-BFGS-B')
    Name of the local minimization method. Valid options are:
    - 'L-BFGS-B'
    - 'Nelder-Mead'
    - 'Powell'
    - 'TNC'
    - 'SLSQP'
local_opts: dict (default is None)
    Options to pass to the local minimizer.
maxfunevals: int (default is None)
    Maximum number of function evaluations. If None, the optimization will stop
    after `totaliter` number of iterations.
totaliter: int (default is 20)
    Maximum number of global iterations.
maxiter: int (default is 5)
    Maximum number of `Tabu Tunneling` iterations during each global iteration.
glbtol: float (default is 1e-5)
    Tolerance whether or not to accept a solution after a tunneling phase.
eps1: float (default is 0.02)
    Constant used to define an aspiration value for the objective function during
    the Tunneling phase.
eps2: float (default is 0.1)
    Perturbation factor used to move away from the latest local minimum at the
    start of a Tunneling phase.
tabulistsize: int (default is 5)
    Size of the (circular) tabu search list.
tabustrategy: str (default is 'farthest')
    Strategy to use when the size of the tabu list exceeds `tabulistsize`. It
    can be 'oldest' to drop the oldest point from the tabu list or 'farthest'
    to drop the element farthest from the last local minimum found.
disp: bool (default is False)
    Set to True to print convergence messages.

Returns

MinimizerResult

Object containing the parameters from the ampgo method, with fit parameters, statistics and such. The return values (x0, fval, eval, msg, tunnel) are stored as ampgo_<parname> attributes.

New in version 0.9.10.

Notes

The Python implementation was written by Andrea Gavana in 2014 (http://infinity77.net/global_optimization/index.html).

The details of the AMPGO algorithm are described in the paper “Adaptive Memory Programming for Constrained Global Optimization” located here:

http://leeds-faculty.colorado.edu/glover/fred%20pubs/416%20-%20AMP%20(TS)%20for%20Constrained%20Global%20Opt%20w%20Lasdon%20et%20al%20.pdf

basinhopping(params=None, **kws)

Use the basinhopping algorithm to find the global minimum of a function.

This method calls :scipydoc:`optimize.basinhopping` using the default arguments. The default minimizer is BFGS, but since lmfit supports parameter bounds for all minimizers, the user can choose any of the solvers present in :scipydoc:`optimize.minimize`.

Parameters

paramsParameters object, optional

Contains the Parameters for the model. If None, then the Parameters used to initialize the Minimizer object are used.

Returns

MinimizerResult

Object containing the optimization results from the basinhopping algorithm.

New in version 0.9.10.

brute(params=None, Ns=20, keep=50, workers=1)

Use the brute method to find the global minimum of a function.

The following parameters are passed to :scipydoc:`optimize.brute` and cannot be changed:

brute() arg

Value

Description

full_output

1

Return the evaluation grid and the objective function’s values on it.

finish

None

No “polishing” function is to be used after the grid search.

disp

False

Do not print convergence messages (when finish is not None).

It assumes that the input Parameters have been initialized, and a function to minimize has been properly set up.

Parameters

paramsParameters, optional

Contains the Parameters for the model. If None, then the Parameters used to initialize the Minimizer object are used.

Nsint, optional

Number of grid points along the axes, if not otherwise specified (see Notes).

keepint, optional

Number of best candidates from the brute force method that are stored in the candidates attribute. If ‘all’, then all grid points from :scipydoc:`optimize.brute` are stored as candidates.

workersint or map-like callable, optional

For parallel evaluation of the grid, added in SciPy v1.3 (see :scipydoc:`optimize.brute` for more details).

Returns

MinimizerResult

Object containing the parameters from the brute force method. The return values (x0, fval, grid, Jout) from :scipydoc:`optimize.brute` are stored as brute_<parname> attributes. The MinimizerResult also contains the candidates attribute and show_candidates() method. The candidates attribute contains the parameters and chisqr from the brute force method as a namedtuple, (‘Candidate’, [‘params’, ‘score’]), sorted on the (lowest) chisqr value. To access the values for a particular candidate one can use result.candidate[#].params or result.candidate[#].score, where a lower # represents a better candidate. The show_candidates(#) uses the pretty_print() method to show a specific candidate-# or all candidates when no number is specified.

New in version 0.9.6.

Notes

The brute() method evalutes the function at each point of a multidimensional grid of points. The grid points are generated from the parameter ranges using Ns and (optional) brute_step. The implementation in :scipydoc:`optimize.brute` requires finite bounds and the range is specified as a two-tuple (min, max) or slice-object (min, max, brute_step). A slice-object is used directly, whereas a two-tuple is converted to a slice object that interpolates Ns points from min to max, inclusive.

In addition, the brute() method in lmfit, handles three other scenarios given below with their respective slice-object:

  • lower bound (min) and brute_step are specified:

    range = (min, min + Ns * brute_step, brute_step).

  • upper bound (max) and brute_step are specified:

    range = (max - Ns * brute_step, max, brute_step).

  • numerical value (value) and brute_step are specified:

    range = (value - (Ns//2) * brute_step, value + (Ns//2) * brute_step, brute_step).

dual_annealing(params=None, **kws)

Use the dual_annealing algorithm to find the global minimum.

This method calls :scipydoc:`optimize.dual_annealing` using its default arguments.

Parameters

paramsParameters, optional

Contains the Parameters for the model. If None, then the Parameters used to initialize the Minimizer object are used.

**kwsdict, optional

Minimizer options to pass to the dual_annealing algorithm.

Returns

MinimizerResult

Object containing the parameters from the dual_annealing method. The return values specific to :scipydoc:`optimize.dual_annealing` (x, fun, nfev, nhev, njev, and nit) are stored as da_<parname> attributes.

New in version 0.9.14.

emcee(params=None, steps=1000, nwalkers=100, burn=0, thin=1, ntemps=1, pos=None, reuse_sampler=False, workers=1, float_behavior='posterior', is_weighted=True, seed=None, progress=True, check_converge=True, nevery=1000)

Bayesian sampling of the posterior distribution using the emcee Markov Chain Monte Carlo package.

The method assumes that the prior is Uniform. You need to have emcee version 3 installed to use this method.

Parameters

paramsParameters, optional

Parameters to use as starting point. If this is not specified then the Parameters used to initialize the Minimizer object are used.

stepsint, optional

How many samples you would like to draw from the posterior distribution for each of the walkers?

nwalkersint, optional

Should be set so \(nwalkers >> nvarys\), where nvarys are the number of parameters being varied during the fit. ‘Walkers are the members of the ensemble. They are almost like separate Metropolis-Hastings chains but, of course, the proposal distribution for a given walker depends on the positions of all the other walkers in the ensemble.’ - from the emcee webpage.

burnint, optional

Discard this many samples from the start of the sampling regime.

thinint, optional

Only accept 1 in every thin samples.

ntempsint, deprecated

ntemps has no effect.

posnumpy.ndarray, optional

Specify the initial positions for the sampler, an ndarray of shape (nwalkers, nvarys). You can also initialise using a previous chain of the same nwalkers and nvarys. Note that nvarys may be one larger than you expect it to be if your userfcn returns an array and is_weighted is False.

reuse_samplerbool, optional

Set to True if you have already run emcee with the Minimizer instance and want to continue to draw from its sampler (and so retain the chain history). If False, a new sampler is created. The keywords nwalkers, pos, and params will be ignored when this is set, as they will be set by the existing sampler. Important: the Parameters used to create the sampler must not change in-between calls to emcee. Alteration of Parameters would include changed min, max, vary and expr attributes. This may happen, for example, if you use an altered Parameters object and call the minimize method in-between calls to emcee.

workersPool-like or int, optional

For parallelization of sampling. It can be any Pool-like object with a map method that follows the same calling sequence as the built-in map function. If int is given as the argument, then a multiprocessing-based pool is spawned internally with the corresponding number of parallel processes. ‘mpi4py’-based parallelization and ‘joblib’-based parallelization pools can also be used here. Note: because of multiprocessing overhead it may only be worth parallelising if the objective function is expensive to calculate, or if there are a large number of objective evaluations per step (nwalkers * nvarys).

float_behaviorstr, optional

Meaning of float (scalar) output of objective function. Use ‘posterior’ if it returns a log-posterior probability or ‘chi2’ if it returns \(\chi^2\). See Notes for further details.

is_weightedbool, optional

Has your objective function been weighted by measurement uncertainties? If is_weighted is True then your objective function is assumed to return residuals that have been divided by the true measurement uncertainty (data - model) / sigma. If is_weighted is False then the objective function is assumed to return unweighted residuals, data - model. In this case emcee will employ a positive measurement uncertainty during the sampling. This measurement uncertainty will be present in the output params and output chain with the name __lnsigma. A side effect of this is that you cannot use this parameter name yourself. Important this parameter only has any effect if your objective function returns an array. If your objective function returns a float, then this parameter is ignored. See Notes for more details.

seedint or numpy.random.RandomState, optional

If seed is an int, a new numpy.random.RandomState instance is used, seeded with seed. If seed is already a numpy.random.RandomState instance, then that numpy.random.RandomState instance is used. Specify seed for repeatable minimizations.

progressbool, optional

Print a progress bar to the console while running.

Returns

MinimizerResult

MinimizerResult object containing updated params, statistics, etc. The updated params represent the median of the samples, while the uncertainties are half the difference of the 15.87 and 84.13 percentiles. The MinimizerResult contains a few additional attributes: chain contain the samples and has shape ((steps - burn) // thin, nwalkers, nvarys). flatchain is a pandas.DataFrame of the flattened chain, that can be accessed with result.flatchain[parname]. lnprob contains the log probability for each sample in chain. The sample with the highest probability corresponds to the maximum likelihood estimate. acor is an array containing the autocorrelation time for each parameter if the autocorrelation time can be computed from the chain. Finally, acceptance_fraction (an array of the fraction of steps accepted for each walker).

Notes

This method samples the posterior distribution of the parameters using Markov Chain Monte Carlo. It calculates the log-posterior probability of the model parameters, F, given the data, D, \(\ln p(F_{true} | D)\). This ‘posterior probability’ is given by:

\[\ln p(F_{true} | D) \propto \ln p(D | F_{true}) + \ln p(F_{true})\]

where \(\ln p(D | F_{true})\) is the ‘log-likelihood’ and \(\ln p(F_{true})\) is the ‘log-prior’. The default log-prior encodes prior information known about the model that the log-prior probability is -numpy.inf (impossible) if any of the parameters is outside its limits, and is zero if all the parameters are inside their bounds (uniform prior). The log-likelihood function is 1:

\[\ln p(D|F_{true}) = -\frac{1}{2}\sum_n \left[\frac{(g_n(F_{true}) - D_n)^2}{s_n^2}+\ln (2\pi s_n^2)\right]\]

The first term represents the residual (\(g\) being the generative model, \(D_n\) the data and \(s_n\) the measurement uncertainty). This gives \(\chi^2\) when summed over all data points. The objective function may also return the log-posterior probability, \(\ln p(F_{true} | D)\). Since the default log-prior term is zero, the objective function can also just return the log-likelihood, unless you wish to create a non-uniform prior.

If the objective function returns a float value, this is assumed by default to be the log-posterior probability, (float_behavior default is ‘posterior’. If your objective function returns \(\chi^2\), then you should use a value of float_behavior=’chi2’.

By default objective functions may return an ndarray of (possibly weighted) residuals. In this case, use is_weighted to select whether these are correctly weighted by measurement uncertainty. Note that this ignores the second term above, so that to calculate a correct log-posterior probability value your objective function should return a float value. With is_weighted=False the data uncertainty, s_n, will be treated as a nuisance parameter to be marginalized out. This uses strictly positive uncertainty (homoscedasticity) for each data point, \(s_n = \exp(\rm{\_\_lnsigma})\). __lnsigma will be present in MinimizerResult.params, as well as Minimizer.chain and nvarys will be increased by one.

References

1

https://emcee.readthedocs.io

least_squares(params=None, **kws)

Least-squares minimization using :scipydoc:`optimize.least_squares`.

This method wraps :scipydoc:`optimize.least_squares`, which has inbuilt support for bounds and robust loss functions. By default it uses the Trust Region Reflective algorithm with a linear loss function (i.e., the standard least-squares problem).

Parameters

paramsParameters, optional

Parameters to use as starting point.

**kwsdict, optional

Minimizer options to pass to :scipydoc:`optimize.least_squares`.

Returns

MinimizerResult

Object containing the optimized parameter and several goodness-of-fit statistics.

Changed in version 0.9.0: Return value changed to MinimizerResult.

leastsq(params=None, **kws)

Use Levenberg-Marquardt minimization to perform a fit.

It assumes that the input Parameters have been initialized, and a function to minimize has been properly set up. When possible, this calculates the estimated uncertainties and variable correlations from the covariance matrix.

This method calls :scipydoc:`optimize.leastsq`. By default, numerical derivatives are used, and the following arguments are set:

leastsq() arg

Default Value

Description

xtol

1.e-7

Relative error in the approximate solution

ftol

1.e-7

Relative error in the desired sum of squares

maxfev

2000*(nvar+1)

Maximum number of function calls (nvar= # of variables)

Dfun

None

Function to call for Jacobian calculation

Parameters

paramsParameters, optional

Parameters to use as starting point.

**kwsdict, optional

Minimizer options to pass to :scipydoc:`optimize.leastsq`.

Returns

MinimizerResult

Object containing the optimized parameter and several goodness-of-fit statistics.

Changed in version 0.9.0: Return value changed to MinimizerResult.

minimize(method='leastsq', params=None, **kws)

Perform the minimization.

Parameters

methodstr, optional

Name of the fitting method to use. Valid values are:

  • ‘leastsq’: Levenberg-Marquardt (default)

  • ‘least_squares’: Least-Squares minimization, using Trust Region Reflective method

  • ‘differential_evolution’: differential evolution

  • ‘brute’: brute force method

  • ‘basinhopping’: basinhopping

  • ‘ampgo’: Adaptive Memory Programming for Global Optimization

  • nelder’: Nelder-Mead

  • ‘lbfgsb’: L-BFGS-B

  • ‘powell’: Powell

  • ‘cg’: Conjugate-Gradient

  • ‘newton’: Newton-CG

  • ‘cobyla’: Cobyla

  • ‘bfgs’: BFGS

  • ‘tnc’: Truncated Newton

  • ‘trust-ncg’: Newton-CG trust-region

  • ‘trust-exact’: nearly exact trust-region

  • ‘trust-krylov’: Newton GLTR trust-region

  • ‘trust-constr’: trust-region for constrained optimization

  • ‘dogleg’: Dog-leg trust-region

  • ‘slsqp’: Sequential Linear Squares Programming

  • ‘emcee’: Maximum likelihood via Monte-Carlo Markov Chain

  • ‘shgo’: Simplicial Homology Global Optimization

  • ‘dual_annealing’: Dual Annealing optimization

In most cases, these methods wrap and use the method with the same name from scipy.optimize, or use scipy.optimize.minimize with the same method argument. Thus ‘leastsq’ will use scipy.optimize.leastsq, while ‘powell’ will use scipy.optimize.minimizer(…, method=’powell’)

For more details on the fitting methods please refer to the SciPy docs.

paramsParameters, optional

Parameters of the model to use as starting values.

**kwsoptional

Additional arguments are passed to the underlying minimization method.

Returns

MinimizerResult

Object containing the optimized parameter and several goodness-of-fit statistics.

Changed in version 0.9.0: Return value changed to MinimizerResult.

penalty(fvars)

Penalty function for scalar minimizers.

Parameters

fvarsnumpy.ndarray

Array of values for the variable parameters.

Returns

rfloat

The evaluated user-supplied objective function.

If the objective function is an array of size greater than 1, use the scalar returned by self.reduce_fcn. This defaults to sum-of-squares, but can be replaced by other options.

prepare_fit(params=None)

Prepare parameters for fitting.

Prepares and initializes model and Parameters for subsequent fitting. This routine prepares the conversion of Parameters into fit variables, organizes parameter bounds, and parses, “compiles” and checks constrain expressions. The method also creates and returns a new instance of a MinimizerResult object that contains the copy of the Parameters that will actually be varied in the fit.

Parameters

paramsParameters, optional

Contains the Parameters for the model; if None, then the Parameters used to initialize the Minimizer object are used.

Returns

MinimizerResult

Notes

This method is called directly by the fitting methods, and it is generally not necessary to call this function explicitly.

Changed in version 0.9.0: Return value changed to MinimizerResult.

scalar_minimize(method='Nelder-Mead', params=None, **kws)

Scalar minimization using :scipydoc:`optimize.minimize`.

Perform fit with any of the scalar minimization algorithms supported by :scipydoc:`optimize.minimize`. Default argument values are:

scalar_minimize() arg

Default Value

Description

method

Nelder-Mead

fitting method

tol

1.e-7

fitting and parameter tolerance

hess

None

Hessian of objective function

Parameters

methodstr, optional

Name of the fitting method to use. One of:

  • ‘Nelder-Mead’ (default)

  • ‘L-BFGS-B’

  • ‘Powell’

  • ‘CG’

  • ‘Newton-CG’

  • ‘COBYLA’

  • ‘BFGS’

  • ‘TNC’

  • ‘trust-ncg’

  • ‘trust-exact’

  • ‘trust-krylov’

  • ‘trust-constr’

  • ‘dogleg’

  • ‘SLSQP’

  • ‘differential_evolution’

paramsParameters, optional

Parameters to use as starting point.

**kwsdict, optional

Minimizer options pass to :scipydoc:`optimize.minimize`.

Returns

MinimizerResult

Object containing the optimized parameter and several goodness-of-fit statistics.

Changed in version 0.9.0: Return value changed to MinimizerResult.

Notes

If the objective function returns a NumPy array instead of the expected scalar, the sum of squares of the array will be used.

Note that bounds and constraints can be set on Parameters for any of these methods, so are not supported separately for those designed to use bounds. However, if you use the differential_evolution method you must specify finite (min, max) for each varying Parameter.

shgo(params=None, **kws)

Use the SHGO algorithm to find the global minimum.

SHGO stands for “simplicial homology global optimization” and calls :scipydoc:`optimize.shgo` using its default arguments.

Parameters

paramsParameters, optional

Contains the Parameters for the model. If None, then the Parameters used to initialize the Minimizer object are used.

**kwsdict, optional

Minimizer options to pass to the SHGO algorithm.

Returns

MinimizerResult

Object containing the parameters from the SHGO method. The return values specific to :scipydoc:`optimize.shgo` (x, xl, fun, funl, nfev, nit, nlfev, nlhev, and nljev) are stored as shgo_<parname> attributes.

New in version 0.9.14.

unprepare_fit()

Clean fit state, so that subsequent fits need to call prepare_fit().

removes AST compilations of constraint expressions.

property values

Return Parameter values in a simple dictionary.

exception gsf.minimizer.MinimizerException(msg)

Bases: Exception

General Purpose Exception.

class gsf.minimizer.MinimizerResult(**kws)

Bases: object

The results of a minimization.

Minimization results include data such as status and error messages, fit statistics, and the updated (i.e., best-fit) parameters themselves in the params attribute.

The list of (possible) MinimizerResult attributes is given below:

Attributes

paramsParameters

The best-fit parameters resulting from the fit.

statusint

Termination status of the optimizer. Its value depends on the underlying solver. Refer to message for details.

var_nameslist

Ordered list of variable parameter names used in optimization, and useful for understanding the values in init_vals and covar.

covarnumpy.ndarray

Covariance matrix from minimization, with rows and columns corresponding to var_names.

init_valslist

List of initial values for variable parameters using var_names.

init_valuesdict

Dictionary of initial values for variable parameters.

nfevint

Number of function evaluations.

successbool

True if the fit succeeded, otherwise False.

errorbarsbool

True if uncertainties were estimated, otherwise False.

messagestr

Message about fit success.

ierint

Integer error value from :scipydoc:`optimize.leastsq` (leastsq only).

lmdif_messagestr

Message from :scipydoc:`optimize.leastsq` (leastsq only).

nvarysint

Number of variables in fit: \(N_{\rm varys}\).

ndataint

Number of data points: \(N\).

nfreeint

Degrees of freedom in fit: \(N - N_{\rm varys}\).

residualnumpy.ndarray

Residual array \({\rm Resid_i}\). Return value of the objective function when using the best-fit values of the parameters.

chisqrfloat

Chi-square: \(\chi^2 = \sum_i^N [{\rm Resid}_i]^2\).

redchifloat

Reduced chi-square: \(\chi^2_{\nu}= {\chi^2} / {(N - N_{\rm varys})}\).

aicfloat

Akaike Information Criterion statistic: \(N \ln(\chi^2/N) + 2 N_{\rm varys}\).

bicfloat

Bayesian Information Criterion statistic: \(N \ln(\chi^2/N) + \ln(N) N_{\rm varys}\).

flatchainpandas.DataFrame

A flatchain view of the sampling chain from the emcee method.

Methods

show_candidates

Pretty_print() representation of candidates from the brute method.

property flatchain

Show flatchain view of the sampling chain from emcee method.

show_candidates(candidate_nmb='all')

Show pretty_print() representation of candidates from brute method.

Showing all stored candidates (default) or the specified candidate-# from the brute method.

Parameters

candidate_nmbint or ‘all’

The candidate-number to show using the pretty_print() method.

gsf.minimizer.asteval_with_uncertainties(*vals, **kwargs)

Calculate object value, given values for variables.

This is used by the uncertainties package to calculate the uncertainty in an object even with a complicated expression.

gsf.minimizer.eval_stderr(obj, uvars, _names, _pars)

Evaluate uncertainty and set .stderr for a parameter obj.

Given the uncertain values uvars (a list of uncertainties.ufloats), a list of parameter names that matches uvars, and a dict of param objects, keyed by name.

This uses the uncertainties package wrapped function to evaluate the uncertainty for an arbitrary expression (in obj._expr_ast) of parameters.

gsf.minimizer.minimize(fcn, params, method='leastsq', args=None, kws=None, iter_cb=None, scale_covar=True, nan_policy='raise', reduce_fcn=None, calc_covar=True, **fit_kws)

Perform a fit of a set of parameters by minimizing an objective (or cost) function using one of the several available methods.

The minimize function takes an objective function to be minimized, a dictionary (Parameters) containing the model parameters, and several optional arguments.

Parameters

fcncallable

Objective function to be minimized. When method is leastsq or least_squares, the objective function should return an array of residuals (difference between model and data) to be minimized in a least-squares sense. With the scalar methods the objective function can either return the residuals array or a single scalar value. The function must have the signature: fcn(params, *args, **kws)

paramsParameters

Contains the Parameters for the model.

methodstr, optional

Name of the fitting method to use. Valid values are:

  • ‘leastsq’: Levenberg-Marquardt (default)

  • ‘least_squares’: Least-Squares minimization, using Trust Region Reflective method

  • ‘differential_evolution’: differential evolution

  • ‘brute’: brute force method

  • ‘basinhopping’: basinhopping

  • ‘ampgo’: Adaptive Memory Programming for Global Optimization

  • nelder’: Nelder-Mead

  • ‘lbfgsb’: L-BFGS-B

  • ‘powell’: Powell

  • ‘cg’: Conjugate-Gradient

  • ‘newton’: Newton-CG

  • ‘cobyla’: Cobyla

  • ‘bfgs’: BFGS

  • ‘tnc’: Truncated Newton

  • ‘trust-ncg’: Newton-CG trust-region

  • ‘trust-exact’: nearly exact trust-region

  • ‘trust-krylov’: Newton GLTR trust-region

  • ‘trust-constr’: trust-region for constrained optimization

  • ‘dogleg’: Dog-leg trust-region

  • ‘slsqp’: Sequential Linear Squares Programming

  • ‘emcee’: Maximum likelihood via Monte-Carlo Markov Chain

  • ‘shgo’: Simplicial Homology Global Optimization

  • ‘dual_annealing’: Dual Annealing optimization

In most cases, these methods wrap and use the method of the same name from scipy.optimize, or use scipy.optimize.minimize with the same method argument. Thus ‘leastsq’ will use scipy.optimize.leastsq, while ‘powell’ will use scipy.optimize.minimizer(…, method=’powell’)

For more details on the fitting methods please refer to the SciPy docs.

argstuple, optional

Positional arguments to pass to fcn.

kwsdict, optional

Keyword arguments to pass to fcn.

iter_cbcallable, optional

Function to be called at each fit iteration. This function should have the signature iter_cb(params, iter, resid, *args, **kws), where params will have the current parameter values, iter the iteration number, resid the current residual array, and *args and **kws as passed to the objective function.

scale_covarbool, optional

Whether to automatically scale the covariance matrix (default is True).

nan_policystr, optional

Specifies action if userfcn (or a Jacobian) returns NaN values. One of:

  • ‘raise’ : a ValueError is raised

  • ‘propagate’ : the values returned from userfcn are un-altered

  • ‘omit’ : non-finite values are filtered

reduce_fcnstr or callable, optional

Function to convert a residual array to a scalar value for the scalar minimizers. See notes in Minimizer.

calc_covarbool, optional

Whether to calculate the covariance matrix (default is True) for solvers other than leastsq and least_squares. Requires the numdifftools package to be installed.

**fit_kwsdict, optional

Options to pass to the minimizer being used.

Returns

MinimizerResult

Object containing the optimized parameter and several goodness-of-fit statistics.

Changed in version 0.9.0: Return value changed to MinimizerResult.

Notes

The objective function should return the value to be minimized. For the Levenberg-Marquardt algorithm from leastsq(), this returned value must be an array, with a length greater than or equal to the number of fitting variables in the model. For the other methods, the return value can either be a scalar or an array. If an array is returned, the sum of squares of the array will be sent to the underlying fitting method, effectively doing a least-squares optimization of the return values.

A common use for args and kws would be to pass in other data needed to calculate the residual, including such things as the data array, dependent variable, uncertainties in the data, and other data structures for the model calculation.

On output, params will be unchanged. The best-fit values and, where appropriate, estimated uncertainties and correlations, will all be contained in the returned MinimizerResult. See fit-results-label for further details.

This function is simply a wrapper around Minimizer and is equivalent to:

fitter = Minimizer(fcn, params, fcn_args=args, fcn_kws=kws,
                   iter_cb=iter_cb, scale_covar=scale_covar,
                   nan_policy=nan_policy, reduce_fcn=reduce_fcn,
                   calc_covar=calc_covar, **fit_kws)
fitter.minimize(method=method)
gsf.minimizer.reduce_cauchylogpdf(r)

Reduce residual array to scalar (cauchylogpdf).

Reduce residual array r to scalar using negative log-likelihood and a Cauchy (Lorentzian) distribution of r:

-scipy.stats.cauchy.logpdf(r)

(where the Cauchy pdf = 1/(pi*(1+r*r))). This gives greater suppression of outliers compared to normal sum-of-squares.

Parameters

rnumpy.ndarray

Residual array.

Returns

float

Negative entropy value calculated from the residual array

gsf.minimizer.reduce_chisquare(r)

Reduce residual array to scalar (chi-square).

Calculate the chi-square value from the residual array r: (r*r).sum()

Parameters

rnumpy.ndarray

Residual array.

Returns

float

Chi-square calculated from the residual array

gsf.minimizer.reduce_negentropy(r)

Reduce residual array to scalar (negentropy).

Reduce residual array r to scalar using negative entropy and the normal (Gaussian) probability distribution of r as pdf:

(norm.pdf(r)*norm.logpdf(r)).sum()

since pdf(r) = exp(-r*r/2)/sqrt(2*pi), this is

((r*r/2 - log(sqrt(2*pi))) * exp(-r*r/2)).sum()

Parameters

rnumpy.ndarray

Residual array.

Returns

float

Negative entropy value calculated from the residual array

gsf.plot_MZ module

gsf.plot_sed_logA module

gsf.plot_sfh_logA module

gsf.posterior_flexible module

class gsf.posterior_flexible.Post(mainbody)

Bases: object

Class function for MCMC

func_tmp(xint, eobs, fmodel)

A function used for chi2 calculation for non-detection in lnprob.

get_lognormal_prior(vals, key_param, mu=0, sigma=100.0)
get_sfh_prior(vals, norder=3, alpha=100.0)

Fit SFH with an n-order polynomial and reflect the residual to the prior. Fit should be done in log-log space.

lnprob_emcee(pos, pars, fy: float, ey: float, wht: float, NR: float, f_fir: bool, f_chind: bool = True, SNlim: float = 1.0, f_scale: bool = False, lnpreject=-inf, f_like: bool = False, flat_prior: bool = False, gauss_prior: bool = True, f_val: bool = True, nsigma: float = 1.0, out=None, f_prior_sfh=False, alpha_sfh_prior=100, norder_sfh_prior=3, verbose=False, NRbb_lim=10000)

Parameters

f_chindbool

If true, includes non-detection in likelihood calculation.

lnpreject

A replaced value when lnprob gets -inf value.

flat_prior

Assumes flat prior for Mdyn. Used only when MB.f_Mdyn==True.

gauss_prior

Assumes gaussian prior for Mdyn. Used only when MB.f_Mdyn==True.

pos

This is a critical parameter, to make use of EMCEE, while keeping pars a dictionary obtained by lmfit. This is pos of sampler.run_mcmc(pos, self.nmc, progress=True).

out

Just for keywords.

Returns:

If f_like, log Likelihood. Else, log Posterior prob.

residual(pars, fy: float, ey: float, wht: float, f_fir: bool, out: bool = False, f_val: bool = False, f_penlize: bool = True, f_only_spec: bool = False, verbose=False)

Parameters

out

model as second output. For lnprob func.

f_firbool

If dust component is on or off.

Returns

residual of model and data.

swap_pars(pars)
swap_pars_inv(pars)

gsf.posterior_nested module

class gsf.posterior_nested.Post_nested(mainbody, params=None)

Bases: object

# Function for MCMC

func_tmp(xint, eobs, fmodel)

A function used for chi2 calculation for non-detection in lnprob.

get_dict(pars)
lnlike(pars, fy, ey, wht, f_fir, f_chind=True, SNlim=1.0, lnpreject=-inf)

Returns

log likelihood

Note:

This is a copy from lnprob, with respr=0.

lnprob(pars, fy, ey, wht, f_fir, f_chind=True, SNlim=1.0, lnpreject=-inf)

Returns:

log posterior

prior_transform(pars)

A function defining the tranform between the parameterisation in the unit hypercube to the true parameters.

Args:

theta (tuple): a tuple containing the parameters.

Returns:

tuple: a new tuple or array with the transformed parameters.

residual(pars, fy, ey, wht, f_fir=False, out=False)

Parameters

out : model as second output. For lnprob func. f_fir : Bool. If dust component is on or off.

Returns

residual of model and data.

residual_nest(pars, fy, ey, wht, f_fir=False, out=False)

Parameters

out : model as second output. For lnprob func. f_fir : Bool. If dust component is on or off.

Returns

residual of model and data.

gsf.version module

gsf.writing module

gsf.writing.get_index(mmax=300)

Purpose

Retrieve spectral indices from each realization.

gsf.writing.get_param(self, res, fitc, tcalc=1.0, burnin=-1)

Purpose

Write a parameter file.

gsf.zfit module

gsf.zfit.check_redshift(fobs, eobs, xobs, fm_tmp, xm_tmp, zbest, zprior, prior, NR, data_len, zliml, zlimu, nmc_cz=100, nwalk_cz=10, nthin=5, f_line_check=False, f_vary=True, NRbb_lim=10000, include_photometry=True)

Fit observed flux with a template to get redshift probability.

Parameters

zbest

Initial value for redshift.

zprior

Redshift grid for prior.

prior

Prior for redshift determination. E.g., Eazy z-probability.

zliml

Lowest redshift for fitting range.

zlimu

Highest redshift for fitting range.

f_varybool

If want to fix redshift.

fm_tmp :

Template spectrum at RF.

xm_tmp :

Template spectrum at RF.

fobs

Observed spectrum. (Already scaled with Cz0prev.)

eobs

Observed spectrum. (Already scaled with Cz0prev.)

xobs

Observed spectrum. (Already scaled with Cz0prev.)

Returns

res_cz :

fitc_cz :

gsf.zfit.get_chi2(zz_prob, fy_cz, ey_cz, x_cz, fm_tmp, xm_tmp, file_zprob, rms_lim=10000.0)

Parameters

zz_probfloat array

redshift array for fit.

fy_cz, ey_cz, x_cz

observed values.

fm_tmp, xm_tmp :

template.

file_zprobstr

output file

gsf.zfit.lnprob_cz(pars, zprior, prior, zliml, zlimu, args, kwargs)

@@@ For now, prior is not in use;

gsf.zfit.residual_z(pars, xm_tmp, fm_tmp, xobs, fobs, eobs, NR, data_len, NRbb_lim=10000, include_photometry=True, f_line_check=False)

Module contents