sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def qderiv(array): # TAKE THE ABSOLUTE DERIVATIVE OF A NUMARRY OBJECT
"""Take the absolute derivate of an image in memory."""
#Create 2 empty arrays in memory of the same dimensions as 'array'
tmpArray = np.zeros(array.shape,dtype=np.float64)
outArray = np.zeros(array.shape, dtype=np.float64)
# Ge... | Take the absolute derivate of an image in memory. | entailment |
def randomSelectFromCSV(tableName, numEntries, seedValue):
"""Function to extract random entries (lines) from a CSV file
Parameters
==========
tableName: str
Filename of the input master CSV file containing individual
images or association names, as well as observational
informa... | Function to extract random entries (lines) from a CSV file
Parameters
==========
tableName: str
Filename of the input master CSV file containing individual
images or association names, as well as observational
information regarding the images
numEntries : int
Number of ... | entailment |
def get_hstwcs(filename,hdulist,extnum):
""" Return the HSTWCS object for a given chip. """
hdrwcs = wcsutil.HSTWCS(hdulist,ext=extnum)
hdrwcs.filename = filename
hdrwcs.expname = hdulist[extnum].header['expname']
hdrwcs.extver = hdulist[extnum].header['extver']
return hdrwcs | Return the HSTWCS object for a given chip. | entailment |
def update_linCD(cdmat, delta_rot=0.0, delta_scale=1.0, cx=[0.0,1.0], cy=[1.0,0.0]):
""" Modify an existing linear CD matrix with rotation and/or scale changes
and return a new CD matrix. If 'cx' and 'cy' are specified, it will
return a distorted CD matrix.
Only those terms which are varyi... | Modify an existing linear CD matrix with rotation and/or scale changes
and return a new CD matrix. If 'cx' and 'cy' are specified, it will
return a distorted CD matrix.
Only those terms which are varying need to be specified on input. | entailment |
def create_CD(orient, scale, cx=None, cy=None):
""" Create a (un?)distorted CD matrix from the basic inputs.
The 'cx' and 'cy' parameters, if given, provide the X and Y coefficients of
the distortion as returned by reading the IDCTAB. Only the first 2 elements
are used and should correspond to the 'OC... | Create a (un?)distorted CD matrix from the basic inputs.
The 'cx' and 'cy' parameters, if given, provide the X and Y coefficients of
the distortion as returned by reading the IDCTAB. Only the first 2 elements
are used and should correspond to the 'OC[X/Y]10' and 'OC[X/Y]11' terms in that
order as read... | entailment |
def ddtohms(xsky,ysky,verbose=False,precision=6):
""" Convert sky position(s) from decimal degrees to HMS format. """
xskyh = xsky /15.
xskym = (xskyh - np.floor(xskyh)) * 60.
xskys = (xskym - np.floor(xskym)) * 60.
yskym = (np.abs(ysky) - np.floor(np.abs(ysky))) * 60.
yskys = (yskym - np.floor(... | Convert sky position(s) from decimal degrees to HMS format. | entailment |
def make_outputwcs(imageObjectList, output, configObj=None, perfect=False):
""" Computes the full output WCS based on the set of input imageObjects
provided as input, along with the pre-determined output name from
process_input. The user specified output parameters are then used to
modify t... | Computes the full output WCS based on the set of input imageObjects
provided as input, along with the pre-determined output name from
process_input. The user specified output parameters are then used to
modify the default WCS to produce the final desired output frame.
The input imageObj... | entailment |
def make_perfect_cd(wcs):
""" Create a perfect (square, orthogonal, undistorted) CD matrix from the
input WCS.
"""
def_scale = (wcs.pscale) / 3600.
def_orientat = np.deg2rad(wcs.orientat)
perfect_cd = def_scale * np.array(
[[-np.cos(def_orientat),np.sin(def_orientat)],
[np.s... | Create a perfect (square, orthogonal, undistorted) CD matrix from the
input WCS. | entailment |
def calcNewEdges(wcs, shape):
"""
This method will compute sky coordinates for all the pixels around
the edge of an image AFTER applying the geometry model.
Parameters
----------
wcs : obj
HSTWCS object for image
shape : tuple
numpy shape tuple for size of image
Return... | This method will compute sky coordinates for all the pixels around
the edge of an image AFTER applying the geometry model.
Parameters
----------
wcs : obj
HSTWCS object for image
shape : tuple
numpy shape tuple for size of image
Returns
-------
border : arr
arr... | entailment |
def createWCSObject(output,default_wcs,imageObjectList):
"""Converts a PyWCS WCS object into a WCSObject(baseImageObject) instance."""
from . import imageObject
outwcs = imageObject.WCSObject(output)
outwcs.default_wcs = default_wcs
outwcs.wcs = default_wcs.copy()
outwcs.final_wcs = default_wcs.... | Converts a PyWCS WCS object into a WCSObject(baseImageObject) instance. | entailment |
def removeAllAltWCS(hdulist,extlist):
"""
Removes all alternate WCS solutions from the header
"""
original_logging_level = log.level
log.setLevel(logutil.logging.WARNING)
try:
hdr = hdulist[extlist[0]].header
wkeys = altwcs.wcskeys(hdr)
if ' ' in wkeys:
wkeys... | Removes all alternate WCS solutions from the header | entailment |
def restoreDefaultWCS(imageObjectList, output_wcs):
""" Restore WCS information to default values, and update imageObject
accordingly.
"""
if not isinstance(imageObjectList,list):
imageObjectList = [imageObjectList]
output_wcs.restoreWCS()
updateImageWCS(imageObjectList, output_wcs... | Restore WCS information to default values, and update imageObject
accordingly. | entailment |
def _py2round(x):
"""
This function returns a rounded up value of the argument, similar
to Python 2.
"""
if hasattr(x, '__iter__'):
rx = np.empty_like(x)
m = x >= 0.0
rx[m] = np.floor(x[m] + 0.5)
m = np.logical_not(m)
rx[m] = np.ceil(x[m] - 0.5)
return... | This function returns a rounded up value of the argument, similar
to Python 2. | entailment |
def mergeWCS(default_wcs, user_pars):
""" Merges the user specified WCS values given as dictionary derived from
the input configObj object with the output PyWCS object computed
using distortion.output_wcs().
The user_pars dictionary needs to have the following set of keys::
use... | Merges the user specified WCS values given as dictionary derived from
the input configObj object with the output PyWCS object computed
using distortion.output_wcs().
The user_pars dictionary needs to have the following set of keys::
user_pars = {'ra':None,'dec':None,'scale':None,'r... | entailment |
def convertWCS(inwcs,drizwcs):
""" Copy WCSObject WCS into Drizzle compatible array."""
drizwcs[0] = inwcs.crpix[0]
drizwcs[1] = inwcs.crval[0]
drizwcs[2] = inwcs.crpix[1]
drizwcs[3] = inwcs.crval[1]
drizwcs[4] = inwcs.cd[0][0]
drizwcs[5] = inwcs.cd[1][0]
drizwcs[6] = inwcs.cd[0][1]
... | Copy WCSObject WCS into Drizzle compatible array. | entailment |
def updateWCS(drizwcs,inwcs):
""" Copy output WCS array from Drizzle into WCSObject."""
crpix = np.array([drizwcs[0],drizwcs[2]], dtype=np.float64)
crval = np.array([drizwcs[1],drizwcs[3]], dtype=np.float64)
cd = np.array([[drizwcs[4],drizwcs[6]],[drizwcs[5],drizwcs[7]]], dtype=np.float64)
inwcs.cd ... | Copy output WCS array from Drizzle into WCSObject. | entailment |
def wcsfit(img_wcs, ref_wcs):
"""
Perform a linear fit between 2 WCS for shift, rotation and scale.
Based on the WCSLIN function from 'drutil.f'(Drizzle V2.9) and modified to
allow for differences in reference positions assumed by PyDrizzle's
distortion model and the coeffs used by 'drizzle'.
P... | Perform a linear fit between 2 WCS for shift, rotation and scale.
Based on the WCSLIN function from 'drutil.f'(Drizzle V2.9) and modified to
allow for differences in reference positions assumed by PyDrizzle's
distortion model and the coeffs used by 'drizzle'.
Parameters
----------
img : obj
... | entailment |
def fitlin(imgarr,refarr):
""" Compute the least-squares fit between two arrays.
A Python translation of 'FITLIN' from 'drutil.f' (Drizzle V2.9).
"""
# Initialize variables
_mat = np.zeros((3,3),dtype=np.float64)
_xorg = imgarr[0][0]
_yorg = imgarr[0][1]
_xoorg = refarr[0][0]
_yo... | Compute the least-squares fit between two arrays.
A Python translation of 'FITLIN' from 'drutil.f' (Drizzle V2.9). | entailment |
def fitlin_rscale(xy,uv,verbose=False):
""" Performs a linear, orthogonal fit between matched
lists of positions 'xy' (input) and 'uv' (output).
Output: (same as for fit_arrays_general)
"""
mu = uv[:,0].mean()
mv = uv[:,1].mean()
mx = xy[:,0].mean()
my = xy[:,1].mean()
u = ... | Performs a linear, orthogonal fit between matched
lists of positions 'xy' (input) and 'uv' (output).
Output: (same as for fit_arrays_general) | entailment |
def fitlin_clipped(xy,uv,verbose=False,mode='rscale',nclip=3,reject=3):
""" Perform a clipped fit based on the number of iterations and rejection limit
(in sigma) specified by the user. This will more closely replicate the results
obtained by 'geomap' using 'maxiter' and 'reject' parameters.
"""... | Perform a clipped fit based on the number of iterations and rejection limit
(in sigma) specified by the user. This will more closely replicate the results
obtained by 'geomap' using 'maxiter' and 'reject' parameters. | entailment |
def readAltWCS(fobj, ext, wcskey=' ', verbose=False):
"""
Reads in alternate primary WCS from specified extension.
Parameters
----------
fobj : str, `astropy.io.fits.HDUList`
fits filename or fits file object
containing alternate/primary WCS(s) to be converted
wcskey : str
... | Reads in alternate primary WCS from specified extension.
Parameters
----------
fobj : str, `astropy.io.fits.HDUList`
fits filename or fits file object
containing alternate/primary WCS(s) to be converted
wcskey : str
[" ",A-Z]
alternate/primary WCS key that will be replac... | entailment |
def forward(self,pixx,pixy):
""" Transform the input pixx,pixy positions in the input frame
to pixel positions in the output frame.
This method gets passed to the drizzle algorithm.
"""
# This matches WTRAXY results to better than 1e-4 pixels.
skyx,skyy = self.in... | Transform the input pixx,pixy positions in the input frame
to pixel positions in the output frame.
This method gets passed to the drizzle algorithm. | entailment |
def backward(self,pixx,pixy):
""" Transform pixx,pixy positions from the output frame back onto their
original positions in the input frame.
"""
skyx,skyy = self.output.wcs_pix2world(pixx,pixy,self.origin)
result = self.input.all_world2pix(skyx,skyy,self.origin)
retur... | Transform pixx,pixy positions from the output frame back onto their
original positions in the input frame. | entailment |
def createMask(input=None, static_sig=4.0, group=None, editpars=False, configObj=None, **inputDict):
""" The user can input a list of images if they like to create static masks
as well as optional values for static_sig and inputDict.
The configObj.cfg file will set the defaults and then override th... | The user can input a list of images if they like to create static masks
as well as optional values for static_sig and inputDict.
The configObj.cfg file will set the defaults and then override them
with the user options. | entailment |
def constructFilename(signature):
"""Construct an output filename for the given signature::
signature=[instr+detector,(nx,ny),detnum]
The signature is in the image object.
"""
suffix = buildSignatureKey(signature)
filename = os.path.join('.', suffix)
return filename | Construct an output filename for the given signature::
signature=[instr+detector,(nx,ny),detnum]
The signature is in the image object. | entailment |
def addMember(self, imagePtr=None):
"""
Combines the input image with the static mask that
has the same signature.
Parameters
----------
imagePtr : object
An imageObject reference
Notes
-----
The signature parameter consists of the tu... | Combines the input image with the static mask that
has the same signature.
Parameters
----------
imagePtr : object
An imageObject reference
Notes
-----
The signature parameter consists of the tuple::
(instrument/detector, (nx,ny), chip_i... | entailment |
def getMaskArray(self, signature):
""" Returns the appropriate StaticMask array for the image. """
if signature in self.masklist:
mask = self.masklist[signature]
else:
mask = None
return mask | Returns the appropriate StaticMask array for the image. | entailment |
def getFilename(self,signature):
"""Returns the name of the output mask file that
should reside on disk for the given signature. """
filename=constructFilename(signature)
if(fileutil.checkFileExists(filename)):
return filename
else:
print("\nmMask file f... | Returns the name of the output mask file that
should reside on disk for the given signature. | entailment |
def close(self):
""" Deletes all static mask objects. """
for key in self.masklist.keys():
self.masklist[key] = None
self.masklist = {} | Deletes all static mask objects. | entailment |
def deleteMask(self,signature):
""" Delete just the mask that matches the signature given."""
if signature in self.masklist:
self.masklist[signature] = None
else:
log.warning("No matching mask") | Delete just the mask that matches the signature given. | entailment |
def saveToFile(self,imageObjectList):
""" Saves the static mask to a file
it uses the signatures associated with each
mask to contruct the filename for the output mask image.
"""
virtual = imageObjectList[0].inmemory
for key in self.masklist.keys():
#... | Saves the static mask to a file
it uses the signatures associated with each
mask to contruct the filename for the output mask image. | entailment |
def expand_image(image, shape):
""" Expand image from original shape to requested shape. Output shape
must be an integer multiple of input image shape for each axis. """
if (shape[0] % image.shape[0]) or (shape[1] % image.shape[1]):
raise ValueError("Output shape must be an integer multiple of input... | Expand image from original shape to requested shape. Output shape
must be an integer multiple of input image shape for each axis. | entailment |
def bilinear_interp(data, x, y):
""" Interpolate input ``data`` at "pixel" coordinates ``x`` and ``y``. """
x = np.asarray(x)
y = np.asarray(y)
if x.shape != y.shape:
raise ValueError("X- and Y-coordinates must have identical shapes.")
out_shape = x.shape
out_size = x.size
x = x.rav... | Interpolate input ``data`` at "pixel" coordinates ``x`` and ``y``. | entailment |
def getflat(self, chip):
"""
Method for retrieving a detector's flat field. For STIS there are three.
This method will return an array the same shape as the image.
"""
sci_chip = self._image[self.scienceExt,chip]
exten = self.errExt+','+str(chip)
# The keyword f... | Method for retrieving a detector's flat field. For STIS there are three.
This method will return an array the same shape as the image. | entailment |
def _assignSignature(self, chip):
"""Assign a unique signature for the image based
on the instrument, detector, chip, and size
this will be used to uniquely identify the appropriate
static mask for the image.
This also records the filename for the static mask to the... | Assign a unique signature for the image based
on the instrument, detector, chip, and size
this will be used to uniquely identify the appropriate
static mask for the image.
This also records the filename for the static mask to the outputNames dictionary. | entailment |
def getReadNoise(self):
"""
Method for returning the readnoise of a detector (in DN).
:units: DN
This should work on a chip, since different chips to be consistant with other
detector classes where different chips have different gains.
"""
if self.proc_unit == ... | Method for returning the readnoise of a detector (in DN).
:units: DN
This should work on a chip, since different chips to be consistant with other
detector classes where different chips have different gains. | entailment |
def setInstrumentParameters(self, instrpars):
""" This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
"""
pri_header = self._image[0].header
if self._isNotValid (instrpars['gain'], instrpars['gnkeyword... | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | entailment |
def doUnitConversions(self):
"""Convert the data to electrons.
This converts all science data extensions and saves
the results back to disk. We need to make sure
the data inside the chips already in memory is altered as well.
"""
for det in range(1,self._numchips+1,1):
... | Convert the data to electrons.
This converts all science data extensions and saves
the results back to disk. We need to make sure
the data inside the chips already in memory is altered as well. | entailment |
def setInstrumentParameters(self, instrpars):
""" This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
"""
pri_header = self._image[0].header
usingDefaultGain = False
usingDefaultReadnoise = Fals... | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | entailment |
def analyze_data(inputFileList, **kwargs):
"""
Determine if images within the dataset can be aligned
Parameters
==========
inputFileList: list
List containing FLT and/or FLC filenames for all input images which comprise an associated
dataset where 'associated dataset' may be a singl... | Determine if images within the dataset can be aligned
Parameters
==========
inputFileList: list
List containing FLT and/or FLC filenames for all input images which comprise an associated
dataset where 'associated dataset' may be a single image, multiple images, an HST association,
o... | entailment |
def generate_msg(filename, msg, key, value):
""" Generate a message for the output log indicating the file/association will not
be processed as the characteristics of the data are known to be inconsistent
with alignment.
"""
log.info('Dataset ' + filename + ' has (keyword = value) of (' + k... | Generate a message for the output log indicating the file/association will not
be processed as the characteristics of the data are known to be inconsistent
with alignment. | entailment |
def drizCR(input=None, configObj=None, editpars=False, **inputDict):
""" Look for cosmic rays. """
log.debug(inputDict)
inputDict["input"] = input
configObj = util.getDefaultConfigObj(__taskname__, configObj, inputDict,
loadOnly=(not editpars))
if configObj i... | Look for cosmic rays. | entailment |
def _driz_cr(sciImage, virtual_outputs, paramDict):
"""mask blemishes in dithered data by comparison of an image
with a model image and the derivative of the model image.
- ``sciImage`` is an imageObject which contains the science data
- ``blotImage`` is inferred from the ``sciImage`` object here which... | mask blemishes in dithered data by comparison of an image
with a model image and the derivative of the model image.
- ``sciImage`` is an imageObject which contains the science data
- ``blotImage`` is inferred from the ``sciImage`` object here which knows
the name of its blotted image
- ``chip``... | entailment |
def createCorrFile(outfile, arrlist, template):
"""
Create a _cor file with the same format as the original input image.
The DQ array will be replaced with the mask array used to create the _cor
file.
"""
# Remove the existing cor file if it exists
if os.path.isfile(outfile):
os.rem... | Create a _cor file with the same format as the original input image.
The DQ array will be replaced with the mask array used to create the _cor
file. | entailment |
def setDefaults(configObj={}):
""" Return a dictionary of the default parameters
which also been updated with the user overrides.
"""
paramDict = {
'gain': 7, # Detector gain, e-/ADU
'grow': 1, # Radius around CR pixel to mask [default=1 for
... | Return a dictionary of the default parameters
which also been updated with the user overrides. | 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 t... | 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 getHelpAsString(docstring=False, show_ver=True):
"""
Return useful help from a file in the script directory called
``__taskname__.help``
"""
install_dir = os.path.dirname(__file__)
taskname = util.base_taskname(__taskname__, __package__)
htmlfile = os.path.join(install_dir, 'htmlhelp', ... | Return useful help from a file in the script directory called
``__taskname__.help`` | entailment |
def setCommonInput(configObj, createOutwcs=True):
"""
The common interface interpreter for MultiDrizzle tasks which not only runs
'process_input()' but 'createImageObject()' and 'defineOutput()' as well to
fully setup all inputs for use with the rest of the MultiDrizzle steps either
as stand-alone t... | The common interface interpreter for MultiDrizzle tasks which not only runs
'process_input()' but 'createImageObject()' and 'defineOutput()' as well to
fully setup all inputs for use with the rest of the MultiDrizzle steps either
as stand-alone tasks or internally to MultiDrizzle itself.
Parameters
... | entailment |
def reportResourceUsage(imageObjectList, outwcs, num_cores,
interactive=False):
""" Provide some information to the user on the estimated resource
usage (primarily memory) for this run.
"""
from . import imageObject
if outwcs is None:
output_mem = 0
else:
... | Provide some information to the user on the estimated resource
usage (primarily memory) for this run. | entailment |
def getMdriztabPars(input):
""" High-level function for getting the parameters from MDRIZTAB
Used primarily for TEAL interface.
"""
filelist,output,ivmlist,oldasndict=processFilenames(input,None)
try:
mdrizdict = mdzhandler.getMdriztabParameters(filelist)
except KeyError:
print... | High-level function for getting the parameters from MDRIZTAB
Used primarily for TEAL interface. | entailment |
def addIVMInputs(imageObjectList,ivmlist):
""" Add IVM filenames provided by user to outputNames dictionary for each input imageObject.
"""
if ivmlist is None:
return
for img,ivmname in zip(imageObjectList,ivmlist):
img.updateIVMName(ivmname) | Add IVM filenames provided by user to outputNames dictionary for each input imageObject. | entailment |
def checkMultipleFiles(input):
""" Evaluates the input to determine whether there is 1 or more than 1 valid input file.
"""
f,i,o,a=buildFileList(input)
return len(f) > 1 | Evaluates the input to determine whether there is 1 or more than 1 valid input file. | entailment |
def createImageObjectList(files,instrpars,group=None,
undistort=True, inmemory=False):
""" Returns a list of imageObject instances, 1 for each input image in the list of input filenames.
"""
imageObjList = []
mtflag = False
mt_refimg = None
for img in files:
i... | Returns a list of imageObject instances, 1 for each input image in the list of input filenames. | entailment |
def _getInputImage (input,group=None):
""" Factory function to return appropriate imageObject class instance"""
# extract primary header and SCI,1 header from input image
sci_ext = 'SCI'
if group in [None,'']:
exten = '[sci,1]'
phdu = fits.getheader(input, memmap=False)
else:
... | Factory function to return appropriate imageObject class instance | entailment |
def processFilenames(input=None,output=None,infilesOnly=False):
"""Process the input string which contains the input file information and
return a filelist,output
"""
ivmlist = None
oldasndict = None
if input is None:
print("No input files provided to processInput")
raise Val... | Process the input string which contains the input file information and
return a filelist,output | entailment |
def process_input(input, output=None, ivmlist=None, updatewcs=True,
prodonly=False, wcskey=None, **workinplace):
"""
Create the full input list of filenames after verifying and converting
files as needed.
"""
newfilelist, ivmlist, output, oldasndict, origflist = buildFileListOrig... | Create the full input list of filenames after verifying and converting
files as needed. | entailment |
def _process_input_wcs(infiles, wcskey, updatewcs):
"""
This is a subset of process_input(), for internal use only. This is the
portion of input handling which sets/updates WCS data, and is a performance
hit - a target for parallelization. Returns the expanded list of filenames.
"""
# Run pars... | This is a subset of process_input(), for internal use only. This is the
portion of input handling which sets/updates WCS data, and is a performance
hit - a target for parallelization. Returns the expanded list of filenames. | entailment |
def _process_input_wcs_single(fname, wcskey, updatewcs):
"""
See docs for _process_input_wcs.
This is separated to be spawned in parallel.
"""
if wcskey in ['', ' ', 'INDEF', None]:
if updatewcs:
uw.updatewcs(fname, checkfiles=False)
else:
numext = fileutil.countExtn(... | See docs for _process_input_wcs.
This is separated to be spawned in parallel. | entailment |
def buildFileList(input, output=None, ivmlist=None,
wcskey=None, updatewcs=True, **workinplace):
"""
Builds a file list which has undergone various instrument-specific
checks for input to MultiDrizzle, including splitting STIS associations.
"""
newfilelist, ivmlist, output, oldasndic... | Builds a file list which has undergone various instrument-specific
checks for input to MultiDrizzle, including splitting STIS associations. | entailment |
def buildFileListOrig(input, output=None, ivmlist=None,
wcskey=None, updatewcs=True, **workinplace):
"""
Builds a file list which has undergone various instrument-specific
checks for input to MultiDrizzle, including splitting STIS associations.
Compared to buildFileList, this version ret... | Builds a file list which has undergone various instrument-specific
checks for input to MultiDrizzle, including splitting STIS associations.
Compared to buildFileList, this version returns the list of the
original file names as specified by the user (e.g., before GEIS->MEF, or
WAIVER FITS->MEF conversion... | entailment |
def buildASNList(rootnames, asnname, check_for_duplicates=True):
"""
Return the list of filenames for a given set of rootnames
"""
# Recognize when multiple valid inputs with the same rootname are present
# this would happen when both CTE-corrected (_flc) and non-CTE-corrected (_flt)
# products... | Return the list of filenames for a given set of rootnames | entailment |
def changeSuffixinASN(asnfile, suffix):
"""
Create a copy of the original asn file and change the name of all members
to include the suffix.
"""
# Start by creating a new name for the ASN table
_new_asn = asnfile.replace('_asn.fits','_'+suffix+'_asn.fits')
if os.path.exists(_new_asn):
... | Create a copy of the original asn file and change the name of all members
to include the suffix. | entailment |
def checkForDuplicateInputs(rootnames):
"""
Check input files specified in ASN table for duplicate versions with
multiple valid suffixes (_flt and _flc, for example).
"""
flist = []
duplist = []
for fname in rootnames:
# Look for any recognized CTE-corrected products
f1 = f... | Check input files specified in ASN table for duplicate versions with
multiple valid suffixes (_flt and _flc, for example). | entailment |
def resetDQBits(imageObjectList, cr_bits_value=4096):
"""Reset the CR bit in each input image's DQ array"""
if cr_bits_value > 0:
for img in imageObjectList:
for chip in range(1,img._numchips+1,1):
sci_chip = img._image[img.scienceExt,chip]
resetbits.reset_dq... | Reset the CR bit in each input image's DQ array | entailment |
def update_member_names(oldasndict, pydr_input):
"""
Update names in a member dictionary.
Given an association dictionary with rootnames and a list of full
file names, it will update the names in the member dictionary to
contain '_*' extension. For example a rootname of 'u9600201m' will
be repl... | Update names in a member dictionary.
Given an association dictionary with rootnames and a list of full
file names, it will update the names in the member dictionary to
contain '_*' extension. For example a rootname of 'u9600201m' will
be replaced by 'u9600201m_c0h' making sure that a MEf file is passed... | entailment |
def manageInputCopies(filelist, **workinplace):
"""
Creates copies of all input images in a sub-directory.
The copies are made prior to any processing being done to the images at all,
including updating the WCS keywords. If there are already copies present,
they will NOT be overwritten, but instead... | Creates copies of all input images in a sub-directory.
The copies are made prior to any processing being done to the images at all,
including updating the WCS keywords. If there are already copies present,
they will NOT be overwritten, but instead will be used to over-write the
current working copies. | entailment |
def buildEmptyDRZ(input, output):
"""
Create an empty DRZ file.
This module creates an empty DRZ file in a valid FITS format so that the HST
pipeline can handle the Multidrizzle zero expossure time exception
where all data has been excluded from processing.
Parameters
----------
input ... | Create an empty DRZ file.
This module creates an empty DRZ file in a valid FITS format so that the HST
pipeline can handle the Multidrizzle zero expossure time exception
where all data has been excluded from processing.
Parameters
----------
input : str
filename of the initial input to... | entailment |
def checkDGEOFile(filenames):
"""
Verify that input file has been updated with NPOLFILE
This function checks for the presence of 'NPOLFILE' kw in the primary header
when 'DGEOFILE' kw is present and valid (i.e. 'DGEOFILE' is not blank or 'N/A').
It handles the case of science files downloaded from ... | Verify that input file has been updated with NPOLFILE
This function checks for the presence of 'NPOLFILE' kw in the primary header
when 'DGEOFILE' kw is present and valid (i.e. 'DGEOFILE' is not blank or 'N/A').
It handles the case of science files downloaded from the archive before the new
software wa... | entailment |
def _setDefaults(input_dict={}):
""" Define full set of default values for unit-testing this module.[OBSOLETE]"""
paramDict = {
'input':'*flt.fits',
'output':None,
'mdriztab':None,
'refimage':None,
'runfile':None,
'workinplace':False,
'updatewcs':True,
... | Define full set of default values for unit-testing this module.[OBSOLETE] | entailment |
def getdarkimg(self,chip):
"""
Return an array representing the dark image for the detector.
Returns
-------
dark : array
The dark array in the same shape as the image with **units of cps**.
"""
# Read the temperature dependeant dark file. The name... | Return an array representing the dark image for the detector.
Returns
-------
dark : array
The dark array in the same shape as the image with **units of cps**. | entailment |
def isCountRate(self):
"""
isCountRate: Method or IRInputObject used to indicate if the
science data is in units of counts or count rate. This method
assumes that the keyword 'BUNIT' is in the header of the input
FITS file.
"""
has_bunit = False
if 'BUNIT... | isCountRate: Method or IRInputObject used to indicate if the
science data is in units of counts or count rate. This method
assumes that the keyword 'BUNIT' is in the header of the input
FITS file. | entailment |
def setInstrumentParameters(self, instrpars):
""" This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
"""
pri_header = self._image[0].header
self.proc_unit = instrpars['proc_unit']
if self._isN... | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | entailment |
def photeq(files='*_flt.fits', sciext='SCI', errext='ERR',
ref_phot=None, ref_phot_ext=None,
phot_kwd='PHOTFLAM', aux_phot_kwd='PHOTFNU',
search_primary=True,
readonly=True, clobber=False, logfile='photeq.log'):
"""
Adjust data values of images by equalizing each chip... | Adjust data values of images by equalizing each chip's PHOTFLAM value
to a single common value so that all chips can be treated equally
by ``AstroDrizzle``.
Parameters
----------
files : str (Default = ``'*_flt.fits'``)
A string containing one of the following:
* a comma-sepa... | entailment |
def _managePsets(configobj, section_name, task_name, iparsobj=None, input_dict=None):
""" Read in parameter values from PSET-like configobj tasks defined for
source-finding algorithms, and any other PSET-like tasks under this task,
and merge those values into the input configobj dictionary.
"""
... | Read in parameter values from PSET-like configobj tasks defined for
source-finding algorithms, and any other PSET-like tasks under this task,
and merge those values into the input configobj dictionary. | entailment |
def edit_imagefindpars():
""" Allows the user to edit the imagefindpars configObj in a TEAL GUI
"""
teal.teal(imagefindpars.__taskname__, returnAs=None,
autoClose=True, loadOnly=False, canExecute=False) | Allows the user to edit the imagefindpars configObj in a TEAL GUI | entailment |
def edit_refimagefindpars():
""" Allows the user to edit the refimagefindpars configObj in a TEAL GUI
"""
teal.teal(refimagefindpars.__taskname__, returnAs=None,
autoClose=True, loadOnly=False, canExecute=False) | Allows the user to edit the refimagefindpars configObj in a TEAL GUI | entailment |
def run(configobj):
""" Primary Python interface for image registration code
This task replaces 'tweakshifts'
"""
print('TweakReg Version %s(%s) started at: %s \n'%(
__version__,__version_date__,util._ptime()[0]))
util.print_pkg_versions()
# make sure 'updatewcs' is set ... | Primary Python interface for image registration code
This task replaces 'tweakshifts' | entailment |
def print_rev_id(localRepoPath):
"""prints information about the specified local repository to STDOUT. Expected method of execution: command-line or
shell script call
Parameters
----------
localRepoPath: string
Local repository path.
Returns
=======
Nothing as such. subroutine ... | prints information about the specified local repository to STDOUT. Expected method of execution: command-line or
shell script call
Parameters
----------
localRepoPath: string
Local repository path.
Returns
=======
Nothing as such. subroutine will exit with a state of 0 if everythin... | entailment |
def get_rev_id(localRepoPath):
"""returns the current full git revision id of the specified local repository. Expected method of execution: python
subroutine call
Parameters
----------
localRepoPath: string
Local repository path.
Returns
=======
full git revision ID of the spec... | returns the current full git revision id of the specified local repository. Expected method of execution: python
subroutine call
Parameters
----------
localRepoPath: string
Local repository path.
Returns
=======
full git revision ID of the specified repository if everything ran OK,... | entailment |
def update(input,refdir="jref$",local=None,interactive=False,wcsupdate=True):
"""
Updates headers of files given as input to point to the new reference files
NPOLFILE and D2IMFILE required with the new C version of MultiDrizzle.
Parameters
-----------
input : string or list
Name... | Updates headers of files given as input to point to the new reference files
NPOLFILE and D2IMFILE required with the new C version of MultiDrizzle.
Parameters
-----------
input : string or list
Name of input file or files acceptable forms:
- single filename with or with... | entailment |
def find_d2ifile(flist,detector):
""" Search a list of files for one that matches the detector specified.
"""
d2ifile = None
for f in flist:
fdet = fits.getval(f, 'detector', memmap=False)
if fdet == detector:
d2ifile = f
return d2ifile | Search a list of files for one that matches the detector specified. | entailment |
def find_npolfile(flist,detector,filters):
""" Search a list of files for one that matches the configuration
of detector and filters used.
"""
npolfile = None
for f in flist:
fdet = fits.getval(f, 'detector', memmap=False)
if fdet == detector:
filt1 = fits.getval(f, '... | Search a list of files for one that matches the configuration
of detector and filters used. | entailment |
def run(configobj=None,editpars=False):
""" Teal interface for running this code.
"""
if configobj is None:
configobj =teal.teal(__taskname__,loadOnly=(not editpars))
update(configobj['input'],configobj['refdir'],
local=configobj['local'],interactive=configobj['interactive'],
w... | Teal interface for running this code. | entailment |
def retrieve_observation(obsid, suffix=['FLC'], archive=False,clobber=False):
"""Simple interface for retrieving an observation from the MAST archive
If the input obsid is for an association, it will request all members with
the specified suffixes.
Parameters
-----------
obsid : string
... | Simple interface for retrieving an observation from the MAST archive
If the input obsid is for an association, it will request all members with
the specified suffixes.
Parameters
-----------
obsid : string
ID for observation to be retrieved from the MAST archive. Only the
IPPSSOOT... | entailment |
def reset_dq_bits(input,bits,extver=None,extname='dq'):
""" This function resets bits in the integer array(s) of a FITS file.
Parameters
----------
filename : str
full filename with path
bits : str
sum or list of integers corresponding to all the bits to be reset
extver : int,... | This function resets bits in the integer array(s) of a FITS file.
Parameters
----------
filename : str
full filename with path
bits : str
sum or list of integers corresponding to all the bits to be reset
extver : int, optional
List of version numbers of the DQ arrays
... | entailment |
def replace(input, **pars):
""" Replace pixels in `input` that have a value of `pixvalue`
with a value given by `newvalue`.
"""
pixvalue = pars.get('pixvalue', np.nan)
if pixvalue is None: pixvalue = np.nan # insure that None == np.nan
newvalue = pars.get('newvalue', 0.0)
ext = pars.g... | Replace pixels in `input` that have a value of `pixvalue`
with a value given by `newvalue`. | entailment |
def tweakback(drzfile, input=None, origwcs = None,
newname = None, wcsname = None,
extname='SCI', force=False, verbose=False):
"""
Apply WCS solution recorded in drizzled file to distorted input images
(``_flt.fits`` files) used to create the drizzled file. This task relies... | Apply WCS solution recorded in drizzled file to distorted input images
(``_flt.fits`` files) used to create the drizzled file. This task relies on
the original WCS and updated WCS to be recorded in the drizzled image's
header as the last 2 alternate WCSs.
Parameters
----------
drzfile : str (D... | entailment |
def extract_input_filenames(drzfile):
"""
Generate a list of filenames from a drizzled image's header
"""
data_kws = fits.getval(drzfile, 'd*data', ext=0, memmap=False)
if len(data_kws) == 0:
return None
fnames = []
for kw in data_kws.cards:
f = kw.value.split('[')[0]
... | Generate a list of filenames from a drizzled image's header | entailment |
def determine_orig_wcsname(header, wnames, wkeys):
"""
Determine the name of the original, unmodified WCS solution
"""
orig_wcsname = None
orig_key = None
if orig_wcsname is None:
for k,w in wnames.items():
if w[:4] == 'IDC_':
orig_wcsname = w
... | Determine the name of the original, unmodified WCS solution | entailment |
def parse_atfile_cat(input):
"""
Return the list of catalog filenames specified as part of the input @-file
"""
with open(input[1:]) as f:
catlist = []
catdict = {}
for line in f.readlines():
if line[0] == '#' or not line.strip():
continue
... | Return the list of catalog filenames specified as part of the input @-file | entailment |
def parse_skypos(ra, dec):
"""
Function to parse RA and Dec input values and turn them into decimal
degrees
Input formats could be:
["nn","nn","nn.nn"]
"nn nn nn.nnn"
"nn:nn:nn.nn"
"nnH nnM nn.nnS" or "nnD nnM nn.nnS"
nn.nnnnnnnn
"nn.nnnnnnn"
"""
... | Function to parse RA and Dec input values and turn them into decimal
degrees
Input formats could be:
["nn","nn","nn.nn"]
"nn nn nn.nnn"
"nn:nn:nn.nn"
"nnH nnM nn.nnS" or "nnD nnM nn.nnS"
nn.nnnnnnnn
"nn.nnnnnnn" | entailment |
def radec_hmstodd(ra, dec):
""" Function to convert HMS values into decimal degrees.
This function relies on the astropy.coordinates package to perform the
conversion to decimal degrees.
Parameters
----------
ra : list or array
List or array of input RA positio... | Function to convert HMS values into decimal degrees.
This function relies on the astropy.coordinates package to perform the
conversion to decimal degrees.
Parameters
----------
ra : list or array
List or array of input RA positions
dec : list or array
... | entailment |
def parse_exclusions(exclusions):
""" Read in exclusion definitions from file named by 'exclusions'
and return a list of positions and distances
"""
fname = fileutil.osfn(exclusions)
if os.path.exists(fname):
with open(fname) as f:
flines = f.readlines()
else:
pri... | Read in exclusion definitions from file named by 'exclusions'
and return a list of positions and distances | entailment |
def parse_colname(colname):
""" Common function to interpret input column names provided by the user.
This function translates column specification provided by the user
into a column number.
Notes
-----
This function will understand the following inputs::
'1,2,... | Common function to interpret input column names provided by the user.
This function translates column specification provided by the user
into a column number.
Notes
-----
This function will understand the following inputs::
'1,2,3' or 'c1,c2,c3' or ['c1','c2','c3... | entailment |
def readcols(infile, cols=None):
""" Function which reads specified columns from either FITS tables or
ASCII files
This function reads in the columns specified by the user into numpy
arrays regardless of the format of the input table (ASCII or FITS
table).
Parameters
... | Function which reads specified columns from either FITS tables or
ASCII files
This function reads in the columns specified by the user into numpy
arrays regardless of the format of the input table (ASCII or FITS
table).
Parameters
----------
infile : string
... | entailment |
def read_FITS_cols(infile, cols=None): # noqa: N802
""" Read columns from FITS table """
with fits.open(infile, memmap=False) as ftab:
extnum = 0
extfound = False
for extn in ftab:
if 'tfields' in extn.header:
extfound = True
break
... | Read columns from FITS table | entailment |
def read_ASCII_cols(infile, cols=[1, 2, 3]): # noqa: N802
""" Interpret input ASCII file to return arrays for specified columns.
Notes
-----
The specification of the columns should be expected to have lists for
each 'column', with all columns in each list combined into a single
... | Interpret input ASCII file to return arrays for specified columns.
Notes
-----
The specification of the columns should be expected to have lists for
each 'column', with all columns in each list combined into a single
entry.
For example::
cols = ['1,2,3','4,... | entailment |
def write_shiftfile(image_list, filename, outwcs='tweak_wcs.fits'):
""" Write out a shiftfile for a given list of input Image class objects
"""
rows = ''
nrows = 0
for img in image_list:
row = img.get_shiftfile_row()
if row is not None:
rows += row
nrows += 1
... | Write out a shiftfile for a given list of input Image class objects | entailment |
def createWcsHDU(wcs): # noqa: N802
""" Generate a WCS header object that can be used to populate a reference
WCS HDU.
For most applications, stwcs.wcsutil.HSTWCS.wcs2header()
will work just as well.
"""
header = wcs.to_header()
header['EXTNAME'] = 'WCS'
header['EXTVER'] = 1
# No... | Generate a WCS header object that can be used to populate a reference
WCS HDU.
For most applications, stwcs.wcsutil.HSTWCS.wcs2header()
will work just as well. | entailment |
def gauss_array(nx, ny=None, fwhm=1.0, sigma_x=None, sigma_y=None,
zero_norm=False):
""" Computes the 2D Gaussian with size nx*ny.
Parameters
----------
nx : int
ny : int [Default: None]
Size of output array for the generated Gaussian. If ny == None,
... | Computes the 2D Gaussian with size nx*ny.
Parameters
----------
nx : int
ny : int [Default: None]
Size of output array for the generated Gaussian. If ny == None,
output will be an array nx X nx pixels.
fwhm : float [Default: 1.0]
Full-width, ... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.