code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Initialize the random number generator
seed(seedValue)
# Get the contents of the table
dataTable = Table.read(tableName, format='ascii.csv')
numRows = len(dataTable)
# Generate a sequence of integers the size of the table, and then
# obtain a random subset of the sequence with no... | 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
information regarding the images
numEntries : int
Number of ... | 5.15855 | 4.637916 | 1.112256 |
hdrwcs = wcsutil.HSTWCS(hdulist,ext=extnum)
hdrwcs.filename = filename
hdrwcs.expname = hdulist[extnum].header['expname']
hdrwcs.extver = hdulist[extnum].header['extver']
return hdrwcs | def get_hstwcs(filename,hdulist,extnum) | Return the HSTWCS object for a given chip. | 2.894021 | 3.12518 | 0.926033 |
rotmat = fileutil.buildRotMatrix(delta_rot)*delta_scale
new_lincd = np.dot(cdmat,rotmat)
cxymat = np.array([[cx[1],cx[0]],[cy[1],cy[0]]])
new_cd = np.dot(new_lincd,cxymat)
return new_cd | 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 varying need to be specified on input. | 3.492619 | 3.988126 | 0.875754 |
cxymat = np.array([[cx[1],cx[0]],[cy[1],cy[0]]])
rotmat = fileutil.buildRotMatrix(orient)*scale/3600.
new_cd = np.dot(rotmat,cxymat)
return new_cd | 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[X/Y]10' and 'OC[X/Y]11' terms in that
order as read... | 5.592545 | 5.835594 | 0.958351 |
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(yskym)) * 60.
fmt = "%."+repr(precision)+"f"
if isinstance(xskyh,np.ndarray):
rah,dech = [],[]
... | def ddtohms(xsky,ysky,verbose=False,precision=6) | Convert sky position(s) from decimal degrees to HMS format. | 1.713357 | 1.68785 | 1.015112 |
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.sin(def_orientat),np.cos(def_orientat)]]
)
return perfect_cd | def make_perfect_cd(wcs) | Create a perfect (square, orthogonal, undistorted) CD matrix from the
input WCS. | 2.936706 | 3.063397 | 0.958644 |
naxis1 = shape[1]
naxis2 = shape[0]
# build up arrays for pixel positions for the edges
# These arrays need to be: array([(x,y),(x1,y1),...])
numpix = naxis1*2 + naxis2*2
border = np.zeros(shape=(numpix,2),dtype=np.float64)
# Now determine the appropriate values for this array
# W... | 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
Returns
-------
border : arr
arr... | 3.410788 | 3.356396 | 1.016205 |
from . import imageObject
outwcs = imageObject.WCSObject(output)
outwcs.default_wcs = default_wcs
outwcs.wcs = default_wcs.copy()
outwcs.final_wcs = default_wcs.copy()
outwcs.single_wcs = default_wcs.copy()
outwcs.updateContextImage(imageObjectList[0].createContext)
#
# Add ex... | def createWCSObject(output,default_wcs,imageObjectList) | Converts a PyWCS WCS object into a WCSObject(baseImageObject) instance. | 4.799067 | 4.913929 | 0.976625 |
original_logging_level = log.level
log.setLevel(logutil.logging.WARNING)
try:
hdr = hdulist[extlist[0]].header
wkeys = altwcs.wcskeys(hdr)
if ' ' in wkeys:
wkeys.remove(' ')
for extn in extlist:
for wkey in wkeys:
if wkey == 'O':
... | def removeAllAltWCS(hdulist,extlist) | Removes all alternate WCS solutions from the header | 4.05561 | 4.061349 | 0.998587 |
if not isinstance(imageObjectList,list):
imageObjectList = [imageObjectList]
output_wcs.restoreWCS()
updateImageWCS(imageObjectList, output_wcs) | def restoreDefaultWCS(imageObjectList, output_wcs) | Restore WCS information to default values, and update imageObject
accordingly. | 3.524223 | 3.663812 | 0.961901 |
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 rx
else:
if x >= 0.0:
return np.floor(x + 0.5)
else:
return np.ceil(x ... | def _py2round(x) | This function returns a rounded up value of the argument, similar
to Python 2. | 1.799015 | 1.951771 | 0.921734 |
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]
drizwcs[7] = inwcs.cd[1][1]
return drizwcs | def convertWCS(inwcs,drizwcs) | Copy WCSObject WCS into Drizzle compatible array. | 1.38794 | 1.354349 | 1.024802 |
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 = cd
inwcs.crval = crval
inwc.crpix = crpix
inwcs.pscale = N.sqrt(N.power(i... | def updateWCS(drizwcs,inwcs) | Copy output WCS array from Drizzle into WCSObject. | 1.968554 | 1.965008 | 1.001805 |
# Define objects that we need to use for the fit...
#in_refpix = img_geom.model.refpix
wmap = WCSMap(img_wcs,ref_wcs)
cx, cy = coeff_converter.sip2idc(img_wcs)
# Convert the RA/Dec positions back to X/Y in output product image
#_cpix_xyref = np.zeros((4,2),dtype=np.float64)
# Start by ... | 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'.
Parameters
----------
img : obj
... | 5.055343 | 4.924044 | 1.026665 |
# Initialize variables
_mat = np.zeros((3,3),dtype=np.float64)
_xorg = imgarr[0][0]
_yorg = imgarr[0][1]
_xoorg = refarr[0][0]
_yoorg = refarr[0][1]
_sigxox = 0.
_sigxoy = 0.
_sigxo = 0.
_sigyox = 0.
_sigyoy = 0.
_sigyo = 0.
_npos = len(imgarr)
# Populate ma... | def fitlin(imgarr,refarr) | Compute the least-squares fit between two arrays.
A Python translation of 'FITLIN' from 'drutil.f' (Drizzle V2.9). | 1.622593 | 1.627256 | 0.997135 |
mu = uv[:,0].mean()
mv = uv[:,1].mean()
mx = xy[:,0].mean()
my = xy[:,1].mean()
u = uv[:,0] - mu
v = uv[:,1] - mv
x = xy[:,0] - mx
y = xy[:,1] - my
Sxx = np.dot(x,x)
Syy = np.dot(y,y)
Sux = np.dot(u,x)
Suy = np.dot(u,y)
Svx = np.dot(v,x)
Svy = np.dot(v,y)
... | 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) | 2.82526 | 2.885547 | 0.979107 |
fitting_funcs = {'rscale':fitlin_rscale,'general':fitlin}
# Get the fitting function to be used
fit_func = fitting_funcs[mode.lower()]
# Perform the initial fit
P,Q = fit_func(xy,uv)
xyc = apply_fitlin(xy,P,Q)
# compute residuals from fit for input positions
dx = uv[:,0] - xyc[0]
... | 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. | 2.617204 | 2.608327 | 1.003403 |
if isinstance(fobj, str):
fobj = fits.open(fobj, memmap=False)
hdr = altwcs._getheader(fobj, ext)
try:
original_logging_level = log.level
log.setLevel(logutil.logging.WARNING)
nwcs = pywcs.WCS(hdr, fobj=fobj, key=wcskey)
except KeyError:
if verbose:
... | 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
[" ",A-Z]
alternate/primary WCS key that will be replac... | 3.657502 | 3.969568 | 0.921385 |
# This matches WTRAXY results to better than 1e-4 pixels.
skyx,skyy = self.input.all_pix2world(pixx,pixy,self.origin)
result= self.output.wcs_world2pix(skyx,skyy,self.origin)
return result | 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. | 11.209837 | 12.254428 | 0.914758 |
skyx,skyy = self.output.wcs_pix2world(pixx,pixy,self.origin)
result = self.input.all_world2pix(skyx,skyy,self.origin)
return result | def backward(self,pixx,pixy) | Transform pixx,pixy positions from the output frame back onto their
original positions in the input frame. | 5.615163 | 4.784395 | 1.173641 |
if input is not None:
inputDict["static_sig"]=static_sig
inputDict["group"]=group
inputDict["updatewcs"]=False
inputDict["input"]=input
else:
print >> sys.stderr, "Please supply an input image\n"
raise ValueError
#this accounts for a user-called init wh... | 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 them
with the user options. | 6.21915 | 7.024632 | 0.885335 |
suffix = buildSignatureKey(signature)
filename = os.path.join('.', suffix)
return filename | def constructFilename(signature) | Construct an output filename for the given signature::
signature=[instr+detector,(nx,ny),detnum]
The signature is in the image object. | 9.327806 | 16.356258 | 0.57029 |
numchips=imagePtr._numchips
log.info("Computing static mask:\n")
chips = imagePtr.group
if chips is None:
chips = imagePtr.getExtensions()
#for chip in range(1,numchips+1,1):
for chip in chips:
chipid=imagePtr.scienceExt + ','+ str(chip)... | 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 tuple::
(instrument/detector, (nx,ny), chip_i... | 6.532228 | 6.067286 | 1.076631 |
if signature in self.masklist:
mask = self.masklist[signature]
else:
mask = None
return mask | def getMaskArray(self, signature) | Returns the appropriate StaticMask array for the image. | 4.085654 | 3.854501 | 1.05997 |
filename=constructFilename(signature)
if(fileutil.checkFileExists(filename)):
return filename
else:
print("\nmMask file for ", str(signature), " does not exist on disk", file=sys.stderr)
return None | def getFilename(self,signature) | Returns the name of the output mask file that
should reside on disk for the given signature. | 9.947441 | 8.6493 | 1.150086 |
for key in self.masklist.keys():
self.masklist[key] = None
self.masklist = {} | def close(self) | Deletes all static mask objects. | 6.956882 | 3.760504 | 1.849987 |
if signature in self.masklist:
self.masklist[signature] = None
else:
log.warning("No matching mask") | def deleteMask(self,signature) | Delete just the mask that matches the signature given. | 5.399329 | 5.18045 | 1.042251 |
virtual = imageObjectList[0].inmemory
for key in self.masklist.keys():
#check to see if the file already exists on disk
filename = self.masknames[key]
#create a new fits image with the mask array and a standard header
#open a new header and data ... | 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. | 6.138467 | 5.700214 | 1.076884 |
if (shape[0] % image.shape[0]) or (shape[1] % image.shape[1]):
raise ValueError("Output shape must be an integer multiple of input "
"image shape.")
sx = shape[1] // image.shape[1]
sy = shape[0] // image.shape[0]
ox = (sx - 1.0) / (2.0 * sx)
oy = (sy - 1.0) / (... | 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. | 2.663307 | 2.434038 | 1.094193 |
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.ravel()
y = y.ravel()
x0 = np.empty(out_size, dtype=np.int)
y0 = np.empty(out_size, dtype=np.int)... | def bilinear_interp(data, x, y) | Interpolate input ``data`` at "pixel" coordinates ``x`` and ``y``. | 1.556594 | 1.534679 | 1.01428 |
sci_chip = self._image[self.scienceExt,chip]
exten = self.errExt+','+str(chip)
# The keyword for STIS flat fields in the primary header of the flt
lflatfile = fileutil.osfn(self._image["PRIMARY"].header['LFLTFILE'])
pflatfile = fileutil.osfn(self._image["PRIMARY"].head... | 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. | 3.322961 | 3.131629 | 1.061097 |
sci_chip = self._image[self.scienceExt,chip]
ny=sci_chip._naxis1
nx=sci_chip._naxis2
detnum = sci_chip.detnum
instr=self._instrument
sig=(instr+self._detector,(nx,ny),int(detnum)) #signature is a tuple
sci_chip.signature=sig | 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 outputNames dictionary. | 11.006943 | 8.609087 | 1.278526 |
if self.proc_unit == 'native':
return self._rdnoise / self._gain()
return self._rdnoise | 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. | 13.272764 | 12.244451 | 1.083982 |
pri_header = self._image[0].header
if self._isNotValid (instrpars['gain'], instrpars['gnkeyword']):
instrpars['gnkeyword'] = 'ATODGAIN'
if self._isNotValid (instrpars['rdnoise'], instrpars['rnkeyword']):
instrpars['rnkeyword'] = 'READNSE'
if self._isNotV... | def setInstrumentParameters(self, instrpars) | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | 4.221634 | 4.192528 | 1.006942 |
for det in range(1,self._numchips+1,1):
chip=self._image[self.scienceExt,det]
conversionFactor = self.effGain
chip._gain = self.effGain #1.
chip.effGain = self.effGain
chip._conversionFactor = conversionFactor | 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. | 14.682862 | 10.453593 | 1.404576 |
pri_header = self._image[0].header
usingDefaultGain = False
usingDefaultReadnoise = False
if self._isNotValid (instrpars['gain'], instrpars['gnkeyword']):
instrpars['gnkeyword'] = None
if self._isNotValid (instrpars['rdnoise'], instrpars['rnkeyword']):
... | def setInstrumentParameters(self, instrpars) | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | 4.384194 | 4.369817 | 1.00329 |
log.info('Dataset ' + filename + ' has (keyword = value) of (' + key + ' = ' + str(value) + ').')
if msg == Messages.NOPROC.value:
log.info('Dataset cannot be aligned.')
else:
log.info('Dataset can be aligned, but the result may be compromised.') | 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. | 9.697117 | 8.123498 | 1.193712 |
log.debug(inputDict)
inputDict["input"] = input
configObj = util.getDefaultConfigObj(__taskname__, configObj, inputDict,
loadOnly=(not editpars))
if configObj is None:
return
if not editpars:
run(configObj) | def drizCR(input=None, configObj=None, editpars=False, **inputDict) | Look for cosmic rays. | 6.224267 | 6.312708 | 0.98599 |
# Remove the existing cor file if it exists
if os.path.isfile(outfile):
os.remove(outfile)
print("Removing old corr file: '{:s}'".format(outfile))
with fits.open(template, memmap=False) as ftemplate:
for arr in arrlist:
ftemplate[arr['sciext']].data = arr['corrFile'... | 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. | 3.395052 | 3.415493 | 0.994015 |
paramDict = {
'gain': 7, # Detector gain, e-/ADU
'grow': 1, # Radius around CR pixel to mask [default=1 for
# 3x3 for non-NICMOS]
'ctegrow': 0, # Length of CTE correction to be applied
'rn': 5, # Read noise ... | def setDefaults(configObj={}) | Return a dictionary of the default parameters
which also been updated with the user overrides. | 7.417766 | 7.435336 | 0.997637 |
helpstr = getHelpAsString(docstring=True, show_ver=True)
if file is None:
print(helpstr)
else:
with open(file, mode='w') as f:
f.write(helpstr) | 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 help. | 3.809956 | 4.624146 | 0.823926 |
install_dir = os.path.dirname(__file__)
taskname = util.base_taskname(__taskname__, __package__)
htmlfile = os.path.join(install_dir, 'htmlhelp', taskname + '.html')
helpfile = os.path.join(install_dir, taskname + '.help')
if docstring or (not docstring and not os.path.exists(htmlfile)):
... | def getHelpAsString(docstring=False, show_ver=True) | Return useful help from a file in the script directory called
``__taskname__.help`` | 3.230413 | 3.002516 | 1.075902 |
from . import imageObject
if outwcs is None:
output_mem = 0
else:
if isinstance(outwcs,imageObject.WCSObject):
owcs = outwcs.final_wcs
else:
owcs = outwcs
output_mem = np.prod(owcs.pixel_shape) * 4 * 3 # bytes used for output arrays
img1 = i... | def reportResourceUsage(imageObjectList, outwcs, num_cores,
interactive=False) | Provide some information to the user on the estimated resource
usage (primarily memory) for this run. | 3.942587 | 3.957891 | 0.996133 |
filelist,output,ivmlist,oldasndict=processFilenames(input,None)
try:
mdrizdict = mdzhandler.getMdriztabParameters(filelist)
except KeyError:
print('No MDRIZTAB found for "%s". Parameters remain unchanged.'%(filelist[0]))
mdrizdict = {}
return mdrizdict | def getMdriztabPars(input) | High-level function for getting the parameters from MDRIZTAB
Used primarily for TEAL interface. | 12.143699 | 12.533627 | 0.968889 |
if ivmlist is None:
return
for img,ivmname in zip(imageObjectList,ivmlist):
img.updateIVMName(ivmname) | def addIVMInputs(imageObjectList,ivmlist) | Add IVM filenames provided by user to outputNames dictionary for each input imageObject. | 4.236021 | 3.72262 | 1.137914 |
f,i,o,a=buildFileList(input)
return len(f) > 1 | def checkMultipleFiles(input) | Evaluates the input to determine whether there is 1 or more than 1 valid input file. | 15.141136 | 12.730499 | 1.189359 |
imageObjList = []
mtflag = False
mt_refimg = None
for img in files:
image = _getInputImage(img,group=group)
image.setInstrumentParameters(instrpars)
image.compute_wcslin(undistort=undistort)
if 'MTFLAG' in image._image['PRIMARY'].header:
# check to see wh... | 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. | 4.634935 | 4.541226 | 1.020635 |
# 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:
# change to use fits more directly here?
if group.find(',') > 0:
grp = group.split(',')
... | def _getInputImage (input,group=None) | Factory function to return appropriate imageObject class instance | 3.497454 | 3.480979 | 1.004733 |
ivmlist = None
oldasndict = None
if input is None:
print("No input files provided to processInput")
raise ValueError
if not isinstance(input, list) and ('_asn' in input or '_asc' in input):
# Input is an association table
# Get the input files, and run makewcs on t... | def processFilenames(input=None,output=None,infilesOnly=False) | Process the input string which contains the input file information and
return a filelist,output | 5.938079 | 5.819006 | 1.020463 |
newfilelist, ivmlist, output, oldasndict, origflist = buildFileListOrig(
input, output=output, ivmlist=ivmlist, wcskey=wcskey,
updatewcs=updatewcs, **workinplace)
if not newfilelist:
buildEmptyDRZ(input, output)
return None, None, output
# run all WCS updating... | 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. | 5.478636 | 5.452275 | 1.004835 |
# Run parseinput though it's likely already been done in processFilenames
outfiles = parseinput.parseinput(infiles)[0]
# Disable parallel processing here for now until hardware I/O gets "wider".
# Since this part is IO bound, parallelizing doesn't help more than a little
# in most cases, and ... | 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. | 6.042474 | 6.092726 | 0.991752 |
if wcskey in ['', ' ', 'INDEF', None]:
if updatewcs:
uw.updatewcs(fname, checkfiles=False)
else:
numext = fileutil.countExtn(fname)
extlist = []
for extn in range(1, numext + 1):
extlist.append(('SCI', extn))
if wcskey in string.ascii_uppercas... | def _process_input_wcs_single(fname, wcskey, updatewcs) | See docs for _process_input_wcs.
This is separated to be spawned in parallel. | 5.007015 | 5.07453 | 0.986695 |
newfilelist, ivmlist, output, oldasndict, filelist = \
buildFileListOrig(input=input, output=output, ivmlist=ivmlist,
wcskey=wcskey, updatewcs=updatewcs, **workinplace)
return newfilelist, ivmlist, output, oldasndict | 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. | 3.482675 | 3.720785 | 0.936005 |
# NOTE: original file name is required in order to correctly associate
# user catalog files (e.g., user masks to be used with 'skymatch') with
# corresponding imageObjects.
filelist, output, ivmlist, oldasndict = processFilenames(input,output)
# verify that all input images specified can be u... | 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 returns the list of the
original file names as specified by the user (e.g., before GEIS->MEF, or
WAIVER FITS->MEF conversion... | 7.60367 | 7.127487 | 1.066809 |
# 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 are in the same directory as an ASN table
filelist, duplicates = checkForDuplicateInputs(rootnames)
if check_for_duplicates and ... | def buildASNList(rootnames, asnname, check_for_duplicates=True) | Return the list of filenames for a given set of rootnames | 8.814432 | 8.706149 | 1.012438 |
# 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):
os.remove(_new_asn)
# copy original ASN table to new table
shutil.copy(asnfile,_new_asn)
# Open up the new copy and convert all MEMNAME's to ... | def changeSuffixinASN(asnfile, suffix) | Create a copy of the original asn file and change the name of all members
to include the suffix. | 3.594502 | 3.541422 | 1.014988 |
flist = []
duplist = []
for fname in rootnames:
# Look for any recognized CTE-corrected products
f1 = fileutil.buildRootname(fname,ext=['_flc.fits'])
f2 = fileutil.buildRootname(fname)
flist.append(f2)
if os.path.exists(f1) and f1 != f2:
# More than... | def checkForDuplicateInputs(rootnames) | Check input files specified in ASN table for duplicate versions with
multiple valid suffixes (_flt and _flc, for example). | 5.59954 | 5.529816 | 1.012609 |
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_bits(sci_chip.dqfile, cr_bits_value,
extver=chip, extname=sci_chip... | def resetDQBits(imageObjectList, cr_bits_value=4096) | Reset the CR bit in each input image's DQ array | 6.170682 | 6.416889 | 0.961631 |
omembers = oldasndict['members'].copy()
nmembers = {}
translated_names = [f.split('.fits')[0] for f in pydr_input]
newkeys = [fileutil.buildNewRootname(file) for file in pydr_input]
keys_map = list(zip(newkeys, pydr_input))
for okey, oval in list(omembers.items()):
if okey in new... | 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 replaced by 'u9600201m_c0h' making sure that a MEf file is passed... | 5.604814 | 5.460886 | 1.026356 |
# Find out what directory is being used for processing
workingdir = os.getcwd()
# Only create sub-directory for copies of inputs, if copies are requested
# Create name of sub-directory for copies
origdir = os.path.join(workingdir,'OrIg_files')
if workinplace['overwrite'] or workinplace['pr... | 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 will be used to over-write the
current working copies. | 3.763831 | 3.676375 | 1.023788 |
msg =
short_msg =
for inputfile in filenames:
try:
dgeofile = fits.getval(inputfile, 'DGEOFILE', memmap=False)
except KeyError:
continue
if dgeofile not in ["N/A", "n/a", ""]:
message = msg.format(inputfile)
try:
... | 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 the archive before the new
software wa... | 5.45089 | 4.612837 | 1.181678 |
paramDict = {
'input':'*flt.fits',
'output':None,
'mdriztab':None,
'refimage':None,
'runfile':None,
'workinplace':False,
'updatewcs':True,
'proc_unit':'native',
'coeffs':True,
'context':False,
'clean':True,
'group':... | def _setDefaults(input_dict={}) | Define full set of default values for unit-testing this module.[OBSOLETE] | 3.577529 | 3.56105 | 1.004628 |
# Read the temperature dependeant dark file. The name for the file is taken from
# the TEMPFILE keyword in the primary header.
tddobj = readTDD.fromcalfile(self.name)
if tddobj is None:
return np.ones(self.full_shape, dtype=self.image_dtype) * self.getdarkcurrent(... | 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**. | 14.658596 | 14.474668 | 1.012707 |
has_bunit = False
if 'BUNIT' in self._image['sci',1].header :
has_bunit = True
countrate = False
if (self._image[0].header['UNITCORR'].strip() == 'PERFORM') or \
(has_bunit and self._image['sci',1].header['bunit'].find('/') != -1) :
countrate... | 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. | 6.070418 | 4.801787 | 1.2642 |
pri_header = self._image[0].header
self.proc_unit = instrpars['proc_unit']
if self._isNotValid (instrpars['gain'], instrpars['gnkeyword']):
instrpars['gnkeyword'] = 'ADCGAIN' #gain has been hardcoded below
if self._isNotValid (instrpars['rdnoise'], instrpars['rnkey... | def setInstrumentParameters(self, instrpars) | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | 6.953135 | 6.915119 | 1.005497 |
# Merge all configobj instances into a single object
configobj[section_name] = {}
# Load the default full set of configuration parameters for the PSET:
iparsobj_cfg = teal.load(task_name)
# Identify optional parameters in input_dicts that are from this
# PSET and add it to iparsobj:
i... | 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. | 4.080118 | 4.102593 | 0.994522 |
teal.teal(imagefindpars.__taskname__, returnAs=None,
autoClose=True, loadOnly=False, canExecute=False) | def edit_imagefindpars() | Allows the user to edit the imagefindpars configObj in a TEAL GUI | 49.304905 | 40.100311 | 1.229539 |
teal.teal(refimagefindpars.__taskname__, returnAs=None,
autoClose=True, loadOnly=False, canExecute=False) | def edit_refimagefindpars() | Allows the user to edit the refimagefindpars configObj in a TEAL GUI | 43.990952 | 35.096867 | 1.253415 |
start_path = os.getcwd()
try:
log.info("Local repository path: {}".format(localRepoPath))
os.chdir(localRepoPath)
log.info("\n== Remote URL")
os.system('git remote -v')
# log.info("\n== Remote Branches")
# os.system("git branch -r")
log.info("\n== L... | 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 will exit with a state of 0 if everythin... | 3.587277 | 3.36021 | 1.067575 |
start_path = os.getcwd()
try:
os.chdir(localRepoPath)
instream = os.popen("git --no-pager log --max-count=1 | head -1")
for streamline in instream.readlines():
streamline = streamline.strip()
if streamline.startswith("commit "):
rv = streamli... | 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 specified repository if everything ran OK,... | 3.472937 | 3.414477 | 1.017121 |
d2ifile = None
for f in flist:
fdet = fits.getval(f, 'detector', memmap=False)
if fdet == detector:
d2ifile = f
return d2ifile | def find_d2ifile(flist,detector) | Search a list of files for one that matches the detector specified. | 2.702171 | 2.708108 | 0.997808 |
npolfile = None
for f in flist:
fdet = fits.getval(f, 'detector', memmap=False)
if fdet == detector:
filt1 = fits.getval(f, 'filter1', memmap=False)
filt2 = fits.getval(f, 'filter2', memmap=False)
fdate = fits.getval(f, 'date', memmap=False)
i... | def find_npolfile(flist,detector,filters) | Search a list of files for one that matches the configuration
of detector and filters used. | 2.163857 | 2.260139 | 0.9574 |
if configobj is None:
configobj =teal.teal(__taskname__,loadOnly=(not editpars))
update(configobj['input'],configobj['refdir'],
local=configobj['local'],interactive=configobj['interactive'],
wcsupdate=configobj['wcsupdate']) | def run(configobj=None,editpars=False) | Teal interface for running this code. | 12.871816 | 14.027697 | 0.9176 |
# Interpret bits value
bits = interpret_bit_flags(bits)
flist, fcol = parseinput.parseinput(input)
for filename in flist:
# open input file in write mode to allow updating the DQ array in-place
p = fits.open(filename, mode='update', memmap=False)
# Identify the DQ array to... | 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, optional
List of version numbers of the DQ arrays
... | 4.387871 | 4.344067 | 1.010084 |
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.get('ext',None)
if ext in ['',' ','None',None]:
ext = None
files = parseinput.parseinput(input)[0]
for f in files:
... | def replace(input, **pars) | Replace pixels in `input` that have a value of `pixvalue`
with a value given by `newvalue`. | 3.437825 | 3.225021 | 1.065985 |
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]
if f not in fnames:
fnames.append(f)
return fnames | def extract_input_filenames(drzfile) | Generate a list of filenames from a drizzled image's header | 4.055209 | 4.05129 | 1.000967 |
orig_wcsname = None
orig_key = None
if orig_wcsname is None:
for k,w in wnames.items():
if w[:4] == 'IDC_':
orig_wcsname = w
orig_key = k
break
if orig_wcsname is None:
# No IDC_ wcsname found... revert to second to last if... | def determine_orig_wcsname(header, wnames, wkeys) | Determine the name of the original, unmodified WCS solution | 2.973716 | 3.01557 | 0.986121 |
with open(input[1:]) as f:
catlist = []
catdict = {}
for line in f.readlines():
if line[0] == '#' or not line.strip():
continue
lspl = line.split()
if len(lspl) > 1:
catdict[lspl[0]] = lspl[1:]
catlist.... | def parse_atfile_cat(input) | Return the list of catalog filenames specified as part of the input @-file | 2.288469 | 2.146485 | 1.066147 |
rval = make_val_float(ra)
dval = make_val_float(dec)
if rval is None:
rval, dval = radec_hmstodd(ra, dec)
return rval, dval | 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" | 5.871977 | 5.81256 | 1.010222 |
hmstrans = string.maketrans(string.ascii_letters,
' ' * len(string.ascii_letters))
if isinstance(ra, list):
rastr = ':'.join(ra)
elif isinstance(ra, float):
rastr = None
pos_ra = ra
elif ra.find(':') < 0:
# convert any non-numeric cha... | 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 positions
dec : list or array
... | 2.379785 | 2.424126 | 0.981708 |
fname = fileutil.osfn(exclusions)
if os.path.exists(fname):
with open(fname) as f:
flines = f.readlines()
else:
print('No valid exclusions file "', fname, '" could be found!')
print('Skipping application of exclusions files to source catalogs.')
return None
... | def parse_exclusions(exclusions) | Read in exclusion definitions from file named by 'exclusions'
and return a list of positions and distances | 3.402678 | 3.247277 | 1.047856 |
if isinstance(colname, list):
cname = ''
for c in colname:
cname += str(c) + ','
cname = cname.rstrip(',')
elif isinstance(colname, int) or colname.isdigit():
cname = str(colname)
else:
cname = colname
if 'c' in cname[0]:
cname = cname.re... | 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,3' or 'c1,c2,c3' or ['c1','c2','c3... | 2.384884 | 2.236319 | 1.066433 |
if _is_str_none(infile) is None:
return None
if infile.endswith('.fits'):
outarr = read_FITS_cols(infile, cols=cols)
else:
outarr = read_ASCII_cols(infile, cols=cols)
return outarr | 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
----------
infile : string
... | 4.405979 | 4.230569 | 1.041462 |
extnum = 0
extfound = False
for extn in ftab:
if 'tfields' in extn.header:
extfound = True
break
extnum += 1
if not extfound:
print('ERROR: No catalog table found in ', infile)
raise ValueError
# No... | def read_FITS_cols(infile, cols=None): # noqa: N802
with fits.open(infile, memmap=False) as ftab | Read columns from FITS table | 6.032477 | 5.959029 | 1.012326 |
flines = f.readlines()
for l in flines: # interpret each line from catalog file
if l[0].lstrip() == '#' or l.lstrip() == '':
continue
else:
# convert first row of data into column definitions using indices
coldict = {str(i + 1): i for i, _ in enumerate(l... | def read_ASCII_cols(infile, cols=[1, 2, 3]): # noqa: N802
# build dictionary representing format of each row
# Format of dictionary: {'colname':col_number,...}
# This provides the mapping between column name and column number
coldict = {}
with open(infile, 'r') as f | 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,... | 3.285439 | 3.25209 | 1.010255 |
rows = ''
nrows = 0
for img in image_list:
row = img.get_shiftfile_row()
if row is not None:
rows += row
nrows += 1
if nrows == 0: # If there are no fits to report, do not write out a file
return
# write out reference WCS now
if os.path.exis... | def write_shiftfile(image_list, filename, outwcs='tweak_wcs.fits') | Write out a shiftfile for a given list of input Image class objects | 3.599049 | 3.493934 | 1.030085 |
orientat = wcs.orientat
else:
# find orientat from CD or PC matrix
if wcs.wcs.has_cd():
cd12 = wcs.wcs.cd[0][1]
cd22 = wcs.wcs.cd[1][1]
elif wcs.wcs.has_pc():
cd12 = wcs.wcs.cdelt[0] * wcs.wcs.pc[0][1]
cd22 = wcs.wcs.cdelt[1] * wcs.wcs.... | def createWcsHDU(wcs): # noqa: N802
header = wcs.to_header()
header['EXTNAME'] = 'WCS'
header['EXTVER'] = 1
# Now, update original image size information
header['NPIX1'] = (wcs.pixel_shape[0], "Length of array axis 1")
header['NPIX2'] = (wcs.pixel_shape[1], "Length of array axis 2")
... | 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. | 2.61492 | 2.668705 | 0.979846 |
if ny is None:
ny = nx
if sigma_x is None:
if fwhm is None:
print('A value for either "fwhm" or "sigma_x" needs to be '
'specified!')
raise ValueError
else:
# Convert input FWHM into sigma
sigma_x = fwhm / (2 * np.s... | 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,
output will be an array nx X nx pixels.
fwhm : float [Default: 1.0]
Full-width, ... | 2.531483 | 2.62782 | 0.96334 |
return (np.exp(-np.power(x, 2) / (2 * np.power(sigma, 2))) /
(sigma * np.sqrt(2 * np.pi))) | def gauss(x, sigma) | Compute 1-D value of gaussian at position x relative to center. | 1.949486 | 2.060942 | 0.945919 |
# find level of noise in histogram
istats = imagestats.ImageStats(img.astype(np.float32), nclip=1,
fields='stddev,mode,mean,max,min')
if istats.stddev == 0.0:
istats = imagestats.ImageStats(img.astype(np.float32),
fields=... | def find_xy_peak(img, center=None, sigma=3.0) | Find the center of the peak of offsets | 3.322655 | 3.339182 | 0.995051 |
from matplotlib import pyplot as plt
xp = pars['xp']
yp = pars['yp']
searchrad = int(pars['searchrad'] + 0.5)
plt.figure(num=pars['figure_id'])
plt.clf()
if pars['interactive']:
plt.ion()
else:
plt.ioff()
plt.imshow(pars['data'], vmin=0, vmax=pars['vmax'],
... | def plot_zeropoint(pars) | Plot 2d histogram.
Pars will be a dictionary containing:
data, figure_id, vmax, title_str, xp,yp, searchrad | 2.961052 | 2.657535 | 1.11421 |
print('Computing initial guess for X and Y shifts...')
# run C function to create ZP matrix
zpmat = cdriz.arrxyzero(imgxy.astype(np.float32), refxy.astype(np.float32),
searchrad)
xp, yp, flux, zpqual = find_xy_peak(zpmat, center=(searchrad, searchrad))
if zpqual is... | def build_xy_zeropoint(imgxy, refxy, searchrad=3.0, histplot=False,
figure_id=1, plotname=None, interactive=True) | Create a matrix which contains the delta between each XY position and
each UV position. | 3.828872 | 3.844245 | 0.996001 |
# Build X and Y arrays
dx = end[0] - start[0]
if dx < 0:
nstart = end
end = start
start = nstart
dx = -dx
stepx = dx / nstep
# Perform linear fit to find exact line that connects start and end
xarr = np.arange(start[0], end[0] + stepx / 2.0, stepx)
yarr = np.... | def build_pos_grid(start, end, nstep, mesh=False) | Return a grid of positions starting at X,Y given by 'start', and ending
at X,Y given by 'end'. The grid will be completely filled in X and Y by
every 'step' interval. | 3.059148 | 3.104922 | 0.985257 |
dqfile = None
# Look for additional file with DQ array, primarily for WFPC2 data
indx = self._filename.find('.fits')
if indx > 3:
suffix = self._filename[indx-4:indx]
dqfile = self._filename.replace(suffix[:3],'_c1')
elif indx < 0 and len(self.... | def find_DQ_extension(self) | Return the suffix for the data quality extension and the name of
the file which that DQ extension should be read from. | 4.273942 | 4.317579 | 0.989893 |
pri_header = self._image[0].header
self.proc_unit = instrpars['proc_unit']
instrpars['gnkeyword'] = 'ATODGAIN' # hard-code for WFPC2 data
instrpars['rnkeyword'] = None
if self._isNotValid (instrpars['exptime'], instrpars['expkeyword']):
instrpars['expkeywor... | def setInstrumentParameters(self, instrpars) | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | 4.542056 | 4.517882 | 1.005351 |
# Image information
_handle = fileutil.openImage(self._filename, mode='readonly', memmap=False)
# Now convert the SCI array(s) units
for det in range(1,self._numchips+1):
chip=self._image[self.scienceExt,det]
conversionFactor = 1.0
# add D2I... | def doUnitConversions(self) | Apply unit conversions to all the chips, ignoring the group parameter.
This insures that all the chips get the same conversions when this
gets done, even if only 1 chip was specified to be processed. | 8.771903 | 8.559925 | 1.024764 |
darkrate = 0.005 # electrons / s
if self.proc_unit == 'native':
darkrate = darkrate / self.getGain(exten) #count/s
try:
chip = self._image[0]
darkcurrent = chip.header['DARKTIME'] * darkrate
except:
msg = "######################... | def getdarkcurrent(self,exten) | Return the dark current for the WFPC2 detector. This value
will be contained within an instrument specific keyword.
The value in the image header will be converted to units
of electrons.
Returns
-------
darkcurrent : float
Dark current for the WFPC3 detector... | 4.441569 | 4.191189 | 1.05974 |
rn = self._image[exten]._rdnoise
if self.proc_unit == 'native':
rn = self._rdnoise / self.getGain(exten)
return rn | def getReadNoise(self, exten) | Method for returning the readnoise of a detector (in counts).
Returns
-------
readnoise : float
The readnoise of the detector in **units of counts/electrons**. | 8.850035 | 11.301612 | 0.783077 |
sci_chip = self._image[self.scienceExt,chip]
### For WFPC2 Data, build mask files using:
maskname = sci_chip.dqrootname+'_dqmask.fits'
dqmask_name = buildmask.buildShadowMaskImage(sci_chip.dqfile,sci_chip.detnum,sci_chip.extnum,maskname,bitvalue=bits,binned=sci_chip.binned)
... | def buildMask(self, chip, bits=0, write=False) | Build masks as specified in the user parameters found in the
configObj object. | 6.419304 | 6.41363 | 1.000885 |
if not isinstance(catalog,Catalog):
if mode == 'automatic': # if an array is provided as the source
# Create a new catalog directly from the image
catalog = ImageCatalog(wcs,catalog,src_find_filters,**kwargs)
else: # a catalog file was provided as the catalog source
... | def generateCatalog(wcs, mode='automatic', catalog=None,
src_find_filters=None, **kwargs) | Function which determines what type of catalog object needs to be
instantiated based on what type of source selection algorithm the user
specified.
Parameters
----------
wcs : obj
WCS object generated by STWCS or PyWCS
catalog : str or ndarray
Filename of existing catalog or nd... | 6.490111 | 7.197229 | 0.901751 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.