orb package

Submodules

orb.cgvar module

orb.constants module

orb.constants.ATOMIC_MASS = 1.66053886e-24

1 Atomic mass in g

orb.constants.FITS_CARD_MAX_STR_LENGTH = 18

Max length of a FITS string card

orb.constants.FWHM_COEFF = 2.3548200450309493

Coefficient used to convert the width of a gaussian function to its FWHM (line_fwhm = line_width * FWHM)

orb.constants.FWHM_SINC_COEFF = 1.20671

Coefficien used to determine sinc fwhm

orb.constants.K_BOLTZMANN = 1.38064852e-16

Boltzmann constant in erg/K

orb.constants.LIGHT_VEL_AAS = 2.99792458e+18

Velocity of the light in the vacuum in A.s-1

orb.constants.LIGHT_VEL_KMS = 299792.458

Velocity of the light in the vacuum in km.s-1

orb.constants.PLANCK = 6.6260755e-27

Planck constant in erg.s

orb.constants.SESAME_URL = 'http://cdsweb.u-strasbg.fr/cgi-bin/nph-sesame/-oxp/SNVA?'

Sesame URL

orb.constants.VIZIER_URL = 'http://webviz.u-strasbg.fr/viz-bin/'

Vizier URL in Canada

orb.constants.VIZIER_URL_CA = 'http://vizier.hia.nrc.ca/viz-bin/'

Vizier URL in Canada

orb.core module

The Core module contains all the core classes of ORB.

class orb.core.Axis(data, axis=None, params=None, mask=None, **kwargs)

Bases: orb.core.Vector1d

Axis class

convert(pos)

convert the position in channel to a a value in axis unit

Parameters

pos – Position in channel

Returns

Value in axis unit

class orb.core.Cm1Vector1d(spectrum, axis=None, params=None, **kwargs)

Bases: orb.core.Vector1d

1d vector class for data projected on a cm-1 axis (e.g. complex spectrum, phase)

change_resolution(resolution)

Return a vector with a defined resolution (note that resolution can only be decreased, there is no way to increase resolution)

get_filter_bandpass_cm1()

Return filter bandpass in cm-1

get_filter_bandpass_pix(border_ratio=0.0)

Return filter bandpass in channels

Parameters

border_ratio – (Optional) Relative portion of filter border removed (can be a negative float to get a bandpass larger than the filter, default 0.)

Returns

(min, max)

mean_in_filter()
needed_params = ('filter_name',)
obs_params = ('step', 'order', 'calib_coeff')
velocity_shift(velocity)

Return a vector with its axis shifted by a given velocity.

Parameters

velocity – Velocity in km/s

class orb.core.ColorStreamHandler(stream=None)

Bases: logging.StreamHandler

Manage colored logging

copied from https://gist.github.com/mooware/a1ed40987b6cc9ab9c65

CRITICAL = '\x1b[31m'
DEBUG = '\x1b[36m'
DEFAULT = '\x1b[0m'
ERROR = '\x1b[31m'
INFO = '\x1b[0m'
WARNING = '\x1b[33m'
format(record)

Format the specified record.

If a formatter is set, use it. Otherwise, use the default formatter for the module.

class orb.core.Data(data, err=None, axis=None, params=None, mask=None, **kwargs)

Bases: object

base class for data objects.

data = array + params (equiv to header, wcs params are contained in the params) + axis (for 1d data and 3d data) + mask (1d for 1d, 2d for 2d and 3d)

assert_axis()

Assert the presence of an axis

assert_err()

Assert the presence of an error

assert_mask()

Assert the presence of a mask

assert_params()

Assert the presence of parameters

convert_params = {}
copy(data=None, **kwargs)

Return a copy of the instance

Parameters
  • data – (Optional) can be used to change data

  • kwargs – Addition kwargs (useful to copy child classes with more kwargs at init)

copy_param(oldkey, newkey)

Copy a parameter with a given key to a parameter with another key. Do it only if the new key is not already set

get_axis()

Return a copy of self.axis

get_err()

Return a copy of self.err

get_gvar()

Return data and err as a gvar.GVar instance

get_header()

Return params as an astropy.io.fits.Header instance

get_mask()

Return a copy of self.mask

get_param(key)

Get class parameter

Parameters

key – parameter key

get_wcs()
get_wcs_header()
has_axis()
has_err()
has_mask()
has_param(key)

Test the presence of a parameter

has_params()

Check the presence of observation parameters

needed_params = ()
set_header(header)

update params from an astropy.io.fits.Header instance.

Parameters

header – An astropy.io.fits.Header instance.

set_mask(data)

Set mask.

A mask must have the shape of the data but for 3d data which has a 2d mask (self.dimx, self.dimy). A Zero indicates a pixel which should be masked (Nans are returned for this pixel).

Parameters

data – mask. Must be a boolean array

set_param(key, value)

Set class parameter

Parameters

key – parameter key

to_bundle()

Return a bundle of picleable objects that can be passed to a parallelized process and recreate the Data object.

to_fits(path)

write data to a FITS file.

Note that most of the information will be lost in the process. The only output guaranteed format is hdf5 (use writeto() method)

Parameters

path – Path to the FITS file

update_params(params)

Update params with a dictionary or an astropy.io.fits.Header

Parameters

params – A dict or an astropy.io.fits.Header instance.

writeto(path)

Write data to an hdf file

Parameters

path – hdf file path.

class orb.core.ExtDebugLoggingFilter(name='')

Bases: logging.Filter

bad_names = ['pp']
filter(record)

Determine if the specified record is to be logged.

Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.

class orb.core.ExtInfoLoggingFilter(name='')

Bases: logging.Filter

bad_names = ['pp']
filter(record)

Determine if the specified record is to be logged.

Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.

class orb.core.FilterFile(filter_name, axis=None, params=None, **kwargs)

Bases: orb.core.Vector1d

Manage filter files

get_filter_bandpass()

Return filter bandpass in nm

get_filter_bandpass_cm1()

Return filter bandpass in cm-1

get_high_order_phase()
get_mean_cm1()

Return mean wavenumber

get_mean_nm()

Return mean wavelength

get_modulation_efficiency()

Return modulation efficiency.

get_observation_params()

Return observation params as tuple (step, order).

get_phase_fit_order()

Return phase fit order.

get_phase_fit_ref()

Return reference wavenumber for phase fitting

get_sky_lines(step_nb)

Return the sky lines in a given filter

get_transmission(step_nb, corr=None)

Return transmission in the filter bandpass :param step_nb: number of steps

Parameters

corr – calibration coeff (at center if None)

needed_params = ('step', 'order', 'phase_fit_order', 'modulation_efficiency', 'bandpass_min_nm', 'bandpass_max_nm', 'instrument')
project(new_axis)

Project vector on a new axis

Parameters

new_axis – Axis. Must be an orb.core.Axis instance.

read_filter_file(return_spline=False)

Return transmission, axis and bandpass

Parameters

return_spline – If True a cubic spline (scipy.interpolate.UnivariateSpline instance) is returned instead of a tuple (filter_nm, filter_trans, filter_min, filter_max)

class orb.core.Indexer(*args, **kwargs)

Bases: orb.core.Tools

Manage locations of created files.

All files locations are stored in a text-like file: the index file. This file is the ‘real’ counterpart of the index (which is ‘virtual’ until core.Indexer.update_index() is called). This method is called each time core.Indexer.__setitem__() is called.

This class can be accessed like a dictionary.

get_path(file_key, file_group=None, err=False)

Return the path of a file recorded in the index.

Equivalent to self[file_key] if the option file_group is not used.

Parameters
  • file_key – Key name of the file to be located

  • file_group – (Optional) Add group prefix to the key name. File group must be ‘cam1’, ‘cam2’, ‘merged’ or their integer equivalent 1, 2, 0. File group can also be set to None (default None).

  • err – (Optional) Print an error instead of a warning if the file is not indexed.

load_index()

Load index file and rebuild index of already located files

set_file_group(file_group)

Set the group of the next files to be recorded. All given file keys will be prefixed by the file group.

Parameters

file_group – File group must be ‘cam1’, ‘cam2’, ‘merged’ or their integer equivalent 1, 2, 0. File group can also be set to None.

update_index()

Update index files with data in the virtual index

class orb.core.Lines(**kwargs)

Bases: orb.core.Tools

This class manages emission lines names and wavelengths.

Spectral lines rest wavelength (excerpt, all recorded lines are in self.air_lines_nm):

============ =======
  Em. Line     Air
============ =======
[OII]3726    372.603
[OII]3729    372.882
Hepsilon     397.007
Hdelta       410.176
Hgamma       434.047
[OIII]4363   436.321
Hbeta        486.133
[OIII]4959   495.892
[OIII]5007   500.684
[NII]6548    654.803
Halpha       656.279
[NII]6583    658.341
[SII]6716    671.647
[SII]6731    673.085
air_lines_name = None
air_lines_nm = {'H10': 379.79044, 'H11': 377.06368, 'H12': 375.01584, 'H13': 373.43746, 'H14': 372.19449, 'H15': 371.19774, 'H8': 388.90557, 'H9': 383.53909, 'Halpha': 656.2819, 'Hbeta': 486.1333, 'Hdelta': 410.17415, 'HeI5876': 587.567, 'HeI6678': 667.81517, 'HeI7065': 706.52153, 'Hepsilon': 397.00788, 'Hgamma': 434.0471, '[ArIII]7136': 713.579, '[ArIII]7751': 775.111, '[FeVII]6087': 608.7, '[NII]5755': 575.459, '[NII]6548': 654.805, '[NII]6583': 658.345, '[NeIII]3869': 386.876, '[OIII]4363': 436.3209, '[OIII]4959': 495.8911, '[OIII]5007': 500.6843, '[OII]3726': 372.6032, '[OII]3729': 372.8815, '[OII]7320': 731.992, '[OII]7330': 733.019, '[OI]6300': 630.0304, '[SIII]6312': 631.206, '[SII]6716': 671.644, '[SII]6731': 673.0816}
air_sky_lines_nm = None

Air sky lines wavelength

get_line_cm1(lines_name, round_ang=False)

Return the wavenumber of a line or a list of lines

Parameters

lines_name – List of line names

get_line_name(lines)

Return the name of a line or a list of lines given their wavelength.

Parameters

lines – List of lines wavelength

get_line_nm(lines_name, round_ang=False)

Return the wavelength of a line or a list of lines

Only str instance will be converted.

Parameters
  • lines_name – List of line names

  • round_ang – (Optional) If True return the rounded wavelength of the line in angstrom (default False)

get_sky_lines(nm_min, nm_max, delta_nm, line_nb=0, get_names=False)

Return sky lines in a range of optical wavelength.

Parameters
  • nm_min – min Wavelength of the lines in nm

  • nm_max – max Wavelength of the lines in nm

  • delta_nm – Wavelength resolution in nm as the minimum wavelength interval of the spectrum. Lines comprises in half of this interval are merged.

  • line_nb – (Optional) Number of the most intense lines to retrieve. If 0 all lines are given (default 0).

  • get_name – (Optional) If True return lines name also.

other_names = {'Halpha': ['H3'], 'Hbeta': ['H4'], 'Hdelta': ['H6'], 'Hepsilon': ['H7'], 'Hgamma': ['H5'], '[NII]6583': ['[NII]6584'], '[OII]3726': ['[OII]3727'], '[SII]6716': ['[SII]6717']}

Air emission lines wavelength

round_nm2ang(nm)

Convert a wavelength in nm into a rounded value in angstrom

Parameters

nm – Line wavelength in nm

sky_lines_file_name = 'sky_lines.orb'

Name of the sky lines data file.

class orb.core.LogRecordSocketReceiver(host='localhost', port=9020, handler=<class 'orb.core.LogRecordStreamHandler'>)

Bases: socketserver.ThreadingTCPServer

Simple TCP socket-based logging receiver suitable for testing.

serve_until_stopped()
server_bind()

Called by constructor to bind the socket.

May be overridden.

class orb.core.LogRecordStreamHandler(request, client_address, server)

