repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.updateContextImage | def updateContextImage(self, contextpar):
""" Reset the name of the context image to `None` if parameter
``context`` is `False`.
"""
self.createContext = contextpar
if not contextpar:
log.info('No context image will be created for %s' %
self._filename)
self.outputNames['outContext'] = None | python | def updateContextImage(self, contextpar):
""" Reset the name of the context image to `None` if parameter
``context`` is `False`.
"""
self.createContext = contextpar
if not contextpar:
log.info('No context image will be created for %s' %
self._filename)
self.outputNames['outContext'] = None | [
"def",
"updateContextImage",
"(",
"self",
",",
"contextpar",
")",
":",
"self",
".",
"createContext",
"=",
"contextpar",
"if",
"not",
"contextpar",
":",
"log",
".",
"info",
"(",
"'No context image will be created for %s'",
"%",
"self",
".",
"_filename",
")",
"sel... | Reset the name of the context image to `None` if parameter
``context`` is `False`. | [
"Reset",
"the",
"name",
"of",
"the",
"context",
"image",
"to",
"None",
"if",
"parameter",
"context",
"is",
"False",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L470-L479 | train | 35,600 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.getKeywordList | def getKeywordList(self, kw):
"""
Return lists of all attribute values for all active chips in the
``imageObject``.
"""
kwlist = []
for chip in range(1,self._numchips+1,1):
sci_chip = self._image[self.scienceExt,chip]
if sci_chip.group_member:
kwlist.append(sci_chip.__dict__[kw])
return kwlist | python | def getKeywordList(self, kw):
"""
Return lists of all attribute values for all active chips in the
``imageObject``.
"""
kwlist = []
for chip in range(1,self._numchips+1,1):
sci_chip = self._image[self.scienceExt,chip]
if sci_chip.group_member:
kwlist.append(sci_chip.__dict__[kw])
return kwlist | [
"def",
"getKeywordList",
"(",
"self",
",",
"kw",
")",
":",
"kwlist",
"=",
"[",
"]",
"for",
"chip",
"in",
"range",
"(",
"1",
",",
"self",
".",
"_numchips",
"+",
"1",
",",
"1",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"... | Return lists of all attribute values for all active chips in the
``imageObject``. | [
"Return",
"lists",
"of",
"all",
"attribute",
"values",
"for",
"all",
"active",
"chips",
"in",
"the",
"imageObject",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L497-L509 | train | 35,601 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.getflat | def getflat(self, chip):
"""
Method for retrieving a detector's flat field.
Returns
-------
flat: array
This method will return an array the same shape as the image in
**units of electrons**.
"""
sci_chip = self._image[self.scienceExt, chip]
# The keyword for ACS flat fields in the primary header of the flt
# file is pfltfile. This flat file is already in the required
# units of electrons.
# The use of fileutil.osfn interprets any environment variable, such as
# jref$, used in the specification of the reference filename
filename = fileutil.osfn(self._image["PRIMARY"].header[self.flatkey])
hdulist = None
try:
hdulist = fileutil.openImage(filename, mode='readonly',
memmap=False)
data = hdulist[(self.scienceExt, chip)].data
if data.shape[0] != sci_chip.image_shape[0]:
ltv2 = int(np.round(sci_chip.ltv2))
else:
ltv2 = 0
size2 = sci_chip.image_shape[0] + ltv2
if data.shape[1] != sci_chip.image_shape[1]:
ltv1 = int(np.round(sci_chip.ltv1))
else:
ltv1 = 0
size1 = sci_chip.image_shape[1] + ltv1
flat = data[ltv2:size2, ltv1:size1]
except FileNotFoundError:
flat = np.ones(sci_chip.image_shape, dtype=sci_chip.image_dtype)
log.warning("Cannot find flat field file '{}'".format(filename))
log.warning("Treating flatfield as a constant value of '1'.")
finally:
if hdulist is not None:
hdulist.close()
return flat | python | def getflat(self, chip):
"""
Method for retrieving a detector's flat field.
Returns
-------
flat: array
This method will return an array the same shape as the image in
**units of electrons**.
"""
sci_chip = self._image[self.scienceExt, chip]
# The keyword for ACS flat fields in the primary header of the flt
# file is pfltfile. This flat file is already in the required
# units of electrons.
# The use of fileutil.osfn interprets any environment variable, such as
# jref$, used in the specification of the reference filename
filename = fileutil.osfn(self._image["PRIMARY"].header[self.flatkey])
hdulist = None
try:
hdulist = fileutil.openImage(filename, mode='readonly',
memmap=False)
data = hdulist[(self.scienceExt, chip)].data
if data.shape[0] != sci_chip.image_shape[0]:
ltv2 = int(np.round(sci_chip.ltv2))
else:
ltv2 = 0
size2 = sci_chip.image_shape[0] + ltv2
if data.shape[1] != sci_chip.image_shape[1]:
ltv1 = int(np.round(sci_chip.ltv1))
else:
ltv1 = 0
size1 = sci_chip.image_shape[1] + ltv1
flat = data[ltv2:size2, ltv1:size1]
except FileNotFoundError:
flat = np.ones(sci_chip.image_shape, dtype=sci_chip.image_dtype)
log.warning("Cannot find flat field file '{}'".format(filename))
log.warning("Treating flatfield as a constant value of '1'.")
finally:
if hdulist is not None:
hdulist.close()
return flat | [
"def",
"getflat",
"(",
"self",
",",
"chip",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"# The keyword for ACS flat fields in the primary header of the flt",
"# file is pfltfile. This flat file is already in the requi... | Method for retrieving a detector's flat field.
Returns
-------
flat: array
This method will return an array the same shape as the image in
**units of electrons**. | [
"Method",
"for",
"retrieving",
"a",
"detector",
"s",
"flat",
"field",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L514-L562 | train | 35,602 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.getExtensions | def getExtensions(self, extname='SCI', section=None):
""" Return the list of EXTVER values for extensions with name specified
in extname.
"""
if section is None:
numext = 0
section = []
for hdu in self._image:
if 'extname' in hdu.header and hdu.header['extname'] == extname:
section.append(hdu.header['extver'])
else:
if not isinstance(section,list):
section = [section]
return section | python | def getExtensions(self, extname='SCI', section=None):
""" Return the list of EXTVER values for extensions with name specified
in extname.
"""
if section is None:
numext = 0
section = []
for hdu in self._image:
if 'extname' in hdu.header and hdu.header['extname'] == extname:
section.append(hdu.header['extver'])
else:
if not isinstance(section,list):
section = [section]
return section | [
"def",
"getExtensions",
"(",
"self",
",",
"extname",
"=",
"'SCI'",
",",
"section",
"=",
"None",
")",
":",
"if",
"section",
"is",
"None",
":",
"numext",
"=",
"0",
"section",
"=",
"[",
"]",
"for",
"hdu",
"in",
"self",
".",
"_image",
":",
"if",
"'extn... | Return the list of EXTVER values for extensions with name specified
in extname. | [
"Return",
"the",
"list",
"of",
"EXTVER",
"values",
"for",
"extensions",
"with",
"name",
"specified",
"in",
"extname",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L647-L662 | train | 35,603 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.buildEXPmask | def buildEXPmask(self, chip, dqarr):
""" Builds a weight mask from an input DQ array and the exposure time
per pixel for this chip.
"""
log.info("Applying EXPTIME weighting to DQ mask for chip %s" %
chip)
#exparr = self.getexptimeimg(chip)
exparr = self._image[self.scienceExt,chip]._exptime
expmask = exparr*dqarr
return expmask.astype(np.float32) | python | def buildEXPmask(self, chip, dqarr):
""" Builds a weight mask from an input DQ array and the exposure time
per pixel for this chip.
"""
log.info("Applying EXPTIME weighting to DQ mask for chip %s" %
chip)
#exparr = self.getexptimeimg(chip)
exparr = self._image[self.scienceExt,chip]._exptime
expmask = exparr*dqarr
return expmask.astype(np.float32) | [
"def",
"buildEXPmask",
"(",
"self",
",",
"chip",
",",
"dqarr",
")",
":",
"log",
".",
"info",
"(",
"\"Applying EXPTIME weighting to DQ mask for chip %s\"",
"%",
"chip",
")",
"#exparr = self.getexptimeimg(chip)",
"exparr",
"=",
"self",
".",
"_image",
"[",
"self",
".... | Builds a weight mask from an input DQ array and the exposure time
per pixel for this chip. | [
"Builds",
"a",
"weight",
"mask",
"from",
"an",
"input",
"DQ",
"array",
"and",
"the",
"exposure",
"time",
"per",
"pixel",
"for",
"this",
"chip",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L722-L732 | train | 35,604 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.buildIVMmask | def buildIVMmask(self ,chip, dqarr, scale):
""" Builds a weight mask from an input DQ array and either an IVM array
provided by the user or a self-generated IVM array derived from the
flat-field reference file associated with the input image.
"""
sci_chip = self._image[self.scienceExt,chip]
ivmname = self.outputNames['ivmFile']
if ivmname is not None:
log.info("Applying user supplied IVM files for chip %s" % chip)
#Parse the input file name to get the extension we are working on
extn = "IVM,{}".format(chip)
#Open the mask image for updating and the IVM image
ivm = fileutil.openImage(ivmname, mode='readonly', memmap=False)
ivmfile = fileutil.getExtn(ivm, extn)
# Multiply the IVM file by the input mask in place.
ivmarr = ivmfile.data * dqarr
ivm.close()
else:
log.info("Automatically creating IVM files for chip %s" % chip)
# If no IVM files were provided by the user we will
# need to automatically generate them based upon
# instrument specific information.
flat = self.getflat(chip)
RN = self.getReadNoiseImage(chip)
darkimg = self.getdarkimg(chip)
skyimg = self.getskyimg(chip)
#exptime = self.getexptimeimg(chip)
#exptime = sci_chip._exptime
#ivm = (flat*exptime)**2/(darkimg+(skyimg*flat)+RN**2)
ivm = (flat)**2/(darkimg+(skyimg*flat)+RN**2)
# Multiply the IVM file by the input mask in place.
ivmarr = ivm * dqarr
# Update 'wt_scl' parameter to match use of IVM file
sci_chip._wtscl = pow(sci_chip._exptime,2)/pow(scale,4)
#sci_chip._wtscl = 1.0/pow(scale,4)
return ivmarr.astype(np.float32) | python | def buildIVMmask(self ,chip, dqarr, scale):
""" Builds a weight mask from an input DQ array and either an IVM array
provided by the user or a self-generated IVM array derived from the
flat-field reference file associated with the input image.
"""
sci_chip = self._image[self.scienceExt,chip]
ivmname = self.outputNames['ivmFile']
if ivmname is not None:
log.info("Applying user supplied IVM files for chip %s" % chip)
#Parse the input file name to get the extension we are working on
extn = "IVM,{}".format(chip)
#Open the mask image for updating and the IVM image
ivm = fileutil.openImage(ivmname, mode='readonly', memmap=False)
ivmfile = fileutil.getExtn(ivm, extn)
# Multiply the IVM file by the input mask in place.
ivmarr = ivmfile.data * dqarr
ivm.close()
else:
log.info("Automatically creating IVM files for chip %s" % chip)
# If no IVM files were provided by the user we will
# need to automatically generate them based upon
# instrument specific information.
flat = self.getflat(chip)
RN = self.getReadNoiseImage(chip)
darkimg = self.getdarkimg(chip)
skyimg = self.getskyimg(chip)
#exptime = self.getexptimeimg(chip)
#exptime = sci_chip._exptime
#ivm = (flat*exptime)**2/(darkimg+(skyimg*flat)+RN**2)
ivm = (flat)**2/(darkimg+(skyimg*flat)+RN**2)
# Multiply the IVM file by the input mask in place.
ivmarr = ivm * dqarr
# Update 'wt_scl' parameter to match use of IVM file
sci_chip._wtscl = pow(sci_chip._exptime,2)/pow(scale,4)
#sci_chip._wtscl = 1.0/pow(scale,4)
return ivmarr.astype(np.float32) | [
"def",
"buildIVMmask",
"(",
"self",
",",
"chip",
",",
"dqarr",
",",
"scale",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"ivmname",
"=",
"self",
".",
"outputNames",
"[",
"'ivmFile'",
"]",
"if",
... | Builds a weight mask from an input DQ array and either an IVM array
provided by the user or a self-generated IVM array derived from the
flat-field reference file associated with the input image. | [
"Builds",
"a",
"weight",
"mask",
"from",
"an",
"input",
"DQ",
"array",
"and",
"either",
"an",
"IVM",
"array",
"provided",
"by",
"the",
"user",
"or",
"a",
"self",
"-",
"generated",
"IVM",
"array",
"derived",
"from",
"the",
"flat",
"-",
"field",
"reference... | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L734-L779 | train | 35,605 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.buildERRmask | def buildERRmask(self,chip,dqarr,scale):
"""
Builds a weight mask from an input DQ array and an ERR array
associated with the input image.
"""
sci_chip = self._image[self.scienceExt,chip]
# Set default value in case of error, or lack of ERR array
errmask = dqarr
if self.errExt is not None:
try:
# Attempt to open the ERR image.
err = self.getData(exten=self.errExt+','+str(chip))
log.info("Applying ERR weighting to DQ mask for chip %s" %
chip)
# Multiply the scaled ERR file by the input mask in place.
#exptime = self.getexptimeimg(chip)
exptime = sci_chip._exptime
errmask = (exptime/err)**2 * dqarr
# Update 'wt_scl' parameter to match use of IVM file
#sci_chip._wtscl = pow(sci_chip._exptime,2)/pow(scale,4)
sci_chip._wtscl = 1.0/pow(scale,4)
del err
except:
# We cannot find an 'ERR' extension and the data isn't WFPC2.
# Print a generic warning message and continue on with the
# final drizzle step.
print(textutil.textbox(
'WARNING: No ERR weighting will be applied to the mask '
'used in the final drizzle step! Weighting will be only '
'by exposure time.\n\nThe data provided as input does not '
'contain an ERR extension'), file=sys.stderr)
print('\n Continue with final drizzle step...', sys.stderr)
else:
# If we were unable to find an 'ERR' extension to apply, one
# possible reason was that the input was a 'standard' WFPC2 data
# file that does not actually contain an error array. Test for
# this condition and issue a Warning to the user and continue on to
# the final drizzle.
print(textutil.textbox(
"WARNING: No ERR weighting will be applied to the mask used "
"in the final drizzle step! Weighting will be only by "
"exposure time.\n\nThe WFPC2 data provided as input does not "
"contain ERR arrays. WFPC2 data is not supported by this "
"weighting type.\n\nA workaround would be to create inverse "
"variance maps and use 'IVM' as the final_wht_type. See the "
"HELP file for more details on using inverse variance maps."),
file=sys.stderr)
print("\n Continue with final drizzle step...", file=sys.stderr)
return errmask.astype(np.float32) | python | def buildERRmask(self,chip,dqarr,scale):
"""
Builds a weight mask from an input DQ array and an ERR array
associated with the input image.
"""
sci_chip = self._image[self.scienceExt,chip]
# Set default value in case of error, or lack of ERR array
errmask = dqarr
if self.errExt is not None:
try:
# Attempt to open the ERR image.
err = self.getData(exten=self.errExt+','+str(chip))
log.info("Applying ERR weighting to DQ mask for chip %s" %
chip)
# Multiply the scaled ERR file by the input mask in place.
#exptime = self.getexptimeimg(chip)
exptime = sci_chip._exptime
errmask = (exptime/err)**2 * dqarr
# Update 'wt_scl' parameter to match use of IVM file
#sci_chip._wtscl = pow(sci_chip._exptime,2)/pow(scale,4)
sci_chip._wtscl = 1.0/pow(scale,4)
del err
except:
# We cannot find an 'ERR' extension and the data isn't WFPC2.
# Print a generic warning message and continue on with the
# final drizzle step.
print(textutil.textbox(
'WARNING: No ERR weighting will be applied to the mask '
'used in the final drizzle step! Weighting will be only '
'by exposure time.\n\nThe data provided as input does not '
'contain an ERR extension'), file=sys.stderr)
print('\n Continue with final drizzle step...', sys.stderr)
else:
# If we were unable to find an 'ERR' extension to apply, one
# possible reason was that the input was a 'standard' WFPC2 data
# file that does not actually contain an error array. Test for
# this condition and issue a Warning to the user and continue on to
# the final drizzle.
print(textutil.textbox(
"WARNING: No ERR weighting will be applied to the mask used "
"in the final drizzle step! Weighting will be only by "
"exposure time.\n\nThe WFPC2 data provided as input does not "
"contain ERR arrays. WFPC2 data is not supported by this "
"weighting type.\n\nA workaround would be to create inverse "
"variance maps and use 'IVM' as the final_wht_type. See the "
"HELP file for more details on using inverse variance maps."),
file=sys.stderr)
print("\n Continue with final drizzle step...", file=sys.stderr)
return errmask.astype(np.float32) | [
"def",
"buildERRmask",
"(",
"self",
",",
"chip",
",",
"dqarr",
",",
"scale",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"# Set default value in case of error, or lack of ERR array",
"errmask",
"=",
"dqarr"... | Builds a weight mask from an input DQ array and an ERR array
associated with the input image. | [
"Builds",
"a",
"weight",
"mask",
"from",
"an",
"input",
"DQ",
"array",
"and",
"an",
"ERR",
"array",
"associated",
"with",
"the",
"input",
"image",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L781-L839 | train | 35,606 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.set_mt_wcs | def set_mt_wcs(self, image):
""" Reset the WCS for this image based on the WCS information from
another imageObject.
"""
for chip in range(1,self._numchips+1,1):
sci_chip = self._image[self.scienceExt,chip]
ref_chip = image._image[image.scienceExt,chip]
# Do we want to keep track of original WCS or not? No reason now...
sci_chip.wcs = ref_chip.wcs.copy() | python | def set_mt_wcs(self, image):
""" Reset the WCS for this image based on the WCS information from
another imageObject.
"""
for chip in range(1,self._numchips+1,1):
sci_chip = self._image[self.scienceExt,chip]
ref_chip = image._image[image.scienceExt,chip]
# Do we want to keep track of original WCS or not? No reason now...
sci_chip.wcs = ref_chip.wcs.copy() | [
"def",
"set_mt_wcs",
"(",
"self",
",",
"image",
")",
":",
"for",
"chip",
"in",
"range",
"(",
"1",
",",
"self",
".",
"_numchips",
"+",
"1",
",",
"1",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]... | Reset the WCS for this image based on the WCS information from
another imageObject. | [
"Reset",
"the",
"WCS",
"for",
"this",
"image",
"based",
"on",
"the",
"WCS",
"information",
"from",
"another",
"imageObject",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L846-L854 | train | 35,607 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject.set_wtscl | def set_wtscl(self, chip, wtscl_par):
""" Sets the value of the wt_scl parameter as needed for drizzling.
"""
sci_chip = self._image[self.scienceExt,chip]
exptime = 1 #sci_chip._exptime
_parval = 'unity'
if wtscl_par is not None:
if type(wtscl_par) == type(''):
if not wtscl_par.isdigit():
# String passed in as value, check for 'exptime' or 'expsq'
_wtscl_float = None
try:
_wtscl_float = float(wtscl_par)
except ValueError:
_wtscl_float = None
if _wtscl_float is not None:
_wtscl = _wtscl_float
elif wtscl_par == 'expsq':
_wtscl = exptime*exptime
_parval = 'expsq'
else:
# Default to the case of 'exptime', if
# not explicitly specified as 'expsq'
_wtscl = exptime
else:
# int value passed in as a string, convert to float
_wtscl = float(wtscl_par)
else:
# We have a non-string value passed in...
_wtscl = float(wtscl_par)
else:
# Default case: wt_scl = exptime
_wtscl = exptime
sci_chip._wtscl_par = _parval
sci_chip._wtscl = _wtscl | python | def set_wtscl(self, chip, wtscl_par):
""" Sets the value of the wt_scl parameter as needed for drizzling.
"""
sci_chip = self._image[self.scienceExt,chip]
exptime = 1 #sci_chip._exptime
_parval = 'unity'
if wtscl_par is not None:
if type(wtscl_par) == type(''):
if not wtscl_par.isdigit():
# String passed in as value, check for 'exptime' or 'expsq'
_wtscl_float = None
try:
_wtscl_float = float(wtscl_par)
except ValueError:
_wtscl_float = None
if _wtscl_float is not None:
_wtscl = _wtscl_float
elif wtscl_par == 'expsq':
_wtscl = exptime*exptime
_parval = 'expsq'
else:
# Default to the case of 'exptime', if
# not explicitly specified as 'expsq'
_wtscl = exptime
else:
# int value passed in as a string, convert to float
_wtscl = float(wtscl_par)
else:
# We have a non-string value passed in...
_wtscl = float(wtscl_par)
else:
# Default case: wt_scl = exptime
_wtscl = exptime
sci_chip._wtscl_par = _parval
sci_chip._wtscl = _wtscl | [
"def",
"set_wtscl",
"(",
"self",
",",
"chip",
",",
"wtscl_par",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"exptime",
"=",
"1",
"#sci_chip._exptime",
"_parval",
"=",
"'unity'",
"if",
"wtscl_par",
"... | Sets the value of the wt_scl parameter as needed for drizzling. | [
"Sets",
"the",
"value",
"of",
"the",
"wt_scl",
"parameter",
"as",
"needed",
"for",
"drizzling",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L856-L892 | train | 35,608 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject._averageFromHeader | def _averageFromHeader(self, header, keyword):
""" Averages out values taken from header. The keywords where
to read values from are passed as a comma-separated list.
"""
_list = ''
for _kw in keyword.split(','):
if _kw in header:
_list = _list + ',' + str(header[_kw])
else:
return None
return self._averageFromList(_list) | python | def _averageFromHeader(self, header, keyword):
""" Averages out values taken from header. The keywords where
to read values from are passed as a comma-separated list.
"""
_list = ''
for _kw in keyword.split(','):
if _kw in header:
_list = _list + ',' + str(header[_kw])
else:
return None
return self._averageFromList(_list) | [
"def",
"_averageFromHeader",
"(",
"self",
",",
"header",
",",
"keyword",
")",
":",
"_list",
"=",
"''",
"for",
"_kw",
"in",
"keyword",
".",
"split",
"(",
"','",
")",
":",
"if",
"_kw",
"in",
"header",
":",
"_list",
"=",
"_list",
"+",
"','",
"+",
"str... | Averages out values taken from header. The keywords where
to read values from are passed as a comma-separated list. | [
"Averages",
"out",
"values",
"taken",
"from",
"header",
".",
"The",
"keywords",
"where",
"to",
"read",
"values",
"from",
"are",
"passed",
"as",
"a",
"comma",
"-",
"separated",
"list",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L929-L939 | train | 35,609 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | baseImageObject._averageFromList | def _averageFromList(self, param):
""" Averages out values passed as a comma-separated
list, disregarding the zero-valued entries.
"""
_result = 0.0
_count = 0
for _param in param.split(','):
if _param != '' and float(_param) != 0.0:
_result = _result + float(_param)
_count += 1
if _count >= 1:
_result = _result / _count
return _result | python | def _averageFromList(self, param):
""" Averages out values passed as a comma-separated
list, disregarding the zero-valued entries.
"""
_result = 0.0
_count = 0
for _param in param.split(','):
if _param != '' and float(_param) != 0.0:
_result = _result + float(_param)
_count += 1
if _count >= 1:
_result = _result / _count
return _result | [
"def",
"_averageFromList",
"(",
"self",
",",
"param",
")",
":",
"_result",
"=",
"0.0",
"_count",
"=",
"0",
"for",
"_param",
"in",
"param",
".",
"split",
"(",
"','",
")",
":",
"if",
"_param",
"!=",
"''",
"and",
"float",
"(",
"_param",
")",
"!=",
"0.... | Averages out values passed as a comma-separated
list, disregarding the zero-valued entries. | [
"Averages",
"out",
"values",
"passed",
"as",
"a",
"comma",
"-",
"separated",
"list",
"disregarding",
"the",
"zero",
"-",
"valued",
"entries",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L941-L955 | train | 35,610 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | imageObject.compute_wcslin | def compute_wcslin(self,undistort=True):
""" Compute the undistorted WCS based solely on the known distortion
model information associated with the WCS.
"""
for chip in range(1,self._numchips+1,1):
sci_chip = self._image[self.scienceExt,chip]
chip_wcs = sci_chip.wcs.copy()
if chip_wcs.sip is None or not undistort or chip_wcs.instrument=='DEFAULT':
chip_wcs.sip = None
chip_wcs.cpdis1 = None
chip_wcs.cpdis2 = None
chip_wcs.det2im = None
undistort=False
# compute the undistorted 'natural' plate scale for this chip
wcslin = distortion.utils.output_wcs([chip_wcs],undistort=undistort)
sci_chip.wcslin_pscale = wcslin.pscale | python | def compute_wcslin(self,undistort=True):
""" Compute the undistorted WCS based solely on the known distortion
model information associated with the WCS.
"""
for chip in range(1,self._numchips+1,1):
sci_chip = self._image[self.scienceExt,chip]
chip_wcs = sci_chip.wcs.copy()
if chip_wcs.sip is None or not undistort or chip_wcs.instrument=='DEFAULT':
chip_wcs.sip = None
chip_wcs.cpdis1 = None
chip_wcs.cpdis2 = None
chip_wcs.det2im = None
undistort=False
# compute the undistorted 'natural' plate scale for this chip
wcslin = distortion.utils.output_wcs([chip_wcs],undistort=undistort)
sci_chip.wcslin_pscale = wcslin.pscale | [
"def",
"compute_wcslin",
"(",
"self",
",",
"undistort",
"=",
"True",
")",
":",
"for",
"chip",
"in",
"range",
"(",
"1",
",",
"self",
".",
"_numchips",
"+",
"1",
",",
"1",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceEx... | Compute the undistorted WCS based solely on the known distortion
model information associated with the WCS. | [
"Compute",
"the",
"undistorted",
"WCS",
"based",
"solely",
"on",
"the",
"known",
"distortion",
"model",
"information",
"associated",
"with",
"the",
"WCS",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L1151-L1168 | train | 35,611 |
spacetelescope/drizzlepac | drizzlepac/imageObject.py | imageObject.set_units | def set_units(self,chip):
""" Define units for this image.
"""
# Determine output value of BUNITS
# and make sure it is not specified as 'ergs/cm...'
sci_chip = self._image[self.scienceExt,chip]
_bunit = None
if 'BUNIT' in sci_chip.header and sci_chip.header['BUNIT'].find('ergs') < 0:
_bunit = sci_chip.header['BUNIT']
else:
_bunit = 'ELECTRONS/S'
sci_chip._bunit = _bunit
#
if '/s' in _bunit.lower():
_in_units = 'cps'
else:
_in_units = 'counts'
sci_chip.in_units = _in_units | python | def set_units(self,chip):
""" Define units for this image.
"""
# Determine output value of BUNITS
# and make sure it is not specified as 'ergs/cm...'
sci_chip = self._image[self.scienceExt,chip]
_bunit = None
if 'BUNIT' in sci_chip.header and sci_chip.header['BUNIT'].find('ergs') < 0:
_bunit = sci_chip.header['BUNIT']
else:
_bunit = 'ELECTRONS/S'
sci_chip._bunit = _bunit
#
if '/s' in _bunit.lower():
_in_units = 'cps'
else:
_in_units = 'counts'
sci_chip.in_units = _in_units | [
"def",
"set_units",
"(",
"self",
",",
"chip",
")",
":",
"# Determine output value of BUNITS",
"# and make sure it is not specified as 'ergs/cm...'",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"_bunit",
"=",
"None",
"if"... | Define units for this image. | [
"Define",
"units",
"for",
"this",
"image",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L1170-L1188 | train | 35,612 |
spacetelescope/drizzlepac | drizzlepac/outputimage.py | getTemplates | def getTemplates(fnames, blend=True):
""" Process all headers to produce a set of combined headers
that follows the rules defined by each instrument.
"""
if not blend:
newhdrs = blendheaders.getSingleTemplate(fnames[0])
newtab = None
else:
# apply rules to create final version of headers, plus table
newhdrs, newtab = blendheaders.get_blended_headers(inputs=fnames)
cleanTemplates(newhdrs[1],newhdrs[2],newhdrs[3])
return newhdrs, newtab | python | def getTemplates(fnames, blend=True):
""" Process all headers to produce a set of combined headers
that follows the rules defined by each instrument.
"""
if not blend:
newhdrs = blendheaders.getSingleTemplate(fnames[0])
newtab = None
else:
# apply rules to create final version of headers, plus table
newhdrs, newtab = blendheaders.get_blended_headers(inputs=fnames)
cleanTemplates(newhdrs[1],newhdrs[2],newhdrs[3])
return newhdrs, newtab | [
"def",
"getTemplates",
"(",
"fnames",
",",
"blend",
"=",
"True",
")",
":",
"if",
"not",
"blend",
":",
"newhdrs",
"=",
"blendheaders",
".",
"getSingleTemplate",
"(",
"fnames",
"[",
"0",
"]",
")",
"newtab",
"=",
"None",
"else",
":",
"# apply rules to create ... | Process all headers to produce a set of combined headers
that follows the rules defined by each instrument. | [
"Process",
"all",
"headers",
"to",
"produce",
"a",
"set",
"of",
"combined",
"headers",
"that",
"follows",
"the",
"rules",
"defined",
"by",
"each",
"instrument",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/outputimage.py#L680-L694 | train | 35,613 |
spacetelescope/drizzlepac | drizzlepac/outputimage.py | addWCSKeywords | def addWCSKeywords(wcs,hdr,blot=False,single=False,after=None):
""" Update input header 'hdr' with WCS keywords.
"""
wname = wcs.wcs.name
if not single:
wname = 'DRZWCS'
# Update WCS Keywords based on PyDrizzle product's value
# since 'drizzle' itself doesn't update that keyword.
hdr['WCSNAME'] = wname
hdr.set('VAFACTOR', value=1.0, after=after)
hdr.set('ORIENTAT', value=wcs.orientat, after=after)
# Use of 'after' not needed if these keywords already exist in the header
if after in WCS_KEYWORDS:
after = None
if 'CTYPE1' not in hdr:
hdr.set('CTYPE2', value=wcs.wcs.ctype[1], after=after)
hdr.set('CTYPE1', value=wcs.wcs.ctype[0], after=after)
hdr.set('CRPIX2', value=wcs.wcs.crpix[1], after=after)
hdr.set('CRPIX1', value=wcs.wcs.crpix[0], after=after)
hdr.set('CRVAL2', value=wcs.wcs.crval[1], after=after)
hdr.set('CRVAL1', value=wcs.wcs.crval[0], after=after)
hdr.set('CD2_2', value=wcs.wcs.cd[1][1], after=after)
hdr.set('CD2_1', value=wcs.wcs.cd[1][0], after=after)
hdr.set('CD1_2', value=wcs.wcs.cd[0][1], after=after)
hdr.set('CD1_1', value=wcs.wcs.cd[0][0], after=after)
# delete distortion model related keywords
deleteDistortionKeywords(hdr)
if not blot:
blendheaders.remove_distortion_keywords(hdr) | python | def addWCSKeywords(wcs,hdr,blot=False,single=False,after=None):
""" Update input header 'hdr' with WCS keywords.
"""
wname = wcs.wcs.name
if not single:
wname = 'DRZWCS'
# Update WCS Keywords based on PyDrizzle product's value
# since 'drizzle' itself doesn't update that keyword.
hdr['WCSNAME'] = wname
hdr.set('VAFACTOR', value=1.0, after=after)
hdr.set('ORIENTAT', value=wcs.orientat, after=after)
# Use of 'after' not needed if these keywords already exist in the header
if after in WCS_KEYWORDS:
after = None
if 'CTYPE1' not in hdr:
hdr.set('CTYPE2', value=wcs.wcs.ctype[1], after=after)
hdr.set('CTYPE1', value=wcs.wcs.ctype[0], after=after)
hdr.set('CRPIX2', value=wcs.wcs.crpix[1], after=after)
hdr.set('CRPIX1', value=wcs.wcs.crpix[0], after=after)
hdr.set('CRVAL2', value=wcs.wcs.crval[1], after=after)
hdr.set('CRVAL1', value=wcs.wcs.crval[0], after=after)
hdr.set('CD2_2', value=wcs.wcs.cd[1][1], after=after)
hdr.set('CD2_1', value=wcs.wcs.cd[1][0], after=after)
hdr.set('CD1_2', value=wcs.wcs.cd[0][1], after=after)
hdr.set('CD1_1', value=wcs.wcs.cd[0][0], after=after)
# delete distortion model related keywords
deleteDistortionKeywords(hdr)
if not blot:
blendheaders.remove_distortion_keywords(hdr) | [
"def",
"addWCSKeywords",
"(",
"wcs",
",",
"hdr",
",",
"blot",
"=",
"False",
",",
"single",
"=",
"False",
",",
"after",
"=",
"None",
")",
":",
"wname",
"=",
"wcs",
".",
"wcs",
".",
"name",
"if",
"not",
"single",
":",
"wname",
"=",
"'DRZWCS'",
"# Upd... | Update input header 'hdr' with WCS keywords. | [
"Update",
"input",
"header",
"hdr",
"with",
"WCS",
"keywords",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/outputimage.py#L696-L729 | train | 35,614 |
spacetelescope/drizzlepac | drizzlepac/outputimage.py | writeSingleFITS | def writeSingleFITS(data,wcs,output,template,clobber=True,verbose=True):
""" Write out a simple FITS file given a numpy array and the name of another
FITS file to use as a template for the output image header.
"""
outname,outextn = fileutil.parseFilename(output)
outextname,outextver = fileutil.parseExtn(outextn)
if fileutil.findFile(outname):
if clobber:
log.info('Deleting previous output product: %s' % outname)
fileutil.removeFile(outname)
else:
log.warning('Output file %s already exists and overwrite not '
'specified!' % outname)
log.error('Quitting... Please remove before resuming operations.')
raise IOError
# Now update WCS keywords with values from provided WCS
if hasattr(wcs.sip,'a_order'):
siphdr = True
else:
siphdr = False
wcshdr = wcs.wcs2header(sip2hdr=siphdr)
if template is not None:
# Get default headers from multi-extension FITS file
# If input data is not in MEF FITS format, it will return 'None'
# NOTE: These are HEADER objects, not HDUs
(prihdr,scihdr,errhdr,dqhdr),newtab = getTemplates(template,EXTLIST)
if scihdr is None:
scihdr = fits.Header()
indx = 0
for c in prihdr.cards:
if c.keyword not in ['INHERIT','EXPNAME']: indx += 1
else: break
for i in range(indx,len(prihdr)):
scihdr.append(prihdr.cards[i])
for i in range(indx, len(prihdr)):
del prihdr[indx]
else:
scihdr = fits.Header()
prihdr = fits.Header()
# Start by updating PRIMARY header keywords...
prihdr.set('EXTEND', value=True, after='NAXIS')
prihdr['FILENAME'] = outname
if outextname == '':
outextname = 'sci'
if outextver == 0: outextver = 1
scihdr['EXTNAME'] = outextname.upper()
scihdr['EXTVER'] = outextver
for card in wcshdr.cards:
scihdr[card.keyword] = (card.value, card.comment)
# Create PyFITS HDUList for all extensions
outhdu = fits.HDUList()
# Setup primary header as an HDU ready for appending to output FITS file
prihdu = fits.PrimaryHDU(header=prihdr)
scihdu = fits.ImageHDU(header=scihdr,data=data)
outhdu.append(prihdu)
outhdu.append(scihdu)
outhdu.writeto(outname)
if verbose:
print('Created output image: %s' % outname) | python | def writeSingleFITS(data,wcs,output,template,clobber=True,verbose=True):
""" Write out a simple FITS file given a numpy array and the name of another
FITS file to use as a template for the output image header.
"""
outname,outextn = fileutil.parseFilename(output)
outextname,outextver = fileutil.parseExtn(outextn)
if fileutil.findFile(outname):
if clobber:
log.info('Deleting previous output product: %s' % outname)
fileutil.removeFile(outname)
else:
log.warning('Output file %s already exists and overwrite not '
'specified!' % outname)
log.error('Quitting... Please remove before resuming operations.')
raise IOError
# Now update WCS keywords with values from provided WCS
if hasattr(wcs.sip,'a_order'):
siphdr = True
else:
siphdr = False
wcshdr = wcs.wcs2header(sip2hdr=siphdr)
if template is not None:
# Get default headers from multi-extension FITS file
# If input data is not in MEF FITS format, it will return 'None'
# NOTE: These are HEADER objects, not HDUs
(prihdr,scihdr,errhdr,dqhdr),newtab = getTemplates(template,EXTLIST)
if scihdr is None:
scihdr = fits.Header()
indx = 0
for c in prihdr.cards:
if c.keyword not in ['INHERIT','EXPNAME']: indx += 1
else: break
for i in range(indx,len(prihdr)):
scihdr.append(prihdr.cards[i])
for i in range(indx, len(prihdr)):
del prihdr[indx]
else:
scihdr = fits.Header()
prihdr = fits.Header()
# Start by updating PRIMARY header keywords...
prihdr.set('EXTEND', value=True, after='NAXIS')
prihdr['FILENAME'] = outname
if outextname == '':
outextname = 'sci'
if outextver == 0: outextver = 1
scihdr['EXTNAME'] = outextname.upper()
scihdr['EXTVER'] = outextver
for card in wcshdr.cards:
scihdr[card.keyword] = (card.value, card.comment)
# Create PyFITS HDUList for all extensions
outhdu = fits.HDUList()
# Setup primary header as an HDU ready for appending to output FITS file
prihdu = fits.PrimaryHDU(header=prihdr)
scihdu = fits.ImageHDU(header=scihdr,data=data)
outhdu.append(prihdu)
outhdu.append(scihdu)
outhdu.writeto(outname)
if verbose:
print('Created output image: %s' % outname) | [
"def",
"writeSingleFITS",
"(",
"data",
",",
"wcs",
",",
"output",
",",
"template",
",",
"clobber",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"outname",
",",
"outextn",
"=",
"fileutil",
".",
"parseFilename",
"(",
"output",
")",
"outextname",
","... | Write out a simple FITS file given a numpy array and the name of another
FITS file to use as a template for the output image header. | [
"Write",
"out",
"a",
"simple",
"FITS",
"file",
"given",
"a",
"numpy",
"array",
"and",
"the",
"name",
"of",
"another",
"FITS",
"file",
"to",
"use",
"as",
"a",
"template",
"for",
"the",
"output",
"image",
"header",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/outputimage.py#L743-L811 | train | 35,615 |
spacetelescope/drizzlepac | drizzlepac/outputimage.py | writeDrizKeywords | def writeDrizKeywords(hdr,imgnum,drizdict):
""" Write basic drizzle-related keywords out to image header as a record
of the processing performed to create the image
The dictionary 'drizdict' will contain the keywords and values to be
written out to the header.
"""
_keyprefix = 'D%03d'%imgnum
for key in drizdict:
val = drizdict[key]['value']
if val is None: val = ""
comment = drizdict[key]['comment']
if comment is None: comment = ""
hdr[_keyprefix+key] = (val, drizdict[key]['comment']) | python | def writeDrizKeywords(hdr,imgnum,drizdict):
""" Write basic drizzle-related keywords out to image header as a record
of the processing performed to create the image
The dictionary 'drizdict' will contain the keywords and values to be
written out to the header.
"""
_keyprefix = 'D%03d'%imgnum
for key in drizdict:
val = drizdict[key]['value']
if val is None: val = ""
comment = drizdict[key]['comment']
if comment is None: comment = ""
hdr[_keyprefix+key] = (val, drizdict[key]['comment']) | [
"def",
"writeDrizKeywords",
"(",
"hdr",
",",
"imgnum",
",",
"drizdict",
")",
":",
"_keyprefix",
"=",
"'D%03d'",
"%",
"imgnum",
"for",
"key",
"in",
"drizdict",
":",
"val",
"=",
"drizdict",
"[",
"key",
"]",
"[",
"'value'",
"]",
"if",
"val",
"is",
"None",... | Write basic drizzle-related keywords out to image header as a record
of the processing performed to create the image
The dictionary 'drizdict' will contain the keywords and values to be
written out to the header. | [
"Write",
"basic",
"drizzle",
"-",
"related",
"keywords",
"out",
"to",
"image",
"header",
"as",
"a",
"record",
"of",
"the",
"processing",
"performed",
"to",
"create",
"the",
"image"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/outputimage.py#L813-L827 | train | 35,616 |
spacetelescope/drizzlepac | drizzlepac/outputimage.py | OutputImage.find_kwupdate_location | def find_kwupdate_location(self,hdr,keyword):
"""
Find the last keyword in the output header that comes before the new
keyword in the original, full input headers.
This will rely on the original ordering of keywords from the original input
files in order to place the updated keyword in the correct location in case
the keyword was removed from the output header prior to calling this method.
"""
# start by looping through the full templates
kw_list = None
last_kw = None
for extn in self.fullhdrs:
if keyword in extn:
#indx = extn.ascard.index_of(keyword)
indx = extn.index(keyword)
kw_list = list(extn.keys())[:indx]
break
if kw_list:
# find which keyword from this list exists in header to be updated
for kw in kw_list[::-1]:
if kw in hdr:
last_kw = kw
break
# determine new value for the last keyword found before the HISTORY kws
if last_kw is None:
hdrkeys = list(hdr.keys())
i = -1
last_kw = hdrkeys[i]
while last_kw == 'HISTORY':
i -= 1
last_kw = hdrkeys[i]
return last_kw | python | def find_kwupdate_location(self,hdr,keyword):
"""
Find the last keyword in the output header that comes before the new
keyword in the original, full input headers.
This will rely on the original ordering of keywords from the original input
files in order to place the updated keyword in the correct location in case
the keyword was removed from the output header prior to calling this method.
"""
# start by looping through the full templates
kw_list = None
last_kw = None
for extn in self.fullhdrs:
if keyword in extn:
#indx = extn.ascard.index_of(keyword)
indx = extn.index(keyword)
kw_list = list(extn.keys())[:indx]
break
if kw_list:
# find which keyword from this list exists in header to be updated
for kw in kw_list[::-1]:
if kw in hdr:
last_kw = kw
break
# determine new value for the last keyword found before the HISTORY kws
if last_kw is None:
hdrkeys = list(hdr.keys())
i = -1
last_kw = hdrkeys[i]
while last_kw == 'HISTORY':
i -= 1
last_kw = hdrkeys[i]
return last_kw | [
"def",
"find_kwupdate_location",
"(",
"self",
",",
"hdr",
",",
"keyword",
")",
":",
"# start by looping through the full templates",
"kw_list",
"=",
"None",
"last_kw",
"=",
"None",
"for",
"extn",
"in",
"self",
".",
"fullhdrs",
":",
"if",
"keyword",
"in",
"extn",... | Find the last keyword in the output header that comes before the new
keyword in the original, full input headers.
This will rely on the original ordering of keywords from the original input
files in order to place the updated keyword in the correct location in case
the keyword was removed from the output header prior to calling this method. | [
"Find",
"the",
"last",
"keyword",
"in",
"the",
"output",
"header",
"that",
"comes",
"before",
"the",
"new",
"keyword",
"in",
"the",
"original",
"full",
"input",
"headers",
".",
"This",
"will",
"rely",
"on",
"the",
"original",
"ordering",
"of",
"keywords",
... | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/outputimage.py#L550-L582 | train | 35,617 |
spacetelescope/drizzlepac | drizzlepac/outputimage.py | OutputImage.addDrizKeywords | def addDrizKeywords(self,hdr,versions):
""" Add drizzle parameter keywords to header. """
# Extract some global information for the keywords
_geom = 'User parameters'
_imgnum = 0
for pl in self.parlist:
# Start by building up the keyword prefix based
# on the image number for the chip
#_keyprefix = 'D%03d'%_imgnum
_imgnum += 1
drizdict = DRIZ_KEYWORDS.copy()
# Update drizdict with current values
drizdict['VER']['value'] = pl['driz_version'][:44]
drizdict['DATA']['value'] = pl['data'][:64]
drizdict['DEXP']['value'] = pl['exptime']
drizdict['OUDA']['value'] = pl['outFinal'][:64]
drizdict['OUWE']['value'] = pl['outWeight'][:64]
if pl['outContext'] is None:
outcontext = ""
else:
outcontext = pl['outContext'][:64]
drizdict['OUCO']['value'] = outcontext
if self.single:
drizdict['MASK']['value'] = pl['singleDrizMask'][:64]
else:
drizdict['MASK']['value'] = pl['finalMask'][:64]
# Process the values of WT_SCL to be consistent with
# what IRAF Drizzle would output
if 'wt_scl_val' in pl:
_wtscl = pl['wt_scl_val']
else:
if pl['wt_scl'] == 'exptime': _wtscl = pl['exptime']
elif pl['wt_scl'] == 'expsq': _wtscl = pl['exptime']*pl['exptime']
else: _wtscl = pl['wt_scl']
drizdict['WTSC']['value'] = _wtscl
drizdict['KERN']['value'] = pl['kernel']
drizdict['PIXF']['value'] = pl['pixfrac']
drizdict['OUUN']['value'] = self.units
if pl['fillval'] is None:
_fillval = 'INDEF'
else:
_fillval = pl['fillval']
drizdict['FVAL']['value'] = _fillval
drizdict['WKEY']['value'] = pl['driz_wcskey']
drizdict['SCAL'] = {'value':pl['scale'],'comment':'Drizzle, pixel size (arcsec) of output image'}
drizdict['ISCL'] = {'value':pl['idcscale'],'comment':'Drizzle, default IDCTAB pixel size(arcsec)'}
# Now update header with values
writeDrizKeywords(hdr,_imgnum,drizdict)
del drizdict
# Add version information as HISTORY cards to the header
if versions is not None:
ver_str = "AstroDrizzle processing performed using: "
hdr.add_history(ver_str)
for k in versions.keys():
ver_str = ' '+str(k)+' Version '+str(versions[k])
hdr.add_history(ver_str) | python | def addDrizKeywords(self,hdr,versions):
""" Add drizzle parameter keywords to header. """
# Extract some global information for the keywords
_geom = 'User parameters'
_imgnum = 0
for pl in self.parlist:
# Start by building up the keyword prefix based
# on the image number for the chip
#_keyprefix = 'D%03d'%_imgnum
_imgnum += 1
drizdict = DRIZ_KEYWORDS.copy()
# Update drizdict with current values
drizdict['VER']['value'] = pl['driz_version'][:44]
drizdict['DATA']['value'] = pl['data'][:64]
drizdict['DEXP']['value'] = pl['exptime']
drizdict['OUDA']['value'] = pl['outFinal'][:64]
drizdict['OUWE']['value'] = pl['outWeight'][:64]
if pl['outContext'] is None:
outcontext = ""
else:
outcontext = pl['outContext'][:64]
drizdict['OUCO']['value'] = outcontext
if self.single:
drizdict['MASK']['value'] = pl['singleDrizMask'][:64]
else:
drizdict['MASK']['value'] = pl['finalMask'][:64]
# Process the values of WT_SCL to be consistent with
# what IRAF Drizzle would output
if 'wt_scl_val' in pl:
_wtscl = pl['wt_scl_val']
else:
if pl['wt_scl'] == 'exptime': _wtscl = pl['exptime']
elif pl['wt_scl'] == 'expsq': _wtscl = pl['exptime']*pl['exptime']
else: _wtscl = pl['wt_scl']
drizdict['WTSC']['value'] = _wtscl
drizdict['KERN']['value'] = pl['kernel']
drizdict['PIXF']['value'] = pl['pixfrac']
drizdict['OUUN']['value'] = self.units
if pl['fillval'] is None:
_fillval = 'INDEF'
else:
_fillval = pl['fillval']
drizdict['FVAL']['value'] = _fillval
drizdict['WKEY']['value'] = pl['driz_wcskey']
drizdict['SCAL'] = {'value':pl['scale'],'comment':'Drizzle, pixel size (arcsec) of output image'}
drizdict['ISCL'] = {'value':pl['idcscale'],'comment':'Drizzle, default IDCTAB pixel size(arcsec)'}
# Now update header with values
writeDrizKeywords(hdr,_imgnum,drizdict)
del drizdict
# Add version information as HISTORY cards to the header
if versions is not None:
ver_str = "AstroDrizzle processing performed using: "
hdr.add_history(ver_str)
for k in versions.keys():
ver_str = ' '+str(k)+' Version '+str(versions[k])
hdr.add_history(ver_str) | [
"def",
"addDrizKeywords",
"(",
"self",
",",
"hdr",
",",
"versions",
")",
":",
"# Extract some global information for the keywords",
"_geom",
"=",
"'User parameters'",
"_imgnum",
"=",
"0",
"for",
"pl",
"in",
"self",
".",
"parlist",
":",
"# Start by building up the keyw... | Add drizzle parameter keywords to header. | [
"Add",
"drizzle",
"parameter",
"keywords",
"to",
"header",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/outputimage.py#L585-L649 | train | 35,618 |
spacetelescope/drizzlepac | drizzlepac/linearfit.py | iter_fit_shifts | def iter_fit_shifts(xy,uv,nclip=3,sigma=3.0):
""" Perform an iterative-fit with 'nclip' iterations
"""
fit = fit_shifts(xy,uv)
if nclip is None: nclip = 0
# define index to initially include all points
for n in range(nclip):
resids = compute_resids(xy,uv,fit)
resids1d = np.sqrt(np.power(resids[:,0],2)+np.power(resids[:,1],2))
sig = resids1d.std()
# redefine what pixels will be included in next iteration
goodpix = resids1d < sigma*sig
xy = xy[goodpix]
uv = uv[goodpix]
fit = fit_shifts(xy,uv)
fit['img_coords'] = xy
fit['ref_coords'] = uv
return fit | python | def iter_fit_shifts(xy,uv,nclip=3,sigma=3.0):
""" Perform an iterative-fit with 'nclip' iterations
"""
fit = fit_shifts(xy,uv)
if nclip is None: nclip = 0
# define index to initially include all points
for n in range(nclip):
resids = compute_resids(xy,uv,fit)
resids1d = np.sqrt(np.power(resids[:,0],2)+np.power(resids[:,1],2))
sig = resids1d.std()
# redefine what pixels will be included in next iteration
goodpix = resids1d < sigma*sig
xy = xy[goodpix]
uv = uv[goodpix]
fit = fit_shifts(xy,uv)
fit['img_coords'] = xy
fit['ref_coords'] = uv
return fit | [
"def",
"iter_fit_shifts",
"(",
"xy",
",",
"uv",
",",
"nclip",
"=",
"3",
",",
"sigma",
"=",
"3.0",
")",
":",
"fit",
"=",
"fit_shifts",
"(",
"xy",
",",
"uv",
")",
"if",
"nclip",
"is",
"None",
":",
"nclip",
"=",
"0",
"# define index to initially include a... | Perform an iterative-fit with 'nclip' iterations | [
"Perform",
"an",
"iterative",
"-",
"fit",
"with",
"nclip",
"iterations"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/linearfit.py#L35-L54 | train | 35,619 |
spacetelescope/drizzlepac | drizzlepac/linearfit.py | fit_all | def fit_all(xy,uv,mode='rscale',center=None,verbose=True):
""" Performs an 'rscale' fit between matched lists of pixel positions xy and uv"""
if mode not in ['general', 'shift', 'rscale']:
mode = 'rscale'
if not isinstance(xy,np.ndarray):
# cast input list as numpy ndarray for fitting
xy = np.array(xy)
if not isinstance(uv,np.ndarray):
# cast input list as numpy ndarray for fitting
uv = np.array(uv)
if mode == 'shift':
logstr = 'Performing "shift" fit'
if verbose:
print(logstr)
else:
log.info(logstr)
result = fit_shifts(xy, uv)
elif mode == 'general':
logstr = 'Performing "general" fit'
if verbose:
print(logstr)
else:
log.info(logstr)
result = fit_general(xy, uv)
else:
logstr = 'Performing "rscale" fit'
if verbose:
print(logstr)
else:
log.info(logstr)
result = geomap_rscale(xy, uv, center=center)
return result | python | def fit_all(xy,uv,mode='rscale',center=None,verbose=True):
""" Performs an 'rscale' fit between matched lists of pixel positions xy and uv"""
if mode not in ['general', 'shift', 'rscale']:
mode = 'rscale'
if not isinstance(xy,np.ndarray):
# cast input list as numpy ndarray for fitting
xy = np.array(xy)
if not isinstance(uv,np.ndarray):
# cast input list as numpy ndarray for fitting
uv = np.array(uv)
if mode == 'shift':
logstr = 'Performing "shift" fit'
if verbose:
print(logstr)
else:
log.info(logstr)
result = fit_shifts(xy, uv)
elif mode == 'general':
logstr = 'Performing "general" fit'
if verbose:
print(logstr)
else:
log.info(logstr)
result = fit_general(xy, uv)
else:
logstr = 'Performing "rscale" fit'
if verbose:
print(logstr)
else:
log.info(logstr)
result = geomap_rscale(xy, uv, center=center)
return result | [
"def",
"fit_all",
"(",
"xy",
",",
"uv",
",",
"mode",
"=",
"'rscale'",
",",
"center",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"mode",
"not",
"in",
"[",
"'general'",
",",
"'shift'",
",",
"'rscale'",
"]",
":",
"mode",
"=",
"'rscale'"... | Performs an 'rscale' fit between matched lists of pixel positions xy and uv | [
"Performs",
"an",
"rscale",
"fit",
"between",
"matched",
"lists",
"of",
"pixel",
"positions",
"xy",
"and",
"uv"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/linearfit.py#L150-L185 | train | 35,620 |
spacetelescope/drizzlepac | drizzlepac/linearfit.py | fit_arrays | def fit_arrays(uv, xy):
""" Performs a generalized fit between matched lists of positions
given by the 2 column arrays xy and uv.
This function fits for translation, rotation, and scale changes
between 'xy' and 'uv', allowing for different scales and
orientations for X and Y axes.
=================================
DEVELOPMENT NOTE:
Checks need to be put in place to verify that
enough objects are available for a fit.
=================================
Output:
(Xo,Yo),Rot,(Scale,Sx,Sy)
where
Xo,Yo: offset,
Rot: rotation,
Scale: average scale change, and
Sx,Sy: scale changes in X and Y separately.
Algorithm and nomenclature provided by: Colin Cox (11 Nov 2004)
"""
if not isinstance(xy,np.ndarray):
# cast input list as numpy ndarray for fitting
xy = np.array(xy)
if not isinstance(uv,np.ndarray):
# cast input list as numpy ndarray for fitting
uv = np.array(uv)
# Set up products used for computing the fit
Sx = xy[:,0].sum()
Sy = xy[:,1].sum()
Su = uv[:,0].sum()
Sv = uv[:,1].sum()
Sux = np.dot(uv[:,0], xy[:,0])
Svx = np.dot(uv[:,1], xy[:,0])
Suy = np.dot(uv[:,0], xy[:,1])
Svy = np.dot(uv[:,1], xy[:,1])
Sxx = np.dot(xy[:,0], xy[:,0])
Syy = np.dot(xy[:,1], xy[:,1])
Sxy = np.dot(xy[:,0], xy[:,1])
n = len(xy[:,0])
M = np.array([[Sx, Sy, n], [Sxx, Sxy, Sx], [Sxy, Syy, Sy]])
U = np.array([Su, Sux, Suy])
V = np.array([Sv, Svx, Svy])
# The fit solutioN...
# where
# u = P0 + P1*x + P2*y
# v = Q0 + Q1*x + Q2*y
#
try:
invM = np.linalg.inv(M.astype(np.float64))
except np.linalg.LinAlgError:
raise SingularMatrixError(
"Singular matrix: suspected colinear points."
)
P = np.dot(invM, U).astype(np.float64)
Q = np.dot(invM, V).astype(np.float64)
if not (np.all(np.isfinite(P)) and np.all(np.isfinite(Q))):
raise ArithmeticError('Singular matrix.')
# Return the shift, rotation, and scale changes
return build_fit(P, Q, 'general') | python | def fit_arrays(uv, xy):
""" Performs a generalized fit between matched lists of positions
given by the 2 column arrays xy and uv.
This function fits for translation, rotation, and scale changes
between 'xy' and 'uv', allowing for different scales and
orientations for X and Y axes.
=================================
DEVELOPMENT NOTE:
Checks need to be put in place to verify that
enough objects are available for a fit.
=================================
Output:
(Xo,Yo),Rot,(Scale,Sx,Sy)
where
Xo,Yo: offset,
Rot: rotation,
Scale: average scale change, and
Sx,Sy: scale changes in X and Y separately.
Algorithm and nomenclature provided by: Colin Cox (11 Nov 2004)
"""
if not isinstance(xy,np.ndarray):
# cast input list as numpy ndarray for fitting
xy = np.array(xy)
if not isinstance(uv,np.ndarray):
# cast input list as numpy ndarray for fitting
uv = np.array(uv)
# Set up products used for computing the fit
Sx = xy[:,0].sum()
Sy = xy[:,1].sum()
Su = uv[:,0].sum()
Sv = uv[:,1].sum()
Sux = np.dot(uv[:,0], xy[:,0])
Svx = np.dot(uv[:,1], xy[:,0])
Suy = np.dot(uv[:,0], xy[:,1])
Svy = np.dot(uv[:,1], xy[:,1])
Sxx = np.dot(xy[:,0], xy[:,0])
Syy = np.dot(xy[:,1], xy[:,1])
Sxy = np.dot(xy[:,0], xy[:,1])
n = len(xy[:,0])
M = np.array([[Sx, Sy, n], [Sxx, Sxy, Sx], [Sxy, Syy, Sy]])
U = np.array([Su, Sux, Suy])
V = np.array([Sv, Svx, Svy])
# The fit solutioN...
# where
# u = P0 + P1*x + P2*y
# v = Q0 + Q1*x + Q2*y
#
try:
invM = np.linalg.inv(M.astype(np.float64))
except np.linalg.LinAlgError:
raise SingularMatrixError(
"Singular matrix: suspected colinear points."
)
P = np.dot(invM, U).astype(np.float64)
Q = np.dot(invM, V).astype(np.float64)
if not (np.all(np.isfinite(P)) and np.all(np.isfinite(Q))):
raise ArithmeticError('Singular matrix.')
# Return the shift, rotation, and scale changes
return build_fit(P, Q, 'general') | [
"def",
"fit_arrays",
"(",
"uv",
",",
"xy",
")",
":",
"if",
"not",
"isinstance",
"(",
"xy",
",",
"np",
".",
"ndarray",
")",
":",
"# cast input list as numpy ndarray for fitting",
"xy",
"=",
"np",
".",
"array",
"(",
"xy",
")",
"if",
"not",
"isinstance",
"(... | Performs a generalized fit between matched lists of positions
given by the 2 column arrays xy and uv.
This function fits for translation, rotation, and scale changes
between 'xy' and 'uv', allowing for different scales and
orientations for X and Y axes.
=================================
DEVELOPMENT NOTE:
Checks need to be put in place to verify that
enough objects are available for a fit.
=================================
Output:
(Xo,Yo),Rot,(Scale,Sx,Sy)
where
Xo,Yo: offset,
Rot: rotation,
Scale: average scale change, and
Sx,Sy: scale changes in X and Y separately.
Algorithm and nomenclature provided by: Colin Cox (11 Nov 2004) | [
"Performs",
"a",
"generalized",
"fit",
"between",
"matched",
"lists",
"of",
"positions",
"given",
"by",
"the",
"2",
"column",
"arrays",
"xy",
"and",
"uv",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/linearfit.py#L272-L340 | train | 35,621 |
spacetelescope/drizzlepac | drizzlepac/linearfit.py | apply_fit | def apply_fit(xy,coeffs):
""" Apply the coefficients from a linear fit to
an array of x,y positions.
The coeffs come from the 'coeffs' member of the
'fit_arrays()' output.
"""
x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]
y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]
return x_new,y_new | python | def apply_fit(xy,coeffs):
""" Apply the coefficients from a linear fit to
an array of x,y positions.
The coeffs come from the 'coeffs' member of the
'fit_arrays()' output.
"""
x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]
y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]
return x_new,y_new | [
"def",
"apply_fit",
"(",
"xy",
",",
"coeffs",
")",
":",
"x_new",
"=",
"coeffs",
"[",
"0",
"]",
"[",
"2",
"]",
"+",
"coeffs",
"[",
"0",
"]",
"[",
"0",
"]",
"*",
"xy",
"[",
":",
",",
"0",
"]",
"+",
"coeffs",
"[",
"0",
"]",
"[",
"1",
"]",
... | Apply the coefficients from a linear fit to
an array of x,y positions.
The coeffs come from the 'coeffs' member of the
'fit_arrays()' output. | [
"Apply",
"the",
"coefficients",
"from",
"a",
"linear",
"fit",
"to",
"an",
"array",
"of",
"x",
"y",
"positions",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/linearfit.py#L448-L458 | train | 35,622 |
spacetelescope/drizzlepac | drizzlepac/linearfit.py | compute_resids | def compute_resids(xy,uv,fit):
""" Compute the residuals based on fit and input arrays to the fit
"""
print('FIT coeffs: ',fit['coeffs'])
xn,yn = apply_fit(uv,fit['coeffs'])
resids = xy - np.transpose([xn,yn])
return resids | python | def compute_resids(xy,uv,fit):
""" Compute the residuals based on fit and input arrays to the fit
"""
print('FIT coeffs: ',fit['coeffs'])
xn,yn = apply_fit(uv,fit['coeffs'])
resids = xy - np.transpose([xn,yn])
return resids | [
"def",
"compute_resids",
"(",
"xy",
",",
"uv",
",",
"fit",
")",
":",
"print",
"(",
"'FIT coeffs: '",
",",
"fit",
"[",
"'coeffs'",
"]",
")",
"xn",
",",
"yn",
"=",
"apply_fit",
"(",
"uv",
",",
"fit",
"[",
"'coeffs'",
"]",
")",
"resids",
"=",
"xy",
... | Compute the residuals based on fit and input arrays to the fit | [
"Compute",
"the",
"residuals",
"based",
"on",
"fit",
"and",
"input",
"arrays",
"to",
"the",
"fit"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/linearfit.py#L461-L467 | train | 35,623 |
spacetelescope/drizzlepac | drizzlepac/astrodrizzle.py | AstroDrizzle | def AstroDrizzle(input=None, mdriztab=False, editpars=False, configobj=None,
wcsmap=None, **input_dict):
""" AstroDrizzle command-line interface """
# Support input of filenames from command-line without a parameter name
# then copy this into input_dict for merging with TEAL ConfigObj
# parameters.
# Load any user-specified configobj
if isinstance(configobj, (str, bytes)):
if configobj == 'defaults':
# load "TEAL"-defaults (from ~/.teal/):
configobj = teal.load(__taskname__)
else:
if not os.path.exists(configobj):
raise RuntimeError('Cannot find .cfg file: '+configobj)
configobj = teal.load(configobj, strict=False)
elif configobj is None:
# load 'astrodrizzle' parameter defaults as described in the docs:
configobj = teal.load(__taskname__, defaults=True)
if input and not util.is_blank(input):
input_dict['input'] = input
elif configobj is None:
raise TypeError("AstroDrizzle() needs either 'input' or "
"'configobj' arguments")
if 'updatewcs' in input_dict: # user trying to explicitly turn on updatewcs
configobj['updatewcs'] = input_dict['updatewcs']
del input_dict['updatewcs']
# 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 values) are folded in
# with a fully populated configObj instance.
try:
configObj = util.getDefaultConfigObj(__taskname__, configobj,
input_dict,
loadOnly=(not editpars))
log.debug('')
log.debug("INPUT_DICT:")
util.print_cfg(input_dict, log.debug)
log.debug('')
# If user specifies optional parameter for final_wcs specification in input_dict,
# insure that the final_wcs step gets turned on
util.applyUserPars_steps(configObj, input_dict, step='3a')
util.applyUserPars_steps(configObj, input_dict, step='7a')
except ValueError:
print("Problem with input parameters. Quitting...", file=sys.stderr)
return
if not configObj:
return
configObj['mdriztab'] = mdriztab
# If 'editpars' was set to True, util.getDefaultConfigObj() will have
# already called 'run()'.
if not editpars:
run(configObj, wcsmap=wcsmap) | python | def AstroDrizzle(input=None, mdriztab=False, editpars=False, configobj=None,
wcsmap=None, **input_dict):
""" AstroDrizzle command-line interface """
# Support input of filenames from command-line without a parameter name
# then copy this into input_dict for merging with TEAL ConfigObj
# parameters.
# Load any user-specified configobj
if isinstance(configobj, (str, bytes)):
if configobj == 'defaults':
# load "TEAL"-defaults (from ~/.teal/):
configobj = teal.load(__taskname__)
else:
if not os.path.exists(configobj):
raise RuntimeError('Cannot find .cfg file: '+configobj)
configobj = teal.load(configobj, strict=False)
elif configobj is None:
# load 'astrodrizzle' parameter defaults as described in the docs:
configobj = teal.load(__taskname__, defaults=True)
if input and not util.is_blank(input):
input_dict['input'] = input
elif configobj is None:
raise TypeError("AstroDrizzle() needs either 'input' or "
"'configobj' arguments")
if 'updatewcs' in input_dict: # user trying to explicitly turn on updatewcs
configobj['updatewcs'] = input_dict['updatewcs']
del input_dict['updatewcs']
# 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 values) are folded in
# with a fully populated configObj instance.
try:
configObj = util.getDefaultConfigObj(__taskname__, configobj,
input_dict,
loadOnly=(not editpars))
log.debug('')
log.debug("INPUT_DICT:")
util.print_cfg(input_dict, log.debug)
log.debug('')
# If user specifies optional parameter for final_wcs specification in input_dict,
# insure that the final_wcs step gets turned on
util.applyUserPars_steps(configObj, input_dict, step='3a')
util.applyUserPars_steps(configObj, input_dict, step='7a')
except ValueError:
print("Problem with input parameters. Quitting...", file=sys.stderr)
return
if not configObj:
return
configObj['mdriztab'] = mdriztab
# If 'editpars' was set to True, util.getDefaultConfigObj() will have
# already called 'run()'.
if not editpars:
run(configObj, wcsmap=wcsmap) | [
"def",
"AstroDrizzle",
"(",
"input",
"=",
"None",
",",
"mdriztab",
"=",
"False",
",",
"editpars",
"=",
"False",
",",
"configobj",
"=",
"None",
",",
"wcsmap",
"=",
"None",
",",
"*",
"*",
"input_dict",
")",
":",
"# Support input of filenames from command-line wi... | AstroDrizzle command-line interface | [
"AstroDrizzle",
"command",
"-",
"line",
"interface"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/astrodrizzle.py#L59-L118 | train | 35,624 |
spacetelescope/drizzlepac | drizzlepac/astrodrizzle.py | _dbg_dump_virtual_outputs | def _dbg_dump_virtual_outputs(imgObjList):
""" dump some helpful information. strictly for debugging """
global _fidx
tag = 'virtual'
log.info((tag+' ')*7)
for iii in imgObjList:
log.info('-'*80)
log.info(tag+' orig nm: '+iii._original_file_name)
log.info(tag+' names.data: '+str(iii.outputNames["data"]))
log.info(tag+' names.orig: '+str(iii.outputNames["origFilename"]))
log.info(tag+' id: '+str(id(iii)))
log.info(tag+' in.mem: '+str(iii.inmemory))
log.info(tag+' vo items...')
for vok in sorted(iii.virtualOutputs.keys()):
FITSOBJ = iii.virtualOutputs[vok]
log.info(tag+': '+str(vok)+' = '+str(FITSOBJ))
if vok.endswith('.fits'):
if not hasattr(FITSOBJ, 'data'):
FITSOBJ = FITSOBJ[0] # list of PrimaryHDU ?
if not hasattr(FITSOBJ, 'data'):
FITSOBJ = FITSOBJ[0] # was list of HDUList ?
dbgname = 'DEBUG_%02d_'%(_fidx,)
dbgname+=os.path.basename(vok)
_fidx+=1
FITSOBJ.writeto(dbgname)
log.info(tag+' wrote: '+dbgname)
log.info('\n'+vok)
if hasattr(FITSOBJ, 'data'):
log.info(str(FITSOBJ._summary()))
log.info('min and max are: '+str( (FITSOBJ.data.min(),
FITSOBJ.data.max()) ))
log.info('avg and sum are: '+str( (FITSOBJ.data.mean(),
FITSOBJ.data.sum()) ))
# log.info(str(FITSOBJ.data)[:75])
else:
log.info(vok+' has no .data attr')
log.info(str(type(FITSOBJ)))
log.info(vok+'\n')
log.info('-'*80) | python | def _dbg_dump_virtual_outputs(imgObjList):
""" dump some helpful information. strictly for debugging """
global _fidx
tag = 'virtual'
log.info((tag+' ')*7)
for iii in imgObjList:
log.info('-'*80)
log.info(tag+' orig nm: '+iii._original_file_name)
log.info(tag+' names.data: '+str(iii.outputNames["data"]))
log.info(tag+' names.orig: '+str(iii.outputNames["origFilename"]))
log.info(tag+' id: '+str(id(iii)))
log.info(tag+' in.mem: '+str(iii.inmemory))
log.info(tag+' vo items...')
for vok in sorted(iii.virtualOutputs.keys()):
FITSOBJ = iii.virtualOutputs[vok]
log.info(tag+': '+str(vok)+' = '+str(FITSOBJ))
if vok.endswith('.fits'):
if not hasattr(FITSOBJ, 'data'):
FITSOBJ = FITSOBJ[0] # list of PrimaryHDU ?
if not hasattr(FITSOBJ, 'data'):
FITSOBJ = FITSOBJ[0] # was list of HDUList ?
dbgname = 'DEBUG_%02d_'%(_fidx,)
dbgname+=os.path.basename(vok)
_fidx+=1
FITSOBJ.writeto(dbgname)
log.info(tag+' wrote: '+dbgname)
log.info('\n'+vok)
if hasattr(FITSOBJ, 'data'):
log.info(str(FITSOBJ._summary()))
log.info('min and max are: '+str( (FITSOBJ.data.min(),
FITSOBJ.data.max()) ))
log.info('avg and sum are: '+str( (FITSOBJ.data.mean(),
FITSOBJ.data.sum()) ))
# log.info(str(FITSOBJ.data)[:75])
else:
log.info(vok+' has no .data attr')
log.info(str(type(FITSOBJ)))
log.info(vok+'\n')
log.info('-'*80) | [
"def",
"_dbg_dump_virtual_outputs",
"(",
"imgObjList",
")",
":",
"global",
"_fidx",
"tag",
"=",
"'virtual'",
"log",
".",
"info",
"(",
"(",
"tag",
"+",
"' '",
")",
"*",
"7",
")",
"for",
"iii",
"in",
"imgObjList",
":",
"log",
".",
"info",
"(",
"'-'",
... | dump some helpful information. strictly for debugging | [
"dump",
"some",
"helpful",
"information",
".",
"strictly",
"for",
"debugging"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/astrodrizzle.py#L303-L341 | train | 35,625 |
spacetelescope/drizzlepac | drizzlepac/wfc3Data.py | WFC3UVISInputImage.getdarkcurrent | def getdarkcurrent(self,chip):
"""
Return the dark current for the WFC3 UVIS detector. This value
will be contained within an instrument specific keyword.
Returns
-------
darkcurrent: float
The dark current value with **units of electrons**.
"""
darkcurrent = 0.
try:
darkcurrent = self._image[self.scienceExt, chip].header['MEANDARK']
except:
msg = "#############################################\n"
msg += "# #\n"
msg += "# Error: #\n"
msg += "# Cannot find the value for 'MEANDARK' #\n"
msg += "# in the image header. WFC3 input images #\n"
msg += "# are expected to have this header #\n"
msg += "# keyword. #\n"
msg += "# #\n"
msg += "# Error occured in WFC3UVISInputImage class #\n"
msg += "# #\n"
msg += "#############################################\n"
raise ValueError(msg)
return darkcurrent | python | def getdarkcurrent(self,chip):
"""
Return the dark current for the WFC3 UVIS detector. This value
will be contained within an instrument specific keyword.
Returns
-------
darkcurrent: float
The dark current value with **units of electrons**.
"""
darkcurrent = 0.
try:
darkcurrent = self._image[self.scienceExt, chip].header['MEANDARK']
except:
msg = "#############################################\n"
msg += "# #\n"
msg += "# Error: #\n"
msg += "# Cannot find the value for 'MEANDARK' #\n"
msg += "# in the image header. WFC3 input images #\n"
msg += "# are expected to have this header #\n"
msg += "# keyword. #\n"
msg += "# #\n"
msg += "# Error occured in WFC3UVISInputImage class #\n"
msg += "# #\n"
msg += "#############################################\n"
raise ValueError(msg)
return darkcurrent | [
"def",
"getdarkcurrent",
"(",
"self",
",",
"chip",
")",
":",
"darkcurrent",
"=",
"0.",
"try",
":",
"darkcurrent",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
".",
"header",
"[",
"'MEANDARK'",
"]",
"except",
":",
"msg",... | Return the dark current for the WFC3 UVIS detector. This value
will be contained within an instrument specific keyword.
Returns
-------
darkcurrent: float
The dark current value with **units of electrons**. | [
"Return",
"the",
"dark",
"current",
"for",
"the",
"WFC3",
"UVIS",
"detector",
".",
"This",
"value",
"will",
"be",
"contained",
"within",
"an",
"instrument",
"specific",
"keyword",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wfc3Data.py#L112-L141 | train | 35,626 |
spacetelescope/drizzlepac | drizzlepac/wfc3Data.py | WFC3IRInputImage.doUnitConversions | def doUnitConversions(self):
"""WF3 IR data come out in electrons, and I imagine the
photometry keywords will be calculated as such, so no image
manipulation needs be done between native and electrons """
# Image information
_handle = fileutil.openImage(self._filename, mode='readonly', memmap=False)
for chip in self.returnAllChips(extname=self.scienceExt):
conversionFactor = 1.0
if '/S' in chip._bunit:
conversionFactor = chip._exptime
else:
print("Input %s[%s,%d] already in units of ELECTRONS"
%(self._filename,self.scienceExt,chip._chip))
chip._effGain = 1.0# chip._gain #1.
chip._conversionFactor = conversionFactor #1.
_handle.close()
self._effGain= 1.0 | python | def doUnitConversions(self):
"""WF3 IR data come out in electrons, and I imagine the
photometry keywords will be calculated as such, so no image
manipulation needs be done between native and electrons """
# Image information
_handle = fileutil.openImage(self._filename, mode='readonly', memmap=False)
for chip in self.returnAllChips(extname=self.scienceExt):
conversionFactor = 1.0
if '/S' in chip._bunit:
conversionFactor = chip._exptime
else:
print("Input %s[%s,%d] already in units of ELECTRONS"
%(self._filename,self.scienceExt,chip._chip))
chip._effGain = 1.0# chip._gain #1.
chip._conversionFactor = conversionFactor #1.
_handle.close()
self._effGain= 1.0 | [
"def",
"doUnitConversions",
"(",
"self",
")",
":",
"# Image information",
"_handle",
"=",
"fileutil",
".",
"openImage",
"(",
"self",
".",
"_filename",
",",
"mode",
"=",
"'readonly'",
",",
"memmap",
"=",
"False",
")",
"for",
"chip",
"in",
"self",
".",
"retu... | WF3 IR data come out in electrons, and I imagine the
photometry keywords will be calculated as such, so no image
manipulation needs be done between native and electrons | [
"WF3",
"IR",
"data",
"come",
"out",
"in",
"electrons",
"and",
"I",
"imagine",
"the",
"photometry",
"keywords",
"will",
"be",
"calculated",
"as",
"such",
"so",
"no",
"image",
"manipulation",
"needs",
"be",
"done",
"between",
"native",
"and",
"electrons"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wfc3Data.py#L165-L184 | train | 35,627 |
spacetelescope/drizzlepac | drizzlepac/acsData.py | ACSInputImage.getdarkcurrent | def getdarkcurrent(self,extver):
"""
Return the dark current for the ACS 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 value for the ACS detector in **units of electrons**.
"""
darkcurrent=0.
try:
darkcurrent = self._image[self.scienceExt,extver].header['MEANDARK']
except:
str = "#############################################\n"
str += "# #\n"
str += "# Error: #\n"
str += "# Cannot find the value for 'MEANDARK' #\n"
str += "# in the image header. ACS input images #\n"
str += "# are expected to have this header #\n"
str += "# keyword. #\n"
str += "# #\n"
str += "# Error occured in the ACSInputImage class #\n"
str += "# #\n"
str += "#############################################\n"
raise ValueError(str)
return darkcurrent | python | def getdarkcurrent(self,extver):
"""
Return the dark current for the ACS 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 value for the ACS detector in **units of electrons**.
"""
darkcurrent=0.
try:
darkcurrent = self._image[self.scienceExt,extver].header['MEANDARK']
except:
str = "#############################################\n"
str += "# #\n"
str += "# Error: #\n"
str += "# Cannot find the value for 'MEANDARK' #\n"
str += "# in the image header. ACS input images #\n"
str += "# are expected to have this header #\n"
str += "# keyword. #\n"
str += "# #\n"
str += "# Error occured in the ACSInputImage class #\n"
str += "# #\n"
str += "#############################################\n"
raise ValueError(str)
return darkcurrent | [
"def",
"getdarkcurrent",
"(",
"self",
",",
"extver",
")",
":",
"darkcurrent",
"=",
"0.",
"try",
":",
"darkcurrent",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"extver",
"]",
".",
"header",
"[",
"'MEANDARK'",
"]",
"except",
":",
"s... | Return the dark current for the ACS 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 value for the ACS detector in **units of electrons**. | [
"Return",
"the",
"dark",
"current",
"for",
"the",
"ACS",
"detector",
".",
"This",
"value",
"will",
"be",
"contained",
"within",
"an",
"instrument",
"specific",
"keyword",
".",
"The",
"value",
"in",
"the",
"image",
"header",
"will",
"be",
"converted",
"to",
... | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/acsData.py#L58-L88 | train | 35,628 |
spacetelescope/drizzlepac | drizzlepac/acsData.py | SBCInputImage.setInstrumentParameters | def setInstrumentParameters(self,instrpars):
""" Sets the instrument parameters.
"""
pri_header = self._image[0].header
if self._isNotValid (instrpars['gain'], instrpars['gnkeyword']):
instrpars['gnkeyword'] = None
if self._isNotValid (instrpars['rdnoise'], instrpars['rnkeyword']):
instrpars['rnkeyword'] = None
if self._isNotValid (instrpars['exptime'], instrpars['expkeyword']):
instrpars['expkeyword'] = 'EXPTIME'
# We need to treat Read Noise and Gain as a special case since it is
# not populated in the SBC primary header for the MAMA
for chip in self.returnAllChips(extname=self.scienceExt):
chip._gain = 1.0 #self.getInstrParameter("", pri_header,
# instrpars['gnkeyword'])
chip._rdnoise = 0.0 #self.getInstrParameter("", pri_header,
# instrpars['rnkeyword'])
chip._exptime = self.getInstrParameter(instrpars['exptime'], pri_header,
instrpars['expkeyword'])
if chip._exptime is None:
print('ERROR: invalid instrument task parameter')
raise ValueError
# We need to determine if the user has used the default readnoise/gain value
# since if not, they will need to supply a gain/readnoise value as well
usingDefaultGain = instrpars['gnkeyword'] is None
usingDefaultReadnoise = instrpars['rnkeyword'] is None
# Set the default readnoise or gain values based upon the amount of user input given.
# Case 1: User supplied no gain or readnoise information
if usingDefaultReadnoise and usingDefaultGain:
# Set the default gain and readnoise values
self._setSBCchippars()
# Case 2: The user has supplied a value for gain
elif usingDefaultReadnoise and not usingDefaultGain:
# Set the default readnoise value
self._setDefaultSBCReadnoise()
# Case 3: The user has supplied a value for readnoise
elif not usingDefaultReadnoise and usingDefaultGain:
# Set the default gain value
self._setDefaultSBCGain()
else:
# In this case, the user has specified both a gain and readnoise values. Just use them as is.
pass | python | def setInstrumentParameters(self,instrpars):
""" Sets the instrument parameters.
"""
pri_header = self._image[0].header
if self._isNotValid (instrpars['gain'], instrpars['gnkeyword']):
instrpars['gnkeyword'] = None
if self._isNotValid (instrpars['rdnoise'], instrpars['rnkeyword']):
instrpars['rnkeyword'] = None
if self._isNotValid (instrpars['exptime'], instrpars['expkeyword']):
instrpars['expkeyword'] = 'EXPTIME'
# We need to treat Read Noise and Gain as a special case since it is
# not populated in the SBC primary header for the MAMA
for chip in self.returnAllChips(extname=self.scienceExt):
chip._gain = 1.0 #self.getInstrParameter("", pri_header,
# instrpars['gnkeyword'])
chip._rdnoise = 0.0 #self.getInstrParameter("", pri_header,
# instrpars['rnkeyword'])
chip._exptime = self.getInstrParameter(instrpars['exptime'], pri_header,
instrpars['expkeyword'])
if chip._exptime is None:
print('ERROR: invalid instrument task parameter')
raise ValueError
# We need to determine if the user has used the default readnoise/gain value
# since if not, they will need to supply a gain/readnoise value as well
usingDefaultGain = instrpars['gnkeyword'] is None
usingDefaultReadnoise = instrpars['rnkeyword'] is None
# Set the default readnoise or gain values based upon the amount of user input given.
# Case 1: User supplied no gain or readnoise information
if usingDefaultReadnoise and usingDefaultGain:
# Set the default gain and readnoise values
self._setSBCchippars()
# Case 2: The user has supplied a value for gain
elif usingDefaultReadnoise and not usingDefaultGain:
# Set the default readnoise value
self._setDefaultSBCReadnoise()
# Case 3: The user has supplied a value for readnoise
elif not usingDefaultReadnoise and usingDefaultGain:
# Set the default gain value
self._setDefaultSBCGain()
else:
# In this case, the user has specified both a gain and readnoise values. Just use them as is.
pass | [
"def",
"setInstrumentParameters",
"(",
"self",
",",
"instrpars",
")",
":",
"pri_header",
"=",
"self",
".",
"_image",
"[",
"0",
"]",
".",
"header",
"if",
"self",
".",
"_isNotValid",
"(",
"instrpars",
"[",
"'gain'",
"]",
",",
"instrpars",
"[",
"'gnkeyword'",... | Sets the instrument parameters. | [
"Sets",
"the",
"instrument",
"parameters",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/acsData.py#L232-L278 | train | 35,629 |
spacetelescope/drizzlepac | drizzlepac/minmed.py | minmed._sumImages | def _sumImages(self,numarrayObjectList):
""" Sum a list of numarray objects. """
if numarrayObjectList in [None, []]:
return None
tsum = np.zeros(numarrayObjectList[0].shape, dtype=numarrayObjectList[0].dtype)
for image in numarrayObjectList:
tsum += image
return tsum | python | def _sumImages(self,numarrayObjectList):
""" Sum a list of numarray objects. """
if numarrayObjectList in [None, []]:
return None
tsum = np.zeros(numarrayObjectList[0].shape, dtype=numarrayObjectList[0].dtype)
for image in numarrayObjectList:
tsum += image
return tsum | [
"def",
"_sumImages",
"(",
"self",
",",
"numarrayObjectList",
")",
":",
"if",
"numarrayObjectList",
"in",
"[",
"None",
",",
"[",
"]",
"]",
":",
"return",
"None",
"tsum",
"=",
"np",
".",
"zeros",
"(",
"numarrayObjectList",
"[",
"0",
"]",
".",
"shape",
",... | Sum a list of numarray objects. | [
"Sum",
"a",
"list",
"of",
"numarray",
"objects",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/minmed.py#L336-L346 | train | 35,630 |
spacetelescope/drizzlepac | drizzlepac/findobj.py | precompute_sharp_round | def precompute_sharp_round(nxk, nyk, xc, yc):
"""
Pre-computes mask arrays to be used by the 'sharp_round' function
for roundness computations based on two- and four-fold symmetries.
"""
# Create arrays for the two- and four-fold symmetry computations:
s4m = np.ones((nyk,nxk),dtype=np.int16)
s4m[yc, xc] = 0
s2m = np.ones((nyk,nxk),dtype=np.int16)
s2m[yc, xc] = 0
s2m[yc:nyk, 0:xc] = -1;
s2m[0:yc+1, xc+1:nxk] = -1;
return s2m, s4m | python | def precompute_sharp_round(nxk, nyk, xc, yc):
"""
Pre-computes mask arrays to be used by the 'sharp_round' function
for roundness computations based on two- and four-fold symmetries.
"""
# Create arrays for the two- and four-fold symmetry computations:
s4m = np.ones((nyk,nxk),dtype=np.int16)
s4m[yc, xc] = 0
s2m = np.ones((nyk,nxk),dtype=np.int16)
s2m[yc, xc] = 0
s2m[yc:nyk, 0:xc] = -1;
s2m[0:yc+1, xc+1:nxk] = -1;
return s2m, s4m | [
"def",
"precompute_sharp_round",
"(",
"nxk",
",",
"nyk",
",",
"xc",
",",
"yc",
")",
":",
"# Create arrays for the two- and four-fold symmetry computations:",
"s4m",
"=",
"np",
".",
"ones",
"(",
"(",
"nyk",
",",
"nxk",
")",
",",
"dtype",
"=",
"np",
".",
"int1... | Pre-computes mask arrays to be used by the 'sharp_round' function
for roundness computations based on two- and four-fold symmetries. | [
"Pre",
"-",
"computes",
"mask",
"arrays",
"to",
"be",
"used",
"by",
"the",
"sharp_round",
"function",
"for",
"roundness",
"computations",
"based",
"on",
"two",
"-",
"and",
"four",
"-",
"fold",
"symmetries",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/findobj.py#L353-L368 | train | 35,631 |
spacetelescope/drizzlepac | drizzlepac/mdzhandler.py | getMdriztabParameters | def getMdriztabParameters(files):
""" Gets entry in MDRIZTAB where task parameters live.
This method returns a record array mapping the selected
row.
"""
# Get the MDRIZTAB table file name from the primary header.
# It is gotten from the first file in the input list. No
# consistency checks are performed.
_fileName = files[0]
_header = fileutil.getHeader(_fileName)
if 'MDRIZTAB' in _header:
_tableName = _header['MDRIZTAB']
else:
raise KeyError("No MDRIZTAB found in file " + _fileName)
_tableName = fileutil.osfn(_tableName)
# Now get the filters from the primary header.
_filters = fileutil.getFilterNames(_header)
# Specifically check to see whether the MDRIZTAB file can be found
mtab_path = os.path.split(_tableName)[0] # protect against no path given for _tableName
if mtab_path and not os.path.exists(mtab_path): # check path first, if given
raise IOError("Directory for MDRIZTAB '%s' could not be accessed!"%mtab_path)
if not os.path.exists(_tableName): # then check for the table itself
raise IOError("MDRIZTAB table '%s' could not be found!"%_tableName)
# Open MDRIZTAB file.
try:
_mdriztab = fits.open(_tableName, memmap=False)
except:
raise IOError("MDRIZTAB table '%s' not valid!" % _tableName)
# Look for matching rows based on filter name. If no
# match, pick up rows for the default filter.
_rows = _getRowsByFilter(_mdriztab, _filters)
if _rows == []:
_rows = _getRowsByFilter(_mdriztab, 'ANY')
# Now look for the row that matches the number of images.
# The logic below assumes that rows for a given filter
# are arranged in ascending order of the 'numimage' field.
_nimages = len(files)
_row = 0
for i in _rows:
_numimages = _mdriztab[1].data.field('numimages')[i]
if _nimages >= _numimages:
_row = i
print('- MDRIZTAB: AstroDrizzle parameters read from row %s.'%(_row+1))
mpars = _mdriztab[1].data[_row]
_mdriztab.close()
interpreted = _interpretMdriztabPars(mpars)
if "staticfile" in interpreted:
interpreted.pop("staticfile")
return interpreted | python | def getMdriztabParameters(files):
""" Gets entry in MDRIZTAB where task parameters live.
This method returns a record array mapping the selected
row.
"""
# Get the MDRIZTAB table file name from the primary header.
# It is gotten from the first file in the input list. No
# consistency checks are performed.
_fileName = files[0]
_header = fileutil.getHeader(_fileName)
if 'MDRIZTAB' in _header:
_tableName = _header['MDRIZTAB']
else:
raise KeyError("No MDRIZTAB found in file " + _fileName)
_tableName = fileutil.osfn(_tableName)
# Now get the filters from the primary header.
_filters = fileutil.getFilterNames(_header)
# Specifically check to see whether the MDRIZTAB file can be found
mtab_path = os.path.split(_tableName)[0] # protect against no path given for _tableName
if mtab_path and not os.path.exists(mtab_path): # check path first, if given
raise IOError("Directory for MDRIZTAB '%s' could not be accessed!"%mtab_path)
if not os.path.exists(_tableName): # then check for the table itself
raise IOError("MDRIZTAB table '%s' could not be found!"%_tableName)
# Open MDRIZTAB file.
try:
_mdriztab = fits.open(_tableName, memmap=False)
except:
raise IOError("MDRIZTAB table '%s' not valid!" % _tableName)
# Look for matching rows based on filter name. If no
# match, pick up rows for the default filter.
_rows = _getRowsByFilter(_mdriztab, _filters)
if _rows == []:
_rows = _getRowsByFilter(_mdriztab, 'ANY')
# Now look for the row that matches the number of images.
# The logic below assumes that rows for a given filter
# are arranged in ascending order of the 'numimage' field.
_nimages = len(files)
_row = 0
for i in _rows:
_numimages = _mdriztab[1].data.field('numimages')[i]
if _nimages >= _numimages:
_row = i
print('- MDRIZTAB: AstroDrizzle parameters read from row %s.'%(_row+1))
mpars = _mdriztab[1].data[_row]
_mdriztab.close()
interpreted = _interpretMdriztabPars(mpars)
if "staticfile" in interpreted:
interpreted.pop("staticfile")
return interpreted | [
"def",
"getMdriztabParameters",
"(",
"files",
")",
":",
"# Get the MDRIZTAB table file name from the primary header.",
"# It is gotten from the first file in the input list. No",
"# consistency checks are performed.",
"_fileName",
"=",
"files",
"[",
"0",
"]",
"_header",
"=",
"fileu... | Gets entry in MDRIZTAB where task parameters live.
This method returns a record array mapping the selected
row. | [
"Gets",
"entry",
"in",
"MDRIZTAB",
"where",
"task",
"parameters",
"live",
".",
"This",
"method",
"returns",
"a",
"record",
"array",
"mapping",
"the",
"selected",
"row",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/mdzhandler.py#L17-L76 | train | 35,632 |
spacetelescope/drizzlepac | drizzlepac/mdzhandler.py | _interpretMdriztabPars | def _interpretMdriztabPars(rec):
"""
Collect task parameters from the MDRIZTAB record and
update the master parameters list with those values
Note that parameters read from the MDRIZTAB record must
be cleaned up in a similar way that parameters read
from the user interface are.
"""
tabdict = {}
# for each entry in the record...
for indx in range(len(rec.array.names)):
# ... get the name, format, and value.
_name = rec.array.names[indx]
_format = rec.array.formats[indx]
_value = rec.field(_name)
# Translate names from MDRIZTAB columns names to
# input parameter names found in IRAF par file.
#
#if _name.find('final') > -1: _name = 'driz_'+_name
if _name in ['shiftfile','mdriztab']:
continue
drizstep_names = ['driz_sep_','final_']
if _name in ['refimage','bits']:
for dnames in drizstep_names:
tabdict[dnames+_name] = _value
continue
if _name in ['driz_sep_bits','final_bits']:
tabdict[_name] = str(_value)
continue
if _name == 'coeffs':
_val = True
if _value in ['INDEF',None,"None",'',' ']: _val = False
tabdict[_name] = _val
continue
par_table = {'subsky':'skysub','crbitval':'crbit','readnoise':'rdnoise'}
if _name in par_table:
_name = par_table[_name]
# We do not care about the first two columns at this point
# as they are only used for selecting the rows
if _name != 'filter' and _name != 'numimages':
# start by determining the format type of the parameter
_fmt = findFormat(_format)
# Based on format type, apply proper conversion/cleaning
if (_fmt == 'a') or (_fmt == 'A'):
_val = cleanBlank(_value)
if _val is None:
_val = ''
elif (_format == 'i1') or (_format=='1L'):
_val = toBoolean(_value)
elif (_format == 'i4') or (_format == '1J'):
_val = cleanInt(_value)
elif ('E' in _format) or (_format == 'f4') :
_val = cleanNaN(_value)
else:
print('MDRIZTAB column ',_name,' has unrecognized format',_format)
raise ValueError
if _name in ['ra','dec']:
for dnames in drizstep_names:
tabdict[dnames+_name] = _val
else:
tabdict[_name] = _val
return tabdict | python | def _interpretMdriztabPars(rec):
"""
Collect task parameters from the MDRIZTAB record and
update the master parameters list with those values
Note that parameters read from the MDRIZTAB record must
be cleaned up in a similar way that parameters read
from the user interface are.
"""
tabdict = {}
# for each entry in the record...
for indx in range(len(rec.array.names)):
# ... get the name, format, and value.
_name = rec.array.names[indx]
_format = rec.array.formats[indx]
_value = rec.field(_name)
# Translate names from MDRIZTAB columns names to
# input parameter names found in IRAF par file.
#
#if _name.find('final') > -1: _name = 'driz_'+_name
if _name in ['shiftfile','mdriztab']:
continue
drizstep_names = ['driz_sep_','final_']
if _name in ['refimage','bits']:
for dnames in drizstep_names:
tabdict[dnames+_name] = _value
continue
if _name in ['driz_sep_bits','final_bits']:
tabdict[_name] = str(_value)
continue
if _name == 'coeffs':
_val = True
if _value in ['INDEF',None,"None",'',' ']: _val = False
tabdict[_name] = _val
continue
par_table = {'subsky':'skysub','crbitval':'crbit','readnoise':'rdnoise'}
if _name in par_table:
_name = par_table[_name]
# We do not care about the first two columns at this point
# as they are only used for selecting the rows
if _name != 'filter' and _name != 'numimages':
# start by determining the format type of the parameter
_fmt = findFormat(_format)
# Based on format type, apply proper conversion/cleaning
if (_fmt == 'a') or (_fmt == 'A'):
_val = cleanBlank(_value)
if _val is None:
_val = ''
elif (_format == 'i1') or (_format=='1L'):
_val = toBoolean(_value)
elif (_format == 'i4') or (_format == '1J'):
_val = cleanInt(_value)
elif ('E' in _format) or (_format == 'f4') :
_val = cleanNaN(_value)
else:
print('MDRIZTAB column ',_name,' has unrecognized format',_format)
raise ValueError
if _name in ['ra','dec']:
for dnames in drizstep_names:
tabdict[dnames+_name] = _val
else:
tabdict[_name] = _val
return tabdict | [
"def",
"_interpretMdriztabPars",
"(",
"rec",
")",
":",
"tabdict",
"=",
"{",
"}",
"# for each entry in the record...",
"for",
"indx",
"in",
"range",
"(",
"len",
"(",
"rec",
".",
"array",
".",
"names",
")",
")",
":",
"# ... get the name, format, and value.",
"_nam... | Collect task parameters from the MDRIZTAB record and
update the master parameters list with those values
Note that parameters read from the MDRIZTAB record must
be cleaned up in a similar way that parameters read
from the user interface are. | [
"Collect",
"task",
"parameters",
"from",
"the",
"MDRIZTAB",
"record",
"and",
"update",
"the",
"master",
"parameters",
"list",
"with",
"those",
"values"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/mdzhandler.py#L86-L158 | train | 35,633 |
spacetelescope/drizzlepac | drizzlepac/buildwcs.py | build | def build(outname, wcsname, refimage, undistort=False,
applycoeffs=False, coeffsfile=None, **wcspars):
""" Core functionality to create a WCS instance from a reference image WCS,
user supplied parameters or user adjusted reference WCS.
The distortion information can either be read in as part of the reference
image WCS or given in 'coeffsfile'.
Parameters
----------
outname : string
filename of output WCS
wcsname : string
WCSNAME ID for generated WCS
refimage : string
filename of image with source WCS used as basis for output WCS
undistort : bool
Create an undistorted WCS?
applycoeffs : bool
Apply coefficients from refimage to generate undistorted WCS?
coeffsfile : string
If specified, read distortion coeffs from separate file
"""
# Insure that the User WCS parameters have values for all the parameters,
# even if that value is 'None'
user_wcs_pars = convert_user_pars(wcspars)
userwcs = wcspars['userwcs']
"""
Use cases to document the logic required to interpret the parameters
WCS generation based on refimage/userwcs parameters
-------------------------------------------------------------
refimage == None, userwcs == False:
*NO WCS specified*
=> print a WARNING message and return without doing anything
refimage == None, userwcs == True:
=> Create WCS without a distortion model entirely from user parameters*
refimage != None, userwcs == False:
=> No user WCS parameters specified
=> Simply use refimage WCS as specified
refimage != None, userwcs == True:
=> Update refimage WCS with user specified values*
Apply distortion and generate final headerlet using processed WCS
-----------------------------------------------------------------
refimage == None, userwcs == True:
*Output WCS generated entirely from user supplied parameters*
Case 1: applycoeffs == False, undistort == True/False (ignored)
=> no distortion model to interpret
=> generate undistorted headerlet with no distortion model
Case 2: applycoeffs == True/False, undistort == True
=> ignore any user specified distortion model
=> generate undistorted headerlet with no distortion model
Case 3: applycoeffs == True, undistort == False
=> WCS from scratch combined with distortion model from another image
=> generate headerlet with distortion model
refimage != None, userwcs == True/False:
*Output WCS generated from reference image possibly modified by user parameters*
Case 4: applycoeffs == False, undistort == True
=> If refimage has distortion, remove it
=> generate undistorted headerlet with no distortion model
Case 5: applycoeffs == False, undistort == False
=> Leave refimage distortion model (if any) unmodified
=> generate a headerlet using same distortion model (if any) as refimage
Case 6: applycoeffs == True, undistort == False
=> Update refimage with distortion model with user-specified model
=> generate a headerlet with a distortion model
Case 7: applycoeffs == True, undistort == True
=> ignore user specified distortion model and undistort WCS
=> generate a headerlet without a distortion model
"""
### Build WCS from refimage and/or user pars
if util.is_blank(refimage) and not userwcs:
print('WARNING: No WCS specified... No WCS created!')
return
customwcs = None
if util.is_blank(refimage) and userwcs:
# create HSTWCS object from user parameters
complete_wcs = True
for key in user_wcs_pars:
if util.is_blank(user_wcs_pars[key]):
complete_wcs = False
break
if complete_wcs:
customwcs = wcs_functions.build_hstwcs(user_wcs_pars['crval1'],user_wcs_pars['crval2'],
user_wcs_pars['crpix1'],user_wcs_pars['crpix2'],
user_wcs_pars['naxis1'],user_wcs_pars['naxis2'],
user_wcs_pars['pscale'],user_wcs_pars['orientat'])
else:
print('WARNING: Not enough WCS information provided by user!')
raise ValueError
if not util.is_blank(refimage):
refwcs = stwcs.wcsutil.HSTWCS(refimage)
else:
refwcs = customwcs
### Apply distortion model (if any) to update WCS
if applycoeffs and not util.is_blank(coeffsfile):
if not util.is_blank(refimage):
replace_model(refwcs, coeffsfile)
else:
if not undistort:
add_model(refwcs,coeffsfile)
# Only working with custom WCS from user, no distortion
# so apply model to WCS, including modifying the CD matrix
apply_model(refwcs)
### Create undistorted WCS, if requested
if undistort:
outwcs = undistortWCS(refwcs)
else:
outwcs = refwcs
if userwcs:
# replace (some/all?) WCS values from refimage with user WCS values
# by running 'updatewcs' functions on input WCS
outwcs = mergewcs(outwcs,customwcs,user_wcs_pars)
### Create the final headerlet and write it out, if specified
if not util.is_blank(refimage):
template = refimage
elif not util.is_blank(coeffsfile):
template = coeffsfile
else:
template = None
# create default WCSNAME if None was given
wcsname = create_WCSname(wcsname)
print('Creating final headerlet with name ',wcsname,' using template ',template)
outhdr = generate_headerlet(outwcs,template,wcsname,outname=outname)
# synchronize this new WCS with the rest of the chips in the image
for ext in outhdr:
if 'extname' in ext.header and ext.header['extname'] == 'SIPWCS':
ext_wcs = wcsutil.HSTWCS(ext)
stwcs.updatewcs.makewcs.MakeWCS.updateWCS(ext_wcs,outwcs)
return outwcs | python | def build(outname, wcsname, refimage, undistort=False,
applycoeffs=False, coeffsfile=None, **wcspars):
""" Core functionality to create a WCS instance from a reference image WCS,
user supplied parameters or user adjusted reference WCS.
The distortion information can either be read in as part of the reference
image WCS or given in 'coeffsfile'.
Parameters
----------
outname : string
filename of output WCS
wcsname : string
WCSNAME ID for generated WCS
refimage : string
filename of image with source WCS used as basis for output WCS
undistort : bool
Create an undistorted WCS?
applycoeffs : bool
Apply coefficients from refimage to generate undistorted WCS?
coeffsfile : string
If specified, read distortion coeffs from separate file
"""
# Insure that the User WCS parameters have values for all the parameters,
# even if that value is 'None'
user_wcs_pars = convert_user_pars(wcspars)
userwcs = wcspars['userwcs']
"""
Use cases to document the logic required to interpret the parameters
WCS generation based on refimage/userwcs parameters
-------------------------------------------------------------
refimage == None, userwcs == False:
*NO WCS specified*
=> print a WARNING message and return without doing anything
refimage == None, userwcs == True:
=> Create WCS without a distortion model entirely from user parameters*
refimage != None, userwcs == False:
=> No user WCS parameters specified
=> Simply use refimage WCS as specified
refimage != None, userwcs == True:
=> Update refimage WCS with user specified values*
Apply distortion and generate final headerlet using processed WCS
-----------------------------------------------------------------
refimage == None, userwcs == True:
*Output WCS generated entirely from user supplied parameters*
Case 1: applycoeffs == False, undistort == True/False (ignored)
=> no distortion model to interpret
=> generate undistorted headerlet with no distortion model
Case 2: applycoeffs == True/False, undistort == True
=> ignore any user specified distortion model
=> generate undistorted headerlet with no distortion model
Case 3: applycoeffs == True, undistort == False
=> WCS from scratch combined with distortion model from another image
=> generate headerlet with distortion model
refimage != None, userwcs == True/False:
*Output WCS generated from reference image possibly modified by user parameters*
Case 4: applycoeffs == False, undistort == True
=> If refimage has distortion, remove it
=> generate undistorted headerlet with no distortion model
Case 5: applycoeffs == False, undistort == False
=> Leave refimage distortion model (if any) unmodified
=> generate a headerlet using same distortion model (if any) as refimage
Case 6: applycoeffs == True, undistort == False
=> Update refimage with distortion model with user-specified model
=> generate a headerlet with a distortion model
Case 7: applycoeffs == True, undistort == True
=> ignore user specified distortion model and undistort WCS
=> generate a headerlet without a distortion model
"""
### Build WCS from refimage and/or user pars
if util.is_blank(refimage) and not userwcs:
print('WARNING: No WCS specified... No WCS created!')
return
customwcs = None
if util.is_blank(refimage) and userwcs:
# create HSTWCS object from user parameters
complete_wcs = True
for key in user_wcs_pars:
if util.is_blank(user_wcs_pars[key]):
complete_wcs = False
break
if complete_wcs:
customwcs = wcs_functions.build_hstwcs(user_wcs_pars['crval1'],user_wcs_pars['crval2'],
user_wcs_pars['crpix1'],user_wcs_pars['crpix2'],
user_wcs_pars['naxis1'],user_wcs_pars['naxis2'],
user_wcs_pars['pscale'],user_wcs_pars['orientat'])
else:
print('WARNING: Not enough WCS information provided by user!')
raise ValueError
if not util.is_blank(refimage):
refwcs = stwcs.wcsutil.HSTWCS(refimage)
else:
refwcs = customwcs
### Apply distortion model (if any) to update WCS
if applycoeffs and not util.is_blank(coeffsfile):
if not util.is_blank(refimage):
replace_model(refwcs, coeffsfile)
else:
if not undistort:
add_model(refwcs,coeffsfile)
# Only working with custom WCS from user, no distortion
# so apply model to WCS, including modifying the CD matrix
apply_model(refwcs)
### Create undistorted WCS, if requested
if undistort:
outwcs = undistortWCS(refwcs)
else:
outwcs = refwcs
if userwcs:
# replace (some/all?) WCS values from refimage with user WCS values
# by running 'updatewcs' functions on input WCS
outwcs = mergewcs(outwcs,customwcs,user_wcs_pars)
### Create the final headerlet and write it out, if specified
if not util.is_blank(refimage):
template = refimage
elif not util.is_blank(coeffsfile):
template = coeffsfile
else:
template = None
# create default WCSNAME if None was given
wcsname = create_WCSname(wcsname)
print('Creating final headerlet with name ',wcsname,' using template ',template)
outhdr = generate_headerlet(outwcs,template,wcsname,outname=outname)
# synchronize this new WCS with the rest of the chips in the image
for ext in outhdr:
if 'extname' in ext.header and ext.header['extname'] == 'SIPWCS':
ext_wcs = wcsutil.HSTWCS(ext)
stwcs.updatewcs.makewcs.MakeWCS.updateWCS(ext_wcs,outwcs)
return outwcs | [
"def",
"build",
"(",
"outname",
",",
"wcsname",
",",
"refimage",
",",
"undistort",
"=",
"False",
",",
"applycoeffs",
"=",
"False",
",",
"coeffsfile",
"=",
"None",
",",
"*",
"*",
"wcspars",
")",
":",
"# Insure that the User WCS parameters have values for all the pa... | Core functionality to create a WCS instance from a reference image WCS,
user supplied parameters or user adjusted reference WCS.
The distortion information can either be read in as part of the reference
image WCS or given in 'coeffsfile'.
Parameters
----------
outname : string
filename of output WCS
wcsname : string
WCSNAME ID for generated WCS
refimage : string
filename of image with source WCS used as basis for output WCS
undistort : bool
Create an undistorted WCS?
applycoeffs : bool
Apply coefficients from refimage to generate undistorted WCS?
coeffsfile : string
If specified, read distortion coeffs from separate file | [
"Core",
"functionality",
"to",
"create",
"a",
"WCS",
"instance",
"from",
"a",
"reference",
"image",
"WCS",
"user",
"supplied",
"parameters",
"or",
"user",
"adjusted",
"reference",
"WCS",
".",
"The",
"distortion",
"information",
"can",
"either",
"be",
"read",
"... | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildwcs.py#L75-L219 | train | 35,634 |
spacetelescope/drizzlepac | drizzlepac/buildwcs.py | create_WCSname | def create_WCSname(wcsname):
""" Verify that a valid WCSNAME has been provided, and if not, create a
default WCSNAME based on current date.
"""
if util.is_blank(wcsname):
ptime = fileutil.getDate()
wcsname = "User_"+ptime
return wcsname | python | def create_WCSname(wcsname):
""" Verify that a valid WCSNAME has been provided, and if not, create a
default WCSNAME based on current date.
"""
if util.is_blank(wcsname):
ptime = fileutil.getDate()
wcsname = "User_"+ptime
return wcsname | [
"def",
"create_WCSname",
"(",
"wcsname",
")",
":",
"if",
"util",
".",
"is_blank",
"(",
"wcsname",
")",
":",
"ptime",
"=",
"fileutil",
".",
"getDate",
"(",
")",
"wcsname",
"=",
"\"User_\"",
"+",
"ptime",
"return",
"wcsname"
] | Verify that a valid WCSNAME has been provided, and if not, create a
default WCSNAME based on current date. | [
"Verify",
"that",
"a",
"valid",
"WCSNAME",
"has",
"been",
"provided",
"and",
"if",
"not",
"create",
"a",
"default",
"WCSNAME",
"based",
"on",
"current",
"date",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildwcs.py#L221-L229 | train | 35,635 |
spacetelescope/drizzlepac | drizzlepac/buildwcs.py | convert_user_pars | def convert_user_pars(wcspars):
""" Convert the parameters provided by the configObj into the corresponding
parameters from an HSTWCS object
"""
default_pars = default_user_wcs.copy()
for kw in user_hstwcs_pars:
default_pars[user_hstwcs_pars[kw]] = wcspars[kw]
return default_pars | python | def convert_user_pars(wcspars):
""" Convert the parameters provided by the configObj into the corresponding
parameters from an HSTWCS object
"""
default_pars = default_user_wcs.copy()
for kw in user_hstwcs_pars:
default_pars[user_hstwcs_pars[kw]] = wcspars[kw]
return default_pars | [
"def",
"convert_user_pars",
"(",
"wcspars",
")",
":",
"default_pars",
"=",
"default_user_wcs",
".",
"copy",
"(",
")",
"for",
"kw",
"in",
"user_hstwcs_pars",
":",
"default_pars",
"[",
"user_hstwcs_pars",
"[",
"kw",
"]",
"]",
"=",
"wcspars",
"[",
"kw",
"]",
... | Convert the parameters provided by the configObj into the corresponding
parameters from an HSTWCS object | [
"Convert",
"the",
"parameters",
"provided",
"by",
"the",
"configObj",
"into",
"the",
"corresponding",
"parameters",
"from",
"an",
"HSTWCS",
"object"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildwcs.py#L231-L238 | train | 35,636 |
spacetelescope/drizzlepac | drizzlepac/buildwcs.py | mergewcs | def mergewcs(outwcs, customwcs, wcspars):
""" Merge the WCS keywords from user specified values into a full HSTWCS object
This function will essentially follow the same algorithm as used by
updatehdr only it will use direct calls to updatewcs.Makewcs methods
instead of using 'updatewcs' as a whole
"""
# start by working on a copy of the refwcs
if outwcs.sip is not None:
wcslin = stwcs.distortion.utils.undistortWCS(outwcs)
outwcs.wcs.cd = wcslin.wcs.cd
outwcs.wcs.set()
outwcs.setOrient()
outwcs.setPscale()
else:
wcslin = outwcs
if customwcs is None:
# update valid pars from wcspars
if wcspars['crval1'] is not None:
outwcs.wcs.crval = np.array([wcspars['crval1'],wcspars['crval2']])
if wcspars['crpix1'] is not None:
outwcs.wcs.crpix = np.array([wcspars['crpix1'],wcspars['crpix2']])
if wcspars['naxis1'] is not None:
outwcs.pixel_shape = (wcspars['naxis1'], wcspars['naxis2'])
outwcs.wcs.crpix = np.array(outwcs.pixel_shape) / 2.0
pscale = wcspars['pscale']
orient = wcspars['orientat']
if pscale is not None or orient is not None:
if pscale is None: pscale = wcslin.pscale
if orient is None: orient = wcslin.orientat
pix_ratio = pscale/wcslin.pscale
delta_rot = wcslin.orientat - orient
delta_rot_mat = fileutil.buildRotMatrix(delta_rot)
outwcs.wcs.cd = np.dot(outwcs.wcs.cd,delta_rot_mat)*pix_ratio
# apply model to new linear CD matrix
apply_model(outwcs)
else:
# A new fully described WCS was provided in customwcs
outwcs.wcs.cd = customwcs.wcs.cd
outwcs.wcs.crval = customwcs.wcs.crval
outwcs.wcs.crpix = customwcs.wcs.crpix
outwcs.pixel_shape = customwcs.pixel_shape
return outwcs | python | def mergewcs(outwcs, customwcs, wcspars):
""" Merge the WCS keywords from user specified values into a full HSTWCS object
This function will essentially follow the same algorithm as used by
updatehdr only it will use direct calls to updatewcs.Makewcs methods
instead of using 'updatewcs' as a whole
"""
# start by working on a copy of the refwcs
if outwcs.sip is not None:
wcslin = stwcs.distortion.utils.undistortWCS(outwcs)
outwcs.wcs.cd = wcslin.wcs.cd
outwcs.wcs.set()
outwcs.setOrient()
outwcs.setPscale()
else:
wcslin = outwcs
if customwcs is None:
# update valid pars from wcspars
if wcspars['crval1'] is not None:
outwcs.wcs.crval = np.array([wcspars['crval1'],wcspars['crval2']])
if wcspars['crpix1'] is not None:
outwcs.wcs.crpix = np.array([wcspars['crpix1'],wcspars['crpix2']])
if wcspars['naxis1'] is not None:
outwcs.pixel_shape = (wcspars['naxis1'], wcspars['naxis2'])
outwcs.wcs.crpix = np.array(outwcs.pixel_shape) / 2.0
pscale = wcspars['pscale']
orient = wcspars['orientat']
if pscale is not None or orient is not None:
if pscale is None: pscale = wcslin.pscale
if orient is None: orient = wcslin.orientat
pix_ratio = pscale/wcslin.pscale
delta_rot = wcslin.orientat - orient
delta_rot_mat = fileutil.buildRotMatrix(delta_rot)
outwcs.wcs.cd = np.dot(outwcs.wcs.cd,delta_rot_mat)*pix_ratio
# apply model to new linear CD matrix
apply_model(outwcs)
else:
# A new fully described WCS was provided in customwcs
outwcs.wcs.cd = customwcs.wcs.cd
outwcs.wcs.crval = customwcs.wcs.crval
outwcs.wcs.crpix = customwcs.wcs.crpix
outwcs.pixel_shape = customwcs.pixel_shape
return outwcs | [
"def",
"mergewcs",
"(",
"outwcs",
",",
"customwcs",
",",
"wcspars",
")",
":",
"# start by working on a copy of the refwcs",
"if",
"outwcs",
".",
"sip",
"is",
"not",
"None",
":",
"wcslin",
"=",
"stwcs",
".",
"distortion",
".",
"utils",
".",
"undistortWCS",
"(",... | Merge the WCS keywords from user specified values into a full HSTWCS object
This function will essentially follow the same algorithm as used by
updatehdr only it will use direct calls to updatewcs.Makewcs methods
instead of using 'updatewcs' as a whole | [
"Merge",
"the",
"WCS",
"keywords",
"from",
"user",
"specified",
"values",
"into",
"a",
"full",
"HSTWCS",
"object",
"This",
"function",
"will",
"essentially",
"follow",
"the",
"same",
"algorithm",
"as",
"used",
"by",
"updatehdr",
"only",
"it",
"will",
"use",
... | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildwcs.py#L240-L282 | train | 35,637 |
spacetelescope/drizzlepac | drizzlepac/buildwcs.py | apply_model | def apply_model(refwcs):
""" Apply distortion model to WCS, including modifying
CD with linear distortion terms
"""
# apply distortion model to CD matrix
if 'ocx10' in refwcs.__dict__ and refwcs.ocx10 is not None:
linmat = np.array([[refwcs.ocx11,refwcs.ocx10],[refwcs.ocy11,refwcs.ocy10]])/refwcs.idcscale
refwcs.wcs.cd = np.dot(refwcs.wcs.cd,linmat)
refwcs.wcs.set()
refwcs.setOrient()
refwcs.setPscale() | python | def apply_model(refwcs):
""" Apply distortion model to WCS, including modifying
CD with linear distortion terms
"""
# apply distortion model to CD matrix
if 'ocx10' in refwcs.__dict__ and refwcs.ocx10 is not None:
linmat = np.array([[refwcs.ocx11,refwcs.ocx10],[refwcs.ocy11,refwcs.ocy10]])/refwcs.idcscale
refwcs.wcs.cd = np.dot(refwcs.wcs.cd,linmat)
refwcs.wcs.set()
refwcs.setOrient()
refwcs.setPscale() | [
"def",
"apply_model",
"(",
"refwcs",
")",
":",
"# apply distortion model to CD matrix",
"if",
"'ocx10'",
"in",
"refwcs",
".",
"__dict__",
"and",
"refwcs",
".",
"ocx10",
"is",
"not",
"None",
":",
"linmat",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"refwcs",
"... | Apply distortion model to WCS, including modifying
CD with linear distortion terms | [
"Apply",
"distortion",
"model",
"to",
"WCS",
"including",
"modifying",
"CD",
"with",
"linear",
"distortion",
"terms"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildwcs.py#L292-L304 | train | 35,638 |
spacetelescope/drizzlepac | drizzlepac/buildwcs.py | replace_model | def replace_model(refwcs, newcoeffs):
""" Replace the distortion model in a current WCS with a new model
Start by creating linear WCS, then run
"""
print('WARNING:')
print(' Replacing existing distortion model with one')
print(' not necessarily matched to the observation!')
# create linear version of WCS to be updated by new model
wcslin = stwcs.distortion.utils.undistortWCS(refwcs)
outwcs = refwcs.deepcopy()
outwcs.wcs.cd = wcslin.wcs.cd
outwcs.wcs.set()
outwcs.setOrient()
outwcs.setPscale()
# add new model to updated WCS object
add_model(outwcs,newcoeffs)
# Update CD matrix with new model
apply_model(outwcs)
# replace original input WCS with newly updated WCS
refwcs = outwcs.deepcopy() | python | def replace_model(refwcs, newcoeffs):
""" Replace the distortion model in a current WCS with a new model
Start by creating linear WCS, then run
"""
print('WARNING:')
print(' Replacing existing distortion model with one')
print(' not necessarily matched to the observation!')
# create linear version of WCS to be updated by new model
wcslin = stwcs.distortion.utils.undistortWCS(refwcs)
outwcs = refwcs.deepcopy()
outwcs.wcs.cd = wcslin.wcs.cd
outwcs.wcs.set()
outwcs.setOrient()
outwcs.setPscale()
# add new model to updated WCS object
add_model(outwcs,newcoeffs)
# Update CD matrix with new model
apply_model(outwcs)
# replace original input WCS with newly updated WCS
refwcs = outwcs.deepcopy() | [
"def",
"replace_model",
"(",
"refwcs",
",",
"newcoeffs",
")",
":",
"print",
"(",
"'WARNING:'",
")",
"print",
"(",
"' Replacing existing distortion model with one'",
")",
"print",
"(",
"' not necessarily matched to the observation!'",
")",
"# create linear version of WCS... | Replace the distortion model in a current WCS with a new model
Start by creating linear WCS, then run | [
"Replace",
"the",
"distortion",
"model",
"in",
"a",
"current",
"WCS",
"with",
"a",
"new",
"model",
"Start",
"by",
"creating",
"linear",
"WCS",
"then",
"run"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildwcs.py#L306-L326 | train | 35,639 |
spacetelescope/drizzlepac | drizzlepac/buildwcs.py | undistortWCS | def undistortWCS(refwcs):
""" Generate an undistorted HSTWCS from an HSTWCS object with a distortion model
"""
wcslin = stwcs.distortion.utils.output_wcs([refwcs])
outwcs = stwcs.wcsutil.HSTWCS()
outwcs.wcs = wcslin.wcs
outwcs.wcs.set()
outwcs.setPscale()
outwcs.setOrient()
outwcs.sip = None
# Update instrument specific keywords
outwcs.inst_kw = refwcs.inst_kw
for kw in refwcs.inst_kw:
outwcs.__dict__[kw] = refwcs.__dict__[kw]
outwcs.pixel_shape = wcslin.pixel_shape
return outwcs | python | def undistortWCS(refwcs):
""" Generate an undistorted HSTWCS from an HSTWCS object with a distortion model
"""
wcslin = stwcs.distortion.utils.output_wcs([refwcs])
outwcs = stwcs.wcsutil.HSTWCS()
outwcs.wcs = wcslin.wcs
outwcs.wcs.set()
outwcs.setPscale()
outwcs.setOrient()
outwcs.sip = None
# Update instrument specific keywords
outwcs.inst_kw = refwcs.inst_kw
for kw in refwcs.inst_kw:
outwcs.__dict__[kw] = refwcs.__dict__[kw]
outwcs.pixel_shape = wcslin.pixel_shape
return outwcs | [
"def",
"undistortWCS",
"(",
"refwcs",
")",
":",
"wcslin",
"=",
"stwcs",
".",
"distortion",
".",
"utils",
".",
"output_wcs",
"(",
"[",
"refwcs",
"]",
")",
"outwcs",
"=",
"stwcs",
".",
"wcsutil",
".",
"HSTWCS",
"(",
")",
"outwcs",
".",
"wcs",
"=",
"wcs... | Generate an undistorted HSTWCS from an HSTWCS object with a distortion model | [
"Generate",
"an",
"undistorted",
"HSTWCS",
"from",
"an",
"HSTWCS",
"object",
"with",
"a",
"distortion",
"model"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildwcs.py#L328-L346 | train | 35,640 |
spacetelescope/drizzlepac | drizzlepac/buildwcs.py | generate_headerlet | def generate_headerlet(outwcs,template,wcsname,outname=None):
""" Create a headerlet based on the updated HSTWCS object
This function uses 'template' as the basis for the headerlet.
This file can either be the original wcspars['refimage'] or
wcspars['coeffsfile'], in this order of preference.
If 'template' is None, then a simple Headerlet will be
generated with a single SIPWCS extension and no distortion
"""
# Create header object from HSTWCS object
siphdr = True
if outwcs.sip is None:
siphdr = False
outwcs_hdr = outwcs.wcs2header(sip2hdr=siphdr)
outwcs_hdr['NPIX1'] = outwcs.pixel_shape[0]
outwcs_hdr['NPIX2'] = outwcs.pixel_shape[1]
# create headerlet object in memory; either from a file or from scratch
if template is not None and siphdr:
print('Creating headerlet from template...')
fname,extn = fileutil.parseFilename(template)
extnum = fileutil.parseExtn(extn)
extname = ('sipwcs',extnum[1])
hdrlet = headerlet.createHeaderlet(fname,wcsname)
# update hdrlet with header values from outwcs
for kw in outwcs_hdr.items():
hdrlet[extname].header[kw[0]] = kw[1]
hdrlet[extname].header['WCSNAME'] = wcsname
else:
print('Creating headerlet from scratch...')
hdrlet = fits.HDUList()
hdrlet.append(fits.PrimaryHDU())
siphdr = fits.ImageHDU(header=outwcs_hdr)
siphdr.header['EXTNAME'] = 'SIPWCS'
siphdr.header['WCSNAME'] = wcsname
hdrlet.append(siphdr)
# Write out header to a file as the final product
if outname is not None:
if outname.find('_hdr.fits') < 0:
outname += '_hdr.fits'
if os.path.exists(outname):
print('Overwrite existing file "%s"'%outname)
os.remove(outname)
hdrlet.writeto(outname)
print('Wrote out headerlet :',outname) | python | def generate_headerlet(outwcs,template,wcsname,outname=None):
""" Create a headerlet based on the updated HSTWCS object
This function uses 'template' as the basis for the headerlet.
This file can either be the original wcspars['refimage'] or
wcspars['coeffsfile'], in this order of preference.
If 'template' is None, then a simple Headerlet will be
generated with a single SIPWCS extension and no distortion
"""
# Create header object from HSTWCS object
siphdr = True
if outwcs.sip is None:
siphdr = False
outwcs_hdr = outwcs.wcs2header(sip2hdr=siphdr)
outwcs_hdr['NPIX1'] = outwcs.pixel_shape[0]
outwcs_hdr['NPIX2'] = outwcs.pixel_shape[1]
# create headerlet object in memory; either from a file or from scratch
if template is not None and siphdr:
print('Creating headerlet from template...')
fname,extn = fileutil.parseFilename(template)
extnum = fileutil.parseExtn(extn)
extname = ('sipwcs',extnum[1])
hdrlet = headerlet.createHeaderlet(fname,wcsname)
# update hdrlet with header values from outwcs
for kw in outwcs_hdr.items():
hdrlet[extname].header[kw[0]] = kw[1]
hdrlet[extname].header['WCSNAME'] = wcsname
else:
print('Creating headerlet from scratch...')
hdrlet = fits.HDUList()
hdrlet.append(fits.PrimaryHDU())
siphdr = fits.ImageHDU(header=outwcs_hdr)
siphdr.header['EXTNAME'] = 'SIPWCS'
siphdr.header['WCSNAME'] = wcsname
hdrlet.append(siphdr)
# Write out header to a file as the final product
if outname is not None:
if outname.find('_hdr.fits') < 0:
outname += '_hdr.fits'
if os.path.exists(outname):
print('Overwrite existing file "%s"'%outname)
os.remove(outname)
hdrlet.writeto(outname)
print('Wrote out headerlet :',outname) | [
"def",
"generate_headerlet",
"(",
"outwcs",
",",
"template",
",",
"wcsname",
",",
"outname",
"=",
"None",
")",
":",
"# Create header object from HSTWCS object",
"siphdr",
"=",
"True",
"if",
"outwcs",
".",
"sip",
"is",
"None",
":",
"siphdr",
"=",
"False",
"outw... | Create a headerlet based on the updated HSTWCS object
This function uses 'template' as the basis for the headerlet.
This file can either be the original wcspars['refimage'] or
wcspars['coeffsfile'], in this order of preference.
If 'template' is None, then a simple Headerlet will be
generated with a single SIPWCS extension and no distortion | [
"Create",
"a",
"headerlet",
"based",
"on",
"the",
"updated",
"HSTWCS",
"object"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildwcs.py#L348-L394 | train | 35,641 |
spacetelescope/drizzlepac | drizzlepac/quickDeriv.py | qderiv | 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)
# Get the length of an array side
(naxis1,naxis2) = array.shape
#print "The input image size is (",naxis1,",",naxis2,")."
#Main derivate loop:
#Shift images +/- 1 in Y.
for y in range(-1,2,2):
if y == -1:
#shift input image 1 pixel right
tmpArray[0:(naxis1-1),1:(naxis2-1)] = array[0:(naxis1-1),0:(naxis2-2)]
#print "Y shift = 1"
else:
#shift input image 1 pixel left
tmpArray[0:(naxis1-1),0:(naxis2-2)] = array[0:(naxis1-1),1:(naxis2-1)]
#print "Y shift = -1"
#print "call _absoluteSubtract()"
(tmpArray,outArray) = _absoluteSubtract(array,tmpArray,outArray)
#Shift images +/- 1 in X.
for x in range(-1,2,2):
if x == -1:
#shift input image 1 pixel right
tmpArray[1:(naxis1-1),0:(naxis2-1)] = array[0:(naxis1-2),0:(naxis2-1)]
#print "X shift = 1"
else:
#shift input image 1 pixel left
tmpArray[0:(naxis1-2),0:(naxis2-1)] = array[1:(naxis1-1),0:(naxis2-1)]
#print "X shift = -1"
#print "call _absoluteSubtract()"
(tmpArray,outArray) = _absoluteSubtract(array,tmpArray,outArray)
return outArray.astype(np.float32) | python | 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)
# Get the length of an array side
(naxis1,naxis2) = array.shape
#print "The input image size is (",naxis1,",",naxis2,")."
#Main derivate loop:
#Shift images +/- 1 in Y.
for y in range(-1,2,2):
if y == -1:
#shift input image 1 pixel right
tmpArray[0:(naxis1-1),1:(naxis2-1)] = array[0:(naxis1-1),0:(naxis2-2)]
#print "Y shift = 1"
else:
#shift input image 1 pixel left
tmpArray[0:(naxis1-1),0:(naxis2-2)] = array[0:(naxis1-1),1:(naxis2-1)]
#print "Y shift = -1"
#print "call _absoluteSubtract()"
(tmpArray,outArray) = _absoluteSubtract(array,tmpArray,outArray)
#Shift images +/- 1 in X.
for x in range(-1,2,2):
if x == -1:
#shift input image 1 pixel right
tmpArray[1:(naxis1-1),0:(naxis2-1)] = array[0:(naxis1-2),0:(naxis2-1)]
#print "X shift = 1"
else:
#shift input image 1 pixel left
tmpArray[0:(naxis1-2),0:(naxis2-1)] = array[1:(naxis1-1),0:(naxis2-1)]
#print "X shift = -1"
#print "call _absoluteSubtract()"
(tmpArray,outArray) = _absoluteSubtract(array,tmpArray,outArray)
return outArray.astype(np.float32) | [
"def",
"qderiv",
"(",
"array",
")",
":",
"# TAKE THE ABSOLUTE DERIVATIVE OF A NUMARRY OBJECT",
"#Create 2 empty arrays in memory of the same dimensions as 'array'",
"tmpArray",
"=",
"np",
".",
"zeros",
"(",
"array",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"float64",
... | Take the absolute derivate of an image in memory. | [
"Take",
"the",
"absolute",
"derivate",
"of",
"an",
"image",
"in",
"memory",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/quickDeriv.py#L18-L58 | train | 35,642 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | get_hstwcs | 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 | python | 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 | [
"def",
"get_hstwcs",
"(",
"filename",
",",
"hdulist",
",",
"extnum",
")",
":",
"hdrwcs",
"=",
"wcsutil",
".",
"HSTWCS",
"(",
"hdulist",
",",
"ext",
"=",
"extnum",
")",
"hdrwcs",
".",
"filename",
"=",
"filename",
"hdrwcs",
".",
"expname",
"=",
"hdulist",
... | Return the HSTWCS object for a given chip. | [
"Return",
"the",
"HSTWCS",
"object",
"for",
"a",
"given",
"chip",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L125-L132 | train | 35,643 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | calcNewEdges | 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
array which contains the new positions for
all pixels around the border of the edges in alpha,dec
"""
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
# We also need to account for any subarray offsets
xmin = 1.
xmax = naxis1
ymin = 1.
ymax = naxis2
# Build range of pixel values for each side
# Add 1 to make them consistent with pixel numbering in IRAF
# Also include the LTV offsets to represent position in full chip
# since the model works relative to full chip positions.
xside = np.arange(naxis1) + xmin
yside = np.arange(naxis2) + ymin
#Now apply them to the array to generate the appropriate tuples
#bottom
_range0 = 0
_range1 = naxis1
border[_range0:_range1,0] = xside
border[_range0:_range1,1] = ymin
#top
_range0 = _range1
_range1 = _range0 + naxis1
border[_range0:_range1,0] = xside
border[_range0:_range1,1] = ymax
#left
_range0 = _range1
_range1 = _range0 + naxis2
border[_range0:_range1,0] = xmin
border[_range0:_range1,1] = yside
#right
_range0 = _range1
_range1 = _range0 + naxis2
border[_range0:_range1,0] = xmax
border[_range0:_range1,1] = yside
edges = wcs.all_pix2world(border[:,0],border[:,1],1)
return edges | python | 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
array which contains the new positions for
all pixels around the border of the edges in alpha,dec
"""
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
# We also need to account for any subarray offsets
xmin = 1.
xmax = naxis1
ymin = 1.
ymax = naxis2
# Build range of pixel values for each side
# Add 1 to make them consistent with pixel numbering in IRAF
# Also include the LTV offsets to represent position in full chip
# since the model works relative to full chip positions.
xside = np.arange(naxis1) + xmin
yside = np.arange(naxis2) + ymin
#Now apply them to the array to generate the appropriate tuples
#bottom
_range0 = 0
_range1 = naxis1
border[_range0:_range1,0] = xside
border[_range0:_range1,1] = ymin
#top
_range0 = _range1
_range1 = _range0 + naxis1
border[_range0:_range1,0] = xside
border[_range0:_range1,1] = ymax
#left
_range0 = _range1
_range1 = _range0 + naxis2
border[_range0:_range1,0] = xmin
border[_range0:_range1,1] = yside
#right
_range0 = _range1
_range1 = _range0 + naxis2
border[_range0:_range1,0] = xmax
border[_range0:_range1,1] = yside
edges = wcs.all_pix2world(border[:,0],border[:,1],1)
return edges | [
"def",
"calcNewEdges",
"(",
"wcs",
",",
"shape",
")",
":",
"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",
"=",
"nax... | 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
array which contains the new positions for
all pixels around the border of the edges in alpha,dec | [
"This",
"method",
"will",
"compute",
"sky",
"coordinates",
"for",
"all",
"the",
"pixels",
"around",
"the",
"edge",
"of",
"an",
"image",
"AFTER",
"applying",
"the",
"geometry",
"model",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L368-L433 | train | 35,644 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | removeAllAltWCS | 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.remove(' ')
for extn in extlist:
for wkey in wkeys:
if wkey == 'O':
continue
altwcs.deleteWCS(hdulist,extn,wkey)
# Forcibly remove OPUS WCS Keywords, since deleteWCS will not do it
hwcs = readAltWCS(hdulist,extn,wcskey='O')
if hwcs is None:
continue
for k in hwcs.keys():
if k not in ['DATE-OBS','MJD-OBS'] and k in hdr:
try:
del hdr[k]
except KeyError:
pass
except:
raise
finally:
log.setLevel(original_logging_level) | python | 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.remove(' ')
for extn in extlist:
for wkey in wkeys:
if wkey == 'O':
continue
altwcs.deleteWCS(hdulist,extn,wkey)
# Forcibly remove OPUS WCS Keywords, since deleteWCS will not do it
hwcs = readAltWCS(hdulist,extn,wcskey='O')
if hwcs is None:
continue
for k in hwcs.keys():
if k not in ['DATE-OBS','MJD-OBS'] and k in hdr:
try:
del hdr[k]
except KeyError:
pass
except:
raise
finally:
log.setLevel(original_logging_level) | [
"def",
"removeAllAltWCS",
"(",
"hdulist",
",",
"extlist",
")",
":",
"original_logging_level",
"=",
"log",
".",
"level",
"log",
".",
"setLevel",
"(",
"logutil",
".",
"logging",
".",
"WARNING",
")",
"try",
":",
"hdr",
"=",
"hdulist",
"[",
"extlist",
"[",
"... | Removes all alternate WCS solutions from the header | [
"Removes",
"all",
"alternate",
"WCS",
"solutions",
"from",
"the",
"header"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L471-L505 | train | 35,645 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | restoreDefaultWCS | 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) | python | 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) | [
"def",
"restoreDefaultWCS",
"(",
"imageObjectList",
",",
"output_wcs",
")",
":",
"if",
"not",
"isinstance",
"(",
"imageObjectList",
",",
"list",
")",
":",
"imageObjectList",
"=",
"[",
"imageObjectList",
"]",
"output_wcs",
".",
"restoreWCS",
"(",
")",
"updateImag... | Restore WCS information to default values, and update imageObject
accordingly. | [
"Restore",
"WCS",
"information",
"to",
"default",
"values",
"and",
"update",
"imageObject",
"accordingly",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L515-L524 | train | 35,646 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | _py2round | 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 rx
else:
if x >= 0.0:
return np.floor(x + 0.5)
else:
return np.ceil(x - 0.5) | python | 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 rx
else:
if x >= 0.0:
return np.floor(x + 0.5)
else:
return np.ceil(x - 0.5) | [
"def",
"_py2round",
"(",
"x",
")",
":",
"if",
"hasattr",
"(",
"x",
",",
"'__iter__'",
")",
":",
"rx",
"=",
"np",
".",
"empty_like",
"(",
"x",
")",
"m",
"=",
"x",
">=",
"0.0",
"rx",
"[",
"m",
"]",
"=",
"np",
".",
"floor",
"(",
"x",
"[",
"m",... | This function returns a rounded up value of the argument, similar
to Python 2. | [
"This",
"function",
"returns",
"a",
"rounded",
"up",
"value",
"of",
"the",
"argument",
"similar",
"to",
"Python",
"2",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L537-L554 | train | 35,647 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | convertWCS | 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]
drizwcs[7] = inwcs.cd[1][1]
return drizwcs | python | 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]
drizwcs[7] = inwcs.cd[1][1]
return drizwcs | [
"def",
"convertWCS",
"(",
"inwcs",
",",
"drizwcs",
")",
":",
"drizwcs",
"[",
"0",
"]",
"=",
"inwcs",
".",
"crpix",
"[",
"0",
"]",
"drizwcs",
"[",
"1",
"]",
"=",
"inwcs",
".",
"crval",
"[",
"0",
"]",
"drizwcs",
"[",
"2",
"]",
"=",
"inwcs",
".",
... | Copy WCSObject WCS into Drizzle compatible array. | [
"Copy",
"WCSObject",
"WCS",
"into",
"Drizzle",
"compatible",
"array",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L711-L722 | train | 35,648 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | updateWCS | 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 = cd
inwcs.crval = crval
inwc.crpix = crpix
inwcs.pscale = N.sqrt(N.power(inwcs.cd[0][0],2)+N.power(inwcs.cd[1][0],2)) * 3600.
inwcs.orient = N.arctan2(inwcs.cd[0][1],inwcs.cd[1][1]) * 180./N.pi | python | 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 = cd
inwcs.crval = crval
inwc.crpix = crpix
inwcs.pscale = N.sqrt(N.power(inwcs.cd[0][0],2)+N.power(inwcs.cd[1][0],2)) * 3600.
inwcs.orient = N.arctan2(inwcs.cd[0][1],inwcs.cd[1][1]) * 180./N.pi | [
"def",
"updateWCS",
"(",
"drizwcs",
",",
"inwcs",
")",
":",
"crpix",
"=",
"np",
".",
"array",
"(",
"[",
"drizwcs",
"[",
"0",
"]",
",",
"drizwcs",
"[",
"2",
"]",
"]",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"crval",
"=",
"np",
".",
"array"... | Copy output WCS array from Drizzle into WCSObject. | [
"Copy",
"output",
"WCS",
"array",
"from",
"Drizzle",
"into",
"WCSObject",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L724-L733 | train | 35,649 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | readAltWCS | 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 replaced by the new key
ext : int
fits extension number
Returns
-------
hdr: fits.Header
header object with ONLY the keywords for specified alternate WCS
"""
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:
print('readAltWCS: Could not read WCS with key %s' % wcskey)
print(' Skipping %s[%s]' % (fobj.filename(), str(ext)))
return None
finally:
log.setLevel(original_logging_level) # restore original logging level
hwcs = nwcs.to_header()
if nwcs.wcs.has_cd():
hwcs = altwcs.pc2cd(hwcs, key=wcskey)
return hwcs | python | 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 replaced by the new key
ext : int
fits extension number
Returns
-------
hdr: fits.Header
header object with ONLY the keywords for specified alternate WCS
"""
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:
print('readAltWCS: Could not read WCS with key %s' % wcskey)
print(' Skipping %s[%s]' % (fobj.filename(), str(ext)))
return None
finally:
log.setLevel(original_logging_level) # restore original logging level
hwcs = nwcs.to_header()
if nwcs.wcs.has_cd():
hwcs = altwcs.pc2cd(hwcs, key=wcskey)
return hwcs | [
"def",
"readAltWCS",
"(",
"fobj",
",",
"ext",
",",
"wcskey",
"=",
"' '",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"fobj",
",",
"str",
")",
":",
"fobj",
"=",
"fits",
".",
"open",
"(",
"fobj",
",",
"memmap",
"=",
"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 replaced by the new key
ext : int
fits extension number
Returns
-------
hdr: fits.Header
header object with ONLY the keywords for specified alternate WCS | [
"Reads",
"in",
"alternate",
"primary",
"WCS",
"from",
"specified",
"extension",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L995-L1036 | train | 35,650 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | WCSMap.forward | 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.input.all_pix2world(pixx,pixy,self.origin)
result= self.output.wcs_world2pix(skyx,skyy,self.origin)
return result | python | 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.input.all_pix2world(pixx,pixy,self.origin)
result= self.output.wcs_world2pix(skyx,skyy,self.origin)
return result | [
"def",
"forward",
"(",
"self",
",",
"pixx",
",",
"pixy",
")",
":",
"# This matches WTRAXY results to better than 1e-4 pixels.",
"skyx",
",",
"skyy",
"=",
"self",
".",
"input",
".",
"all_pix2world",
"(",
"pixx",
",",
"pixy",
",",
"self",
".",
"origin",
")",
"... | 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. | [
"Transform",
"the",
"input",
"pixx",
"pixy",
"positions",
"in",
"the",
"input",
"frame",
"to",
"pixel",
"positions",
"in",
"the",
"output",
"frame",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L53-L62 | train | 35,651 |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | WCSMap.backward | 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)
return result | python | 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)
return result | [
"def",
"backward",
"(",
"self",
",",
"pixx",
",",
"pixy",
")",
":",
"skyx",
",",
"skyy",
"=",
"self",
".",
"output",
".",
"wcs_pix2world",
"(",
"pixx",
",",
"pixy",
",",
"self",
".",
"origin",
")",
"result",
"=",
"self",
".",
"input",
".",
"all_wor... | Transform pixx,pixy positions from the output frame back onto their
original positions in the input frame. | [
"Transform",
"pixx",
"pixy",
"positions",
"from",
"the",
"output",
"frame",
"back",
"onto",
"their",
"original",
"positions",
"in",
"the",
"input",
"frame",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L64-L70 | train | 35,652 |
spacetelescope/drizzlepac | drizzlepac/staticMask.py | createMask | 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.
"""
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 where config is not defined yet
configObj = util.getDefaultConfigObj(__taskname__,configObj,inputDict,loadOnly=(not editpars))
if configObj is None:
return
if not editpars:
run(configObj) | python | 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.
"""
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 where config is not defined yet
configObj = util.getDefaultConfigObj(__taskname__,configObj,inputDict,loadOnly=(not editpars))
if configObj is None:
return
if not editpars:
run(configObj) | [
"def",
"createMask",
"(",
"input",
"=",
"None",
",",
"static_sig",
"=",
"4.0",
",",
"group",
"=",
"None",
",",
"editpars",
"=",
"False",
",",
"configObj",
"=",
"None",
",",
"*",
"*",
"inputDict",
")",
":",
"if",
"input",
"is",
"not",
"None",
":",
"... | 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. | [
"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",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/staticMask.py#L32-L55 | train | 35,653 |
spacetelescope/drizzlepac | drizzlepac/staticMask.py | staticMask.addMember | 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_id)
The signature is defined in the image object for each chip
"""
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)
chipimage=imagePtr.getData(chipid)
signature=imagePtr[chipid].signature
# If this is a new signature, create a new Static Mask file which is empty
# only create a new mask if one doesn't already exist
if ((signature not in self.masklist) or (len(self.masklist) == 0)):
self.masklist[signature] = self._buildMaskArray(signature)
maskname = constructFilename(signature)
self.masknames[signature] = maskname
else:
chip_sig = buildSignatureKey(signature)
for s in self.masknames:
if chip_sig in self.masknames[s]:
maskname = self.masknames[s]
break
imagePtr[chipid].outputNames['staticMask'] = maskname
stats = ImageStats(chipimage,nclip=3,fields='mode')
mode = stats.mode
rms = stats.stddev
nbins = len(stats.histogram)
del stats
log.info(' mode = %9f; rms = %7f; static_sig = %0.2f' %
(mode, rms, self.static_sig))
if nbins >= 2: # only combine data from new image if enough data to mask
sky_rms_diff = mode - (self.static_sig*rms)
np.bitwise_and(self.masklist[signature],
np.logical_not(np.less(chipimage, sky_rms_diff)),
self.masklist[signature])
del chipimage | python | 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_id)
The signature is defined in the image object for each chip
"""
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)
chipimage=imagePtr.getData(chipid)
signature=imagePtr[chipid].signature
# If this is a new signature, create a new Static Mask file which is empty
# only create a new mask if one doesn't already exist
if ((signature not in self.masklist) or (len(self.masklist) == 0)):
self.masklist[signature] = self._buildMaskArray(signature)
maskname = constructFilename(signature)
self.masknames[signature] = maskname
else:
chip_sig = buildSignatureKey(signature)
for s in self.masknames:
if chip_sig in self.masknames[s]:
maskname = self.masknames[s]
break
imagePtr[chipid].outputNames['staticMask'] = maskname
stats = ImageStats(chipimage,nclip=3,fields='mode')
mode = stats.mode
rms = stats.stddev
nbins = len(stats.histogram)
del stats
log.info(' mode = %9f; rms = %7f; static_sig = %0.2f' %
(mode, rms, self.static_sig))
if nbins >= 2: # only combine data from new image if enough data to mask
sky_rms_diff = mode - (self.static_sig*rms)
np.bitwise_and(self.masklist[signature],
np.logical_not(np.less(chipimage, sky_rms_diff)),
self.masklist[signature])
del chipimage | [
"def",
"addMember",
"(",
"self",
",",
"imagePtr",
"=",
"None",
")",
":",
"numchips",
"=",
"imagePtr",
".",
"_numchips",
"log",
".",
"info",
"(",
"\"Computing static mask:\\n\"",
")",
"chips",
"=",
"imagePtr",
".",
"group",
"if",
"chips",
"is",
"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_id)
The signature is defined in the image object for each chip | [
"Combines",
"the",
"input",
"image",
"with",
"the",
"static",
"mask",
"that",
"has",
"the",
"same",
"signature",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/staticMask.py#L145-L205 | train | 35,654 |
spacetelescope/drizzlepac | drizzlepac/staticMask.py | staticMask.getMaskArray | 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 | python | 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 | [
"def",
"getMaskArray",
"(",
"self",
",",
"signature",
")",
":",
"if",
"signature",
"in",
"self",
".",
"masklist",
":",
"mask",
"=",
"self",
".",
"masklist",
"[",
"signature",
"]",
"else",
":",
"mask",
"=",
"None",
"return",
"mask"
] | Returns the appropriate StaticMask array for the image. | [
"Returns",
"the",
"appropriate",
"StaticMask",
"array",
"for",
"the",
"image",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/staticMask.py#L211-L217 | train | 35,655 |
spacetelescope/drizzlepac | drizzlepac/staticMask.py | staticMask.getFilename | 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 for ", str(signature), " does not exist on disk", file=sys.stderr)
return None | python | 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 for ", str(signature), " does not exist on disk", file=sys.stderr)
return None | [
"def",
"getFilename",
"(",
"self",
",",
"signature",
")",
":",
"filename",
"=",
"constructFilename",
"(",
"signature",
")",
"if",
"(",
"fileutil",
".",
"checkFileExists",
"(",
"filename",
")",
")",
":",
"return",
"filename",
"else",
":",
"print",
"(",
"\"\... | Returns the name of the output mask file that
should reside on disk for the given signature. | [
"Returns",
"the",
"name",
"of",
"the",
"output",
"mask",
"file",
"that",
"should",
"reside",
"on",
"disk",
"for",
"the",
"given",
"signature",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/staticMask.py#L219-L229 | train | 35,656 |
spacetelescope/drizzlepac | drizzlepac/staticMask.py | staticMask.close | def close(self):
""" Deletes all static mask objects. """
for key in self.masklist.keys():
self.masklist[key] = None
self.masklist = {} | python | def close(self):
""" Deletes all static mask objects. """
for key in self.masklist.keys():
self.masklist[key] = None
self.masklist = {} | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"masklist",
".",
"keys",
"(",
")",
":",
"self",
".",
"masklist",
"[",
"key",
"]",
"=",
"None",
"self",
".",
"masklist",
"=",
"{",
"}"
] | Deletes all static mask objects. | [
"Deletes",
"all",
"static",
"mask",
"objects",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/staticMask.py#L241-L246 | train | 35,657 |
spacetelescope/drizzlepac | drizzlepac/staticMask.py | staticMask.deleteMask | 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") | python | 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") | [
"def",
"deleteMask",
"(",
"self",
",",
"signature",
")",
":",
"if",
"signature",
"in",
"self",
".",
"masklist",
":",
"self",
".",
"masklist",
"[",
"signature",
"]",
"=",
"None",
"else",
":",
"log",
".",
"warning",
"(",
"\"No matching mask\"",
")"
] | Delete just the mask that matches the signature given. | [
"Delete",
"just",
"the",
"mask",
"that",
"matches",
"the",
"signature",
"given",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/staticMask.py#L248-L253 | train | 35,658 |
spacetelescope/drizzlepac | drizzlepac/staticMask.py | staticMask.saveToFile | 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():
#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 unit
newHDU = fits.PrimaryHDU()
newHDU.data = self.masklist[key]
if virtual:
for img in imageObjectList:
img.saveVirtualOutputs({filename:newHDU})
else:
try:
newHDU.writeto(filename, overwrite=True)
log.info("Saving static mask to disk: %s" % filename)
except IOError:
log.error("Problem saving static mask file: %s to "
"disk!\n" % filename)
raise IOError | python | 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():
#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 unit
newHDU = fits.PrimaryHDU()
newHDU.data = self.masklist[key]
if virtual:
for img in imageObjectList:
img.saveVirtualOutputs({filename:newHDU})
else:
try:
newHDU.writeto(filename, overwrite=True)
log.info("Saving static mask to disk: %s" % filename)
except IOError:
log.error("Problem saving static mask file: %s to "
"disk!\n" % filename)
raise IOError | [
"def",
"saveToFile",
"(",
"self",
",",
"imageObjectList",
")",
":",
"virtual",
"=",
"imageObjectList",
"[",
"0",
"]",
".",
"inmemory",
"for",
"key",
"in",
"self",
".",
"masklist",
".",
"keys",
"(",
")",
":",
"#check to see if the file already exists on disk",
... | Saves the static mask to a file
it uses the signatures associated with each
mask to contruct the filename for the output mask image. | [
"Saves",
"the",
"static",
"mask",
"to",
"a",
"file",
"it",
"uses",
"the",
"signatures",
"associated",
"with",
"each",
"mask",
"to",
"contruct",
"the",
"filename",
"for",
"the",
"output",
"mask",
"image",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/staticMask.py#L255-L282 | train | 35,659 |
spacetelescope/drizzlepac | drizzlepac/stisData.py | expand_image | 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 "
"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) / (2.0 * sy)
# generate output coordinates:
y, x = np.indices(shape, dtype=np.float)
x = x / sx - ox
y = y / sy - oy
# interpolate:
return bilinear_interp(image, x, y) | python | 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 "
"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) / (2.0 * sy)
# generate output coordinates:
y, x = np.indices(shape, dtype=np.float)
x = x / sx - ox
y = y / sy - oy
# interpolate:
return bilinear_interp(image, x, y) | [
"def",
"expand_image",
"(",
"image",
",",
"shape",
")",
":",
"if",
"(",
"shape",
"[",
"0",
"]",
"%",
"image",
".",
"shape",
"[",
"0",
"]",
")",
"or",
"(",
"shape",
"[",
"1",
"]",
"%",
"image",
".",
"shape",
"[",
"1",
"]",
")",
":",
"raise",
... | Expand image from original shape to requested shape. Output shape
must be an integer multiple of input image shape for each axis. | [
"Expand",
"image",
"from",
"original",
"shape",
"to",
"requested",
"shape",
".",
"Output",
"shape",
"must",
"be",
"an",
"integer",
"multiple",
"of",
"input",
"image",
"shape",
"for",
"each",
"axis",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/stisData.py#L415-L433 | train | 35,660 |
spacetelescope/drizzlepac | drizzlepac/stisData.py | bilinear_interp | 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.ravel()
y = y.ravel()
x0 = np.empty(out_size, dtype=np.int)
y0 = np.empty(out_size, dtype=np.int)
np.clip(x, 0, data.shape[1] - 2, out=x0)
np.clip(y, 0, data.shape[0] - 2, out=y0)
x1 = x0 + 1
y1 = y0 + 1
f00 = data[(y0, x0)]
f10 = data[(y1, x0)]
f01 = data[(y0, x1)]
f11 = data[(y1, x1)]
w00 = (x1 - x) * (y1 - y)
w10 = (x1 - x) * (y - y0)
w01 = (x - x0) * (y1 - y)
w11 = (x - x0) * (y - y0)
interp = w00 * f00 + w10 * f10 + w01 * f01 + w11 * f11
return interp.reshape(out_shape).astype(data.dtype.type) | python | 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.ravel()
y = y.ravel()
x0 = np.empty(out_size, dtype=np.int)
y0 = np.empty(out_size, dtype=np.int)
np.clip(x, 0, data.shape[1] - 2, out=x0)
np.clip(y, 0, data.shape[0] - 2, out=y0)
x1 = x0 + 1
y1 = y0 + 1
f00 = data[(y0, x0)]
f10 = data[(y1, x0)]
f01 = data[(y0, x1)]
f11 = data[(y1, x1)]
w00 = (x1 - x) * (y1 - y)
w10 = (x1 - x) * (y - y0)
w01 = (x - x0) * (y1 - y)
w11 = (x - x0) * (y - y0)
interp = w00 * f00 + w10 * f10 + w01 * f01 + w11 * f11
return interp.reshape(out_shape).astype(data.dtype.type) | [
"def",
"bilinear_interp",
"(",
"data",
",",
"x",
",",
"y",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"y",
"=",
"np",
".",
"asarray",
"(",
"y",
")",
"if",
"x",
".",
"shape",
"!=",
"y",
".",
"shape",
":",
"raise",
"ValueError",
"... | Interpolate input ``data`` at "pixel" coordinates ``x`` and ``y``. | [
"Interpolate",
"input",
"data",
"at",
"pixel",
"coordinates",
"x",
"and",
"y",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/stisData.py#L436-L467 | train | 35,661 |
spacetelescope/drizzlepac | drizzlepac/stisData.py | STISInputImage.getflat | 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 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"].header['PFLTFILE'])
# Try to open the file in the location specified by LFLTFILE.
try:
handle = fileutil.openImage(lflatfile, mode='readonly', memmap=False)
hdu = fileutil.getExtn(handle,extn=exten)
lfltdata = hdu.data
if lfltdata.shape != self.full_shape:
lfltdata = expand_image(lfltdata, self.full_shape)
except IOError:
lfltdata = np.ones(self.full_shape, dtype=sci_chip.data.dtype)
print("Cannot find file '{:s}'. Treating flatfield constant value "
"of '1'.\n".format(lflatfile))
# Try to open the file in the location specified by PFLTFILE.
try:
handle = fileutil.openImage(pflatfile, mode='readonly', memmap=False)
hdu = fileutil.getExtn(handle,extn=exten)
pfltdata = hdu.data
except IOError:
pfltdata = np.ones(self.full_shape, dtype=sci_chip.data.dtype)
print("Cannot find file '{:s}'. Treating flatfield constant value "
"of '1'.\n".format(pflatfile))
flat = lfltdata * pfltdata
return flat | python | 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 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"].header['PFLTFILE'])
# Try to open the file in the location specified by LFLTFILE.
try:
handle = fileutil.openImage(lflatfile, mode='readonly', memmap=False)
hdu = fileutil.getExtn(handle,extn=exten)
lfltdata = hdu.data
if lfltdata.shape != self.full_shape:
lfltdata = expand_image(lfltdata, self.full_shape)
except IOError:
lfltdata = np.ones(self.full_shape, dtype=sci_chip.data.dtype)
print("Cannot find file '{:s}'. Treating flatfield constant value "
"of '1'.\n".format(lflatfile))
# Try to open the file in the location specified by PFLTFILE.
try:
handle = fileutil.openImage(pflatfile, mode='readonly', memmap=False)
hdu = fileutil.getExtn(handle,extn=exten)
pfltdata = hdu.data
except IOError:
pfltdata = np.ones(self.full_shape, dtype=sci_chip.data.dtype)
print("Cannot find file '{:s}'. Treating flatfield constant value "
"of '1'.\n".format(pflatfile))
flat = lfltdata * pfltdata
return flat | [
"def",
"getflat",
"(",
"self",
",",
"chip",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"exten",
"=",
"self",
".",
"errExt",
"+",
"','",
"+",
"str",
"(",
"chip",
")",
"# The keyword for STIS flat ... | 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. | [
"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",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/stisData.py#L28-L66 | train | 35,662 |
spacetelescope/drizzlepac | drizzlepac/stisData.py | STISInputImage._assignSignature | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"ny",
"=",
"sci_chip",
".",
"_naxis1",
"nx",
"=",
"sci_chip",
".",
"_naxis2",
"detnum",
"=",
"sci_c... | 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. | [
"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",
"."... | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/stisData.py#L97-L113 | train | 35,663 |
spacetelescope/drizzlepac | drizzlepac/stisData.py | NUVInputImage.doUnitConversions | 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):
chip=self._image[self.scienceExt,det]
conversionFactor = self.effGain
chip._gain = self.effGain #1.
chip.effGain = self.effGain
chip._conversionFactor = conversionFactor | python | 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):
chip=self._image[self.scienceExt,det]
conversionFactor = self.effGain
chip._gain = self.effGain #1.
chip.effGain = self.effGain
chip._conversionFactor = conversionFactor | [
"def",
"doUnitConversions",
"(",
"self",
")",
":",
"for",
"det",
"in",
"range",
"(",
"1",
",",
"self",
".",
"_numchips",
"+",
"1",
",",
"1",
")",
":",
"chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"det",
"]",
"conversionF... | 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. | [
"Convert",
"the",
"data",
"to",
"electrons",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/stisData.py#L286-L301 | train | 35,664 |
spacetelescope/drizzlepac | drizzlepac/drizCR.py | drizCR | 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 is None:
return
if not editpars:
run(configObj) | python | 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 is None:
return
if not editpars:
run(configObj) | [
"def",
"drizCR",
"(",
"input",
"=",
"None",
",",
"configObj",
"=",
"None",
",",
"editpars",
"=",
"False",
",",
"*",
"*",
"inputDict",
")",
":",
"log",
".",
"debug",
"(",
"inputDict",
")",
"inputDict",
"[",
"\"input\"",
"]",
"=",
"input",
"configObj",
... | Look for cosmic rays. | [
"Look",
"for",
"cosmic",
"rays",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/drizCR.py#L34-L44 | train | 35,665 |
spacetelescope/drizzlepac | drizzlepac/drizCR.py | createCorrFile | 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.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']
if arr['dqext'][0] != arr['sciext'][0]:
ftemplate[arr['dqext']].data = arr['dqMask']
ftemplate.writeto(outfile)
print("Created CR corrected file: '{:s}'".format(outfile)) | python | 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.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']
if arr['dqext'][0] != arr['sciext'][0]:
ftemplate[arr['dqext']].data = arr['dqMask']
ftemplate.writeto(outfile)
print("Created CR corrected file: '{:s}'".format(outfile)) | [
"def",
"createCorrFile",
"(",
"outfile",
",",
"arrlist",
",",
"template",
")",
":",
"# Remove the existing cor file if it exists",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"outfile",
")",
":",
"os",
".",
"remove",
"(",
"outfile",
")",
"print",
"(",
"\"Re... | 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. | [
"Create",
"a",
"_cor",
"file",
"with",
"the",
"same",
"format",
"as",
"the",
"original",
"input",
"image",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/drizCR.py#L300-L318 | train | 35,666 |
spacetelescope/drizzlepac | drizzlepac/drizCR.py | setDefaults | 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
# 3x3 for non-NICMOS]
'ctegrow': 0, # Length of CTE correction to be applied
'rn': 5, # Read noise in electrons
'snr': '4.0 3.0', # Signal-to-noise ratio
'scale': '0.5 0.4', # scaling factor applied to the derivative
'backg': 0, # Background value
'expkey': 'exptime' # exposure time keyword
}
if len(configObj) > 0:
for key in configObj:
paramDict[key] = configObj[key]
return paramDict | python | 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
# 3x3 for non-NICMOS]
'ctegrow': 0, # Length of CTE correction to be applied
'rn': 5, # Read noise in electrons
'snr': '4.0 3.0', # Signal-to-noise ratio
'scale': '0.5 0.4', # scaling factor applied to the derivative
'backg': 0, # Background value
'expkey': 'exptime' # exposure time keyword
}
if len(configObj) > 0:
for key in configObj:
paramDict[key] = configObj[key]
return paramDict | [
"def",
"setDefaults",
"(",
"configObj",
"=",
"{",
"}",
")",
":",
"paramDict",
"=",
"{",
"'gain'",
":",
"7",
",",
"# Detector gain, e-/ADU",
"'grow'",
":",
"1",
",",
"# Radius around CR pixel to mask [default=1 for",
"# 3x3 for non-NICMOS]",
"'ctegrow'",
":",
"0"... | Return a dictionary of the default parameters
which also been updated with the user overrides. | [
"Return",
"a",
"dictionary",
"of",
"the",
"default",
"parameters",
"which",
"also",
"been",
"updated",
"with",
"the",
"user",
"overrides",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/drizCR.py#L321-L341 | train | 35,667 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | getMdriztabPars | 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('No MDRIZTAB found for "%s". Parameters remain unchanged.'%(filelist[0]))
mdrizdict = {}
return mdrizdict | python | 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('No MDRIZTAB found for "%s". Parameters remain unchanged.'%(filelist[0]))
mdrizdict = {}
return mdrizdict | [
"def",
"getMdriztabPars",
"(",
"input",
")",
":",
"filelist",
",",
"output",
",",
"ivmlist",
",",
"oldasndict",
"=",
"processFilenames",
"(",
"input",
",",
"None",
")",
"try",
":",
"mdrizdict",
"=",
"mdzhandler",
".",
"getMdriztabParameters",
"(",
"filelist",
... | High-level function for getting the parameters from MDRIZTAB
Used primarily for TEAL interface. | [
"High",
"-",
"level",
"function",
"for",
"getting",
"the",
"parameters",
"from",
"MDRIZTAB"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L298-L311 | train | 35,668 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | addIVMInputs | 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) | python | 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) | [
"def",
"addIVMInputs",
"(",
"imageObjectList",
",",
"ivmlist",
")",
":",
"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. | [
"Add",
"IVM",
"filenames",
"provided",
"by",
"user",
"to",
"outputNames",
"dictionary",
"for",
"each",
"input",
"imageObject",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L313-L320 | train | 35,669 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | checkMultipleFiles | 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 | python | 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 | [
"def",
"checkMultipleFiles",
"(",
"input",
")",
":",
"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. | [
"Evaluates",
"the",
"input",
"to",
"determine",
"whether",
"there",
"is",
"1",
"or",
"more",
"than",
"1",
"valid",
"input",
"file",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L322-L326 | train | 35,670 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | createImageObjectList | 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:
image = _getInputImage(img,group=group)
image.setInstrumentParameters(instrpars)
image.compute_wcslin(undistort=undistort)
if 'MTFLAG' in image._image['PRIMARY'].header:
# check to see whether we are dealing with moving target observations...
_keyval = image._image['PRIMARY'].header['MTFLAG']
if not util.is_blank(_keyval):
if isinstance(_keyval,bool):
mtflag = _keyval
else:
if 'T' in _keyval:
mtflag = True
else:
mtflag = False
else:
mtflag = False
if mtflag:
print("#####\nProcessing Moving Target Observations using reference image as WCS for all inputs!\n#####\n")
if mt_refimg is None:
mt_refimg = image
else:
image.set_mt_wcs(mt_refimg)
image.inmemory = inmemory # set flag for inmemory processing
# Now add (possibly updated) image object to list
imageObjList.append(image)
return imageObjList | python | 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:
image = _getInputImage(img,group=group)
image.setInstrumentParameters(instrpars)
image.compute_wcslin(undistort=undistort)
if 'MTFLAG' in image._image['PRIMARY'].header:
# check to see whether we are dealing with moving target observations...
_keyval = image._image['PRIMARY'].header['MTFLAG']
if not util.is_blank(_keyval):
if isinstance(_keyval,bool):
mtflag = _keyval
else:
if 'T' in _keyval:
mtflag = True
else:
mtflag = False
else:
mtflag = False
if mtflag:
print("#####\nProcessing Moving Target Observations using reference image as WCS for all inputs!\n#####\n")
if mt_refimg is None:
mt_refimg = image
else:
image.set_mt_wcs(mt_refimg)
image.inmemory = inmemory # set flag for inmemory processing
# Now add (possibly updated) image object to list
imageObjList.append(image)
return imageObjList | [
"def",
"createImageObjectList",
"(",
"files",
",",
"instrpars",
",",
"group",
"=",
"None",
",",
"undistort",
"=",
"True",
",",
"inmemory",
"=",
"False",
")",
":",
"imageObjList",
"=",
"[",
"]",
"mtflag",
"=",
"False",
"mt_refimg",
"=",
"None",
"for",
"im... | Returns a list of imageObject instances, 1 for each input image in the list of input filenames. | [
"Returns",
"a",
"list",
"of",
"imageObject",
"instances",
"1",
"for",
"each",
"input",
"image",
"in",
"the",
"list",
"of",
"input",
"filenames",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L328-L362 | train | 35,671 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | _getInputImage | 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:
# change to use fits more directly here?
if group.find(',') > 0:
grp = group.split(',')
if grp[0].isalpha():
grp = (grp[0],int(grp[1]))
else:
grp = int(grp[0])
else:
grp = int(group)
phdu = fits.getheader(input, memmap=False)
phdu.extend(fits.getheader(input, ext=grp, memmap=False))
# Extract the instrument name for the data that is being processed by Multidrizzle
_instrument = phdu['INSTRUME']
# Determine the instrument detector in use. NICMOS is a special case because it does
# not use the 'DETECTOR' keyword. It instead used 'CAMERA' to identify which of it's
# 3 camera's is in use. All other instruments support the 'DETECTOR' keyword.
if _instrument == 'NICMOS':
_detector = phdu['CAMERA']
else:
try:
_detector = phdu['DETECTOR']
except KeyError:
# using the phdu as set above (fits.getheader) is MUCH faster and
# works for the majority of data; but fileutil handles waivered fits
phdu = fileutil.getHeader(input+exten)
_detector = phdu['DETECTOR'] # if this fails, let it throw
del phdu # just to keep clean
# Match up the instrument and detector with the right class
# only importing the instrument modules as needed.
try:
if _instrument == 'ACS':
from . import acsData
if _detector == 'HRC': return acsData.HRCInputImage(input,group=group)
if _detector == 'WFC': return acsData.WFCInputImage(input,group=group)
if _detector == 'SBC': return acsData.SBCInputImage(input,group=group)
if _instrument == 'NICMOS':
from . import nicmosData
if _detector == 1: return nicmosData.NIC1InputImage(input)
if _detector == 2: return nicmosData.NIC2InputImage(input)
if _detector == 3: return nicmosData.NIC3InputImage(input)
if _instrument == 'WFPC2':
from . import wfpc2Data
return wfpc2Data.WFPC2InputImage(input,group=group)
"""
if _detector == 1: return wfpc2Data.PCInputImage(input)
if _detector == 2: return wfpc2Data.WF2InputImage(input)
if _detector == 3: return wfpc2Data.WF3InputImage(input)
if _detector == 4: return wfpc2Data.WF4InputImage(input)
"""
if _instrument == 'STIS':
from . import stisData
if _detector == 'CCD': return stisData.CCDInputImage(input,group=group)
if _detector == 'FUV-MAMA': return stisData.FUVInputImage(input,group=group)
if _detector == 'NUV-MAMA': return stisData.NUVInputImage(input,group=group)
if _instrument == 'WFC3':
from . import wfc3Data
if _detector == 'UVIS': return wfc3Data.WFC3UVISInputImage(input,group=group)
if _detector == 'IR': return wfc3Data.WFC3IRInputImage(input,group=group)
except ImportError:
msg = 'No module implemented for '+str(_instrument)+'!'
raise ValueError(msg)
# If a supported instrument is not detected, print the following error message
# and raise an exception.
msg = 'Instrument: ' + str(_instrument) + '/' + str(_detector) + ' not yet supported!'
raise ValueError(msg) | python | 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:
# change to use fits more directly here?
if group.find(',') > 0:
grp = group.split(',')
if grp[0].isalpha():
grp = (grp[0],int(grp[1]))
else:
grp = int(grp[0])
else:
grp = int(group)
phdu = fits.getheader(input, memmap=False)
phdu.extend(fits.getheader(input, ext=grp, memmap=False))
# Extract the instrument name for the data that is being processed by Multidrizzle
_instrument = phdu['INSTRUME']
# Determine the instrument detector in use. NICMOS is a special case because it does
# not use the 'DETECTOR' keyword. It instead used 'CAMERA' to identify which of it's
# 3 camera's is in use. All other instruments support the 'DETECTOR' keyword.
if _instrument == 'NICMOS':
_detector = phdu['CAMERA']
else:
try:
_detector = phdu['DETECTOR']
except KeyError:
# using the phdu as set above (fits.getheader) is MUCH faster and
# works for the majority of data; but fileutil handles waivered fits
phdu = fileutil.getHeader(input+exten)
_detector = phdu['DETECTOR'] # if this fails, let it throw
del phdu # just to keep clean
# Match up the instrument and detector with the right class
# only importing the instrument modules as needed.
try:
if _instrument == 'ACS':
from . import acsData
if _detector == 'HRC': return acsData.HRCInputImage(input,group=group)
if _detector == 'WFC': return acsData.WFCInputImage(input,group=group)
if _detector == 'SBC': return acsData.SBCInputImage(input,group=group)
if _instrument == 'NICMOS':
from . import nicmosData
if _detector == 1: return nicmosData.NIC1InputImage(input)
if _detector == 2: return nicmosData.NIC2InputImage(input)
if _detector == 3: return nicmosData.NIC3InputImage(input)
if _instrument == 'WFPC2':
from . import wfpc2Data
return wfpc2Data.WFPC2InputImage(input,group=group)
"""
if _detector == 1: return wfpc2Data.PCInputImage(input)
if _detector == 2: return wfpc2Data.WF2InputImage(input)
if _detector == 3: return wfpc2Data.WF3InputImage(input)
if _detector == 4: return wfpc2Data.WF4InputImage(input)
"""
if _instrument == 'STIS':
from . import stisData
if _detector == 'CCD': return stisData.CCDInputImage(input,group=group)
if _detector == 'FUV-MAMA': return stisData.FUVInputImage(input,group=group)
if _detector == 'NUV-MAMA': return stisData.NUVInputImage(input,group=group)
if _instrument == 'WFC3':
from . import wfc3Data
if _detector == 'UVIS': return wfc3Data.WFC3UVISInputImage(input,group=group)
if _detector == 'IR': return wfc3Data.WFC3IRInputImage(input,group=group)
except ImportError:
msg = 'No module implemented for '+str(_instrument)+'!'
raise ValueError(msg)
# If a supported instrument is not detected, print the following error message
# and raise an exception.
msg = 'Instrument: ' + str(_instrument) + '/' + str(_detector) + ' not yet supported!'
raise ValueError(msg) | [
"def",
"_getInputImage",
"(",
"input",
",",
"group",
"=",
"None",
")",
":",
"# extract primary header and SCI,1 header from input image",
"sci_ext",
"=",
"'SCI'",
"if",
"group",
"in",
"[",
"None",
",",
"''",
"]",
":",
"exten",
"=",
"'[sci,1]'",
"phdu",
"=",
"f... | Factory function to return appropriate imageObject class instance | [
"Factory",
"function",
"to",
"return",
"appropriate",
"imageObject",
"class",
"instance"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L371-L449 | train | 35,672 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | processFilenames | 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 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 them
oldasndict = asnutil.readASNTable(input, prodonly=infilesOnly)
if not infilesOnly:
if output in ["",None,"None"]:
output = oldasndict['output'].lower() # insure output name is lower case
asnhdr = fits.getheader(input, memmap=False)
# Only perform duplication check if not already completed...
dupcheck = asnhdr.get('DUPCHECK',default="PERFORM") == "PERFORM"
#filelist = [fileutil.buildRootname(fname) for fname in oldasndict['order']]
filelist = buildASNList(oldasndict['order'],input,check_for_duplicates=dupcheck)
elif (not isinstance(input, list)) and \
(input[0] == '@') :
# input is an @ file
f = open(input[1:])
# Read the first line in order to determine whether
# IVM files have been specified in a second column...
line = f.readline()
f.close()
# Parse the @-file with irafglob to extract the input filename
filelist = irafglob.irafglob(input, atfile=util.atfile_sci)
# If there is a second column...
if len(line.split()) == 2:
# ...parse out the names of the IVM files as well
ivmlist = irafglob.irafglob(input, atfile=util.atfile_ivm)
if output in ['',None,"None"]:
if len(filelist) == 1:
output = fileutil.buildNewRootname(filelist[0])
else:
output = 'final'
else:
#input is a string or a python list
try:
filelist, output = parseinput.parseinput(input, outputname=output)
if output in ['',None,"None"]:
if len(filelist) == 1:
output = fileutil.buildNewRootname(filelist[0])
else:
output = 'final'
if not isinstance(input, list):
filelist.sort()
except IOError: raise
# sort the list of input files
# this ensures the list of input files has the same order on all platforms
# it can have ifferent order because listdir() uses inode order, not unix type order
#filelist.sort()
return filelist, output, ivmlist, oldasndict | python | 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 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 them
oldasndict = asnutil.readASNTable(input, prodonly=infilesOnly)
if not infilesOnly:
if output in ["",None,"None"]:
output = oldasndict['output'].lower() # insure output name is lower case
asnhdr = fits.getheader(input, memmap=False)
# Only perform duplication check if not already completed...
dupcheck = asnhdr.get('DUPCHECK',default="PERFORM") == "PERFORM"
#filelist = [fileutil.buildRootname(fname) for fname in oldasndict['order']]
filelist = buildASNList(oldasndict['order'],input,check_for_duplicates=dupcheck)
elif (not isinstance(input, list)) and \
(input[0] == '@') :
# input is an @ file
f = open(input[1:])
# Read the first line in order to determine whether
# IVM files have been specified in a second column...
line = f.readline()
f.close()
# Parse the @-file with irafglob to extract the input filename
filelist = irafglob.irafglob(input, atfile=util.atfile_sci)
# If there is a second column...
if len(line.split()) == 2:
# ...parse out the names of the IVM files as well
ivmlist = irafglob.irafglob(input, atfile=util.atfile_ivm)
if output in ['',None,"None"]:
if len(filelist) == 1:
output = fileutil.buildNewRootname(filelist[0])
else:
output = 'final'
else:
#input is a string or a python list
try:
filelist, output = parseinput.parseinput(input, outputname=output)
if output in ['',None,"None"]:
if len(filelist) == 1:
output = fileutil.buildNewRootname(filelist[0])
else:
output = 'final'
if not isinstance(input, list):
filelist.sort()
except IOError: raise
# sort the list of input files
# this ensures the list of input files has the same order on all platforms
# it can have ifferent order because listdir() uses inode order, not unix type order
#filelist.sort()
return filelist, output, ivmlist, oldasndict | [
"def",
"processFilenames",
"(",
"input",
"=",
"None",
",",
"output",
"=",
"None",
",",
"infilesOnly",
"=",
"False",
")",
":",
"ivmlist",
"=",
"None",
"oldasndict",
"=",
"None",
"if",
"input",
"is",
"None",
":",
"print",
"(",
"\"No input files provided to pro... | Process the input string which contains the input file information and
return a filelist,output | [
"Process",
"the",
"input",
"string",
"which",
"contains",
"the",
"input",
"file",
"information",
"and",
"return",
"a",
"filelist",
"output"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L452-L518 | train | 35,673 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | process_input | 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(
input, output=output, ivmlist=ivmlist, wcskey=wcskey,
updatewcs=updatewcs, **workinplace)
if not newfilelist:
buildEmptyDRZ(input, output)
return None, None, output
# run all WCS updating -- Now done in buildFileList
#pydr_input = _process_input_wcs(newfilelist, wcskey, updatewcs)
pydr_input = newfilelist
# AsnTable will handle the case when output==None
if not oldasndict:# and output is not None:
oldasndict = asnutil.ASNTable(pydr_input, output=output)
oldasndict.create()
asndict = update_member_names(oldasndict, pydr_input)
asndict['original_file_names'] = origflist
# Build output filename
drz_extn = '_drz.fits'
for img in newfilelist:
# special case logic to automatically recognize when _flc.fits files
# are provided as input and produce a _drc.fits file instead
if '_flc.fits' in img:
drz_extn = '_drc.fits'
break
if output in [None,'']:
output = fileutil.buildNewRootname(asndict['output'],
extn=drz_extn)
else:
if '.fits' in output.lower():
pass
elif drz_extn[:4] not in output.lower():
output = fileutil.buildNewRootname(output, extn=drz_extn)
log.info('Setting up output name: %s' % output)
return asndict, ivmlist, output | python | 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(
input, output=output, ivmlist=ivmlist, wcskey=wcskey,
updatewcs=updatewcs, **workinplace)
if not newfilelist:
buildEmptyDRZ(input, output)
return None, None, output
# run all WCS updating -- Now done in buildFileList
#pydr_input = _process_input_wcs(newfilelist, wcskey, updatewcs)
pydr_input = newfilelist
# AsnTable will handle the case when output==None
if not oldasndict:# and output is not None:
oldasndict = asnutil.ASNTable(pydr_input, output=output)
oldasndict.create()
asndict = update_member_names(oldasndict, pydr_input)
asndict['original_file_names'] = origflist
# Build output filename
drz_extn = '_drz.fits'
for img in newfilelist:
# special case logic to automatically recognize when _flc.fits files
# are provided as input and produce a _drc.fits file instead
if '_flc.fits' in img:
drz_extn = '_drc.fits'
break
if output in [None,'']:
output = fileutil.buildNewRootname(asndict['output'],
extn=drz_extn)
else:
if '.fits' in output.lower():
pass
elif drz_extn[:4] not in output.lower():
output = fileutil.buildNewRootname(output, extn=drz_extn)
log.info('Setting up output name: %s' % output)
return asndict, ivmlist, output | [
"def",
"process_input",
"(",
"input",
",",
"output",
"=",
"None",
",",
"ivmlist",
"=",
"None",
",",
"updatewcs",
"=",
"True",
",",
"prodonly",
"=",
"False",
",",
"wcskey",
"=",
"None",
",",
"*",
"*",
"workinplace",
")",
":",
"newfilelist",
",",
"ivmlis... | Create the full input list of filenames after verifying and converting
files as needed. | [
"Create",
"the",
"full",
"input",
"list",
"of",
"filenames",
"after",
"verifying",
"and",
"converting",
"files",
"as",
"needed",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L521-L569 | train | 35,674 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | _process_input_wcs_single | 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(fname)
extlist = []
for extn in range(1, numext + 1):
extlist.append(('SCI', extn))
if wcskey in string.ascii_uppercase:
wkey = wcskey
wname = ' '
else:
wname = wcskey
wkey = ' '
altwcs.restoreWCS(fname, extlist, wcskey=wkey, wcsname=wname)
# make an asn table at the end
# Make sure there is a WCSCORR table for each input image
if wcskey not in ['', ' ', 'INDEF', None] or updatewcs:
wcscorr.init_wcscorr(fname) | python | 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(fname)
extlist = []
for extn in range(1, numext + 1):
extlist.append(('SCI', extn))
if wcskey in string.ascii_uppercase:
wkey = wcskey
wname = ' '
else:
wname = wcskey
wkey = ' '
altwcs.restoreWCS(fname, extlist, wcskey=wkey, wcsname=wname)
# make an asn table at the end
# Make sure there is a WCSCORR table for each input image
if wcskey not in ['', ' ', 'INDEF', None] or updatewcs:
wcscorr.init_wcscorr(fname) | [
"def",
"_process_input_wcs_single",
"(",
"fname",
",",
"wcskey",
",",
"updatewcs",
")",
":",
"if",
"wcskey",
"in",
"[",
"''",
",",
"' '",
",",
"'INDEF'",
",",
"None",
"]",
":",
"if",
"updatewcs",
":",
"uw",
".",
"updatewcs",
"(",
"fname",
",",
"checkfi... | See docs for _process_input_wcs.
This is separated to be spawned in parallel. | [
"See",
"docs",
"for",
"_process_input_wcs",
".",
"This",
"is",
"separated",
"to",
"be",
"spawned",
"in",
"parallel",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L613-L636 | train | 35,675 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | buildFileList | 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, oldasndict, filelist = \
buildFileListOrig(input=input, output=output, ivmlist=ivmlist,
wcskey=wcskey, updatewcs=updatewcs, **workinplace)
return newfilelist, ivmlist, output, oldasndict | python | 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, 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",
")",
":",
"newfilelist",
",",
"ivmlist",
",",
"output",
",",
"oldasn... | Builds a file list which has undergone various instrument-specific
checks for input to MultiDrizzle, including splitting STIS associations. | [
"Builds",
"a",
"file",
"list",
"which",
"has",
"undergone",
"various",
"instrument",
"-",
"specific",
"checks",
"for",
"input",
"to",
"MultiDrizzle",
"including",
"splitting",
"STIS",
"associations",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L639-L648 | train | 35,676 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | buildASNList | 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 are in the same directory as an ASN table
filelist, duplicates = checkForDuplicateInputs(rootnames)
if check_for_duplicates and duplicates:
# Build new ASN tables for each set of input files
origasn = changeSuffixinASN(asnname, 'flt')
dupasn = changeSuffixinASN(asnname, 'flc')
errstr = 'ERROR:\nMultiple valid input files found:\n'
for fname, dname in zip(filelist, duplicates):
errstr += ' %s %s\n' % (fname, dname)
errstr += ('\nNew association files have been generated for each '
'version of these files.\n %s\n %s\n\nPlease '
're-start astrodrizzle using of these new ASN files or '
'use widlcards for the input to only select one type of '
'input file.' % (dupasn, origasn))
print(textutil.textbox(errstr), file=sys.stderr)
# generate new ASN files for each case,
# report this case of duplicate inputs to the user then quit
raise ValueError
return filelist | python | 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 are in the same directory as an ASN table
filelist, duplicates = checkForDuplicateInputs(rootnames)
if check_for_duplicates and duplicates:
# Build new ASN tables for each set of input files
origasn = changeSuffixinASN(asnname, 'flt')
dupasn = changeSuffixinASN(asnname, 'flc')
errstr = 'ERROR:\nMultiple valid input files found:\n'
for fname, dname in zip(filelist, duplicates):
errstr += ' %s %s\n' % (fname, dname)
errstr += ('\nNew association files have been generated for each '
'version of these files.\n %s\n %s\n\nPlease '
're-start astrodrizzle using of these new ASN files or '
'use widlcards for the input to only select one type of '
'input file.' % (dupasn, origasn))
print(textutil.textbox(errstr), file=sys.stderr)
# generate new ASN files for each case,
# report this case of duplicate inputs to the user then quit
raise ValueError
return filelist | [
"def",
"buildASNList",
"(",
"rootnames",
",",
"asnname",
",",
"check_for_duplicates",
"=",
"True",
")",
":",
"# 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 ... | Return the list of filenames for a given set of rootnames | [
"Return",
"the",
"list",
"of",
"filenames",
"for",
"a",
"given",
"set",
"of",
"rootnames"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L709-L739 | train | 35,677 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | changeSuffixinASN | 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):
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 include suffix
fasn = fits.open(_new_asn, mode='update', memmap=False)
fasn[0].header['DUPCHECK'] = "COMPLETE"
newdata = fasn[1].data.tolist()
for i in range(len(newdata)):
val = newdata[i][0].decode(encoding='UTF-8').strip()
if 'prod' not in newdata[i][1].decode(encoding='UTF-8').lower():
val += '_'+suffix
newdata[i] = (val,newdata[i][1].strip(),newdata[i][2])
# Redefine dtype to support longer strings for MEMNAME
new_dtype = []
d = fasn[1].data.dtype
msize = d.descr[0][1][1:]
new_size = int(msize[1:])+8
mtype = msize[0]
new_dtype.append((d.descr[0][0],d.descr[0][1].replace(msize,'{}{}'.format(mtype,new_size))))
new_dtype.append(d.descr[1])
new_dtype.append(d.descr[2])
# Assign newly created, reformatted array to extension
newasn = np.array(newdata,dtype=new_dtype)
fasn[1].data = newasn
fasn.close()
return _new_asn | python | 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):
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 include suffix
fasn = fits.open(_new_asn, mode='update', memmap=False)
fasn[0].header['DUPCHECK'] = "COMPLETE"
newdata = fasn[1].data.tolist()
for i in range(len(newdata)):
val = newdata[i][0].decode(encoding='UTF-8').strip()
if 'prod' not in newdata[i][1].decode(encoding='UTF-8').lower():
val += '_'+suffix
newdata[i] = (val,newdata[i][1].strip(),newdata[i][2])
# Redefine dtype to support longer strings for MEMNAME
new_dtype = []
d = fasn[1].data.dtype
msize = d.descr[0][1][1:]
new_size = int(msize[1:])+8
mtype = msize[0]
new_dtype.append((d.descr[0][0],d.descr[0][1].replace(msize,'{}{}'.format(mtype,new_size))))
new_dtype.append(d.descr[1])
new_dtype.append(d.descr[2])
# Assign newly created, reformatted array to extension
newasn = np.array(newdata,dtype=new_dtype)
fasn[1].data = newasn
fasn.close()
return _new_asn | [
"def",
"changeSuffixinASN",
"(",
"asnfile",
",",
"suffix",
")",
":",
"# Start by creating a new name for the ASN table",
"_new_asn",
"=",
"asnfile",
".",
"replace",
"(",
"'_asn.fits'",
",",
"'_'",
"+",
"suffix",
"+",
"'_asn.fits'",
")",
"if",
"os",
".",
"path",
... | Create a copy of the original asn file and change the name of all members
to include the suffix. | [
"Create",
"a",
"copy",
"of",
"the",
"original",
"asn",
"file",
"and",
"change",
"the",
"name",
"of",
"all",
"members",
"to",
"include",
"the",
"suffix",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L742-L779 | train | 35,678 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | resetDQBits | 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_bits(sci_chip.dqfile, cr_bits_value,
extver=chip, extname=sci_chip.dq_extn) | python | 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_bits(sci_chip.dqfile, cr_bits_value,
extver=chip, extname=sci_chip.dq_extn) | [
"def",
"resetDQBits",
"(",
"imageObjectList",
",",
"cr_bits_value",
"=",
"4096",
")",
":",
"if",
"cr_bits_value",
">",
"0",
":",
"for",
"img",
"in",
"imageObjectList",
":",
"for",
"chip",
"in",
"range",
"(",
"1",
",",
"img",
".",
"_numchips",
"+",
"1",
... | Reset the CR bit in each input image's DQ array | [
"Reset",
"the",
"CR",
"bit",
"in",
"each",
"input",
"image",
"s",
"DQ",
"array"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L823-L831 | train | 35,679 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | update_member_names | 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
as an input and not the corresponding GEIS file.
"""
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 newkeys:
nkey = pydr_input[newkeys.index(okey)]
nmembers[nkey.split('.fits')[0]] = oval
oldasndict.pop('members')
# replace should be always True to cover the case when flt files were removed
# and the case when names were translated
oldasndict.update(members=nmembers, replace=True)
oldasndict['order'] = translated_names
return oldasndict | python | 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
as an input and not the corresponding GEIS file.
"""
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 newkeys:
nkey = pydr_input[newkeys.index(okey)]
nmembers[nkey.split('.fits')[0]] = oval
oldasndict.pop('members')
# replace should be always True to cover the case when flt files were removed
# and the case when names were translated
oldasndict.update(members=nmembers, replace=True)
oldasndict['order'] = translated_names
return oldasndict | [
"def",
"update_member_names",
"(",
"oldasndict",
",",
"pydr_input",
")",
":",
"omembers",
"=",
"oldasndict",
"[",
"'members'",
"]",
".",
"copy",
"(",
")",
"nmembers",
"=",
"{",
"}",
"translated_names",
"=",
"[",
"f",
".",
"split",
"(",
"'.fits'",
")",
"[... | 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
as an input and not the corresponding GEIS file. | [
"Update",
"names",
"in",
"a",
"member",
"dictionary",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L834-L863 | train | 35,680 |
spacetelescope/drizzlepac | drizzlepac/processInput.py | manageInputCopies | 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.
"""
# 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['preserve']:
# if sub-directory does not exist yet, create it
if not os.path.exists(origdir):
os.mkdir(origdir)
printMsg = True
# check to see if copies already exist for each file
for fname in filelist:
copymade = False # If a copy is made, no need to restore
copyname = os.path.join(origdir,fname)
short_copyname = os.path.join('OrIg_files',fname)
if workinplace['overwrite']:
print('Forcibly archiving original of: ',fname, 'as ',short_copyname)
# make a copy of the file in the sub-directory
if os.path.exists(copyname): os.chmod(copyname, 438) # octal 666
shutil.copy(fname,copyname)
os.chmod(copyname,292) # octal 444 makes files read-only
if printMsg:
print('\nTurning OFF "preserve" and "restore" actions...\n')
printMsg = False # We only need to print this one time...
copymade = True
if (workinplace['preserve'] and not os.path.exists(copyname)) \
and not workinplace['overwrite']:
# Preserving a copy of the input, but only if not already archived
print('Preserving original of: ',fname, 'as ',short_copyname)
# make a copy of the file in the sub-directory
shutil.copy(fname,copyname)
os.chmod(copyname,292) # octal 444 makes files read-only
copymade = True
if 'restore' in workinplace and not copymade:
if (os.path.exists(copyname) and workinplace['restore']) and not workinplace['overwrite']:
print('Restoring original input for ',fname,' from ',short_copyname)
# replace current files with original version
os.chmod(fname, 438) # octal 666
shutil.copy(copyname, fname)
os.chmod(fname, 438) | python | 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.
"""
# 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['preserve']:
# if sub-directory does not exist yet, create it
if not os.path.exists(origdir):
os.mkdir(origdir)
printMsg = True
# check to see if copies already exist for each file
for fname in filelist:
copymade = False # If a copy is made, no need to restore
copyname = os.path.join(origdir,fname)
short_copyname = os.path.join('OrIg_files',fname)
if workinplace['overwrite']:
print('Forcibly archiving original of: ',fname, 'as ',short_copyname)
# make a copy of the file in the sub-directory
if os.path.exists(copyname): os.chmod(copyname, 438) # octal 666
shutil.copy(fname,copyname)
os.chmod(copyname,292) # octal 444 makes files read-only
if printMsg:
print('\nTurning OFF "preserve" and "restore" actions...\n')
printMsg = False # We only need to print this one time...
copymade = True
if (workinplace['preserve'] and not os.path.exists(copyname)) \
and not workinplace['overwrite']:
# Preserving a copy of the input, but only if not already archived
print('Preserving original of: ',fname, 'as ',short_copyname)
# make a copy of the file in the sub-directory
shutil.copy(fname,copyname)
os.chmod(copyname,292) # octal 444 makes files read-only
copymade = True
if 'restore' in workinplace and not copymade:
if (os.path.exists(copyname) and workinplace['restore']) and not workinplace['overwrite']:
print('Restoring original input for ',fname,' from ',short_copyname)
# replace current files with original version
os.chmod(fname, 438) # octal 666
shutil.copy(copyname, fname)
os.chmod(fname, 438) | [
"def",
"manageInputCopies",
"(",
"filelist",
",",
"*",
"*",
"workinplace",
")",
":",
"# Find out what directory is being used for processing",
"workingdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"# Only create sub-directory for copies of inputs, if copies are requested",
"# Creat... | 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. | [
"Creates",
"copies",
"of",
"all",
"input",
"images",
"in",
"a",
"sub",
"-",
"directory",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/processInput.py#L866-L918 | train | 35,681 |
spacetelescope/drizzlepac | drizzlepac/tweakreg.py | _managePsets | 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.
"""
# 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:
if input_dict is not None:
for key in list(input_dict.keys()):
if key in iparsobj_cfg:
if iparsobj is not None and key in iparsobj:
raise DuplicateKeyError("Duplicate parameter '{:s}' "
"provided for task {:s}".format(key, task_name))
iparsobj_cfg[key] = input_dict[key]
del input_dict[key]
if iparsobj is not None:
iparsobj_cfg.update(iparsobj)
del iparsobj_cfg['_task_name_']
# merge these parameters into full set
configobj[section_name].merge(iparsobj_cfg) | python | 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.
"""
# 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:
if input_dict is not None:
for key in list(input_dict.keys()):
if key in iparsobj_cfg:
if iparsobj is not None and key in iparsobj:
raise DuplicateKeyError("Duplicate parameter '{:s}' "
"provided for task {:s}".format(key, task_name))
iparsobj_cfg[key] = input_dict[key]
del input_dict[key]
if iparsobj is not None:
iparsobj_cfg.update(iparsobj)
del iparsobj_cfg['_task_name_']
# merge these parameters into full set
configobj[section_name].merge(iparsobj_cfg) | [
"def",
"_managePsets",
"(",
"configobj",
",",
"section_name",
",",
"task_name",
",",
"iparsobj",
"=",
"None",
",",
"input_dict",
"=",
"None",
")",
":",
"# Merge all configobj instances into a single object",
"configobj",
"[",
"section_name",
"]",
"=",
"{",
"}",
"#... | 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",... | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakreg.py#L46-L74 | train | 35,682 |
spacetelescope/drizzlepac | drizzlepac/tweakreg.py | edit_imagefindpars | 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) | python | 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) | [
"def",
"edit_imagefindpars",
"(",
")",
":",
"teal",
".",
"teal",
"(",
"imagefindpars",
".",
"__taskname__",
",",
"returnAs",
"=",
"None",
",",
"autoClose",
"=",
"True",
",",
"loadOnly",
"=",
"False",
",",
"canExecute",
"=",
"False",
")"
] | Allows the user to edit the imagefindpars configObj in a TEAL GUI | [
"Allows",
"the",
"user",
"to",
"edit",
"the",
"imagefindpars",
"configObj",
"in",
"a",
"TEAL",
"GUI"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakreg.py#L81-L85 | train | 35,683 |
spacetelescope/drizzlepac | drizzlepac/tweakreg.py | edit_refimagefindpars | 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) | python | 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) | [
"def",
"edit_refimagefindpars",
"(",
")",
":",
"teal",
".",
"teal",
"(",
"refimagefindpars",
".",
"__taskname__",
",",
"returnAs",
"=",
"None",
",",
"autoClose",
"=",
"True",
",",
"loadOnly",
"=",
"False",
",",
"canExecute",
"=",
"False",
")"
] | Allows the user to edit the refimagefindpars configObj in a TEAL GUI | [
"Allows",
"the",
"user",
"to",
"edit",
"the",
"refimagefindpars",
"configObj",
"in",
"a",
"TEAL",
"GUI"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakreg.py#L87-L91 | train | 35,684 |
spacetelescope/drizzlepac | drizzlepac/updatenpol.py | find_d2ifile | 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 | python | 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 | [
"def",
"find_d2ifile",
"(",
"flist",
",",
"detector",
")",
":",
"d2ifile",
"=",
"None",
"for",
"f",
"in",
"flist",
":",
"fdet",
"=",
"fits",
".",
"getval",
"(",
"f",
",",
"'detector'",
",",
"memmap",
"=",
"False",
")",
"if",
"fdet",
"==",
"detector",... | Search a list of files for one that matches the detector specified. | [
"Search",
"a",
"list",
"of",
"files",
"for",
"one",
"that",
"matches",
"the",
"detector",
"specified",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/updatenpol.py#L257-L265 | train | 35,685 |
spacetelescope/drizzlepac | drizzlepac/updatenpol.py | find_npolfile | 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, 'filter1', memmap=False)
filt2 = fits.getval(f, 'filter2', memmap=False)
fdate = fits.getval(f, 'date', memmap=False)
if filt1 == 'ANY' or \
(filt1 == filters[0] and filt2 == filters[1]):
npolfile = f
return npolfile | python | 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, 'filter1', memmap=False)
filt2 = fits.getval(f, 'filter2', memmap=False)
fdate = fits.getval(f, 'date', memmap=False)
if filt1 == 'ANY' or \
(filt1 == filters[0] and filt2 == filters[1]):
npolfile = f
return npolfile | [
"def",
"find_npolfile",
"(",
"flist",
",",
"detector",
",",
"filters",
")",
":",
"npolfile",
"=",
"None",
"for",
"f",
"in",
"flist",
":",
"fdet",
"=",
"fits",
".",
"getval",
"(",
"f",
",",
"'detector'",
",",
"memmap",
"=",
"False",
")",
"if",
"fdet",... | Search a list of files for one that matches the configuration
of detector and filters used. | [
"Search",
"a",
"list",
"of",
"files",
"for",
"one",
"that",
"matches",
"the",
"configuration",
"of",
"detector",
"and",
"filters",
"used",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/updatenpol.py#L267-L281 | train | 35,686 |
spacetelescope/drizzlepac | drizzlepac/updatenpol.py | run | 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'],
wcsupdate=configobj['wcsupdate']) | python | 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'],
wcsupdate=configobj['wcsupdate']) | [
"def",
"run",
"(",
"configobj",
"=",
"None",
",",
"editpars",
"=",
"False",
")",
":",
"if",
"configobj",
"is",
"None",
":",
"configobj",
"=",
"teal",
".",
"teal",
"(",
"__taskname__",
",",
"loadOnly",
"=",
"(",
"not",
"editpars",
")",
")",
"update",
... | Teal interface for running this code. | [
"Teal",
"interface",
"for",
"running",
"this",
"code",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/updatenpol.py#L286-L295 | train | 35,687 |
spacetelescope/drizzlepac | drizzlepac/hlautils/astroquery_utils.py | retrieve_observation | 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
ID for observation to be retrieved from the MAST archive. Only the
IPPSSOOT (rootname) of exposure or ASN needs to be provided; eg., ib6v06060.
suffix : list
List containing suffixes of files which should be requested from MAST.
path : string
Directory to use for writing out downloaded files. If `None` (default),
the current working directory will be used.
archive : Boolean
Retain copies of the downloaded files in the astroquery created sub-directories? Default is 'False'.
clobber : Boolean
Download and Overwrite existing files? Default is 'False'.
Returns
-------
local_files : list
List of filenames
"""
local_files = []
# Query MAST for the data with an observation type of either "science" or "calibration"
obsTable = Observations.query_criteria(obs_id=obsid, obstype='all')
# Catch the case where no files are found for download
if len(obsTable) == 0:
log.info("WARNING: Query for {} returned NO RESULTS!".format(obsid))
return local_files
dpobs = Observations.get_product_list(obsTable)
dataProductsByID = Observations.filter_products(dpobs,
productSubGroupDescription=suffix,
extension='fits',
mrp_only=False)
# After the filtering has been done, ensure there is still data in the table for download.
# If the table is empty, look for FLT images in lieu of FLC images. Only want one
# or the other (not both!), so just do the filtering again.
if len(dataProductsByID) == 0:
log.info("WARNING: No FLC files found for {} - will look for FLT files instead.".format(obsid))
suffix = ['FLT']
dataProductsByID = Observations.filter_products(dpobs,
productSubGroupDescription=suffix,
extension='fits',
mrp_only=False)
# If still no data, then return. An exception will eventually be thrown in
# the higher level code.
if len(dataProductsByID) == 0:
log.info("WARNING: No FLC or FLT files found for {}.".format(obsid))
return local_files
allImages = []
for tableLine in dataProductsByID:
allImages.append(tableLine['productFilename'])
log.info(allImages)
if not clobber:
rowsToRemove = []
for rowCtr in range(0,len(dataProductsByID)):
if os.path.exists(dataProductsByID[rowCtr]['productFilename']):
log.info("{} already exists. File download skipped.".format(dataProductsByID[rowCtr]['productFilename']))
rowsToRemove.append(rowCtr)
if rowsToRemove:
rowsToRemove.reverse()
for rowNum in rowsToRemove:
dataProductsByID.remove_row(rowNum)
manifest = Observations.download_products(dataProductsByID, mrp_only=False)
if not clobber:
rowsToRemove.reverse()
for rownum in rowsToRemove:
if not manifest:
local_files = allImages
return local_files
else:
manifest.insert_row(rownum,vals=[allImages[rownum],"LOCAL","None","None"])
download_dir = None
for file,fileStatus in zip(manifest['Local Path'],manifest['Status']):
if fileStatus != "LOCAL":
# Identify what sub-directory was created by astroquery for the download
if download_dir is None:
file_path = file.split(os.sep)
file_path.remove('.')
download_dir = file_path[0]
# Move or copy downloaded file to current directory
local_file = os.path.abspath(os.path.basename(file))
if archive:
shutil.copy(file, local_file)
else:
shutil.move(file, local_file)
# Record what files were downloaded and their current location
local_files.append(os.path.basename(local_file))
else:
local_files.append(file)
if not archive:
# Remove astroquery created sub-directories
shutil.rmtree(download_dir)
return local_files | python | 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
ID for observation to be retrieved from the MAST archive. Only the
IPPSSOOT (rootname) of exposure or ASN needs to be provided; eg., ib6v06060.
suffix : list
List containing suffixes of files which should be requested from MAST.
path : string
Directory to use for writing out downloaded files. If `None` (default),
the current working directory will be used.
archive : Boolean
Retain copies of the downloaded files in the astroquery created sub-directories? Default is 'False'.
clobber : Boolean
Download and Overwrite existing files? Default is 'False'.
Returns
-------
local_files : list
List of filenames
"""
local_files = []
# Query MAST for the data with an observation type of either "science" or "calibration"
obsTable = Observations.query_criteria(obs_id=obsid, obstype='all')
# Catch the case where no files are found for download
if len(obsTable) == 0:
log.info("WARNING: Query for {} returned NO RESULTS!".format(obsid))
return local_files
dpobs = Observations.get_product_list(obsTable)
dataProductsByID = Observations.filter_products(dpobs,
productSubGroupDescription=suffix,
extension='fits',
mrp_only=False)
# After the filtering has been done, ensure there is still data in the table for download.
# If the table is empty, look for FLT images in lieu of FLC images. Only want one
# or the other (not both!), so just do the filtering again.
if len(dataProductsByID) == 0:
log.info("WARNING: No FLC files found for {} - will look for FLT files instead.".format(obsid))
suffix = ['FLT']
dataProductsByID = Observations.filter_products(dpobs,
productSubGroupDescription=suffix,
extension='fits',
mrp_only=False)
# If still no data, then return. An exception will eventually be thrown in
# the higher level code.
if len(dataProductsByID) == 0:
log.info("WARNING: No FLC or FLT files found for {}.".format(obsid))
return local_files
allImages = []
for tableLine in dataProductsByID:
allImages.append(tableLine['productFilename'])
log.info(allImages)
if not clobber:
rowsToRemove = []
for rowCtr in range(0,len(dataProductsByID)):
if os.path.exists(dataProductsByID[rowCtr]['productFilename']):
log.info("{} already exists. File download skipped.".format(dataProductsByID[rowCtr]['productFilename']))
rowsToRemove.append(rowCtr)
if rowsToRemove:
rowsToRemove.reverse()
for rowNum in rowsToRemove:
dataProductsByID.remove_row(rowNum)
manifest = Observations.download_products(dataProductsByID, mrp_only=False)
if not clobber:
rowsToRemove.reverse()
for rownum in rowsToRemove:
if not manifest:
local_files = allImages
return local_files
else:
manifest.insert_row(rownum,vals=[allImages[rownum],"LOCAL","None","None"])
download_dir = None
for file,fileStatus in zip(manifest['Local Path'],manifest['Status']):
if fileStatus != "LOCAL":
# Identify what sub-directory was created by astroquery for the download
if download_dir is None:
file_path = file.split(os.sep)
file_path.remove('.')
download_dir = file_path[0]
# Move or copy downloaded file to current directory
local_file = os.path.abspath(os.path.basename(file))
if archive:
shutil.copy(file, local_file)
else:
shutil.move(file, local_file)
# Record what files were downloaded and their current location
local_files.append(os.path.basename(local_file))
else:
local_files.append(file)
if not archive:
# Remove astroquery created sub-directories
shutil.rmtree(download_dir)
return local_files | [
"def",
"retrieve_observation",
"(",
"obsid",
",",
"suffix",
"=",
"[",
"'FLC'",
"]",
",",
"archive",
"=",
"False",
",",
"clobber",
"=",
"False",
")",
":",
"local_files",
"=",
"[",
"]",
"# Query MAST for the data with an observation type of either \"science\" or \"calib... | 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 (rootname) of exposure or ASN needs to be provided; eg., ib6v06060.
suffix : list
List containing suffixes of files which should be requested from MAST.
path : string
Directory to use for writing out downloaded files. If `None` (default),
the current working directory will be used.
archive : Boolean
Retain copies of the downloaded files in the astroquery created sub-directories? Default is 'False'.
clobber : Boolean
Download and Overwrite existing files? Default is 'False'.
Returns
-------
local_files : list
List of filenames | [
"Simple",
"interface",
"for",
"retrieving",
"an",
"observation",
"from",
"the",
"MAST",
"archive"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astroquery_utils.py#L15-L123 | train | 35,688 |
spacetelescope/drizzlepac | drizzlepac/pixreplace.py | replace | 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.get('ext',None)
if ext in ['',' ','None',None]:
ext = None
files = parseinput.parseinput(input)[0]
for f in files:
fimg = fits.open(f, mode='update', memmap=False)
if ext is None:
# replace pixels in ALL extensions
extn = [i for i in fimg]
else:
if type(ext) == type([]):
extn = [fimg[e] for e in ext]
else:
extn = [fimg[ext]]
for e in extn:
if e.data is not None and e.is_image: # ignore empty Primary HDUs
print("Converting {}[{},{}] value of {} to {}".format(
f,e.name,e.ver,pixvalue,newvalue))
if np.isnan(pixvalue):
e.data[np.isnan(e.data)] = newvalue
else:
e.data[np.where(e.data == pixvalue)] = newvalue
fimg.close() | python | 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.get('ext',None)
if ext in ['',' ','None',None]:
ext = None
files = parseinput.parseinput(input)[0]
for f in files:
fimg = fits.open(f, mode='update', memmap=False)
if ext is None:
# replace pixels in ALL extensions
extn = [i for i in fimg]
else:
if type(ext) == type([]):
extn = [fimg[e] for e in ext]
else:
extn = [fimg[ext]]
for e in extn:
if e.data is not None and e.is_image: # ignore empty Primary HDUs
print("Converting {}[{},{}] value of {} to {}".format(
f,e.name,e.ver,pixvalue,newvalue))
if np.isnan(pixvalue):
e.data[np.isnan(e.data)] = newvalue
else:
e.data[np.where(e.data == pixvalue)] = newvalue
fimg.close() | [
"def",
"replace",
"(",
"input",
",",
"*",
"*",
"pars",
")",
":",
"pixvalue",
"=",
"pars",
".",
"get",
"(",
"'pixvalue'",
",",
"np",
".",
"nan",
")",
"if",
"pixvalue",
"is",
"None",
":",
"pixvalue",
"=",
"np",
".",
"nan",
"# insure that None == np.nan",... | Replace pixels in `input` that have a value of `pixvalue`
with a value given by `newvalue`. | [
"Replace",
"pixels",
"in",
"input",
"that",
"have",
"a",
"value",
"of",
"pixvalue",
"with",
"a",
"value",
"given",
"by",
"newvalue",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/pixreplace.py#L67-L104 | train | 35,689 |
spacetelescope/drizzlepac | drizzlepac/tweakback.py | extract_input_filenames | 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]
if f not in fnames:
fnames.append(f)
return fnames | python | 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]
if f not in fnames:
fnames.append(f)
return fnames | [
"def",
"extract_input_filenames",
"(",
"drzfile",
")",
":",
"data_kws",
"=",
"fits",
".",
"getval",
"(",
"drzfile",
",",
"'d*data'",
",",
"ext",
"=",
"0",
",",
"memmap",
"=",
"False",
")",
"if",
"len",
"(",
"data_kws",
")",
"==",
"0",
":",
"return",
... | Generate a list of filenames from a drizzled image's header | [
"Generate",
"a",
"list",
"of",
"filenames",
"from",
"a",
"drizzled",
"image",
"s",
"header"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakback.py#L351-L364 | train | 35,690 |
spacetelescope/drizzlepac | drizzlepac/tweakback.py | determine_orig_wcsname | 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
orig_key = k
break
if orig_wcsname is None:
# No IDC_ wcsname found... revert to second to last if available
if len(wnames) > 1:
orig_key = wkeys[-2]
orig_wcsname = wnames[orig_key]
return orig_wcsname,orig_key | python | 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
orig_key = k
break
if orig_wcsname is None:
# No IDC_ wcsname found... revert to second to last if available
if len(wnames) > 1:
orig_key = wkeys[-2]
orig_wcsname = wnames[orig_key]
return orig_wcsname,orig_key | [
"def",
"determine_orig_wcsname",
"(",
"header",
",",
"wnames",
",",
"wkeys",
")",
":",
"orig_wcsname",
"=",
"None",
"orig_key",
"=",
"None",
"if",
"orig_wcsname",
"is",
"None",
":",
"for",
"k",
",",
"w",
"in",
"wnames",
".",
"items",
"(",
")",
":",
"if... | Determine the name of the original, unmodified WCS solution | [
"Determine",
"the",
"name",
"of",
"the",
"original",
"unmodified",
"WCS",
"solution"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakback.py#L379-L396 | train | 35,691 |
spacetelescope/drizzlepac | drizzlepac/tweakutils.py | parse_skypos | 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"
"""
rval = make_val_float(ra)
dval = make_val_float(dec)
if rval is None:
rval, dval = radec_hmstodd(ra, dec)
return rval, dval | python | 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"
"""
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",
")",
":",
"rval",
"=",
"make_val_float",
"(",
"ra",
")",
"dval",
"=",
"make_val_float",
"(",
"dec",
")",
"if",
"rval",
"is",
"None",
":",
"rval",
",",
"dval",
"=",
"radec_hmstodd",
"(",
"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"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L173-L191 | train | 35,692 |
spacetelescope/drizzlepac | drizzlepac/tweakutils.py | radec_hmstodd | 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
List or array of input Dec positions
Returns
-------
pos : arr
Array of RA,Dec positions in decimal degrees
Notes
-----
This function supports any specification of RA and Dec as HMS or DMS;
specifically, the formats::
["nn","nn","nn.nn"]
"nn nn nn.nnn"
"nn:nn:nn.nn"
"nnH nnM nn.nnS" or "nnD nnM nn.nnS"
See Also
--------
astropy.coordinates
"""
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 characters to spaces
# (we already know the units)
rastr = ra.translate(hmstrans).strip()
rastr = rastr.replace(' ', ' ')
# convert 'nn nn nn.nn' to final 'nn:nn:nn.nn' string
rastr = rastr.replace(' ', ':')
else:
rastr = ra
if isinstance(dec, list):
decstr = ':'.join(dec)
elif isinstance(dec, float):
decstr = None
pos_dec = dec
elif dec.find(':') < 0:
decstr = dec.translate(hmstrans).strip()
decstr = decstr.replace(' ', ' ')
decstr = decstr.replace(' ', ':')
else:
decstr = dec
if rastr is None:
pos = (pos_ra, pos_dec)
else:
pos_coord = coords.SkyCoord(rastr + ' ' + decstr,
unit=(u.hourangle, u.deg))
pos = (pos_coord.ra.deg, pos_coord.dec.deg)
return pos | python | 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
List or array of input Dec positions
Returns
-------
pos : arr
Array of RA,Dec positions in decimal degrees
Notes
-----
This function supports any specification of RA and Dec as HMS or DMS;
specifically, the formats::
["nn","nn","nn.nn"]
"nn nn nn.nnn"
"nn:nn:nn.nn"
"nnH nnM nn.nnS" or "nnD nnM nn.nnS"
See Also
--------
astropy.coordinates
"""
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 characters to spaces
# (we already know the units)
rastr = ra.translate(hmstrans).strip()
rastr = rastr.replace(' ', ' ')
# convert 'nn nn nn.nn' to final 'nn:nn:nn.nn' string
rastr = rastr.replace(' ', ':')
else:
rastr = ra
if isinstance(dec, list):
decstr = ':'.join(dec)
elif isinstance(dec, float):
decstr = None
pos_dec = dec
elif dec.find(':') < 0:
decstr = dec.translate(hmstrans).strip()
decstr = decstr.replace(' ', ' ')
decstr = decstr.replace(' ', ':')
else:
decstr = dec
if rastr is None:
pos = (pos_ra, pos_dec)
else:
pos_coord = coords.SkyCoord(rastr + ' ' + decstr,
unit=(u.hourangle, u.deg))
pos = (pos_coord.ra.deg, pos_coord.dec.deg)
return pos | [
"def",
"radec_hmstodd",
"(",
"ra",
",",
"dec",
")",
":",
"hmstrans",
"=",
"string",
".",
"maketrans",
"(",
"string",
".",
"ascii_letters",
",",
"' '",
"*",
"len",
"(",
"string",
".",
"ascii_letters",
")",
")",
"if",
"isinstance",
"(",
"ra",
",",
"list"... | 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
List or array of input Dec positions
Returns
-------
pos : arr
Array of RA,Dec positions in decimal degrees
Notes
-----
This function supports any specification of RA and Dec as HMS or DMS;
specifically, the formats::
["nn","nn","nn.nn"]
"nn nn nn.nnn"
"nn:nn:nn.nn"
"nnH nnM nn.nnS" or "nnD nnM nn.nnS"
See Also
--------
astropy.coordinates | [
"Function",
"to",
"convert",
"HMS",
"values",
"into",
"decimal",
"degrees",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L201-L270 | train | 35,693 |
spacetelescope/drizzlepac | drizzlepac/tweakutils.py | parse_exclusions | 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:
print('No valid exclusions file "', fname, '" could be found!')
print('Skipping application of exclusions files to source catalogs.')
return None
# Parse out lines which can be interpreted as positions and distances
exclusion_list = []
units = None
for line in flines:
if line[0] == '#' or 'global' in line[:6]:
continue
# Only interpret the part of the line prior to the comment
# if a comment has been attached to the line
if '#' in line:
line = line.split('#')[0].rstrip()
if units is None:
units = 'pixels'
if line[:3] in ['fk4', 'fk5', 'sky']:
units = 'sky'
if line[:5] in ['image', 'physi', 'pixel']:
units = 'pixels'
continue
if 'circle(' in line:
nline = line.replace('circle(', '')
nline = nline.replace(')', '')
nline = nline.replace('"', '')
vals = nline.split(',')
if ':' in vals[0]:
posval = vals[0] + ' ' + vals[1]
else:
posval = (float(vals[0]), float(vals[1]))
else:
# Try to interpret unformatted line
if ',' in line:
split_tok = ','
else:
split_tok = ' '
vals = line.split(split_tok)
if len(vals) == 3:
if ':' in vals[0]:
posval = vals[0] + ' ' + vals[1]
else:
posval = (float(vals[0]), float(vals[1]))
else:
continue
exclusion_list.append(
{'pos': posval, 'distance': float(vals[2]), 'units': units}
)
return exclusion_list | python | 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:
print('No valid exclusions file "', fname, '" could be found!')
print('Skipping application of exclusions files to source catalogs.')
return None
# Parse out lines which can be interpreted as positions and distances
exclusion_list = []
units = None
for line in flines:
if line[0] == '#' or 'global' in line[:6]:
continue
# Only interpret the part of the line prior to the comment
# if a comment has been attached to the line
if '#' in line:
line = line.split('#')[0].rstrip()
if units is None:
units = 'pixels'
if line[:3] in ['fk4', 'fk5', 'sky']:
units = 'sky'
if line[:5] in ['image', 'physi', 'pixel']:
units = 'pixels'
continue
if 'circle(' in line:
nline = line.replace('circle(', '')
nline = nline.replace(')', '')
nline = nline.replace('"', '')
vals = nline.split(',')
if ':' in vals[0]:
posval = vals[0] + ' ' + vals[1]
else:
posval = (float(vals[0]), float(vals[1]))
else:
# Try to interpret unformatted line
if ',' in line:
split_tok = ','
else:
split_tok = ' '
vals = line.split(split_tok)
if len(vals) == 3:
if ':' in vals[0]:
posval = vals[0] + ' ' + vals[1]
else:
posval = (float(vals[0]), float(vals[1]))
else:
continue
exclusion_list.append(
{'pos': posval, 'distance': float(vals[2]), 'units': units}
)
return exclusion_list | [
"def",
"parse_exclusions",
"(",
"exclusions",
")",
":",
"fname",
"=",
"fileutil",
".",
"osfn",
"(",
"exclusions",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"flines",
"=",
... | Read in exclusion definitions from file named by 'exclusions'
and return a list of positions and distances | [
"Read",
"in",
"exclusion",
"definitions",
"from",
"file",
"named",
"by",
"exclusions",
"and",
"return",
"a",
"list",
"of",
"positions",
"and",
"distances"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L273-L331 | train | 35,694 |
spacetelescope/drizzlepac | drizzlepac/tweakutils.py | parse_colname | 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']
'1-3' or 'c1-c3'
'1:3' or 'c1:c3'
'1 2 3' or 'c1 c2 c3'
'1' or 'c1'
1
Parameters
----------
colname :
Column name or names to be interpreted
Returns
-------
cols : list
The return value will be a list of strings.
"""
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.replace('c', '')
ctok = None
cols = None
if '-' in cname:
ctok = '-'
if ':' in cname:
ctok = ':'
if ctok is not None:
cnums = cname.split(ctok)
c = list(range(int(cnums[0]), int(cnums[1]) + 1))
cols = [str(i) for i in c]
if cols is None:
ctok = ',' if ',' in cname else ' '
cols = cname.split(ctok)
return cols | python | 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']
'1-3' or 'c1-c3'
'1:3' or 'c1:c3'
'1 2 3' or 'c1 c2 c3'
'1' or 'c1'
1
Parameters
----------
colname :
Column name or names to be interpreted
Returns
-------
cols : list
The return value will be a list of strings.
"""
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.replace('c', '')
ctok = None
cols = None
if '-' in cname:
ctok = '-'
if ':' in cname:
ctok = ':'
if ctok is not None:
cnums = cname.split(ctok)
c = list(range(int(cnums[0]), int(cnums[1]) + 1))
cols = [str(i) for i in c]
if cols is None:
ctok = ',' if ',' in cname else ' '
cols = cname.split(ctok)
return cols | [
"def",
"parse_colname",
"(",
"colname",
")",
":",
"if",
"isinstance",
"(",
"colname",
",",
"list",
")",
":",
"cname",
"=",
"''",
"for",
"c",
"in",
"colname",
":",
"cname",
"+=",
"str",
"(",
"c",
")",
"+",
"','",
"cname",
"=",
"cname",
".",
"rstrip"... | 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']
'1-3' or 'c1-c3'
'1:3' or 'c1:c3'
'1 2 3' or 'c1 c2 c3'
'1' or 'c1'
1
Parameters
----------
colname :
Column name or names to be interpreted
Returns
-------
cols : list
The return value will be a list of strings. | [
"Common",
"function",
"to",
"interpret",
"input",
"column",
"names",
"provided",
"by",
"the",
"user",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L334-L390 | train | 35,695 |
spacetelescope/drizzlepac | drizzlepac/tweakutils.py | readcols | 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
Filename of the input file
cols : string or list of strings
Columns to be read into arrays
Returns
-------
outarr : array
Numpy array or arrays of columns from the table
"""
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 | python | 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
Filename of the input file
cols : string or list of strings
Columns to be read into arrays
Returns
-------
outarr : array
Numpy array or arrays of columns from the table
"""
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",
")",
":",
"if",
"_is_str_none",
"(",
"infile",
")",
"is",
"None",
":",
"return",
"None",
"if",
"infile",
".",
"endswith",
"(",
"'.fits'",
")",
":",
"outarr",
"=",
"read_FITS_cols",
"(",
"infil... | 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
Filename of the input file
cols : string or list of strings
Columns to be read into arrays
Returns
-------
outarr : array
Numpy array or arrays of columns from the table | [
"Function",
"which",
"reads",
"specified",
"columns",
"from",
"either",
"FITS",
"tables",
"or",
"ASCII",
"files"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L393-L421 | train | 35,696 |
spacetelescope/drizzlepac | drizzlepac/tweakutils.py | read_FITS_cols | 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
extnum += 1
if not extfound:
print('ERROR: No catalog table found in ', infile)
raise ValueError
# Now, read columns from the table in this extension if no column names
# were provided by user, simply read in all columns from table
if _is_str_none(cols[0]) is None:
cols = ftab[extnum].data.names
# Define the output
outarr = [ftab[extnum].data.field(c) for c in cols]
return outarr | python | 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
extnum += 1
if not extfound:
print('ERROR: No catalog table found in ', infile)
raise ValueError
# Now, read columns from the table in this extension if no column names
# were provided by user, simply read in all columns from table
if _is_str_none(cols[0]) is None:
cols = ftab[extnum].data.names
# Define the output
outarr = [ftab[extnum].data.field(c) for c in cols]
return outarr | [
"def",
"read_FITS_cols",
"(",
"infile",
",",
"cols",
"=",
"None",
")",
":",
"# noqa: N802",
"with",
"fits",
".",
"open",
"(",
"infile",
",",
"memmap",
"=",
"False",
")",
"as",
"ftab",
":",
"extnum",
"=",
"0",
"extfound",
"=",
"False",
"for",
"extn",
... | Read columns from FITS table | [
"Read",
"columns",
"from",
"FITS",
"table"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L424-L447 | train | 35,697 |
spacetelescope/drizzlepac | drizzlepac/tweakutils.py | read_ASCII_cols | 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
entry.
For example::
cols = ['1,2,3','4,5,6',7]
where '1,2,3' represent the X/RA values, '4,5,6' represent the Y/Dec
values and 7 represents the flux value for a total of 3 requested
columns of data to be returned.
Returns
-------
outarr : list of arrays
The return value will be a list of numpy arrays, one for each
'column'.
"""
# 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:
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.split())}
break
numcols = len(cols)
outarr = [[] for _ in range(numcols)]
convert_radec = False
# Now, map specified columns to columns in file and populate output arrays
for l in flines: # interpret each line from catalog file
l = l.strip()
lspl = l.split()
# skip blank lines, comment lines, or lines with
# fewer columns than requested by user
if not l or len(lspl) < numcols or l[0] == '#' or "INDEF" in l:
continue
# For each 'column' requested by user, pull data from row
for c, i in zip(cols, list(range(numcols))):
cnames = parse_colname(c)
if len(cnames) > 1:
# interpret multi-column specification as one value
outval = ''
for cn in cnames:
cnum = coldict[cn]
cval = lspl[cnum]
outval += cval + ' '
outarr[i].append(outval)
convert_radec = True
else:
# pull single value from row for this column
cnum = coldict[cnames[0]]
if isfloat(lspl[cnum]):
cval = float(lspl[cnum])
else:
cval = lspl[cnum]
# Check for multi-column values given as "nn:nn:nn.s"
if ':' in cval:
cval = cval.replace(':', ' ')
convert_radec = True
outarr[i].append(cval)
# convert multi-column RA/Dec specifications
if convert_radec:
outra = []
outdec = []
for ra, dec in zip(outarr[0], outarr[1]):
radd, decdd = radec_hmstodd(ra, dec)
outra.append(radd)
outdec.append(decdd)
outarr[0] = outra
outarr[1] = outdec
# convert all lists to numpy arrays
for c in range(len(outarr)):
outarr[c] = np.array(outarr[c])
return outarr | python | 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
entry.
For example::
cols = ['1,2,3','4,5,6',7]
where '1,2,3' represent the X/RA values, '4,5,6' represent the Y/Dec
values and 7 represents the flux value for a total of 3 requested
columns of data to be returned.
Returns
-------
outarr : list of arrays
The return value will be a list of numpy arrays, one for each
'column'.
"""
# 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:
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.split())}
break
numcols = len(cols)
outarr = [[] for _ in range(numcols)]
convert_radec = False
# Now, map specified columns to columns in file and populate output arrays
for l in flines: # interpret each line from catalog file
l = l.strip()
lspl = l.split()
# skip blank lines, comment lines, or lines with
# fewer columns than requested by user
if not l or len(lspl) < numcols or l[0] == '#' or "INDEF" in l:
continue
# For each 'column' requested by user, pull data from row
for c, i in zip(cols, list(range(numcols))):
cnames = parse_colname(c)
if len(cnames) > 1:
# interpret multi-column specification as one value
outval = ''
for cn in cnames:
cnum = coldict[cn]
cval = lspl[cnum]
outval += cval + ' '
outarr[i].append(outval)
convert_radec = True
else:
# pull single value from row for this column
cnum = coldict[cnames[0]]
if isfloat(lspl[cnum]):
cval = float(lspl[cnum])
else:
cval = lspl[cnum]
# Check for multi-column values given as "nn:nn:nn.s"
if ':' in cval:
cval = cval.replace(':', ' ')
convert_radec = True
outarr[i].append(cval)
# convert multi-column RA/Dec specifications
if convert_radec:
outra = []
outdec = []
for ra, dec in zip(outarr[0], outarr[1]):
radd, decdd = radec_hmstodd(ra, dec)
outra.append(radd)
outdec.append(decdd)
outarr[0] = outra
outarr[1] = outdec
# convert all lists to numpy arrays
for c in range(len(outarr)):
outarr[c] = np.array(outarr[c])
return outarr | [
"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 a... | 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,5,6',7]
where '1,2,3' represent the X/RA values, '4,5,6' represent the Y/Dec
values and 7 represents the flux value for a total of 3 requested
columns of data to be returned.
Returns
-------
outarr : list of arrays
The return value will be a list of numpy arrays, one for each
'column'. | [
"Interpret",
"input",
"ASCII",
"file",
"to",
"return",
"arrays",
"for",
"specified",
"columns",
"."
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L450-L541 | train | 35,698 |
spacetelescope/drizzlepac | drizzlepac/tweakutils.py | write_shiftfile | 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
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.exists(outwcs):
os.remove(outwcs)
p = fits.HDUList()
p.append(fits.PrimaryHDU())
p.append(createWcsHDU(image_list[0].refWCS))
p.writeto(outwcs)
# Write out shiftfile to go with reference WCS
with open(filename, 'w') as f:
f.write('# frame: output\n')
f.write('# refimage: %s[wcs]\n' % outwcs)
f.write('# form: delta\n')
f.write('# units: pixels\n')
f.write(rows)
print('Writing out shiftfile :', filename) | python | 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
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.exists(outwcs):
os.remove(outwcs)
p = fits.HDUList()
p.append(fits.PrimaryHDU())
p.append(createWcsHDU(image_list[0].refWCS))
p.writeto(outwcs)
# Write out shiftfile to go with reference WCS
with open(filename, 'w') as f:
f.write('# frame: output\n')
f.write('# refimage: %s[wcs]\n' % outwcs)
f.write('# form: delta\n')
f.write('# units: pixels\n')
f.write(rows)
print('Writing out shiftfile :', filename) | [
"def",
"write_shiftfile",
"(",
"image_list",
",",
"filename",
",",
"outwcs",
"=",
"'tweak_wcs.fits'",
")",
":",
"rows",
"=",
"''",
"nrows",
"=",
"0",
"for",
"img",
"in",
"image_list",
":",
"row",
"=",
"img",
".",
"get_shiftfile_row",
"(",
")",
"if",
"row... | Write out a shiftfile for a given list of input Image class objects | [
"Write",
"out",
"a",
"shiftfile",
"for",
"a",
"given",
"list",
"of",
"input",
"Image",
"class",
"objects"
] | 15bec3c929a6a869d9e71b9398ced43ede0620f1 | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L544-L572 | train | 35,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.