SpectraPy API

Mathematical utilities

This module contains the class to compute a bilinear interpolation on image

class spectrapy.math.interp.BiLinearInterpolator(data, variance=None)[source]

Class to compute bi-linear interpolation

compute(x: array, y: array)[source]

Interpolate the image along x and y values

Parameters
  • x (array_like, shape(N,)) – The x positions on the image

  • y (array_like, shape(N,)) – The y positions on the image

This module contains function to compute line positions

spectrapy.math.peaks.find_peak_1d(data: array, min_points: int, variance: Optional[array] = None)[source]

Computes the line peak position

Parameters
  • data (np.ma.array, shape(N,)) – The masked data values

  • min_points (int) – The min number of points required to compute the peak position

  • variance (np.array, shape(N,)) – The data variance values

spectrapy.math.peaks.old_find_peak_1d(data, min_points)[source]

Old find peak 1D

This module contains functions for polynomial fitting and evaluation

spectrapy.math.poly.polyfit1d(x, y, deg, var=None, cov=False)[source]

Fits polynomial 1D

Parameters
  • x (array_like, shape(N,)) – X values

  • y (array_like, shape(N,)) – Y values

  • degs (int) – The degree of the polynomial

  • var (array_like, shape(N,), optional) – The Y variances

  • cov (bool) – If True computes covariances on fitted parameters

spectrapy.math.poly.polyfit2d(x, y, z, degs, var=None, cov=False)[source]

Fits polynomial 2D

Parameters
  • x (array_like, shape(N,)) – X values

  • y (array_like, shape(N,)) – Y values

  • z (array_like, shape(N,)) – Z values

  • degs (array_like, shape(2,)) – The X and Y degrees of the polynomial

  • var (array_like, shape(N,), optional) – The Z variances

  • cov (bool) – If True computes covariances on fitted parameters

spectrapy.math.poly.polyval2d(pos, matrix, cov=None)[source]

Evaluates 2d polynomial and variance on it value in case covariance matrix is provided.

