specex.utils module

SPECEX - SPECtra EXtractor.

This module provides utility functions used by other specex modules.

Copyright (C) 2022-2023 Maurizio D’Addona <mauritiusdadd@gmail.com>

class specex.utils.ScaleBar(ax, x0=0.025, y0=0.025, length=1, size=0.025, orientation='hor', n_subunits=2, text=None, fontsize=8, units='arcsec', scale_factor=1)[source]

A simple scalebar.

set_wcs(wcs)[source]

Set the WCS.

Parameters

wcsastropy.wcs.WCS

The WCS to use.

Returns

None.

update()[source]

Update the ScaleBar.

Returns

None.

specex.utils.find_prog(prog)[source]

Find the path of a pregram in your PATH.

Parameters

progstr

Name of the program.

Returns

str

The path of the program.

specex.utils.get_aspect(ax)[source]

Get ratio between y-axis and x-axis of a matplotlib figure.

Parameters

axmatplotlib.axes._subplots.AxesSubplot

Ther axis you want to get the axes ratio.

Returns

ratiofloat

The aspect ratio.

specex.utils.get_ellipse_skypoints(center: ~astropy.coordinates.sky_coordinate.SkyCoord, a: ~astropy.units.quantity.Quantity, b: ~astropy.units.quantity.Quantity, angle: ~astropy.units.quantity.Quantity = <Quantity 0. deg>, n_points: int = 20) → list[source]

Get points of an ellips on the skyplane.

Parameters

centerastropy.coordinates.SkyCoord

DESCRIPTION.

aapu.quantity.Quantity

Angular size of the semi-major axis.

bapu.quantity.Quantity

Angular size of the semi-mino axis.

angleapu.quantity.Quantity, optional

Rotation angle of the semi-major axis respect to the RA axis. The default is 0 deg.

n_pointsint, optional

Number of points to return. The default is 25.

Returns

ellipse_pointslist of coordinates.SkyCoord

List of SkyCoord corresponding to the points of the ellipse.

Example

>>> import numpy as np
>>> from matplotlib import pyplot as plt
>>> from astropy.io import fits
>>> from astropy.wcs import WCS
>>> from astropy.wcs.utils import wcs_to_celestial_frame
>>> from astropy.coordinates import SkyCoord
>>> from astropy import units as apu
>>> from astropy.utils.data import get_pkg_data_filename
>>> from specex.utils import get_ellipse_skypoints
>>> fn = get_pkg_data_filename('galactic_center/gc_msx_e.fits')
>>> image = fits.getdata(fn, ext=0)
>>> w = WCS(fits.getheader(fn, ext=0))
>>> ellipse_center = w.pixel_to_world(50, 60)
>>> a = 10 * apu.arcmin
>>> b = 5 * apu.arcmin
>>> angle = 45 * apu.deg
>>> world_points = get_ellipse_skypoints(
...     center=ellipse_center,
...     a=a, b=b,
...     angle=angle
... )
>>> pp_val = np.array([
...     [x.l.value, x.b.value] for x in world_points
... ])
>>> fig = plt.figure()
>>> ax = fig.add_subplot(projection=w)
>>> ax.imshow(
...     image,
...     vmin=-2.e-5,
...     vmax=2.e-4,
...     origin='lower',
...     cmap='plasma'
... )
>>> ax.plot(
...     pp_val[..., 0], pp_val[..., 1],
...     color='#31cc02',
...     lw=2,
...     ls='--',
...     transform=ax.get_transform(wcs_to_celestial_frame(w))
... )
>>> ax.set_aspect(1)
>>> plt.show()
>>> plt.close(fig)
specex.utils.get_log_img(img, vclip=0.5)[source]

Get the image in log scale.

Parameters

imgnumpy.ndarray

The image data.

vclipfloat, optional

Contrast factor. The default is 0.5.

Returns

log_imagenumpy.ndarray

The logarithm of the input image.

vclip2-tuple of floats

The median +- vclip*std of the image.

specex.utils.get_mask_intervals(mask)[source]

Get intervals where mask is True.

Parameters

masknumpy.ndarry

The mask array.

Returns

regionslist of 2-tuples

List of intervals.

Example

>>> mask = (0, 0, 0, 0 ,0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1 ,0 ,0)
>>> get_mask_intervals(mask)

[(5, 8), (10, 11), (14, 19)]

specex.utils.get_pbar(partial, total=None, wid=32, common_char='█', upper_char='▄', lower_char='▀')[source]

Return a nice text/unicode progress bar showing partial and total progress.

Parameters

partialfloat

Partial progress expressed as decimal value.