Bases: socketserver.StreamRequestHandler

Handler for a streaming logging request.

This basically logs the record using whatever logging policy is configured locally.

handle()

Handle multiple requests - each expected to be a 4-byte length, followed by the LogRecord in pickle format. Logs the record according to whatever policy is configured locally.

handleLogRecord(record)
unPickle(data)
class orb.core.Logger(debug=False, logfilter='default')

Bases: object

getLogger()
get_file_logging_state()

Return True if the file logging appears set

get_logdateformat()

Return a string describing the logging date format

get_logfilter(logfilter)
get_logformat()

Return a string describing the logging format

get_logging_state()

Return True if the logging is set

get_simplelogformat()

Return a string describing the simple logging format

listen()

Listen and handle logging sent on TCP socket

logfilters = {'default': <orb.core.ExtDebugLoggingFilter object>, 'extdebug': <orb.core.ExtDebugLoggingFilter object>, 'extinfo': <orb.core.ExtInfoLoggingFilter object>, 'none': <orb.core.NoLoggingFilter object>}
start_file_logging(logfile_path=None, logfilter=None)

Start file logging

Parameters

logfile_path – Path to the logfile. If none is provided a default logfile path is used.

start_logging(logfilter=None)

Reset logging only if logging is not set

Parameters

logfilter – If set to None, default logfilter set at init will be applied (default None)

class orb.core.NoInstrumentConfigParams

Bases: orb.core.ROParams

Special dictionary which elements can be accessed like attributes.

Attributes are read-only and may be defined only once.

class orb.core.NoLoggingFilter(name='')

Bases: logging.Filter

filter(record)

Determine if the specified record is to be logged.

Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.

class orb.core.Params

Bases: dict

Special dictionary which elements can be accessed like attributes.

convert()

Convert to a nice pickable object

load(path)

Load data from an HDF5 file saved with save method.

save(path)

Try to save data in an HDF5 format.

Warning

All elements might not be saved

class orb.core.ParamsFile(file_path, reset=True, **kwargs)

Bases: orb.core.Tools

Manage correspondance between multiple dict containing the same parameters and a file on disk.

Its behaviour is similar to astrometry.StarsParams.

append(params)

Append a dict to the file.

Parameters

params – A dict of parameters

f = None
get_data()
class orb.core.ProgressBar(max_index, silent=False)

Bases: object

Display a simple progress bar in the terminal

Parameters

max_index – Index representing a 100% completed task.

BAR_LENGTH = 10.0
MAX_CARAC = 78
REFRESH_COUNT = 3
end(silent=False)

End the progress bar and display the total time needed to complete the process.

Parameters

silent – If True remove the progress bar from the screen. Further diplayed text will be displayed above the progress bar.

update(index, info='', remains=True, nolog=True)

Update the progress bar.

Parameters
  • index – Index representing the progress of the process. Must be less than index_max.

  • info – (Optional) Information to be displayed as comments (default ‘’).

  • remains – (Optional) If True, remaining time is displayed (default True).

  • nolog – (Optional) No logging of the printed text is made (default True).

class orb.core.ROParams

Bases: orb.core.Params

Special dictionary which elements can be accessed like attributes.

Attributes are read-only and may be defined only once.

reset(key, value)

Force parameter reset

class orb.core.TextColor

Bases: object

Define ANSI Escape sequences to display text with colors.

CYAN = '\x1b[36m'
DEFAULT = '\x1b[0m'
END = '\x1b[0m'
GREEN = '\x1b[32m'
KORED = '\x1b[91m'
OKGREEN = '\x1b[92m'
RED = '\x1b[31m'
YELLOW = '\x1b[33m'
class orb.core.Tools(instrument=None, config=None, data_prefix='./temp/data.')

Bases: object

Base parent class for processing classes.

Load instrument config file and give access to orb data files.

filters = ['SN1', 'SN2', 'SN3', 'C1', 'C2', 'C3', 'C4', 'FULL', 'PS1_r', 'PS1_i', 'PS1_g', 'PS1_y', 'PS1_z', 'F656N', 'SPIOMM_CALIB']
instruments = ['sitelle', 'spiomm']
load_sip(fits_path)

Return a astropy.wcs.WCS object from a FITS file containing SIP parameters.

Parameters

fits_path – Path to the FITS file

save_sip(fits_path, hdr, overwrite=True)

Save SIP parameters from a header to a blanck FITS file.

Parameters
  • fits_path – Path to the FITS file

  • hdr – header from which SIP parameters must be read

  • overwrite – (Optional) Overwrite the FITS file.

set_config(key, cast, optional=False)

Set configuration parameter (from the configuration file)

update_config(config)

Update config values from a dict

Parameters

config – Configuration dictionary

class orb.core.Vector1d(*args, **kwargs)

Bases: orb.core.Data

Basic 1d vector management class.

Vector can have a projection axis.

add(vector)

Add another vector. Note that, if the axis differs, only the common part is kept.

Parameters

vector – Must be a Vector1d instance.

crop(xmin, xmax, returned_class=None)

Crop data. :param xmin: xmin :param xmax: xmax

math(opname, arg=None)

Do math operations with another vector instance.

Parameters
  • opname – math operation, must be a numpy.ufuncs.

  • arg – If None, no argument is supplied. Else, can be a float or a Vector1d instance.

multiply(vector)

Multiply by another vector. Note that, if the axis differs, only the common part is kept.

Parameters

vector – Must be a Cm1Vector1d instance.

plot(plot_real=True, **kwargs)

Plot vector

Parameters
  • plot_real – If True, plot only the real part, if False plot only the imaginary part, if both, plot the real and imaginary part. Plot only the real part by default.

  • kwargs – All keyword arguments accepted by matplotlib.plot()

project(new_axis, returned_class=None, quality=10, timing=False)

Project vector on a new axis

Parameters
  • new_axis – Axis. Must be an orb.core.Axis instance.

  • returned_class – (Optional) If not None, set the returned class. Must be a subclass of Vector1d.

  • quality – an integer from 2 to infinity which gives the zero padding factor before interpolation. The more zero padding, the better will be the interpolation, but the slower too.

Returns

A new Spectrum instance

Warning

Though much (much!) faster than pure resampling, this can be a little less precise for complex data. For non complex data, its nothing more than a linear interpolation.

reverse()

Reverse data. Do not reverse the axis.

subtract(vector)

Subtract another vector. Note that, if the axis differs, only the common part is kept.

Parameters

vector – Must be a Cm1Vector1d instance.

sum()

Sum of the data

class orb.core.WCSData(data, instrument=None, config=None, data_prefix='./', sip=None, reset_wcs=False, **kwargs)

Bases: orb.core.Tools, orb.core.Data

Add WCS functionalities to a Data instance.

arc2pix(x)

Convert pixels to arcseconds

Parameters

x – a value or a vector in pixel

assert_dxdymaps()

Raise an exception if dxdymaps are not loaded

convert_params = {'AIRMASS': 'airmass', 'BINNING': 'binning', 'CAMERA': 'camera', 'EXPTIME': 'exposure_time', 'FILTER': 'filter_name', 'INSTRUME': 'instrument', 'camera_number': 'camera'}
default_params = {'camera': 1, 'target_dec': 0.0, 'target_ra': 0.0, 'target_x': 0, 'target_y': 0}
get_initial_alignment_parameters()

Return initial alignemnt coefficients for camera 2 as a core.Params instance

get_scale()

Return mean platescale in arcsec/pixel

get_wcs(validate=True)

Return the WCS of the cube as an astropy.wcs.WCS instance

get_wcs_header()

Return the WCS of the cube as a astropy.io.fits.Header instance

has_dxdymaps()

Return True is self.dxmap and self.dymap exist

is_cam1()

Return true is image comes from camera 1 or is a merged frame

is_cam2()

Return true is image comes from camera 2

pix2arc(x)

Convert arcseconds to pixels

Parameters

x – a value or a vector in arcsec

pix2world(xy, deg=True)

Convert pixel coordinates to celestial coordinates

Parameters
  • xy – A tuple (x,y) of pixel coordinates or a list of tuples ((x0,y0), (x1,y1), …)

  • deg – (Optional) If true, celestial coordinates are returned in sexagesimal format (default False).

Note

it is much more efficient to pass a list of coordinates than run the function for each couple of coordinates you want to transform.

query_vizier(catalog='gaia', max_stars=100, as_pandas=False)

