LineStacker

main

LineStacker Module:

Main Stacker module. Contains all basic functions.

class LineStacker.Coord(x, y, z=0, obsSpecArg=0, weight=1, image=0)

Describes a stacking position on an image.

Class used internally to represent coordinates. May describe a physical coordinate or a pixel coordinate.

Init: Creates a coordinate. A pixel coordinate should always specify to which image it belongs. Physical coordinates should be in J2000 radians.

Parameters:
  • x – x coordinate of stacking target
  • y – y coordinate of stacking target
  • z – redshift of stacking target
  • obsSpecArg – argument of spectral bin on which to center the stack, will be computed from z and fEm if not specified
  • weight – Weight of the. source in case of mean stacking. Default is 1.
  • image – Index of the image associated to the source. Automatically set with LineStacker.readCoords.
class LineStacker.CoordList(imagenames=[], coord_type='physical', unit='rad')

Extended list to contain list of coordinates.

Requires an image list in case of pixel coordinates to work properly.

Parameters:
  • imagenames – A list of image names, requiered for pixle coordinates to work properly.
  • coord_type‘physical’ or ‘pixel’. ‘physical’ coordinates should be converted to pixels using LineStacker.getPixelCoords before stacking.
  • unit – can be ‘rad’, ‘deg’ or ‘pix’.
LineStacker.getPixelCoords(coords, imagenames)

Creates pixel coordinate list from a physical coordinate list and a list of images.

Parameters:
  • coords – A list of stacker.Coord coordinates.
  • imagenames – A list of images’ paths.
LineStacker.randomCoords(imagenames, ncoords=10)

Randomize a set of coordinates anywhere on any images.

Parameters:
  • imagenames – A list of images paths.
  • ncoords – Number of random coordinates. Default is 10.
LineStacker.randomizeCoords(coords, beam, maxBeamRange=5)

Randomize a new set of coordinates at a distance [beam, maxBeamRange*beam] of the original coordinates

Parameters:
  • coords – list of original coordinates (stacker.Coord instances)
  • beam – beam size is radians, new random coordinates will be at a minimum distance beam from the original coordinates.
  • maxBeamRange – maximum distance from original coordinates at which new coordinates can be located, in units of beams. Default is 5.
LineStacker.readCoordsNamesGUI()

Open GUI to select coordinates files.

Returns path of selected files.

LineStacker.writeCoords(coordpath, coords, unit='deg')

Write coordinates to a file

Parameters:
  • coordpath – absolute path to coordinate file to be created
  • coords – list of coordinates (stacker.Coord instances) to write to file

line_image

LineStacker.line_image Module:

Module for cube line stacking.

LineStacker.line_image.calculate_amp_weights(coords, fit=False)

Sets weights of each coord to one over the line amplitude.

/!\ only use if lines are visible pre-stacking

Parameters:
  • coords – A coordList object of all target coordinates.
  • fit

    If set to True, spectra will be extracted from each coordinate pixel and fited with a gaussian. The gaussian’s extracted amplitude will be used as the line’s amplitude.

    If set to False, the line’s amplitude is set to the value of the brightest spectral bin of each coordinate pixel.

LineStacker.line_image.calculate_sigma2_weights(coords, maskradius=0.0)

Computes standard deviation of data cubes and sets weights to one over sigma**2.

Parameters:
  • coords – A coordList object of all target coordinates.
  • maskradius – Radius (in pixel) of the mask, centered on coordinate center, to avoid including pixels close to source in noise computation.
LineStacker.line_image.calculate_sigma2_weights_spectral(coords, maskradius=0.0)

Computes standard deviation of data cubes in every spectral channel and sets weights to one over sigma**2.

Parameters:
  • coords – A coordList object of all target coordinates.
  • maskradius – Radius (in pixel) of the mask, centered on coordinate center, to avoid including pixels close to source in noise computation.
LineStacker.line_image.stack(coords, outfile='stackResult.image', stampsize=32, imagenames=[], method='mean', spectralMethod='z', weighting=None, returnWeights=False, maskradius=0, psfmode='point', primarybeam=None, fEm=0, N_chans='default', plotIt=False, regridFromZ=False, regridMethod='scaleToMax', saveSubCubes=False, **kwargs)