totalfloat, optional

Total progress expresses as decimal value. If it is not provided or it is None, than partial progress will be shown as total progress.

widint , optional

Width in charachters of the progress bar. The default is 32.

Returns

pbarstr

A unicode progress bar.

specex.utils.get_sdss_spectral_templates(outdir: str, use_cached: bool = True) → list[source]

Download spectral templates from SDSS.

Parameters

outdirstr

Path where to save the templates.

use_cachedbool, optional

If true, do not redownload the package file if it is still present. Default is True.

Returns

templateslist

A a list of dictionaries that have the following structure:

‘file’str

The path of the actual template file

‘type’str

The type of template. Can be ‘star’, ‘galaxy’ or ‘qso’

‘sub-type’str

The sub-type of the object

specex.utils.get_sdss_template_data(sdss_template_file: str) → dict[source]

Get spectrum from a SDSS spectral template file.

Parameters

sdss_template_filestr

Path of a SDSS spectral template file.

Returns

t_dictdict
A dictionary contatining the following keys and values:
‘flux’numpy.ndarray 1D

The flux data in arbitrary units

‘wavelengths’numpy.ndarray 1D

The wavelengths

specex.utils.get_spectrum_snr(flux: ndarray, var: ndarray | None = None, smoothing_window: int | None = 51, smoothing_order: int | None = 11)[source]

Compute the SRN of a spectrum.

Parameters

fluxnumpy.ndarray

The spectrum itself.

varnumpy.ndarray, optional

The variance of the spectrum itself. The default value is None.

smoothing_windowint, optional

Parameter to be passed to the smoothing function. The default is 51.

smoothing_orderint, optional

Parameter to be passed to the smoothing function. The default is 11.

Returns

sn_specfloat

The SNR of the spectrum.

specex.utils.get_spectrum_snr_emission(flux, var=None, bin_size=150)[source]

Compute the SRN of a spectrum considering emission lines only.

Parameters

fluxnumpy.ndarray

The spectrum itself.

bin_sizeint, optional

Bin size to search for emission lines. The default is 50.

Returns

sn_specfloat

The SNR of the spectrum.

specex.utils.get_vclip(img, vclip=0.25, nsamples=1000)[source]

Get the clipping values to use with imshow function.

Parameters

imgnumpy.ndarray

Image data.

vclipfloat, optional

Contrast parameter. The default is 0.5.

Returns

vminfloat

median - vclip*std.

vmaxfloat

median + vclip*std.

specex.utils.load_rgb_fits(fits_file, ext_r=1, ext_g=2, ext_b=3)[source]

Load an RGB image from a FITS file.

Parameters

fits_filestr

The path of the fits file.

ext_rint, optional

The index of the extension containing the red channel. The default is 1.

ext_gint, optional

The index of the extension containing the green channel. The default is 2.

ext_bint, optional

The index of the extension containing the blue channel. The default is 3.

Returns

dict
The dictionary contains the following key: value pairs:
‘data’: 3D numpy.ndarray

The actual image data.

‘wcs’: astropy.wcs.WCS

The WCS of the image.

specex.utils.log_rebin(wave, spec_list, oversample=1, flux_conserving=False)[source]

Logarithmically rebin a spectrum conserving the flux.

Parameters

wavelist or numpy.ndarray

The wavelengths of the originaò dispersion grating.

spec_listlist

A list of numpy.ndarrays corrsponding toe the fulx or other quantities to be rebinned with the dispersion grating.

oversampleint, optional

Whether to oversample the new dispersion grating. The default is 1.

flux_conservingbool, optional

If False conserve the flux density instead of the flux. The default is False.

Raises

ValueError

If wave is not monotonically increasing or if it does not have the same dimension of the fluxes.

Returns

rebinned_spec_listlist

A list containing the rebinned input fluxes.

log_wavenumpy.ndarray

The log-reminned disperions grating.

velscalefloat

The velocity scale of the new dispersion grating.

specex.utils.loop_print(text, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, end=None)[source]

Print a single line of text.

This function can be used to print a row of text that should be overwritten in a next iteration.

Remember to use loop_print.reset() before a new loop.

Parameters

textTYPE

DESCRIPTION.

fileTYPE, optional

DESCRIPTION. The default is sys.stdout.

Returns

None.

specex.utils.nannmad(x, scale=1.48206, axis=None)[source]

Compute the MAD of an array.

Compute the Median Absolute Deviation of an array ignoring NaNs.

Parameters

xnp.ndarray

The input array.

scalefloat, optional

A costant scale factor that depends on the distributuion. See https://en.wikipedia.org/wiki/Median_absolute_deviation. The default is 1.4826.

