orb.utils package

Submodules

orb.utils.astrometry module

class orb.utils.astrometry.Gaussian(params)

Bases: orb.utils.astrometry.PSF

Class implementing the gaussian profile

Note

The Gaussian profile used here is: \(f(x,y) = H + A \times \exp(\frac{-r^2}{2 W^2})\)

and, \(r = (x - dx)^2 + (y - dy)^2\)

The total flux F under the 2D profile is: \(F = 2 \pi A W^2\)

array2d(nx, ny)

Return a 2D profile given the size of the returned array.

Parameters
  • nx – Length of the returned array along x axis

  • ny – Length of the returned array along y axis

flux()

Return the total flux under the 2D profile.

The total flux F under a 2D profile is : \(F = 2 \pi A W^2\)

Note

Under a 1d profile the flux is \(F = \sqrt{2\pi}A W\)

flux_error(amplitude_err, width_err)

Return flux error.

Parameters
  • amplitude_err – estimation of the amplitude error

  • width_err – estimation of the width error

input_params = ['height', 'amplitude', 'x', 'y', 'fwhm']

Keys of the input parameters

params = {}

dictionary containing the parameters of the profile

width = None
class orb.utils.astrometry.Moffat(params)

Bases: orb.utils.astrometry.PSF

Class implementing the Moffat profile.

This profile is useful to fit stars on CCD arrays.

Note

The Moffat profile has been first proposed by Moffat (1969) A&A. The exact form of the equation used has been derived from Trujillo et al. (2001) MNRAS, 977. The PSF:

\(f(x,y) = H + A \times [1+(\frac{r}{\alpha})^2]^{-\beta}\)

with, \(\alpha = \frac{\text{FWHM}}{2\sqrt{2^{1/\beta} - 1}}\)

and, \(r = (x - dx)^2 + (y - dy)^2\)

The total flux F under the 2D profile is thus: \(F = A \times \frac{\pi \alpha^2}{\beta - 1}\)

alpha = None
array2d(nx, ny)

Return a 2D profile given the size of the returned array.

Parameters
  • nx – Length of the returned array along x axis

  • ny – Length of the returned array along y axis

flux()

Return the total flux under the 2D profile.

flux_error(amplitude_err, width_err)

Return flux error.

Parameters
  • amplitude_err – estimation of the amplitude error

  • width_err – estimation of the width error

Warning

Not implemented yet!

input_params = ['height', 'amplitude', 'x', 'y', 'fwhm', 'beta']

Keys of the input parameters

params = {}

dictionary containing the parameters of the profile

class orb.utils.astrometry.PSF

Bases: object

General class of inheritance for point spread functions (PSFs)

array2d(nx, ny)

Return a 2D profile given the size of the returned array.

Parameters
  • nx – Length of the returned array along x axis

  • ny – Length of the returned array along y axis

params = None
varray2d(nx, ny)

Return a vectorized 2D profile given the size of the returned array.

Parameters
  • nx – Length of the returned array along x axis

  • ny – Length of the returned array along y axis

orb.utils.astrometry.aperture_photometry(star_box, fwhm_guess, background_guess=None, background_guess_err=0.0, aper_coeff=3.0, warn=True, x_guess=None, y_guess=None, return_surfaces=False, aperture_surface=None, annulus_surface=None)

Return the aperture photometry of a star centered in a star box.

Parameters
  • star_box – Star box

  • fwhm_guess – Guessed FWHM. Used to get the aperture radius.

  • background_guess – (Optional) If not None, this guess is used instead of the background determination in an annulus around the star (default None).

  • background_guess_err – (Optional) Error on the background guess. Used to compute the aperture photometry error (default 0.).

  • aper_coeff – (Optional) Aperture coefficient. The aperture radius is Rap = aper_coeff * FWHM. Better when between 1.5 to reduce the variation of the collected photons with varying FWHM and 3. to account for the flux in the wings (default 3., better for Moffat stars with a high SNR).

  • warn – (Optional) If True, print a warning when the background cannot be well estimated (default True).

  • x_guess – (Optional) position of the star along x axis. If None, star is assumed to lie at the very center of the frame (default None).

  • y_guess – (Optional) position of the star along y axis. If None, star is assumed to lie at the very center of the frame (default None).

  • return_surfaces – (Optional) If True returns also the aperture_surface and annulus_surface computed. Useful if multiple stars with the same FWHM must be done (default False).

  • aperture_surface – (Optional) Pre-computed aperture_surface. Accelerate the process for multiple stars with the same FWHM but must be used with caution. aper_coeff is of no use if aperture_surface if given (default None). See orb.utils.astrometry.multi_aperture_photometry().

  • annulus_surface – (Optional) Pre-computed annulus_surface. Accelerate the process for multiple stars with the same FWHM but must be used with caution. aper_coeff is of no use if annulus_surface if given (default None). See orb.utils.astrometry.multi_aperture_photometry().

Returns

A Tuple (flux, flux_error, aperture surface, bad_estimation_flag). If the estimation is bad, bad_estimation_flat is set to 1, else it is set to 0.

Note

Best aperture for maximum S/N: 1. FWHM (Howell 1989, Howell 1992). But that works only when the PSF is well sampled which is not always the case so a higher aperture coefficient may be better. More over, to get exact photometry the result must be corrected by aperture growth curve for the ‘missing light’. A coefficient of 1.27 FWHM corresponds to 3 sigma and collects more than 99% of the light if the star is a pure Gaussian. A coefficient of 3 for Moffat stars reduces the variations of the proportion of collected photons when the FWHM is changing and seems to be the best.

Note

Best radius for sky background annulus is determined from this rule of thumb: The number of pixels to estimate the background must be al least 3 times the number of pixel in the aperture (Merline & Howell 1995). Choosing the aperture radius coefficient(Cap) as Rap = Cap * FWHM and the inner radius coefficient (Cin) as Rin = Cin * FWHM, gives the outer radius coefficient (Cout): Cout = sqrt(3*Cap^2 + Cin^2)

Warning

The star MUST be at the center (+/- 1 pixel) of the star box.

orb.utils.astrometry.bin_header(hdr, binning)
orb.utils.astrometry.bin_wcs(wcs, binning)

Return a binned wcs

orb.utils.astrometry.brute_force_guess(image, star_list, x_range, y_range, r_range, rc, zoom_factor, box_size, verbose=True, init_wcs=None, out_wcs=None, raise_border_error=True)

Determine a precise alignment guess by brute force.

Parameters
  • star_list – List of star position. Must be given in pixels.

  • x_range – range of x values to check

  • y_range – range of y values to check

  • r_range – range of angle values to check

  • rc – rotation center (rc, ry). If a WCS is given the rotation center is obtained from the wcs itself and must be set to None.

  • zoom_factor – zoom_factor

  • verbose – (Optional) If True, print some informations (default True).

  • init_wcs – (Optional) WCS instance (can contain an SIP distortion model, default None). Must be the SIP of the frame in which the star position have computed.

  • out_wcs – (Optional) WCS instance (can contain an SIP distortion model, default None). Must be the SIP of the frame in which the stars are looked for.

  • raise_border_error – (Optional) if True raise an exception if the returned guess is on the border of the brute force grid (defaut True).

orb.utils.astrometry.compute_alignment_vectors(fit_results, min_coeff=0.2)

compute alignement vectors from a list of fit results as returned by fit_stars_in_cube.

Parameters
  • fit_results – fit results.

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

orb.utils.astrometry.compute_radec_pm(ra_deg, dec_deg, pm_ra_mas, pm_dec_mas, yr)

Compute RA/DEC in degrees with proper motion values.

Parameters
  • ra_deg – RA in degrees

  • dec_deg – DEC in degrees

  • pm_ra_mas – Proper motion along RA axis in mas/yr (cos of declination)

  • pm_dec_mas – Proper motion along DEC axis in mas/yr

  • yr – Number of years

orb.utils.astrometry.create_wcs(target_x, target_y, deltax, deltay, target_ra, target_dec, rotation, sip=None)

Create a WCS with an optional SIP distortion model.

Parameters
  • wcs – Original WCS. If None, a 2 axis WCS is created instead.

  • target_x – Target X position in pixels

  • target_y – Target Y position in pixels

  • deltax – Plate scale in arcdeg / pixel along X axis (don’t forget to divide by 3600 if originally in arcsec by pixels)

  • deltax – Plate scale in arcdeg / pixel along Y axis (don’t forget to divide by 3600 if originally in arcsec by pixels)

  • target_ra – Target RA

  • target_dec – Target DEC

  • rotation – Rotation angle

  • sip – (Optional) astropy.WCS instance containing a valid SIP.

orb.utils.astrometry.dec2deg(dec)

Convert DEC in sexagesimal format to degrees.

Parameters

dec – DEC in sexagesimal format

orb.utils.astrometry.deg2dec(deg, string=False)

Convert DEC in degrees to sexagesimal.

Parameters

deg – DEC in degrees

orb.utils.astrometry.deg2ra(deg, string=False)

Convert RA in degrees to sexagesimal.

Parameters

deg – RA in degrees

orb.utils.astrometry.df2list(sources)

Convert a sources pandas.DataFrame instance to a list of positions

orb.utils.astrometry.dflist2arr(df, key)

Convert a list of stars fit results (as the one returned by orb.cube.fit_stars) saved in a data frame (which can be loaded with utils.io.load_df) to a array of vectors given the key which must be extracted.

Parameters
  • df – list of DataFrames

  • key – Can be flux, aperture_flux, flux_err, aperture_flux_err, etc.

orb.utils.astrometry.fit2df(fit)

Convert fit results to a pandas.DataFrame instance

orb.utils.astrometry.fit_sip(scale, star_list1, star_list2, params=None, init_sip=None, err=None, sip_order=4, crpix=None, crval=None, plot=False)

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).

Parameters
  • scale – Plate scale of the image in arcseconds (can be a tuple (scalex, scaley) or a single float)

  • 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 3).

  • 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.

orb.utils.astrometry.fit_sip_from_points(xy, radec, sip_order=None, proj_point=None)

Return a fitted WCS with SIP.

This is a simple wrapper around astropy.wcs.utils.fit_wcs_from_points().

Parameters
  • xy – (x,y) tuple in pixels

  • radec – (ra, dec) tuple in degrees

  • sip_order – SIP order. If SIP is None, the returned WCS will not contain SIP.

orb.utils.astrometry.fit_star(star_box, profile_name='gaussian', fwhm_pix=None, amp=None, beta=3.5, height=None, pos=None, fix_height=False, fix_amp=False, fix_beta=True, fix_fwhm=False, fix_pos=False, fit_tol=0.001, check=True, fwhm_min=0.5, check_reject=False, ron=10.0, dcl=0.0, estimate_local_noise=True, precise_guess=False, saturation=None)

Fit a single star

Parameters
  • star_box – The box where the star has to be fitted.

  • profile_name – (Optional) Name of the PSF profile to use to fit stars. May be ‘gaussian’ or ‘moffat’ (default ‘gaussian’).

  • amp – (Optional) Amplitude guess, replace the value of the automatic estimation (default None).

  • fwhm_pix – (Optional) Estimate of the FWHM in pixels. If None given FWHM is estimated to half the box size (default None).

  • beta – (Optional) Beta parameter of the moffat psf. Used only if the fitted profile is a Moffat psf (default 3.5).

  • height – (Optional) Height guess, replace the value of the automatic estimation (default None).

  • pos – (Optional) Position guess as a tuple (x,y), replace the value of the automatic estimation (default None).

  • fix_amp – (Optional) Fix amplitude parameter to its estimation (default False)

  • fix_height – (Optional) Fix height parameter to its estimation (default False)

  • fix_beta – (Optional) Fix beta to the given value (default True).

  • fix_fwhm – (Optional) Fix FWHM to its estimation (default False).

  • fix_pos – (Optional) Fix position parameters (x,y) at their estimated value (default False).

  • fit_tol – (Optional) Tolerance on the paramaters fit (the lower the better but the longer too) (default 1e-2).

  • check – (Optional) If True, check fit results for oddities (default True).

  • fwhm_min – (Optional) Minimum valid FWHM [in pixel] of the fitted star (default 0.5)

  • check_reject – (Optional) [Debug] If True, print the reason why a fit is rejected (default False).

  • ron – (Optional) Readout noise in ADU/pixel (default 10.). estimate_local_noise must be set to False for this noise to be taken into account.

  • dcl – (Optional) Dark current level in ADU/pixel (default 0.). estimate_local_noise must be set to False for this noise to be taken into account.

  • estimate_local_noise – (Optional) If True, the level of noise is computed from the background pixels around the stars. ron and dcl are thus not used (default True).

  • precise_guess – (Optional) If True, the fit guess will be more precise but this can lead to errors if the stars positions are not already well known (default False).

  • saturation – (Optional) If not None, all pixels above the saturation level are removed from the fit (default None).

