INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Calculate the autocorrelation function of the noise where the noise is a 2d array that may contain nans | def nan_acf(noise):
"""
Calculate the autocorrelation function of the noise
where the noise is a 2d array that may contain nans
Parameters
----------
noise : 2d-array
Noise image.
Returns
-------
acf : 2d-array
The ACF.
"""
corr = np.zeros(noise.shape)
... |
Create the matrix ita of the noise where the noise may be a masked array where ita ( x y ) is the correlation between pixel pairs that have the same separation as x and y. | def make_ita(noise, acf=None):
"""
Create the matrix ita of the noise where the noise may be a masked array
where ita(x,y) is the correlation between pixel pairs that have the same separation as x and y.
Parameters
----------
noise : 2d-array
The noise image
acf : 2d-array
... |
Calculate the expected bias on each of the parameters in the model pars. Only parameters that are allowed to vary will have a bias. Calculation follows the description of Refrieger & Brown 1998 ( cite ). | def RB_bias(data, pars, ita=None, acf=None):
"""
Calculate the expected bias on each of the parameters in the model pars.
Only parameters that are allowed to vary will have a bias.
Calculation follows the description of Refrieger & Brown 1998 (cite).
Parameters
----------
data : 2d-array
... |
Calculate and apply a bias correction to the given fit parameters | def bias_correct(params, data, acf=None):
"""
Calculate and apply a bias correction to the given fit parameters
Parameters
----------
params : lmfit.Parameters
The model parameters. These will be modified.
data : 2d-array
The data which was used in the fitting
acf : 2d-ar... |
Calculate the parameter errors for a fitted source using the description of Condon 97 All parameters are assigned errors assuming that all params were fit. If some params were held fixed then these errors are overestimated. | def condon_errors(source, theta_n, psf=None):
"""
Calculate the parameter errors for a fitted source
using the description of Condon'97
All parameters are assigned errors, assuming that all params were fit.
If some params were held fixed then these errors are overestimated.
Parameters
-----... |
Convert pixel based errors into sky coord errors | def errors(source, model, wcshelper):
"""
Convert pixel based errors into sky coord errors
Parameters
----------
source : :class:`AegeanTools.models.SimpleSource`
The source which was fit.
model : lmfit.Parameters
The model which was fit.
wcshelper : :class:`AegeanTools.wc... |
Convert pixel based errors into sky coord errors Uses covariance matrix for ra/ dec errors and calculus approach to a/ b/ pa errors | def new_errors(source, model, wcshelper): # pragma: no cover
"""
Convert pixel based errors into sky coord errors
Uses covariance matrix for ra/dec errors
and calculus approach to a/b/pa errors
Parameters
----------
source : :class:`AegeanTools.models.SimpleSource`
The source which... |
Convert an lmfit. Parameters object into a function which calculates the model. | def ntwodgaussian_lmfit(params):
"""
Convert an lmfit.Parameters object into a function which calculates the model.
Parameters
----------
params : lmfit.Parameters
Model parameters, can have multiple components.
Returns
-------
model : func
A function f(x,y) that will ... |
Fit the model to the data data may contain flagged or masked data with the value of np. NaN | def do_lmfit(data, params, B=None, errs=None, dojac=True):
"""
Fit the model to the data
data may contain 'flagged' or 'masked' data with the value of np.NaN
Parameters
----------
data : 2d-array
Image data
params : lmfit.Parameters
Initial model guess.
B : 2d-array
... |
Take a set of parameters that were fit with lmfit and replace the errors with the 1 \ sigma errors calculated using the covariance matrix. | def covar_errors(params, data, errs, B, C=None):
"""
Take a set of parameters that were fit with lmfit, and replace the errors
with the 1\sigma errors calculated using the covariance matrix.
Parameters
----------
params : lmfit.Parameters
Model
data : 2d-array
Image data
... |
act as a multiprocessing barrier | def barrier(events, sid, kind='neighbour'):
"""
act as a multiprocessing barrier
"""
events[sid].set()
# only wait for the neighbours
if kind=='neighbour':
if sid > 0:
logging.debug("{0} is waiting for {1}".format(sid, sid - 1))
events[sid - 1].wait()
if s... |
Perform sigma clipping on an array ignoring non finite values. | def sigmaclip(arr, lo, hi, reps=3):
"""
Perform sigma clipping on an array, ignoring non finite values.
During each iteration return an array whose elements c obey:
mean -std*lo < c < mean + std*hi
where mean/std are the mean std of the input array.
Parameters
----------
arr : iterabl... |
A shallow wrapper for sigma_filter. | def _sf2(args):
"""
A shallow wrapper for sigma_filter.
Parameters
----------
args : list
A list of arguments for sigma_filter
Returns
-------
None
"""
# an easier to debug traceback when multiprocessing
# thanks to https://stackoverflow.com/a/16618842/1710603
t... |
Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. | def sigma_filter(filename, region, step_size, box_size, shape, domask, sid):
"""
Calculate the background and rms for a sub region of an image. The results are
written to shared memory - irms and ibkg.
Parameters
----------
filename : string
Fits file to open
region : list
... |
Calculate the background and noise images corresponding to the input file. The calculation is done via a box - car approach and uses multiple cores and shared memory. | def filter_mc_sharemem(filename, step_size, box_size, cores, shape, nslice=None, domask=True):
"""
Calculate the background and noise images corresponding to the input file.
The calculation is done via a box-car approach and uses multiple cores and shared memory.
Parameters
----------
filename ... |
Create a background and noise image from an input image. Resulting images are written to outbase_bkg. fits and outbase_rms. fits | def filter_image(im_name, out_base, step_size=None, box_size=None, twopass=False, cores=None, mask=True, compressed=False, nslice=None):
"""
Create a background and noise image from an input image.
Resulting images are written to `outbase_bkg.fits` and `outbase_rms.fits`
Parameters
----------
i... |
Combine data and a fits header to write a fits file. | def write_fits(data, header, file_name):
"""
Combine data and a fits header to write a fits file.
Parameters
----------
data : numpy.ndarray
The data to be written.
header : astropy.io.fits.hduheader
The header for the fits file.
file_name : string
The file to writ... |
Convert sexegessimal RA string into a float in degrees. | def dec2dec(dec):
"""
Convert sexegessimal RA string into a float in degrees.
Parameters
----------
dec : string
A string separated representing the Dec.
Expected format is `[+- ]hh:mm[:ss.s]`
Colons can be replaced with any whit space character.
Returns
-------
... |
Convert decimal degrees into a sexagessimal string in degrees. | def dec2dms(x):
"""
Convert decimal degrees into a sexagessimal string in degrees.
Parameters
----------
x : float
Angle in degrees
Returns
-------
dms : string
String of format [+-]DD:MM:SS.SS
or XX:XX:XX.XX if x is not finite.
"""
if not np.isfinite(x)... |
Convert decimal degrees into a sexagessimal string in hours. | def dec2hms(x):
"""
Convert decimal degrees into a sexagessimal string in hours.
Parameters
----------
x : float
Angle in degrees
Returns
-------
dms : string
String of format HH:MM:SS.SS
or XX:XX:XX.XX if x is not finite.
"""
if not np.isfinite(x):
... |
Calculate the great circle distance between to points using the haversine formula [ 1 ] _. | def gcd(ra1, dec1, ra2, dec2):
"""
Calculate the great circle distance between to points using the haversine formula [1]_.
Parameters
----------
ra1, dec1, ra2, dec2 : float
The coordinates of the two points of interest.
Units are in degrees.
Returns
-------
dist : flo... |
Calculate the bearing of point 2 from point 1 along a great circle. The bearing is East of North and is in [ 0 360 ) whereas position angle is also East of North but ( - 180 180 ] | def bear(ra1, dec1, ra2, dec2):
"""
Calculate the bearing of point 2 from point 1 along a great circle.
The bearing is East of North and is in [0, 360), whereas position angle is also East of North but (-180,180]
Parameters
----------
ra1, dec1, ra2, dec2 : float
The sky coordinates (de... |
Translate a given point a distance r in the ( initial ) direction theta along a great circle. | def translate(ra, dec, r, theta):
"""
Translate a given point a distance r in the (initial) direction theta, along a great circle.
Parameters
----------
ra, dec : float
The initial point of interest (degrees).
r, theta : float
The distance and initial direction to translate (d... |
Calculate the Rhumb line distance between two points [ 1 ] _. A Rhumb line between two points is one which follows a constant bearing. | def dist_rhumb(ra1, dec1, ra2, dec2):
"""
Calculate the Rhumb line distance between two points [1]_.
A Rhumb line between two points is one which follows a constant bearing.
Parameters
----------
ra1, dec1, ra2, dec2 : float
The position of the two points (degrees).
Returns
---... |
Calculate the bearing of point 2 from point 1 along a Rhumb line. The bearing is East of North and is in [ 0 360 ) whereas position angle is also East of North but ( - 180 180 ] | def bear_rhumb(ra1, dec1, ra2, dec2):
"""
Calculate the bearing of point 2 from point 1 along a Rhumb line.
The bearing is East of North and is in [0, 360), whereas position angle is also East of North but (-180,180]
Parameters
----------
ra1, dec1, ra2, dec2 : float
The sky coordinates... |
Translate a given point a distance r in the ( initial ) direction theta along a Rhumb line. | def translate_rhumb(ra, dec, r, theta):
"""
Translate a given point a distance r in the (initial) direction theta, along a Rhumb line.
Parameters
----------
ra, dec : float
The initial point of interest (degrees).
r, theta : float
The distance and initial direction to translate ... |
Convert galactic l/ b to fk5 ra/ dec | def galactic2fk5(l, b):
"""
Convert galactic l/b to fk5 ra/dec
Parameters
----------
l, b : float
Galactic coordinates in radians.
Returns
-------
ra, dec : float
FK5 ecliptic coordinates in radians.
"""
a = SkyCoord(l, b, unit=(u.radian, u.radian), frame='galac... |
Mask a 2d image ( data ) such that pixels within region are set to nan. | def mask_plane(data, wcs, region, negate=False):
"""
Mask a 2d image (data) such that pixels within 'region' are set to nan.
Parameters
----------
data : 2d-array
Image array.
wcs : astropy.wcs.WCS
WCS for the image in question.
region : :class:`AegeanTools.regions.Region`... |
Created a masked version of file using a region. | def mask_file(regionfile, infile, outfile, negate=False):
"""
Created a masked version of file, using a region.
Parameters
----------
regionfile : str
A file which can be loaded as a :class:`AegeanTools.regions.Region`.
The image will be masked according to this region.
infile... |
Apply a given mask ( region ) to the table removing all the rows with ra/ dec inside the region If negate = False then remove the rows with ra/ dec outside the region. | def mask_table(region, table, negate=False, racol='ra', deccol='dec'):
"""
Apply a given mask (region) to the table, removing all the rows with ra/dec inside the region
If negate=False then remove the rows with ra/dec outside the region.
Parameters
----------
region : :class:`AegeanTools.regio... |
Apply a region file as a mask to a catalog removing all the rows with ra/ dec inside the region If negate = False then remove the rows with ra/ dec outside the region. | def mask_catalog(regionfile, infile, outfile, negate=False, racol='ra', deccol='dec'):
"""
Apply a region file as a mask to a catalog, removing all the rows with ra/dec inside the region
If negate=False then remove the rows with ra/dec outside the region.
Parameters
----------
regionfile : str... |
Convert a MIMAS region (. mim ) file into a DS9 region (. reg ) file. | def mim2reg(mimfile, regfile):
"""
Convert a MIMAS region (.mim) file into a DS9 region (.reg) file.
Parameters
----------
mimfile : str
Input file in MIMAS format.
regfile : str
Output file.
"""
region = Region.load(mimfile)
region.write_reg(regfile)
logging.i... |
Convert a MIMAS region (. mim ) file into a MOC region (. fits ) file. | def mim2fits(mimfile, fitsfile):
"""
Convert a MIMAS region (.mim) file into a MOC region (.fits) file.
Parameters
----------
mimfile : str
Input file in MIMAS format.
fitsfile : str
Output file.
"""
region = Region.load(mimfile)
region.write_fits(fitsfile, moctool=... |
Convert a string that describes a box in ds9 format into a polygon that is given by the corners of the box | def box2poly(line):
"""
Convert a string that describes a box in ds9 format, into a polygon that is given by the corners of the box
Parameters
----------
line : str
A string containing a DS9 region command for a box.
Returns
-------
poly : [ra, dec, ...]
The corners of ... |
Parse a string that describes a circle in ds9 format. | def circle2circle(line):
"""
Parse a string that describes a circle in ds9 format.
Parameters
----------
line : str
A string containing a DS9 region command for a circle.
Returns
-------
circle : [ra, dec, radius]
The center and radius of the circle.
"""
words =... |
Parse a string of text containing a DS9 description of a polygon. | def poly2poly(line):
"""
Parse a string of text containing a DS9 description of a polygon.
This function works but is not very robust due to the constraints of healpy.
Parameters
----------
line : str
A string containing a DS9 region command for a polygon.
Returns
-------
... |
Parse a DS9 region file and write a MIMAS region (. mim ) file. | def reg2mim(regfile, mimfile, maxdepth):
"""
Parse a DS9 region file and write a MIMAS region (.mim) file.
Parameters
----------
regfile : str
DS9 region (.reg) file.
mimfile : str
MIMAS region (.mim) file.
maxdepth : str
Depth/resolution of the region file.
"... |
Return a region that is the combination of those specified in the container. The container is typically a results instance that comes from argparse. | def combine_regions(container):
"""
Return a region that is the combination of those specified in the container.
The container is typically a results instance that comes from argparse.
Order of construction is: add regions, subtract regions, add circles, subtract circles,
add polygons, subtract pol... |
Construct a region which is the intersection of all regions described in the given list of file names. | def intersect_regions(flist):
"""
Construct a region which is the intersection of all regions described in the given
list of file names.
Parameters
----------
flist : list
A list of region filenames.
Returns
-------
region : :class:`AegeanTools.regions.Region`
The i... |
Save the given region to a file | def save_region(region, filename):
"""
Save the given region to a file
Parameters
----------
region : :class:`AegeanTools.regions.Region`
A region.
filename : str
Output file name.
"""
region.save(filename)
logging.info("Wrote {0}".format(filename))
return |
Convert a MIMAS region (. mim ) file into a image ( eg. png ) | def save_as_image(region, filename):
"""
Convert a MIMAS region (.mim) file into a image (eg .png)
Parameters
----------
region : :class:`AegeanTools.regions.Region`
Region of interest.
filename : str
Output filename.
"""
import healpy as hp
pixels = list(region.get... |
Return some pixel information based on the given hdu header pixarea - the area of a single pixel in deg2 pixscale - the side lengths of a pixel ( assuming they are square ) | def get_pixinfo(header):
"""
Return some pixel information based on the given hdu header
pixarea - the area of a single pixel in deg2
pixscale - the side lengths of a pixel (assuming they are square)
Parameters
----------
header : HDUHeader or dict
FITS header information
Retur... |
Create a: class: AegeanTools. fits_image. Beam object from a fits header. | def get_beam(header):
"""
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
... |
Search through an image header. If the keywords BMAJ/ BMIN/ BPA are not set but there are AIPS history cards then we can populate the BMAJ/ BMIN/ BPA. Fix the header if possible otherwise don t. Either way don t complain. | def fix_aips_header(header):
"""
Search through an image header. If the keywords BMAJ/BMIN/BPA are not set,
but there are AIPS history cards, then we can populate the BMAJ/BMIN/BPA.
Fix the header if possible, otherwise don't. Either way, don't complain.
Parameters
----------
header : HDUH... |
Set the image data. Will not work if the new image has a different shape than the current image. | def set_pixels(self, pixels):
"""
Set the image data.
Will not work if the new image has a different shape than the current image.
Parameters
----------
pixels : numpy.ndarray
New image data
Returns
-------
None
"""
if... |
Calculate the rms of the image. The rms is calculated from the interqurtile range ( IQR ) to reduce bias from source pixels. | def get_background_rms(self):
"""
Calculate the rms of the image. The rms is calculated from the interqurtile range (IQR), to
reduce bias from source pixels.
Returns
-------
rms : float
The image rms.
Notes
-----
The rms value is cach... |
Get the sky coordinates for a given image pixel. | def pix2sky(self, pixel):
"""
Get the sky coordinates for a given image pixel.
Parameters
----------
pixel : (float, float)
Image coordinates.
Returns
-------
ra,dec : float
Sky coordinates (degrees)
"""
pixbox = ... |
Get the pixel coordinates for a given sky position ( degrees ). | def sky2pix(self, skypos):
"""
Get the pixel coordinates for a given sky position (degrees).
Parameters
----------
skypos : (float,float)
ra,dec position in degrees.
Returns
-------
x,y : float
Pixel coordinates.
"""
... |
Open a file read contents return a list of all the sources in that file. | def load_sources(filename):
"""
Open a file, read contents, return a list of all the sources in that file.
@param filename:
@return: list of OutputSource objects
"""
catalog = catalogs.table_to_source_list(catalogs.load_table(filename))
logging.info("read {0} sources from {1}".format(len(cat... |
Will search the beam info from the HISTORY: param hdulist:: return: | def search_beam(hdulist):
"""
Will search the beam info from the HISTORY
:param hdulist:
:return:
"""
header = hdulist[0].header
history = header['HISTORY']
history_str = str(history)
#AIPS CLEAN BMAJ= 1.2500E-02 BMIN= 1.2500E-02 BPA= 0.00
if 'BMAJ' in history_str:
... |
Ensure that a > = b for a given source object. If a<b then swap a/ b and increment pa by 90. err_a/ err_b are also swapped as needed. | def fix_shape(source):
"""
Ensure that a>=b for a given source object.
If a<b then swap a/b and increment pa by 90.
err_a/err_b are also swapped as needed.
Parameters
----------
source : object
any object with a/b/pa/err_a/err_b properties
"""
if source.a < source.b:
... |
Angle theta is periodic with period pi. Constrain theta such that - pi/ 2<theta< = pi/ 2. | def theta_limit(theta):
"""
Angle theta is periodic with period pi.
Constrain theta such that -pi/2<theta<=pi/2.
Parameters
----------
theta : float
Input angle.
Returns
-------
theta : float
Rotate angle.
"""
while theta <= -1 * np.pi / 2:
theta += ... |
Convert a telescope name into a latitude returns None when the telescope is unknown. | def scope2lat(telescope):
"""
Convert a telescope name into a latitude
returns None when the telescope is unknown.
Parameters
----------
telescope : str
Acronym (name) of telescope, eg MWA.
Returns
-------
lat : float
The latitude of the telescope.
Notes
--... |
Determine how many cores we are able to use. Return 1 if we are not able to make a queue via pprocess. | def check_cores(cores):
"""
Determine how many cores we are able to use.
Return 1 if we are not able to make a queue via pprocess.
Parameters
----------
cores : int
The number of cores that are requested.
Returns
-------
cores : int
The number of cores available.
... |
Look for and return all the aux files that are associated witht this filename. Will look for: background ( _bkg. fits ) rms ( _rms. fits ) mask (. mim ) catalogue ( _comp. fits ) psf map ( _psf. fits ) | def get_aux_files(basename):
"""
Look for and return all the aux files that are associated witht this filename.
Will look for:
background (_bkg.fits)
rms (_rms.fits)
mask (.mim)
catalogue (_comp.fits)
psf map (_psf.fits)
will return filenames if they exist, or None ... |
Generator function. Segment an image into islands and return one island at a time. | def _gen_flood_wrap(self, data, rmsimg, innerclip, outerclip=None, domask=False):
"""
Generator function.
Segment an image into islands and return one island at a time.
Needs to work for entire image, and also for components within an island.
Parameters
----------
... |
Estimates the number of sources in an island and returns initial parameters for the fit as well as limits on those parameters. | def estimate_lmfit_parinfo(self, data, rmsimg, curve, beam, innerclip, outerclip=None, offsets=(0, 0),
max_summits=None):
"""
Estimates the number of sources in an island and returns initial parameters for the fit as well as
limits on those parameters.
Par... |
Convert fitting results into a set of components | def result_to_components(self, result, model, island_data, isflags):
"""
Convert fitting results into a set of components
Parameters
----------
result : lmfit.MinimizerResult
The fitting results.
model : lmfit.Parameters
The model that was fit.
... |
Populate the global_data object by loading or calculating the various components | def load_globals(self, filename, hdu_index=0, bkgin=None, rmsin=None, beam=None, verb=False, rms=None, bkg=None, cores=1,
do_curve=True, mask=None, lat=None, psf=None, blank=False, docov=True, cube_index=None):
"""
Populate the global_data object by loading or calculating the variou... |
Generate and save the background and RMS maps as FITS files. They are saved in the current directly as aegean - background. fits and aegean - rms. fits. | def save_background_files(self, image_filename, hdu_index=0, bkgin=None, rmsin=None, beam=None, rms=None, bkg=None, cores=1,
outbase=None):
"""
Generate and save the background and RMS maps as FITS files.
They are saved in the current directly as aegean-background.f... |
Save the image data. This is probably only useful if the image data has been blanked. | def save_image(self, outname):
"""
Save the image data.
This is probably only useful if the image data has been blanked.
Parameters
----------
outname : str
Name for the output file.
"""
hdu = self.global_data.img.hdu
hdu.data = self.g... |
Calculate an rms image and a bkg image. | def _make_bkg_rms(self, mesh_size=20, forced_rms=None, forced_bkg=None, cores=None):
"""
Calculate an rms image and a bkg image.
Parameters
----------
mesh_size : int
Number of beams per box default = 20
forced_rms : float
The rms of the image.
... |
Estimate the background noise mean and RMS. The mean is estimated as the median of data. The RMS is estimated as the IQR of data/ 1. 34896. | def _estimate_bkg_rms(self, xmin, xmax, ymin, ymax):
"""
Estimate the background noise mean and RMS.
The mean is estimated as the median of data.
The RMS is estimated as the IQR of data / 1.34896.
Parameters
----------
xmin, xmax, ymin, ymax : int
The... |
Load a fits file ( bkg/ rms/ curve ) and make sure that it is the same shape as the main image. | def _load_aux_image(self, image, auxfile):
"""
Load a fits file (bkg/rms/curve) and make sure that
it is the same shape as the main image.
Parameters
----------
image : :class:`AegeanTools.fits_image.FitsImage`
The main image that has already been loaded.
... |
Do island refitting ( priorized fitting ) on a group of islands. | def _refit_islands(self, group, stage, outerclip=None, istart=0):
"""
Do island refitting (priorized fitting) on a group of islands.
Parameters
----------
group : list
A list of components grouped by island.
stage : int
Refitting stage.
... |
Take an Island do all the parameter estimation and fitting. | def _fit_island(self, island_data):
"""
Take an Island, do all the parameter estimation and fitting.
Parameters
----------
island_data : :class:`AegeanTools.models.IslandFittingData`
The island to be fit.
Returns
-------
sources : list
... |
Execute fitting on a list of islands This function just wraps around fit_island so that when we do multiprocesing a single process will fit multiple islands before returning results. | def _fit_islands(self, islands):
"""
Execute fitting on a list of islands
This function just wraps around fit_island, so that when we do multiprocesing
a single process will fit multiple islands before returning results.
Parameters
----------
islands : list of :... |
Run the Aegean source finder. | def find_sources_in_image(self, filename, hdu_index=0, outfile=None, rms=None, bkg=None, max_summits=None, innerclip=5,
outerclip=4, cores=None, rmsin=None, bkgin=None, beam=None, doislandflux=False,
nopositive=False, nonegative=False, mask=None, lat=None, img... |
Take an input catalog and image and optional background/ noise images fit the flux and ra/ dec for each of the given sources keeping the morphology fixed | def priorized_fit_islands(self, filename, catalogue, hdu_index=0, outfile=None, bkgin=None, rmsin=None, cores=1,
rms=None, bkg=None, beam=None, lat=None, imgpsf=None, catpsf=None, stage=3, ratio=None, outerclip=3,
doregroup=True, docov=True, cube_index=None):
... |
Determine whether a list of files are of a recognizable output type. | def check_table_formats(files):
"""
Determine whether a list of files are of a recognizable output type.
Parameters
----------
files : str
A list of file names
Returns
-------
result : bool
True if *all* the file names are supported
"""
cont = True
formats =... |
Print a list of all the file formats that are supported for writing. The file formats are determined by their extensions. | def show_formats():
"""
Print a list of all the file formats that are supported for writing.
The file formats are determined by their extensions.
Returns
-------
None
"""
fmts = {
"ann": "Kvis annotation",
"reg": "DS9 regions file",
"fits": "FITS Binary Table",
... |
Modify the metadata dictionary. DATE PROGRAM and PROGVER are added/ modified. | def update_meta_data(meta=None):
"""
Modify the metadata dictionary.
DATE, PROGRAM, and PROGVER are added/modified.
Parameters
----------
meta : dict
The dictionary to be modified, default = None (empty)
Returns
-------
An updated dictionary.
"""
if meta is None... |
Save a catalogue of sources using filename as a model. Meta data can be written to some file types ( fits votable ). | def save_catalog(filename, catalog, meta=None, prefix=None):
"""
Save a catalogue of sources using filename as a model. Meta data can be written to some file types
(fits, votable).
Each type of source will be in a separate file:
- base_comp.ext :class:`AegeanTools.models.OutputSource`
- base_i... |
Load a catalogue and extract the source positions ( only ) | def load_catalog(filename):
"""
Load a catalogue and extract the source positions (only)
Parameters
----------
filename : str
Filename to read. Supported types are csv, tab, tex, vo, vot, and xml.
Returns
-------
catalogue : list
A list of [ (ra, dec), ...]
"""
... |
Load a table from a given file. | def load_table(filename):
"""
Load a table from a given file.
Supports csv, tab, tex, vo, vot, xml, fits, and hdf5.
Parameters
----------
filename : str
File to read
Returns
-------
table : Table
Table of data.
"""
supported = get_table_formats()
fmt =... |
Write a table to a file. | def write_table(table, filename):
"""
Write a table to a file.
Parameters
----------
table : Table
Table to be written
filename : str
Destination for saving table.
Returns
-------
None
"""
try:
if os.path.exists(filename):
os.remove(file... |
Convert a table of data into a list of sources. | def table_to_source_list(table, src_type=OutputSource):
"""
Convert a table of data into a list of sources.
A single table must have consistent source types given by src_type. src_type should be one of
:class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`,
or :class:`Ae... |
Write a catalog ( list of sources ) to a file with format determined by extension. | def write_catalog(filename, catalog, fmt=None, meta=None, prefix=None):
"""
Write a catalog (list of sources) to a file with format determined by extension.
Sources must be of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSo... |
Convert a table into a FITSTable and then write to disk. | def writeFITSTable(filename, table):
"""
Convert a table into a FITSTable and then write to disk.
Parameters
----------
filename : str
Filename to write.
table : Table
Table to write.
Returns
-------
None
Notes
-----
Due to a bug in numpy, `int32` and ... |
Write an output file in ds9. reg format that outlines the boundaries of each island. | def writeIslandContours(filename, catalog, fmt='reg'):
"""
Write an output file in ds9 .reg format that outlines the boundaries of each island.
Parameters
----------
filename : str
Filename to write.
catalog : list
List of sources. Only those of type :class:`AegeanTools.models.... |
Write an output file in ds9. reg or kvis. ann format that contains bounding boxes for all the islands. | def writeIslandBoxes(filename, catalog, fmt):
"""
Write an output file in ds9 .reg, or kvis .ann format that contains bounding boxes for all the islands.
Parameters
----------
filename : str
Filename to write.
catalog : list
List of sources. Only those of type :class:`AegeanToo... |
Write an annotation file that can be read by Kvis (. ann ) or DS9 (. reg ). Uses ra/ dec from catalog. Draws ellipses if bmaj/ bmin/ pa are in catalog. Draws 30 circles otherwise. | def writeAnn(filename, catalog, fmt):
"""
Write an annotation file that can be read by Kvis (.ann) or DS9 (.reg).
Uses ra/dec from catalog.
Draws ellipses if bmaj/bmin/pa are in catalog. Draws 30" circles otherwise.
Only :class:`AegeanTools.models.OutputSource` will appear in the annotation file
... |
Output an sqlite3 database containing one table for each source type | def writeDB(filename, catalog, meta=None):
"""
Output an sqlite3 database containing one table for each source type
Parameters
----------
filename : str
Output filename
catalog : list
List of sources of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.... |
Calculate the normalised distance between two sources. Sources are elliptical Gaussians. | def norm_dist(src1, src2):
"""
Calculate the normalised distance between two sources.
Sources are elliptical Gaussians.
The normalised distance is calculated as the GCD distance between the centers,
divided by quadrature sum of the radius of each ellipse along a line joining the two ellipses.
... |
Great circle distance between two sources. A check is made to determine if the two sources are the same object in this case the distance is zero. | def sky_dist(src1, src2):
"""
Great circle distance between two sources.
A check is made to determine if the two sources are the same object, in this case
the distance is zero.
Parameters
----------
src1, src2 : object
Two sources to check. Objects must have parameters (ra,dec) in d... |
Do a pairwise comparison of all sources and determine if they have a normalized distance within eps. | def pairwise_ellpitical_binary(sources, eps, far=None):
"""
Do a pairwise comparison of all sources and determine if they have a normalized distance within
eps.
Form this into a matrix of shape NxN.
Parameters
----------
sources : list
A list of sources (objects with parameters: r... |
Regroup the islands of a catalog according to their normalised distance. | def regroup_vectorized(srccat, eps, far=None, dist=norm_dist):
"""
Regroup the islands of a catalog according to their normalised distance.
Assumes srccat is recarray-like for efficiency.
Return a list of island groups.
Parameters
----------
srccat : np.rec.arry or pd.DataFrame
Sho... |
Regroup the islands of a catalog according to their normalised distance. Return a list of island groups. Sources have their ( island source ) parameters relabeled. | def regroup(catalog, eps, far=None, dist=norm_dist):
"""
Regroup the islands of a catalog according to their normalised distance.
Return a list of island groups. Sources have their (island,source) parameters relabeled.
Parameters
----------
catalog : str or object
Either a filename to ... |
Load a file from disk and return an HDUList If filename is already an HDUList return that instead | def load_file_or_hdu(filename):
"""
Load a file from disk and return an HDUList
If filename is already an HDUList return that instead
Parameters
----------
filename : str or HDUList
File or HDU to be loaded
Returns
-------
hdulist : HDUList
"""
if isinstance(filenam... |
Compress a file using decimation. | def compress(datafile, factor, outfile=None):
"""
Compress a file using decimation.
Parameters
----------
datafile : str or HDUList
Input data to be loaded. (HDUList will be modified if passed).
factor : int
Decimation factor.
outfile : str
File to be written. Defa... |
Expand and interpolate the given data file using the given method. Datafile can be a filename or an HDUList | def expand(datafile, outfile=None):
"""
Expand and interpolate the given data file using the given method.
Datafile can be a filename or an HDUList
It is assumed that the file has been compressed and that there are `BN_?` keywords in the
fits header that describe how the compression was done.
... |
Strip and make a string case insensitive and ensure it is either true or false. | def change_autocommit_mode(self, switch):
"""
Strip and make a string case insensitive and ensure it is either 'true' or 'false'.
If neither, prompt user for either value.
When 'true', return True, and when 'false' return False.
"""
parsed_switch = switch.strip().lower()... |
Returns a string in ASCII Armor format for the given binary data. The output of this is compatiple with pgcrypto s armor/ dearmor functions. | def armor(data, versioned=True):
"""
Returns a string in ASCII Armor format, for the given binary data. The
output of this is compatiple with pgcrypto's armor/dearmor functions.
"""
template = '-----BEGIN PGP MESSAGE-----\n%(headers)s%(body)s\n=%(crc)s\n-----END PGP MESSAGE-----'
body = base64.b... |
Given a string in ASCII Armor format returns the decoded binary data. If verify = True ( the default ) the CRC is decoded and checked against that of the decoded data otherwise it is ignored. If the checksum does not match a BadChecksumError exception is raised. | def dearmor(text, verify=True):
"""
Given a string in ASCII Armor format, returns the decoded binary data.
If verify=True (the default), the CRC is decoded and checked against that
of the decoded data, otherwise it is ignored. If the checksum does not
match, a BadChecksumError exception is raised.
... |
Takes the last character of the text and if it is less than the block_size assumes the text is padded and removes any trailing zeros or bytes with the value of the pad character. See http:// www. di - mgt. com. au/ cryptopad. html for more information ( methods 1 3 and 4 ). | def unpad(text, block_size):
"""
Takes the last character of the text, and if it is less than the block_size,
assumes the text is padded, and removes any trailing zeros or bytes with the
value of the pad character. See http://www.di-mgt.com.au/cryptopad.html for
more information (methods 1, 3, and 4... |
Given a text string and a block size pads the text with bytes of the same value as the number of padding bytes. This is the recommended method and the one used by pgcrypto. See http:// www. di - mgt. com. au/ cryptopad. html for more information. | def pad(text, block_size, zero=False):
"""
Given a text string and a block size, pads the text with bytes of the same value
as the number of padding bytes. This is the recommended method, and the one used
by pgcrypto. See http://www.di-mgt.com.au/cryptopad.html for more information.
"""
num = bl... |
AES keys must be either 16 24 or 32 bytes long. If a key is provided that is not one of these lengths pad it with zeroes ( this is what pgcrypto does ). | def aes_pad_key(key):
"""
AES keys must be either 16, 24, or 32 bytes long. If a key is provided that is not
one of these lengths, pad it with zeroes (this is what pgcrypto does).
"""
if len(key) in (16, 24, 32):
return key
if len(key) < 16:
return pad(key, 16, zero=True)
eli... |
Deconstruct the field for Django 1. 7 + migrations. | def deconstruct(self):
"""
Deconstruct the field for Django 1.7+ migrations.
"""
name, path, args, kwargs = super(BaseEncryptedField, self).deconstruct()
kwargs.update({
#'key': self.cipher_key,
'cipher': self.cipher_name,
'charset': self.chars... |
Return a new Cipher object for each time we want to encrypt/ decrypt. This is because pgcrypto expects a zeroed block for IV ( initial value ) but the IV on the cipher object is cumulatively updated each time encrypt/ decrypt is called. | def get_cipher(self):
"""
Return a new Cipher object for each time we want to encrypt/decrypt. This is because
pgcrypto expects a zeroed block for IV (initial value), but the IV on the cipher
object is cumulatively updated each time encrypt/decrypt is called.
"""
return s... |
Better than excluding everything that is not needed collect only what is needed. | def find_packages_by_root_package(where):
"""Better than excluding everything that is not needed,
collect only what is needed.
"""
root_package = os.path.basename(where)
packages = [ "%s.%s" % (root_package, sub_package)
for sub_package in find_packages(where)]
packages.insert(0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.