User modules
q3dfit
- q3dfit.q3df.q3dfit(q3din, cols=None, rows=None, onefit=False, ncores=1, quiet=True, mpipath=None, nocrash=False)[source]
This is the core routine to fit the continuum and emission lines of a spectrum. For single-threaded processing, the routine calls
q3df_oneCore. For multi-threaded processing, the routine runs :py:mod:`~q3dfit.q3df_helperFunctions as a script through MPI. This in turn callsq3df_multiCore.- Parameters:
q3din (
str|q3din) – Either a string with the path to the numpy save file containing the input initialization objectq3din, or the object itself.cols (
Union[int,list,None]) – Optional. Column values for spaxels to be fitted. Default is None, which means all columns will be fitted. If a scalar, only that column will be fitted. If a 2-element list, the elements are the starting and ending columns to be fitted. Unity-offset values assumed.rows (
Union[int,list,None]) – Optional. Row values for spaxels to be fitted. Default is None, which means all rows will be fitted. If a scalar, only that row will be fitted. If a 2-element list, the elements are the starting and ending rows to be fitted. Unity-offset values assumed.onefit (
bool) – Optional. If set, only one fit is performed infitloop. Default is False.ncores (
int) – Optional. Number of cores for parallel processing. Default is 1.quiet (
bool) – Optional. If False, some progress messages are written to stdout. Default is True. If a logfile is specified inq3din, these messages are written to the logfile as well. Some messages appear only in the logfile.mpipath (
Optional[str]) – Optional. Path to the MPI executable. Default is None.nocrash (
bool) – Optional. If set, the routine will continue with the next spaxel in case of a crash. Default is False.
contfit
Continuum fitting routines and subroutines.
- q3dfit.contfit.fitpoly(wave, flux, weight, index, logfile=None, quiet=True, fitord=3, refit=None)[source]
Fit the continuum as a polynomial.
- Parameters:
wave (
ndarray) – Wavelengthsflux (
ndarray) – Fluxesweight (
ndarray) – Weightsindex (
ndarray) – Points used in the fit.logfile (
Optional[str]) – Optional. Name of the log file. Default is None.quiet (
bool) – Optional. Suppress output to stdout? Default is True.fitord (
int) – Optional. Order of the polynomial. Default is 3.refit (
Optional[dict[str, ArrayLike]]) – Optional. Refit with a different polynomial order? If so, set to dictionary with keys ‘ord’ and ‘ran’ for the order and range of the refit, respectively. Can specify multiple ranges and orders as array_like. Default is None.
- Return type:
- Returns:
np.ndarray – best fit continuum model
dict[str, ArrayLike] – Dictionary with single key-value pair, ‘poly’ and the polynomial coefficients.
None – Unused
None – Unused
- q3dfit.contfit.fitqsohost(wave, flux, weight, index, logfile=None, quiet=True, refit=None, template_wave=None, template_flux=None, zstar=None, flux_log=None, err_log=None, index_log=None, siginit_stars=50.0, add_poly_degree=30, mult_poly_degree=0, av_star=None, fitran=None, qsoord=None, hostord=None, blrpar=None, qsoonly=False, hostonly=False, blronly=False, fluxunit=None, waveunit=None, *, qsoxdr, **kwargs)[source]
Fit the continuum using a quasar template and a stellar template. Calls
qsohostfcn()to jointly fit the quasar and host galaxy components. Callsppxf()orquestfit()to refit the residual after subtracting the quasar component.Additional keywords can be passed to
fit()by passing them as keyword arguments to this function. Arguments to theoptimizefunctions can be passed by setting the keyword argument argslmfit to a dictionary of parameter names and values as keys and values. Arguments toquestfit()for the refit can be passed by setting the keyword argument args_questfit to a dictionary of parameter names and values as keys and values.- Parameters:
wave (
ndarray) – Wavelengthsflux (
ndarray) – Fluxesweight (
ndarray) – Weightsindex (
ndarray) – Points used in the fit.logfile (
Optional[str]) – Optional. Name of the log file. Default is None.quiet (
bool) – Optional. Suppress output to stdout? Default is True.fitran (
Optional[ArrayLike]) – Optional. Wavelength range to fit. Default is None, to fit all wavelengths.qsoord (
Optional[int]) – Optional. Order of the polynomial added to the quasar multiplier. Default is None.hostord (
Optional[int]) – Optional. Order of the polynomial model for the host galaxy. Default is None.blrpar (
Optional[ArrayLike]) – Optional. Parameters of the broad line region scattering model. If set, fit this part of the model. Set to array_like Default is None.qsoonly (
bool) – Optional. Fit only the quasar template. Default is False.hostonly (
bool) – Optional. Fit only the host galaxy. Default is False.blronly (
bool) – Optional. Fit only the broad line region scattering model. Default is False.refit (
Optional[str]) – Optional. Refit the continuum residual after subtracting the quasar. Options are ‘ppxf’ or ‘questfit’. Default is None, which means no refit.template_wave (
Optional[ndarray]) – Optional, but must be set if refit=’ppxf’. Wavelength array of the stellar template used as model for stellar continuum.template_flux (
Optional[ndarray]) – Optional, but must be set if refit=’ppxf’. Flux array of the stellar template used as model for stellar continuum.zstar (
Optional[float]) – Optional, but must be set if refit=’ppxf’. Input guess for redshift of the stellar continuum. Default is None.flux_log (
Optional[ndarray]) – Optional, but must be set if refit=’ppxf’. Flux values for the log-rebinned pixels.err_log (
Optional[ndarray]) – Optional, but must be set if refit=’ppxf’. Error values for the log-rebinned pixels.index_log (
Optional[ndarray]) – Optional, but must be set if refit=’ppxf’. Pixels used in the fit for the pPXF fit, as log-rebinned.siginit_stars (
float) – Optional. Initial guess for the stellar velocity dispersion in km/s, used in the pPXF fit. Default is 50. km/s.add_poly_degree (
int) – Optional. Degree of the additive polynomial for the pPXF fit. Default is 30.mult_poly_degree (
int) – Optional. Degree of the multiplicative polynomial for the pPXF fit. Default is 0.av_star (
Optional[float]) – Optional. Initial guess for stellar reddening, used in the pPXF fit. Default is None, which means no reddening is applied.qsoxdr (
str) – Path and filename for the quasar template.fluxunit (
Optional[str]) – Optional. Units of the flux, as defined byCube. Default is None. Passed toquestfit()if refit=’questfit’.waveunit (
Optional[Literal['micron','Angstrom']]) – Optional. Units of the wavelength, as defined byCube. Default is None.
- Return type:
tuple[ndarray,dict[str,Any],Optional[float],Optional[float]]- Returns:
numpy.ndarray – Best fit continuum model.
dict[str, Any] – Best fit parameters. It contains a the key ‘qso_host’, which contains the parameters as a
Parametersobject. If refit is also set to True inq3din(), then it also contains the key ‘ppxf’, which contains the best fit parameters from the pPXF fit as another dictionary with keys ‘stelmod’, ‘polymod’, ‘stelweights’, ‘polyweights’, ‘sigma’, ‘sigma_err’, and ‘av’. If refit is set to ‘questfit’, it will contain the best fit parameters with keys set by thequestfit()function.Optional[float] – Best fit stellar redshift if refit=’ppxf’. Otherwise, the input redshift or None if not set.
Optional[float] – Best fit stellar redshift error if refit=’ppxf’. Otherwise, None.
- q3dfit.contfit.questfit(wave, flux, weight, index, logfile=None, quiet=True, z=None, fluxunit=None, tempdir=None, *, config_file, **kwargs)[source]
Fit the MIR continuum. Calls
questfitfcn()to fit the continuum using the templates specified in the configuration file.- Parameters:
wave (
ndarray) – Wavelengthsflux (
ndarray) – Fluxesweight (
ndarray) – Weightsindex (
ndarray) – Points used in the fit.quiet (
bool) – Optional. Suppress output? Default is True.z (
Optional[float]) – Optional. Redshift of the source, for redshifting the templates. Default is None.fluxunit (
Optional[str]) – Optional. Units of the flux, as defined byCube. Default is None. The templates are assumed to be in f_nu. If this unit contains ‘micron’ or ‘Angstrom’, the flux is assumed to be in f_lambda. The templates are then converted to f_lambda. If None, the templates are not converted.tempdir (
Optional[str]) – Optional. Directory containing the templates, to search if default directory does not contain template. Default is None.config_file (
str) – Configuration file for the fit.
- Return type:
tuple[ndarray,dict[str,Any],Optional[float],Optional[float]]- Returns:
numpy.ndarray – Best fit continuum model.
dict[str, Any] – Best fit parameters. Key ‘MIRparams’ is a
Parametersobject containing the best fit parameters. Key ‘comp_best_fit’ is a dictionary containing with key/value pairs of the component names and their values evaluated at the best fit parameters.Optional[float] – Input redshift, if set. Otherwise, None.
Optional[float] – None, as the redshift error is not calculated in this function.
- q3dfit.contfit.linfit_plus_FeII(lam, flux, weight, index, logfile=None, quiet=True, specConv=None, Fe_z=0.0, Fe_FWHM_opt=None, Fe_FWHM_uv=None, tempdir=None, **kwargs)[source]
Fit the continuum as a superposition of a linear fit and an FeII template. Optical FeII template taken from Vestergaard & Wilkes (2001). UV FeII template follows the PyQSOFit code (Guo et al. 2018) which uses the template by Shen et al. (2019). Which is in turn a composite of VW01, Tsuzuki et al. (2006) and Salviander et al. (2007). The UV and optical FeII templates are scaled up/down separately from each other.
- Parameters:
lam (
ndarray) – Wavelengthsflux (
ndarray) – Fluxesweight (
ndarray) – Weightsindex (
ndarray) – Points used in the fit.logfile (
Optional[str]) – Optional. Name of the log file. Default is None.quiet (
bool) – Optional. Suppress output to stdout? Default is True.specConv (
Optional[<module ‘q3dfit.spectConvol’ from ‘/home/docs/checkouts/readthedocs.org/user_builds/q3dfit/checkouts/latest/q3dfit/spectConvol.py’>]) – Optional. Spectral resolution object. If set to None, no convolution will be performed. The default is None.Fe_z (
float) – Optional. Redshift of the FeII template. Default is 0.Fe_FWHM_opt (
Optional[float]) – Optional. The smoothing kernel of the optical FeII template, in km/s. Default is None, which means no smoothing.Fe_FWHM_uv (
Optional[float]) – Optional. The smoothing kernel of the optical FeII template, in km/s. Default is None, which means no smoothing.tempdir (
Optional[str]) – Optional. Directory containing the templates, to search if default directory does not contain template. Default is None.
- Returns:
numpy.ndarray – Best fit continuum model.
dict[str, Any] – Best fit parameters.
- q3dfit.contfit.Fe_template_vw01(filename, Fe_z=None, Fe_FWHM=None, specConv=None, wavecen=None, tempdir=None)[source]
Load the Vestergaard & Wilkes 2001 FeII template; redshift it; convolve it with intrinsic broadening; and convolve it with the instrumental resolution.
- Parameters:
filename (
str) – Name of the FeII template file.Fe_z (
Optional[float]) – Optional. Redshift to apply to the FeII template. Default is None, which means no redshift is applied.Fe_FWHM (
Optional[float]) – Optional. The Gaussian smoothing kernel for the FeII template in km/s. Default is None, which means no smoothing is applied.specConv (
Optional[object]) – Optional. Instance ofspectConvolspecifying the instrumental spectral resolution convolution. Default is None, which means no convolution is applied.wavecen (
Optional[float]) – Optional. Central wavelength for creating specConv instance, to find proper gratings. Default is None, which means no convolution is applied.tempdir (
Optional[str]) – Optional. Directory containing the templates, to search if default directory does not contain template. Default is None.
- Return type:
- Returns:
np.ndarray – Flux array of the FeII template.
np.ndarray – Wavelength array of the FeII template.
lineutil
- q3dfit.lineutil.jwstlinez(z, gal, instrument, mode, grat_filt, waveunit='micron', outdir=None)[source]
Creates a table of emission lines expected to be found in a given instrument configuration for JWST. The ‘observed’ column displays a redshifted emission line center calculated using the input z value. Therefore, it is only as precise as the known z value.
References stored under q3dfit/data/linelists are .tbl of filenames:
lines_H2.tbl lines_DSNR_micron.tbl lines_TSB.tbl lines_ref.tbl lines_PAH.tbl
Data for instrument configurations in microns can be found in q3dfit/data/jwst_tables in the files:
miri.tbl nirspec.tbl
String inputs are not case sensitive, but must be entered with exact spelling. Otherwise, the function will return errors.
- Parameters:
z (
float) – Galaxy, systemic redshift. Used for redshifting emission lines for ‘observed’ column.gal (
str) – Galaxy name for filenaming. Can also be customized for any other desired filename designationsinstrument (
Literal['NIRSpec','MIRI']) – JWST instrument. Inputs: NIRSpec, MIRI Used to grab the right table for each instrument.mode (
str) – Instrument mode. NIRSpec Inputs: IFU, MOS, FSs, BOTS MIRI Inputs: MRSgrat_filt (
str) – Grating and filter combination for NIRSpec or channel for MIRI. NIRSpec Inputs: G140M_F0701P, G140M_F1001P, G235M_F1701P, G395M_F2901P, G140H_F0701P, G140H_F1001P, G235H_F1701P, G395H_F2901P, Prism_Clear MIRI Inputs: Ch1_A, Ch1_B, Ch1_C, Ch2_A, Ch2_B, Ch2_C, Ch3_A, Ch3_B, Ch3_C, Ch4_A, Ch4_B, Ch4_Cwaveunit (
Literal['micron','Angstrom']) – Optional. Determines the unit of input wavelengths and output table. Inputs are ‘micron’ or ‘Angstrom’. Default is ‘micron’.outdir (
Optional[str]) – Optional. Output directory. Default is None, meaning no output file is saved.
- Return type:
- Returns:
Table – An astropy table of emission lines with keywords ‘name’, ‘lines’, ‘linelab’, ‘observed’. Example Row: H2_43_Q6, 2.98412, H$_2$(4-3) Q(6), 4.282212 Internally, everything is processed in microns, so filename inclues range values in microns. The units of the table can be Angstroms or microns, depending on the entered value of waveunit. Output table contains comments descring data sources
- q3dfit.lineutil.observedlinez(z, gal, lamb_min, lamb_max, vacuum=True, waveunit='micron', outdir=None)[source]
Similar to jwstline(), observedlinez() produces a table with emission lines in the provided range. Unlike jwstline(), this function can solve for a user-specified range of wavelengths and can account for air wavelength conversions. The column ‘observed’ accounts for both redshifting and air refraction. It reports an expected center for an emission distribution and can be used to identify unknown emission lines for fitting.
All input wavelengths are assumed to be REDSHIFTED!
References stored under q3dfit/data/linelists are .tbl of filenames:
lines_H2.tbl lines_DSNR_micron.tbl lines_TSB.tbl lines_ref.tbl lines_PAH.tbl
More tables can be added manually if saved in the linelists folder and called in this function definition.
- Parameters:
z (
float) – Galaxy redshiftgal (
str) – Galaxy name for filenaming. Can also be customized for any other desired filename designationslamb_min (
float) – minimum <OBSERVED> wavelength value of instrument, units determined by waveunit valuelamb_max (
float) – maximum <OBSERVED> wavelength of instrument, units determined by waveunit valuevacuum (
bool) – Optional. If false, enables conversion to air wavelengths. Default is True, meaning all wavelengths are in vacuum.waveunit (
Literal['micron','Angstrom']) – Optional. Determines the unit of input wavelengths and output table. Inputs are ‘micron’ or ‘Angstrom’. Default is ‘micron’.outdir (
Optional[str]) – Optional. Output directory. Default is None, meaning no output file is saved.
- Return type:
- Returns:
Table – An astropy table of emission lines with keywords ‘name’, ‘lines’, ‘linelab’, ‘observed’ Example Row: H2_43_Q6, 2.98412, H$_2$(4-3) Q(6), 4.282212 Interanlly, everything is processed in microns, so filename inclues range values in microns. The units of the table can be Angstroms or microns, depending on the entered value of waveunit.
Output table contains comments descring data sources
- q3dfit.lineutil.restline(gal, lamb_min, lamb_max, waveunit='micron', outdir=None)[source]
Similar to jwstlinez() and observedlinez(), restline() produces a table with emission lines in the provided range. Unlike the other 2 linelist functions, this function has REST wavelength lamb_min and lamb_max inputs. This function is useful for identifying various emissions in a rest spectrum for fitting and analysis. In this way, the funtion operates a lot like a search function.
All input wavelengths are assumed to be in the REST FRAME!
References stored under q3dfit/linelists are .tbl of filenames:
lines_H2.tbl lines_DSNR_micron.tbl lines_TSB.tbl lines_ref.tbl
More tables can be added manually if saved in the linelists folder and called in this function definition.
- Parameters:
gal (
str) – Galaxy name for filenaming. Can also be customized for any other desired filename designationslamb_min (
float) –- minimum <REST> wavelength value of instrument, units determined by
waveunit value
lamb_max (
float) – maximum <REST> wavelength of instrument, units determined by waveunit valuewaveunit (
Literal['micron','Angstrom']) – Optional. Determines the unit of input wavelengths and output table. Inputs are ‘micron’ or ‘Angstrom’. Default is ‘micron’.outdir (
Optional[str]) – Optional. Output directory. Default is None, meaning no output file is saved.
- Return type:
- Returns:
Table – An astropy table of emission lines with keywords ‘name’, ‘lines’, ‘linelab’ Example Row: H2_43_Q6, 2.98412, H$_2$(4-3) Q(6), 4.282212 Interanlly, everything is processed in microns, so filename inclues range values in microns. The units of the table can be Angstroms or microns, depending on the entered value of waveunit. Output table contains comments descring data sources
q3dcollect
- q3dfit.q3dcollect.q3dcollect(q3di, cols=None, rows=None, quiet=True, compsortpar='sigma', compsortdir='up', ignoreres=False)[source]
Collate spaxel information together. As input, it requires a
q3doutobjects output by the fit.Nothing is returned, but the result is saved to the location
label.line.npz andlabel.cont.npy. Thelabel.line.npz file contains the following dictionaries: emlwav, emlwaverr, emlsig, emlsigerr, emlflx, emlflxerr, emlweq, and emlncomp; and the values ncols, nrows. Thelabel.cont.npy file contains the contcube dictionary.- Parameters:
cols (
Union[int,list,None]) – Optional. Column values for spaxels to be collated. Default is None, which means all columns will be collated. If a scalar, only that column will be collated. If a 2-element list, the elements are the starting and ending columns to be collated. Unity-offset values assumed.rows (
Union[int,list,None]) – Optional. Column values for spaxels to be collated. Default is None, which means all columns will be collated. If a scalar, only that column will be collated. If a 2-element list, the elements are the starting and ending columns to be collated. Unity-offset values assumed.quiet (
bool) – Optional. If True, suppresses output to stdout. Default is True.compsortpar (
Literal['flux','sigma','wave']) – Optional. Parameter by which to sort components. Options are ‘sigma’, ‘flux’, ‘wave’. Default is ‘sigma’.compsortdir (
Literal['down','up']) – Optional. Direction in which to sort components. Options are ‘up’ and ‘down’. Default is ‘up’.ignoreres (
bool) – Optional. Parameter passed tosepfitpars(). If True, ignore spectral resolution in computing observed sigmas and peak fluxes. This is mainly for backward compatibility with old versions, which did not store the spectral resolution in an easily accessible way in the specConv object. Default is False.
templates
- q3dfit.templates.read_bpass(infile, outfile, waverange=[1.0, 100000.0], binary=False, zs=[0.001, 0.002, 0.003, 0.004, 0.006, 0.008, 0.01, 0.014, 0.02, 0.03, 0.04])[source]
Read the BPASS templates into a dictionary. Templates located here: https://bpass.auckland.ac.nz/14.html. Download the gzipped tarball of the desired version and alpha-enhancement. Unpack it into a directory, and pass the path to the directory to this function.
From p 14 of the v2.3 manual: These files contain the primary output of BPASS, which is the stellar spectral energy distribution (SED). Flux values are given every 1 Angstrom in the range 1 - 100,000 A. Most users will wish to resample to lower resolution, depending on their use case. We caution that some of the stellar atmospheres we use also have slightly lower spectral resolution. Each file has 52 columns and 105 rows. The first column lists a wavelength in angstroms, and each remaining column n (n>1) holds the model flux for the population at an age of 10^(6+0.1*(n-2)) years at that wavelength. The units of flux are Solar Luminosities per Angstrom, normalised for a cluster of 1e6 Msun formed in a single instantaneous burst. The total luminosity of the SED can be simply calculated by summing all the rows together. Or the flux over the wavelength range from, for example, 2000 to 3000 Angstroms can be calculated by summing the 2000th to 3000th rows.
- Parameters:
infile (
str) – The path to the BPASS template files.outfile (
str) – The path to the output file where the numpy save file will be written. Should have a .npy extension.waverange (ArrayLike) – Optional. The wavelength range to use for the templates, expressed in Angstroms. Defaults to [1., 100000.].
binary (
bool) – Optional. If True, the models with binary star evolution will be used. Defaults to False.zs (ArrayLike) – Optional. The metallicities to include. The options are [0.001,0.002,0.003,0.004,0.006,0.008,0.010,0.014,0.020,0.030,0.040]. Defaults to all metallicities.
- Return type:
Classes
- class q3dfit.readcube.Cube(infile, datext=1, varext=2, dqext=3, wmapext=4, wavext=None, zerodq=False, error=False, invvar=False, fluxnorm=1.0, fluxunit_in='MJy/sr', fluxunit_out='erg/s/cm2/micron/sr', usebunit=False, pixarea_sqas=None, waveunit_in='micron', waveunit_out='micron', usecunit=False, quiet=False, logfile=None)[source]
Bases:
objectRead in and contain a data cube and associated information.
- Parameters:
infile (
str) – Name of input FITS file.datext (
int) – Optional. Extension number of data. Defaults to 1.varext (
int) – Optional. Extension number of variance. Defaults to 2.dqext (
Optional[int]) – Optional. Extension number of data quality. Defaults to 3. If DQ extension is not present, set to None. This will set all DQ values to 0.wmapext (
Optional[int]) – Optional. Extension number of weight. Defaults to 4. If weight extension is not present, set to None.wavext (
Optional[int]) – Optional. Extension number of wavelength data. Defaults to None.zerodq (
bool) – Optional. Zero out the DQ array. Default is False. Even if dqext is present, this will set all DQ values to 0.error (
bool) – Optional. If the variance extension contains errors rather than variance, set to True. Defaults to False.invvar (
bool) – Optional. If the variance extension contains inverse variance rather than variance, set to True. Defaults to False.fluxnorm (
float) – Optional. Factor by which to divide the data. Defaults to 1.fluxunit_in (
str) – Optional. Flux unit of input data cube. Default is MJy/sr (JWST default). Must be parseable byunits.fluxunit_out (
str) – Optional. Flux unit carried by object. Default is erg/s/cm2/micron/sr. Must be parseable byunits.usebunit (
bool) – Optional. If BUNIT and fluxunit_in differ, default to BUNIT. Default is False.pixarea_sqas (
Optional[float]) – Optional. Spaxel area in square arcseconds. If present and flux units are per sr or per square arcseconds, will convert surface brightness units to flux per spaxel. Default is None. If set to None and header contains PIXAR_A2, routine will use that value.waveunit_in (
str) – Optional. Wavelength unit of input data cube. Default is micron.waveunit_out (
str) – Optional. Wavelength unit carried by object. Default is micron.usecunit (
bool) – Optional. If CUNIT and waveunit_in differ, default to CUNIT. Default is False.logfile (
Optional[str]) – Optional. Filename for progress messages. Default is None.quiet (
bool) – Optional. Send progress messages to stdout. Default is False.
- Variables:
dat (numpy.ndarray) – Data array (ncols, nrows, nwave).
var (numpy.ndarray) – Variance array (ncols, nrows, nwave).
err (numpy.ndarray) – Error array (ncols, nrows, nwave). Recorded as nan when the variance is negative.
dq (numpy.ndarray) – Data quality array (ncols, nrows, nwave).
wmap (numpy.ndarray) – Weight (1/variance) array (ncols, nrows, nwave). If wmap extension is not present, set to None.
wave (numpy.ndarray) – Wavelength array (nwave).
cdelt (float) – Constant dispersion. If a wavelength extension is present, this is the difference between the first two wavelengths.
crpix (int) – WCS pixel zero point, in unity-offset coordinates. If a wavelength extension is present, this is the first pixel (i.e., 1).
crval (float) – WCS wavelength zero point. If a wavelength extension is present, this is the first wavelength.
header_phu (astropy.io.fits.Header) – Primary header data unit.
header_dat (astropy.io.fits.Header) – Header for the data extension.
header_var (astropy.io.fits.Header) – Header for the variance extension.
header_dq (astropy.io.fits.Header) – Optional. Header for the data quality extension. If dq extension is not present, set to None.
header_wmap (astropy.io.fits.Header) – Optional. Header for the wmap extension. If wmap extension is not present, set to None.
cubedim (int) – Number of dimensions of the “cube” (1, 2, or 3).
ncols (int) – Number of columns. If the data are 1D, this is 1. If the data are 2D, this is the number of spectra.
nrows (int) – Number of rows. If the data are 1D or 2D, this is 1.
nwave (int) – Number of wavelength elements.
Examples
>>> from q3dfit import readcube >>> cube = readcube.Cube('infile.fits') >>> cube.convolve(2.5) >>> cube.writefits('outfile.fits')
- convolve(refsize, wavescale=False, method='circle')[source]
Spatially smooth a cube. Updates the data, variance, and error attributes.
- makeqsotemplate(outpy, col=None, row=None, norm=1.0, plot=True, radius=1.0)[source]
Extract the quasar spectrum and save it to a numpy file.
- Parameters:
outpy (
str) – Name of the numpy save file for the resulting qso spectrum.col (
Optional[int]) – Optional. x value of aperture center, in unity-offset coordinates. Default is None, in which case the cube is median- collapsed in wavelength and the peak spaxel is used.row (
Optional[int]) – Optional.yx value of aperture center, in unity-offset coordinates. Default is None, in which case the cube is median- collapsed in wavelength and the peak spaxel is used.norm (
float) – Optional. Factor by which to divide output spectrum. Default is 1.plot (
bool) – Optional. Plot extracted spectrum. Default is True.radius (
float) – Optional. Radius for circular extraction. Must be > 0. Default is 1.
- specextract(col, row, radius=1.0, norm=1.0, plot=True, medfilt=None, ylim=None)[source]
Extract a spectrum in a single spaxel or a circular aperture.
- Parameters:
col (
float) – x value of aperture center, in unity-offset coordinates.row (
float) – y value of aperture center, in unity-offset coordinates.radius (
float) – Optional. Radius for circular extraction. If 0, extract single spaxel. Default is 1.norm (
float) – Optional. Factor by which to divide output spectrum. Default is 1.plot (
bool) – Optional. Plot extracted spectrum.medfilt (
Optional[int]) – Optional. If not None, apply median filter of specified size to extracted spectrum. Default is None.ylim (
Optional[tuple]) – Optional. Y-axis limits for plot. Default is None, in which case the plot will autoscale.
- Returns:
numpy.ndarray – Array of size nwave x (1-3), including data and var and/or dq if present.
- reproject(newheader, new2dshape, newpixarea_sqas, parallel=True)[source]
Reproject cube onto a new WCS. Overwrites the data, variance, dq, and error attributes. Also updates the pixel area, nrows, ncols, and PIXEL_A2 keyword in the header.
- Parameters:
- writefits(outfile)[source]
Write cube to file outfile. Assumes extension order empty phu (if present in original fits file), datext, varext, dqext, and wmapext.
- Parameters:
outfile (
str) – Name of output file.
- class q3dfit.q3din.q3din(infile, label, argsreadcube={}, cutrange=None, fitrange=None, logfile=None, name=None, outdir=None, spect_convol={}, zsys_gas=None, vacuum=True, datext=1, varext=2, dqext=3)[source]
Bases:
objectInitialize fit.
- Parameters:
infile – Name of input FITS file. Also sets the attribute
infile.label – Shorthand label for filenames. Also sets the attribute
label.argsreadcube – Optional. Dict of parameter name/value pairs to pass to
Cube. Default is an empty dictionary. Also sets the attributeargsreadcube.cutrange – Optional. Set of wavelength limits to cut out of fit. Default is None. Also sets the attribute
cutrange.fitrange – Optional. Set of wavelength limits to fit. Default is None, which means fit the entire range. Also sets the attribute
fitrange.logfile – Optional. Filename to which to print progess messages. Default is None. Also sets the attribute
logfile.name – Optional. Full name of source for plot labels, etc. Default is None. Also sets the attribute
name.outdir – Optional. Output directory for files. Default is None, which means the current directory. Also sets the attribute
outdir.spect_convol – Optional. Input dictionary to pass to
spectConvol. Default is an empty dictionary, which means no convolution. Also sets the attributespect_convol.zsys_gas – Optional. Systemic redshift of galaxy. Default is None. Also sets the attribute
zsys_gas. Sets the initial guess for redshift in the line fit and/or continuum fit if not None and not overridden by the user with the zinit parameter. Also serves as the systemic redshift inq3dpro, if not None and not overridden by the user with the zsys parameter inq3dpro.vacuum – Optional. Are wavelengths in vacuum? Default is True. Also sets the attribute
vacuum.datext – Optional. Extension number for data array in FITS. Default is 1. Also sets the attribute
datext.varext – Optional. Extension number for variance array in FITS. Default is 2. Also sets the attribute
varext.dqext – Optional. Extension number for data quality array in FITS. Default is 3. Also sets the attribute
dqext.
- Variables:
docontfit (bool) – Is the continuum fit? Set to False by default. Added by constructor and updated to True by
init_contfit().dolinefit (bool) – Are emission lines fit? Set to False by default. Added by constructor and updated to True by
init_linefit().lines (list) – List of lines to fit. Added by
init_linefit().ncomp (dict[str, numpy.ndarray]) – # of components for each fitted line and spaxel. Added by
init_linefit().siginit_gas (dict[str, numpy.ndarray]) – Initial guess for sigma for each line, spaxel, and component. Added by
init_linefit().siglim_gas (dict[str, numpy.ndarray]) – Lower and upper limits for sigma for each line, spaxel, and component. Added by
init_linefit().zinit_gas (dict[str, numpy.ndarray]) – Initial guess for redshift for each line, spaxel, and component. Added by
init_linefit().linetie (dict[str, str]) – Anchor line for a group of one or more lines. Each line in the group is tied to the others in velocity. Each group is independent. Each key corresponds to a line being fit, and the value is the anchor line. Added by
init_linefit().linevary (dict[str, dict[Literal['flx','cwv','sig'], numpy.ndarray]]) – Flags to vary flux, central wavelength, and sigma for each line, spaxel, and component. Added by
init_linefit().siginit_gas – Initial guess for sigma for each line, spaxel, and component. Added by
init_linefit().siginit_stars (numpy.ndarray) – Initial guess for stellar velocity dispersion for each spaxel, if fitting a stellar template. Added by
init_contfit().zinit_stars (numpy.ndarray) – Initial guess for stellar redshift for spaxel, if fitting a stellar template. Added by
init_contfit().ncols (int) – Number of columns in data cube. Added by
load_cube().nrows (int) – Number of rows in data cube. Added by
load_cube().cubedim (int) – Dimension of data cube. Added by
load_cube().
- init_linefit(lines, linetie=None, maxncomp=1, siginit=50.0, siglim_gas=[5.0, 2000.0], zinit=None, fcnlineinit='lineinit', argslineinit={}, argslinelist={}, argslinefit={}, checkcomp=True, fcncheckcomp='checkcomp', argscheckcomp={}, perror_useresid=False, perror_errspecwin=20, perror_residwin=200, quiet=False)[source]
Initialize line fit.
- Parameters:
linetie (
Union[str,list[str],dict[str,str],None]) – Optional on input. As input: 1. Set to None to fit all lines independently. 2. Set to a single line to tie all lines together. 3. Set to a list of strings to tie lines in groups. Default is None.maxncomp (
int) – Optional. Maximum possible number of velocity components in any line. Default is 1. Also sets the attributemaxncomp.siginit (
float) – Optional. Uniform initial guess for emission-line velocity dispersion in km/s. Default is 50. This can be overridden by settingsiginit_gasfor individual lines, spaxels, and components after initialization.siglim_gas (ArrayLike) – Optional. Lower and upper limits for sigma in km/s for each line, spaxel, and component. Default is [5., 2000.]. This can be overridden by setting
siglim_gasfor individual lines, spaxels, and components after initialization.zinit (
Optional[float]) – Optional. Initial redshift in km/s to apply to each line. If zinit is None, try to usezsys_gas. Default is None. This can be overridden by settingzinit_gasfor individual lines, spaxels, and components after initialization.fcnlineinit (
str) – Optional. Name of routine to initialize line fit. Default islineinit(). Also sets the attributefcnlineinit.argslineinit (
dict) – Optional. Arguments for the line initialization function specified by fcnlineinit. Default is an empty dict. Also sets the attributeargslineinit.argslinelist (
dict) – Optional. Arguments forlinelist(). Default is an empty dict. Also sets the attributeargslinelist.argslinefit (
dict) – Optional. Arguments forfit()or to the fitting method selected. Default is an empty dict. Also sets the attributeargslinefit. Available arguments forfit()are ‘method’, ‘max_nfev’, and ‘iter_cb’, which can be passed as key/value pairs. If ‘method’ is not set, it defaults to ‘least_squares’. If the key ‘max_nfev’ is not set, it defaults to 200*(Nfitpars+1). If the key ‘iter_cb’ is not set, it defaults to None. Any other key/value pairs are passed as arguments to the fitting function through the ‘fit_kws’ argument tofit().checkcomp (
bool) – Optional. If True, reject components usingcheckcomp(). Default is True. Also sets the attributecheckcomp.fcncheckcomp (
str) – Optional. Name of routine for component rejection. Default is ‘checkcomp’. Also sets the attributefcncheckcomp.argscheckcomp (
dict) – Optional. Arguments for the component rejection function fcncheckcomp. Default is an empty dict. Also sets the attributeargscheckcomp.perror_errspecwin (
int) – Optional. Parameter for calculating the error on the flux peak using the median of the error spectrum in a window of this width in pixels, centered on the best-fit peak. Default is 20 pixels. Also sets the attributeperror_errspecwin.perror_residwin (
int) – Optional. Parameter for calculating the error on the flux peak using the standard deviation of the fit residuals in a window of this width centered on the best-fit peak. Default is 200 pixels. Also sets the attributeperror_residwin.perror_useresid (
bool) – Optional. If True, use the flux peak error calculated from the residuals as the error on the flux peak if it is greater than the flux peak error calculated byfit(). Default is False. Useful if the error spectrum is not reliable. Also sets the attributeperror_useresid.quiet (
bool) – Optional. Suppress messages. Default is False.
- init_contfit(fcncontfit, argscontfit={}, siginit=50.0, zinit=None, dividecont=False, av_star=None, keepstarz=False, maskwidths=None, maskwidths_def=500.0, masksig_secondfit=2.0, nolinemask=False, nomaskran=None, startempfile=None, startempwaveunit='micron', startempvac=True, quiet=False)[source]
Initialize continuum fit.
- Parameters:
fcncontfit (
str) – Function to fit continuum. Assumed to be a function inq3dfit.contfit. Exception isppxf.ppxf, for which one can specify ‘ppxf’. Also sets the attributefcncontfit.argscontfit (
dict) – Optional. Arguments for the continuum fitting function fcncontfit. Default is an empty dict. Also sets the attributeargscontfit.siginit (
float) – Optional. Uniform initial guess for stellar velocity dispersion in km/s, if fitting a stellar template. Default is 50. This can be overridden by settingsiginit_starsfor individual spaxels after initialization.zinit (
Optional[float]) – Optional. Initial redshift for stellar template, if fitting one. If zinit is None, try to usezsys_gas. Default is None. This can be overridden by settingzinit_starsfor individual spaxels after initialization.dividecont (
bool) – Optional. Divide data by continuum fit. Default is to subtract. Also sets the attributedividecont.av_star (
Optional[float]) – Optional. Initial guess for A_V for stellar template fitting inppxf(). Default is None, which means no extinction is applied. Also sets the attributeav_star.keepstarz (
bool) – Optional. If True, don’t redshift stellar template before fitting. Default is False. Also sets the attributekeepstarz.maskwidths (
Union[Table,dict[str,ndarray],None]) – Optional. Prior to the first continuum fit infitloop(), mask these half-widths, in km/s, around the emission lines to be fit. To use this option, specify a value for each line and component. If set to None and both continuum and emission-line fits are attempted, routine defaults to uniform value set by maskwidths_def. Default is None. Also sets the attributemaskwidths.maskwidths_def (
float) – Optional. Prior to the first continuum fit infitloop(), mask this uniform half-width, in km/s, around each emission line to be fit. Default is 500. Also sets the attributemaskwidths_def.masksig_secondfit (
float) – Optional. When computing half-widths for masking before the second fit infitloop(), best-fit sigmas from the first fit are multiplied by this number. Default is 2.nolinemask (
bool) – Optional. If True, don’t mask emission lines before continuum fit. Default is False. Also sets the attributenolinemask.nomaskran (ArrayLike) – Optional. ArrayLike with 2 x nreg dimensions. Set of lower and upper wavelength limits of regions not to mask. Default is None. Also sets the attribute
nomaskran.startempfile (
Optional[str]) – Optional. Name of numpy save file containing stellar templates. Default is None. Also sets the attributestartempfile. Must be set for stellar template fitting to work. To create the file, use thesave()function on a dictionary containing the keys ‘wave’ and ‘flux’. ‘wave’ is a 1d numpy array with rest wavelengths. ‘flux’ is a 2d array, with the first dimension being the number of wavelengths and the second dimension being the number of templates. If the key ‘sigma’ is present, it is a 1d numpy array with the resolution the template(s) at each wavelength in the input wavelength unit. The resolution is expressed as the sigma of a Gaussian. This is used to convolve the template to the resolution of the data cube usingspect_convolver(). If the stellar template is not in vacuum wavelengths, setstartempvacto False. If it is in ‘Angstroms’ rather than ‘micron’, setstartempwaveunitto ‘Angstrom’.startempwaveunit (
Literal['micron','Angstrom']) – Optional. Wavelength unit for stellar template. Options are ‘micron’ and ‘Angstroms.’ Default is ‘micron.’ Conversion is done to match the output wavelength unit of the data cube, which is set inCube. Also sets the attributestartempwaveunit.startempvac (
bool) – Optional. Is the stellar template in vacuum wavelengths? If True and the data are in air wavelengths, the template is converted to air wavelengths infitspec(). Default is True. Also sets the attributestartempvac.quiet (
bool) – Optional. Suppress messages. Default is False.tweakcntfit – Optional. Tweak the continuum fit using local polynomial fitting. Default is None. (Not yet implemented.)
- get_dispersion()[source]
Instantiate
spectConvolobject with dispersion information for selected gratings.- Return type:
- Returns:
Optional[spectConvol.spectConvol] –
spectConvolobject, or None (no convolution) if q3di.spect_convol is an empty dictionary.
- class q3dfit.q3dout.q3dout(wave, spec, spec_err, fitrange=None, col=None, row=None, gd_indx=None, fitran_indx=None, fluxunit='erg/s/cm^2/micron', waveunit='micron', fluxnorm=1.0, pixarea_sqas=None, nogood=False)[source]
Bases:
objectThis object is created by
q3dfwhen running on any single spaxel. It collects the output and contains functions to generate plots for a single spaxel.For multi-spaxel post-processing, see
q3dpro.- Parameters:
- Variables:
fitrange (np.ndarray) – Wavelength range for fitting. Added by constructor. Defaults to None.
col (int) – Column index. Added by constructor. Defaults to None.
row (int) – Row index. Added by constructor. Defaults to None.
gd_indx (ndarray) – Good data indices. Added by constructor. Defaults to None.
fitran_indx (ndarray) – Fit range indices. Added by constructor. Defaults to None.
fluxunit (str) – Flux density unit. Added by constructor. Defaults to erg/s/cm^2/micron.
linefluxunit (str) – Line flux unit. Added by
sepfitpars().waveunit (str) – Wavelength unit. Added by constructor. Defaults to ‘micron’.
fluxnorm (float) – Flux normalization. Added by constructor. Defaults to 1.0.
pixarea_sqas (float) – Pixel area in square arcseconds. Added by constructor. Defaults to None.
nogood (bool) – No good data present. Added by constructor. Defaults to False.
docontfit (bool) – Do continuum fit. Added by constructor. Defaults to False. Updated by
init_contfit().dolinefit (bool) – Do line fit. Added by constructor. Defaults to False. Updated by
init_linefit().add_poly_degree – Degree of additive polynomial in the pPXF fit. Default is -1, which means no additive polynomial. Added by
sepcontpars().stelmod (float) – Stellar component of continuum fit. Added/updated by
sepcontpars().qsomod (float) – QSO component of continuum fit. Added/updated by
sepcontpars().hostmod (float) – Host component of continuum fit. Added/updated by
sepcontpars().polymod_refit (ndarray) – Polynomial component of continuum fit, if refit with fitqsohost. Added/updated by
sepcontpars().line_fitpars (dict) –
Line fit parameters. Added/updated by
sepfitpars(). Contains the following keys:flux: Table with total fluxes of emission lines.
fluxerr: Table with total flux errors of emission lines.
fluxpk: Table with peak fluxes of emission lines.
fluxpkerr: Table with peak flux errors of emission lines.
fluxpk_obs: Table with peak fluxes of emission lines, corrected for spectral resolution.
fluxpkerr_obs: Table with peak flux errors of emission lines, corrected for spectral resolution.
sigma: Table with line widths (sigmas) of emission lines.
sigmaerr: Table with line width errors (sigmas) of emission lines.
sigma_obs: Table with line widths (sigmas) of emission lines, corrected for spectral resolution.
sigmaerr_obs: Table with line width errors (sigmas) of emission lines, corrected for spectral resolution.
wave: Table with line central wavelengths of emission lines.
waveerr: Table with line central wavelength errors of emission lines.
tflux: Total fluxes of emission lines, summed over components.
tfluxerr: Total flux errors of emission lines, summed over components.
filelab (str) – File label for plotting methods. Added/updated by
load_q3dout().
- init_linefit(linelist, linelabel, maxncomp=1, line_dat=None, parinit=None, line_fit=None, param=None, perror=None, perror_resid=None, perror_errspec=None, fitstatus=None, dof=None, redchisq=None, nfev=None, covar=None, errorbars=None)[source]
Initialize output line fit parameters.
- Parameters:
linelist (
Table) – Emission line labels and rest frame wavelengths, as part of an astropy Table output bylinelist(). Passed directly from the listlines parameter offitspec()to this function.linelabel (
list[str]) – List of lines to fit. Copy oflinesfromq3din.maxncomp (
int) – Maximum number of components. Copy ofmaxncomp.line_dat (
Optional[ArrayLike]) – Continuum-subtracted fluxes for emission line fit, fromfitspec(). Includes data within the fit range.parinit (
Optional[Parameters]) – Initial parameters, output from the line initialization routine.param (
Optional[dict]) – Dictionary with parameter names as keys, and best-fit values as values. Copy ofbest_values.perror (
Optional[dict]) – Parameter errors. Dictionary with parameter names as keys, and errors as values. Values are copies ofstderr. If there is no error in the peak flux values, or it is a NaN, it is set to the value computed from the error spectrum (see below). If ~q3dfit.q3din.q3din.perror_useresid is set to True and the error from the flux residual is greater than the error from the covariance matrix, then the error is set to the value computed from the residuals (see below).perror_resid (
Optional[dict]) – Copy of perror, but with peak flux errors computed from the residuals of the fit, rather than from the covariance matrix. The error is the standard deviation of the residuals in a window around the line, with the window size in pixels set byperror_residwin.perror_errspec (
Optional[dict]) – Copy of perror, but with peak flux errors computed from the error spectrum, rather than from the covariance matrix. The error is the median of the error spectrum in a window around the line, with the window size in pixels set byperror_errspecwin.fitstatus (
Optional[int]) – Fit status, passed from the fitting routine. If method is set to ‘least_squares’ byargslinefit, then this is described by the status attribute ofleast_squares(). If the method is set to leastsq, then this is the ier integer return code fromleastsq().redchisq (
Optional[float]) – Reduced chi-squared. Copy ofredchi.nfev (
Optional[int]) – Number of function evaluations. Copy ofnfev.covar (
Optional[ArrayLike]) – Covariance matrix. Copy ofcovar.errorbars (
Optional[bool]) – If True, then no errors are computed for the line fit. Copy oferrorbars.
- init_contfit(ct_method='subtract', cont_dat=None, ct_indx=None, cont_fit=None, ct_coeff=None, ct_rchisq=None, zstar=None, zstar_err=None)[source]
Initialize continuum fit parameters.
- Parameters:
ct_method (
Literal['subtract','divide']) – Method for continuum fit. Default is ‘subtract’. Set on initialization ofq3dinbydividecont.cont_dat (
Optional[ArrayLike]) – Fluxes minus any best-fit emission-line model. Includes data within the fit range. Set to None until assigned byfitspec().ct_indx (
Optional[ArrayLike]) – Indices to cont_dat that are used for the continuum fit; i.e., emission lines are masked out. Set to None until assigned byfitspec().cont_fit (
Optional[ArrayLike]) – Best-fit continuum model, over the fit range. Set to None until assigned byfitspec().ct_coeff (
Optional[dict]) – Parameters of the continuum fit. Set to None until assigned byfitspec(). Exact form depends on the continuum fit function used. See modulecontfitfor details.ct_rchisq (
Optional[float]) – Reduced chi-squared from continuum fit. Set to None until assigned byfitspec().zstar (
Optional[float]) – Best-fit zstar. Set to None until assigned byfitspec().zstar_err (
Optional[float]) – Error in best-fit zstar. Set to None until assigned byfitspec().
- cmplin(line, comp)[source]
Return the model flux for all fitted wavelengths in a given line and component, from the best-fit parameters in
param.
- sepfitpars(waveran=None, doublets=None, ignoreres=False)[source]
Convert output of LMFIT, with best-fit line parameters in a single array, into a dictionary with separate arrays for different line parameters. Compute total line fluxes from the best-fit line parameters.
This routine sets
line_fitpars.- Parameters:
waveran (
Optional[ArrayLike]) – Set to upper and lower limits to return line parameters only for lines within the given wavelength range. Lines outside this range have fluxes set to 0.doublets (
Optional[dict]) – Dictionary of doublet lines for which to combine fluxes.ignoreres (
bool) – Ignore spectral resolution in computing observed sigmas and peak fluxes. This is mainly for backward compatibility with old versions, which did not store the spectral resolution in an easily accessible way in the specConv object.
- sepcontpars(q3di, decompose_qso_fit=None, decompose_ppxf_fit=None)[source]
Separate continuum fit parameters into individual components.
- Parameters:
q3di –
q3dinobject with input parameters.decompose_qso_fit (
Optional[bool]) – Optional. Decompose QSO fit if continuum fit method isfitqsohost(). Default is None, which means True if the continuum fit method isfitqsohost(), and False otherwise.decompose_ppxf_fit (
Optional[bool]) – Optional. Decompose pPXF fit if continuum fit method isppxf. Default is None, which means True if the continuum fit method isppxf, and False otherwise.
- plot_line(q3di, fcn='plotline', savefig=False, outfile=None, argssavefig={'bbox_inches': 'tight', 'dpi': 300}, plotargs={})[source]
Line plotting function.
- Parameters:
fcn (
str) – Name of the plotting function to use. Default isplotcont().savefig (
bool) – If True, save the figure to a file. Default is False.outfile (
Optional[str]) – If savefig is True, the name of the output file to save the figure. Default is None, which means the output file will be named <filelab>_cnt where <filelab> is the path+filename set byload_q3dout().argssavefig (
dict) – Optional. Dictionary of arguments to pass tosavefig(). Defaults to {‘bbox_inches’: ‘tight’, ‘dpi’: 300}.plotargs (
dict) – Additional keyword arguments to pass to the plotting function.
- plot_cont(q3di, fcn='plotcont', savefig=False, outfile=None, argssavefig={'bbox_inches': 'tight', 'dpi': 300}, plotargs={})[source]
Continuum plotting function.
- Parameters:
fcn (
str) – Name of the plotting function to use. Default isplotcont().savefig (
bool) – If True, save the figure to a file. Default is False.outfile (
Optional[str]) – If savefig is True, the name of the output file to save the figure. Default is None, which means the output file will be named <filelab>_cnt where <filelab> is the path+filename set byload_q3dout().argssavefig (
dict) – Optional. Dictionary of arguments to pass tosavefig(). Defaults to {‘bbox_inches’: ‘tight’, ‘dpi’: 300}.plotargs (
dict) – Additional keyword arguments to pass to the plotting function.
- class q3dfit.q3dpro.Q3Dpro(q3di, quiet=True, nocont=False, noline=False, platescale=0.15, background='white', bad=nan, zsys=None, zsys_gas=None, **kwargs)[source]
Bases:
objectClass to process the q3dfit output data.
- Parameters:
q3di (
str|q3din) – Path to the q3dfit output file or q3din object. Also updatesq3dinit.quiet (
bool) – Optional. Flag to suppress print statements. Default is True. Also updatesquiet.nocont (
bool) – Optional. If False, createContDataobject and assign tocontdat. Default is False.noline (
bool) – Optional. If False, createLineDataobject and assign tolinedat. Default is False.zsys (
Optional[float]) – Optional. Systemic redshift of the galaxy. Default is None, which will use the value from the q3din object. Also updateszsysandzsys_gas.zsys_gas (
Optional[float]) – Optional. Kept for backwards compatibility; zsys is preferred. Default is None. Setting this will updatezsysandzsys_gas.
- Variables:
q3dinit (q3din.q3din) – Copy of
q3dinobject. Added/updated by__init__().target_name (str) – Full name of source for plot labels, etc. . Added/updated by :method:init.
pix (float) – Plate scale of the data. Added/updated by :method:init.
bad (float) – Value for bad data. Default is np.nan. Added/updated by :method:init.
dataDIR (str) – Directory of the data, from q3dinit. Added/updated by :method:init.
contdat (Optional[ContData]) – Continuum data object. Added/updated by :method:init, using :class:ContData. If nocont is True, this will be None.
linedat (Optional[LineData]) – Emission line data object. Added/updated by :method:init, using :class:LineData. If noline is True, this will be None.
map_bkg (str) – Background color for the maps. Default is ‘white’. Added/updated by :method:init.
zsys (float) – Systemic redshift of the galaxy. Added/updated by
__init__().zsys_gas (float) – Kept for backwards compatibility; zsys is preferred. Equal to zsys. Added/updated by
__init__().
- get_zsys(zsys, zsys_gas)[source]
Get the systemic redshift of the galaxy from the zsys or zsys_gas attribute or q3din object, in that order.
- Return type:
- Returns:
float – Systemic redshift of the galaxy.
- get_linemap(line, applymask=True, **kwargs)[source]
Create arrays holding maps of properties of an emission line.
- Parameters:
- Return type:
tuple[float,str,dict[Literal['Ftot','Fci','Sig','v50','w80'],dict[Literal['data','err','line','mask'],ndarray|list]]]- Returns:
float – Rest wavelength of the line in microns.
str – Full label of the line for plotting.
dict[Literal[‘Ftot’,’Fci’,’Sig’,’v50’,’w80’], dict[Literal[‘data’,’err’,’line’,’mask’], np.ndarray | list]] – Dictionary of line properties. Keys are ‘Ftot’, ‘Fci’, ‘Sig’, ‘v50’, ‘w80’. Each key contains a dictionary with keys ‘data’, ‘err’, ‘name’, ‘mask’. ‘data’ and ‘err’ are the data and error arrays, respectively, with shape (ncols, nrows, ncomp). ‘name’ is the properly formatted name of the property, for plotting. ‘mask’ is the mask array, with shape (ncols, nrows, ncomp). In the mask, 1 is good data and
badis bad data.
- make_linemap(line, xyCenter=None, xyStyle=None, fluxcmap='YlOrBr_r', fluxlog=False, ranges=None, compSort=None, saveData=False, saveFormat='png', dpi=100, **kwargs)[source]
Plot maps of properties of an emission line.
- Parameters:
line (
str) – Name of the line for which to create plots.compSort (
Optional[dict[Literal['sort_by','sort_range'],Any]]) – Optional. The ‘sort_by’ key must take one of the following values, which are keys of the dictionary output byget_linemap(): ‘Ftot’, ‘Fci’, ‘Sig’, ‘v50’, or ‘w80’. The ‘sort_range’ key is optional and is a tuple of lists. Each list contains two values that define the range of the component values to be used in the sorting. For the nth element of the tuple, the last existing component that lies in the range will be the nth component in the re-sorted line maps. If ‘sort_range’ is not provided, the components will be sorted based on the absolute value of the ‘sort_by’ parameter. Default is None, which means no sorting.xyCenter (
Optional[list]) – Optional. Center of the plot in 0-offset spaxel coordinates. Default is None, which means the center is the spatial middle of the FOV.xyStyle (
Optional[str]) – Optional. Set this to ‘kpc’ to label the axes in kpc from xyCenter. Set to any other string to label the axes in pixels from xyCenter. Default is None, which means the axes are labeled in pixels from the lower left corner.fluxcmap (
str) – Optional. Color palette for the flux maps. Default is ‘YlOrBr_r’.fluxlog (
bool) – Optional. If True, plot the flux maps with a log scale. Default is False.ranges (
Optional[dict[Literal['Ftot','Fci','Sig','v50','w80'],list]]) – Optional. Dictionary with one or more of the following keys: ‘Ftot’, ‘Fci’, ‘Sig’, ‘v50’, ‘w80’. The values of each key are lists of two values that define the range of the parameter to be plotted. Default is None, which means the full range of the parameter is plotted.saveData (
bool) – Optional. If True, save the plots to a file. Default is False.saveFormat (
Literal['png','ps','pdf','svg']) – Optional. Format for saving the plots. Default is ‘png’.dpi (
int) – Optional. Dots per inch for the saved plots. Default is 100.
- make_lineratio_map(lineA, lineB, snrcut=3.0, vminmax=[None, None], kpc=False, cmap='inferno', saveData=False, saveFormat='png', dpi=100, **kwargs)[source]
Plot map of the line ratio of two emission lines.
- Parameters:
lineA (
str) – Name of the first line for the line ratio.lineB (
str) – Name of the second line for the line ratio.snrcut (
float) – Optional. Signal-to-noise ratio cut for the line maps. Default is 3.vminmax (
list) – Optional. List of two values that define the range of the line ratio to be plotted. Default is [None, None], which means the full range of the line ratio is plotted.kpc (
bool) – Optional. If True, label the axes in kpc from the galaxy center. Default is False.cmap (
str) – Optional. Color palette for the line ratio map. Default is ‘inferno’.saveData (
bool) – Optional. If True, save the plots to a file. Default is False.saveFormat (
str) – Optional. Format for saving the plots. Default is ‘png’.dpi (
int) – Optional. Dots per inch for the saved plots. Default is 100.
- make_BPT(snrcut=3.0, kpc=False, cmap='inferno', saveData=False, saveFormat='png', dpi=100, **kwargs)[source]
Plot usual BPT diagrams.
- Parameters:
snrcut (
float) – Optional. Signal-to-noise ratio cut for the line maps. Default is 3.kpc (
bool) – Optional. If True, label the axes in kpc from the galaxy center. Default is False.cmap (
str) – Optional. Color palette for the line ratio map. Default is ‘inferno’.saveData (
bool) – Optional. If True, save the plots to a file. Default is False.saveFormat (
str) – Optional. Format for saving the plots. Default is ‘png’.dpi (
int) – Optional. Dots per inch for the saved plots. Default is 100.
- class q3dfit.q3dpro.OneLineData(linedata, line, quiet=True, **kwargs)[source]
Bases:
objectParse all line data for a given emission line from a LineData object.
- Parameters:
- Variables:
ncols (int) – Copy of
ncols.nrows (int) – Copy of
nrows.bad (float) – Copy of
bad.dataDIR (str) – Copy of
dataDIR.target_name (str) – Copy of
target_name.flux (numpy.ndarray) – Total flux of each spaxel and component for this line.
fpklux (numpy.ndarray) – Peak flux of each spaxel and component for this line.
sig (numpy.ndarray) – Sigma of each spaxel and component for this line.
wave (numpy.ndarray) – Central wavelength of each spaxel and component for this line.
ncomp (numpy.ndarray) – Number of components fit to each spaxel for this line.
cvdf_zref (float) – Reference redshift for computing velocities. Defined in
calc_cvdf().cvdf_vel (numpy.ndarray) – Model velocities. 1D array. Defined in
calc_cvdf().vdf (numpy.ndarray) – Velocity distribution in flux space. 3D data with two dimensions of imaging plane and third of model points. Defined in
calc_cvdf().cvdf (numpy.ndarray) – Cumulative velocity distribution function. 3D data with two dimensions of imaging plane and third of model points. Defined in
calc_cvdf().cvdf_nmod (int) – Number of model points. Defined in
calc_cvdf().
- calc_cvdf(zref, vlimits=[-10000.0, 10000.0], vstep=1.0)[source]
Compute cumulative velocity distribution function for this line, for each spaxel.
- calc_cvdf_vel(pct, calc_from_posvel=True)[source]
Compute a velocity at % pct from one side of the CVDF.
- Parameters:
- Return type:
- Returns:
numpy.ndarray – Array of size (ncols, nrows) containing the velocity at the given percentile.
- make_cvdf_map(pct, velran=[-300.0, 300.0], calc_from_posvel=True, cmap='RdYlBu_r', center=[0.0, 0.0], markcenter=None, saveData=False, saveFormat='png', dpi=100, **kwargs)[source]
Make a map of the cumulative velocity distribution function at a given percentile.
- Parameters:
pct (
float) – Percentile to plot. Must be between 0 and 100.velran (ArrayLike) – Optional. Range of velocities to plot, in km/s. Default is [-3e2, 3e2].
calc_from_posvel (
bool) – Optional. If True, the zero-point is at positive velocities. Default is True.cmap (
str) – Optional. Colormap to use. Default is ‘RdYlBu_r’.center (ArrayLike) – Optional. Location, in zero-offset spaxel coordinates, from which to compute axis offsets. Default is [0., 0.].
markcenter (
Optional[ArrayLike]) – Optional. Location, in axes coordinates, to mark with a star. Default is None.outfile – Optional. Name of file to save the plot. Default is None.
outformat – Optional. Format of the output file. Default is ‘png’.
outdpi – Optional. DPI of the output file. Default is 100.
- class q3dfit.q3dpro.LineData(q3di)[source]
Bases:
objectRead in and store line data for all fitted lines in the numpy save file created by
q3dcollect().Individual line measurements can be obtained with corresponding methods.
- Parameters:
q3di (
q3din) – q3d initialization object containing line names and other parameters.- Variables:
lines (list) – Copy of
lines.maxncomp (int) – Copy of
maxncomp.data (numpy.lib.npyio.NpzFile) – Contents of the line data (.npz) file.
ncols (int) – Copy of
ncols.nrows (int) – Copy of
nrows.bad (float) – Value of bad pixels. Default is np.nan.
dataDIR (str) – Copy of
outdir.target_name (str) – Copy of
name.colname (list) – Sorted list of dictionary names in the
dataattribute. Set in_read_npz().
- get_flux(lineselect, fluxsel='ftot', **kwargs)[source]
Get flux and error of a given line.
- Parameters:
lineselect (
str) – Which line to grab.fluxsel (
str) – Optional. Which type of flux to grab, as defined inq3dcollect(). Options are ‘ftot’, ‘fc1’, ‘fc1pk’, ‘fc2’, ‘fc2pk’, …, ‘fcN’, ‘fcNpk’ for N total components. Default is ‘ftot’.
- Return type:
- Returns:
dict[Literal[‘flx’, ‘flxerr’], numpy.ndarray] – Each key contains an array of size (ncols, nrows, ncomp).
- get_sigma(lineselect, compsel=1, **kwargs)[source]
Get sigma and error of a given line and component.
- class q3dfit.q3dpro.ContData(q3di)[source]
Bases:
objectRead in and store continuum data for all spaxels in the numpy save file created by
q3dcollect().- Parameters:
q3di (
q3din)
- class q3dfit.spectConvol.spectConvol(spect_convol, waveunit='micron')[source]
Bases:
objectConvolve an input spectrum by grating resolution.
JWST provides NIRSpec dispersion files. However, MIRI is not provided. Instead, we take a Cubic Spline interpolation based on the curves in the Jdocs website.
For the constructor, the requested dispersion curves are either loaded from a file, created from a flat dispersion curve, or computed from a formula in the case of MRS.
- Parameters:
spect_convol (
dict[str,Union[dict[str,str],str,None]]) – ws_instrum contains instrument/grating combinations. dispdir is the directory of dispersion files. If set to None (default), the q3dfit dispersion_file directory is used.waveunit (
Literal['micron','Angstrom']) – Optional. Wavelength unit, either ‘micron’ or ‘Angstrom’. Default is ‘micron’.
- Raises:
SystemExit – If no ws_instrum dictionary is found in the input dictionary. If an error is found in the input dictionary.
- Variables:
dispdir – Full directory of dispersion files in the repository.
InstGratObjs – Nested dictionary whose keys are instrument/grating combinations. The values are dispersion objects.
- spect_convolver(wave, flux, dsig=None, wavecen=None, oversample=1)[source]
Convolves an input spectrum by the spectral resolution.
- Parameters:
wave (
ndarray) – Wavelength array of input spectrumflux (
ndarray) – Flux array of input spectrumdsig (
Optional[ndarray]) – Optional. Native dispersion of the input spectrum. If not specified, the input spectrum is assumed to have perfect resolution. Default is None.wavecen (
Optional[float]) – Optional. Central wavelength of a spectral feature, to check if it falls in the range of a grating. Default is None, which means no check is performed.oversample (
int) – Optional. Oversample the spectrum by this factor before convolution. Default is 1, which means no oversampling is performed. Passed tovarsmooth().
- Return type:
- Returns:
np.ndarray – Convolved spectrum.
- selectInstGrat(wavecen=None)[source]
Make a list of instrument/grating combinations to use for convolution. If wavecen is not specified, all instrument/grating combinations are used. The length of the output list must be 1 or 2.
If it’s 2, the gratings may need to have some overlap in wavelength. (See get_InstGrat_waveDlam for more details.) Should probably do a check for this …
- get_InstGrat_waveDlam(InstGratSelect)[source]
Get wavelength and dlambda for selected grating(s). If one grating, return the wavelength and dlambda. If two gratings, return the combined wavelength and dlambda, with the overlap region split between the two gratings. If MRS is used, return None for both, as we calculate the dispersion from a formula.
- Parameters:
InstGratSelect (
list) – List of instrument/grating combinations. The length of the list is 1 or 2. If 2 are specified, they must have overlapping wavelengths.- Return type:
- Returns:
Optional[float, np.ndarray] – Wavelength of the grating(s).
Optional[float, np.ndarray] – Delta lambda of the grating(s).
- class q3dfit.spectConvol.dispersion[source]
Bases:
objectClass to carry dispersion information.
- Variables:
dispdir (str) – Directory that holds the file of the dispersion data, if any. Added by constructor and populated by
setdir().dlam (np.ndarray) – Delta lambda. Added by constructor and populated by
compute_Rdlam().filename (str) – Filename of the dispersion data file. Added by constructor and populated by subclasses as needed.
R (np.ndarray) – Resolving power. Added by constructor and populated by
compute_Rdlam().wave (np.ndarray) – Wavelength. Added by constructor and populated by
read()orcompute_Rdlam().waveunit (str) – Wavelength unit. Default is ‘micron’. Can be set to ‘Angstrom’ if needed.
- setdir(dispdir=None)[source]
Set the attribute carrying the directory of the associated dispersion file.
- read(filename)[source]
Get dispersion data from a dispersion file(s). The file must be in FITS format. The dispersion file must have a wavelength array and a dispersion array. The dispersion array can be either R, dlambda, or dvel (delta velocity). The method chooses from these in order of preference dvel, R, dlambda, if more than one is present. It then computes R and dlambda and adds these to the object.
The method also checks the wavelength unit in the file header and converts the wavelength and dispersion arrays to the object’s wavelength unit, if necessary.
- Parameters:
filename (
str) – Filename and path of the dispersion file to load.- Raises:
- write(filename, wave=None, waveunit=None, disp=None, type='R', overwrite=False)[source]
Write dispersion file from dispersion data. Can specify the dispersion quantity (disp) and type (type) to write. If not specified, the method uses the dispersion data in the object, starting with R, then dlambda.
- Parameters:
filename (
str) – Filename and full path of the output dispersion file.wave (
Optional[ndarray]) – Optional. Wavelength array. Default is None, which means take from the object.waveunit (
Optional[Literal['micron','Angstrom']]) – Optional. Wavelength unit, either ‘micron’ or ‘Angstrom’. Default is None, which means use the object’s wavelength unit.disp (
Optional[ndarray]) – Optional. Dispersion array. Default is None, which means use the dispersion data in the object.type (
Literal['R','DVEL','LAMBDA']) – Optional. Type of dispersion. Options are ‘R’, ‘DVEL’, or ‘DLAMBDA’. Default is ‘R’.overwrite (
bool) – Optional. Overwrite existing dispersion file. Default is False.
- Raises:
- class q3dfit.spectConvol.InstGratDispersion(inst, grat, dispdir=None, waveunit='micron')[source]
Bases:
dispersion- writeInstGrat(wave=None, waveunit=None, disp=None, type='R', overwrite=False)[source]
Write the dispersion file.
- Parameters:
wave (
Optional[ndarray]) – Optional. Wavelength array. Default is None, which means the object’s wavelength array is used.waveunit (
Optional[Literal['micron','Angstrom']]) – Optional. Wavelength unit, either ‘micron’ or ‘Angstrom’. Default is None, which means the object’s wavelength unit is used.disp (
Optional[ndarray]) – Optional. Dispersion array. Default is None, which means the object’s dispersion array is used.type (
Literal['R','DVEL','DLAMBDA']) – Optional. Type of dispersion. Default is ‘R’. Options are ‘R’, ‘DVEL’, or ‘DLAMBDA’.overwrite (
bool) – Optional. Overwrite existing dispersion file. Default is False.
- class q3dfit.spectConvol.FlatDispersion(disp, type, wave=None, waveunit='micron')[source]
Bases:
dispersion- writeFlat(dispdir=None, wave=None, waveunit=None, overwrite=False)[source]
Write the flat dispersion file.
- Parameters:
dispdir (
Optional[str]) – Optional. Directory to write the dispersion file. Default is None.wave (
Optional[ndarray]) – Optional. Wavelength array. Default is None, which means the object’s wavelength array is used.waveunit (
Optional[Literal['micron','Angstrom']]) – Optional. Wavelength unit, either ‘micron’ or ‘Angstrom’. Default is None, which means the object’s wavelength unit is used.overwrite (
bool) – Optional. Overwrite existing dispersion file. Default is False.
Internal modules
checkcomp
- q3dfit.checkcomp.checkcomp(linepars, linetie, ncomp, siglim, sigcut=3.0, subone=False, ignore=[])[source]
Automatically search for “good” components.
- Parameters:
linepars (
dict[str,Any]) –line_fitparsattribute ofq3doutncomp (
dict[str,int]) – # of components for each fitted line.siglim (
dict[str,ndarray]) – Sigma limits for emission lines.sigcut (
float) – Optional. Sigma threshold in flux for rejection of a component. Default is 3.subone (
bool) – Optional. If True, remove only one component if multiple lines are found to be insignificant. Useful when degeneracy between components lowers significance for all components, but some components still exist. Default is False.ignore (
list[str]) – Optional. Array of lines to ignore in looking for good copmonents, array of string-typed elements. Default is empty list.
- Return type:
- Returns:
dict[str, int] – # of good components for each unique linetie anchor. The input ncomp is also updated to reflect correct new # of components.
fitloop
- q3dfit.fitloop.fitloop(ispax, colarr, rowarr, cube, q3di, listlines, specConv, onefit=False, quiet=True)[source]
Perform fitting loops over spaxels. This function calls
fitspec()to fit the data.- Parameters:
ispax (
int) – Value of index over which to loop.colarr (
ndarray) – Array of column #s of spaxels to be fit (0-offset).rowarr (
ndarray) – Array of row #s of spaxels to be fit (0-offset).listlines (
Table) – Emission line labels and rest frame wavelengths, as part of an astropy Table output bylinelist().specConv (
Optional[spectConvol]) – Instance ofspectConvolspecifying the instrumental spectral resolution convolution. If None, no convolution is performed.onefit (
bool) – If set, only one fit is performed. Default is False.quiet (
bool) – Optional. Suppress progress messages. Default is False.
fitspec
- q3dfit.fitspec.fitspec(wlambda, flux, err, dq, q3di, zstar=None, listlines=None, listlinesz=None, ncomp=None, linevary=None, maskwidths=None, peakinit=None, siginit_gas=None, siginit_stars=None, siglim_gas=None, specConv=None, fluxunit=None, waveunit=None, quiet=True)[source]
This function is the core routine to fit the continuum and emission lines of a spectrum.
- Parameters:
wlambda (
ndarray) – Spectrum, observed-frame wavelengths.flux (
ndarray) – Spectrum, fluxes.err (
ndarray) – Spectrum, flux errors.zstar (
Optional[float]) – Optional. Initial guess for stellar redshift. Use None if no continuum fit is done.siginit_stars (
Optional[float]) – Optional. Initial guess for stellar line widths for fitting. It is created byinit_contfit()or specified on input. Set to None if no continuum fit is done.listlines (
Optional[Table]) – Optional. Emission line labels and rest frame wavelengths, as part of an astropy Table output bylinelist(). Use None if no emission-line fit is done.listlinesz (
Optional[dict[str,ndarray]]) – Optional. Initial guess for emission line observed frame wavelengths. Use None if no emission-line fit is done.ncomp (
Optional[dict[str,int]]) – Optional. Number of components fit to each line. Use None if no emission-line fit is done.linevary (
Optional[dict[str,dict[str,ndarray]]]) – Optional. Dictionary specifying which parameters to vary for each line. Nested dictionary with line names as keys, and dictionaries as values. This is passed tolineinit, or another function specified infcnlineinit. These dictionaries have keys ‘flx’, ‘cen’, and ‘sig’, with boolean arrays as values. Default is None.maskwidths (
Union[Table,dict[str,ndarray],None]) – Optional. Widths, in km/s, of emission-line regions to mask from continuum fit. If set to None, routine will look for maskwidths attribute inq3din. If this is None and both continuum and emission- line fits are attempted, routine defaults to value set in maskwidths_def attribute ofq3din.peakinit (
Union[Table,dict[str,ndarray],None]) – Optional. Initial guess for peak emission-line flux densities. If set to None, routine will look for peakinit attribute inq3din. If this is None and line fit is done, routine estimates from data.siginit_gas (
Optional[dict[str,ndarray]]) – Optional. Initial guess for emission line widths for fitting. It is created byinit_linefit()or specified on input. Set to None if no emission-line fit is done.siglim_gas (
Optional[dict[str,ndarray]]) – Optional. Sigma limits for line fitting. It is created byinit_linefit()or specified on input. Set to None if no emission-line fit is done.specConv (
Optional[spectConvol]) – Optional. Instance ofspectConvolspecifying the instrumental spectral resolution convolution. If None, no convolution is done.fluxunit (
Optional[str]) – Optional. Units of flux density defined inCube. Default is None.waveunit (
Optional[str]) – Optional. Units of wavelength defined inCube. Default is None.quiet (
bool) – Optional. If False, some progress messages are written to stdout. Default is True.
- Return type:
- Returns:
q3dout.q3dout – Instance of
q3doutcontaining the fit results.
- q3dfit.fitspec.airtovac(wv, waveunit='Angstrom', logfile=None, quiet=True)[source]
Takes an array of wavelengths in air and converts them to vacuum using eq. 3 from Morton et al. 1991.
- Parameters:
- Return type:
- Returns:
ndarray – An array of the same dimensions as the input and in the same units as the input
References
Morton 1991, ApJSS, 77, 119
Examples
>>> wv=np.arange(3000,7000,1) >>> vac_wv=airtovac(wv) array([3000.87467224, 3001.87492143, 3002.87517064, ..., 6998.92971915, 6999.92998844, 7000.93025774])
- q3dfit.fitspec.masklin(llambda, linelambda, halfwidth, nomaskran=None)[source]
Masks emission lines from the spectrum for continuum fitting
- Parameters:
llambda (
ndarray) – Wavelengths of the spectrum.linelambda (
dict[str,ndarray]) – Dictionary with line names as keys and arrays of central wavelengths as values, one value per component.halfwidth (
Table) – Dictionary with line names as keys and arrays of half widths as values, one value per component; or a Table with the same structure.nomaskran (
Optional[ArrayLike]) – Optional. Set of lower and upper wavelength limits of regions not to mask. If None, no regions are excluded.
- Return type:
- Returns:
numpy.ndarray – Array of llambda-array indices indicating non-masked wavelengths.
Examples
from masklin import masklin
Generate linelist:
from linelist import linelist mylist=[‘Halpha’,’Hbeta’,’Hgamma’] u=linelist(inlines=mylist)
Generate wavelength array:
import numpy as np llambda=np.arange(3000.,8000.,1.)
Generate half widths for masking: from astropy.table import Table # https://docs.astropy.org/en/stable/table/construct_table.html halfwidth=Table([u[‘name’]]) # populate another column # https://docs.astropy.org/en/stable/table/modify_table.html halfwidth[‘halfwidths’]=6000.0 # I have chosen a huge masking width for better visual eff #now use the masking function ind=masklin(llambda, u, halfwidth, 60.)
# plot the spectrum without and with the masking from matplotlib import pyplot as plt plt.interactive(True) fig=plt.figure(1, figsize=(8,8)) plt.clf() spec=1.+(llambda-3000.0)*1e-3 plt.plot(llambda, spec, color=’grey’,alpha=0.3) plt.scatter(llambda[ind],spec[ind]+0.05,color=’red’,alpha=0.1,s=2) plt.show()
# now let’s define a no-masking array dontmask=np.array([[3000,4000,5000],[4000,5000,6000]]) ind1=masklin(llambda, u, halfwidth, 60., nomaskran=dontmask) plt.scatter(llambda[ind1],spec[ind1]-0.05,color=’blue’,alpha=0.03,s=2) plt.show()
lineinit
- q3dfit.lineinit.lineinit(linelist, linelistz, linetie, initflux, initsig, siglim, ncomp, linevary=None, specConv=None, lineratio=None, waves=None)[source]
Initialize parameters for emission-line fitting.
- Parameters:
linelist (
Table) – Emission lines to fit.linelistz (
dict) – Initial guess for line redshifts.linetie (
dict) – Line to which to tie each line.initflux (
dict[str,ndarray]) – Initial guess for line fluxes.initsig (
dict[str,ndarray]) – Initial guess for line sigmas.siglim (
dict[str,ndarray]) – Lower and upper limits for line sigmas.ncomp (
dict[str,ndarray]) – Number of components for each line.linevary (
Optional[dict[str,ndarray]]) – Optional. Line parameter vary flags (fix/free). If set to None, all parameters are set to vary=True. The default is None.specConv (
Optional[spectConvol]) – Optional. Spectral resolution object. If set to None, no convolution will be performed. The default is None.lineratio (
Union[Table,QTable,None]) –Optional. Table of line ratio constraints, beyond those in the doublets table, https://github.com/Q3D/q3dfit/blob/main/q3dfit/data/linelists/doublets.tbl. The default is None. The table must contain the columns line1, line2, comp, and optionally value, fixed, lower, and upper.
line1/line2: the names of the two lines to which the ratio line1/line2 applies. These are the labels found in the linelist Table.
comp: an array of velocity components (zero-indexed) on which to apply the constraints, one array for each pair of lines.
value: the initial value of line1/line2. Presently, if value is specified for one pair of lines, it must be specified for all. Otherwise, the initial value is determined from the data.
fixed: The ratio can be fixed to the initial value. Presently, if fixed is defined, it must be set to True or False for all pairs of line.
lower/upper: If the ratio is not fixed, lower and upper limits can also be specified. (If they are not, and the line pair is a doublet in the doublets.tbl file, then the lower and upper limits are set using the data in that file.) Presently, if lower or upper is defined here for one set of lines, it must be defined here for every pair of lines.
waves (
Optional[ndarray]) – Optional. Wavelength array for determining if a line is in the fit range. The default is None.
- Return type:
- Returns:
tuple[Model, Parameters] – A tuple containing the LMFIT Model and the fit parameters.
- q3dfit.lineinit.set_params(fit_params, NAME, VALUE=None, VARY=True, LIMITED=None, TIED=None, LIMITS=None)[source]
Set parameters for the lmfit model using the lmfit Parameters object.
- Parameters:
fit_params (
Parameters) – Fit parameter object.NAME (
str) – Parameter name.VALUE (
Optional[float]) – Optional. Initial value. The default is None, in which case no value is set.VARY (
bool) – Vary flag. The default is True, in which case the parameter is free to vary.LIMITED (
Optional[ArrayLike]) – Whether or not to limit the parameter. The default, None, is to set no limits.TIED (
Optional[str]) – Expression for tying the parameter to another. The default is None.LIMITS (
Optional[ndarray]) – Limits for the parameter. The default is None, in which case no limits are set.
- Return type:
- Returns:
Parameters – Modified fit parameter object.
linelist
- q3dfit.linelist.linelist(inlines=None, linelab=True, waveunit='micron', vacuum=True)[source]
Generates an astropy Table of lines from the master files provided in /data/linelist. No required parameters; by default the entire tables are read from the linelist_air.tbl and linelist_vac.tbl, recomputed into vacuum and returned
- Parameters:
inlines (
Optional[list]) – Optional. A list of strings to match against the ‘name’ part of the master list to return only the lines requested. Default is None, which returns all lines in the master list.linelab (
bool) – Optional. Whether to return the Tex-friendly labels for the lines. Default is True.vacuum (
bool) – Optional. Whether to return wavelengths in vacuum (returns air wavelengths if false); conversion is equation 3 from Morton et al. 1991 ApJSS 77 119. Default is True.waveunit (
Literal['micron','Angstrom']) – Optional. Output wavelength unit of ‘Angstrom’ or ‘micron’. Default is ‘micron’.
- Return type:
- Returns:
Table – Columns ‘name’, ‘linelab’, ‘lines’. ‘name’ is the name of the line, ‘linelab’ is the LaTeX-friendly label, and ‘lines’ is the central wavelength in the units requested. Example: ‘Lyalpha’, ‘Ly$alpha$’, 1215.67
Examples
To get the central wavelengths in microns of all lines in Table 2 of Smith et al. 2007 ApJ 656 770 (PAHFIT paper) plus the high-ionization [NeVI] line typical of AGN:
>>> mylist=['H2_00_S7','H2_00_S6','H2_00_S5','[ArII]6.99','[NeVI]7.65','H2_00_S4', ... '[ArIII]8.99','H2_00_S3','[SIV]10.51','H2_00_S2','[NeII]12.81', ... '[NeIII]15.56','H2_00_S1','[SIII]18.71','[OIV]25.89','[FeII]25.99', ... 'H2_00_S0','[SIII]33.48','[SiII]34.82'] >>> u=linelist(mylist)
To get the central wavelengths in microns of the strongest lines in Storchi-Bergmann et al. 2009 MNRAS 394, 1148 (NIFS spectra of AGN):
>>> mylist=['Pae','[SIII]0.9533','HeII1.0126','HeI1.0833','Pag', '[SIX]1.2524', ... '[FeII]1.2570', 'Pab', '[FeII]1.6440', 'Br11', 'Br10','Brg', ... '[SiVII]2.4833'] >>> u=linelist(mylist)
Will return all lines in the catalog with labels and central wavelengths in vacuum in microns:
>>> u=linelist()
Will produce a table of vacuum wavelengths in microns for three lines in the same order as given, and a warning there is a duplicated line in mylist:
>>> mylist=['Paa', 'Halpha', 'Paa'] >>> u=linelist(inlines=mylist)
Will produce a table of air wavelengths in Angstroms for three lines, report that line ‘junk’ is not in the line list, convert to air wavelengths and to microns, complain that H2_00_S0 is outside the validity of the Morton’s formula for vacuum to air conversion, and remove the line lables.
>>> mylist=['Paa', 'Halpha', 'junk', 'H2_00_S0'] >>> u=linelist(inlines=mylist,vacuum=False,waveunit='Angstrom',linelab=False)
To get the central wavelength for an individual feature by name:
>>> wv=np.array(linelist(['Halpha'])['lines'])
OR
>>> u=linelist() >>> wv=np.array(u['lines'][(u['name']=='Halpha')])
plot
- q3dfit.plot.plotcont(q3do, savefig=False, outfile=None, argssavefig={'bbox_inches': 'tight', 'dpi': 300}, questfit=False, q3di=None, compspec=None, complabs=None, compcols=None, title=None, xran=None, yran=None, zeroymin=False, xstyle='lin', ystyle='lin', figsize=(10, 5), waveunit_in='micron', waveunit_out=None, fluxunit_out='flambda', mode='dark')[source]
Created on Tue Jun 1 13:32:37 2021 @author: annamurphree
Plots continuum fit of optical data (fit by fitqsohost or ppxf) or IR data (fit by questfit).
- Parameters:
savefig (
bool) – Optional. If True, saves the plot to a file. Defaults to False.outfile (
Optional[str]) – Optional. Full path and name of output plot. Defaults to None, which means no output file is created.argssavefig (
dict) – Optional. Dictionary of arguments to pass tosavefig(). Defaults to {‘bbox_inches’: ‘tight’, ‘dpi’: 300}.questfit (
bool) – Optional. If True, indicates that the fit is an IR spectrum fit by questfit. Defaults to False.q3di (
Optional[q3din]) – Optional.q3dinobject containing fit initialization. Only needed for IR spectra fit by questfit. Defaults to None.compspec (
Optional[ndarray]) – Optional. Array of component spectra to overplot on continuum data. If None, no components are overplotted.complabs (
Optional[list]) – Optional. List of labels for component spectra. Defaults to None, which means labels are automatically generated as ‘Component 1’, ‘Component 2’, etc.compcols (
Optional[list]) – Optional. List of colors for component spectra. Defaults to None, which means colors are automatically generated as ‘C0’, ‘C1’, etc.title (
Optional[str]) – Optional. Title for the plot. Defaults to None.xran (
Optional[list]) – Optional. Range of x-axis (wavelength) to plot. If None, applies the fitrange attribute ofq3dout.yran (
Optional[list]) – Optional. Range of y-axis (flux) to plot. If None, the y-axis limits are determined automatically based on the data.zeroymin (
bool) – Optional. If True, sets the minimum y-axis value to 0. Defaults to False.xstyle (
Literal['log','lin']) – Optional. Style of x-axis scale, either ‘log’ or ‘lin’. Defaults to ‘lin’.ystyle (
Literal['log','lin']) – Optional. Style of y-axis scale, either ‘log’ or ‘lin’. Defaults to ‘lin’.figsize (
tuple) – Optional. Size of the figure in inches, specified as a tuple (width, height). Defaults to (10, 5).mode (
Literal['dark','light']) – Optional. Plot style, either ‘dark’ or ‘light’. Defaults to ‘dark’. This affects the background color and text color of the plot.waveunit_in (
Literal['micron','Angstrom']) – Optional. Input wavelength unit, either ‘micron’ or ‘Angstrom’. Defaults to ‘micron’.waveunit_out (
Optional[str]) – Optional. Output wavelength unit, either ‘micron’ or ‘Angstrom’. If None, defaults to waveunit_in.fluxunit_out (
Literal['flambda','lambdaflambda','fnu']) – Optional. Output flux unit, either ‘flambda’, ‘lambdaflambda’, or ‘fnu’. Defaults to ‘flambda’. The input flux unit is always ‘flambda’. Choosing ‘lambdaflambda’ multiplies the flux by wavelength (in the units of waveunit_out), and ‘fnu’ multiplies the flux by wavelength^2/c, where c is the speed of light in the units of waveunit_out.
- q3dfit.plot.plotline(q3do, nx=1, ny=1, figsize=(16, 13), line=None, center_obs=None, center_rest=None, waveunit_in='micron', waveunit_out=None, specConv=None, yran=None, zeroymin=False, size=300.0, savefig=False, outfile=None, argssavefig={'bbox_inches': 'tight', 'dpi': 300}, mode='dark')[source]
Plot emission line fit and output to JPG
- Parameters:
q3do (
q3dout) –q3doutobject containing the output of the fit.nx (
int) – Number of columns in the plot grid. Defaults to 1.ny (
int) – Number of rows in the plot grid. Defaults to 1.figsize (
tuple) – Size of the figure in inches, specified as a tuple (width, height).line (
Optional[ArrayLike]) – Optional. List of lines in which to center the subplots. If None, the center of the plot window is determined from center_obs or center_rest.center_obs (
Optional[ArrayLike]) – Optional. List of wavelengths in the observed frame to center the subplots. If None, the center of the plot window is determined from line or center_rest.center_rest (
Optional[ArrayLike]) – Optional. List of wavelengths in the rest frame to center the subplots. If None, the center of the plot window is determined from line or center_obs.waveunit_in (
Literal['micron','Angstrom']) – Optional. Input wavelength unit, either ‘micron’ or ‘Angstrom’. Defaults to ‘micron’.waveunit_out (
Optional[str]) – Optional. Output wavelength unit, either ‘micron’ or ‘Angstrom’. If None, defaults to waveunit_in.specConv (
Optional[spectConvol]) – Optional.spectConvolobject for spectral convolution. If None, no convolution is applied.yran (
Optional[list]) – Optional. Range of y-axis (flux) to plot. If None, the y-axis limits are determined automatically based on the data.zeroymin (
bool) – Optional. If True, sets the minimum y-axis value to 0. Defaults to False.size (
Union[float, ArrayLike]) – Optional. Size of the plot window in Angstroms. If a single float issavefig (
bool) – Optional. If True, saves the plot to a file. Defaults to False.outfile (
Optional[str]) – Optional. Full path and name of output plot. Defaults to None, which means no output file is created.argssavefig (
dict) – Optional. Dictionary of arguments to pass tosavefig(). Defaults to {‘bbox_inches’: ‘tight’, ‘dpi’: 300}.mode (
Literal['dark','light']) – Optional. Plotting mode, either ‘dark’ or ‘light’. Defaults to ‘dark
- q3dfit.plot.plotquest(MIRgdlambda, MIRgdflux, MIRcontinuum, ct_coeff, q3di, zstar=0.0, savefig=True, outfile=None, templ_mask=[], lines=[], linespec=[], show=False, mode='light', ymin=-1, ymax=-1, try_adjust_ax=True, row=-1, col=-1)[source]
Plot the fit to the residual of the quasar-host galaxy decomposition, if refit is done with questfit. This function is presently only called internally by
fitqsohost().Further documentation pending more testing and development.
q3df_helperFunctions
Functions called by q3dfit for single- and multi-threaded
execution.
If called externally (i.e., if we run q3df_helperFunctions.py from the command line),
this script will execute q3df_multiCore on multiple cores using MPI. This script
is called by q3dfit when running in a multi-core environment.
Functions called by q3dfit for single- and multi-threaded
execution.
If called externally (i.e., if we run q3df_helperFunctions.py from the command line),
this script will execute q3df_multiCore on multiple cores using MPI. This script
is called by q3dfit when running in a multi-core environment.
- q3dfit.q3df_helperFunctions.execute_fitloop(nspax, colarr, rowarr, cube, q3di, linelist, specConv, onefit, quiet, core=1, nocrash=False)[source]
Handle the FITLOOP execution. In its own function due to commonality between single- and multi-threaded execution
- Parameters:
nspax (
int) – Number of spaxels to be fitted.colarr (
ndarray[int]) – Array of column #s of spaxels to be fit (0-offset).rowarr (
ndarray[int]) – Array of row #s of spaxels to be fit (0-offset).linelist (
Table) – Emission line labels and rest frame wavelengths, as part of an astropy Table output bylinelist().specConv (
spectConvol) – Instance ofspectConvolspecifying the instrumental spectral resolution convolution.quiet (
bool) – If False, progress messages are written to stdout.onefit (
bool) – If True, only one fit is performed.core (
int) – Optional. Core number for multi-threaded execution. Default is 1.nocrash (
bool) – Optional. If set, the routine will continue with the next spaxel in case of a crash. Default is False.
- q3dfit.q3df_helperFunctions.q3df_oneCore(inobj, cols=None, rows=None, onefit=False, quiet=True, nocrash=False)[source]
q3dfit()calls this function for single-threaded execution. The parameters are passed through fromq3dfit()and on tofitloop().- Parameters:
inobj (
str|q3din) – Either a string with the path to the numpy save file containing the input initialization objectq3din, or the object itself.cols (
Union[int,list,ndarray,None]) – Optional. Column values for spaxels to be fitted. Default is None, which means all columns will be fitted. If a scalar, only that column will be fitted. If a 2-element list or array, the elements are the starting and ending columns to be fitted. Unity-offset values assumed.rows (
Union[int,list,ndarray,None]) – Optional. Row values for spaxels to be fitted. Default is None, which means all rows will be fitted. If a scalar, only that row will be fitted. If a 2-element list or array, the elements are the starting and ending rows to be fitted. Unity-offset values assumed.onefit (
bool) – Optional. If set, only one fit is performed infitloop(). Default is False.quiet (
bool) – Optional. If False, progress messages are written to stdout. Default is True.nocrash (
bool) – Optional. If set, the routine will continue with the next spaxel in case of a crash. Default is False.
- q3dfit.q3df_helperFunctions.q3df_multiCore(rank, size, inobj, cols=None, rows=None, onefit=False, quiet=True, nocrash=False)[source]
Run
fitloopon a single core in a multi-core environment. This function is called byq3df_helperFunctionswhen run externally.q3dfit()callsq3df_helperFunctionsexternally when running in a multi-core environment.- Parameters:
rank (
int) – Rank of this core for MPI execution.size (
int) – Number of cores available for MPI execution.inobj (
str|q3din) – Either a string with the path to the numpy save file containing the input initialization objectq3din, or the object itself.cols (
Optional[list[int]]) – Optional. Column values for spaxels to be fitted. If a single-element list, only that column will be fitted. If a 2-element list, the elements are the starting and ending columns to be fitted. Unity-offset values assumed. Default is None, which means all columns will be fitted.rows (
Optional[list[int]]) – Optional. Row values for spaxels to be fitted. If a single-element list, only that row will be fitted. If a 2-element list, the elements are the starting and ending rows to be fitted. Unity-offset values assumed. Default is None, which means all rows will be fitted.onefit (
bool) – Optional. If True, only one fit is performed infitloop(), instead of two. Default is False.quiet (
bool) – Optional. If False, progress messages are written to stdout. Default is True.
- q3dfit.q3df_helperFunctions.string_to_intList(strArray)[source]
Convert a string of the form “[1, 2, 3, …]” to a list of integers.
- Parameters:
strArray (
str) – The string to be converted. The string is expected to be a list of integers in square brackets, separated by commas; a single integer; or a value starting with ‘N’ to indicate None.- Return type:
- Returns:
intList – A list of integers, or None if the input string started with ‘N’.
q3dmath
- q3dfit.q3dmath.interptemp(spec_lam, temp_lam, template)[source]
(Linearly) interpolate templates from template wavelength grid to data wavelength grid.
- Parameters:
spec_lam (ArrayLike) – Wavelengths of data arrays.
temp_lam (ArrayLike) – Wavelengths of template arrays.
template (ArrayLike) – Model fluxes from templates. Second dimension is the number of templates.
- Return type:
ArrayLike
- Returns:
ArrayLike – The interpolated templates.
- q3dfit.q3dmath.interp_lis(spec_lam, temp_lam_lis, template_lis)[source]
This function samples a single template or list of templates onto the wavelength array of the input observed spectrum. The output is padded with NaN values instead of extrapolating beyond any template’s wavelength range.
- Parameters:
spec_lam (ArrayLike) – reference wavelength array onto which the templates(s) are interpolated
temp_lam_lis (
Union[list[ArrayLike], ArrayLike]) – Template wavelength array or list containing the wavelength arrays of the different templates (not required to be at same length). (Also accepts 1D list, list containing a 1D array, or list of lists)template_lis (
Union[list[ArrayLike], ArrayLike]) – Template flux array or list containing the flux arrays of the different templates (not required to be at same length). (Also accepts 1D list, list containing a 1D array, or list of lists)
- Return type:
- Returns:
numpy.ndarray – Array containing the flux of the templates interpolated onto the spec_lam input array. If 2D, the 2nd dimension corresponds to the flux arrays of individual templates, i.e. the newly sampled flux of template 0 can be accessed as new_temp[:,0], while for template 1 this is new_temp[:,1], etc. The new_temp array is padded with NaN values where the wavelength range of the respective template was more narrow than the observed spectum.
- q3dfit.q3dmath.cutoff_NaNs(spec_lam, new_temp)[source]
This function removes any NaN values from the output of the interp_lis() function.
- Parameters:
spec_lam (ArrayLike) – reference wavelength array onto which the templates(s) are interpolated
new_temp (
ndarray) – 1D or 2D array with newly interpolated template fluxes, corresponding to the output of interp_lis()
- Return type:
- Returns:
new_temp_NoNan – Same as new_temp, but without any NaN elements / rows containing at least one NaN value
q3dutil
Utility functions that are used by multiple modules in the q3dfit package.
- q3dfit.q3dutil.get_q3dio(inobj)[source]
Load initialization or output object. Determine whether it’s already an object, or needs to be loaded from file.
- q3dfit.q3dutil.get_spaxels(ncols, nrows, cols=None, rows=None)[source]
Set up 1D arrays specifying column value and row value for each spaxel to be fitted. These are zero-offset for indexing other arrays.
- Parameters:
ncols (
int) – Total number of columns in the data cube.nrows (
int) – Total number of rows in the data cube.cols (
Union[int,list,ndarray,None]) – Optional. Column values for spaxels to be fitted. Default is None, which means all columns will be fitted. If a scalar, only that column will be fitted. If a 2-element list or array, the elements are the starting and ending columns to be fitted. Unity-offset values assumed.rows (
Union[int,list,ndarray,None]) – Optional. Row values for spaxels to be fitted. Default is None, which means all rows will be fitted. If a scalar, only that row will be fitted. If a 2-element list or array, the elements are the starting and ending rows to be fitted. Unity-offset values assumed.
- Return type:
- Returns:
int – Number of spaxels to be fitted.
np.ndarray[int] – 1D array of column values for spaxels to be fitted.
np.ndarray[int] – 1D array of row values for spaxels to be fitted.
- q3dfit.q3dutil.write_msg(message, file=None, quiet=True)[source]
Write message to log file and/or
stdout().
- class q3dfit.q3dutil.lmlabel(label, reverse=False)[source]
Bases:
objectRemove characters from a label string that are incompatible with LMFIT’s parser; or reverse the operation.
All keys of a Parameters() instance must be strings and valid Python symbol names. This class replaces incompatible characters with valid symbols.
https://lmfit.github.io/lmfit-py/parameters.html#lmfit.parameter.Parameters
qsohostfcn
- q3dfit.qsohostfcn.qso_mult_exp(wave, qsotemplate, a, b, c, d, e, f, g, h, i)[source]
Model exponentials for qso template multiplier
- Parameters:
wave (ArrayLike) – 1-D array of wavelengths
qsotemplate (
ndarray) – 1-D array of the quasar spectrum to be fita (
float) – scale factor for constant termb (
float) – scale factor for exponential decayc (
float) – exponential decay constantd (
float) – scale factor for exponential decay in reversee (
float) – exponential decay constant in reversef (
float) – scale factor for exponential riseg (
float) – exponential rise constanth (
float) – scale factor for exponential rise in reversei (
float) – exponential rise constant in reverse
- Return type:
- Returns:
np.ndarray – Multiplicative factor times the quasar spectrum
- q3dfit.qsohostfcn.setup_qso_mult_exp(p)[source]
Set up model exponentials for qso template multiplier
- Parameters:
p (
ndarray) – list of initial guesses for the exponential fit parameters a-i- Return type:
- Returns:
lmfit.Model – lmfit model for the qso template multiplier
lmfit.Parameters – lmfit parameters for the qso template multiplier
- q3dfit.qsohostfcn.qso_mult_leg(wave, qsotemplate, i, j, k, l, m, n, o, p, q, r)[source]
Model legendre polys for qso template multiplier
- Parameters:
wave (ArrayLike) – 1-D array of wavelengths
qsotemplate (
ndarray) – 1-D array of the quasar spectrum to be fiti (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.j (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.k (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.l (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.m (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.n (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.o (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.p (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.q (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.r (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.
- Return type:
- Returns:
np.ndarray – Multiplicative factor times the quasar spectrum
- q3dfit.qsohostfcn.setup_qso_mult_leg(p)[source]
Set up model legendre polys for qso template multiplier
- Parameters:
p (
ndarray) – list of initial guesses for the exponential fit parameters a-i- Return type:
- Returns:
lmfit.Model – lmfit model for the qso template multiplier
lmfit.Parameters – lmfit parameters for the qso template multiplier
- q3dfit.qsohostfcn.stars_add_leg(wave, i, j, k, l, m, n, o, p, q, r)[source]
Model legendre for additive starlight continuum
- Parameters:
wave (ArrayLike) – 1-D array of wavelengths
i (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.j (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.k (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.l (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.m (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.n (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.o (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.p (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.q (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.r (
float) – scale factors for 1-10 order legendre polynomials. 0th order is the constant term and is set to 0.
- Return type:
- Returns:
np.ndarray – Polynomial model for the additive starlight continuum
- q3dfit.qsohostfcn.setup_stars_add_leg(p)[source]
Set up model legendre for additive starlight continuum
- Parameters:
p (
ndarray) – list of initial guess for the legendre polynomial- Return type:
- Returns:
lmfit.Model – lmfit model for the additive starlight continuum
lmfit.Parameters – lmfit parameters for the additive starlight continuum
- q3dfit.qsohostfcn.stars_add_exp(wave, a, b, c, d, e, f, g, h, i)[source]
Model exponentials for additive starlight continuum
- Parameters:
wave (ArrayLike) – 1-D array of the wavelength to be fit
a (
float) – scale factor for constant termb (
float) – scale factor for exponential decayc (
float) – exponential decay constantd (
float) – scale factor for exponential decay in reversee (
float) – exponential decay constant in reversef (
float) – scale factor for exponential riseg (
float) – exponential rise constanth (
float) – scale factor for exponential rise in reversei (
float) – exponential rise constant in reverse
- Return type:
- Returns:
np.ndarray – Exponential model for the additive starlight continuum
- q3dfit.qsohostfcn.setup_stars_add_exp(p)[source]
Set up model exponentials for additive starlight continuum
- Parameters:
p (
ndarray) – list of initial guess for the legendre polynomial fit- Return type:
- Returns:
lmfit.Model – lmfit model for the additive starlight continuum
lmfit.Parameters – lmfit parameters for the additive starlight continuum
- q3dfit.qsohostfcn.qsohostfcn(wave, params_fit=None, qsoflux=None, qsoonly=False, qsoord=None, hostonly=False, hostord=None, blronly=False, blrpar=None, medflux=None)[source]
Set up or evaluate the model for the QSO and host galaxy featureless continuum fit.
- Parameters:
wave (
ndarray) – 1-D array of wavelengthsparams_fit (
Optional[dict]) – Optional. Dictionary of parameters to evaluate the model. If None, the function returns the lmfit model object and parameter object for fitting. If not None, the function returns the model evaluated at the parameters in params_fit.qsoflux (
Optional[ndarray]) – Optional. 1-D array of the quasar template flux. Only needed if params_fit is not None.qsoonly (
bool) – Optional. Fit/evaluate only the QSO component. Default is False.qsoord (
Optional[int]) – Optional. Order of the Legendre polynomial for the QSO template multiplier. Default is None, which means no Legendre polynomial is used. The maximum order is 10.hostonly (
bool) – Optional. Fit/evaluate only the host galaxy component. Default is False.hostord (
Optional[int]) – Optional. Order of the Legendre polynomial for the host galaxy template multiplier. Default is None, which means no Legendre polynomial is used. The maximum order is 10.blronly (
bool) – Optional. Fit/evaluate only the scattered-light broad line region component. Default is False.blrpar (
Optional[ArrayLike]) – Optional. Array of parameters for the broad line region model. Only needed if scattered light broad line region component is included. Default is None. Must be in the form [amplitude, center, sigma, amplitude, center, sigma, …], where each set of three parameters is for a single Gaussian component. The center is not varied in the fit, and the bounds on the sigma are set to 2000 and 6000 km/s.medflux (
Optional[float]) – Optional. Estimate for the continuum level for setting initial guesses. Default is None, which sets the continuum level to 1.
- Return type:
tuple[Optional[ndarray],Optional[Model],Optional[Parameters]]- Returns:
tuple – If params_fit is not None, returns a tuple of the evaluated model, None, None. If params_fit is None, returns a tuple of None, the lmfit model object, and the lmfit parameters object.
questfitfcn
- q3dfit.questfitfcn.set_up_fit_blackbody_model(p, p_fixfree, name)[source]
Function defined to set up fitting blackbody_model within lmfit
- Parameters:
p (
list) – List of initial guesses for the normalization and T of the blackbody model fit. Limits on the temperature are set to 50-3000 K. Lower limit on the normalization is the minimum positive float value.p_fixfree (
list) – List of fix/free values (0/1) for the blackbody model parameters.name (
str) – Name of the blackbody model, for labeling.
- Return type:
- Returns:
blackbody_model_model (lmfit model)
blackbody_model_paramters (lmfit model parameters)
- q3dfit.questfitfcn.set_up_fit_powerlaw_model(p, p_fixfree, name)[source]
Set up fitting powerlaw_model within lmfit.
- Parameters:
p (ArrayLike) – List of initial guesses for the normalization and exponent of the powerlaw model fit. The lower limit on the normalization is the minimum positive float value.
p_fixfree (ArrayLike) – List of fix/free values (0/1) for the powerlaw model parameters.
- Return type:
- Returns:
lmfit.Model
lmfit.Parameters
- q3dfit.questfitfcn.set_up_fit_model_scale(p, p_fixfree, model_name, model, maxamp=None)[source]
Set up fitting model_scale within lmfit
- Parameters:
p (ArrayLike) – List containing initial guess for the scale factor. The lower limit on the scale factor is the minimum positive float value. If maxamp is not None, the upper limit is set to maxamp.
p_fixfree (ArrayLike) – List containing fix/free value (0/1) for the scale factor.
model_name (
str) – Name of the scaled model.model (
str) – Name of the model to be scaled.maxamp (
Optional[float]) – Optional. Maximum value for the scale factor. If None, the maximum value is not set.
- Return type:
- Returns:
lmfit.Model
lmfit.Parameters
- q3dfit.questfitfcn.set_up_absorption(p, p_fixfree, model_name, abs_model)[source]
Set up fitting ice absorption model within lmfit.
- Parameters:
p (ArrayLike) – List containing initial guess for the tau of the absorption model. The lower limit on tau is the minimum positive float value, and the upper limit is 10.
p_fixfree (ArrayLike) – List containing fix/free value (0/1) for tau.
model_name (
str) – Name for the output model.abs_model (
str) – Name of the absorption model with values of tau.
- Return type:
- Returns:
lmfit.Model
lmfit.Parameters
- q3dfit.questfitfcn.set_up_fit_extinction(p, p_fixfree, model_name, extinction_model, mixed_or_screen)[source]
Set up extinction fit.
- Parameters:
p (ArrayLike) – List containing initial guess for A_V. The lower limit on A_V is the minimum positive float value, and the upper limit is 100.
p_fixfree (ArrayLike) – List containing fix/free value (0/1) for A_V.
model_name (
str) – Name for extincted model.extinction_model (
str) – Name of extinction curve containing values A_lambda.mixed_or_screen (
Literal['M','S']) – ‘M’ for mixed model, ‘S’ for screen model.
- Return type:
- Returns:
lmfit.Model
lmfit.Parameters