sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _skyUserFromHeaderKwd(imageSet,paramDict):
"""
subtract the sky from all the chips in the imagefile that imageSet represents
imageSet is a single imageObject reference
paramDict should be the subset from an actual config object
"""
_skyValue=0.0 #this will be the sky value computed for ... | subtract the sky from all the chips in the imagefile that imageSet represents
imageSet is a single imageObject reference
paramDict should be the subset from an actual config object | entailment |
def _skySub(imageSet,paramDict,saveFile=False):
"""
subtract the sky from all the chips in the imagefile that imageSet represents
imageSet is a single imageObject reference
paramDict should be the subset from an actual config object
if saveFile=True, then images that have been sky subtracted are sa... | subtract the sky from all the chips in the imagefile that imageSet represents
imageSet is a single imageObject reference
paramDict should be the subset from an actual config object
if saveFile=True, then images that have been sky subtracted are saved to a predetermined output name
else, overwrite the i... | entailment |
def _computeSky(image, skypars, memmap=False):
"""
Compute the sky value for the data array passed to the function
image is a fits object which contains the data and the header
for one image extension
skypars is passed in as paramDict
"""
#this object contains the returned values from the... | Compute the sky value for the data array passed to the function
image is a fits object which contains the data and the header
for one image extension
skypars is passed in as paramDict | entailment |
def _subtractSky(image,skyValue,memmap=False):
"""
subtract the given sky value from each the data array
that has been passed. image is a fits object that
contains the data and header for one image extension
"""
try:
np.subtract(image.data,skyValue,image.data)
except IOError:
... | subtract the given sky value from each the data array
that has been passed. image is a fits object that
contains the data and header for one image extension | entailment |
def _updateKW(image, filename, exten, skyKW, Value):
"""update the header with the kw,value"""
# Update the value in memory
image.header[skyKW] = Value
# Now update the value on disk
if isinstance(exten,tuple):
strexten = '[%s,%s]'%(exten[0],str(exten[1]))
else:
strexten = '[%s]... | update the header with the kw,value | entailment |
def _addDefaultSkyKW(imageObjList):
"""Add MDRIZSKY keyword to "commanded" SCI headers of all input images,
if that keyword does not already exist.
"""
skyKW = "MDRIZSKY"
Value = 0.0
for imageSet in imageObjList:
fname = imageSet._filename
numchips=imageSet._numchips
... | Add MDRIZSKY keyword to "commanded" SCI headers of all input images,
if that keyword does not already exist. | entailment |
def help(file=None):
"""
Print out syntax help for running astrodrizzle
Parameters
----------
file : str (Default = None)
If given, write out help to the filename specified by this parameter
Any previously existing file with this name will be deleted before
writing out the h... | Print out syntax help for running astrodrizzle
Parameters
----------
file : str (Default = None)
If given, write out help to the filename specified by this parameter
Any previously existing file with this name will be deleted before
writing out the help. | entailment |
def rd2xy(input,ra=None,dec=None,coordfile=None,colnames=None,
precision=6,output=None,verbose=True):
""" Primary interface to perform coordinate transformations from
pixel to sky coordinates using STWCS and full distortion models
read from the input image header.
"""
single_coor... | Primary interface to perform coordinate transformations from
pixel to sky coordinates using STWCS and full distortion models
read from the input image header. | entailment |
def create_astrometric_catalog(inputs, **pars):
"""Create an astrometric catalog that covers the inputs' field-of-view.
Parameters
----------
input : str, list
Filenames of images to be aligned to astrometric catalog
catalog : str, optional
Name of catalog to extract astrometric po... | Create an astrometric catalog that covers the inputs' field-of-view.
Parameters
----------
input : str, list
Filenames of images to be aligned to astrometric catalog
catalog : str, optional
Name of catalog to extract astrometric positions for sources in the
input images' field-... | entailment |
def build_reference_wcs(inputs, sciname='sci'):
"""Create the reference WCS based on all the inputs for a field"""
# start by creating a composite field-of-view for all inputs
wcslist = []
for img in inputs:
nsci = countExtn(img)
for num in range(nsci):
extname = (sciname, nu... | Create the reference WCS based on all the inputs for a field | entailment |
def get_catalog(ra, dec, sr=0.1, fmt='CSV', catalog='GSC241'):
""" Extract catalog from VO web service.
Parameters
----------
ra : float
Right Ascension (RA) of center of field-of-view (in decimal degrees)
dec : float
Declination (Dec) of center of field-of-view (in decimal degrees... | Extract catalog from VO web service.
Parameters
----------
ra : float
Right Ascension (RA) of center of field-of-view (in decimal degrees)
dec : float
Declination (Dec) of center of field-of-view (in decimal degrees)
sr : float, optional
Search radius (in decimal degrees) ... | entailment |
def compute_radius(wcs):
"""Compute the radius from the center to the furthest edge of the WCS."""
ra, dec = wcs.wcs.crval
img_center = SkyCoord(ra=ra * u.degree, dec=dec * u.degree)
wcs_foot = wcs.calc_footprint()
img_corners = SkyCoord(ra=wcs_foot[:, 0] * u.degree,
dec=... | Compute the radius from the center to the furthest edge of the WCS. | entailment |
def find_gsc_offset(image, input_catalog='GSC1', output_catalog='GAIA'):
"""Find the GSC to GAIA offset based on guide star coordinates
Parameters
----------
image : str
Filename of image to be processed.
Returns
-------
delta_ra, delta_dec : tuple of floats
Offset in decim... | Find the GSC to GAIA offset based on guide star coordinates
Parameters
----------
image : str
Filename of image to be processed.
Returns
-------
delta_ra, delta_dec : tuple of floats
Offset in decimal degrees of image based on correction to guide star
coordinates relati... | entailment |
def extract_sources(img, **pars):
"""Use photutils to find sources in image based on segmentation.
Parameters
----------
dqmask : ndarray
Bitmask which identifies whether a pixel should be used (1) in source
identification or not(0). If provided, this mask will be applied to the
... | Use photutils to find sources in image based on segmentation.
Parameters
----------
dqmask : ndarray
Bitmask which identifies whether a pixel should be used (1) in source
identification or not(0). If provided, this mask will be applied to the
input array prior to source identificati... | entailment |
def classify_sources(catalog, sources=None):
""" Convert moments_central attribute for source catalog into star/cr flag.
This algorithm interprets the central_moments from the source_properties
generated for the sources as more-likely a star or a cosmic-ray. It is not
intended or expected to be precis... | Convert moments_central attribute for source catalog into star/cr flag.
This algorithm interprets the central_moments from the source_properties
generated for the sources as more-likely a star or a cosmic-ray. It is not
intended or expected to be precise, merely a means of making a first cut at
removi... | entailment |
def generate_source_catalog(image, **kwargs):
""" Build source catalogs for each chip using photutils.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordinate frame
defined by the reference WCS `refwcs`. The sources w... | Build source catalogs for each chip using photutils.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordinate frame
defined by the reference WCS `refwcs`. The sources will be
- identified using photutils segmentation-b... | entailment |
def generate_sky_catalog(image, refwcs, **kwargs):
"""Build source catalog from input image using photutils.
This script borrows heavily from build_source_catalog.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordina... | Build source catalog from input image using photutils.
This script borrows heavily from build_source_catalog.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordinate frame
defined by the reference WCS `refwcs`. The s... | entailment |
def compute_photometry(catalog, photmode):
""" Compute magnitudes for sources from catalog based on observations photmode.
Parameters
----------
catalog : `~astropy.table.Table`
Astropy Table with 'source_sum' column for the measured flux for each source.
photmode : str
Specificati... | Compute magnitudes for sources from catalog based on observations photmode.
Parameters
----------
catalog : `~astropy.table.Table`
Astropy Table with 'source_sum' column for the measured flux for each source.
photmode : str
Specification of the observation filter configuration used for... | entailment |
def filter_catalog(catalog, **kwargs):
""" Create a new catalog selected from input based on photometry.
Parameters
----------
bright_limit : float
Fraction of catalog based on brightness that should be retained.
Value of 1.00 means full catalog.
max_bright : int
Maximum nu... | Create a new catalog selected from input based on photometry.
Parameters
----------
bright_limit : float
Fraction of catalog based on brightness that should be retained.
Value of 1.00 means full catalog.
max_bright : int
Maximum number of sources to keep regardless of `bright_l... | entailment |
def build_self_reference(filename, clean_wcs=False):
""" This function creates a reference, undistorted WCS that can be used to
apply a correction to the WCS of the input file.
Parameters
----------
filename : str
Filename of image which will be corrected, and which will form the basis
... | This function creates a reference, undistorted WCS that can be used to
apply a correction to the WCS of the input file.
Parameters
----------
filename : str
Filename of image which will be corrected, and which will form the basis
of the undistorted WCS.
clean_wcs : bool
Spe... | entailment |
def read_hlet_wcs(filename, ext):
"""Insure `stwcs.wcsutil.HSTWCS` includes all attributes of a full image WCS.
For headerlets, the WCS does not contain information about the size of the
image, as the image array is not present in the headerlet.
"""
hstwcs = wcsutil.HSTWCS(filename, ext=ext)
if... | Insure `stwcs.wcsutil.HSTWCS` includes all attributes of a full image WCS.
For headerlets, the WCS does not contain information about the size of the
image, as the image array is not present in the headerlet. | entailment |
def build_hstwcs(crval1, crval2, crpix1, crpix2, naxis1, naxis2, pscale, orientat):
""" Create an `stwcs.wcsutil.HSTWCS` object for a default instrument without
distortion based on user provided parameter values.
"""
wcsout = wcsutil.HSTWCS()
wcsout.wcs.crval = np.array([crval1, crval2])
wcsout.... | Create an `stwcs.wcsutil.HSTWCS` object for a default instrument without
distortion based on user provided parameter values. | entailment |
def within_footprint(img, wcs, x, y):
"""Determine whether input x, y fall in the science area of the image.
Parameters
----------
img : ndarray
ndarray of image where non-science areas are marked with value of NaN.
wcs : `stwcs.wcsutil.HSTWCS`
HSTWCS or WCS object with naxis terms... | Determine whether input x, y fall in the science area of the image.
Parameters
----------
img : ndarray
ndarray of image where non-science areas are marked with value of NaN.
wcs : `stwcs.wcsutil.HSTWCS`
HSTWCS or WCS object with naxis terms defined.
x, y : ndarray
arrays ... | entailment |
def create_image_footprint(image, refwcs, border=0.):
""" Create the footprint of the image in the reference WCS frame.
Parameters
----------
image : `astropy.io.fits.HDUList` or str
Image to extract sources for matching to
the external astrometric catalog.
refwcs : `stwcs.wcsutil.... | Create the footprint of the image in the reference WCS frame.
Parameters
----------
image : `astropy.io.fits.HDUList` or str
Image to extract sources for matching to
the external astrometric catalog.
refwcs : `stwcs.wcsutil.HSTWCS`
Reference WCS for coordinate frame of image.
... | entailment |
def find_hist2d_offset(filename, reference, refwcs=None, refnames=['ra', 'dec'],
match_tolerance=5., chip_catalog=True, search_radius=15.0,
min_match=10, classify=True):
"""Iteratively look for the best cross-match between the catalog and ref.
Parameters
------... | Iteratively look for the best cross-match between the catalog and ref.
Parameters
----------
filename : `~astropy.io.fits.HDUList` or str
Single image to extract sources for matching to
the external astrometric catalog.
reference : str or `~astropy.table.Table`
... | entailment |
def build_wcscat(image, group_id, source_catalog):
""" Return a list of `~tweakwcs.tpwcs.FITSWCS` objects for all chips in an image.
Parameters
----------
image : str, ~astropy.io.fits.HDUList`
Either filename or HDUList of a single HST observation.
group_id : int
Integer ID for gr... | Return a list of `~tweakwcs.tpwcs.FITSWCS` objects for all chips in an image.
Parameters
----------
image : str, ~astropy.io.fits.HDUList`
Either filename or HDUList of a single HST observation.
group_id : int
Integer ID for group this image should be associated with; primarily
... | entailment |
def update_from_shiftfile(shiftfile,wcsname=None,force=False):
"""
Update headers of all images specified in shiftfile with shifts
from shiftfile.
Parameters
----------
shiftfile : str
Filename of shiftfile.
wcsname : str
Label to give to new WCS solution being created by t... | Update headers of all images specified in shiftfile with shifts
from shiftfile.
Parameters
----------
shiftfile : str
Filename of shiftfile.
wcsname : str
Label to give to new WCS solution being created by this fit. If
a value of None is given, it will automatically use 'TW... | entailment |
def updatewcs_with_shift(image,reference,wcsname=None, reusename=False,
fitgeom='rscale',
rot=0.0,scale=1.0,xsh=0.0,ysh=0.0,fit=None,
xrms=None, yrms = None,
verbose=False,force=False,sciext='SCI'):
"""
Update t... | Update the SCI headers in 'image' based on the fit provided as determined
in the WCS specified by 'reference'. The fit should be a 2-D matrix as
generated for use with 'make_vector_plot()'.
Notes
-----
The algorithm used to apply the provided fit solution to the image
involves applying the fol... | entailment |
def linearize(wcsim, wcsima, wcsref, imcrpix, f, shift, hx=1.0, hy=1.0):
""" linearization using 5-point formula for first order derivative
"""
x0 = imcrpix[0]
y0 = imcrpix[1]
p = np.asarray([[x0, y0],
[x0 - hx, y0],
[x0 - hx * 0.5, y0],
[... | linearization using 5-point formula for first order derivative | entailment |
def update_refchip_with_shift(chip_wcs, wcslin, fitgeom='rscale',
rot=0.0, scale=1.0, xsh=0.0, ysh=0.0,
fit=None, xrms=None, yrms=None):
""" Compute the matrix for the scale and rotation correction
Parameters
----------
chip_wcs: wcs object
... | Compute the matrix for the scale and rotation correction
Parameters
----------
chip_wcs: wcs object
HST of the input image
wcslin: wcs object
Reference WCS from which the offsets/rotations are determined
fitgeom: str
NOT USED
rot : float
Amount of rotation measur... | entailment |
def update_wcs(image,extnum,new_wcs,wcsname="",reusename=False,verbose=False):
"""
Updates the WCS of the specified extension number with the new WCS
after archiving the original WCS.
The value of 'new_wcs' needs to be the full
HSTWCS object.
Parameters
----------
image : str
F... | Updates the WCS of the specified extension number with the new WCS
after archiving the original WCS.
The value of 'new_wcs' needs to be the full
HSTWCS object.
Parameters
----------
image : str
Filename of image with WCS that needs to be updated
extnum : int
Extension numb... | entailment |
def create_unique_wcsname(fimg, extnum, wcsname):
"""
This function evaluates whether the specified wcsname value has
already been used in this image. If so, it automatically modifies
the name with a simple version ID using wcsname_NNN format.
Parameters
----------
fimg : obj
PyFIT... | This function evaluates whether the specified wcsname value has
already been used in this image. If so, it automatically modifies
the name with a simple version ID using wcsname_NNN format.
Parameters
----------
fimg : obj
PyFITS object of image with WCS information to be updated
extn... | entailment |
def get_pool_size(usr_config_value, num_tasks):
""" Determine size of thread/process-pool for parallel processing.
This examines the cpu_count to decide and return the right pool
size to use. Also take into account the user's wishes via the config
object value, if specified. On top of that, don't allo... | Determine size of thread/process-pool for parallel processing.
This examines the cpu_count to decide and return the right pool
size to use. Also take into account the user's wishes via the config
object value, if specified. On top of that, don't allow the pool size
returned to be any higher than the n... | entailment |
def init_logging(logfile=DEFAULT_LOGNAME, default=None, level=logging.INFO):
"""
Set up logger for capturing stdout/stderr messages.
Must be called prior to writing any messages that you want to log.
"""
if logfile == "INDEF":
if not is_blank(default):
logname = fileutil.buildN... | Set up logger for capturing stdout/stderr messages.
Must be called prior to writing any messages that you want to log. | entailment |
def end_logging(filename=None):
"""
Close log file and restore system defaults.
"""
if logutil.global_logging_started:
if filename:
print('Trailer file written to: ', filename)
else:
# This generally shouldn't happen if logging was started with
# init... | Close log file and restore system defaults. | entailment |
def findrootname(filename):
"""
Return the rootname of the given file.
"""
puncloc = [filename.find(char) for char in string.punctuation]
if sys.version_info[0] >= 3:
val = sys.maxsize
else:
val = sys.maxint
for num in puncloc:
if num !=-1 and num < val:
... | Return the rootname of the given file. | entailment |
def removeFileSafely(filename,clobber=True):
""" Delete the file specified, but only if it exists and clobber is True.
"""
if filename is not None and filename.strip() != '':
if os.path.exists(filename) and clobber: os.remove(filename) | Delete the file specified, but only if it exists and clobber is True. | entailment |
def displayEmptyInputWarningBox(display=True, parent=None):
""" Displays a warning box for the 'input' parameter.
"""
if sys.version_info[0] >= 3:
from tkinter.messagebox import showwarning
else:
from tkMessageBox import showwarning
if display:
msg = 'No valid input files fo... | Displays a warning box for the 'input' parameter. | entailment |
def count_sci_extensions(filename):
""" Return the number of SCI extensions and the EXTNAME from a input MEF file.
"""
num_sci = 0
extname = 'SCI'
hdu_list = fileutil.openImage(filename, memmap=False)
for extn in hdu_list:
if 'extname' in extn.header and extn.header['extname'] == extna... | Return the number of SCI extensions and the EXTNAME from a input MEF file. | entailment |
def verifyUniqueWcsname(fname,wcsname):
"""
Report whether or not the specified WCSNAME already exists in the file
"""
uniq = True
numsci,extname = count_sci_extensions(fname)
wnames = altwcs.wcsnames(fname,ext=(extname,1))
if wcsname in wnames.values():
uniq = False
return uni... | Report whether or not the specified WCSNAME already exists in the file | entailment |
def verifyUpdatewcs(fname):
"""
Verify the existence of WCSNAME in the file. If it is not present,
report this to the user and raise an exception. Returns True if WCSNAME
was found in all SCI extensions.
"""
updated = True
numsci,extname = count_sci_extensions(fname)
for n in range(1,n... | Verify the existence of WCSNAME in the file. If it is not present,
report this to the user and raise an exception. Returns True if WCSNAME
was found in all SCI extensions. | entailment |
def verifyRefimage(refimage):
"""
Verify that the value of refimage specified by the user points to an
extension with a proper WCS defined. It starts by making sure an extension gets
specified by the user when using a MEF file. The final check comes by looking
for a CD matrix in the WCS object itsel... | Verify that the value of refimage specified by the user points to an
extension with a proper WCS defined. It starts by making sure an extension gets
specified by the user when using a MEF file. The final check comes by looking
for a CD matrix in the WCS object itself. If either test fails, it returns
a ... | entailment |
def findWCSExtn(filename):
""" Return new filename with extension that points to an extension with a
valid WCS.
Returns
=======
extnum : str, None
Value of extension name as a string either as provided by the user
or based on the extension number for the firs... | Return new filename with extension that points to an extension with a
valid WCS.
Returns
=======
extnum : str, None
Value of extension name as a string either as provided by the user
or based on the extension number for the first extension which
conta... | entailment |
def verifyFilePermissions(filelist, chmod=True):
""" Verify that images specified in 'filelist' can be updated.
A message will be printed reporting the names of any images which
do not have write-permission, then quit.
"""
badfiles = []
archive_dir = False
for img in filelist:
fname... | Verify that images specified in 'filelist' can be updated.
A message will be printed reporting the names of any images which
do not have write-permission, then quit. | entailment |
def getFullParList(configObj):
"""
Return a single list of all parameter names included in the configObj
regardless of which section the parameter was stored
"""
plist = []
for par in configObj.keys():
if isinstance(configObj[par],configobj.Section):
plist.extend(getFullParLi... | Return a single list of all parameter names included in the configObj
regardless of which section the parameter was stored | entailment |
def validateUserPars(configObj,input_dict):
""" Compares input parameter names specified by user with those already
recognized by the task.
Any parameters provided by the user that does not match a known
task parameter will be reported and a ValueError exception will be
raised.
... | Compares input parameter names specified by user with those already
recognized by the task.
Any parameters provided by the user that does not match a known
task parameter will be reported and a ValueError exception will be
raised. | entailment |
def applyUserPars_steps(configObj, input_dict, step='3a'):
""" Apply logic to turn on use of user-specified output WCS if user provides
any parameter on command-line regardless of how final_wcs was set.
"""
step_kws = {'7a': 'final_wcs', '3a': 'driz_sep_wcs'}
stepname = getSectionName(configObj,... | Apply logic to turn on use of user-specified output WCS if user provides
any parameter on command-line regardless of how final_wcs was set. | entailment |
def getDefaultConfigObj(taskname,configObj,input_dict={},loadOnly=True):
""" Return default configObj instance for task updated
with user-specified values from input_dict.
Parameters
----------
taskname : string
Name of task to load into TEAL
configObj : string
... | Return default configObj instance for task updated
with user-specified values from input_dict.
Parameters
----------
taskname : string
Name of task to load into TEAL
configObj : string
The valid values for 'configObj' would be::
None ... | entailment |
def getSectionName(configObj,stepnum):
""" Return section label based on step number.
"""
for key in configObj.keys():
if key.find('STEP '+str(stepnum)+':') >= 0:
return key | Return section label based on step number. | entailment |
def displayMakewcsWarningBox(display=True, parent=None):
""" Displays a warning box for the 'makewcs' parameter.
"""
if sys.version_info[0] >= 3:
from tkinter.messagebox import showwarning
else:
from tkMessageBox import showwarning
ans = {'yes':True,'no':False}
if ans[display]:
... | Displays a warning box for the 'makewcs' parameter. | entailment |
def printParams(paramDictionary, all=False, log=None):
"""
Print nicely the parameters from the dictionary.
"""
if log is not None:
def output(msg):
log.info(msg)
else:
def output(msg):
print(msg)
if not paramDictionary:
output('No parameters wer... | Print nicely the parameters from the dictionary. | entailment |
def isCommaList(inputFilelist):
"""Return True if the input is a comma separated list of names."""
if isinstance(inputFilelist, int) or isinstance(inputFilelist, np.int32):
ilist = str(inputFilelist)
else:
ilist = inputFilelist
if "," in ilist:
return True
return False | Return True if the input is a comma separated list of names. | entailment |
def loadFileList(inputFilelist):
"""Open up the '@ file' and read in the science and possible
ivm filenames from the first two columns.
"""
f = open(inputFilelist[1:])
# check the first line in order to determine whether
# IVM files have been specified in a second column...
lines = f.read... | Open up the '@ file' and read in the science and possible
ivm filenames from the first two columns. | entailment |
def readCommaList(fileList):
""" Return a list of the files with the commas removed. """
names=fileList.split(',')
fileList=[]
for item in names:
fileList.append(item)
return fileList | Return a list of the files with the commas removed. | entailment |
def update_input(filelist, ivmlist=None, removed_files=None):
"""
Removes files flagged to be removed from the input filelist.
Removes the corresponding ivm files if present.
"""
newfilelist = []
if removed_files == []:
return filelist, ivmlist
else:
sci_ivm = list(zip(filel... | Removes files flagged to be removed from the input filelist.
Removes the corresponding ivm files if present. | entailment |
def get_expstart(header,primary_hdr):
"""shouldn't this just be defined in the instrument subclass of imageobject?"""
if 'expstart' in primary_hdr:
exphdr = primary_hdr
else:
exphdr = header
if 'EXPSTART' in exphdr:
expstart = float(exphdr['EXPSTART'])
expend = float(ex... | shouldn't this just be defined in the instrument subclass of imageobject? | entailment |
def compute_texptime(imageObjectList):
"""
Add up the exposure time for all the members in
the pattern, since 'drizzle' doesn't have the necessary
information to correctly set this itself.
"""
expnames = []
exptimes = []
start = []
end = []
for img in imageObjectList:
exp... | Add up the exposure time for all the members in
the pattern, since 'drizzle' doesn't have the necessary
information to correctly set this itself. | entailment |
def computeRange(corners):
""" Determine the range spanned by an array of pixel positions. """
x = corners[:, 0]
y = corners[:, 1]
_xrange = (np.minimum.reduce(x), np.maximum.reduce(x))
_yrange = (np.minimum.reduce(y), np.maximum.reduce(y))
return _xrange, _yrange | Determine the range spanned by an array of pixel positions. | entailment |
def getRotatedSize(corners, angle):
""" Determine the size of a rotated (meta)image."""
if angle:
_rotm = fileutil.buildRotMatrix(angle)
# Rotate about the center
_corners = np.dot(corners, _rotm)
else:
# If there is no rotation, simply return original values
_corners... | Determine the size of a rotated (meta)image. | entailment |
def readcols(infile, cols=[0, 1, 2, 3], hms=False):
"""
Read the columns from an ASCII file as numpy arrays.
Parameters
----------
infile : str
Filename of ASCII file with array data as columns.
cols : list of int
List of 0-indexed column numbers for columns to be turned into n... | Read the columns from an ASCII file as numpy arrays.
Parameters
----------
infile : str
Filename of ASCII file with array data as columns.
cols : list of int
List of 0-indexed column numbers for columns to be turned into numpy arrays
(DEFAULT- [0,1,2,3]).
Returns
-----... | entailment |
def parse_colnames(colnames,coords=None):
""" Convert colnames input into list of column numbers.
"""
cols = []
if not isinstance(colnames,list):
colnames = colnames.split(',')
# parse column names from coords file and match to input values
if coords is not None and fileutil.isFits(coord... | Convert colnames input into list of column numbers. | entailment |
def createFile(dataArray=None, outfile=None, header=None):
"""
Create a simple fits file for the given data array and header.
Returns either the FITS object in-membory when outfile==None or
None when the FITS file was written out to a file.
"""
# Insure that at least a data-array has been provid... | Create a simple fits file for the given data array and header.
Returns either the FITS object in-membory when outfile==None or
None when the FITS file was written out to a file. | entailment |
def base_taskname(taskname, packagename=None):
"""
Extract the base name of the task.
Many tasks in the `drizzlepac` have "compound" names such as
'drizzlepac.sky'. This function will search for the presence of a dot
in the input `taskname` and if found, it will return the string
to the right o... | Extract the base name of the task.
Many tasks in the `drizzlepac` have "compound" names such as
'drizzlepac.sky'. This function will search for the presence of a dot
in the input `taskname` and if found, it will return the string
to the right of the right-most dot. If a dot is not found, it will return... | entailment |
def addStep(self,key):
"""
Add information about a new step to the dict of steps
The value 'ptime' is the output from '_ptime()' containing
both the formatted and unformatted time for the start of the
step.
"""
ptime = _ptime()
print('==== Processing Step ... | Add information about a new step to the dict of steps
The value 'ptime' is the output from '_ptime()' containing
both the formatted and unformatted time for the start of the
step. | entailment |
def endStep(self,key):
"""
Record the end time for the step.
If key==None, simply record ptime as end time for class to represent
the overall runtime since the initialization of the class.
"""
ptime = _ptime()
if key is not None:
self.steps[key]['end'... | Record the end time for the step.
If key==None, simply record ptime as end time for class to represent
the overall runtime since the initialization of the class. | entailment |
def reportTimes(self):
"""
Print out a formatted summary of the elapsed times for all the
performed steps.
"""
self.end = _ptime()
total_time = 0
print(ProcSteps.__report_header)
for step in self.order:
if 'elapsed' in self.steps[step]:
... | Print out a formatted summary of the elapsed times for all the
performed steps. | entailment |
def run(configObj=None, input_dict={}, loadOnly=False):
""" Build DQ masks from all input images, then apply static mask(s).
"""
# If called from interactive user-interface, configObj will not be
# defined yet, so get defaults using EPAR/TEAL.
#
# Also insure that the input_dict (user-specified ... | Build DQ masks from all input images, then apply static mask(s). | entailment |
def buildDQMasks(imageObjectList,configObj):
""" Build DQ masks for all input images.
"""
# Insure that input imageObject is a list
if not isinstance(imageObjectList, list):
imageObjectList = [imageObjectList]
for img in imageObjectList:
img.buildMask(configObj['single'], configObj[... | Build DQ masks for all input images. | entailment |
def buildMask(dqarr, bitvalue):
""" Builds a bit-mask from an input DQ array and a bitvalue flag """
return bitfield_to_boolean_mask(dqarr, bitvalue, good_mask_value=1,
dtype=np.uint8) | Builds a bit-mask from an input DQ array and a bitvalue flag | entailment |
def buildMaskImage(rootname, bitvalue, output, extname='DQ', extver=1):
""" Builds mask image from rootname's DQ array
If there is no valid 'DQ' array in image, then return
an empty string.
"""
# If no bitvalue is set or rootname given, assume no mask is desired
# However, this name wou... | Builds mask image from rootname's DQ array
If there is no valid 'DQ' array in image, then return
an empty string. | entailment |
def buildShadowMaskImage(dqfile,detnum,extnum,maskname,bitvalue=None,binned=1):
""" Builds mask image from WFPC2 shadow calibrations.
detnum - string value for 'DETECTOR' detector
"""
# insure detnum is a string
if type(detnum) != type(''):
detnum = repr(detnum)
_funcroot = '_func_Sha... | Builds mask image from WFPC2 shadow calibrations.
detnum - string value for 'DETECTOR' detector | entailment |
def xy2rd(input,x=None,y=None,coords=None, coordfile=None,colnames=None,separator=None,
hms=True, precision=6,output=None,verbose=True):
""" Primary interface to perform coordinate transformations from
pixel to sky coordinates using STWCS and full distortion models
read from the input im... | Primary interface to perform coordinate transformations from
pixel to sky coordinates using STWCS and full distortion models
read from the input image header. | entailment |
def run(configObj, wcsmap=None):
""" Interface for running `wdrizzle` from TEAL or Python command-line.
This code performs all file ``I/O`` to set up the use of the drizzle code for
a single exposure to replicate the functionality of the original `wdrizzle`.
"""
# Insure all output filenames speci... | Interface for running `wdrizzle` from TEAL or Python command-line.
This code performs all file ``I/O`` to set up the use of the drizzle code for
a single exposure to replicate the functionality of the original `wdrizzle`. | entailment |
def mergeDQarray(maskname,dqarr):
""" Merge static or CR mask with mask created from DQ array on-the-fly here.
"""
maskarr = None
if maskname is not None:
if isinstance(maskname, str):
# working with file on disk (default case)
if os.path.exists(maskname):
... | Merge static or CR mask with mask created from DQ array on-the-fly here. | entailment |
def _setDefaults(configObj={}):
"""set up the default parameters to run drizzle
build,single,units,wt_scl,pixfrac,kernel,fillval,
rot,scale,xsh,ysh,blotnx,blotny,outnx,outny,data
Used exclusively for unit-testing, if any are defined.
"""
paramDict={"build":True,
"single... | set up the default parameters to run drizzle
build,single,units,wt_scl,pixfrac,kernel,fillval,
rot,scale,xsh,ysh,blotnx,blotny,outnx,outny,data
Used exclusively for unit-testing, if any are defined. | entailment |
def interpret_maskval(paramDict):
""" Apply logic for interpreting final_maskval value...
"""
# interpret user specified final_maskval value to use for initializing
# output SCI array...
if 'maskval' not in paramDict:
return 0
maskval = paramDict['maskval']
if maskval is None:
... | Apply logic for interpreting final_maskval value... | entailment |
def run_driz(imageObjectList,output_wcs,paramDict,single,build,wcsmap=None):
""" Perform drizzle operation on input to create output.
The input parameters originally was a list
of dictionaries, one for each input, that matches the
primary parameters for an ``IRAF`` `drizzle` task.
This method would... | Perform drizzle operation on input to create output.
The input parameters originally was a list
of dictionaries, one for each input, that matches the
primary parameters for an ``IRAF`` `drizzle` task.
This method would then loop over all the entries in the
list and run `drizzle` for each entry.
... | entailment |
def run_driz_img(img,chiplist,output_wcs,outwcs,template,paramDict,single,
num_in_prod,build,_versions,_numctx,_nplanes,chipIdxCopy,
_outsci,_outwht,_outctx,_hdrlist,wcsmap):
""" Perform the drizzle operation on a single image.
This is separated out from :py:func:`run_driz` so ... | Perform the drizzle operation on a single image.
This is separated out from :py:func:`run_driz` so as to keep together
the entirety of the code which is inside the loop over
images. See the :py:func:`run_driz` code for more documentation. | entailment |
def run_driz_chip(img,chip,output_wcs,outwcs,template,paramDict,single,
doWrite,build,_versions,_numctx,_nplanes,_numchips,
_outsci,_outwht,_outctx,_hdrlist,wcsmap):
""" Perform the drizzle operation on a single chip.
This is separated out from `run_driz_img` so as to keep to... | Perform the drizzle operation on a single chip.
This is separated out from `run_driz_img` so as to keep together
the entirety of the code which is inside the loop over
chips. See the `run_driz` code for more documentation. | entailment |
def do_driz(insci, input_wcs, inwht,
output_wcs, outsci, outwht, outcon,
expin, in_units, wt_scl,
wcslin_pscale=1.0,uniqid=1, pixfrac=1.0, kernel='square',
fillval="INDEF", stepsize=10,wcsmap=None):
"""
Core routine for performing 'drizzle' operation on a single i... | Core routine for performing 'drizzle' operation on a single input image
All input values will be Python objects such as ndarrays, instead
of filenames.
File handling (input and output) will be performed by calling routine. | entailment |
def _regwrite(shapelist,outfile):
""" Writes the current shape list out as a region file """
# This function corrects bugs and provides improvements over the pyregion's
# ShapeList.write method in the following:
#
# 1. ShapeList.write crashes if regions have no comments;
# 2. ShapeList.write con... | Writes the current shape list out as a region file | entailment |
def _needs_ref_WCS(reglist):
""" Check if the region list contains shapes in image-like coordinates
"""
from pyregion.wcs_helper import image_like_coordformats
for r in reglist:
if r.coord_format in image_like_coordformats:
return True
return False | Check if the region list contains shapes in image-like coordinates | entailment |
def extension_from_filename(filename):
"""
Parse out filename from any specified extensions.
Returns rootname and string version of extension name.
"""
# Parse out any extension specified in filename
_indx1 = filename.find('[')
_indx2 = filename.find(']')
if _indx1 > 0:
# check f... | Parse out filename from any specified extensions.
Returns rootname and string version of extension name. | entailment |
def count_extensions(img, extname='SCI'):
""" Return the number of 'extname' extensions. 'img' can be either a file
name, an HDU List object (from fits), or None (to get the number of all
HDU headers.
"""
if isinstance(img, str):
img = fits.open(img, memmap=False)
img.close()
eli... | Return the number of 'extname' extensions. 'img' can be either a file
name, an HDU List object (from fits), or None (to get the number of all
HDU headers. | entailment |
def get_extver_list(img, extname='SCI'):
""" Return a list of all extension versions of 'extname' extensions.
'img' can be either a file name or a HDU List object (from fits).
"""
if isinstance(img, str):
img = fits.open(img, memmap=False)
img.close()
elif not isinstance(img, fits.HD... | Return a list of all extension versions of 'extname' extensions.
'img' can be either a file name or a HDU List object (from fits). | entailment |
def _check_FITS_extvers(img, extname, extvers):
"""Returns True if all (except None) extension versions specified by the
argument 'extvers' and that are of the type specified by the argument
'extname' are present in the 'img' FITS file. Returns False if some of the
extension versions for a given EXTNAME... | Returns True if all (except None) extension versions specified by the
argument 'extvers' and that are of the type specified by the argument
'extname' are present in the 'img' FITS file. Returns False if some of the
extension versions for a given EXTNAME cannot be found in the FITS image. | entailment |
def run_generator(product_category,obs_info):
"""
This is the main calling subroutine. It decides which filename generation subroutine should be run based on the
input product_category, and then passes the information stored in input obs_info to the subroutine so that the
appropriate filenames can be ge... | This is the main calling subroutine. It decides which filename generation subroutine should be run based on the
input product_category, and then passes the information stored in input obs_info to the subroutine so that the
appropriate filenames can be generated.
Parameters
----------
product_catego... | entailment |
def single_exposure_product_filename_generator(obs_info,nn):
"""
Generate image and sourcelist filenames for single-exposure products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: proposal_id,
visit_id, instrument, detector, filter,... | Generate image and sourcelist filenames for single-exposure products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: proposal_id,
visit_id, instrument, detector, filter, and ipppssoot
nn : string
the single-exposure image number (... | entailment |
def filter_product_filename_generator(obs_info,nn):
"""
Generate image and sourcelist filenames for filter products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: proposal_id,
visit_id, instrument, detector, and filter
nn : strin... | Generate image and sourcelist filenames for filter products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: proposal_id,
visit_id, instrument, detector, and filter
nn : string
the single-exposure image number (NOTE: only used in
... | entailment |
def total_detection_product_filename_generator(obs_info,nn):
"""
Generate image and sourcelist filenames for total detection products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: proposal_id,
visit_id, instrument, and detector
... | Generate image and sourcelist filenames for total detection products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: proposal_id,
visit_id, instrument, and detector
nn : string
the single-exposure image number (NOTE: only used in
... | entailment |
def multivisit_mosaic_product_filename_generator(obs_info,nn):
"""
Generate image and sourcelist filenames for multi-visit mosaic products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: group_id,
instrument, detector, and filter
... | Generate image and sourcelist filenames for multi-visit mosaic products
Parameters
----------
obs_info : list
list of items that will be used to generate the filenames: group_id,
instrument, detector, and filter
nn : string
the single-exposure image number (NOTE: only used in
... | entailment |
def build_referenceWCS(catalog_list):
""" Compute default reference WCS from list of Catalog objects.
"""
wcslist = []
for catalog in catalog_list:
for scichip in catalog.catalogs:
wcslist.append(catalog.catalogs[scichip]['wcs'])
return utils.output_wcs(wcslist) | Compute default reference WCS from list of Catalog objects. | entailment |
def convex_hull(points):
"""Computes the convex hull of a set of 2D points.
Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_.
The algorithm has O(n log n) complexity.
Credit: `<http://en.wikibooks.org/wiki/Algor... | Computes the convex hull of a set of 2D points.
Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_.
The algorithm has O(n log n) complexity.
Credit: `<http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Con... | entailment |
def _estimate_2dhist_shift(imgxy, refxy, searchrad=3.0):
""" Create a 2D matrix-histogram which contains the delta between each
XY position and each UV position. Then estimate initial offset
between catalogs.
"""
print("Computing initial guess for X and Y shifts...")
# create ZP matrix
... | Create a 2D matrix-histogram which contains the delta between each
XY position and each UV position. Then estimate initial offset
between catalogs. | entailment |
def _find_peak(data, peak_fit_box=5, mask=None):
"""
Find location of the peak in an array. This is done by fitting a second
degree 2D polynomial to the data within a `peak_fit_box` and computing the
location of its maximum. An initial
estimate of the position of the maximum will be performed by sea... | Find location of the peak in an array. This is done by fitting a second
degree 2D polynomial to the data within a `peak_fit_box` and computing the
location of its maximum. An initial
estimate of the position of the maximum will be performed by searching
for the location of the pixel/array element with t... | entailment |
def openFile(self, openDQ=False):
""" Open file and set up filehandle for image file
"""
if self._im.closed:
if not self._dq.closed:
self._dq.release()
assert(self._dq.closed)
fi = FileExtMaskInfo(clobber=False,
... | Open file and set up filehandle for image file | entailment |
def get_wcs(self):
""" Helper method to return a list of all the input WCS objects associated
with this image.
"""
wcslist = []
for chip in self.chip_catalogs:
wcslist.append(self.chip_catalogs[chip]['wcs'])
return wcslist | Helper method to return a list of all the input WCS objects associated
with this image. | entailment |
def buildSkyCatalog(self):
""" Convert sky catalog for all chips into a single catalog for
the entire field-of-view of this image.
"""
self.all_radec = None
self.all_radec_orig = None
ralist = []
declist = []
fluxlist = []
idlist = []
f... | Convert sky catalog for all chips into a single catalog for
the entire field-of-view of this image. | entailment |
def buildDefaultRefWCS(self):
""" Generate a default reference WCS for this image. """
self.default_refWCS = None
if self.use_wcs:
wcslist = []
for scichip in self.chip_catalogs:
wcslist.append(self.chip_catalogs[scichip]['wcs'])
self.default_r... | Generate a default reference WCS for this image. | entailment |
def transformToRef(self,ref_wcs,force=False):
""" Transform sky coords from ALL chips into X,Y coords in reference WCS.
"""
if not isinstance(ref_wcs, pywcs.WCS):
print(textutil.textbox('Reference WCS not a valid HSTWCS object'),
file=sys.stderr)
raise V... | Transform sky coords from ALL chips into X,Y coords in reference WCS. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.