API Reference

NIRDust: Near Infrared Dust Finder.

NIRDust is a python package that uses K-band (2.2 micrometers) spectra to measure the temperature of the dust heated by an Active Galactic Nuclei (AGN) accretion disk.

nirdust.core module

Core functionalities for NIRDust.

class nirdust.core.NirdustSpectrum(spectral_axis, flux, z=0, metadata=_Nothing.NOTHING, noise=_Nothing.NOTHING)[source]

Bases: object

Class containing a spectrum to operate with Nirdust.

Stores the flux and wavelength axis of the spectrum in a Spectrum1D object and provides various methods for obtaining the dust component and perform blackbody fitting. The flux parameter recieves either flux-calibrated intensity or non flux-calibrated intensity, in both cases Nirdust will assign ‘ADU’ units to it.

Parameters:
  • flux (~numpy.ndarray, or ~astropy.units.Quantity) – Spectral intensity.

  • frequency_axis (~numpy.ndarray, or ~astropy.units.Quantity) – Spectral axis in units of Hz.

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

  • metadata (mapping, optional) – Any dict like object. This is a good place to store the header of the fits file or any arbitrary mapping. Internally NirdustSpectrum wraps the object inside a convenient metadata object usefull to access the keys as attributes.

spec1d_

Contains the wavelength axis and the flux axis of the spectrum in unities of Å and ADU respectively.

Type:

specutils.Spectrum1D object

noise

A value of the uncertainty representative of all the spectral range. If the value of noise is not provided, Nirdust will compute it by default using noise_region_uncertainty from Astropy inside the region 20650 - 21000 Å. The user can re-compute noise using the class method compute_noise.

Type:

float.

compute_noise(low_lim=20650, upper_lim=21000)[source]

Compute noise for the spectrum.

Uses noise_region_uncertainty from Astropy to compute the noise of the spectrum inside a Spectral Region given by the low_lim and upper_lim parameters.

Parameters:
  • low_lim (float) – A float containing the lower limit for the region where the noise will be computed. Must be in Å. Default is 20650.

  • upper_lim (float) – A float containing the lower limit for the region where the noise will be computed. Must be in Å. Default is 21000.

Returns:

A new instance of NirdustSpectrum class with the new noise parameter.

Return type:

NirdustSpectrum object

convert_to_frequency()[source]

Convert the spectral axis to frequency in units of Hz.

Returns:

out – New instance of the NirdustSpectrun class containing the spectrum with a frquency axis in units of Hz.

Return type:

object NirsdustSpectrum

cut_edges(mini, maxi)[source]

Cut the spectrum in wavelength range.

Parameters:
  • mini (float) – Lower limit to cut the spectrum.

  • maxi (float) – Upper limit to cut the spectrum.

Returns:

out – Return a new instance of class NirdustSpectrum cut in wavelength.

Return type:

NirsdustSpectrum object

property frequency_axis

Frequency axis access.

mask_spectrum(line_intervals=None, mask=None)[source]

Mask spectrum to remove spectral lines.

Recives either a boolean mask containing False values in the line positions or a list with the line positions as given by the line_spectrum method of the NirdustSpectrum class. This method uses one of those imputs to remove points from the spectrum.

Parameters:
  • line_intervals (python iterable) – Any iterable object with pairs containing the beginning and end of the region were the spectral lines are. The second return of line_spectrum is valid.

  • mask (boolean array) – array with same length as the spectrum containing boolean values with False values in the indexes that should be masked.

Returns:

A new instance of NirdustSpectrum class with the especified intervals removed.

Return type:

NirdustSpectrum object

normalize()[source]

Normalize the spectrum to the unity using the mean value.

Returns:

out – New instance of the NirdustSpectrun class with the flux normalized to unity.

Return type:

NirsdustSpectrum object

property spectral_dispersion

Assume linearity to compute the spectral dispersion.

property spectral_length

Total number of spectral data points.

property spectral_range

First and last values of spectral_axis.

nirdust.core.public_members_asdict(object)[source]

Thin wrapper around attr.asdict, that ignore all private members.

nirdust.preprocessing module

Collection of preprocessing utilities.

nirdust.preprocessing.line_spectrum(spectrum, noise_factor=3, window=50)[source]

Construct the line spectrum.

Uses various Specutils features to fit the continuum of the spectrum, subtract it and find the emission and absorption lines. Then fits all the lines with gaussian models to construct the line spectrum using astropy.models.Gaussian1D.