Parameters
  • pos (array_like, shape(2,)) – (x,y) polynoial coordinates

  • matrix (array_like, shape(N, M)) – Matrix describing polynomial

  • cov (array_like, shape(N*M,N*M), optional) – Covaiance matrix on coeffiecients matrix`

Returns

The value the polynomial and the variance on this value. Variance is None is case covariance matrix is not provided

Return type

float, float or None

This module collects statistical functions for SpectraPy

spectrapy.math.stats.clipped_average(data, var=None, sigma=3.0, maxiters=1, axis=0)[source]

Perform sigma-clipping on the provided data and return average and variance on average.

See https://en.wikipedia.org/wiki/Weighted_arithmetic_mean

Parameters
  • data (numpy.array) – The data use to compute average

  • var (numpy.array, optional) – The variance on data

  • sigma (float, optional) – The number of standard deviations to use for both the lower and upper clipping limit.

  • maxiters (int, optional) – The number of iterations to perform sigma clipping

  • axis (int, optional) – Clip along the given axis

Returns

The clippend average and the variance on the clipped average

Return type

float, float

Data I/O utilities

This module contains class to handle lines catalog

class spectrapy.dataio.catalog.Catalog[source]

Class to handle line catalogs used in IDSModel calibration

static load(catalog, wstart: Optional[float] = None, wend: Optional[float] = None)[source]

Loads line catalog. Lines in the catalog are sorted and the duplicated lines will be removed

Parameters
  • catalog (array_like or str) –

    catalog parameter could be:
    • Table of lines

    • file name of the catalog

    • list of catalog file names in case you are loading several catalogs

  • wstart (float, optional) – If wstart is not None, loads lines >= wstart

  • wend (float, optional) – If wend is not None, loads lines <= wend

Returns

The catalog

Return type

Catalog

static set_col_names(catalog)[source]

Sets the catalog column names

Parameters

catalog (Table) – The catalog instance

This module contains class to handle FITS images

class spectrapy.dataio.display.Display[source]

Class which wraps DS9 class, used to display data and regions

clear()[source]

Clears ds9 frames.

static data_to_region(data: array) array[source]

Adds 1 pixel offset to data coordinates to display them (in the right position) as DS9 region.

Parameters

data (array_like) – Input data coordinates

Returns

The offsets data

Return type

array_like

get_subimage(x: int, y: int, length: int, width: int)[source]

Returns the sub image

Parameters
  • x (int) – The X starting pixel

  • y (int) – The Y starting pixel

  • length (int) – The image X length

  • width (int) – The image Y length

Returns

The Image subimage

Return type

spectrapy.dataio.image

has_image()[source]

Checks if image has been displayed

property image

The loaded image

property image_dims

Returns the X and Y image dimensions

Returns

The image X and Y dimensions

Return type

array_like, shape(2, )

join_frames()[source]

Removes the 2nd frame from DS9 display

load_image(*filenames, data_hdu=0, var_hdu=None, err_hdu=None, flag_hdu=None)[source]

Loads image from file

Parameters
  • filenames (list) – Image file names list

  • data_hdu (str, int) – Fits HDU containing data

static region_to_data(region) array[source]

Ds9 pixels starts from 1, data from 0. This method removes the offset from ds9 regions

Parameters

regions (pyregion) – Region instance

Returns

Data values

Return type

array_like

property regions

Gets ds9 regions

replace_regions(filename: str)[source]

Loads regions from file and replace the current DS9 regions

Parameters

filename (str) – The name of the file containg the new regions

reset_background()[source]

Clears DS9 and displays again the whole image.

split_frames(axis: int = 0)[source]

Splits ds9 into 2 frames.

Parameters

axis (int) – If axis == 0 creates 2 frames rows alligned. Otherwise columns alligned

trim_image(x: int, y: int, lenght: int, width: int)[source]

Displays a sub image.

Parameters
  • x (int) – Image x starting pixel

  • y (int) – Image y starting pixel

  • lenght (int) – Image x lenght

  • width (int) – Image y width

property xlen: int

Gets the image X lenght if is image is loaded

property xstart: int

In case a sub image is displayed returns the X offset respect to the whole image

Returns

The X offset of the subimage

Return type

int

property ylen: int

Gets the image Y lenght if is image is loaded

property ystart: int

In case a sub image is displayed returns the Y offset respect to the whole image

Returns

The Y offset of the subimage

Return type

int

This module contains class to handle FITS images

class spectrapy.dataio.image.Image(data, variances: Optional[array] = None, flags: Optional[array] = None, start: Optional[array] = None)[source]

Class to handle image data, variances and flags mask

compute_profile(sigma: float = 3.0, maxiters: int = 1, axis: int = 0)[source]

Compute image profile along axis. Profile is computed computing a sigma clipped average in the direction orthogonal to the axis direction.

Parameters
  • sigma (float, optional) – The number of standard deviations to use for both the lower and upper clipping limit.

  • maxiters (int, optional) – The max number of iterations to perform sigma clipping.

  • axis (int, optional) – Clip along the given axis.

property data

Scientific data

property flags

Gets data flags

get_subimage(xstart: int, ystart: int, xlen: int, ylen: int)[source]

Extracts a sub image.

Parameters
  • xstart (int) – Pixel x starting point

  • ystart (int) – Pixel y starting point

  • xlen (int) – Size along X in pixel of the sub image

  • ylen (int) – Size along Y in pixel of the sub image

Returns

A new sub image

Return type

Image

Raises

Exception: – If ylen <=0 If xlen <=0 If sub image is totally of of image

has_variances()[source]

Checks if variance exits

property header

Gets Image header (if data comes from Fits file)

interpolate(xpos, ypos=None)[source]

Estimates the values of image (and variance if exists) in float x,y positions.

Parameters
  • xpos (array_like, shape(N,)) – Array of x positions In case number of column is 2, is the array of x and y positions

  • ypos (array_like, shape(N,)) – Array of y positions

is_valid(value)[source]

Checks if the value layer is compliant with data layer (type and shape).

Parameters

value (array_like, shape(2,)) – The new values layer

Returns

Returns True in case is compliant

Return type

bool

static load(*datafiles, data_hdu=0, var_hdu=None, err_hdu=None, flag_hdu=None)[source]

Loads image from Fits file.

Parameters
  • datafiles (list) – File name containing science data

  • data_hdu (int or str, optional) – Name or number of Fits extention containg science data

  • var_hdu (int or str, optional) – Name or number of Fits extention containg variances on data

  • err_hdu (int or str, optional) – Name or number of Fits extention containg errors on data

  • flag_hdu (int or str, optional) – Name or number of Fits extention containg flags on data pixels

Returns

New instance of image

Return type

Image

load_flags(filename: str, flag_hdu=0)[source]

Loads image flags from file and append them to the current image

Parameters
  • flagsfile (str) – File name containing flags on data

  • flag_hdu (int or str, optional) – Name or number of Fits extention containg flags on data

static load_single_image(filename: str, data_hdu=0, var_hdu=None, err_hdu=None, flag_hdu=None)[source]

Loads image from Fits file.

Parameters
  • filename (str) – File name containing science data

  • data_hdu (int or str, optional) – Name or number of Fits extention containg science data

  • var_hdu (int or str, optional) – Name or number of Fits extention containg variances on data

  • err_hdu (int or str, optional) – Name or number of Fits extention containg errors on data

  • flag_hdu (int or str, optional) – Name or number of Fits extention containg flags on data pixels

Returns

New instance of image

Return type

Image

load_variances(filename: str, var_hdu=0, err_hdu=None)[source]

Loads variances (or errors) from file and append them to the current image

Parameters
  • filename (str) – The file containg variances

  • var_hdu (str or int, optional) – The fits HDU containg variances

  • err_hdu (str or int, optional) – The fits HDU containg errors. In case it is not None the var_hdu parameter is ignored

property shape

The image array 2d shape.

property start

The image X, Y offset in case is a subimage

property variances

Variances on scientific data

Raises

Exception – If variances are not yet set.

This module contains class to extracted 2D spectra

class spectrapy.dataio.spectra.Spectra(hdus=None, file=None)[source]

Class to handle extracted spectra

add_dataset(data, wstart: float, wstride: float, slit_id: str, content)[source]

Adds a new spectrum dataset extracted and linearly wavelegth calibrated

Parameters
  • data (array_like, shape(3, N, M)) – The spectrum dataset containg: data, variance and quality

  • wstart (float) – The wavelegth starting value

  • wstride (float) – The wavelength step value

  • slit_id (str) – The spectrum ID

dump_join(filename: str, **kargs)[source]

Join al spectra 2D and save them into file in a unique image. Usefull to compare wavelength calibrations between slits.

Parameters
  • filename (str) – The output file name

  • kargs (dict, optional) – The keyword optional parameters required by HDUlist.writeto method

get_dataset(slit_id: str, content)[source]

Gets spectrum dataset

Parameters

slit_id (str) – The spectrum ID

Returns

The spectrum dataset containg: data, variance and quality

Return type

np.array, shape(3, N, M)

get_wavelengths(slit_id: str)[source]

Gets the wavelengths range for the required spectrum

Parameters

slid_id (str) – The spectrum ID required

static open(name, mode='readonly', memmap=None, save_backup=False, cache=True, lazy_load_hdus=None, **kwargs)[source]

Opens the fits file and returns the Spectra instance

property spectra_ids

Gets the IDs of spectra in the class

The mathematical models

Module containg class to handle instrument and files properties

class spectrapy.models.instrument.Instrument[source]

Class which collects instrument parameters

property data_hdu

Get the extention name or number (Primart is 0), where scientific data are stored.

Returns

Extenton name or number

Return type

int or str

property dispersion_direction

Get the instrument dispersion direction

Returns

The valid string: LR, RL, DU or UD

Return type

str

property err_hdu

Get the extention name or number (Primary is 0), where variances on scientific data are stored.

Returns

Extenton name or number

Return type

int or str

property flag_hdu

Get the extention name or number (Primart is 0), where quality flags on scientific data are stored. This extentions contains interger numbers, where 0 means good pixels.

Returns

Extenton name or number

Return type

int or str

property linear_dispersion

Get the nominal linear dispersion value

Returns

The nominal lineal dispersion value

Return type

float

static load(filename)[source]

Load instrument configuration file

Parameters

filename (str) – Input file name

property pixel_scale

Get pixel scale [arcsec/pix]

Returns

The detector pixel scale

Return type

float

property reference_lambda

Get the arbitrary reference lambda value

property var_hdu

Get the extention name or number (Primary is 0), where variances on scientific data are stored.

Returns

Extenton name or number

Return type

int or str

property xpixels

Get the number of pixels along X axis

Returns

The number of pixels along X axis

Return type

int

property ypixels

Get the number of pixels along Y axis

Returns

The number of pixels along Y axis

Return type

int

This module is the base class for all instrument geometrical models

class spectrapy.models.model.Model1d(coeffs, cov=None)[source]

Class to handle 1d local model

property coeffs

The polynomial’s coefficients

Returns

The polynomial’s coefficient values

Return type

array_like, shape(N,)

property covariance

Get the covariance matrix if exists

Returns

The covariance matrix if exists

Return type

None or array_like, shape(N,N)

log_coeffs()[source]

Displays the polynomial’s coefficients and the error on them.

property poly: poly1d

Gets the poly1d associated to the model coefficents

property variance

Get the variance on polynomial’s coefficients (if covariance exists)

Returns

The variance on polynomial’s coefficients or None if covariance is missing

Return type

None or array_like, shape(N,)

property vpoly: poly1d

Gets the poly1d associated to the model variances

class spectrapy.models.model.Model2d[source]

Generic class for 2D calibration models

property blue_direction

Get the position of the blue region of the spectrum respect of the center of it. Blue position is 1 if dispertion is going from up to bottom or from right to left. It is -1 in the other cases.

Returns

The position of spectrum blue region respect to the “center” of the spectrum

Return type

int

property covariance

Get the covariance matrixes associated to model coefficient matrixes

Return type

array_like, shape(L,M,N)

property deg

Get order of local 1d polynomial.

property dispersion_direction

Converts rotation matrix to dispersion direction string

Returns

The dispersion direction string: LR, RL, UD or DU.

Return type

str

Raises

Exception – Raise exception in case the rotation matrix is not valid

static load(filename)[source]

Load file containg OptModel parameters and returns a new OptModel

Parameters

filename (str) – The input filename to load

Returns

The new loaded model

Return type

pickled object

property model

The coefficents model

Returns

The model coefficents

Return type

array_like, shape(L,M,N)

property red_direction

Get the position of the red region of the spectrum respect of the center of it. Red position is 1 if dispertion is going from botton to up or from left to right. It is -1 in the other cases.

Returns

The position of spectrum red region respect to the “center” of the spectrum

Return type

int

property rotation

Get the rotation matrix related to the dispersion direction

writeto(filename, overwrite=False)[source]

Save the OptModel parameters values

Parameters
  • filename (str) – The output filename

  • overwrite (bool, optional) – The overwrite flag for output file

Raises

Exception – If output file already exits an the overwrite is off.

property xdeg

The order of the global model along X axis

Return type

int

property ydeg

The order of the global model along Y axis

Return type

int

The module contains classes to handle the Optical Model

class spectrapy.models.optmodel.OptModel2d(xdeg, ydeg, instrument=None, fov_scales=None)[source]

Class used to describe optical distortion in the FOV. It converts mm into pixels

compute(pos)[source]

Apply the OptModel and convert position from mm into pixels

Parameters

pos (array_like, shape(2,)) – The (x,y) position in mm

Returns

The (x,y) position in pixels and the variances on this position. In case model 2d covariance matrices are None, the variance is None.

Return type

np.array, shape(2,), np.array or None

property dispersion_versor

Get the orientation of dispersion direction.

Returns

The versor containg the dispersion orientation

Return type

array_like, shape(1,2)

flipx()[source]

Flip optical model along X axis

flipy()[source]

Flip optical model along Y axis

static load(filename)[source]

Load file containg Optical Model parameters and return a new OptModel

Parameters

filename (str) – The input filename containig OptModel2d coefficients

Returns

The Optical Model contained in the input file.

Return type

OptModel2d instance

refit(mm_pos, pix_pos)[source]

Computes new OptModel coefficients, fitting positions in mm versus positions in pixels

Parameters
  • mm_pos (array_like, shape(N,2)) – The mask mm positions

  • pix_pos (array_like, shape(N,2)) – The new pixels positions (retrieved from DS9 regions)

property shift

Get both X and Y shifts

Returns

The shifts along X and Y axes

Return type

array_like, shape(2,)

property sign

Get signs of the scales along X and Y directions.

Returns

X and Y sign the Optical model scales

Return type

np.array, shape(2,)

property slit_versor

Get the orientation of the slit.

Returns

The versor containg the slit orientation

Return type

array_like, shape(1,2)

property xmodel

it converts from x,y [mm] in x [pixels]

Returns

The Optical Model for X positions.

Return type

array_like, shape(N,M)

Type

The OptModel for X

property xscale

The main scale of OptModel for X [pixels/mm]

Returns

The main scale factor long X axis

Return type

float

property xshift

The center of OptModel for X [pixels]

Returns

The value of the shift along X axis

Return type

float

property ymodel

it converts from x,y [mm] in y [pixels]

Returns

The Optical Model for Y positions.

Return type

array_like, shape(N,M)

Type

The OptModel for X

property yscale

The main scale of OptModel for Y [pixels/mm]

Returns

The main scale factor long Y axis

Return type

float

property yshift

The center of OptModel for Y [pixels]

Parameters

value (float) – The value of the shift along Y axis

This module contains classes of CRV models 2D and 1D

class spectrapy.models.crvmodel.CrvModel1d(coeffs, rotation, cov=None)[source]

Class to handle local Curvature 1d model

compute(delta_disp)[source]

Compute variation respect to spectra trace perfectly aligned to the pixel grid.

Parameters

delta_disp (array_like, shape(N,)) – Distances (in pixels) respect to reference position

Returns

  • array_linke, shape(N,2) – Displacements respect to pixels grid

  • array_linke, shape(N,2) – Variances on displacements

property dispersion_vector

Returns the direction versor oriented according with model rotation

property rotation

Get the rotation matrix from this model

property slit_versor

Get the orientation of the slit.

Returns

The versor containg the slit orientation

Return type

array_like, shape(1,2)

class spectrapy.models.crvmodel.CrvModel2d(deg, xdeg, ydeg, instrument=None)[source]

Class used to model 2D spectra curvatures

compute(pos, delta_disp)[source]

Compute the local curvature model and returns the list of (x,y) positions along the slit trace.

Parameters

pos (array_like, shape(2,)) – The reference position in pixels where the curvature model is computed

delta_disp: array_like, shape(N,)

The list of distances from the pos reference position (in pixels), computed along dispersion direction

Returns

The pixels trace positions

Return type

array_like, shape(N, 2)

property dispersion_vector

Returns the direction versor oriented according with model rotation

get_local_model(pos)[source]

Get the local 1d model

Parameters

pos (array_like, shape(2,)) – The center of the local model

Returns

The CRV model

Return type

CrvModel1d

get_trace_edges(pos, image_dims)[source]

Get the trace limits on image

static load(filename)[source]

Load file containg CrvModel parameters and returns a brand new model

Parameters

filename (str) – The input filename

refit(xdata, ydata, zdata, var=None)[source]

Recomputes the global model fitting variation of the coeffs model in the FOV

Parameters
  • x (array_like, shape(N,)) – The X positions in the FOV [pixels]

  • y (array_like, shape(N,)) – The Y positions in the FOV [pixels]

  • z (array_like, shape(N,L)) – The coefficients values in the FOV. One layer for each polynomial’s power

  • var (array_like, shape(N,L), optional) – The variance on coefficients in the FOV. One layer for each polynomial’s power

refit_trace(pos, xdata, ydata, wdata=None)[source]

Fit a curve of trace position give (x,y) point positions along the trace.

Parameters
  • pos (array_like, shape(2,)) – The center of the local model 1d

  • xdata (array_like, shape(N,)) – The absoulte X positions of regions (in pixels) on the FOV

  • ydata (array_like, shape(N,)) – The absoulte X positions of regions (in pixels) on the FOV

Returns

The local curvature model which maps the trace

Return type

CrvModel1d instance

This module contains classes of IDS models 2D and 1D

class spectrapy.models.idsmodel.IdsModel1d(coeffs, reference_lambda, cov=None)[source]

Class to handle 1d ids local model

compute(lambdas)[source]

Evaluate the model in a give lambda positions

Parameters

lambdas (array_like, shape(N,)) – The list of lambda values [A]

Returns

The of delta values respect of reference lambda in pixels

Return type

array_like, shape(N,)

property reference_lambda

The lambda reference value

Returns

The reference lambda value

Return type

float

class spectrapy.models.idsmodel.IdsModel2d(deg, xdeg, ydeg, instrument=None)[source]

Class used to describe 2D wavelenght solution in the FOV

compute(pos, lambdas)[source]

Computes line positions lambdas respect to the reference position

Parameters
  • pos (array_like, shape (2,)) – The (x,y) reference position

  • lambdas (array_like, shape (N,)) – The list of line position [A]

Returns

The expected position of the lines [pixels]

Return type

array_like, shape(N,2)

get_delta_dispersion(pos, xy)[source]

Gets the delta values between a reference position (pos) and lines positions, along the dispersion direction according to grism orientation

Parameters
  • pos (array_like, shape(2,)) – The reference position

  • xy (array_like, shape(2, N)) – The line positions

Returns

The delta values

Return type

np.array, shape(N,)

get_local_model(pos)[source]

Get the local 1d model

Parameters

pos (array_like, shape(2,)) – The center of the local model

Returns

The IDS model

Return type

IdsModel1d

property inv_dispersion

Get the first approximation of the inverse of linear dispersion

Returns

The first order approximation of the linear dispersion

Return type

float

static load(filename)[source]

Load file containg IdsModel parameters and returns a brand new model.

Parameters

filename (str) – The file name containg the model

property reference_lambda

The reference lambda value where the 1d local polynomial is centered.

Returns

The reference lambda value

Return type

float

refit_slit(lambdas, delta_disp)[source]

Recompute the model for a single slit.

@param lambdas: line positions [A] @type lambdas: np.array 1 by n

writeto(filename, overwrite=False)[source]

Save the IdsModel parameters values

Parameters
  • filename (str) – The ouput filename

  • overwrite (bool, optional) – The overwrite flag in case output file already exists

Raises

Exception – If file exists and overwrite flag is False

Masks geometry

This module contains classes to handle MOS/LS mask slits

class spectrapy.mask.mask.Mask[source]

This class contains the geometrical description of the mask

add_slit(slit)[source]

Adds slit description to the mask

compute_scales(slit_width=1.0)[source]

Searches for mask orientation: slit lenght is alolng X or Y axis Defines a rough conversion from mm to pixels

Parameters

slit_width (float, optional) – The typical slit with in arcsec

Returns

The x and y scales in arcsec/mm

Return type

array_like (2,)

keys()[source]

Returns the slits IDs

static load(filename)[source]

Loads mask from a mask description file and return a new Mask instance

Parameters

filename (str) – File name containg the mask description

property opt

Returns the Optical Model instance

class spectrapy.mask.mask.MaskSlit(slit_id, geometry, opt=None)[source]

This class contains the geometrical description of the slit

property center

The slit center

property deltat: float

Delta t inside along the slit

property dispersion_edge

Gets the edge along the dispersion direction

get_num_rows()[source]

Gets the number of pixels of the slit

get_pix_center()[source]

Gets the pixel of slit center

get_pix_left_edge()[source]

Get the left margin of the slit according with dispersion direction

get_pix_position(t=0)[source]

Handles slit as a linear bezier curve. t=0 is the left margin and t=1 is the rigth margin

get_pix_right_edge()[source]

Get the right margin of the slit according with dispersion direction

get_pix_vertices()[source]

Returns vertices of slit in pixels

get_slit_pix(left_margin=0, right_margin=0)[source]

Get the slit discretized in pixels If left_margin > 0: starts inside the slit of left_margin pixels If left_margin < 0: virtually extends the slit on the left side If right_margin > 0: ends befor the natural slit end of right_margin pixels If right_margin < 0: virtually extends the slit on the right side

property length

The length of the slit along the cross dispersion direction

property opt

The Optical Model instance

property reference

True is this slit is a reference slit

property rotation

The slit rotation angle

property semi_axis

The slit semi axis

property slit_id

The unique slit ID

property vertices

Vertices of the slit in mm anticlockwise direction starting from lower left corner.

Returns

The (x,y) vertices of the slit [mm]

Return type

array_like, shape(4, 2)

property width

The width of the slit along the dispersion direction

property xdispersion_edge

Gets the edge along cross dispersion direction

Models Calibration

This module contains the interface class to calibrate the models

class spectrapy.modelscalib.calib.ModelsCalibration(instrument, mask=None, opt=None, crv=None, ids=None)[source]

Class to calibrate the IdsModel

ids_iter(catalog, wstart: Optional[float] = None, wend: Optional[float] = None, use_ref: bool = False)[source]

Starts iterate the mask slit by slit, to achieve IDS calibration.

Parameters
  • catalog (array_like or str) – The catalog used in IDS calibration

  • wstart (float, optional) – The wavelength starting value for the catalog

  • wend (float, optional) – The wavelength ending value for the catalog

  • use_ref (bool) – If True, use also reference slits for IDS calibration

next(fit=True)[source]

Iterate to the next slit in IDS calibration.

Parameters

fit (bool, optional) – If fit is False, move to the next slit without fitting the IDS model on the current slit.

prev(fit=True)[source]

Iterate to the previous slit in IDS calibration.

Parameters

fit (bool, optional) – If fit is False, move to the previous slit without fitting the IDS model on the current slit.

stop_iter(fit=True)[source]

Stop IDS iteration and refit the global model if fit is True

Parameters

fit (bool, optional) – If bool is False no IDS fit is performed

This module contains classes to calibrate the Optical Model

class spectrapy.modelscalib.optcalib.OptModelCalibration(instrument, mask=None, opt=None)[source]

Class to calibrate the OptModel

static data_to_region(data)[source]

Add 1 pixel offset to data coordinate to display them (in the right position) as DS9 region.

fit_opt_model()[source]

Reads adjusted slit position in pixel from DS9 regions and refits the OptModel

property instrument

The instrument instance

load_image(*filenames)[source]

Loads image data from file

Parameters

filenames (list) – The input list of file names containg data

property mask

Gets the mask in use

new_opt_model(xdeg: int, ydeg: int)[source]

Creates a new model from scratch

Parameters
  • xdeg (int) – The X degree of the global 2D model

  • ydeg (int) – The Y degree of the global 2D model

property opt

Gets the optical model

plot_opt_model(color: str = 'blue', edit: bool = False)[source]

Plots DS9 regions of slits described by mask geometry

Parameters
  • color (str, optional) – The color of the center of the model

  • edit (bool, optional) – If False slits region can be just moved on the frame. If True slit geomtries can also be modified. Usefull in LS case

static region_to_data(region)[source]

Ds9 pixels starts from 1, data from 0. This method removes the offset from ds9 regions

restart_display()[source]

Restart DS9 displat in case it is closed accidentally

This module contains the classes to calibrate the spectra tracing

class spectrapy.modelscalib.crvcalib.CrvModelCalibration(instrument, mask=None, opt=None, crv=None)[source]

Class to calibrate the CrvModel

property crv

Gets the Curvature model instance

display_single_slit(slit_id: str)[source]

Displays just a single slit trace.

Parameters

slit_id (str) – The slit ID to display

fit_crv_model(weight: bool = True, filename: Optional[str] = None)[source]

Reads adjusted slit curvature in pixel and refit the CrvModel

Parameters
  • weight (bool, optional) – If weight is True, compute a weighted fit where weights are 1/sqrt(variances)

  • filename (str, optional) – If not None, loads regions from file

new_crv_model(deg: int, xdeg: int, ydeg: int)[source]

Sets up a new model

Parameters
  • deg (int) – The local degree of the curvature model

  • xdeg (int) – The global X degree

  • ydeg (int) – The global Y degree

plot_crv_model(npixels=10, pos=(0,))[source]

Plots DS9 regions of slits described by mask geometry

reload_traces_from_regions()[source]

In case user adjusts regions by hand, this function reloads region positions from DS9 and ignores variances on region positions.

set_trace_limits(blue, red)[source]

Given the slit reference position moves blue a given amount of pixels in the blue direction and in the red direction.

Parameters
  • blue (int) – The amount of pixel in the blue direction

  • red (int) – The amount of pixel in the red direction

This module contains class the calibrate IDS model

class spectrapy.modelscalib.idscalib.IdsModelCalibration(instrument, mask=None, opt=None, crv=None, ids=None)[source]

Class to calibrate the IdsModel

fit_ids_model(single_slit=False, filename=None)[source]

Reads adjusted slit curvature in pixel and refit the CrvModel

Parameters
  • single_slit (bool, optional) – Fit the solution for a single slit

  • filename (str, optional) – If it is not None, reload regions from filename

property ids

The IDSModel instance

new_ids_model(deg: int, xdeg: int, ydeg: int)[source]

Creates new IDS model from scratch

Parameters
  • deg (int) – The degree of the local IDS 1D polynomial

  • xdeg (int) – The degree along the X axis of the global IDS polynomial

  • ydeg (int) – The degree along the Y axis of the global IDS polynomial

plot_ids_model(catalog, *, wstart: Optional[float] = None, wend: Optional[float] = None, slit_id: Optional[str] = None, nsplit: int = 1, use_ref: bool = False)[source]

Plots DS9 regions of slits described by mask structure

Parameters
  • catalog (str) – The lines catalog

  • wstart (float, optional) – The starting point of the lines catalog

  • wend (float, optional) – The ending point of the lines catalog

  • slit_id (str, optional) – In case is not None display only this slit

  • nsplit (int, optional) – The number of points for each slit

plot_slice(slit_id: str, t: float = 0.1)[source]

Plots a slit slice along dispersion direction. This is just an auxiliary function. It can be usefull to match lines and references plots

Parameters
  • slit_id (str) – The ID of slit to slice

  • t (float, optional) – The t parameter used to select where perfome the slicing. This parameter goes from 0 up to 1. 0 is the left edge and 1 is the right edge. Every value between 0 and 1 is a point in the middle of the slit

This module contains class to iterate IDS model calibration

class spectrapy.modelscalib.model1diter.Model1dIterator(slit_ids, catalog=None)[source]

Class used to iterate across the slits and store 1d models

property catalog

Gets the catalog line list if available

Returns

List of list catalog

Return type

array_like, shape(N, 3)

property current_slit

Gets the current slit ID

dump_models(filename: str, overwrite: bool = False)[source]

Saves the models already stored

Parameters
  • filename (str) – Output file name

  • overwrite (bool, optional) – Overwrite flag in case file already exists

get_model(slit_id: Optional[str] = None)[source]

Gets the model of a given slit ID

Parameters

slit_id (str, optional) – The slit ID. In case is None, uses the current slit ID

Returns

The related 1D model

Return type

1dModel

has_model(slit_id: Optional[str] = None)[source]

Checks if model of a given slit ID already exists

Parameters

slit_id (str, optional) – The slit ID. In case is None, uses the current slit ID

Returns

True if the model exists

Return type

bool

property has_next

Returns True if further slits are avaialble after the current one. Returns False if the end of the slit IDs list is reached

property has_prev

Returns True if further slits are available before the current one. Returns False if the begin of the slit IDs list is reached

load_models(filename: str)[source]

Loads already computed models

Parameters

filename (str) – Input file name

next()[source]

Sets the cursor to the next slit.

prev()[source]

Sets the cursor to the previos slit.

set_model(model, slit_id: Optional[str] = None)[source]

Set the model for a given slit ID

Parameters
  • model (Model1d) – The model 1d instance to set

  • slit_id (str, optional) – The slit ID. In case is None, uses the current slit ID

Returns

The related 1D model

Return type

1dModel

Calibration on Data

This module contains the classes to compute the tracing on data

class spectrapy.datacalib.tracingcalib.TraceCalibration(instrument, mask, opt, crv, engine='Sobel')[source]

Class to apply models on science data

compute_spectra_traces(slit_win=20, pix_bin=50, var=False, sub_pixels=5, plot=False, right=False, logp=False)[source]

Fit the edge of the spectrum trace for each slit.

Parameters
  • slit_win (int, optional) – Size of the window around the expected position of the trace

  • pix_bin (int, optional) – Size of the collapsing window to obtain the profile edge

load_flags(filename: str)[source]

Loads bad pixels from bad pixel image.

Parameters

filename (str) – The file containg bad pixels

load_image(*filenames)[source]

Loads images and set them in DS9

Parameters

filenames (slit) – The list of images

new_crv_model(deg, xdeg, ydeg)[source]

Not implemented method

reload_traces_from_regions()[source]

Not implemented method

writeto(filename: str, overwrite: bool = False)[source]

Save the already computed CRVModel

Parameters
  • filename (str) – The output filename

  • overwrite (bool, optional) – The overwrite flag for output file

Raises

Exception – If output file already exits an the overwrite is off.

This module contains classes to compute slit edges

class spectrapy.datacalib.edges.DoubleTanH(dispersion_direction='LR')[source]

Class to evaluate tracing step position fitting pair of TanH

compute_fg(xdata, ydata, edges)[source]

Computes the parameters first guesses

Parameters
  • xdata (array_like, shape(N,)) – The x data of the edge

  • ydata (array_like, shape(N,)) – The y data of the edge

  • edges (array_like, shape(N,)) – The edges values

compute_slice_edge(center, slice_shape, var=False, sub_pixels=5, plot=False, right=False, logp=False)[source]

Computes the edge of the slice collapsion it along the dispersion direction

Parameters
  • center (np.array, shape(2,)) – The center of the slice

  • slice_shape (np.array, shape(2,)) – The shape of the slice

  • plot (bool) – Debugging parameter. If True plot the profile, the fit and the edge

Returns

edge, variance – The edge position in pixels and the variance along the cross dispersion direction CHECK!!!

Return type

np.array, float

static ddouble(x, *p)[source]

The Jacobian matrix of the double function.

static dleft(x, *p)[source]

The Jacobian matrix of the left function.

static double(x, *p)[source]

Defines a function which has one step on left, another step on right and a gap in the midle.

static dright(x, *p)[source]

The Jacobian matrix of the right function.

get_bottom_step()[source]

Computes edge position in case the step is going down

get_step(bottom)[source]

Computes the position of the edge

get_up_step()[source]

Computes edge position in case the step is going up

static left(x, *p)[source]

Defines a function which has step on left.

plot(xdata, ydata, profile_edges, edge=None, vdata=None)[source]

Plots edge profile data, fitted profile, edge position and egde profile

static right(x, *p)[source]

Defines a function which has step on right.

class spectrapy.datacalib.edges.EdgeEngine(dispersion_direction='LR')[source]

The Edge interface class

compute_slice_edge(center, edge, edge_var)[source]

Computes the edge of the slice collapsion it along the dispersion direction

Parameters

center (np.array, shape(2,)) – The center of the slice

Returns

edge, variance – The edge position in pixels and the variance along the cross dispersion direction CHECK!!!

Return type

np.array, float

property image

The loaded image

xprofile(sub_image, yprofile)[source]

Gets the x values for the yprofile, starting from the sub image offset starts

Parameters
  • sub_image (Image) – The image of the yprofile

  • yprofile (array_like, shape(N, )) – The profile of the sub image

Returns

The range along the profile

Return type

np.arange

class spectrapy.datacalib.edges.Sobel(dispersion_direction='LR')[source]

This class uses sobel filter to compute spectra edges

compute_slice_edge(center, slice_shape, var=False, sub_pixels=5, plot=False, right=False, logp=False, sigma=2.0, maxiters=3)[source]

Computes the edge of the slice collapsion it along the dispersion direction

Parameters
  • center (np.array, shape(2,)) – The center of the slice

  • slice_shape (np.array, shape(2,)) – The shape of the slice

  • plot (bool) – Debugging parameter. If True plot the profile, the fit and the edge

Returns

edge, variance – The edge position in pixels and the variance along the cross dispersion direction CHECK!!!

Return type

np.array, float

get_step(bottom)[source]

Gets the trace step

Parameters

bottom (bool) – If True returns the down step

property image

The loaded image

This module contains the class the calibrate the wavelenght solution on real data

class spectrapy.datacalib.wavelengthcalib.WavelengthCalibration(instrument, mask, opt, crv, ids)[source]

Class to calibrate the IdsModel

static compute_line_positions(waves, delta_disp, fluxes, lines, margin: int)[source]

Compute position of lines

compute_spectra_wave(catalog, margin: int = 10)[source]

Compute lines positions on frames and create the extraction table used for extraction.

Parameters
  • catalog (array_like or str) – Line catalog to use. See _load_catalog method

  • margin (int [pixels]) – The margin around the expected line position use to compute the real line position

Returns

The extraction table containing the solutions used by extraction procedure

Return type

ExtTable

has_lambda_range()[source]

Checks is the wavelength range is set

new_ids_model(deg, xdeg, ydeg)[source]

Not implemented method

set_lambda_range(blue: float, red: float)[source]

Sets the lambda range used for computing IDS model on data

Parameters
  • blue (float [Angstrom]) – Blue limit for IDS computation

  • red (float [Angstrom]) – Red limit for IDS computation

This module contains classes the handle the Extraction Table

class spectrapy.datacalib.extractiontable.ExtTable[source]

Class to handle the data structure used to to store all model solutions.

add_row(slit_id: str, pos, var_pos, crv, ids)[source]

Add row to the table.

Parameters
  • slit_is (str) – The unique slit ID

  • pos (array_like, shape(2,) [pixel]) – The detector (x,y) position (in pixels) for the models

  • var_pos (array_like, shape(2,)) – The variance on pos

  • crv (CrvModel1d) – The Curvature model for this position

  • ids (IdsModel1d) – The Inverse Dispersion Solution model for this position

create_region_str(lines, slit_id: int, rows=None, wrange=None, color: str = 'green')[source]

Display entire slit solutions

get_spectrum_area(slit_id, wstart, wend, px_margin=2)[source]

Computes spectrum area on the detector. Area provided by this method can be out of image

Parameters
  • slit_id (str) – The unique slit ID

  • wstart (float) – The wavelength starting point for area computation

  • wend (float) – The wavelength ending point for area computation

  • px_margin (int, optional) – Extra pixel margin along each direction in spectrum area computation

property instrument

The instrument configuration

keys()[source]

Gets slits IDs

Returns

A set-like providing a view on list IDs

Return type

set-like object

static load(filename)[source]

Loads the extraction table from file.

Parameters

filename (str) – The input file name

static load_instrument(hdu)[source]

Loads instrument configuration from hdu

Parameters

hdu (HDUImage) – The fits HDU containg the instrument information

rectify(deg: int = 2, margin: int = 0)[source]

Refit IDS along each slit of the ExtractionTable in order to find a smoother solution

Parameters
  • deg (int, optional) – Degree of the fit

  • margin (int, optional) – Number of pixel next to the edges (both) to exclude in refit

Returns

New extraction table for the current slit

Return type

ExtTable

writeto(filename: str, overwrite=False)[source]

Save the Extraction Table as FITS file.

Parameters
  • filename (str) – The output filename

  • overwrite (bool, optional) – The overwrite flag.

Raises

Exception – Raise error in case file already exists and overwrite flag is False

class spectrapy.datacalib.extractiontable.ExtTableRow(slit_id, pos, var_pos, crv, ids)[source]

Class to handle single row of the Extraction Slit

property center

The center of the slit

compute(values)[source]

Apply all models and get the position of lambda for the current row.

Parameters

values (array_like, shape(N,)) – The list of wavelength values [A]

Returns

The positions of the input wavelengths list

Return type

array_like, shape(N,2)

property crv

Gets the CRV model of the current row

property ids

Gets the IDS model of the current row

class spectrapy.datacalib.extractiontable.ExtTableSlit(slit_id: str)[source]

Class to handle single slit of the Extraction Table

add_row(pos, var_pos, crv, ids)[source]

Add row to the table.

Parameters
  • pos (array_like, shape(2,) [pixel]) – The detector (x,y) position (in pixels) for the models

  • var_pos (array_like, shape(2,)) – The variance on pos

  • crv (CrvModel1d) – The Curvature model for this position

  • ids (IdsModel1d) – The Inverse Dispersion Solution model for this position

compute(t: float, wavelengths)[source]

Compute the pixel for each arbitrary row in the slit

Parameter

t: float

The position along the slit. t goes from 0 up to 1

wavelengths: array_like, shape(N,)

The wavelength values

returns

position – The position of the wavelenghts

rtype

array_like, shape(N,2)

create_model(opt_deg: int = 2, crv_deg: int = 2, ids_deg: int = 2, margin: int = 1)[source]

Creates a 2D slit model used to compute every position of slit regardless of list rows

Parameters
  • opt_deg (int, optional) – The degree of the polinomial use to fit the slit position

  • crv_deg (int, optional) – The degree of the polinomial used to fit the Curvature model variantion inside the slit

  • ids_deg (int, optional) – The degree of the polinomial used to fit the Inverse dispersion solution variantion inside the slit

  • margin (int, optional) – The number of pixel to exclude at the edge of the slit for the IDS fitting

get_ids_values()[source]

Gets the IDS position and coefficients for the whole slit

Parameters

slit_id (str) – The slit ID

rectify(deg: int = 2, margin: int = 0)[source]

Refit IDS along a single slit in order to find a smoother solution

Parameters
  • slit_id (str) – Slit ID of the current slit

  • deg (int) – Degree of the fit

  • margin – Number of pixel next to the edges (both) to exclude in refit

Spectra Extraction

This module contains class the compute the resampling kernel profile 1D

class spectrapy.extraction.kernelprofile.KernelProfile(radius: float, pxsample: int)[source]

This class implements the resampling kernel profile using a cutoff function in Fourier space

get_profile_value(subpixel)[source]

Get the profile value

Parameters

subpixel (float) – The pixel value (float) where evaluate the profile

Returns

The profile value

Return type

float

has_profile() bool[source]

Returns True is the kernel profile has been computed

static load(filename)[source]

Temporary method

property profile

Gets the profile values

Returns

The profile values

Return type

np.array, shape(N,)

This module contains the ResamplingBox class

class spectrapy.extraction.resamplingbox.ResamplingBox(radius: float = 0.0)[source]

This is the class to handle the box area around a resampling point

has_position() bool[source]

Returns True if the position has been set

is_out_of_box(pos) bool[source]

Checks if the pixel position is out of the box

Parameters

pos (array_like, shape(2,)) – The pixel position

Returns

True in case the pixel is out of the resampling box

Return type

bool

is_out_of_circle(pos) bool[source]

Checks if the pixel position is out of the resampling kernel circle

Parameters

pos (array_like, shape(2,)) – The pixel position

Returns

True in case the pixel is out of the resampling kernel circle

Return type

bool

property radius

Gets the radius of the resampling kernel

set_position(pos)[source]

Sets the position of the resampling box and computes the starting end the ending points along X and Y axes

Parameters

pos (array_like, shape(2,)) – The center of the box: the point to resample

property xend: int

The X ending point of the box

property xrange: arange

Gets a range along the X axis of the box

property xsize: int

The X size of the box

property xstart: int

The X starting point of the box

property yend: int

The Y ending point of the box

property yrange: arange

Gets a range along the Y axis of the box

property ysize: int

The Y size of the box

property ystart: int

The Y starting point of the box

This module contains core class the handle resampling

class spectrapy.extraction.resamplingkernel.ResamplingKernel(radius: float = 2.0, pix_sample: int = 1000)[source]

The resampling kernel class

interpolate(pos, data, sigma=None, cov=False)[source]

Interpolates the image in one point

Parameters
  • pos (array_like, shape(2,)) – The (x,y) position to interpolate

  • data (np.ma.array) – The Image to interpolate

  • sigma (np.array, optional) – The square root of the variances on Image if available

property position

Gets the kernel position