orb.utils.astrometry.fit_stars_in_frame(frame, star_list, box_size, profile_name='gaussian', scale=None, fwhm_pix=None, beta=3.5, fit_tol=0.01, fwhm_min=0.5, fix_height=None, fix_aperture_fwhm_pix=None, fix_beta=True, fix_fwhm=False, readout_noise=10.0, dark_current_level=0.0, local_background=True, no_aperture_photometry=False, precise_guess=False, aper_coeff=3.0, no_fit=False, estimate_local_noise=True, multi_fit=False, enable_zoom=False, enable_rotation=False, saturation=None, fix_pos=False, nozero=False, silent=True, sip=None, background_value=None, filter_background=False)

Fit stars in a frame.

Note

2 fitting modes are possible:

  • Individual fit mode [multi_fit=False]: Stars are all fit independantly.

  • Multi fit mode [multi_fit=True]: Stars are fitted all together considering that the position pattern is well known, the same shift in x and y will be applied. Optionally the pattern can be rotated and zoomed. The FWHM is also considered to be the same. This option is far more robust and precise for alignment purpose.

Parameters
  • frame – The frame containing the stars to fit.

  • star_list – A list of star positions as an array of shape (star_nb, 2)

  • box_size – The size of the box created around a star to fit its parameter.

  • profile_name – (Optional) Name of the PSF profile to use to fit stars. May be ‘gaussian’ or ‘moffat’ (default ‘gaussian’).

  • fwhm_pix – (Optional) Estimate of the FWHM in pixels. If None given FWHM is estimated to half the box size (default None).

  • scale – (Optional) Scale of the frame in arcsec/pixel. If given the fwhm in arcseconds is also computed (keyword: ‘fwhm_arc’) with the fit parameters (default None).

  • beta – (Optional) Beta parameter of the moffat psf. Used only if the fitted profile is a Moffat psf (default 3.5).

  • fix_height – (Optional) Fix height parameter to its estimation. If None, set by default to True in individual fit mode [multi_fit=False] and False in multi fit mode [multi_fit=True] (default None).

  • fix_beta – (Optional) Fix beta to the given value (default True).

  • fix_fwhm – (Optional) Fix FWHM to the given value or the estimated value (default False).

  • fix_pos – (Optional) Fix x,y positions of the stars to the given value.

  • fit_tol – (Optional) Tolerance on the paramaters fit (the lower the better but the longer too) (default 1e-2).

  • nozero – (Optional) If True do not fit any star which box (the pixels around it) contains a zero. Valid only in individual fit mode [multi_fit=False] (default False).

  • fwhm_min – (Optional) Minimum valid FWHM of the fitted star (default 0.5)

  • silent – (Optional) If True no messages are printed (default True).

  • local_background – (Optional) If True, height is estimated localy, i.e. around the star. If False, the sky background is determined in the whole frame. In individual fit mode [multi_fit=False] height will be the same for all the stars, and the fix_height option is thus automatically set to True. In multi fit mode [multi_fit=True] height is considered as a covarying parameter for all the stars but it won’t be fixed (default True).

  • fix_aperture_fwhm_pix – (Optional) If a positive float. FWHM used to scale aperture size is not computed from the mean FWHM in the frame but fixed to the given float (default None).

  • no_aperture_photometry – (Optional) If True, aperture photometry will not be done after profile fitting (default False).

  • precise_guess – (Optional) If True, the fit guess will be more precise but this can lead to errors if the stars positions are not already well known. Valid only in individual fit mode [multi_fit=False] (default False).

  • readout_noise – (Optional) Readout noise in ADU/pixel (can be computed from bias frames: std(master_bias_frame)) (default 10.)

  • dark_current_level – (Optional) Dark current level in ADU/pixel (can be computed from dark frames: median(master_dark_frame)) (default 0.)

  • aper_coeff – (Optional) Aperture coefficient. The aperture radius is Rap = aper_coeff * FWHM. Better when between 1.5 to reduce the variation of the collected photons with varying FWHM and 3. to account for the flux in the wings (default 3., better for star with a high SNR).

  • no_fit – (Optional) If True, no fit is done. Only the aperture photometry. Star positions in the star list must thus be precise (default False).

  • multi_fit – (Optional) If True all stars are fitted at the same time. More robust for alignment purpose. The difference of position between the stars in the star list must be precisely known because the overall shift only is estimated (default False).

  • enable_zoom – (Optional) If True, the stars position pattern can be zoomed to better adjust it to the real frame. Valid only in multi fit mode [multi_fit=True] (default False).

  • enable_rotation – (Optional) If True, the stars position pattern can be rotated to better adjust it to the real frame Valid only in multi fit mode [multi_fit=True] (default False).

  • estimate_local_noise – (Optional) If True, the level of noise is computed from the background pixels around the stars. readout_noise and dark_current_level are thus not used (default True).

  • saturation – (Optional) If not None, all pixels above the saturation level are removed from the fit (default None).

  • sip – (Optional) A pywcs.WCS instance containing SIP distorsion correction (default None).

  • background_value – (Optional) If not None, this background value is used in the fit functions and will be fixed for fit and aperture photometry. Note also that in this case local_background is automatically set to False (default None).

Returns

Parameters of a 2D fit of the stars positions.

See also

astrometry.Astrometry.load_star_list() to load a predefined list of stars or astrometry.Astrometry.detect_stars() to automatically create it.

See also

utils.astrometry.fit_star() and orb.cutils.multi_fit_stars()

orb.utils.astrometry.fit_wcs(star_list_pix, star_list_deg, wcs, fitsip=False)
orb.utils.astrometry.get_cd(wcs)

Return CD matrix from a header with PC matrix.

Parameters

wcs – astropy.wcs.WCS instance.

Returns

CD matrix

orb.utils.astrometry.get_profile(profile_name)

Return the PSF profile class corresponding to the given profile name.

Parameters

name (profile) – The name of the PSF profile. Must be ‘moffat’ or ‘gaussian’.

orb.utils.astrometry.get_wcs_parameters(wcs, fix_rc=None)

Return comprehensive parameters from a simple WCS as created with orb.utils.astrometry.create_wcs.

Parameters
  • wcs – An astropy.wcs.WCS instance created with orb.utils.astrometry.create_wcs.

  • fix_rc – Fix the rotation center of the returned parameters to a given value. Must be atuple (target_x, target_y)

Returns

target_x, target_y, deltax, deltay, target_ra, target_dec, rotation

orb.utils.astrometry.guess(star_box, pos=None, height=None, precise_pos=False)

Return an estimation of the star parameters.

Parameters
  • star_box – Sub-part of an image surrounding a star. The center of the star must be placed near the center of the box. The dimensions of the box must be greater than 3 times the FWHM of the star.

  • pos – (Optional) Position guess as a tuple (x,y). Used to estimate amplitude (default None).

  • height – (Optional) Guess of the background level. Used to estimate amplitude (default None).

  • precise_pos – (Optional) If True, position is estimated from the marginal distribution of the PSF. Return a far better estimation if and only if the star is well centered in the box, i.e. if and only if the position of the star is already known. This can lead to errors when trying to find the star in the box, in this case precise_pos must be set to False (default False).

Returns

[height,amplitude,x,y,width]

orb.utils.astrometry.histogram_registration(star_list1, star_list2, dimx, dimy, xy_bins)

Fast histogram registration of an image based on the comparison of two star lists: one created from the real star position in the image and the other from, e.g. a catalog.

Parameters
  • star_list1 – first list of stars

  • star_list2 – second list of stars

  • dimx – X dimension of the image in pixels

  • dimy – Y dimension of the image inp ixels

  • xy_bins – number of bins along X and Y

Warning

This kind of registration is very sensitive to the angle between each list. It is better to use it on a range of angles (steps of 0.5 degree) to make sure the best correlation is found.

orb.utils.astrometry.load_star_list(star_list, remove_nans=False)

Load a list of stars coordinates from an hdffile, a pandas DataFrame, a numpy.ndarray or a 2 columns text file.

Star_list

can be a np.ndarray of shape (n, 2) or a path to a star list

Parameters

remove_nans – If True, Nans are removed from the output star list

orb.utils.astrometry.mag(flux)
Return the instrumental magnitude of a given flux (magnitude 0

is set to 1 e-)

Parameters

flux – Flux in e-

orb.utils.astrometry.match_star_lists(wcs, sl1deg, sl2pix, rc, xyrange=(500, 50), rrange=(6, 1), zrange=(0.03, 0.015), nsteps=7)
orb.utils.astrometry.multi_aperture_photometry(frame, pos_list, fwhm_guess_pix, aper_coeff=3.0, detect_fwhm=False, silent=False)

Aperture photometry of multiple sources in a frame.

Parameters
  • frame – Frame

  • pos_list – List of the positions of the sources

  • fwhm_guess_pix – Initial guess on the FWHM of the sources.

  • aper_coeff – (Optional) Aperture coefficient used for photometry (default 3.).

  • detect_fwhm – (Optional) If True FWHM is automatically computed from a fit on the sources. Sources must be stars or bright point sources. If most of the sources are stars this might work well enough (default False).

  • silent – (Optional) Silent function if True (default False).

orb.utils.astrometry.pc2cd(hdr)

Convert header PC definition to CD definition

Parameters

hdr – A FITS header

Returns

converted FITS header

orb.utils.astrometry.pix2world(hdr, dimx, dimy, star_list_pix, dxmap, dymap)

Convert pixel positions to RA/DEC coordinates.

Parameters
  • hdr – pyfits.Header instance

  • dimx – Image dimension along X

  • dimy – Image dimension along Y

  • star_list_pix – List of star coordinates in pixels

  • dxmap – Distortion error map along X axis returned by orb.astrometry.Astrometry.register().

  • dymap – Distortion error map along Y axis returned by orb.astrometry.Astrometry.register().

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.

orb.utils.astrometry.ra2deg(ra)

Convert RA in sexagesimal format to degrees.

Parameters

ra – RA in sexagesimal format

orb.utils.astrometry.radial_profile(a, xc, yc, rmax)

Return the average radial profile on a region of a 2D array.

Parameters
  • a – A 2D array

  • xc – Center of the profile along x axis

  • yc – Center of the profile along y axis

  • rmax – Radius of the profile

Returns

(R axis, V axis). A tuple of 2 vectors giving the radius axis and the corresponding values axis.

orb.utils.astrometry.realign_images(_cube)

Realign images of a small cube of images

Parameters

_cube – A 3 dimensional np.ndarray.

Warning

This procedure is robust but very slow. Do not use it to realign a large number of images.

orb.utils.astrometry.sky_background_level(im, smooth_coeff=0.1, return_mode=False, bins=25, return_error=False)

Return the level of the sky background based on the maximum of the histogram of the pixels distribution in the image.

Parameters
  • im – Image.

  • smooth_coeff – (Optional) the smoothing degree, i.e. the number of smoothing points is defined by smooth_coeff * size(histogram) (default 0.05). If smooth_coeff <= 0. no smoothing is applied.

  • return_mode – (Optional) If True the returned value is the mode (an entire value for a distribution of integers). If False, return the mean of a sigmacut realized around the mode (a fractional value, generally more precise).

  • bins – (Optional) Number of bins for the histogram (default 20).

  • return_error – (Optional) If True, the error on the estimation is returned (default False).