Parameters:
  • spectrum (NirdustSpectrum object) – A spectrum stored in a NirdustSpectrum class object.

  • noise_factor (float) – Same parameter as in specutils.fitting.find_lines_threshold. Factor multiplied by the spectrum’s`uncertainty`, used for thresholding. Default is 3.

  • window (float) – Same parameter as in specutils.fitting.fit_lines. Width of the region around each line of the spectrum to use in the fitting. If None, then the whole spectrum will be used in the fitting. Window is used in the Gaussian fitting of the spectral lines. Default is 50 (Å).

Returns:

out – Returns in the first element a NirdustSpectrum of the same lenght as the original spectrum containing the fitted lines. In the 2nd position, returns the intervals where those lines were found determined by 3-sigma values around the center of the line.

Return type:

NirdustSpectrum, Quantity

nirdust.preprocessing.match_spectral_axes(first_sp, second_sp, scaling='downscale', clean=True)[source]

Resample the higher resolution spectrum.

Spectrum_resampling uses the spectral_axis of one imput spectrum to resample the spectral_axis of the otherone, depending on the scaling parameter. To do so this function uses the FluxConservingResampler class of Specutils. The order of the input spectra is arbitrary and the order in the output is the same as in the input. It is recomended to run this function after the class methods ‘cut_edges’ and ‘mask_spectrum’.

Parameters:
  • first_sp (NirdustSpectrum object) –

  • second_sp (NirdustSpectrum object) –

  • scaling (string) – If downscale the higher resolution spectrum will be resampled to match the lower resolution spectrum. If upscale the lower resolution spectrum will be resampled to match the higher resolution spectrum.

  • clean (bool) – Flag to indicate if the spectrums have to be cleaned by nan values after the rescaling procedure. nan values occur at the edges of the resampled spectrum when it is forced to extrapolate beyond the spectral range of the reference spectrum.

Returns:

out

Return type:

NirdustSpectrum, NirdustSpectrum

nirdust.bbody module

Blackbody/temperature utilities.

class nirdust.bbody.BasinhoppingFitter(target_spectrum, external_spectrum, basinhopping_kwargs)[source]

Bases: object

Basinhopping fitter class.

Fit a BlackBody model to the data using scipy modeling methods.

target_spectrum

Instance of NirdustSpectrum containing the central spectrum.

Type:

NirdustSpectrum object

external_spectrum

Instance of NirdustSpectrum containing the external spectrum.

Type:

NirdustSpectrum object

basinhopping_kwargs

Dictionary of keyword arguments to be passed to the scipy basinhopping routine. Read the documentation for a detailed description: docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.basinhopping.html

Type:

dict

fit(x0, minimizer_kwargs)[source]

Start fitting computation.

Parameters:
  • x0 (tuple) – Vector indicating the initial guess values in order, i.e: (T, alpha, beta, gamma). Default: (1000.0, 8.0, 9.0, -5.0)

  • minimizer_kwargs (dict) – Extra keyword arguments to be passed to the local minimizer.

Returns:

results – Results of the fitting procedure.

Return type:

NirdustResult object

property ndim_

Return number of fittable parameters.

run_model(x0, minimizer_kwargs)[source]

Run fitter given an initial guess.

Parameters:
  • x0 (tuple) – Vector indicating the initial guess values in order, i.e: (T, alpha, beta, gamma). Default: (1000.0, 1.0, 1.0, 1.0)

  • minimizer_kwargs (dict) – Extra keyword arguments to be passed to the local minimizer.

Returns:

results – Results of the local minimizer.

Return type:

OptimizeResult object

exception nirdust.bbody.ConvergenceWarning[source]

Bases: RuntimeWarning

Raised when the fitting procedure failed to converge.

class nirdust.bbody.NirdustParameter(name, value, uncertainty=None)[source]

Bases: object

Parameter representation.

name

Parameter name.

Type:

str

value

Expected value for parameter after fitting procedure.

Type:

scalar, ~astropy.units.Quantity

uncertainty

Uncertainties associated to the fitted value.

Type:

scalar, ~astropy.units.Quantity

class nirdust.bbody.NirdustResults(temperature, alpha, beta, gamma, fitted_blackbody, target_spectrum, external_spectrum, minimizer_results)[source]

Bases: object

Create the class NirdustResults.

Storages the results obtained with BasinhoppingFitter plus the dust spectrum. The method plot() can be called to plot the spectrum and the blackbody model obtained in the fitting.

temperature

Parameter object with the expected blackbody temperature and its uncertainty.

Type:

NirdustParameter

alpha

Parameter object with the expected alpha value and its uncertainty. Note: No unit is provided as the intensity is in arbitrary units.

Type:

NirdustParameter

beta

Parameter object with the expected beta value and its uncertainty. Note: No unit is provided as the intensity is in arbitrary units.

Type:

NirdustParameter

gamma