axisint or None

The axis along which to compute the MAD. The default is None.

Returns

nmad

The NMAD value.

specex.utils.parse_regionfile(regionfile, key_ra='ALPHA_J2000', key_dec='DELTA_J2000', key_id='NUMBER', file_format='ds9')[source]

Parse a regionfile and return an asrtopy Table with sources information.

Note that the only supported shape are ‘circle’, ‘ellipse’ and ‘box’, other shapes in the region file will be ignored. Note also that ‘box’ is treated as the bounding box of an ellipse.

Parameters

regionfilestr

Path of the regionfile.

pixel_scalefloat or None, optional

The pixel scale in mas/pixel used to compute the dimension of the size of the objects. If None, height and width in the region file will be considered already in pixel units.

key_rastr, optional

Name of the column that will contain RA of the objects. The default value is ‘ALPHA_J2000’.

key_decstr, optional

Name of the column that will contain DEC of the objects The default value is ‘DELTA_J2000’.

file_formatstr, optional

Format of the input regionfile. The default value is ‘ds9’.

Returns

sourcesastropy.table.Table

The table containing the sources.

skyframeNone

Placeholder.

specex.utils.plot_lines(ax, wave_range, lw=0.7, lines_z=0, label_size='medium', colors=['green', 'red', 'yellow'], label_y=0.02, alpha=[0.5, 0.75, 0.9], ls=['--', '--', '--'], label_rotation=90)[source]

Plot emission and/or absorption lines.

Parameters

axmatplotlib Axes

The Axes where to draw the lines.

wave_rangeliat or numpy.ndarray

wavelength range.

lwfloat, optional

width of the plotted lines. The default is 0.7.

lines_zfloat, optional

The redshift. The default is 0.

label_sizefloat or str, optional

The size of the labels. The deafult value is ‘medium’.

colorslist of 3 colors, optional

The color used to draw the different type of lines. The first color is assinged to absorption lines, the second one to emission lines and the third one to lines that can be both absoprtion and emission. The default value is [‘green’, ‘red’, ‘yellow’].

label_yfloat, optional

The position of the labels in axis-coordinates. The default value is 0.02

alphalist of 3 floats, optional

The value of the alpha transparence used to draw the lines. The order is the same of the colors array. The default value is [0.5, 0.75, 0.9].

lslist of 3 line styles, optional

Styles used to plot lines. The order is the same of the colors array. The default value is [’–’, ‘–’, ‘–‘]

label_rotationfloat, optional

The rotation in degrees of the labels. The default value is 90

Returns

None.

specex.utils.plot_masked_regions(ax, wavelengths, nan_mask, wave_range=None, label_min_wid=100)[source]

Plot a mask over a region containing missing data.

Parameters

axTYPE

DESCRIPTION.

wavelengthsTYPE

DESCRIPTION.

nan_maskTYPE

DESCRIPTION.

wave_rangeTYPE, optional

DESCRIPTION. The default is None.

label_min_widintm optional

The default value is 100.

Returns

region_patchesdict

DESCRIPTION.

specex.utils.plot_scandata(target, scandata)[source]

Plot debugging information about zchi2.

Parameters

targetredrock.Target

The target object.

scandatadict

The full scandata as returned by redrock.

Returns

figmatplotlib.pyplot.Figure

The figure of the plot.

axTYPE

The main axis of the plot.

specex.utils.plot_spectrum(wavelengths, flux, variance=None, nan_mask=None, restframe=False, cutout=None, cutout_vmin=None, cutout_vmax=None, cutout_wcs=None, redshift=None, smoothing=None, wavelengt_units=None, flux_units=None, extra_info={}, extraction_info={}, wave_range=None, show_legend=True, axs=None)[source]

Plot a spectrum.

Parameters

wavelengthsnumpy.ndarray 1D

An array containing the wavelengths.

fluxnumpy.ndarray 1D

An array containing the fluxes corresponding to the wavelengths.

variancenumpy.ndarray 1D, optional

An array containing the variances corresponding to the wavelengths. If it is None, then the variance is not plotted. The default is None.

nan_masknumpy.ndarray 1D of ndtype=bool, optional

An array of dtype=bool that contains eventual invalid fluxes that need to be masked out (ie. nan_mask[j] = True means that wavelengths[j], flux[j] and variance[j] are masked). If it is None, then no mask is applyed. The default is None.

restframebool, optional

If True, then the spectrum is plotted in the observer restframe (ie. the spectrum is de-redshifted before plotting). In order to use this option, a valid redshift must be specified. The default is False.