orb.utils.astrometry.transform_star_position_A_to_B(star_list_A, params, rc, zoom_factor, sip_A=None, sip_B=None)

Transform star positions in camera A to the positions in camera B given the transformation parameters.

Optionally SIP distorsion parameters can be given.

The transformation steps are:

dist_pix_camA -> perf_pix_camA -> geometric transformation_A2B
-> perf_pix_camB -> dist_pix_camB
Parameters
  • star_list_A – List of star coordinates in the cube A.

  • params – Transformation parameters [dx, dy, dr, da, db].

  • rc – Rotation center coordinates.

  • zoom_factor – Zooming factor between the two cameras. Can be a couple (zx, zy).

  • sip_A – (Optional) pywcs.WCS instance containing SIP parameters of the frame A (default None).

  • sip_B – (Optional) pywcs.WCS instance containing SIP parameters of the frame B (default None).

orb.utils.astrometry.transform_wcs(wcs, params, rc, zoom_factor, sip=None, wcs_params=None)

Gometric transformation of a wcs

Parameters
  • wcs – wcs.

  • params – Transformation parameters [dx, dy, dr, da, db].

  • rc – Rotation center coordinates.

  • zoom_factor – Zooming factor between the two cameras. Can be a couple (zx, zy).

  • sip – (Optional) pywcs.WCS instance containing SIP parameters of the output wcs (default None).

  • wcs_params – If already computed, accelerates the process. Must be obtained with compute_wcs_parameters(wcs).

orb.utils.astrometry.world2pix(hdr, dimx, dimy, star_list_deg, dxmap, dymap)

Convert RA/DEC coordinates to pixel positions.

Parameters
  • hdr – pyfits.Header instance

  • dimx – Image dimension along X

  • dimy – Image dimension along Y

  • star_list_deg – List of star coordinates in degrees

  • dxmap – Distortion error map along X axis returned by orb.astrometry.Astrometry.register().

  • dymap – Distortion error map along Y axis returned by orb.astrometry.Astrometry.register().

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.

orb.utils.err module

exception orb.utils.err.DeepFrameError

Bases: orb.utils.err.ORBError

exception orb.utils.err.FitError

Bases: orb.utils.err.ORBError

exception orb.utils.err.FitInitError

Bases: orb.utils.err.ORBError

exception orb.utils.err.FitInputError

Bases: orb.utils.err.ORBError

exception orb.utils.err.ORBError

Bases: RuntimeError

exception orb.utils.err.ValidationError

Bases: orb.utils.err.ORBError

orb.utils.fft module

orb.utils.fft.apod2sigma(apod, fwhm)

Return the broadening of the gaussian-sinc function in the spectrum for a given apodization level. Unit is that of the fwhm.

Parameters

apod – Apodization level (must be >= 1.)

orb.utils.fft.apod2width(apod)

Return the width of the gaussian window for a given apodization level.

Parameters

apod – Apodization level (must be >= 1.)

The apodization level is the broadening factor of the line (an apodization level of 2 mean that the line fwhm will be 2 times wider).

orb.utils.fft.border_cut_window(n, coeff=0.2)

Return a window function with only the edges cut by a nice gaussian shape function.

Parameters
  • n – Window length

  • coeff – Border size in percentage of the total length.

orb.utils.fft.clean_phase(ph)

Return a cleaned phase vector (which does not depend on an arbitrary modulo pi)

orb.utils.fft.cube_raw_fft(x, apod=None)

Compute the raw FFT of a cube (the last axis beeing the interferogram axis)

Parameters
  • x – Interferogram cube

  • apod – (Optional) Apodization function used. See utils.gaussian_window() (default None)

orb.utils.fft.gaussian_window(coeff, x)

Return a Gaussian apodization function for a given broadening factor.

Parameters
  • coeff – FWHM relative to the sinc function. Must be a float > 1.

  • x – Must be an axis defined between -1 and 1 inclusively. x = np.linspace(-1., 1., n) for a symmetrical window.

orb.utils.fft.indft(a, x)

Inverse Non-uniform Discret Fourier Transform.

Compute the irregularly sampled interferogram from a regularly sampled spectrum.

Parameters
  • a – regularly sampled spectrum.

  • x – positions of the interferogram samples. If x = range(size(a)), this function is equivalent to an idft or a ifft. Note that the ifft is of course much faster to compute. This vector may have any length.

orb.utils.fft.interf_mean_energy(interf)

Return the mean energy of an interferogram by step.

Parameters

interf – an interferogram

Warning

The mean of the interferogram is substracted to compute only the modulation energy. This is the modulation energy which must be conserved in the resulting spectrum. Note that the interferogram transformation function (see utils.transform_interferogram()) remove the mean of the interferogram before computing its FFT.

Note

NaNs are set to 0.

orb.utils.fft.learner95_window(x)

Return the apodization function described in Learner et al., J. Opt. Soc. Am. A, 12, (1995).

This function is closely related to the minimum four-term Blackman-Harris window.

Parameters

x – Must be an axis defnined between -1 and 1 inclusively. x = np.linspace(-1., 1., n) for a symmetrical window.

orb.utils.fft.mod2pi(a)

Return the smallest signed modulo 2 pi of any angle in radians

orb.utils.fft.ndft(a, xk, vj)

Non-uniform Discret Fourier Tranform

Compute the spectrum from an interferogram. Note that the axis can be irregularly sampled.

If the spectral axis (output axis) is irregular the result is exact. But there is no magic: if the input axis (interferogram sampling) is irregular the output spectrum is not exact because the projection basis is not orthonormal.

If the interferogram is the addition of multiple regularly sampled scans with a opd shift between each scan, the result will be good as long as there are not too much scans added one after the other. But if the interferogram steps are randomly distributed, it will be better to use a classic FFT because the resulting noise will be much lower.

Parameters
  • a – 1D interferogram

  • xk – 1D sampling steps of the interferogram. Must have the same size as a and must be relative to the real step length, i.e. if the sampling is uniform xk = np.arange(a.size).

  • vj – 1D frequency sampling of the output spectrum.

orb.utils.fft.next_power_of_two(n)

Return the next power of two greater than n.

Parameters

n – The number from which the next power of two has to be computed. Can be an array of numbers.

orb.utils.fft.norton_beer_window(fwhm='1.6', n=1000)

Return an extended Norton-Beer window function (see [NAY2007]).

Returned window is symmetrical.

Parameters
  • fwhm – FWHM relative to the sinc function. Must be: 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9 or 2.0. (default ‘1.6’)

  • n – Number of points (default 1000)

Note

Coefficients of the extended Norton-Beer functions apodizing functions [NAY2007] :

FWHM

C0

C1

C2

C4

C6

C8

1.1

0.701551

-0.639244

0.937693

0.000000

0.000000

0.000000

1.2

0.396430

-0.150902

0.754472

0.000000

0.000000

0.000000

1.3

0.237413

-0.065285

0.827872

0.000000

0.000000

0.000000

1.4

0.153945

-0.141765

0.987820

0.000000

0.000000

0.000000

1.5

0.077112

0.000000

0.703371

0.219517

0.000000

0.000000

1.6

0.039234

0.000000

0.630268

0.234934

0.095563

0.000000

1.7

0.020078

0.000000

0.480667

0.386409

0.112845

0.000000

1.8

0.010172

0.000000

0.344429

0.451817

0.193580

0.000000

1.9

0.004773

0.000000

0.232473

0.464562

0.298191

0.000000

2.0

0.002267

0.000000

0.140412

0.487172

0.256200

0.113948

NAY2007(1,2)

Naylor, D. A., & Tahic, M. K. (2007). Apodizing functions for Fourier transform spectroscopy. Journal of the Optical Society of America A.

orb.utils.fft.phase_model(sigma, sigmaref, p)

Phase model

A simple polynomial. Defining a reference wavenumber in the given axis is important since, if a 0 is not in the axis, the polynomial fitting is unstable. This reference is defined in the filterfile.

orb.utils.fft.raw_fft(x, apod=None, inverse=False, return_complex=False, return_phase=False)

Compute the raw FFT of a vector.

Return the absolute value of the complex vector by default.

Parameters
  • x – Interferogram.

  • apod – (Optional) Apodization function used. See utils.norton_beer_window() (default None)

  • inverse – (Optional) If True compute the inverse FFT (default False).

  • return_complex – (Optional) If True, the complex vector is returned (default False).

  • return_phase – (Optional) If True, the phase is returned.(default False)

orb.utils.fft.sigma2apod(sigma, fwhm)

This is the inverse of apod2sigma.

As the inverse is at least complicated to compute. This is done via minimization.

orb.utils.fft.spectrum_mean_energy(spectrum)

Return the mean energy of a spectrum by channel.

Parameters

spectrum – a 1D spectrum

orb.utils.fft.width2apod(width)

This is the inverse of apod2width.

As the inverse is at least complicated to compute. This is done via minimization.

orb.utils.filters module

orb.utils.filters.compute_weights(calib, nm_laser, step_nb, step, order, range_border_coeff, filter_min_cm1, filter_max_cm1)

Compute weights for a fit based on a spectrum with a given filter bandpass

Parameters
  • calib – Calibration laser observed wavelength

  • nm_laser – Calibration laser theoretical wavelength

  • step_nb – Vector length

  • step – Step size (in nm)

  • order – Folding order

  • range_border_coeff – Percentage of the vector size considered as bad borders near the filter edges (must be between 0.2 and 0.).

  • filter_min_cm1 – Minimum wavenumber of the filter in cm-1

  • filter_max_cm1 – Maximum wavenumber of the filter in cm-1

orb.utils.fit module

orb.utils.fit.BIC(residual, k)

Bayesian Information Criterion https://en.wikipedia.org/wiki/Bayesian_information_criterion

Parameters
  • residual – Fit residual (as a vector)

  • k – Number of free parameters of the model

orb.utils.fit.estimate_flux(spectrum, axis, lines_cm1, vel, filter_range_pix, oversampling_ratio)
orb.utils.fit.estimate_velocity_prepared(spectrum, vels, combs, precision, filter_range_pix, max_comps, threshold=2.5, return_score=False, prod=True)

Provide a velocity estimate. Most of the input should be computed with a dedicated function such as fft.Spectrum.prepare_velocity_estimate.

Parameters

threshold – Detection threshold as a factor of the std of the calculated score.

orb.utils.fit.get_comb(lines_cm1, vel, axis, oversampling_ratio)
orb.utils.fit.gvardict2pickdict(gvardict)

Convert a dictionary containing gvars into a nice pickable dictionary with couples of _mean / _sdev keys.

Use the pickdict2gvardict to return to the original dictionary.

orb.utils.fit.paramslist2pick(paramslist)
orb.utils.fit.pick2paramslist(picklist)
orb.utils.fit.pickdict2gvardict(pickdict)

Invert gvardict2pickdict.

orb.utils.fit.prepare_combs(lines_cm1, axis, vel_range, oversampling_ratio, precision)
orb.utils.fit.sigma2vel(sigma, lines, axis_step)

Convert a broadening in channels to a velocity in km/s :param sigma: broadening in channels :param lines: line position in the unit of axis_step :param axis_step: axis step size

orb.utils.fit.vel2sigma(vel, lines, axis_step)

Convert a velocity in km/s to a broadening in channels. :param vel: velocity in km/s :param lines: line position in the unit of axis_step :param axis_step: axis step size

orb.utils.image module

orb.utils.image.bf_laser_aligner(im1, im2, init_dx, init_dy, init_angle, zf, binning=4)

Align two complementary laser frames (i.e. cam1 and cam2) with a brute force algorithm.

Parameters
  • im1 – frame 1

  • im2 – frame 2

  • init_dx – Initial alignement parameter along X axis

  • init_dy – Initial alignement parameter along Y axis

  • init_angle – Initial angle

  • zf – Zoom factor

  • binning – Binning of the data for the first pass

Warning

This function returns parameters much different that the alignement parameters we get from stars… I don’t know why !