Parameter object with the expected gamma value and its uncertainty. Note: No unit is provided as the intensity is in arbitrary units.

Type:

NirdustParameter

fitted_blackbody

BlackBody instance with the best fit value of temperature.

Type:

~astropy.modeling.models.BlackBody

target_spectrum

Instance of NirdustSpectrum containing the central spectrum.

Type:

NirdustSpectrum object

external_spectrum

Instance of NirdustSpectrum containing the external spectrum.

Type:

NirdustSpectrum object

minimizer_results

Instance of OptimizeResult that generates in the fitting procedure.

Type:

OptimizeResult object

plot(axes=None, data_kws=None, model_kws=None, show_components=False)[source]

Build a plot of the fitted spectrum and the fitted model.

Parameters:
  • axes (tuple of matplotlib.pyplot.Axis objects) – Tuple with two objects of type Axes containing complete information of the properties to generate the image, by default it is None.

  • data_kws (dict) – Dictionaries of keyword arguments. Passed to the data plotting function.

  • model_kws (dict) – Dictionaries of keyword arguments. Passed to the model plotting function.

  • show_components (bool) – Flag to indicate if the three components of the model should be plotted.

Returns:

out – The axis where the method draws.

Return type:

matplotlib.pyplot.Axis :

nirdust.bbody.alpha_vs_beta(theta, target_spectrum, external_spectrum)[source]

Alpha term positivity relative to beta term.

Here we assume that: alpha * ExternalSpectrum > 10**beta * BlackBody in mean values.

Parameters:
  • theta (array-like) – Parameter vector: (temperature, alpha, beta, gamma).

  • target_spectrum (NirdustSpectrum object) – Instance of NirdustSpectrum containing the total central spectrum.

  • external_spectrum (NirdustSpectrum object) – Instance of NirdustSpectrum containing the external spectrum.

Returns:

alpha_positivity – The difference between alpha term and beta term mean values, given the data; i.e.: mean(alpha * ExternalSpectrum) - (10**beta * BlackBody)

Return type:

scalar

nirdust.bbody.fit_blackbody(target_spectrum, external_spectrum, x0=None, bounds=None, gamma_target_fraction=0.05, seed=None, niter=200, stepsize=1)[source]

Fitter function.

Fit a BlackBody model to the data using Markov Chain Monte Carlo (MCMC) sampling of the parameter space using the emcee implementation. This function serves as a wrapper around the NirdustFitter class.

Parameters:
  • target_spectrum (NirdustSpectrum object) – Instance of NirdustSpectrum containing the nuclear spectrum.

  • external_spectrum (NirdustSpectrum object) – Instance of NirdustSpectrum containing the external spectrum.

  • x0 (tuple, optional) – Vector indicating the initial guess values of temperature, alpha, beta and gamma.

  • bounds (tuple) – Tuple of 4 pairs of values indicating the minimum and maximum allowed values of the fitted parameters. The order is: T, alpha, beta, gamma. Example: bounds = ((0, 2000), (0, 20), (6, 10), (-10, 0))

  • gamma_target_fraction (float) – Maximum fraction of gamma vs target flux allowed to constraint the gamma value in the fitting procedure. Default: 0.05.

  • seed (int) – Random number generation seed for the basinhopping algorithm.

  • niter (int) – Number of basinhopping iterations. This numbers represents how many times the local minimizer will be excecuted. Default: 200.

  • stepsize (float) – Maximum step size for use in the random displacement of x0 for each basinhopping iteration. Default: 1.0.

Returns:

result – Instance of NirdustResults after the fitting procedure.

Return type:

NirdustResults object

nirdust.bbody.make_constraints(args, gamma_fraction)[source]

Make scipy minimizer constraints.

Parameters:
  • args (tuple) – Extra arguments to be passed to likelihood and model functions. args = (target_spectrum, external_spectrum)

  • gamma_fraction (float) – Maximum fraction allowed to constraint the gamma value in the fitting procedure.

Returns:

contraints – Constraints as required by the scipy SLSQP minimizer.

Return type:

tuple

nirdust.bbody.make_gamma_vs_target_flux(gamma_fraction)[source]

Encapsulate gamma_fraction for gamma constraint function.

Parameters:

gamma_fraction (scalar) – Value between [0, 1] representing the maximum fraction of Target flux allowed for the gamma term.

Returns:

gamma_vs_target_flux – Function that computes the gamma term positivity relative to the total target flux. Call signature: gamma_vs_target_flux(theta, target_spectrum, external_spectrum)

Return type:

function

nirdust.bbody.make_minimizer_kwargs(args, bounds, constraints, options=None)[source]

Make scipy minimizer keyword arguments.