Performs line stacking in the image domain. returns: Estimate of stacked flux assuming point source.

Parameters:
  • coords – A coordList object of all target coordinates. outfile Target name for stacked image.
  • stampsize – size of target image in pixels
  • imagenames – Name of images to extract flux from.
  • method – ‘mean’ or ‘median’, will determined how pixels are calculated
  • spectralMethod

    Method to select the central frequency of the stack. The corresponding value should be found in the 3rd column of the coord file. Possible methods are:

    ‘z’: the redshift of the observed line, if used fEm (emission frequency) must be informed as an argument of this Stack function.

    ‘centralFreq’: the (observed) central frequency, or velocity.

    ‘channel’: to dirrectly input the channel number of the center of the stack.

  • weighting

    used if method set to ‘mean’, possible values are:

    ‘sigma2’, weights are set to 1/sigma**2 where sigma is the standard deviation of the corresponding data cube (excluding masked region). See calculate_sigma2_weights

    ‘sigma2F’, similar to sigma2 except weights are individually computed for each spectral bin. See calculate_sigma2_weights_spectral

    ‘1/A’, /!\ only use if lines are visible pre-stacking, weights are set to one over the line amplitude. See calculate_amp_weights

    None, using weights in coords (set to 1 by default).

  • returnWeights

    If true weights of each source are written in outfile “weightFile.csv” in format: coord.x, coord.y, coord.z, coord.weight.

    If multiple weights exist for one source (for each spectral channel) all are written.

  • maskradius – allows blanking of centre pixels in weight calculation
  • psfmode – Allows application of filters to stacking, currently not supported.
  • primarybeam – only applies if weighting=’pb’
  • fEm – rest emission frequency of the line,
  • N_chans – number of channels of the resulting stack, default is number of channels in the first image.
  • plotIt – direct plot option
  • regridFromZ – if set to True new images will be created, regridded to take into account the redshift difference of the different sources. See LineStacker.analysisTools.regridFromZ for a more complete description. NB: ALL IMAGES SHOULD HAVE SAME FREQUENCY BIN originally.
  • regridMethod – Used if regridFromZ is True. Can be set either to ‘scaleToMin’ or ‘scaleToMax’. In the first case all images are regrided to match the smallest redshift (over-gridding), all images are regridded to match the highest redshift in the other case (under-gridding)
  • saveSubCubes – If set to True (or to str) sub cubes will be saved as a numpy file. (outSubCubes.npy if set to True, user defined is set to str)

OneD_Stacker

LineStacker.OneD_Stacker Module:

Module for one dimensional line stacking.

class LineStacker.OneD_Stacker.Image(spectrum=[], amp=[], velocities=[], frequencies=[], z=None, fEmLine=False, centerIndex=None, centralVelocity=None, centralFrequency=None, weights=1, name='', fit=False, velOrFreq='vel')

Image class, each object is a spectrum to stack, containing all necessary information to be stacked they can consist simply of a the flux array, or flux and corresponding spectral values

Parameters:
  • coords – A coordList object of all target coordinates.
  • spectrum – Spectrum should be of the shape [N,2] or [2,N], where N is the number of spectral bins. The second dimension being the flux and the first the spectral values.
  • amp – Instead of defining spectrum one can define only the amplitude (flux).
  • velocities=[] – In the case where amp is defined it is still possible to define the velocites
  • frequencies=[] – In the case where amp is defined it is still possible to define the frequencies
  • z – Redshift, one of the possible way to define central frequency. If using redshift fEmLine (emission frequency of the line) should be defined. In addition the Image spectra should consist of BOTH amplitudes and spectral information (frequencies or velocites), and not amplitude alone.
  • fEmLine – Emission frequency of the line, needed if redshift argument is used.
  • centerIndex – channel index of the line center, an other possible way to define line center.
  • centralFrequency – (observed) Frequency of the line center, an other possible way to define line center.
  • centralVelocity – Observed velocity of the line center, an other possible way to define line center.
  • weights

    The weighting scheme to use.

    Can be set to ‘1/A’ or ‘sigma2’. If sigma2 is used std of the entire spectra is used UNLESS, fit is set to True, in which case the central part around the line is excluded from std calculation (central here means one FWHM on each side of the center of the line).

    Alternativelly user input can be used, float or list (or array)

  • name – name of the image, can allow easier identification
  • fit – If fit is set to True, the spectrum will be fitted with a gaussian to try and identify the line center (as well as amplitude if weight is set to 1/A)
  • velOrFreq – Defining if spectral dimension is velocity or frequency.