orb.utils.image.bilinear_interpolation(c, x, y)

Bilinear interpolation in a 2x2xN cube

Parameters
  • c – 2x2xN cube

  • x – position in the cube along x between 0 and 1

  • y – position in the cube along y between 0 and 1

orb.utils.image.bin_image(a, binning)

Return mean binned image.

Parameters
  • image – 2d array to bin.

  • binning – binning (must be an integer >= 1).

Note

Only the complete sets of rows or columns are binned so that depending on the bin size and the image size the last columns or rows can be ignored. This ensures that the binning surface is the same for every pixel in the binned array.

orb.utils.image.check_frames(frames, sigma_reject=2.5)

Check and reject deviating frames based on their median level.

Frames with a too deviant median level are discarded. This function is used by utils.create_master_frame().

Parameters
  • frames – Set of frames to check

  • sigma_reject – (Optional) Rejection coefficient (default 2.5)

orb.utils.image.compute_binning(image_shape, detector_shape)

Return binning along both axis given the image shape and the detector shape.

Parameters
  • image_size – Tuple [x,y] giving the image shape

  • detector_shape – Tuple [x,y] giving the detector shape (i.e. maximum numbers of pixels along the x and y axis.)

orb.utils.image.correct_cosmic_rays(frame, cr_map)

correct cosmic rays in an image

CRs are replaced by a weighted average of the neighbouring region. Weights are calculated from a 2d gaussian kernel.

Parameters
  • frame – image

  • cr_map – cosmic ray map (1 = CR, 0 = NO_CR). must be of boolean type.

orb.utils.image.correct_hot_pixels(im, hp_map, box_size=3, std_filter_coeff=1.5)

Correct hot pixels in an image given a map of their position.

The algorithm used replaces a hot pixel value by the median of the pixels in a box around it. Pixels values which are not too much different from the values around are not modified.

Parameters
  • im – Image to correct

  • hp_map – Hot pixels map (1 for hot pixels, 0 for normal pixel)

  • box_size – (Optional) Size of the correction box (default 3).

  • std_filter_coeff – (Optional) Coefficient on the std used to check if the value of a hot pixel must be changed (default 1.5).

orb.utils.image.correct_map2d(map2d, bad_value=nan)

Correct a map of values by interpolation along columns.

The bad value must be specified.

Parameters
  • map2d – The map to correct

  • bad_value – (Optional) Value considered as bad (default np.nan).

orb.utils.image.create_master_frame(frames, combine='average', reject='avsigclip', sigma=3.0, silent=False, check=True)

Create a master frame from a set a frames.

This method has been inspired by the IRAF function combine.

Parameters
  • frames – Frames to combine.

  • reject – (Optional) Rejection operation. Can be ‘sigclip’, ‘minmax’, ‘avsigclip’ (default ‘avsigclip’)

  • combine – (Optional) Combining operation. Can be ‘average’ or ‘median’ (default ‘average’)

  • sigma – (Optional) Sigma factor for pixel rejection (default 3.).

  • silent – (Optional) If True no information message are displayed.

  • check – (Optional) If True deviating frames are rejected before combination (default True).

Note

Rejection operations:

  • sigclip: A Sigma Clipping algorithm is applied for each pixel. Min and max values are rejected to estimate the mean and the standard deviation at each pixel. Then all values over (median + sigma * std) or below (median - sigma * std) are rejected. Those steps are repeated (this time not excluding the extreme values) while no other value is rejected or the minimum number of values to keep is reached. Work best with at least 10 frames.

  • avsigclip: Average Sigma Clipping algorithm is the same as Sigma Clipping algorithm but the standard deviation at each pixel is estimated using an averaged value of the std over the lines. This work best than sigma clipping for a small number of frames. This algorithm is a little more time consuming than the others. Works best with at least 5 frames.

  • minmax: Minimum and maximum values at each pixel are rejected.

Warning

No rejection operation can be performed with less than 3 frames.

orb.utils.image.crop_pixel_positions(pixs, xmin, xmax, ymin, ymax)

Returned a croped list of pixels position

orb.utils.image.extract_elliptical_profile(im, x0, y0, rX, rY, theta, n=20, percentile=None)

Extract the elliptical profile of a source

Parameters
  • im – Image

  • x0 – X position of the center

  • theta – Angle of the ellipse (in deg)

  • rX – Radius of the X axis

  • rY – Radius of the Y axis

  • n – (Optional) Number of divisions (default 20)

  • percentile – (Optional) percentile instead of std. Return (r, lmedian, [lmin, lmax]). Remember that the 1-sigma percentile is 15.865 for a gaussian distribution (default None).

Parma y0

Y position of the center

Returns

a tuple (r, l, lerr) where r is the list of radiuses along rX, l the mean luminosity in the ellipse portion corresponding to the radius, lerr the standard deviation of the luminosity in the same portion of the ellipse.

orb.utils.image.filter_background(im)

Filter modulated background

orb.utils.image.fit_calibration_laser_map(calib_laser_map, calib_laser_nm, pixel_size=15.0, binning=4, mirror_distance_guess=240000.0, return_model_fit=False)

Fit a calibration laser map.

Fit an opto-mechanical model first and uses Zernike polynomials to fit the residual wavefront error.

The model is based on optical parameters.

Parameters
  • calib_laser_map – Reference calibration laser map.

  • calib_laser_nm – Wavelength of the calibration laser in nm.

  • pixel_size – (Optional) Size of the CCD pixels in um (default 15).

  • binning – (Optional) Maps are binned to accelerate the process. Set the binning factor (default 4).

  • mirror_distance_guess – (Optional) Guess on the mirror distance in um (default 2.2e5).

  • return_model_fit – (Optional) If True the optical model fit is also returned (i.e. without the wavefront modeling with Zernike polynomials) (default False).

Note

Zernike polynomial fit routine has been written by Tim van Werkhoven (werkhoven@strw.leidenuniv.nl) as a part of libtim. It can be found in ORB module in ./ext/zern.py.

orb.utils.image.fit_map(data_map, err_map, smooth_deg)

Fit map with low order polynomials

Parameters
  • data_map – data map

  • err_map – error map

  • smooth_deg – Degree of fit smoothing (beware of high smoothing degrees)

Returns

a tuple: (fitted data map, residual map, fit RMS error)

orb.utils.image.fit_map_gradient(im, im_err)
orb.utils.image.fit_map_theta(data_map, err_map, theta_map)

fit any data map with respect to theta. Given the corresponding theta map.

Parameters
  • data_map – Data map to fit

  • err_map – Uncertainty on the data map

  • theta_map – Theta map (in degree)

orb.utils.image.fit_map_zernike(data_map, weights_map, nmodes)

Fit a map with Zernike polynomials.

Bad values must be set to NaN (not 0.)

Parameters
  • data_map – Data map to fit

  • weights_map – weights map (high weight value stands for high precision data)

  • nmodes – Number of zernike modes to use for fitting.

Returns

(fitted data map, error map, fit error)

Note

Zernike polynomial fit routine has been written by Tim van Werkhoven (werkhoven@strw.leidenuniv.nl) as a part of libtim. It can be found in ORB module in ./ext/zern.py.

orb.utils.image.fit_phase_map(data_map, err_map, theta_map)

Fit an order 0 phase map with a simple cos(theta) model

orb.utils.image.get_box_coords(ix, iy, box_size, x_lim_min, x_lim_max, y_lim_min, y_lim_max)

Return the coordinates of a box given the center of the box, its size and the limits of the range along x and y axes.

Parameters
  • ix – center of the box along x axis

  • iy – center of the box along y axis

  • box_size – Size of the box. The final size of the box will generally be the same if box_size is odd. Note that the final size of the box cannot be guaranteed.

  • x_lim_min – Minimum limit of the range along x.

  • x_lim_max – Maximum limit of the range along x.

  • y_lim_min – Minimum limit of the range along y.

  • y_lim_max – Maximum limit of the range along y.

Returns

x_min, x_max, y_min, y_max

orb.utils.image.get_quadrant_dims(quad_number, dimx, dimy, div_nb)

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

Parameters
  • quad_number – Quadrant number

  • dimx – X axis dimension.

  • dimy – Y axis dimension.

  • div_nb – 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)

orb.utils.image.gradient_map(dimx, dimy, h, da, db)

Simple gradient map model

orb.utils.image.high_pass_diff_image_filter(im, deg=1)

Return a high pass filtered image using the method of low pass diffrence filtering given by Mighell (1999).

Parameters
  • im – Image to filter

  • deg – (Optional) Radius of the kernel of the low pass filter. Must be > 0 (default 1).

orb.utils.image.high_pass_image_filter(im)

Return a high pass filtered image.

Parameters

im – Image to filter

orb.utils.image.in_ellipse(x, y, x0, y0, rX, rY, theta)

Tell whether a pixel is in the ellipse or not.

Parameters
  • x – X position of the point

  • y – Y position of the point

  • x0 – X position of the center

  • theta – Angle of the ellipse (in deg)

  • rX – Radius of the X axis

  • rY – Radius of the Y axis

Parma y0

Y position of the center

orb.utils.image.interpolate_map(m, dimx, dimy, deg=3)

Interpolate 2D data map.

This function is robust to Nans.

Warning

The interpolation process is much longer if Nans are present in the map.

Parameters
  • m – Map

  • dimx – X dimension of the result

  • dimy – Y dimension of the result

orb.utils.image.low_pass_image_filter(im, deg)

Return a low pass filtered image using a gaussian kernel.

Parameters
  • im – Image to filter

  • deg – Radius of the kernel. Must be > 0.

orb.utils.image.nanbin_image(im, binning)

Mean image (or cube) binning robust to NaNs.

Parameters
  • im – Image or cube to bin

  • binning – Binning factor (must be an integer)

orb.utils.image.nn_interpolate(A, new_size)

Vectorized Nearest Neighbor Interpolation adapated from https://gist.github.com/KeremTurgutlu/68feb119c9dd148285be2e247267a203

orb.utils.image.on_ellipse(x, y, x0, y0, rX, rY, theta, e=0.5)

Tell whether a pixel is on the ellipse or not.

Parameters
  • x – X position of the point

  • y – Y position of the point

  • x0 – X position of the center

  • theta – Angle of the ellipse (in deg)

  • rX – Radius of the X axis

  • rY – Radius of the Y axis

  • e – (Optional) Precision in pixels (default 0.5).

Parma y0

Y position of the center

orb.utils.image.polar_map2d(f, n, corner=False, circle=True)

Map a function over a square matrix in polar coordinates. The origin is placed at the center of the map by default.

Parameters
  • f – The function to map.

  • n – Matrix size. Can be a couple of integers (nx, ny).

  • corner – (Optional) If True, the origin of the coordinates becomes the corner (0,0) of the map (default False)

  • circle – (Optional) If False and if the matrix is not squared, the coordinates are those of an ellipsis of the same shape as the matrix (default True).

orb.utils.image.pp_create_master_frame(frames, combine='average', reject='avsigclip', sigma=3.0, ncpus=0)

Run a parallelized version of utils.create_master_frame().

Use it only for big data set because it can be much slower for a small data set (< 500 x 500 x 10).

Parameters
  • frames – Frames to combine.

  • reject – (Optional) Rejection operation. Can be ‘sigclip’, ‘minmax’, ‘avsigclip’ (default ‘avsigclip’)

  • combine – (Optional) Combining operation. Can be ‘average’ or ‘median’ (default ‘average’)

  • sigma – (Optional) Sigma factor for pixel rejection (default 3.).

See also

utils.create_master_frame()

orb.utils.image.shift_frame(frame, dx, dy, x_min, x_max, y_min, y_max, order, fill_value=nan)

Return a shifted frame wit the same dimensions.

Parameters
  • frame – Two dimensions array to be shifted

  • dx – Shift value along the axis 0

  • dy – Shift value along the axis 1

  • x_max, y_min, y_max (x_min,) – Boundaries of the region to be shifted.

  • order – interpolation order.

  • (Optional) (fill_value) – Value of the extrapolated points (default np.nan).