cutoutnumpy.ndarray 2D or 3D, optional

A grayscale or RGB image to be shown alongside the spectrum. If None, no image is shown. The default is None.

cutout_wcsastropy.wcs.WCS, optional

An optional WCS for the cutout. The default is None.

cutout_vminfloat, optional

The value to be interpreted as black in the cutout image. If it is None, the value is determined automatically. The default is None.

cutout_vmaxfloat, optional

The value to be interpreted as white in the cutout image. If it is None, the value is determined automatically. The default is None.

redshiftfloat, optional

The redshift of the spectrum. If None then no emission/absorption line is plotted and restframe option is ignored. The default is None.

smoothingint or None, optional

If an integer greater than zero is passed to this parameter, then the value is used as the window size of scipy.filter.savgol_filter used to smooth the flux of the spectum. If this value is 0 or None then no smoothing is performed. The default is None.

wavelengt_unitsstr, optional

The units of the wavelengths. The default is None.

flux_unitsstr, optional

The units of the fluxes. The default is None.

extra_infodict of {str: str, …}, optional

A dictionary containing extra information to be shown in the plot. Both keys and values of the dictionary must be strings. This dict is rendered as a table of two columns filled with the keys and the values. The default is {}.

extraction_info: dict, optionale

This dictionary must contain extraction information from specex. If not empty or None, extraction information are used to plot the apertures used by specex over the cutout (if provided). The default is {}.

wave_range: list, optional

Range of wavelengths to plot. The default value is None.

show_legend: bool, optional

Show the legend if true. Default value it True.

axs: list of matplotlib.axes._subplots.AxesSubplots, optional

List of axes to use for plotting. If none a new figure with the appropriate axes is created. The default value is None.

Returns

figmatplotlib.figure.Figure

The figure containing the plots.

axs: list of matplotlib.axes._subplots.AxesSubplots

A list of the axes subplots in the figure.

specex.utils.plot_zfit_check(target, zbest, plot_template=None, restframe=False, wavelengt_units='Angstrom', flux_units='')[source]

Plot the check images for the fitted targets.

This function will plot the spectra of the target object along with the spectra of the best matching tamplate and some other info.

Parameters

targetredrock.targets.Target object

A targets used in redshift estimation process.

zfitastropy.table.Table

A table containing the reshift and other info of the input targets.

plot_templatelist of redrock.templates or None, optional

If not None, plot the best matching tamplate.

rest_framebool, optional

Whether to plot the spectrum at restrframe.

wave_unitsstr, optional

The units of the wavelength grid. The default value id ‘Angstrom’

flux_unitsstr, optional

The units of the spectum. The default value is ‘’.

Returns

figmatplotlib.figure.Figure

The Figure object containing the plot.

axs2-tuple of matplotlib.axes._subplots.AxesSubplot and/or None

List of AxesSubplot. If no cutout was passed in input, the list will contain only the axes of the plot of the spectrum, otherwise two axes will be in the list: the first axes containing the plot of the spectrum and the second axes containing the cutout of the object.

specex.utils.rotate_data(data: ndarray, angle: Quantity, data_wcs: WCS | None = None)[source]

Rotate data by angle and update the optionally given WCS data.

Parameters

datanumpy.ndarray

The data to be rotated.

angleapu.Quantity

The rotation angle.

data_wcsastropy.wcs.WCS or None, optional

A WCS for the data. The default is None.

Returns

dict

A dictionary with the the following keys and values.

  • ‘data’numpy.ndarray

    The rotated data

  • ‘wcs’astropy.wcs.WCS or None

    The updated WCS for the rotated data

specex.utils.simple_pbar_callback(k, total, min_interval=1)[source]

Print a progressbar with a cooldown interval.

Parameters

kfloat

DESCRIPTION.

totalfloat

DESCRIPTION.

min_intervalTYPE, optional

Miniumum interval in seconds between two printings. The default is 1.

Returns

None.

specex.utils.stack(data: ndarray, wave_mask: ndarray | None = None, average: bool = False, quite: bool = False) → ndarray[source]

Stack the spectral cube along wavelength axis.

Parameters

datanumpy.ndarray

The spectral datacube.

wave_masknp.ndarray, optional

1D wavelength mask. Wavelength corresponding to a False will not be used in the stacking. The default is None.

quitebool, optional

Whether to avoid printing a progress bar or not. The default value is False.

Returns

new_datanumpy.ndarray

The stacked datacube.

specex.utils.static_vars(**kwargs)[source]

Add attributes to a function.

Parameters

**kwargsTYPE

Keyword arguments will be added as attributes.

Returns

func

The decorator function.