freqToVel(freq, z, fEmLine)

Function to go from frequencies to velocites. Requieres rest emission frequency and redshift.

velToFreq(vel, z, fEmLine)

Function to go from velocites to frequencies. Requieres rest emission frequency and redshift.

LineStacker.OneD_Stacker.Stack(Images, chansStack='full', method='mean', center='lineCenterIndex', regridFromZ=False, regridMethod='scaleToMin')

Main (one dimmensional) stacking function.

Requieres list of Image objects.

Parameters:
  • Images – List of images, images have to objects of the Image class (LineStacker.OneD_Stacker.Image).
  • chansStack – Number of channels to stack. Set to ‘full’ to stack all channels from all images. User input (int) otherwise
  • method – stacking method, ‘mean’ and ‘median’ supported
  • center

    Method to find central frequency of the stack, possible values are:

    “center”, to stack all spectra center to center,

    ‘fit’ to use gaussian fitting on the spectrum to determine line center,

    ‘zero_vel’ to stack on velocity=0 bin,

    ‘lineCenterIndex’ use the line center initiated with the image,

    Or dirrectly defined by the user (int)

  • regridFromZ – if set to True spectra will be regridded to take into account the redshift difference of the different sources. See LineStacker.analysisTools.regridFromZ1D for a more complete description.
  • regridMethod – Used if regridFromZ is True. Can be set either to ‘scaleToMin’ or ‘scaleToMax’. In the first case all spetcra are regrided to match the smallest redshift (over-gridding), all spectra are regridded to match the highest redshift in the other case (under-gridding).

analysisTools

LineStacker.analysisTools Module:

Module containing statistical/analysis tools for stacking.

LineStacker.analysisTools.bootStraping_Cube(coords, stampsize=32, imagenames=[], method='mean', weighting=None, maxmaskradius=0, fEm=0, spectralMethod='z', N_chans=30, nRandom=1000, save='amp')

Performs bootstrapping stack of cubes. See stacker.line_image.stack for further information on stack parametres

Parameters:
  • coords – A stacker.coordList object of all target coordinates
  • stampsize – size of target image in pixels
  • imagenames – Name of images to extract cubes from
  • method – stacking method, ‘mean’ or ‘median’
  • weighting

    weighting method to use if stacking method is mean

    possible values are ‘sigma2’, ‘sigma2F’, ‘1/A’, ‘None’, 1 or user input (float)

    see stacker.line-image for a complete description of weighting methods

  • maskradius – radius of the mask used to blank the centre pixels in weight calculation
  • fEm – rest emission frequency of the line
  • N_chans – number of channels of the resulting stack
  • nRandom – number of boostrap itterations
  • save

    data to save at each bootstrap itterations

    possible values are ‘all’, ‘amp’, ‘ampAndWidth’ and ‘outflow’

    ‘all’ saves the full stack at each bootstrap itteration /!caution, can be memory expensive

    ‘amp’ saves the amplitude (maximum value of the stack) of the line, at each bootstrap itteration, fastest

    ‘ampAndWidth’ fits the line with a gaussian and saves the corresponding amplitude and width at each bootstrap itteration, can be cpu exppensive

    ‘ouflow’ fits the line with two gaussian components and saves the stack parameters at each bootstrap itteration, can be cpu exppensive

    for ‘amp’, ‘ampAndWidth’ and ‘ouflow’ the line is obtained by summing all pixels inside the stack stamp.

LineStacker.analysisTools.bootstraping_OneD(Images, nRandom=1000, chansStack='full', method='mean', center='lineCenterIndex', save='all')

Performs bootstrapping stack of spectra. See stacker.OneD_Stacker.stack for further information on stack parametres.