Parameters:
  • args (tuple) – Extra arguments to be passed to likelihood and model functions. args = (target_spectrum, external_spectrum)

  • bounds (tuple) – Tuple of 4 pairs of values indicating the minimum and maximum allowed values of the fitted parameters. The order is: T, alpha, beta, gamma. Example: bounds = ((0, 2000), (0, 20), (6, 10), (-10, 0))

  • contraints (tuple) – Constraints as required by the scipy SLSQP minimizer.

  • options (dict) – Extra options to be passed to the local minimizer through the options keyword. Default: {“maxiter”: 1000}

nirdust.bbody.negative_gaussian_log_likelihood(theta, target_spectrum, external_spectrum)[source]

Negative Gaussian logarithmic likelihood.

Compute the negative likelihood of the model represented by the parameter theta given the data. The negative sign is added for minimization purposes, i.e. finding the maximum likelihood parameters is the same as minimizing the negative likelihood.

Parameters:
  • theta (array-like) – Parameter vector: (temperature, alpha, beta, gamma).

  • target_spectrum (NirdustSpectrum object) – Instance of NirdustSpectrum containing the total central spectrum.

  • external_spectrum (NirdustSpectrum object) – Instance of NirdustSpectrum containing the external spectrum.

Returns:

loglike – Negative logarithmic likelihood for parameter theta.

Return type:

scalar

nirdust.bbody.target_model(external_spectrum, T, alpha, beta, gamma)[source]

Compute the expected spectrum given a blackbody prediction.

Parameters:
  • external_spectrum (NirdustSpectrum object) – Instance of NirdustSpectrum containing the external spectrum.

  • T (float) – BlackBody temperature in Kelvin.

  • alpha (float) – Multiplicative coefficient for external_flux.

  • beta (float) – Multiplicative coefficient for blackbody.

  • gamma (float) – Additive coefficient.

Returns:

prediction – Expected flux given the input parameters.

Return type:

~numpy.ndarray

nirdust.io module

NIRDust Input/Output.

exception nirdust.io.HeaderKeywordError[source]

Bases: KeyError

Raised when header keyword not found.

nirdust.io.infer_fits_science_extension(hdulist)[source]

Auto detect fits science extension using the provided keywords.

Parameters:

hdulist (~astropy.io.fits.HDUList) – Object containing the FITS extensions.

Returns:

extensions – Array with the science extensions indeces in the hdulist.

Return type:

~numpy.array

nirdust.io.pix2wavelength(pix_arr, header, z=0)[source]

Transform pixel to wavelength.

This function uses header information to perform WCS transformation.

Parameters:
  • pix_arr (float or ~numpy.ndarray) – Array of pixels values.

  • header (FITS header) – Header of the spectrum.

  • z (float) – Redshift of object. Use for the scale factor 1 / (1 + z).

Returns:

wavelength – Array with the spectral axis.

Return type:

~numpy.ndarray

nirdust.io.read_fits(file_name, extension=None, z=0)[source]

Read a spectrum in FITS format and store as a NirdustSpectrum object.

Parameters:
  • file_name (str) – Path to where the fits file is stored.

  • extension (int or str) – Extension of the FITS file where the spectrum is stored. If None the extension will be automatically identified by searching relevant header keywords. Default is None.

  • z (float) – Redshift of the galaxy. Used to scale the spectral axis with the cosmological sacle factor 1/(1+z). Default is 0.

Returns:

out – Returns an instance of the class NirdustSpectrum.

Return type:

NirsdustSpectrum object

nirdust.io.read_table(file_name, wavelength_column=0, flux_column=1, format='ascii', z=0, **kwargs)[source]

Read a spectrum from a table and store it in a NirdustSpectrum object.

The table must contain two columns for the wavelength and the intensity/flux, the column number can be specified by parameters. It is assumed that the unit of the wavelength axis is Å.

Parameters:
  • file_name (str) – Path to where the fits file is stored.

  • wavelength_column (int) – The positional number of the wavelengh column. Default is 0.

  • flux_column (int) – The positional number of the intensity/flux column. Default is 1.

  • kwargs – Args from``astropy.table.Table.read``.

Returns:

out – Returns an instance of the class NirdustSpectrum.

Return type:

NirsdustSpectrum object

nirdust.io.spectrum(flux, header, z=0)[source]

Instantiate a NirdustSpectrum object from FITS parameters.

Parameters:
  • flux (~astropy.units.Quantity) – Intensity for each pixel in arbitrary units.

  • header (FITS header) – Header of the spectrum.

  • z (float) – Redshif of the galaxy.

Returns:

spectrum – Return a instance of the class NirdustSpectrum with the entered parameters.

Return type:

NirsdustSpectrum