Note

To avoid spline interpolation defects around stars use order 1 (linear interpolation).

orb.utils.image.simulate_calibration_laser_map(nx, ny, pixel_size, mirror_distance, theta_cx, theta_cy, phi_x, phi_y, phi_r, calib_laser_nm)

Simulate a calibration laser map from optical and mechanical parameters

Parameters
  • nx – Number of pixels along X

  • ny – Number of pixels along Y

  • pixel_size – Size of a pixel in microns

  • mirror_distance – Distance to the mirror in microns on the optical axis.

  • theta_cx – Angle from the optical axis to the mirror center in degrees along X axis (in degrees)

  • theta_cy – Angle from the optical axis to the mirror center in degrees along Y axis (in degrees)

  • phi_x – Tilt of the mirror along X in degrees

  • phi_y – Tilt of the mirror along Y in degrees

  • phi_r – Rotation angle of the camera in degrees

  • calib_laser_nm – Calibration laser wavelength in nm

orb.utils.image.simulate_theta_map(nx, ny, pixel_size, mirror_distance, theta_cx, theta_cy, phi_x, phi_y, phi_r)

Simulate incident angle (theta) map from optical and mechanical parameters

Parameters
  • nx – Number of pixels along X

  • ny – Number of pixels along Y

  • pixel_size – Size of a pixel in microns

  • mirror_distance – Distance to the mirror in microns on the optical axis.

  • theta_cx – Angle from the optical axis to the mirror center in degrees along X axis (in degrees)

  • theta_cy – Angle from the optical axis to the mirror center in degrees along Y axis (in degrees)

  • phi_x – Tilt of the mirror along X in degrees

  • phi_y – Tilt of the mirror along Y in degrees

  • phi_r – Rotation angle of the camera in degrees

orb.utils.image.smooth_map(pm, binning=20, smoothdeg=3)

Fast map smoothin.

orb.utils.image.tilt_calibration_laser_map(cmap, calib_laser_nm, phi_x, phi_y, phi_r)

Tilt and rotate a calibration laser map.

Parameters
  • cmap – calibration laser map.

  • calib_laser_nm – Calibration laser wavelength in nm.

  • phi_x – tilt angle along X axis (degrees).

  • phi_y – tilt angle along Y axis (degrees).

  • phi_r – Rotation angle (degrees).

orb.utils.image.transform_frame(frame, x_min, x_max, y_min, y_max, d, rc, zoom_factor, interp_order, mask=None, fill_value=nan, sip_A=None, sip_B=None)

Transform one frame or a part of it using transformation coefficients.

Parameters
  • frame – Frame to transform

  • x_min – Lower x boundary of the transformed section (can be a tuple in order to get multiple sections)

  • x_max – Upper x boundary of the transformed section (can be a tuple in order to get multiple sections)

  • y_min – Lower y boundary of the transformed section (can be a tuple in order to get multiple sections)

  • y_max – Upper y boundary of the transformed section (can be a tuple in order to get multiple sections)

  • d – Transformation coefficients [dx, dy, dr, da, db]

  • rc – Rotation center of the frame [rc_x, rc_y]

  • zoom_factor – Zoom on the image. Can be a couple (zx, zy).

  • interp_order – Interpolation order

  • mask – (Optional) If a mask frame is passed it is transformed also (default None).

  • fill_value – (Optional) Fill value for extrapolated points (default np.nan).

  • sip_A – (Optional) pywcs.WCS() instance containing SIP parameters of the output image (default None).

  • sip_B – (Optional) pywcs.WCS() instance containing SIP parameters of the input image (default None).

orb.utils.image.unwrap_phase_map0(phase_map, bin_size=20, line_size=30)

Phase is defined modulo pi. The Unwrapping is a reconstruction of the phase so that the distance between two neighbour pixels is always less than pi/2. 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.

Parameters

phase_map – Order 0 phase map.

orb.utils.io module

orb.utils.io.array2dict(data)

Convert an array read from an hdf5 file to a dict. :param data: array of params returned by dict2array

orb.utils.io.cast(a, t_str)
orb.utils.io.cast2hdf5(val)
orb.utils.io.cast_storing_dtype(arr)
orb.utils.io.dict2array(data)

Convert a dictionary to an array that can be written in an hdf5 file

Parameters

data – Must be a dict instance

orb.utils.io.dict2header(params)

convert a dict to a pyfits.Header() instance

Warning

this is a destructive process, illegal values are

removed from the header.

Parameters

params – a dict instance

orb.utils.io.get_hdu_data_index(hdul)

Return the index of the first header data unit (HDU) containing data.

Parameters

hdul – A pyfits.HDU instance

orb.utils.io.get_sitelle_slice(slice_str)

Strip a string containing SITELLE like slice coordinates.

Parameters

slice_str – Slice string.

orb.utils.io.get_storing_dtype(arr)
orb.utils.io.header_fits2hdf5(fits_header)

convert a pyfits.Header() instance to a header for an hdf5 file

Parameters

fits_header – Header of the FITS file

orb.utils.io.header_hdf52fits(hdf5_header)

convert an hdf5 header to a pyfits.Header() instance.

Parameters

hdf5_header – Header of the HDF5 file

orb.utils.io.load_dflist(path)

Save a list of dataframes

Parameters

path – path to the output file

orb.utils.io.open_file(file_name, mode='r')

Open a file in write mode (by default) and return a file object.

Create the file if it doesn’t exist (only in write mode).

Parameters
  • file_name – Path to the file, can be either relative or absolute.

  • mode – (Optional) Can be ‘w’ for write mode, ‘r’ for read mode and ‘a’ for append mode.

orb.utils.io.open_hdf5(file_path, mode)

Return a h5py.File instance with some informations.

Parameters
  • file_path – Path to the hdf5 file.

  • mode – Opening mode. Can be ‘r’, ‘r+’, ‘w’, ‘w-‘, ‘x’, ‘a’.

Note

Please refer to http://www.h5py.org/.

orb.utils.io.read_fits(fits_path, no_error=False, nan_filter=False, return_header=False, return_hdu_only=False, return_mask=False, silent=False, delete_after=False, data_index=None, image_mode='classic', chip_index=None, binning=None, fix_header=True, dtype=<class 'float'>, mask_path=None)

Read a FITS data file and returns its data.

Parameters
  • fits_path – Path to the file, can be either relative or absolut.

  • no_error – (Optional) If True this function will only display a warning message if the file does not exist (so it does not raise an exception) (default False)

  • nan_filter – (Optional) If True replace NaN by zeros (default False)

  • return_header – (Optional) If True return a tuple (data, header) (default False).

  • return_hdu_only – (Optional) If True return FITS header data unit only. No data will be returned (default False).

  • return_mask – (Optional) If True return only the mask corresponding to the data file (default False).

  • silent – (Optional) If True no message is displayed except if an error is raised (default False).

  • delete_after – (Optional) If True delete file after reading (default False).

  • data_index – (Optional) Index of data in the header data unit (Default None).

  • image_mode – (Optional) Can be ‘sitelle’, ‘spiomm’ or ‘classic’. In ‘sitelle’ mode, the parameter chip_index must also be set to 0 or 1. In this mode only one of both SITELLE quadrants is returned. In ‘classic’ mode the whole frame is returned (default ‘classic’).

  • chip_index – (Optional) Index of the chip of the SITELLE image. Used only if image_mode is set to ‘sitelle’ In this case, must be 1 or 2. Else must be None (default None).

  • binning – (Optional) If not None, returned data is binned by this amount (must be an integer >= 1)

  • fix_header – (Optional) If True, fits header is fixed to avoid errors due to header inconsistencies (e.g. WCS errors) (default True).

  • dtype – (Optional) Data is converted to the given dtype (e.g. np.float32, default float).

  • mask_path – (Optional) Path to the corresponding mask image.

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.

orb.utils.io.read_hdf5(file_path, return_header=False, dtype=<class 'float'>)

Read an HDF5 data file created with core.Tools.write_hdf5().

Parameters
  • file_path – Path to the file, can be either relative or absolute.

  • return_header – (Optional) If True return a tuple (data, header) (default False).

  • dtype – (Optional) Data is converted to the given type (e.g. np.float32, default float).

Note

Please refer to http://www.h5py.org/.

orb.utils.io.read_sitelle_chip(hdu, chip_index, substract_bias=True)

Return chip data of a SITELLE FITS image.

Parameters
  • hdu – pyfits.HDU Instance of the SITELLE image

  • chip_index – Index of the chip to read. Must be 1 or 2.

  • substract_bias – If True bias is automatically substracted by using the overscan area (default True).

orb.utils.io.read_spiomm_data(hdu, image_path, substract_bias=True)

Return data of an SpIOMM FITS image.

Parameters
  • hdu – pyfits.HDU Instance of the SpIOMM image

  • image_path – Image path

  • substract_bias – If True bias is automatically substracted by using the associated bias frame as an overscan frame. Mean bias level is thus computed along the y axis of the bias frame (default True).

orb.utils.io.read_votable(votable_file)

read a votable and transfer it as as pandas dataframe.

taken from https://gist.github.com/icshih/52ca49eb218a2d5b660ee4a653301b2b

orb.utils.io.save_dflist(dflist, path)

Save a list of dataframes

Parameters
  • dflist – list of pandas dataframes

  • path – path to the output file

orb.utils.io.save_starlist(path, starlist)

Save a star list as a two columnfile X, Y readable by ds9

orb.utils.io.write_fits(fits_path, fits_data, fits_header=None, silent=False, overwrite=True, mask=None, replace=False, record_stats=False, mask_path=None)

Write data in FITS format. If the file doesn’t exist create it with its directories.

If the file already exists add a number to its name before the extension (unless ‘overwrite’ option is set to True).

Parameters
  • fits_path – Path to the file, can be either relative or absolut.

  • fits_data – Data to be written in the file.

  • fits_header – (Optional) Optional keywords to update or create. It can be a pyfits.Header() instance or a list of tuples [(KEYWORD_1, VALUE_1, COMMENT_1), (KEYWORD_2, VALUE_2, COMMENT_2), …]. Standard keywords like SIMPLE, BITPIX, NAXIS, EXTEND does not have to be passed.

  • silent – (Optional) If True turn this function won’t display any message (default False)

  • overwrite – (Optional) If True overwrite the output file if it exists (default True).

  • mask – (Optional) It not None must be an array with the same size as the given data but filled with ones and zeros. Bad values (NaN or Inf) are converted to 1 and the array is converted to 8 bit unsigned integers (uint8). This array will be written to the disk with the same path terminated by ‘_mask’. The header of the mask FITS file will be the same as the original data (default None).

  • replace – (Optional) If True and if the file already exist, new data replace old data in the existing file. NaN values do not replace old values. Other values replace old values. New array MUST have the same size as the existing array. Note that if replace is True, overwrite is automatically set to True.

  • record_stats – (Optional) If True, record mean and median of data. Useful if they often have to be computed (default False).

  • mask_path – (Optional) Path to the corresponding mask image.

Note

float64 data is converted to float32 data to avoid too big files with unnecessary precision

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.

orb.utils.io.write_hdf5(file_path, data, header=None, silent=False, overwrite=True, max_hdu_check=True, compress=False)

Write data in HDF5 format.

A header can be added to the data. This method is useful to handle an HDF5 data file like a FITS file. It implements most of the functionality of the method core.Tools.write_fits().

Note

The output HDF5 file can contain mutiple data header units (HDU). Each HDU is in a specific group named ‘hdu*’, * being the index of the HDU. The first HDU is named HDU0. Each HDU contains one data group (HDU*/data) which contains a numpy.ndarray and one header group (HDU*/header). Each subgroup of a header group is a keyword and its associated value, comment and type.