Parameters:
  • Images – a list of stacker.OneD_Stacker.Images
  • nRandom – number of boostrap itterations
  • chansStack – number of channels to stack, either a fixed number or ‘full’ for entire spectra
  • method – stacking method, ‘mean’ or ‘median’
  • center – Method to center spectra. See stacker.OneD_Stacker.stack for further information on centering methods.
  • save

    data to save at each bootstrap itterations

    possible values are ‘all’, ‘amp’ and ‘ampAndWidth’

    ‘all’ saves the full stack at each bootstrap itteration /!caution, can be memory expensive

    ‘amp’ saves the amplitude of the line (maximum value of the stack) at each bootstrap itteration, fastest

    ‘ampAndWidth’ fits the line with a gaussian and saves the corresponding amplitude and width at each bootstrap itteration, can be cpu exppensive.

LineStacker.analysisTools.noise_estimator(imagenames, nRandom=10000, maskradius=0, maskCenter=[0, 0], continuum=True, chanToNoise='random')

Estimates noise of image cube.

Parameters:
  • imagename – Path to image
  • nRandom – Number of itterations
  • maskradius – Radius of the mask (in pixels)
  • maskCenter – Center location of the mask (in pixels). NB: CENTER OF IMAGE IS DEFINED AS [0,0]
  • continuum – If set to True points will be taken at random on the any of the spectral channels. Otherwise all channels are probbed independantly.
  • chanTonoise – If set to a specific (int) value then noise will be extracted from the specified channel. NB: only works if continuum i set to True.
LineStacker.analysisTools.randomizeCoords(coords, beam=0, lowerLimit='default', upperLimit='default')

Function to randomize stacking coordinates, new ramdom position uniformally randomized, centered on the original stacking coordinate

Parameters:
  • coords – A list of stacker.Coord coordinates
  • lowerLimit

    Lower spatial limit (distance from stacking position) to random new random position.

    Default is 5 beams

  • upperLimit

    Upper spatial limit (distance from stacking position) to random new random position.

    Default is 10 beams

  • beam – beam size, needed if lowerLimit or upperLimit are set to ‘default’
LineStacker.analysisTools.rebin_CubesSpectra(coords, imagenames, regionSize=False, widths=False, outputName='_SpectralRebinned')
Rebin a list of image-cubes so that all width have the same width as the smallest width

/!\ Lines must be visible before stacking to operate rebinning

/!\ Only one coord per image is necessary for rebinning

coords
A coordList object of all target coordinates.
imagenames
Name of images to rebin
regionSize

size (in pixels) to extract the spectra from

If set to False spectra will be extracted solely from the coord pixel

widths

widths of the lines

If set to ‘False’ the spectra will be fitted with a gaussian to extract the width

outputName
Suffix of the rebinned cube, to add to the original cube name.
LineStacker.analysisTools.rebin_OneD(images)
Rebin a list of images so that all width have the same width as the smallest width

/!\ Lines must be visible before stacking to operate rebinning

images
A list of stacker.OneD_Stacker.images
LineStacker.analysisTools.regridFromZ(coords, imagenames, stampsize=32, N_chans=0, fEm=0, writeImage=True, regridMethod='scaleToMin')

Cube regridding function coorecting the observed linewidth change due to redshift. Spectral dimensions are rebinned to a new_size=old_size*zRatio where zRatio=(1+z)/(1+zRef) where z is the observed line redshift and zRef is either the smaller (scaleToMin) or bigger (scaleToMax) redshift among the studied lines.

Parameters:
  • coords – A coordList object of all target coordinates.
  • imagenames – Name of images to extract flux from.
  • stampsize – size of target image in pixels
  • N_chans – number of channels of the resulting stack, default is number of channels in the first image.
  • fEm – rest emission frequency of the line
  • writeImage – boolean, if set to True regridded images will be written to disk (in ./regridedImages)
  • regridMethod – Method of regridding, can be set either to ‘scaleToMin’ or ‘scaleToMax’. In the first case all spetcra are regrided to match the smallest redshift (over-gridding), all spectra are regridded to match the highest redshift in the other case (under-gridding). NB: Using ‘scaleToMin’ while having sources at z=0 will lead to errors when writting stacked image to disk.
  • Returns – List of new regridded image cubes and associated coordinates if writeImage is True or list of regridded stamps otherwise.
LineStacker.analysisTools.regridFromZ1D(images, regridMethod='scaleToMin')

1D regridding function correcting the observed linewidth change due to redshift. Spectra are rebinned to a new_size=old_size*zRatio where zRatio=(1+z)/(1+zRef) where z is the observed line redshit and zRef is either the smaller (scaleToMin) or bigger (scaleToMax) redshift among the studied lines.