Return a list of star coordinates around an object in a given radius based on a query to VizieR Services (http://vizier.u-strasbg.fr/viz-bin/VizieR)

Parameters
  • catalog – (Optional) Catalog to ask on the VizieR database (see notes) (default ‘gaia’)

  • max_stars – (Optional) Maximum number of row to retrieve (default 100)

  • as_pandas – (Optional) If True, results are returned as a pandas.DataFrame instance. Else a numpy.ndarray instance is returned (default False).

See also

orb.orb.utils.web.query_vizier()

set_dxdymaps(dxmap, dymap)

Set dxmap and dymap. Must have the same shape as the image shape.

Parameters
  • dxmap – Path to a dxmap or a numpy.ndarray

  • dymap – Path to a dymap or a numpy.ndarray

set_wcs(wcs)

Set WCS from a WCS instance or a FITS image

Parameters

wcs – Must be an astropy.wcs.WCS instance or a path to a FITS image

validate_wcs()

Verify the internal coherence between comprehensive wcs parameters and FITS keywords.

world2pix(radec)

Convert celestial coordinates to pixel coordinates

Parameters

xy – A tuple (x,y) of celestial coordinates or a list of tuples ((x0,y0), (x1,y1), …). Must be in degrees.

Note

it is much more effficient to pass a list of coordinates than run the function for each couple of coordinates you want to transform.

writeto(path)

Write data to an hdf file

Parameters

path – hdf file path.

class orb.core.Waves(nm, velocity=0.0)

Bases: object

Wave class that keep the best conversions possible from nm to cm1.

get_cm1()

Return wavenumber of waves in cm-1 (taking velocity into account)

get_cm1_rest()

Return restframe wavelength of waves in cm-1

get_nm()

Return wavelength of waves in nm (taking velocity into account)

get_nm_rest()

“Return restframe wavelength of waves in nm

set_velocity(velocity)

Set waves velocity.

Parameters

velocity – velocity in km/s

orb.cube module

Cube handling module

class orb.cube.Cube(path, params=None, instrument=None, **kwargs)

Bases: orb.cube.HDFCube

Provide additional cube methods when observation parameters are known.

get_axis_corr()

Return the reference wavenumber correction

get_base_axis()

Return the spectral axis (in cm-1) at the center of the cube

get_uncalibrated_filter_bandpass()

Return filter bandpass as two 2d matrices (min, max) in pixels

integrate(filter_function, xmin=None, xmax=None, ymin=None, ymax=None, split=100, mean=True, square_filter=False)

Integrate a cube under a filter function and generate an image

Parameters
  • filter_function – Must be an orb.core.Cm1Vector1d instance or the name of a filter registered in orb/data/

  • xmin – (Optional) lower boundary of the ROI along x axis (default None, i.e. min)

  • xmax – (Optional) lower boundary of the ROI along y axis (default None, i.e. min)

  • ymin – (Optional) upper boundary of the ROI along x axis (default None, i.e. max)

  • ymax – (Optional) upper boundary of the ROI along y axis (default None, i.e. max)

needed_params = ('step', 'order', 'filter_name', 'exposure_time', 'step_nb', 'zpd_index')
validate()

Check if this class is valid

class orb.cube.FDCube(image_list_path, image_mode='classic', chip_index=1, no_sort=False, silent_init=False, **kwargs)

Bases: orb.core.Tools

Basic handling class for a set of frames grouped into one virtual cube.

This is a basic class which is mainly used to export data into an hdf5 cube.

export(export_path, mask=None, params=None)

Export FDCube as an hdf5 cube

Parameters
  • export_path – Export path

  • mask – (Optional) A boolean array of shape (self.dimx, self.dimy) which zeros indicates bad pixels to be replaced with Nans when reading data (default None).

  • params – (Optional) A dict of parameters that will be added to the exported cube.

get_cube_header()

Return the header of a cube from the header of the first frame by keeping only the general keywords.

get_frame_header(index)

Return the header of a frame given its index in the list.

The header is returned as an instance of pyfits.Header().

Parameters

index – Index of the frame

Note

Please refer to http://www.stsci.edu/institute/software_hardware/pyfits/ for more information on PyFITS module and http://fits.gsfc.nasa.gov/ for more information on FITS files.

class orb.cube.HDFCube(path, indexer=None, instrument=None, config=None, data_prefix='./', **kwargs)

Bases: orb.core.WCSData

This class implements the use of an HDF5 cube.

compute_sum_image(step_size=100)

compute the sum along z axis

copy()

Return a copy of the instance

Parameters
  • data – (Optional) can be used to change data

  • kwargs – Addition kwargs (useful to copy child classes with more kwargs at init)

crop(path, cx, cy, size)

Extract a part of the file and write it to a new hdf file

WCS and most datasets will be croped also to try to keep a valid cube

Parameters
  • cx – X center position

  • xy – Y center position

  • size – Size of the cropped rectangle. A tuple (sz, sy). Can be single int in which case the cropped data is a box.

Warning

size of the returned box is not guaranteed if cx and cy are on the border of the image.

detect_fwhm(star_list)
detect_stars(**kwargs)

Detect valid stars in the image

Parameters

kwargs – orb.image.Image.detect_stars kwargs.

fit_stars_in_cube(star_list, path=None, correct_alignment=False, alignment_vectors=None, add_cube=None, **kwargs)

Fit stars in the cube.

Frames must not be too disaligned. Disalignment can be corrected as the cube is fitted by setting correct_alignment option to True.

Note

2 fitting modes are possible:

* Individual fit mode [multi_fit=False]
* Multi fit mode [multi_fit=True]

see astrometry.utils.fit_stars_in_frame() for more information.

Parameters
  • path – (Optional) path where the results are saved to.

  • correct_alignment – (Optional) If True, the initial star positions from the star list are corrected by their last recorded deviation. Useful when the cube is smoothly disaligned from one frame to the next.

  • alignment_vectors – (Optional) If not None, must be a tuple of 2 vectors (dx, dy), each one having the same length as the number of frames in the cube. It is used as a guess for the alignement of the stars.

  • add_cube – (Optional) A tuple [Cube instance, coeff]. This cube is added to the data before the fit so that the fitted data is self.data[] + coeff * Cube[].

  • kwargs – (Optional) orb.utils.astrometry.fit_stars_in_frame kwargs.

fit_stars_in_frame(star_list, index, **kwargs)

Fit stars in frame

Parameters
  • star_list – Path to a list of stars

  • index – frame index

  • kwargs – orb.image.Image.fit_stars kwargs.

get_airmass()

Return the airmass

get_alignment_vectors(star_list, min_coeff=0.2, alignment_vectors=None, path=None)

Return alignement vectors

Parameters
  • star_list – list of stars

  • min_coeff – The minimum proportion of stars correctly fitted to assume a good enough calculated disalignment (default 0.2).

  • path – If not None, fit results are written to this path

Returns

alignment_vector_x, alignment_vector_y, alignment_error

get_all_data()

Return the whole data cube

get_axis(x, y)

Return the axis at x, y

get_binned_cube(binning)

Return the binned version of the cube

get_calibration_coeff_map()

Return calibration laser map

get_calibration_laser_map(checkattr=True)

Return calibration laser map

get_data(x_min, x_max, y_min, y_max, z_min, z_max, silent=False)

Return a part of the data cube.

Parameters
  • x_min – minimum index along x axis

  • x_max – maximum index along x axis

  • y_min – minimum index along y axis

  • y_max – maximum index along y axis

  • z_min – minimum index along z axis

  • z_max – maximum index along z axis

  • silent – (Optional) deprecated, only here for old cube architecture (default False).

get_data_frame(index)

Return one frame of the cube.

Parameters

index – Index of the frame to be returned

get_data_from_region(region)

Return a list of vectors extracted along the 3rd axis at the pixel positions defined by a list of pixels.

Return also a list of corresponding axes if self.get_axis() returns something else than None.

Note

pixels do not have to be contiguous but, as the quadrant containing all the pixels is extracted primarily to speed up the process, they should be contained in a field small enough to avoid filling the RAM (a 400x400 pixels box is generally a good limit).

Parameters

region – A ds9-like region file or a list of pixels having the same format as the list returned by np.nonzero(), i.e. (x_positions_1d_array, y_positions_1d_array).

get_dataset(path, protect=True)

Return a dataset (but not ‘data’, instead use get_data).

Parameters
  • path – dataset path

  • protect – (Optional) check if dataset is protected (default True).

get_dataset_attrs(path)

Return the attributes attached to a dataset

get_datasets()

Return all datasets contained in the cube

get_deep_frame(recompute=False, compute=True)

Return the deep frame of a cube (in counts, i.e. e- x gain).

Parameters
  • compute – (Optional) If True, deep frame can be computed if not already present. If False, raise an exception when deep frame is not already present (default True).

  • recompute – (Optional) Force deep frame computation even if it is already present in the cube (default False).

… warning:: deep frame computation should only be done on an

interferogram cube. Deep frame computed on a spectral cube is much more noisy by definition.

Note

In this process NaNs are handled correctly

get_detection_frame()
get_dxdymaps()

Return dxdymaps.

get_frame_header(index)

Return the header of a frame given its index in the list.

The header is returned as an instance of pyfits.Header().

Parameters

index – Index of the frame

get_gain()

Return camera gain value

get_high_order_phase()

Return high order phase.

This is just the config high order phase

get_level()

Return reduction level of the cube.

  • level 1: old hdf5 architecture, real output, unit in erg/cm2/s/A, deep frame is the mean of the interferogram cube

  • level 2: new hdf5 architecture, real output, unit in erg/cm2/s/A, deep frame is the sum of the interferogram cube

  • level 3: new hdf5 architecture, complex output, unit in counts, data can be calibrated via flambda parameter : spectrum *= cube.params.flambda / cube.dimz / cube.exposure_time, deep frame is the sum of the interferogram cube

  • level 2.5: CFHT version, similar to level3 but calibrated data is hard written. Used calibration vector is cube.params.flambda2. spectrum = spectrum_counts * cube.params.flambda.

get_master_frame(combine=None, reject=None)

Combine frames along z to create a master frame.

Parameters
  • reject – (Optional) Rejection operation for master frames creation. Can be ‘sigclip’, ‘minmax’, ‘avsigclip’ or None (default ‘avsigclip’). See orb.utils.image.create_master_frame().

  • combine – (Optional) Combining operation for master frames creation. Can be ‘average’ or ‘median’ (default ‘average’). See orb.utils.image.create_master_frame().

get_phase_maps()

Return a PhaseMaps instance if phase maps are set

get_quadrant_dims(quad_number, div_nb=None, dimx=None, dimy=None)

Return the indices of a quadrant along x and y axes.

Parameters
  • quad_number – Quadrant number

  • div_nb – (Optional) Use another number of divisions along x and y axes. (e.g. if div_nb = 3, the number of quadrant is 9 ; if div_nb = 4, the number of quadrant is 16)

  • dimx – (Optional) Use another x axis dimension. Other than the axis dimension of the managed data cube

  • dimy – (Optional) Use another y axis dimension. Other than the axis dimension of the managed data cube

get_raw_alignement_vectors(star_number=60, searched_size=80)

Return raw alignment vectors based on brute force.

Slow but useful when alignment between frames is very bad.

Returns

dx, dy vectors

get_region(region, integrate=True)

Return a list of valid pixels from a ds9 region file or a ds9-style region definition

e.g. for a circle defined in celestial coordinates:

“fk5;circle(290.96388,14.019167,843.31194”)”

Parameters
  • region – a ds9 region file path or a ds9-style region definition as a string.

  • integrate – Used when multiple regions are defined. If True, all regions are integrated. If False, a list of individual regions is returned.

get_resized_data(size_x, size_y)
Resize the data cube and return it using spline

interpolation.

This function is used only to resize a cube of flat or dark frames. Note that resizing dark or flat frames must be avoided.

Parameters
  • size_x – New size of the cube along x axis

  • size_y – New size of the cube along y axis

Warning

This function must not be used to resize images containing star-like objects (a linear interpolation must be done in this case).

get_theta_map()

Return the incident angle map from the calibration laser map

get_zvector(x, y, r=0, return_region=False, median=False)

Return an orb.fft.Vector1d instance taken at a given position in x, y.

Parameters
  • x – x position

  • y – y position

  • r – (Optional) If r > 0, vector is integrated over a circular aperture of radius r. In this case the number of pixels is returned as a parameter: pixels

  • median – If True, a median is used instead of a mean to combine vectors. As the resulting vector is integrated, the median value of the combined spectra is then scaled to the number of integrated pixels.

  • return_region – (Optional) If True, region is returned also (default False)

get_zvector_from_region(region, median=False)

Return an orb.fft.Vector1d instance integrated over a given region

Parameters
  • region – A ds9-like region file or a list of pixels having the same format as the list returned by np.nonzero(), i.e. (x_positions_1d_array, y_positions_1d_array).

  • median – If True, a median is used instead of a mean to combine vectors. As the resulting vector is integrated, the median value of the combined spectra is then scaled to the number of integrated pixels.

has_dataset(path)

Check if a dataset is present

has_same_2D_size(cube_test)

Check if another cube has the same dimensions along x and y axes.

Parameters

cube_test – Cube to check

is_level1()

Return True if cube is level 1

open_hdf5(mode='r')

Return a handle on the hdf5 file.

Parameters

mode – opening mode. can be ‘r’ or ‘a’.

optional_params = ('target_ra', 'target_dec', 'target_x', 'target_y', 'dark_time', 'flat_time', 'camera', 'wcs_rotation', 'calibration_laser_map_path')
protected_datasets = ('data', 'mask', 'header', 'deep_frame', 'params', 'axis', 'calib_map', 'phase_map', 'phase_map_err', 'phase_maps_coeff_map', 'phase_maps_cm1_axis', 'standard_image', 'standard_spectrum')
to_fits(path)

write data to a FITS file.

Note that most of the information will be lost in the process. The only output guaranteed format is hdf5 (use writeto() method instead)

Parameters

path – Path to the FITS file

validate_x_index(x, clip=True)

validate an x index, return an integer inside the boundaries or raise an exception if it is off boundaries

Parameters
  • x – x index

  • clip – (Optional) If True return an index inside the boundaries, else: raise an exception (default True).

validate_y_index(y, clip=True)

validate an y index, return an integer inside the boundaries or raise an exception if it is off boundaries

Parameters
  • y – y index (can be an array or a list of indexes)

  • clip – (Optional) If True return an index inside the boundaries, else: raise an exception (default True).

writeto(path, div_nb=4)

Write data to an hdf file

Parameters
  • path – hdf file path.

  • div_nb – cube is extracted by quadrant to avoid feeling the RAM. In case of memory error just use a higher number of divisions.

class orb.cube.InterferogramCube(path, params=None, instrument=None, **kwargs)

Bases: orb.cube.Cube

Provide additional methods for an interferogram cube when observation parameters are known.

get_interferogram(x, y, r=0, median=False)

Return an orb.fft.Interferogram instance.

See Cube.get_zvector for the parameters.

get_mean_interferogram(xmin, xmax, ymin, ymax)

Return mean interferogram in a box [xmin:xmax, ymin:ymax, :] along z axis

Parameters
  • xmin – min boundary along x axis

  • xmax – max boundary along x axis

  • ymin – min boundary along y axis

  • ymax – max boundary along y axis

get_phase(x, y)

If phase maps are set, return the phase at x, y

get_spectrum(x, y, r=0)

Return an orb.fft.Spectrum instance.

phase_maps must be set to get a reliable spectrum

See Cube.get_zvector for the parameters.

class orb.cube.MockArray(path=None)

Bases: object

class orb.cube.RWHDFCube(path, shape=None, instrument=None, reset=False, dtype=<class 'numpy.float32'>, **kwargs)

Bases: orb.cube.HDFCube

set_calibration_laser_map(calib_map)

Set calibration map.

Parameters

calib_map – Calibration map

set_dataset(path, data, protect=True)

Write a dataset to the hdf5 file

Parameters
  • path – dataset path

  • data – data to write.

  • protect – (Optional) check if dataset is protected (default True).

set_deep_frame(deep_frame)

Append a deep frame to the HDF5 cube.

Parameters

deep_frame – Deep frame to append.

set_dxdymaps(dxmap, dymap)

Set dxdymaps

Parameters
  • dxmap – dxmap

  • dymap – dymap

set_frame_header(index, header)

Set the header of a frame.

The header must be an instance of pyfits.Header().

Parameters
  • index – Index of the frame

  • header – Header as a pyfits.Header instance.

set_mask(data)

Set mask

A mask must have the shape of the data but for 3d data which has a 2d mask (self.dimx, self.dimy). A Zero indicates a pixel which should be masked (Nans are returned for this pixel).

Parameters

data – mask. Must be a boolean array

set_param(key, value)

Set class parameter

Parameters
  • key – parameter key

  • value – parameter value

set_params(params)

Set class parameters

Parameters

params – a dict of parameters

set_phase_maps(phase_maps)

Set phase maps from a PhaseMaps instance

set_standard_image(std_im)

Set standard image

Parameters

std_im – An image.Image instance or a path to an hdf5 image.

set_standard_spectrum(std_sp)

Set standard spectrum

Parameters

std_sp – a orb.photometry.StandardSpectrum instance or a path to an hdf5 spectrum.

write_frame(index, data=None, header=None, section=None, record_stats=False)

Write a frame.

This function is here for backward compatibility but a simple self[:,:,index] may be used instead.

Parameters
  • index – Index of the frame

  • data – (Optional) Frame data (default None).

  • header – (Optional) Frame header (default None).

  • section – (Optional) If not None, must be a 4-tuple [xmin, xmax, ymin, ymax] giving the section to write instead of the whole frame. Useful to modify only a part of the frame (default None).

  • record_stats – (Optional) If True, frame stats are recorder in its header (default False).

class orb.cube.SpectralCube(*args, **kwargs)

Bases: orb.cube.Cube

Provide additional methods for a spectral cube when observation parameters are known.

compute_flambda(deg=1, std_im=None, std_sp=None)

Return flamba calibration function

Parameters
  • deg – Degree of the polynomial used to fit the flux correction vector (this is only used if std_sp is set to a standard spectrum.)

  • std_im – Standard image used to correct the absolute calibration.

  • std_sp – Standard spectrum used to compute the wavelength dependant flux calibration.

compute_modulation_ratio()
get_axis(x, y)

Return the spectral axis at x, y

get_calibration_coeff_map()

Return the calibration coeff map based on the calibration laser map and the laser wavelength.

get_calibration_coeff_map_orig()

Return the original calibration coeff map (not the version computed by get_calibration_coeff_map())

get_calibration_laser_map()

Return the calibration laser map of the cube

get_calibration_laser_map_orig()

Return the original calibration laser map (not the version computed by get_calibration_laser_map())

get_deep_frame(recompute=False, compute=False)

Return the deep frame of a cube (in counts, i.e. e- x gain).

Parameters
  • compute – (Optional) If True, deep frame can be computed if not already present. If False, raise an exception when deep frame is not already present (default True).

  • recompute – (Optional) Force deep frame computation even if it is already present in the cube (default False).

… warning:: deep frame computation should only be done on an

interferogram cube. Deep frame computed on a spectral cube is much more noisy by definition.

Note

In this process NaNs are handled correctly

get_filter_range()

Return the range of the filter in the unit of the spectral cube as a tuple (min, max)

get_filter_range_pix(xy=None, border_ratio=0.0)

Return the range of the filter in channel index as a tuple (min, max)

get_fwhm_map()

Return the theoretical FWHM map in cm-1 based only on the angle and the theoretical attained resolution.

get_mask_from_ds9_region_file(region, integrate=True)

Return a mask from a ds9 region file.

Parameters
  • region – Path to a ds9 region file.

  • integrate – (Optional) If True, all pixels are integrated into one mask, else a list of region masks is returned (default True)

get_sky_lines()

Return the wavenumber of the sky lines in the filter range

get_spectrum(x, y, r=0, median=False, mean_flux=False)

Return a orb.fft.RealSpectrum extracted at x, y and integrated over a circular aperture or radius r.

Parameters
  • x – x position

  • y – y position

  • r – (Optional) If r > 0, vector is integrated over a circular aperture of radius r. In this case the number of pixels is returned as a parameter: pixels

  • median – If True, a median is used instead of a mean to combine spectra. As the resulting spectrum is integrated, the median value of the combined spectra is then scaled to the number of integrated pixels.

  • mean_flux – If True, the mean spectrum (ie per pixel flux) is returned.

get_spectrum_bin(x, y, b, median=False, mean_flux=False)

Return a spectrum integrated over a binned region.

Parameters
  • x – X position of the bottom-left pixel

  • y – Y position of the bottom-left pixel

  • b – Binning. If 1, only the central pixel is extracted

  • median – If True, a median is used instead of a mean to combine spectra. As the resulting spectrum is integrated, the median value of the combined spectra is then scaled to the number of integrated pixels.

  • mean_flux – If True, the mean spectrum (ie per pixel flux) is returned.

Returns

(axis, spectrum)

get_spectrum_from_region(region, median=False, mean_flux=False)

Return the integrated spectrum of a given region.

Parameters
  • region – A ds9-like region file or a list of pixels having the same format as the list returned by np.nonzero(), i.e. (x_positions_1d_array, y_positions_1d_array).

  • median – If True, a median is used instead of a mean to combine spectra. As the resulting spectrum is integrated, the median value of the combined spectra is then scaled to the number of integrated pixels.

  • mean_flux – If True, the mean spectrum (ie per pixel flux) is returned.

Note

the region must not have a size greater than 400x400 pixels. If you really need a larger region, you can split you region into smaller ones and combine the resulting spectra.

get_spectrum_in_annulus(x, y, rmin, rmax, median=False, mean_flux=False)

Return a. orb.fft.RealSpectrum extracted at x, y and integrated over a circular annulus of min radius rmin and max radius rmax.

Parameters
  • x – x position

  • y – y position

  • rmin – rmin of the annulus

  • rmax – rmax of the annulus

  • median – If True, a median is used instead of a mean to combine spectra. As the resulting spectrum is integrated, the median value of the combined spectra is then scaled to the number of integrated pixels.

  • mean_flux – If True, the mean spectrum (ie per pixel flux) is returned.

get_standard_image()

Return standard image

get_standard_spectrum()

Return standard spectrum

get_theta_map()

Return the incident angle map (in degree)

has_flux_calibration()

Return True if the cube is calibrated in flux

has_wavenumber_calibration()

Return True if the cube is calibrated in wavenumber

has_wcs_calibration()

Return True if the cube has valid wcs

reset_calibration_coeff_map()

Reset the computed calibration coeff map alone

reset_calibration_laser_map()

Reset the compute calibration laser map (and also the calibration coeff map). Must be called when the wavenumber calibration has changed

..seealso :: correct_wavelength()

reset_params()

Reset parameters

set_flambda(flambda)

Set flux calibration.

Parameters

flambda – must be core.Cm1Vector1d instance.

orb.cutils module

orb.fft module

class orb.fft.HighOrderPhaseCube(*args, **kwargs)

Bases: orb.core.Data

generate_phase_cube(path, dimx, dimy, axis=None)
get_map(order)
get_phase(x, y, asarr=False, axis=None)
get_phase_coeffs(x, y)
class orb.fft.Interferogram(interf, err=None, axis=None, params=None, **kwargs)

Bases: orb.core.Vector1d

Interferogram class.

apodize(window_type, inplace=False)

Apodization of the interferogram

Parameters

window_type – Name of the apodization function (can be ‘learner95’ or a float > 1.)

crop(xmin, xmax)

Crop data. see Vector1d.crop()

get_phase()

Classical phase computation method. Returns a Phase instance.

get_spectrum(mertz=True)

Classical spectrum computation method. Returns a Spectrum instance.

Parameters

mertz – If True, multiply by Mertz ramp. Must be used for assymetric interferograms.

is_right_sided()

Check if interferogram is right sided (left side wrt zpd shorter than right side)

multiply_by_mertz_ramp(inplace=False)

Multiply by Mertz (1976) ramp function to avoid counting symmetric samples twice and reduce emission lines contrast wrt the background.

needed_params = ('step', 'order', 'zpd_index', 'calib_coeff', 'filter_name', 'exposure_time')
subtract_low_order_poly(order=3, inplace=False)

low order polynomial substraction to suppress low frequency noise

Parameters

order – (Optional) Polynomial order (beware of high order polynomials, default 3).

subtract_mean(inplace=False)

substraction of the mean of the interferogram where the interferogram is not nan

symmetric()

Return an interferogram which is symmetric around the zpd

transform()

zero padded fft.

Returns

A Spectrum instance (or a core.Vector1d instance if interferogram is full of zeros or nans)

Note

no phase correction is made here.

class orb.fft.Phase(spectrum, axis=None, params=None, **kwargs)

Bases: orb.core.Cm1Vector1d

Phase class

cleaned(border_ratio=0.0)

Return a cleaned phase vector with values out of the filter set to nan and a median around 0 (modulo pi).

Parameters

border_ratio – (Optional) Relative portion of the phase in the filter range removed (can be a negative float, default 0.)

Returns

A Phase instance

polyfit(deg, amplitude=None, coeffs=None, return_coeffs=False, border_ratio=0.1)

Polynomial fit of the phase

Parameters
  • deg – Degree of the fitting polynomial. Must be >= 0.

  • amplitude – (Optional) Amplitude of the spectrum. Used to weight the phase data (default None).

  • coeffs – (Optional) Used to fix some coefficients to a given value. If not None, must be a list of length = deg. set a coeff to a np.nan or a None to let the parameter free (default None).

  • return_coeffs – (Optional) If True return (fit coefficients, error on coefficients) else return a Phase instance representing the fitted phase (default None).

  • border_ratio – (Optional) relative width on the borders of the filter range removed from the fitted values (default 0.1)

subtract_low_order_poly(deg, border_ratio=0.1)

low order polynomial substraction to suppress low frequency noise

Parameters
  • deg – Degree of the fitting polynomial. Must be >= 0.

  • border_ratio – (Optional) relative width on the borders of the filter range removed from the fitted values (default 0.1)

class orb.fft.PhaseMaps(phase_maps_path, overwrite=False, indexer=None, **kwargs)

Bases: orb.core.Tools

generate_phase_cube(path, coeffs=None, x_range=None, y_range=None, silent=False)

Generate a phase cube from the given phase maps.

Parameters

coeffs – Used to set some coefficients to a given value. If not None, must be a list of length = order. set a coeff to a np.nan to use the phase map value.

get_coeffs(x, y, unbin=False)

Return coeffs at position x, y in the maps. x, y are binned position by default (set unbin to True to get real positions on the detector)

Parameters
  • x – X position (dectector position)

  • y – Y position (dectector position)

  • unbin – If True, positions are unbinned position (i.e. real positions on the detector) (default False).

get_map(order)

Return map of a given order

Parameters

order – Polynomial order

get_map_err(order)

Return map uncertainty of a given order

Parameters

order – Polynomial order

get_mapped_model(order)

Return mapped model

get_phase(x, y, unbin=False, coeffs=None)

Return a phase instance at position x, y in the maps. x, y are binned position by default (set unbin to True to get real positions on the detector)

Parameters
  • x – X position (dectector position)

  • y – Y position (dectector position)

  • unbin – If True, positions are unbinned position (i.e. real positions on the detector) (default False).

  • coeffs – Used to set some coefficients to a given value. If not None, must be a list of length = order. set a coeff to a np.nan to use the phase map value.

modelize()

Replace phase maps by their model inplace

phase_maps = None
reverse_polarity()

Add pi to the order 0 phase map to reverse polarity of the corrected spectrum.

unwrap_phase_map_0()

Unwrap order 0 phase map.

Phase is defined modulo pi/2. The Unwrapping is a reconstruction of the phase so that the distance between two neighboor pixels is always less than pi/4. Then the real phase pattern can be recovered and fitted easily.

The idea is the same as with np.unwrap() but in 2D, on a possibly very noisy map, where a naive 2d unwrapping cannot be done.

validate_xy(x, y, unbin=False)
class orb.fft.RealInterferogram(*args, **kwargs)

Bases: orb.fft.Interferogram

Class used for an observed interferogram in counts

combine(interf, transmission=None, ratio=None)

Combine two interferograms (one from each camera) and return the result

Parameters
  • interf – Another Interferogram instance coming from the complementary camera.

  • transmission – (Optional) Must be a Vector1d instance. if None supplied, transmission is computed from the combined interferogram which may add some noise (default None).

  • ratio – (Optional) optical transmission ratio self / interf. As the beamsplitter and the differential gain of the cameras produce a difference in the number of counts collected in one camera or the other, the interferograms must be corrected for this ratio before being combined. If None, this ratio is computed from the provided interferograms.

compute_transmission(interf)

Return the transmission vector computed from the combination of two complementary interferograms.

Parameters

interf – Another Interferogram instance coming from the complementary camera.

math(opname, arg=None)

Do math operations and update the ‘source_counts’ value.

Parameters
  • opname – math operation, must be a numpy.ufuncs.

  • arg – If None, no argument is supplied. Else, can be a float or a Vector1d instance.

subtract_sky(sky)

Subtract sky interferogram (or any background interferogram).

The values of the parameter ‘pixels’ in both this interferogram and the sky interferogram should be set to the number of integrated pixels.

transform()

Zero padded fft. See Interferogram.transform()

class orb.fft.RealSpectrum(*args, **kwargs)

Bases: orb.fft.Spectrum

Spectrum class computed from real interferograms (in counts)

compute_counts_in_spectrum()

Return the number of counts in the spectrum

compute_me()

Return the modulation efficiency, computed from the ratio between the number of counts in the original interferogram and the number of counts in the spectrum.

subtract_sky(sky)

Subtract spectrum interferogram (or any background spectrum).

Parameters

sky – A spectrum instance.

The values of the parameter ‘pixels’ in both this interferogram and the sky interferogram should be set to the number of integrated pixels.

class orb.fft.Spectrum(spectrum, err=None, axis=None, params=None, **kwargs)

Bases: orb.core.Cm1Vector1d

Spectrum class

apodize(coeff)

Return an apodized spectrum (works well only if spectrum is complex)

autofit(lines, *args, **kwargs)
correct_phase(phase)

Correct spectrum phase

Parameters

phase – can be a 1d array or a Phase instance.

estimate_flux(lines, vel, max_comps=1)
estimate_parameters(lines, vel_range, max_comps=1, precision=10, threshold=1, prod=True, return_score=False)
estimate_velocity_prepared(combs, vels, precision, filter_range_pix, max_comps=1, threshold=1, prod=True, return_score=False)
fit(lines, fmodel='sinc', nofilter=True, max_iter=None, nogvar=False, **kwargs)

Fit lines in a spectrum

Wrapper around orb.fit.fit_lines_in_spectrum.

Parameters
  • lines – lines to fit.

  • max_iter – (Optional) Maximum number of iterations (default None)

  • kwargs – kwargs used by orb.fit.fit_lines_in_spectrum.

get_amplitude()

return amplitude

get_imag()

Return the imaginary part

get_phase()

return phase

get_real()

Return the real part

interpolate(axis, quality=10, timing=False)

Resample spectrum by interpolation over the given axis

This is a simple wrapper around core.Vector1d.project which now integrates all the fft interpolation method when data is complex.

It has been kept for backward compatibility. Please use the project method.

inverse_transform()

Return the inverse transform of the spectrum. This should be the exact inverse transform of Interferogram.transform()

prepare_fit(lines, fmodel='sinc', nofilter=True, **kwargs)

Return the input parameters, which can be reused to accelerate similar fits.

prepare_velocity_estimate(lines, vel_range, precision=10)
prepared_fit(inputparams, max_iter=None, nogvar=False, **kwargs)

Run a fit already prepared with prepare_fit() method.

zpd_shift(shift)

correct spectrum phase from shifted zpd

class orb.fft.StandardSpectrum(*args, **kwargs)

Bases: orb.fft.RealSpectrum

Spectrum class for standard spectrum computed from real interferograms (in counts).

Spectrum unit should be in counts.

compute_flux_correction_vector(deg=None, resolution=None, return_residual=False)

Compute flux correction vector by fitting a simulated model of the standard star on the observed spectrum.

convert_params = {'AIRMASS': 'airmass', 'CAMERA': 'camera', 'EXPTIME': 'exposure_time', 'FILTER': 'filter_name', 'INSTRUME': 'instrument'}
get_standard()

Return the standard spectrum

to_counts_s()

Return spectrum in counts/s

orb.fit module

Fit module of ORB.

Defines the general Fitting classes and the fitting models.

Best accessed through fit_lines_in_*() functions (defined at the end of the file)

class orb.fit.Cm1InputParams(step, order, step_nb, nm_laser, theta_proj, theta_orig, apodization, zpd_index, filter_name)

Bases: orb.fit.InputParams

Manage the input parameters for orb.fit.FitVector and orb.fit.fit_lines_in_spectrum().

add_filter_model(**kwargs)
add_lines_model(lines, **kwargs)
check_signal_range()
convert()

Convert class to a pickable dict object

set_signal_range(rmin, rmax)
class orb.fit.Cm1LinesModel(p_dict)

Bases: orb.fit.LinesModel

Emission/absorption lines model with a channel unity in cm-1.

Reimplements fit.LinesModel to use more physical units : channels are translated to cm-1 and velocity to km/s in input and output.

See also

For more information please refer to fit.LinesModel

accepted_keys = ['line_nb', 'fmodel', 'ratio', 'amp_def', 'pos_def', 'fwhm_def', 'sigma_def', 'alpha_def', 'amp_cov', 'pos_cov', 'fwhm_cov', 'sigma_cov', 'alpha_cov', 'amp_guess', 'pos_guess', 'fwhm_guess', 'sigma_guess', 'alpha_guess', 'step_nb', 'step', 'order', 'nm_laser', 'nm_laser_obs']

Accepted keys of the input dictionary (see fit.Model.p_dict)

parse_dict()

Parse input dictionary fit.Model.p_dict

class orb.fit.ContinuumModel(p_dict)

Bases: orb.fit.Model

Polynomial continuum model.

Input dictionary fit.Model.p_dict:

{'poly_order':
 'poly_guess':}
Parameters
  • poly_order – Order of the polynomial to fit (be careful with high order polynomials).

  • poly_guess – Initial guess on the coefficient values : must be a tuple of length poly_order + 1.

Note

This model must be added to the others.

accepted_keys = ('poly_def', 'poly_order', 'poly_guess')

Accepted keys of the input dictionary (see fit.Model.p_dict)

check_input()

Check input parameters

get_model(x, p_free=None, return_models=False, multf=None, return_complex=False)

Return model M(x, p).

Parameters
  • x – Positions where the model M(x, p) is computed.

  • p_free – (Optional) New values of the free parameters (default None).

  • multf – 1d vector with the same length as x vector which represent the function by which the model must be multiplied.

  • return_models – (Optional) If True return also individual models (default False)

  • return_complex – (Optional) If True return a complex model (default False).

get_p_val_as_array(p_val=None)
make_guess(v)

If a parameter value at init is a NaN this value is guessed.

Parameters

v – Data vector from which the guess is made.

parse_dict()

Parse input dictionary fit.Model.p_dict

class orb.fit.FilterModel(p_dict)

Bases: orb.fit.Model

Simple model of filter based on a real filter shape. The only possible free parameter is a wavelength/wavenumber shift.

Input dictionary fit.Model.p_dict:

{'filter_function':,
 'shift_guess':,
 'shift_def':}
Parameters
  • filter_function – Transmission of the filter over the fitted spectral range (axis must be exactly the same).

  • shift_guess – Guess on the filter shift in pixels.

  • shift_def – Definition of the shift parameter, can be ‘free’ or ‘fixed’

Note

This model must be multiplied with the other and used last.

accepted_keys = ('filter_function', 'shift_guess', 'shift_def')

Accepted keys of the input dictionary (see fit.Model.p_dict)

check_input()

Check input parameters

get_model(x, p_free=None, return_models=False, return_complex=False)

Return model M(x, p).

Parameters
  • x – Positions where the model M(x, p) is computed.

  • p_free – (Optional) New values of the free parameters (default None).

  • return_models – (Optional) If True return also individual models (default False)

  • return_complex – (Optional) If True return a complex model (default False).

make_guess(v)

If a parameter value at init is a NaN this value is guessed.

Parameters

v – Data vector from which the guess is made.

parse_dict()

Parse input dictionary fit.Model.p_dict

class orb.fit.FitVector(vector, models, params, fit_tol=1e-08, signal_range=None, max_iter=None, docomplex=False, nogvar=False, vector_err=None)

Bases: object

General fitting class for a 1d array of data based on Levenberg-Marquardt least square fit algorithm.

Accept any combination of models (based on fit.Model)

Note

This class is a wrapper around scipy.optimize.leastsq(). Most of its purpose consists in passing an array of purely free parameters to scipy.optimize.leastsq() and creating the objective function from free and fixed parameters by combining the different models.

fit(compute_mcmc_error=False)

Fit data vector.

This is the central function of the class.

Parameters

compute_mcmc_error – (Optional) Compute Markov chain Monte-Carlo error on the fit parameters (Uncertainty estimates might be slighly better constrained but computing time can be orders of magnitude longer) (default False).

fit_tol = None
get_model(all_p_free, return_models=False, x=None)

Return the combined model of the vector given a set of free parameters.

This function is typically called to compute the objective function. It can also be called to obtain the final model based on fitted parameters.

Parameters
  • all_p_free – Vector of free parameters.

  • return_models – (Optional) If True return also individual models (default False)

  • x – (Optional) array of data points on which model is computed instead of a typical np.arange(step_nb) (default None).

max_fev = 5000
models = None
models_operation = None
models_operations = ['add', 'mult']
priors_keys_list = None
priors_list = None
vector = None
class orb.fit.InputParams(step_nb)

Bases: object

add_continuum_model(**kwargs)
add_lines_model(lines, fwhm_guess, **kwargs)
append_model(model, operation, params)
check_signal_range()
clean_kwargs(kwargs, params)
convert()

Convert class to a pickable dict object

has_model(model)
set_signal_range(rmin, rmax)
class orb.fit.LinesModel(p_dict)

Bases: orb.fit.Model

Emission/absorption lines model with a channel unity in pixels.

Note

This class is best seen as a basic class implemented with more physical unities by fit.Cm1LinesModel or fit.NmLinesModel.

Note

Each line is built on 3 (or more) parameters : amplitude, FWHM, position and sigma/alpha (the 4th and 5th parameters are used only for some models – see below for details on the different models).

Some lines can have one or more covarying parameters: FWHM can be the same for all the lines (this is True if lines are not resolved), lines issued from the same ion can have the same speed (e.g. [NII] doublet, [SII] doublet, [OIII] doublet), and some fixed transition ratios between lines can also be set (e.g. [NII]6584/[NII]6548 can be set to 2.89, when [NII]6548 is likely to be really noisy).

Input dictionary fit.Model.p_dict:

{'line_nb':,
 'fmodel':,
 'amp_def':,
 'pos_def':,
 'fwhm_def':,
 'sigma_def':, # only for sincgauss fmodel
 'alpha_def':, # only for sincphased fmode
 'amp_cov':,
 'pos_cov':,
 'fwhm_cov':,
 'sigma_cov':, # only for sincgauss fmodel
 'alpha_cov':, # only for sincphased fmodel
 'amp_guess':,
 'pos_guess':,
 'fwhm_guess':,
 'sigma_guess':, # only for sincgauss fmodel
 'alpha_guess':} #  only for sincphased fmodel
Parameters
  • line_nb – Number of lines.

  • fmodel – Line shape, can be ‘gaussian’, ‘sinc’, ‘sinc2’ or ‘sincgauss’.

  • amp_def – Definition of the amplitude parameter, can be ‘free’, ‘fixed’ or set to a label that defines its covarying group.

  • pos_def – Definition of the position parameter in pixels, can be ‘free’, ‘fixed’ or set to a label that defines its covarying group.

  • fwhm_def – Definition of the FWHM parameter in pixels, can be ‘free’, ‘fixed’ or set to a label that defines its covarying group.

  • sigma_def – Definition of the sigma parameter in pixels, can be ‘free’, ‘fixed’ or set to a label that defines its covarying group.

  • amp_cov – Guess on the covariant value of the amplitude (best set to 0 in general). There must be as many values as covarying amplitude groups or only one value if it is the same for all groups.

  • pos_cov – Guess on the covariant value of the velocity (in pixels). There must be as many values as covarying amplitude groups or only one value if it is the same for all groups.

  • fwhm_cov – Guess on the covariant value of the FWHM (best set to 0 in general). There must be as many values as covarying amplitude groups or only one value if it is the same for all groups.

  • sigma_cov – Guess on the covariant value of sigma (best set to 0 in general). There must be as many values as covarying amplitude groups or only one value if it is the same for all groups.

  • amp_guess – Initial guess on the amplitude value of the lines. Best set to a NaN in general (it can be automatically guessed with good robusteness). But if lines have a covarying amplitude the initial guess fixes their ratio.

  • pos_guess – Initial guess on the position of the lines: the PRECISE rest frame position must be given here, especially if lines share a covarying position, because their relative position will be fixed.

  • fwhm_guess – Initial guess on the FWHM of the lines. This guess must be the MOST PRECISE possible (to a few 10%), it is by far the most unstable parameter especially for sinc lines.

  • sigma_guess – Initial guess on the value of sigma. Best set to 0. in general

Example: A red spectrum containing [NII]6548, Halpha, [NII]6584, [SII]6716 and [SII]6731, with a mean velocity of 1500 km/s (which translates in a pixel shift of 5.5), with a fixed amplitude ratio netween [NII] lines, the same speed for lines issued from the same ions and a shared FWHM between everybody but Halpha would be defined this way:

{'line_nb' : 5,
 'amp_def' : ('1', 'free', '1', 'free', 'free'),
 'pos_def' : ('1', '2', '1', '3', '3'), 
 'fwhm_def': ('1', '2', '1', '1', '1'),
 'amp_cov': 0.,
 'pos_cov': 5.5,
 'fwhm_cov': 0.,
 'amp_guess': (1., np.nan, 2.89, np.nan, np.nan), # here the amplitude ratio between covarying [NII] lines is fixed.
 'pos_guess': (40,60,80,120,140), # positions are given in pixel and are purely arbitrary in this example
 'fwhm_guess': 2.43}

Note

Line shapes (fmodel keyword):

  • gaussian: A classical gaussian line shape. See cutils.gaussian1d().

  • sinc: A pure sinc line shape, True interferometric line shape if lines are strongly unresolved and if the interferometer has no assymetry (generally good on SITELLE/SpIOMM low res cubes –i.e. less than 500 steps– if the line SNR is not too high –i.e. < 50–). See cutils.sinc1d().

  • sinc2: sinc2 = sqrt(sinc**2.). Can be used for spectra not corrected in phase (where the absolute value of the complex spectrum is taken).

  • sincgauss: Convolution of a Gaussian (of width sigma) and a sinc (FWHM). This line shape has a 4th parameter: sigma. This is much closer to the true line shape, but it takes much more time to compute because of the generally very small value of sigma. This can be used to fit resolved lines, like e.g. Halpha in absorption or active nucleus with broader emission. See cutils.sincgauss1d().

accepted_keys = ('line_nb', 'fmodel', 'ratio', 'amp_def', 'pos_def', 'fwhm_def', 'sigma_def', 'alpha_def', 'amp_cov', 'pos_cov', 'fwhm_cov', 'sigma_cov', 'alpha_cov', 'amp_guess', 'pos_guess', 'fwhm_guess', 'sigma_guess', 'alpha_guess')

Accepted keys of the input dictionary (see fit.Model.p_dict)

check_input()

Check input parameters

get_model(x, p_free=None, return_models=False, multf=None, return_complex=False)

Return model M(x, p).

Parameters
  • x – Positions where the model M(x, p) is computed.

  • p_free – (Optional) New values of the free parameters (default None).

  • multf – 1d vector with the same length as x vector which represent the function by which the model must be multiplied.

  • return_models – (Optional) If True return also individual models (default False)

  • return_complex – (Optional) If True return a complex model.

get_p_val_as_array(p_val=None)
get_priors()

Return priors. Replace gaussian distribution by lognormal distribution for some parameters.

log_param_keys = ['fwhm', 'sigma']

Parameter keys that have a lognormal distribution

make_guess(v)

If a parameter value at init is a NaN this value is guessed.

Parameters

v – Data vector from which the guess is made.

p_array = None

equivalent of fit.Model.p_val but presented as an array with each row corresponding to a line which is easier to handle.

param_keys = ['amp', 'pos', 'fwhm', 'sigma', 'alpha']

Parameter keys

parse_dict()

Parse input dictionary fit.Model.p_dict

same_param_keys = ['fwhm', 'sigma']

Parameter keys which must be the same if covarying

class orb.fit.Model(p_dict)

Bases: object

Template class for fit models. This class cannot be used directly.

The main purpose of a Model class is to output a model given a set of parameters.

Methods that must be implemented by real classes:

  • fit.Model.parse_dict()

  • fit.Model.check_input()

  • fit.Model.make_guess()

  • fit.Model.get_model()

Note

A model is computed from a given set of parameters stored in fit.Model.p_val. From this set some parameters are free, some are fixed and some are covarying, i.e. the value of a subset of parameters can be computed from 1 free parameter.

Taking the definition of the parameters (free, fixed or covarying, stored in fit.Model.p_def) into account, the reduced free parameter set is stored in fit.Model.p_free, the reduced set of fixed parameters is stored in fit.Model.p_fixed, the set of covarying parameters is stored in fit.Model.p_cov and when the model needs to be computed, the full set of model parameters (fit.Model.p_val) is computed again from set.p_free`, fit.Model.p_fixed, fit.Model.p_cov and fit.Model.p_def.

A group of covarying parameters is defined by the same label. If fit.Model.p_def is:

['free', 'fixed', '1', '2', 'free', 'fixed', '2', '1', '2', 'free']

It means that we have 3 free parameters, 2 fixed parameters and 2 groups of covarying parameters. The first group contains 2 parameters and the second group contains 3 parameters. In this case the real number of free parameters will be 3 + 2 (one free parameter for each group of covarying parameters) = 5 and the real number of fixed parameters will be 2 + 5 (one fixed parameter for each covarying parameters) = 7.

A Model class works this way :

  1. Init: the dictionary defining the parameters (free, fixed, covarying) and their values is parsed with fit.Model.parse_dict(): fit.Model.p_def, fit.Model.p_val and fit.Model.p_cov are created. Then fit.Model.val2free() is called to create fit.Model.p_free and fit.Model.p_fixed.

  2. the set of free parameters can then be changed with fit.Model.set_p_free() before calling fit.Model.get_model(). the updated values of fit.Model.p_val are computed before the model is created via fit.Model.free2val(). A new set of free parameters can also be passed to fit.Model.get_model().

accepted_keys = ()

Accepted keys of the input dictionary (see fit.Model.p_dict)

check_input()

Check input parameters

free2val()

Read the array of parameters definition fit.Model.p_def and update the parameter values based on the new set of free parameters fit.Model.p_free.

get_model(x, return_models=False, return_complex=False)

Compute a model M(x, p) for all passed x positions. p are the parameter values stored in fit.Model.p_val

Parameters
  • x – Positions where the model M(x, p) is computed.

  • return_models – (Optional) If True return also individual models (default False)

  • return_complex – (Optional) If True return a complex model (default False).

get_p_free()

Return the vector of free parameters fit.Model.p_free

get_p_val()

Return fit.Model.p_val

get_priors()

Return priors

make_guess(v)

If a parameter value at init is a NaN this value is guessed.

Parameters

v – Data vector from which the guess is made.

p_cov = None

dict that stores the groups of covarying parameters by label and their associated value and covarying operation (a pointer to a function), i.e.:

{['cov_label_1': (value1, cov_operation1)],
 ['cov_label_2': (value2, cov_operation2)],
 ...}
p_def = None

Definition the full set of parameters (fixed, free or covarying). This array as the same shape as fit.Model.p_val

p_dict = None

Input dictionary defining the parameters. Contains the initial values of the parameters

p_fixed = None

Array of fixed parameters. Each covarying parameter is stored as fixed. And one free parameter is added for each group of covarying parameters.

p_free = None

Up to date value of the free parameters. Its size is always less or equal to the size of the full set of parameters used directly to compute the model. It reflects the real number of fitted parameters. For each group of covarying parameters one free parameter is added.

p_val = None

Up to date values of the full set of parameters used by the model (initial guess before fit, fitted value after fit). This array as the same shape as fit.Model.p_def. It does not reflect the real number of fitted parameters.

parse_dict()

Parse input dictionary to create fit.Model.p_def, fit.Model.p_val and fit.Model.p_cov

set_p_free(p_free)

Set the vector of free parameters fit.Model.p_free

Parameters

p_free – New vector of free parameters

set_p_val(p_val)

Set fit.Model.p_val

Warning

This method is used to bypass all the initialized parameters and reuse an already initialized model with another full set of parameters. Note that you might want to call fit.Model.get_model() directly after this method because any call to fit.Model.set_p_free() or fit.Model.free2val() will recompute fit.Model.p_val from the init values and the actual fit.Model.p_free.

Parameters

p_val – New full set of parameters.

val2free()

Recompute the set of free parameters fit.Model.p_free with the updated values of fit.Model.p_val

class orb.fit.NmLinesModel(p_dict)

Bases: orb.fit.Cm1LinesModel

Emission/absorption lines model with a channel unity in nm.

Reimplements fit.Cm1LinesModel to use nm instead of cm-1. Channels are translated to cm-1 and velocity to km/s in input and output.

See also

For more information please refer to fit.Cm1LinesModel and fit.LinesModel

parse_dict()

Parse input dictionary fit.Model.p_dict

class orb.fit.OutputParams

Bases: orb.fit.Params

convert()

Convert class to a raw pickable format

get_axis()

Returns the axis of the fitted spectrum

get_params()

Return basic parameters of the fitted spectrum

get_residual()

Return fit residual

get_spectrum()

Return fitted spectrum

plot(*args, **kwargs)

Plot fitted spectrum. Convenient wrapper around pyplot.plot() function

plot_residual(*args, **kwargs)

Plot residual. Convenient wrapper around pyplot.plot() function

translate(inputparams, fitvector, nogvar=False)
class orb.fit.Params

Bases: orb.core.Params

Manage a set of parameters as a special dictionary which elements can be accessed like attributes.

orb.fit.create_cm1_lines_model(lines_cm1, amp, step, order, resolution, theta, vel=0.0, sigma=0.0, alpha=0.0, fmodel='sincgauss', ratio=0.25)

Return a simple emission-line spectrum model in cm-1

Parameters
  • lines – lines in cm-1

  • amp – Amplitude (must have the same size as lines)

  • step – Step size

  • order – Folding order

  • resolution – Resolution of the spectrum

  • theta – Incident angle

  • vel – (Optional) Global velocity shift applied to all the lines (in km/s, default 0.)

  • sigma – (Optional) Line broadening (in km/s, default 0.)

  • alpha – (Optional) Phase coefficient of the lines (default 0.)

  • fmodel – (Optional) Lines model. Can be ‘gaussian’, ‘sinc’, ‘sincgauss’, ‘sincphased’, ‘sincgaussphased’ (default sincgauss).

orb.fit.create_cm1_lines_model_raw(lines_cm1, amp, step, order, step_nb, corr, zpd_index, vel=0, sigma=0, alpha=0, fmodel='sinc')

Return a simple emission-line spectrum model in cm-1 from raw parameters. For more physical parameters use create_cm1_lines_model().

Parameters
  • lines_cm1 – lines in cm-1

  • amp – Amplitude (must have the same size as lines)

  • step – Step size

  • order – Folding order

  • step_nb – Total numer of steps

  • corr – calibration coeff.

  • zpd_index – ZPD index.

  • vel – (Optional) Global velocity shift applied to all the lines (in km/s, default 0.)

  • sigma – (Optional) Line broadening (in km/s, default 0.)

  • alpha – (Optional) Phase coefficient of the lines (default 0.)

  • fmodel – (Optional) Lines model. Can be ‘gaussian’, ‘sinc’, ‘sincgauss’, ‘sincphased’, ‘sincgaussphased’ (default sincgauss).

orb.fit.create_lines_model(lines, amp, fwhm, step_nb, line_shift=0.0, sigma=0.0, alpha=0.0, fmodel='sincgauss')

Return a simple emission-line spectrum model with no physical units.

Parameters
  • lines – lines channels.

  • amp – Amplitude (must have the same size as lines).

  • fwhm – lines FWHM (in channels).

  • step_nb – Number of steps of the spectrum.

  • line_shift – (Optional) Global shift applied to all the lines (in channels, default 0.)

  • sigma – (Optional) Sigma of the lines (in channels, default 0.)

  • alpha – (Optional) Phase coefficient of the lines (default 0.)

  • fmodel – (Optional) Lines model. Can be ‘gaussian’, ‘sinc’, ‘sincgauss’, ‘sincphased’, ‘sincgaussphased’ (default sincgauss).

orb.fit.fit_lines_in_spectrum(spectrum, lines, step, order, nm_laser, theta, zpd_index, wavenumber=True, filter_name=None, apodization=1.0, fit_tol=1e-10, velocity_range=None, compute_mcmc_error=False, max_iter=None, **kwargs)

Fit lines in spectrum

Warning

If spectrum is in wavenumber (option wavenumber set to True) input and output unit will be in cm-1. If spectrum is in wavelength (option wavenumber set to False) input and output unit will be in nm.

Parameters
  • spectrum – Spectrum to fit

  • lines – Positions of the lines in nm/cm-1

  • step – Step size in nm

  • order – Folding order

  • nm_laser – Calibration laser wavelength in nm.

  • theta_proj – Projected incident angle of the spectrum in degrees.

  • zpd_index – Index of the ZPD in the interferogram.

  • apodization – (Optional) Apodization level. Permit to separate the broadening due to the apodization and the real line broadening (see ‘broadening’ output parameter, default 1.).

  • fit_tol – (Optional) Tolerance on the fit value (default 1e-10).

  • filter_name – (Optional) Filter file path (default None).

  • velocity_range – (Optional) Range of velocity to check around the shift_guess value. If not None, a brute force algorithm is used to find the best velocity value. If more than one shift_guess is given (e.g. if lines are have different velocities, the mean velocity will be used as an initial velocity guess). The quality of this guess depends strongly on the spectrum noise. Try avoid using it with low a SNR spectrum.

  • compute_mcmc_error – (Optional) If True, uncertainty estimates are computed from a Markov chain Monte-Carlo algorithm. If the estimates can be better constrained, the fitting time is orders of magnitude longer (default False).

  • max_iter – (Optional) Maximum number of iterations (default None)

  • kwargs – (Optional) Fitting parameters of orb.fit.Cm1LinesInput or orb.fit.FitVector.

Returns

a dictionary containing:

  • all the fit parameters [key: ‘fit_params’]

  • lines parameters [key: ‘lines_params’] Lines parameters are given as an array of shape (lines_nb, 5). The order of the 5 parameters for each lines is [height at the center of the line, amplitude, position, fwhm, sigma]. Position and FWHM are given in nm/cm-1 depending on the input unit (i.e. nm if wavenumber is False and cm-1 if wavenumber is True)

  • lines parameters errors [key: ‘lines_params_err’]

  • velocity [key: ‘velocity’] Velocity of the lines in km/s

  • velocity error [key: ‘velocity_err’] Error on the velocity of the lines in km/s

  • residual [key: ‘residual’]

  • chi-square [key: ‘chi2’]

  • reduced chi-square [key: ‘rchi2’]

  • SNR [key: ‘snr’]

  • continuum parameters [key: ‘cont_params’]

  • fitted spectrum [key: ‘fitted_vector’]

  • log(Gaussian Bayes Factor) [key: ‘logGBF’]

orb.fit.fit_lines_in_vector(vector, lines, fwhm_guess, fit_tol=1e-10, compute_mcmc_error=False, max_iter=None, **kwargs)

Fit lines in a vector

Use this function only if little is known about the vector. A vector resulting from an interferogram FFT is assumed : i.e. regular axis, symmetrical line shape.

Warning

All position units are in channels

Parameters
  • vector – vector to fit

  • lines – Positions of the lines in channels

  • fwhm_guess – Initial guess on the lines FWHM (in channels).

  • fit_tol – (Optional) Tolerance on the fit value (default 1e-10).

  • compute_mcmc_error – (Optional) If True, uncertainty estimates are computed from a Markov chain Monte-Carlo algorithm. If the estimates can be better constrained, the fitting time is orders of magnitude longer (default False).

  • max_iter – (Optional) Maximum number of iterations (default None)

  • kwargs – (Optional) Fitting parameters of orb.fit.LinesInput or orb.fit.FitVector.

Returns

a dictionary containing:

  • all the fit parameters [key: ‘fit_params’]

  • lines parameters [key: ‘lines_params’] Lines parameters are given as an array of shape (lines_nb, 5). The order of the 5 parameters for each lines is [height at the center of the line, amplitude, position, fwhm, sigma]. Postion and FWHM are given in channels.

  • lines parameters errors [key: ‘lines_params_err’]

  • residual [key: ‘residual’]

  • chi-square [key: ‘chi2’]

  • reduced chi-square [key: ‘rchi2’]

  • SNR [key: ‘snr’]

  • continuum parameters [key: ‘cont_params’]

  • fitted spectrum [key: ‘fitted_vector’]

  • log(Gaussian Bayes Factor) [key: ‘logGBF’]

orb.image module

The Image module is aimed to manage image class

class orb.image.Frame2D(*args, **kwargs)

Bases: orb.core.WCSData

crop(cx, cy, size, return_cutout=False)

Return a portion of the image as another Frame2D instance.

Parameters
  • cx – X center position

  • cy – Y center position

  • size – Size of the cropped rectangle. A tuple (sz, sy). Can be single int in which case the cropped data is a box.

  • return_cutout – If True return only the cutout, not a new image object (default False).

Warning

size of the returned box is not guaranteed if cx and cy are on the border of the image.

get_stats(fast=True)

Return image stats

Parameters

fast – If fast, only a random fraction of the image is used to make stats.

Returns

mean, median, std

imshow(wcs=True, **kwargs)

Convenient image plotting function

Parameters
  • figsize – size of the figure (same as pyplot.figure’s figsize keyword)

  • wcs – if True, display wcs coordinates. Else, pixel coordinates are shown.

Params kwargs

other kwargs of orb.utils.graph.imshow()

class orb.image.Image(data, **kwargs)

Bases: orb.image.Frame2D

DETECT_INDEX = 0
FIT_TOL = 0.01
REDUCED_CHISQ_LIMIT = 1.5
aperture_photometry(star_list, aper_coeff=3.0, silent=False)

Perform aperture photometry.

Based on photutils.

Parameters

star_list – May be an array (n, 2) or a path to a star

list file created with detect_stars()

Parameters

aper_coeff – (Optional) Aperture coefficient (default 3.) Aperture = aper_coeff * fwhm.

compute_alignment_parameters(image2, xy_range, r_range, correct_distortion=False, star_list1=None, fwhm_arc=None, brute_force=True, coeffs=(0, 0, 0, 0, 0, 1), skip_check=False)

Return the alignment coefficients that match the stars of this image to the stars of the image 2.

Parameters
  • image2 – Image instance.

  • xy_range – Range of x, y values to brute force around the initial parameters passed in coeffs. if two ranges are given (e.g. (np.linspace(-5,5,10), np.linspace(-1,1,10))) a second brute force pass is done centered on the values of the first pass.

  • r_range – Range of angles to brute force around the initial parameters passed in coeffs. if two ranges are given (e.g. (np.linspace(-5,5,10), np.linspace(-1,1,10))) a second brute force pass is done centered on the values of the first pass.

  • correct_distortion – (Optional) If True, a SIP is computed to match stars from frame 2 onto the stars from frame 1. But it needs a lot of stars to run correctly (default False).

  • star_list1 – (Optional) Path to a list of stars in the cube. If given the fwhm_arc must also be set (default None).

  • fwhm_arc – (Optional) mean FWHM of the stars in arcseconds. Must be given if star_list1 is not None (default None).

  • brute_force – (Optional) If True the first step is a brute force guess. This is very useful if the initial parameters are not well known (default True).

  • coeffs – (Optional) initial alignement parameters (dx, dy, dr, da, db, zoom). If aligning camera 2 on camera 1, use self.get_initial_alignment_parameters() to set coeffs.

Note

The alignement coefficients are:

  • dx : shift along x axis in pixels

  • dy : shift along y axis in pixels

  • dr : rotation angle between images (the center of rotation is the center of the images of the camera 1) in degrees

  • da : tip angle between cameras (along x axis) in degrees

  • db : tilt angle between cameras (along y axis) in degrees

Note

The process tries to find the stars detected in the camera A in the frame of the camera B. It goes through 2 steps:

  1. Rough alignment (brute force style) only looking over dx, dy. dr is kept to its initial value (init_angle), da and db are set to 0.

  2. Fine alignment pass.

Warning

This alignment process do not work if the initial parameters are too far from the real value. The angle must be known within a few degrees. The shift must be known within 4 % of the frame size (The latter can be changed using the SIZE_COEFF constant)

compute_panstarrs_photometry(star_number=1000, max_xmatch_radius=10, max_roundness=0.5, eps=None, modulated=False, calibrated=False)
copy(data=None)

Return a copy of the instance

Parameters

data – (Optional) can be used to change data

detect_fwhm(star_list)

Return fwhm of a list of stars (in pixels)

can be converted to arcseconds with self.pix2arc()

Parameters

star_list – list of stars (can be an np.ndarray or a path to a star list).

detect_stars(min_star_number=30, max_roundness=0.5, max_radius_coeff=1.3, path=None, saturation_threshold=None, filter_background=False)

Detect star positions in data.

Parameters
  • min_star_number – Minimum number of stars to detect. Must be greater or equal to 4 (minimum star number for any alignment process). this is also the number of stars returned (sorted by intensity)

  • path – (Optional) Path to the output star list file. If None, nothing is written.

  • saturation_threshold – (Optional) reject stars higher than this threshold. Can be a float, False or None. If False: saturation_threshold is set to 99.9th percentile. If None (default) it is set to 0.45 * 99.9th percentile to avoid selecting stars which will saturate at ZPD.

detrend(bias=None, dark=None, flat=None, shift=None, cr_map=None)

Return a detrended image

Parameters
  • bias – Master bias

  • dark – Master dark (must be in counts/s)

  • flat – Master flat

  • shift – shift correction (dx, dy)

  • cr_map – A map of cosmic rays with boolean type: 1 = CR, 0 = NO_CR

find_object(is_standard=False, return_radec=False, optimize=True)

Try to find the object given the name in the header

Parameters
  • is_standard – if object is a standard, do not try to resolve the name.

  • return_radec – if true, radec coordinates are retruned instead of image coordinates (pixel position).

fit_sip(star_list1, star_list2, params=None, init_sip=None, err=None, sip_order=2, crpix=None, crval=None)

FIT the distortion correction polynomial to match two lists of stars (the list of stars 2 is distorded to match the list of stars 1).

Warning

If you want to fit a SIP for a WCS do not use this function. Use register(skip_registration=True, compute_distortion=True, sip_order=anything > 2).

Parameters
  • star_list1 – list of stars 1

  • star_list2 – list of stars 2

  • params – (Optional) Transformation parameter to go from the list of stars 1 to the list of stars 2. Must be a tuple [dx, dy, dr, da, db, rcx, rcy, zoom_factor] (default None).

  • init_sip – (Optional) Initial SIP (an astropy.wcs.WCS object, default None)

  • err – (Optional) error on the star positions of the star list 2 (default None).

  • sip_order – (Optional) SIP order (default 2).

  • crpix – (Optional) If an initial wcs is not given (init_sip set to None) this header value must be given.

  • crval – (Optional) If an initial wcs is not given (init_sip set to None) this header value must be given.

fit_stars(star_list, **kwargs)

Fit stars in one frame.

This function is basically a wrapper around orb.utils.astrometry.fit_stars_in_frame().

Note

2 fitting modes are possible:

* Individual fit mode [multi_fit=False]
* Multi fit mode [multi_fit=True]

see orb.utils.astrometry.fit_stars_in_frame() for more information.

Parameters

Warning

Some optional arguments are taken directly from the values computed at the init of the Class. The following optional arguments thus cannot be passed:

* profile_name
* scale
* fwhm_pix
* beta
* fit_tol          
get_box_size()
get_fwhm_pix()
get_stars_from_catalog(max_stars=5000)

Return star positions, corrected for proper motion from Gaia DR3

load_fit_results(fit_results_path=None)

Load a file containing the fit results

profiles = ['moffat', 'gaussian']
register(max_stars_detect=60, max_roundness=0.5, max_radius_coeff=1.5, saturation_threshold=False, sip_order=3, rrange=None, xyrange=None, nsteps=7, return_fit_params=False, skip_registration=False, compute_precision=True, compute_distortion=False, return_error_maps=False, return_error_spl=False, sl_cat_deg=None, fwhm_arc=None, filter_background=True, fwhm_limit_factor=3, proj_point=None)

Register data and return a corrected pywcs.WCS object.

Optionally (if return_error_maps set to True or return_error_spl set to True) 2 distortion maps used to refine a calculated SIP distortion model are returned.

Precise RA/DEC positions of the stars in the field are recorded from a catalog of the VIZIER server.

Using the real position of the same stars in the frame, WCS transformation parameters are optimized va a SIP model.

Parameters
  • max_stars_detect – (Optional) Number of detected stars in the frame for the initial wcs parameters (default 60).

  • max_radius_coeff – (Optional) Maximum radius to detect stars.

  • nsteps – (Optional) Number of refinement steps (default 7).

  • sip_order – (Optional) SIP order (default 3). compute_distortion must be True for this parameter to be used.

  • return_fit_params – (Optional) If True return final fit parameters instead of wcs (default False).

  • compute_distortion – (Optional) If True, optical distortion (SIP) are computed. Note that a frame with a lot of stars is better for this purpose. Setting this to True and sip_order to None refit the wcs without any SIP parameters. (default False).

  • compute_precision – (Optional) If True, astrometrical precision is computed (default True).

  • return_error_maps – (Optional) If True, error maps (200x200 pixels) on the registration are returned (default False).

  • return_error_spl – (Optional) If True, error maps on the registration are returned as scipy.interpolate.RectBivariateSpline instances (default False).

  • sl_cat_deg – (Optional) A list of star positions in degree to perform registration. fwhm_arc must also be set.

  • fwhm_arc – (Optional) must be set if sl_cat_deg is not None.

  • fwhm_limit_factor – (Optional) Limit on the distance of the stars used during distorsion computation in proportion of the FWHM (default 3).

  • proj_point – (Optional) a Tuple (ra, dec in degrees) giving the projection point of the fitted wcs (useful only in the case when compute_distorsion is set to True, default None).

reset_fwhm_arc(fwhm_arc)

Reset FWHM of stars in arcsec

Parameters

fwhm_arc – FWHM of stars in arcsec

reset_profile_name(profile_name)

Reset the name of the profile used.

Parameters

profile_name – Name of the PSF profile to use for fitting. Can be ‘moffat’ or ‘gaussian’.

reset_sip()

Remove sip informations

reset_wcs(target_ra, target_dec, fov=None, wcs_rotation=None)

Reset WCS to a raw WCS that can be registered without error with register().

Parameters
  • target_ra – RA at the center of the field

  • target_dec – DEC at the center of the field

  • fov – (Optional) If the instrument is unknown (not sitelle/spiomm) the field of view must be set in arcminutes (default None).

  • fov – (Optional) If the instrument is unknown (not sitelle/spiomm) the wcs_rotation must be set in degrees (default None).

transform(params, order=1)

Return a transformed image.

Parameters
  • params – A dictionary containing the keys ‘coeffs’=[dx, dy, dr, da, db], ‘rc’, ‘zoom_factor’. This is exactly the dictionary returned by self.compute_alignment_coeffs(). may optionally contain ‘sip1’ and ‘sip2’ where sip1 is the sip of the image to transform and sip2 is the sip of the image it is aligned to.

  • order – Interpolation order (default 1)

class orb.image.StandardImage(data, **kwargs)

Bases: orb.image.Image

compute_flux_correction_factor()

Compute the flux correction factor that can be used by orb.photometry.Photometry.get_flambda()

orb.old module

class orb.old.Cube(data, **kwargs)

Bases: orb.core.Tools

3d numpy data cube handling. Base class for all Cube classes

get_data(x_min, x_max, y_min, y_max, z_min, z_max, silent=False, mask=False)

Return a part of the data cube.

Parameters
  • x_min – minimum index along x axis

  • x_max – maximum index along x axis

  • y_min – minimum index along y axis

  • y_max – maximum index along y axis

  • z_min – minimum index along z axis

  • z_max – maximum index along z axis

  • silent – (Optional) if False display a progress bar during data loading (default False)

  • mask – (Optional) if True return mask (default False).

get_mean_image(recompute=False)

Return the mean image of a cube (corresponding to a deep frame for an interferogram cube or a specral cube).

Parameters

recompute – (Optional) Force to recompute mean image even if it is already present in the cube (default False).

Note

In this process NaNs are considered as zeros.

class orb.old.HDFCube(cube_path, params=None, silent_init=False, binning=None, **kwargs)

Bases: orb.old.Cube

This class implements the use of an HDF5 cube.

An HDF5 cube is similar to the frame-divided cube implemented by the class orb.core.Cube but it makes use of the really fast data access provided by HDF5 files. The “frame-divided” concept is keeped but all the frames are grouped into one hdf5 file.

An HDF5 cube must have a certain architecture:

  • Each frame has its own group called ‘frameIIIII’, IIIII being a integer giving the position of the frame on 5 characters filled with zeros. e.g. the first frame group is called frame00000

  • Each frame group is divided into at least 2 datasets: data and header (e.g. the data of the first frame will be in the dataset frame00000/data)

  • A mask dataset can be added to each frame.

orb.image photometry

class orb.photometry.Photometry(filter_name, camera_index, instrument='sitelle', airmass=1)

Bases: object

STEP_NB = 2000
cameras = [0, 1, 2]
compute_flambda(cm1_axis, eps=None, modulated=True)

Compute the flambda calibration function from the correction vector.

It can be computed with cube.SpectralCube.compute_flux_calibration() or image.StandardImage.compute_flux_correction_factor() and fft.StandardSpectrum.compute_flux_correction_vector().

flux2counts(flux, modulated=True, eps=None, opd_jitter=None, wf_error=None)

convert a flux in erg/cm2/s/A to a flux in counts/s in both cameras

Parameters

flux – Flux must be in erg/cm2/s/A

Returns

a flux in counts/s

get_ccd_gain()
get_modulated_transmission(eps=None, opd_jitter=None, wf_error=None)
get_modulation_efficiency(opd_jitter=None, wf_error=None)

Return modulation efficiency

Parameters
  • opd_jitter – OPD jitter in nm (standard deviation)

  • wf_error – wavefront error ratio (e.g. 1/30.)

get_qe()
get_transmission(tterm)
get_unmodulated_transmission(eps=None)
transmission_terms = ['atmosphere', 'mirror', 'optics', 'filter', 'telescope']
class orb.photometry.Standard(std_name, **kwargs)

Bases: orb.core.Tools

Manage standard files and photometrical calibration

ang = None
compute_optimal_texp(step, order, seeing, filter_name, camera_number, saturation=30000, airmass=1.0)

Compute the optimal exposition time given the total flux of the star in ADU/s.

Parameters
  • step – Step size in nm

  • order – Folding order

  • seeing – Star’s FWHM in arcsec

  • filter_name – Name of the filter

  • camera_number – Number of the camera

  • saturation – (Optional) Saturation value of the detector (default 30000).

  • airmass – (Optional) Airmass (default 1)

flux = None
get_spectrum(filter_name, cm1_axis)

Return part of the standard spectrum corresponding to the observation parameters.

Returned spectrum is calibrated in erg/cm^2/s/A

Parameters

cm1_axis – Axis instance in cm-1

simulate_measured_flux(filter_name, cm1_axis, airmass=1, camera_index=1, opd_jitter=None, wf_error=None, modulated=True)

Return a simulation of the measured flux in counts/s

Parameters
  • filter_name – Filter name

  • n – Number of steps

  • corr – (Optional) Correction coefficient related to the incident angle (default None, taken at the center of the field).

  • opd_jitter – OPD jitter in nm (standard deviation)

  • wf_error – wavefront error ratio (e.g. 1/30.)

orb.sim

class orb.sim.Base(step_nb, params, instrument='sitelle', **kwargs)

Bases: object

class orb.sim.Interferogram(*args, **kwargs)

Bases: orb.sim.Base

add_background()
add_line(wave, vel=0, flux=1, sigma=0, jitter=0)
Parameters
  • wave – The name of the line or the line wavenumber in cm-1

  • vel – Velocity in km/s

  • jitter – Std of an OPD jitter. Must be given in nm.

add_spectrum(spectrum)
Parameters

spectrum – Spectrum instance which must be defined on the filter range.

get_interferogram()
class orb.sim.SkyModel(airmass=1, instrument='sitelle')

Bases: object

Very basic sky model which generate a spectrum of the sky.

It includes continuum brightness, sky lines and moon brightness.

most data comes from https://www.gemini.edu/observing/telescopes-and-sites/sites

get_spectrum(cm1_axis)
class orb.sim.SourceSpectrum(spectrum, axis, instrument='sitelle', data_prefix='./', **kwargs)

Bases: orb.core.Vector1d, orb.core.Tools

add_line(wave, flux, vel=None, sigma=None)

add a line to the spectrum

Parameters
  • wave – Name of the line or its wavenumber in cm-1 (can be a tuple)

  • vel – Velocity in km/s

  • flux – Flux in erg/cm2/s

  • sigma – Broadening in km/s

add_spectrum(spectrum)

Spectrum

Parameters

spectrum – spectrum vector, must be in erg/cm2/s/A

get_interferogram(params, camera=0, theta=None, binning=1, me_factor=1.0, x=None, bypass_flux2counts=False, noiseless=True)
Parameters

x – scanning vector (to simulate a non-uniform

scan). Must be given in step fraction. e.g. x = (np.arange(params[‘step_nb’]) - params[‘zpd_index’]) will simulate the default scanning sequence.

class orb.sim.Spectrum(*args, **kwargs)

Bases: orb.sim.Base

add_component(lines, amp, noise_std=0, vel=0, sigma=0)
get_spectrum()

Module contents