Parameters
  • file_path – Path to the HDF5 file to create

  • data – A numpy array (numpy.ndarray instance) of numeric values. If a list of arrays is given, each array will be placed in a specific HDU. The header keyword must also be set to a list of headers of the same length.

  • header – (Optional) Optional keywords to update or create. It can be a pyfits.Header() instance or a list of tuples [(KEYWORD_1, VALUE_1, COMMENT_1), (KEYWORD_2, VALUE_2, COMMENT_2), …]. Standard keywords like SIMPLE, BITPIX, NAXIS, EXTEND does not have to be passed (default None). It can also be a list of headers if a list of arrays has been passed to the option ‘data’.

  • max_hdu_check – (Optional): When True, if the input data is a list (interpreted as a list of data unit), check if it’s length is not too long to make sure that the input list is not a single data array that has not been converted to a numpy.ndarray format. If the number of HDU to create is indeed very long this can be set to False (default True).

  • silent – (Optional) If True turn this function won’t display any message (default False)

  • overwrite – (Optional) If True overwrite the output file if it exists (default True).

  • compress – (Optional) If True data is compressed using the SZIP library (see https://www.hdfgroup.org/doc_resource/SZIP/). SZIP library must be installed (default False).

Note

Please refer to http://www.h5py.org/.

orb.utils.log module

orb.utils.log.print_caller_traceback(self)

Print the traceback of the calling function.

orb.utils.log.setup_socket_logging()

orb.utils.misc module

orb.utils.misc.aggregate_pixels(pixel_list, radius=1.42)

Aggregate neighbouring pixels into a set of sources. Two neighbours are found if there distance is smaller than a given radius (in pixels).

Parameters
  • pixel_list – A list of pixel position as returned by a function like numpy.nonzero.

  • radius – (Optional) Max separation between two pixels of the same source (default 1.42).

Returns

A list of pixel list. Each item of the list corresponds to a source and each source is itself a list of pixel positions (x,y).

orb.utils.misc.compute_obs_params(nm_min_filter, nm_max_filter, theta_min=5.01, theta_max=11.28)

Compute observation parameters (order, step size) given the filter bandpass.

Parameters
  • nm_min_filter – Min wavelength of the filter in nm.

  • nm_max_filter – Max wavelength of the filter in nm.

  • theta_min – (Optional) Min angle of the detector (default 5.01).

  • theta_max – (Optional) Max angle of the detector (default 11.28).

Returns

A tuple (order, step size, max wavelength)

orb.utils.misc.convert_camera_parameter(param)

Convert camera parameter to an integer value

orb.utils.misc.correct_bad_frames_vector(bad_frames_vector, dimz)

Remove bad indexes of the bad frame vector.

Parameters
  • bad_frames_vector – The vector of indexes to correct

  • dimz – Dimension of the cube along the 3rd axis.

orb.utils.misc.find(pattern, path)

Find a file from a pattern at a given path https://stackoverflow.com/questions/1724693/find-a-file-in-python

orb.utils.misc.get_axis_from_hdr(hdr, axis_index=1)

Return axis from a classic FITS header

Parameters
  • hdr – FITS header

  • axis_index – (Optional) Index of the axis to retrieve (default 1)

orb.utils.misc.get_cfht_odometer(path)

Return the odometer of a cfht FITS file from its path.

orb.utils.misc.get_mask_from_ds9_region_file(reg_path, x_range, y_range, integrate=True, header=None)

Return a mask from a ds9 region file or from a ds9-like region string.

Parameters
  • reg_path – Path to a ds9 region file or ds9-like region string

  • x_range – Range of x image coordinates considered as valid. Pixels outside this range are rejected..

  • y_range – Range of y image coordinates considered as valid. Pixels outside this range are rejected.

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

  • header – (Optional) Header containing the WCS transformation if the region file is in celestial coordinates (default None).

Note

The returned array can be used like a list of indices returned by e.g. numpy.nonzero().

Note

Coordinates can be celestial or image coordinates (x,y). if coordinates are celestial a header must be passed to the function.

orb.utils.misc.read_instrument_value_from_file(path)

Read the instrument value form an hdf5/fits file

Parameters

path – path to an hdf5/fits file.

orb.utils.misc.restore_error_settings(old_settings)

Restore old floating point error settings of numpy.

orb.utils.misc.sort_image_list(file_list, image_mode, cube=True)

Sort a list of fits files.

Parameters
  • file_list – A list of file names

  • image_mode – Image mode, can be ‘sitelle’ or ‘spiomm’.

  • cube – If True, image list is considered as a cube list. Headers are used to get the right order based on step number instead of file path (default True).

orb.utils.parallel module

class orb.utils.parallel.Job(job, timeout)

Bases: object

class orb.utils.parallel.JobServer(ncpus, timeout=1000, spawn=False)

Bases: object

submit(func, args=(), modules=())
class orb.utils.parallel.RayJob(job)

Bases: object

class orb.utils.parallel.RayJobServer

Bases: object

submit(func, args=(), modules=())
orb.utils.parallel.apply_async(pool, fun, args)
orb.utils.parallel.close_pp_server(js, silent=False)

Destroy the parallel python job server to avoid too much opened files.

Parameters

js – job server.

Note

Please refer to http://www.parallelpython.com/ for sources and information on Parallel Python software.

orb.utils.parallel.get_ncpus(ncpus)

Return ncpus considering the target ncpus and the hard limits setting

orb.utils.parallel.get_stats_str(js)

Return job server statistics as a string

orb.utils.parallel.init_pp_server(ncpus=0, silent=False, use_ray=False, timeout=1000)

Initialize a server for parallel processing.

Parameters
  • ncpus – (Optional) Number of cpus to use. 0 means use all available cpus (default 0)

  • silent – (Optional) If silent no message is printed (Default False).

Note

Please refer to http://www.parallelpython.com/ for sources and information on Parallel Python software

orb.utils.parallel.run_dill_encoded(payload)
orb.utils.parallel.timed_process(func, timeout, args=[])

Run a timed process which terminates after timeout seconds if it does not return before.

Parameters
  • func – Timed func which will be terminated after timeout seconds. must be func(*args, returned_dict). The results of the function must be put in returned_dict.

  • timeout – Timeout in s.

  • args – arguments of the function

Returns

returned_dict

orb.utils.photometry module

orb.utils.photometry.ABmag2flambda(ABmag, lam)

Convert AB magnitude to flux in erg/cm2/s/A

Parameters
  • ABmag – A magnitude in the AB magnitude system

  • lam – Wavelength in angstrom

orb.utils.photometry.ABmag2fnu(ABmag)

Return flux in erg/cm2/s/Hz from AB magnitude (Oke, ApJS, 27, 21, 1974)

ABmag = -2.5 * log10(f_nu) - 48.60 f_nu = 10^(-0.4 * (ABmag + 48.60))

Parameters

ABmag – A magnitude in the AB magnitude system

Note

Definition of the zero-point can change and be e.g. 48.59 for Oke standard stars (Hamuy et al., PASP, 104, 533, 1992). This is the case for Spectrophotometric Standards given on the ESO website (https://www.eso.org/sci/observing/tools/standards/spectra/okestandards.html). Here the HST definition is used.

orb.utils.photometry.compute_equivalent_bandwidth(nm_axis, filter_transmission)

Return the equivalent bandwidth of a given filter.

Parameters
  • nm_axis – Filter transmission axis in nm.

  • filter_transmission – Filter transmission curve

orb.utils.photometry.compute_flux_calibration_vector(re_spectrum, th_spectrum, std_step, std_order, std_exp_time, std_corr, filter_min_pix, filter_max_pix)

Compute the flux calibration vector from an observed spectrum and the standard spectrum.

Parameters
  • re_spectrum – Observed spectrum in wavenumber.

  • th_spectrum – standard spectrum (in erg/cm2/s/A) in wavenumber.

  • std_step – Standard step size (in nm)

  • std_order – Standard folding order

  • std_exp_time – Standard Exposition time

  • std_corr – Standard Correction coeff.

  • filter_min_pix – Filter min position in pixels

  • filter_max_pix – Filter max position in pixels

orb.utils.photometry.compute_mean_photon_energy(nm_axis, filter_transmission)

Return mean energy of the photons passing thourgh a given filter (in erg).

Parameters
  • nm_axis – Filter transmission axis in nm.

  • filter_transmission – Filter transmission curve

orb.utils.photometry.compute_mean_star_flux(star_spectrum, filter_transmission)

Return mean star flux given a spectrum and the filter. Both files must be given along the same wavelength/wavenumber axis.

Parameters
  • star_spectrum – Spectrum of the star

  • filter_transmission – Filter transmission curve

orb.utils.photometry.compute_optimal_texp(star_flux, seeing, plate_scale, saturation=30000)

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

Parameters
  • star_flux – Total star flux in ADU/s

  • seeing – Star FWHM in arcsec

  • plate_scale – Size of 1 pixel in arcsec.

  • saturation – (Optional) Saturation value (default 30000).

orb.utils.photometry.compute_photon_energy(nm_axis)

Return the photon energy (in erg) computed for all the wavelength along a given wavelength axis.

Parameters

nm_axis – Wavelength axis in nm

orb.utils.photometry.compute_star_central_pixel_value(seeing, plate_scale)

Return the relative value of the pixel containing the greatest proportion of the flux (central pixel) of Gaussian star.

Parameters
  • seeing – Star FWHM in arcsec

  • plate_scale – Size of the pixels in arcsec.

orb.utils.photometry.convert_cm1_flux2fluxdensity(a, cm1_axis)

Convert a spectrum in X/s to X/s/A (X may be ADU or erg/cm^2)

Parameters
  • a – spectrum

  • cm1_axis – Axis of the spectrum in cm-1

orb.utils.photometry.ext2trans(ext, airmass)

Convert extinction to transmission

Parameters
  • ext – extinction

  • airmass – airmass

orb.utils.photometry.fit_std_spectrum(real_spectrum, std_spectrum, polydeg=2)

Fit a real spectrum multiplied by a polynomial over a standard spectrum.

Return the polynomial which can be used directly as a calibration curve.

Parameters
  • real_spectrum – Observed spectrum

  • std_spectrum – Standard spectrum

  • polydeg – Degree of the polynomial

orb.utils.photometry.flambda2ABmag(flambda, lam)

Return AB magnitude from flux in erg/cm2/s/A

Parameters
  • flambda – Flux in erg/cm2/s/A. Can be an array.

  • lambda – Wavelength in A of the Flux. If flambda is an array lambda must have the same shape.

orb.utils.photometry.fnu2flambda(fnu, nu)

Convert a flux in erg/cm2/s/Hz to a flux in erg/cm2/s/A

Parameters
  • fnu – Flux in erg/cm2/s/Hz

  • nu – frequency in Hz

orb.utils.photometry.lambda2nu(lam)

Convert lambda in Ang to nu in Hz

Parameters

lam – Wavelength in angstrom

orb.utils.photometry.modulation_efficiency_opd_jitter(cm1, opd_jitter)

Return the ME given the OPD jitter

Parameters
  • cm1 – wavenumber in cm-1

  • opd_jitter – OPD jitter in nm (standard deviation)

orb.utils.photometry.modulation_efficiency_wavefront_error(cm1, wferr)

Return the ME given the OPD jitter

Parameters
  • cm1 – wavenumber in cm-1

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

orb.utils.sim module

orb.utils.sim.fft(interf, zp_coeff=2, apod=None, phase=None)

Basic Fourier Transform with zero-padding.

Useful to compute a quick assumption-less FFT.

ZPD is assumed to be on the first sample of the interferogram

Parameters
  • interf – interferogram

  • zp_coeff – Zero-padding coefficient (2 by default)

  • apod – Apodization function

Returns

axis, complex interferogram FFT

orb.utils.sim.line_interf(sigma, step_nb, phi=0, symm=False, jitter=0.0)

Simulate a simple line interferogram (a cosine)

ZPD is on the first sample of the returned interferogram.

Parameters
  • sigma – line frequency (must be < step_nb/2)

  • step_nb – Length of the interferogram

  • phi – (Optional) Phase of the line (in radians) (default 0).

  • symm – (Optional) If True, returned spectrum is symmetric, it has two times more steps - 1. Zpd position is equal to step_nb - 0.5.

  • jitter – (Optional) Std of an OPD jitter. Must be a float between 0 and 1 (jitter distribution is normal, default 0.).

orb.utils.sim.step_interf(sigma_min, sigma_max, step_nb, symm=False)

Simulate a step interferogram

ZPD is on the first sample of the returned interferogram.

Parameters
  • sigma_ax – max frequency of the step (must be < step_nb/2)

  • step_nb – Length of the interferogram

  • symm – (Optional) If True, returned spectrum is symmetric, it has two times more steps - 1. Zpd position is equal to step_nb - 0.5.

Note

results are much better with a symmetric interferogram but ZPD is not on the first sample and the spectrum must thus be phase corrected.

orb.utils.spectrum module

orb.utils.spectrum.amp_ratio_from_flux_ratio(line0_cm1, line1_cm1, flux_ratio)
Return the amplitude ratio (amp(line0) / amp(line1)) from the flux

ratio (at constant fwhm and broadening).

Parameters
  • line0 – Wavenumber of the line 0 (in cm-1).

  • line1 – Wavenumber of the line 1 (in cm-1).

  • flux_ratio – Flux ratio: flux(line0) / flux(line1).

orb.utils.spectrum.cm12nm(cm1)

Convert a wavenumber in cm-1 to a wavelength in nm.

Parameters

cm1 – wavenumber in cm-1

orb.utils.spectrum.cm12pix(cm1_axis, cm1)

Convert a wavenumber in cm-1 to a pixel position given an axis in cm-1.

Parameters
  • cm1_axis – Axis in cm-1

  • cm1 – Wavenumber in cm-1

orb.utils.spectrum.compute_line_fwhm(step_nb, step, order, apod_coeff=1.0, corr=1.0, wavenumber=False)

Return the expected FWHM (in nm or in cm-1) of a line given the observation parameters.

Parameters
  • step_nb – Number of steps from the zpd to the longest side of the interferogram.

  • step – Step size in nm

  • order – Folding order

  • apod_coeff – (Optional) Apodization coefficient. 1. stands for no apodization and gives the FWHM of the central lobe of the sinc (default 1.)

  • corr – (Optional) Coefficient of correction (default 1.)

  • wavenumber – (Optional) If True the result is returned in cm-1, else it is returned in nm.

orb.utils.spectrum.compute_line_fwhm_pix(oversampling_ratio=1.0)

Return the expected FWHM of an unapodized sinc line in pixels.

Oversampling_ratio

Ratio of the real number of steps of the spectrum vs step_nb (must be > 1.) For a two sided interferogram the oversampling ratio is 2.

orb.utils.spectrum.compute_mean_shift(velocity, step_nb, step, order, wavenumber=False)

Return the mean shift at the central wavelength of the band defined by step and order parameters given its velocity in nm or in cm-1.

Parameters
  • velocity – Line velocity in km.s-1

  • step_nb – Number of steps

  • step – Step size in nm

  • order – Folding order

  • wavenumber – (Optional) If True the result is returned in cm-1, else it is returned in nm.

orb.utils.spectrum.compute_radial_velocity(line, rest_line, wavenumber=False, relativistic=True)

Return relativistic radial velocity in km.s-1

V [km.s-1] = c [km.s-1]* (Lambda^2 / Lambda_0^2 - 1) / (Lambda^2 / Lambda_0^2 + 1)

Parameters
  • line – Emission line wavelength/wavenumber (can be a numpy array)

  • rest_line – Rest-frame wavelength/wavenumber (can be a numpy array but must have the same size as line)

  • wavenumber – (Optional) If True the result is returned in cm-1, else it is returned in nm.

orb.utils.spectrum.compute_resolution(step_nb, step, order, corr=1, sigma=None)

Return the theoretical resolution of a given scan

Parameters
  • step_nb – Number of steps of the longest side of the interferogram.

  • step – Step size (in nm)

  • order – Folding order

  • corr – Correction coefficient for the incident angle.

  • sigma – Wavenumber at which the resolution is computed. If None given, the central wavenumber in the bandpass is used. Note that, when the incident angle changes, the bandpass is shifted so that the computed resolution is the same at any inceident angle if sigma is not fixed.

orb.utils.spectrum.compute_step_nb(resolution, step, order)

Return the number of steps on the longest side of the interferogram given the resolution and the observation parameters.

Parameters
  • resolution – Resolution

  • step – Step size (in nm)

  • order – Folding order

orb.utils.spectrum.corr2theta(corr)

Convert the correction coefficient to an incident angle.

Parameters

corr – Correction coefficient

orb.utils.spectrum.create_cm1_axis(n, step, order, corr=1.0)

Create a regular wavenumber axis in cm-1.

Parameters
  • n – Number of steps on the axis

  • step – Step size in nm

  • order – Folding order

  • corr – (Optional) Coefficient of correction (default 1.)

orb.utils.spectrum.create_nm_axis(n, step, order, corr=1.0)

Create a regular wavelength axis in nm.

Parameters
  • n – Number of steps on the axis

  • step – Step size in nm

  • order – Folding order (cannot be 0)

  • corr – (Optional) Coefficient of correction (default 1.)

orb.utils.spectrum.create_nm_axis_ireg(n, step, order, corr=1.0)

Create an irregular wavelength axis from the regular wavenumber axis in cm-1.

Parameters
  • n – Number of steps on the axis

  • step – Step size in nm

  • order – Folding order (must be > 0)

  • corr – (Optional) Coefficient of correction (default 1.)

orb.utils.spectrum.detect_velocity(spec, axis_cm1, lines_cm1, ncomps=1, vrange=1000)

Detect velocity of different components in a spectrum.

Parameters

ncomps – maximum velocity components

orb.utils.spectrum.dsinc1d(x, h, a, dx, fwhm, sigma)

Return a 1D double sinc

Parameters
  • x – Array giving the positions where the function is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM

  • sigma – broadening

orb.utils.spectrum.fast_pix2w(pix, axis_min, axis_step)

Fast conversion of pixel to wavelength/wavenumber

Parameters
  • pix – position along axis in pixels

  • axis_min – min axis wavelength/wavenumber

  • axis_step – axis step size in wavelength/wavenumber

orb.utils.spectrum.fast_w2pix(w, axis_min, axis_step)

Fast conversion of wavelength/wavenumber to pixel

Parameters
  • w – wavelength/wavenumber

  • axis_min – min axis wavelength/wavenumber

  • axis_step – axis step size in wavelength/wavenumber

orb.utils.spectrum.fwhm_cm12nm(fwhm_cm1, cm1)

Convert a FWHM in cm-1 to a FWHM in nm.

The central wavelength in cm-1 of the line must also be given

Parameters
  • fwhm_cm1 – FWHM in cm-1

  • cm1 – Wavelength in cm-1 where the FWHM is evaluated

orb.utils.spectrum.fwhm_nm2cm1(fwhm_nm, nm)

Convert a FWHM in nm to a FWHM in cm-1.

The central wavelength in nm of the line must also be given

Parameters
  • fwhm_nm – FWHM in nm

  • nm – Wavelength in nm where the FWHM is evaluated

orb.utils.spectrum.gaussian1d(x, h, a, dx, fwhm)

Return a 1D gaussian given a set of parameters.

Parameters
  • x – Array giving the positions where the gaussian is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM, \(\text{FWHM} = \text{Width} \times 2 \sqrt{2 \ln 2}\)

orb.utils.spectrum.gaussian1d_complex(x, h, a, dx, fwhm)

Return a 1D gaussian given a set of parameters.

Parameters
  • x – Array giving the positions where the gaussian is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM, \(\text{FWHM} = \text{Width} \times 2 \sqrt{2 \ln 2}\)

orb.utils.spectrum.gaussian1d_flux(a, fwhm)

Compute flux of a 1D Gaussian.

Parameters
  • a – Amplitude

  • fwhm – FWHM

orb.utils.spectrum.guess_snr(calib_spectrum, flambda, exp_time)

Guess calibrated spectrum snr

Parameters
  • calib_spectrum – Calibrated spectrum

  • flambda – Calibration FLAMBDA

  • exp_time – Exposure time by step

orb.utils.spectrum.line_shift(velocity, line, wavenumber=False, relativistic=True)

Return the line shift (in nm or in cm-1) given its relativistic velocity

beta = v / c

gamma = sqrt((1 + beta) / (1 - beta))

lambda - lambda_0 = lambda_0 * (gamma - 1)

Parameters
  • velocity – Line velocity in km.s-1

  • line – Wavelength/wavenumber of the line. Must be in cm-1 if wavenumber is True, must be in nm otherwise.

  • wavenumber – (Optional) If True the result is returned in cm-1, else it is returned in nm.

orb.utils.spectrum.lorentzian1d(x, h, a, dx, fwhm)

Return a 1D lorentzian :param x: Array giving the positions where the function is evaluated :param h: Height :param a: Amplitude :param dx: Position of the center :param fwhm: FWHM

orb.utils.spectrum.mertz1d(x, h, a, dx, fwhm, ratio)

Complex ILS when Mertz ramp is used during the Fourier transform.

Parameters
  • x – 1D array of float64 giving the positions where the function is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM of the sinc

  • ratio – Ratio of the shortest side over the longest side of the interferogram

orb.utils.spectrum.nm2cm1(nm)

Convert a wavelength in nm to a wavenumber in cm-1.

Parameters

nm – wavelength in nm

orb.utils.spectrum.nm2pix(nm_axis, nm)

Convert a wavelength in nm to a pixel position given an axis in nm

Warning

Slow because of interpolation : using fast_w2pix is much faster.

Parameters
  • nm_axis – Axis in nm

  • nm – Wavelength in nm

orb.utils.spectrum.phase_shift_cm1_axis(step_nb, step, order, nm_laser_obs, nm_laser)

Compute phase shift on a given cm1 axis

Parameters
  • step_nb – Number of steps

  • step – Step size in nm

  • order – Folding order

  • nm_laser_obs – Observed calibration laser wavelength (in nm)

  • nm_laser – Calibration laser wavelength (in nm)

orb.utils.spectrum.pix2cm1(cm1_axis, pix)

Convert a wavenumber in cm-1 to a pixel position given an axis in cm-1.

Parameters
  • cm1_axis – Axis in cm-1

  • pix – Pixel position

orb.utils.spectrum.pix2nm(nm_axis, pix)

Convert a pixel position to a wavelength in nm given an axis in nm

Warning

Slow because of interpolation : using fast_pix2w is much faster.

Parameters
  • nm_axis – Axis in nm

  • pix – Pixel position

orb.utils.spectrum.sinc1d(x, h, a, dx, fwhm)

Return a 1D sinc :param x: Array giving the positions where the function is evaluated :param h: Height :param a: Amplitude :param dx: Position of the center :param fwhm: FWHM

orb.utils.spectrum.sinc1d_complex(x, h, a, dx, fwhm)

The “complex” version of the sinc (understood as the Fourier Transform of a boxcar function from 0 to MPD).

This is the real sinc function when ones wants to fit both the real part and the imaginary part of the spectrum.

Parameters
  • x – 1D array of float64 giving the positions where the function is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM of the sinc

orb.utils.spectrum.sinc1d_flux(a, fwhm)

Compute flux of a 1D sinc.

Parameters
  • a – Amplitude

  • fwhm – FWHM

orb.utils.spectrum.sinc1d_phased(x, h, a, dx, fwhm, alpha)

The phased version of the sinc function when that can be used to fit a spectrum with a non perfect correction of the order 0 of the phase.

Parameters
  • x – 1D array of float64 giving the positions where the function is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM of the sinc

  • alpha – Mixing coefficient (in radians).

orb.utils.spectrum.sinc21d_flux(a, fwhm)

Compute flux of a 1D sinc2. THIS IS BOGUS WITH CURRENT DEFINITION OF SINC2 MODEL :param a: Amplitude :param fwhm: FWHM

orb.utils.spectrum.sincgauss1d(x, h, a, dx, fwhm, sigma)

Return a 1D sinc convoluted with a gaussian of parameter sigma.

If sigma == 0 returns a pure sinc.

Parameters

x – 1D array of float64 giving the positions where the

sinc is evaluated

Parameters
  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM of the sinc

  • sigma – Sigma of the gaussian.

orb.utils.spectrum.sincgauss1d_complex(x, h, a, dx, fwhm, sigma)

The “complex” version of the sincgauss (dawson definition).

This is the real sinc*gauss function when ones wants to fit both the real part and the imaginary part of the spectrum.

Parameters
  • x – 1D array of float64 giving the positions where the function is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM of the sinc

  • sigma – Sigma of the gaussian.

orb.utils.spectrum.sincgauss1d_complex_erf(x, h, a, dx, fwhm, sigma)

The “complex” version of the sincgauss (erf formulation).

This is the real sinc*gauss function when ones wants to fit both the real part and the imaginary part of the spectrum.

Parameters
  • x – 1D array of float64 giving the positions where the function is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM of the sinc

  • sigma – Sigma of the gaussian.

orb.utils.spectrum.sincgauss1d_flux(a, fwhm, sigma)

Compute flux of a 1D sinc convoluted with a Gaussian of parameter sigma.

Parameters
  • a – Amplitude

  • fwhm – FWHM of the sinc

  • sigma – Sigma of the gaussian

  • no_err – (Optional) No error is returned (default False)

orb.utils.spectrum.sincgauss1d_phased(x, h, a, dx, fwhm, sigma, alpha)

The phased version of the sinc*gauss function when that can be used to fit a spectrum with a non perfect correction of the order 0 of the phase.

Parameters
  • x – 1D array of float64 giving the positions where the function is evaluated

  • h – Height

  • a – Amplitude

  • dx – Position of the center

  • fwhm – FWHM of the sinc

  • sigma – Sigma of the gaussian.

  • alpha – Mixing coefficient (in radians).

orb.utils.spectrum.thermal_broadening_kms(wl, aw, T)

Return the width of the line due to thermal broadening in km/s.

Equation can be refered to Harwit (Astrophysical concepts) but his definition gives the HWHM (Half-Width at Half-Maximum).

Parameters
  • wl – Wavelength of the line (in nm)

  • aw – Atomic weight of the emitting atom

  • T – Temperature in K

orb.utils.spectrum.theta2corr(theta)

Convert the incident angle to a correction coefficient.

Parameters

theta – Incident angle in degrees

orb.utils.spectrum.velocity_classic2relativistic(vel)

Convert a classic velocity to a relativistic velocity

Parameters

vel – Classic velocity in km/s

orb.utils.spectrum.velocity_relativistic2classic(vel)

Convert a relativistic velocity to a classic velocity

Parameters

vel – Relativistic velocity in km/s

orb.utils.stats module

orb.utils.stats.robust_mean(a, weights=None, warn=True)

Compute the mean of a distribution even with NaN values

This is based on bottleneck module. See: https://pypi.python.org/pypi/Bottleneck

Parameters
  • a – A distribution of values

  • weights – Weights of each value of a (Must have the same length as a). If None, weights are all considered equal to 1 (default None).

  • warn – If True, warnings are raised.

orb.utils.stats.robust_median(a, warn=True)

Compute the median of a distribution (skip NaN values).

This is based on bottleneck module. See: https://pypi.python.org/pypi/Bottleneck

Parameters
  • a – A distribution of values

  • warn – If True, warnings are raised.

orb.utils.stats.robust_modulo(_dat, mod)

Return an array modulo mod.

Returned values have the smallest possible absolute value. e.g. -1.1 % 1 = -0.1, -0.6 % 1 = 0.4. This is perfect to compute the residual of a phase fit (which is known modulo pi)

This is robust to NaN and fast.

orb.utils.stats.robust_std(a, warn=True)

Compute the std of a distribution even with NaN values

This is based on bottleneck module. See: https://pypi.python.org/pypi/Bottleneck

Parameters
  • a – A distribution of values

  • warn – If True, warnings are raised.

orb.utils.stats.robust_sum(a, warn=True)

Compute the sum of a distribution (skip NaN values)

This is based on bottleneck module. See: https://pypi.python.org/pypi/Bottleneck

Parameters
  • a – A distribution of values

  • warn – If True, warnings are raised.

orb.utils.stats.sigmacut(x, sigma=3.0, min_values=3, central_value=None, warn=False, return_index_list=False)

Return a distribution after a sigma cut rejection of the too deviant values.

Parameters
  • x – The distribution to cut

  • sigma – (Optional) Number of sigma above which values are considered as deviant (default 3.)

  • min_values – (Optional) Minimum number of values to return (default 3)

  • central_value – (Optional) If not none, this value is used as the central value of the cut. Else the median of the distribution is used as the central value (default None)

  • warn – (Optional) If False no warning message is printed (default False).

  • return_index_list – (Optional) If True the list of the non rejected values is returned also (default False).

orb.utils.stats.unbiased_mean(a, perc=16)

Return an unbiased measure of the mean.

Robust to outliers, but the underlying distribution must be Normal-ish between the choosen percentile limit.

orb.utils.stats.unbiased_std(a)

Return the std based on the interquartile range.

Robust to outliers, but the underlying distribution must be Normal-ish

https://en.wikipedia.org/wiki/Robust_measures_of_scale

orb.utils.validate module

orb.utils.validate.has_dtype(obj, dtype, raise_exception=True, object_name='object')

Check if object is a numpy.ndarray of the correct type :param obj: object to validate :param dtype: array dtype :param raise_exception: If True raise an exception else raise a debug.

orb.utils.validate.has_len(obj, length, raise_exception=True, object_name='object')

Check if object is 1d and if its length is correct :param obj: Object to check :param raise_exception: If True raise an exception else raise a debug. :param length: length of the object

orb.utils.validate.have_same_shape(objs, raise_exception=True, object_name='arrays')

Check if all numpy.ndarrays have the same shape :param obj: list of objects to validate :param raise_exception: If True raise an exception else raise a debug.

orb.utils.validate.index(a, a_min, a_max, clip=True)

Return a valid index (clipped between a_min and a_max - 1) or raise an exception.

Parameters
  • a – index. Can be a list or an array of indexes.

  • a_min – Min index.

  • a_max – Max index (max possible index will be considered as a_max -1)

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

orb.utils.validate.is_1darray(obj, raise_exception=True, object_name='object')

Check if object is a 1d numpy.ndarray :param obj: object to validate :param raise_exception: If True raise an exception else raise a debug.

orb.utils.validate.is_2darray(obj, raise_exception=True, object_name='object')

Check if object is a 2d numpy.ndarray :param obj: object to validate :param raise_exception: If True raise an exception else raise a debug.

orb.utils.validate.is_3darray(obj, raise_exception=True, object_name='object')

Check if object is a 3d numpy.ndarray :param obj: object to validate :param raise_exception: If True raise an exception else raise a debug.

orb.utils.validate.is_iterable(obj, raise_exception=True, object_name='object')

check if object is a tuple or a list or a 1darray

Parameters
  • obj – Object to check

  • raise_exception – If True raise an exception else raise a debug.

orb.utils.validate.is_ndarray(obj, raise_exception=True, object_name='object')

Check if object is a numpy.ndarray :param obj: object to validate :param raise_exception: If True raise an exception else raise a debug.

orb.utils.validate.is_xdarray(obj, ndim, raise_exception=True, object_name='object')

Check if object is a numpy.ndarray with the correct number of dimensions

Parameters
  • obj – object to validate

  • ndim – number of dimensions

  • raise_exception – If True raise an exception else raise a debug.

orb.utils.vector module

orb.utils.vector.complex2float(a)
orb.utils.vector.correct_vector(vector, bad_value=nan, deg=3, polyfit=False, smoothing=True)

Correct a given vector for non valid values by interpolation or polynomial fit.

Parameters
  • vector – The vector to be corrected.

  • bad_value – (Optional) Bad value to correct (default np.nan)

  • deg – (Optional) Spline degree or polyfit degree (default 3)

  • polyfit – (Optional) If True non valid values are guessed using a polynomial fit to the data instead of an spline interpolation (default False)

orb.utils.vector.fft_filter(a, cutoff_coeff, width_coeff=0.2, filter_type='high_pass')

Simple lowpass or highpass FFT filter (high pass or low pass)

Filter shape is a gaussian.

Parameters
  • a – Vector to filter

  • cutoff_coeff – Coefficient defining the position of the cut frequency (Cut frequency = cut_coeff * vector length)

  • width_coeff – (Optional) Coefficient defining the width of the smoothed part of the filter (width = width_coeff * vector length) (default 0.2)

  • filter_type – (Optional) Type of filter to use. Can be ‘high_pass’ or ‘low_pass’.

orb.utils.vector.float2complex(a)
orb.utils.vector.interpolate_axis(a, new_axis, deg, old_axis=None, fill_value=nan)

Interpolate a vector along a new axis.

Parameters
  • a – vector to interpolate

  • new_axis – Interpolation axis

  • deg – Interpolation degree

  • old_axis – (Optional) Original vector axis. If None, a regular range axis is assumed (default None).

  • fill_value – (Optional) extrapolated points are filled with this value (default np.nan)

orb.utils.vector.interpolate_size(a, size, deg)

Change size of a vector by interpolation

Parameters
  • a – vector to interpolate

  • size – New size of the vector

  • deg – Interpolation degree

orb.utils.vector.polyfit1d(a, deg, w=None, return_coeffs=False)

Fit a polynomial to a 1D vector.

Parameters
  • a – Vector to fit

  • deg – Fit degree

  • return_coeffs – (Optional) If True return fit coefficients as returned by numpy.polynomial.polynomial.polyfit() (default False).

  • w – (Optional) If not None, weights to apply to the fit. Must have the same shape as the vector to fit (default None)

orb.utils.vector.robust_unwrap(vec, dis)

Unwrap a vector with a given discontinuity. Robust to nans.

Note that the returned vector will start somewhere around 0 since all modulo bias is removed.

Parameters
  • vec – 1d Vector to unwrap.

  • dis – discontinuity (eg. np.pi)

orb.utils.vector.smooth(a, deg=2, kind='gaussian', keep_sides=True)

Smooth a given vector.

Parameters
  • a – Vector to smooth

  • deg – (Optional) Smoothing degree (or kernel radius) Must be an integer (default 2).

  • kind – Kind of smoothing function. ‘median’ or ‘mean’ are self-explanatory. ‘gaussian’ uses a gaussian function for a weighted average. ‘gaussian_conv’ and ‘cos_conv’ make use of convolution with a gaussian kernel or a cosine kernel. Convolution is much faster but less rigorous on the edges of the vector (default ‘gaussian’).

Params keep_sides

If True, the vector is seen as keeping its side values above its real boudaries (If False, the values outside the vector are 0. and this creates an undesirable border effect when convolving).

orb.utils.web module

class orb.utils.web.Catalog(name, out, sort)

Bases: object

orb.utils.web.query_sesame(object_name, verbose=True, degree=False, pm=False)

Query the SESAME Database to get RA/DEC given the name of an object.

Parameters
  • object_name – Name of the object

  • verbose – (Optional) If True print messages (default True)

  • degree – (Optional) If True return RA DEC in degrees (default False)

  • pm – (Optional) If True proper motion is also returned (default False) (mu_ra*cos(dec), mu_dec)

Returns

[RA, DEC]

orb.utils.web.query_vizier(radius, target_ra, target_dec, catalog='gaia', max_stars=100, return_all_columns=False, 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)

Note that the idea of this method has been picked from an IDL function: QUERYVIZIER (http://idlastro.gsfc.nasa.gov/ftp/pro/sockets/queryvizier.pro)

Parameters
  • radius – Radius around the target in arc-minutes.

  • target_ra – Target RA in degrees

  • target_dec – Target DEC in degrees

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

  • catalog – (Optional) can be ‘usno’ - Version B1 of the US Naval Observatory catalog (2003), ‘gaia’ - GAIA DR1, or ‘2mass’ - 2MASS (default Gaia)

  • return_all_columns – (Optional) If True, return all columns. Else only ra, dec and Mag are returned (default False).

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