Parameters:
  • Images – List of images, images have to objects of the Image class (LineStacker.OneD_Stacker.Image).
  • regridMethod – Method of regridding, can be set either to ‘scaleToMin’ or ‘scaleToMax’. In the first case all spetcra are regrided to match the smallest redshift (over-gridding), all spectra are regridded to match the highest redshift in the other case (under-gridding).
  • Returns – List of new regridded images.
LineStacker.analysisTools.stack_estimator(coords, nRandom=100, imagenames=[], stampsize=1, method='mean', N_chans=30, lowerLimit='default', upperLimit='default', save='central_pixel', fEm=0, **kwargs)

Performs stacks at random positions a set number of times.Allows to probe the relevance of stack through stacking random positions as a Monte Carlo process.

Parameters:
  • coords – A coordList object of all target coordinates.
  • nRandom – Number of itterations
  • imagenames – Name of imagenames to stack
  • stampsize – Size of the stamp to stack (because only the central pixel is extracted anyway, this should be kept to default to enhance efficiency)
  • method – Method for stacking, see LineStacker.line_image.stack
  • N_chans – Number of channels in the stack
  • lowerLimit – Lower spatial limit (distance from stacking position) to randomize new stacking position. Default is 5 beams
  • upperLimit – Upper spatial limit (distance from stacking position) to randomize new stacking position. Default is 10 beams
  • save – either ‘central_pixel’ or ‘all’. If ‘central_pixel’ only the spectrum of central pixel is saved.
  • returns – STD, mean and all random stacks.
LineStacker.analysisTools.subsample_OneD(images, nRandom=10000, maxTest=<function maximizeSNR>, **kwargs)

Randomly ressamples spectra and grades them accordingly to a given grade function. Returns the grade of each spectra as a dictionnary.

Parameters:
  • images – A list of stacker.OneD_Stacker.images
  • nRandom – Number of itterations of the Monte-Carlo process
  • maxTest – function test to grade the sources build your own, or use existing: maximizeAmp, maximizeSNR, maximizeOutflow. Default is to maximize amplitude (amplitude being simply maximum value of spectra)

tools

LineStacker.tools.ProgressBar(n, total)

show progress of a process :param n: current step :param total: total number of steps

LineStacker.tools.fit Module:

Basic custom fit module for LineStacker.

LineStacker.tools.fit.DoubleGauss(f=[], amp1=0, amp2=0, f01=0, f02=0, sigma1=0, sigma2=0)

Sum of two Gaussian function

LineStacker.tools.fit.DoubleGaussFit(fctToFit=[], fullFreq=[], sigma1='default', sigma2='default', ampScale=0.1, returnAllComp=False, returnInfos=False, returnError=False)

Double Gaussian (sum of two Gaussians) fitting function. Return order: fitting function, (first Gaussian, second Gaussian), (fitting parameters), (error on fitting parameters)

Parameters:
  • fctToFit – One dimensionnal array to be fitted.
  • fullFreq – Spectral dimension array. Not requiered
  • sigma1 – Initial width of the first Gaussian component for fitting, ‘default’ is 3 bins.
  • sigma2 – Initial width of the second Gaussian component for fitting, ‘default’ is 6 bins.
  • ampScale – Initial amp ratio (between the two Gaussian components) for fitting, default is 0.1.
  • returnAllComp – If set to True function returns both individual components.
  • returnInfos – If set to True function returns fitted parameters.
  • returnError – If set to True function returns error on fitted parameters.
LineStacker.tools.fit.GaussFit(fctToFit=[], fullFreq=[], sigma='default', returnInfos=False, returnError=False)

Simple Gaussian fitting function. Return order: fitting function, (fitting parameters), (error on fitting parameters)

Parameters:
  • fctToFit – One dimensionnal array to be fitted
  • fullFreq – Spectral dimension array. Not requiered
  • sigma – initial width for fitting, ‘default’ is 3 bins
  • returnInfos – If set to True function returns fitted parameters
  • returnError – If set to True function returns error on fitted parameters
LineStacker.tools.fit.gaussFct(x, a, x0, sigma, constant=0)

Basic Gaussian function