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/alignimages.py
generate_source_catalogs
def generate_source_catalogs(imglist, **pars): """Generates a dictionary of source catalogs keyed by image name. Parameters ---------- imglist : list List of one or more calibrated fits images that will be used for source detection. Returns ------- sourcecatalogdict : dictionary a dictionary (keyed by image name) of two element dictionaries which in tern contain 1) a dictionary of the detector-specific processing parameters and 2) an astropy table of position and photometry information of all detected sources """ output = pars.get('output', False) sourcecatalogdict = {} for imgname in imglist: log.info("Image name: {}".format(imgname)) sourcecatalogdict[imgname] = {} # open image imghdu = fits.open(imgname) imgprimaryheader = imghdu[0].header instrument = imgprimaryheader['INSTRUME'].lower() detector = imgprimaryheader['DETECTOR'].lower() # get instrument/detector-specific image alignment parameters if instrument in detector_specific_params.keys(): if detector in detector_specific_params[instrument].keys(): detector_pars = detector_specific_params[instrument][detector] # to allow generate_source_catalog to get detector specific parameters detector_pars.update(pars) sourcecatalogdict[imgname]["params"] = detector_pars else: sys.exit("ERROR! Unrecognized detector '{}'. Exiting...".format(detector)) log.error("ERROR! Unrecognized detector '{}'. Exiting...".format(detector)) else: sys.exit("ERROR! Unrecognized instrument '{}'. Exiting...".format(instrument)) log.error("ERROR! Unrecognized instrument '{}'. Exiting...".format(instrument)) # Identify sources in image, convert coords from chip x, y form to reference WCS sky RA, Dec form. imgwcs = HSTWCS(imghdu, 1) fwhmpsf_pix = sourcecatalogdict[imgname]["params"]['fwhmpsf']/imgwcs.pscale #Convert fwhmpsf from arsec to pixels sourcecatalogdict[imgname]["catalog_table"] = amutils.generate_source_catalog(imghdu, fwhm=fwhmpsf_pix, **detector_pars) # write out coord lists to files for diagnostic purposes. Protip: To display the sources in these files in DS9, # set the "Coordinate System" option to "Physical" when loading the region file. imgroot = os.path.basename(imgname).split('_')[0] numSci = amutils.countExtn(imghdu) # Allow user to decide when and how to write out catalogs to files if output: for chip in range(1,numSci+1): chip_cat = sourcecatalogdict[imgname]["catalog_table"][chip] if chip_cat and len(chip_cat) > 0: regfilename = "{}_sci{}_src.reg".format(imgroot, chip) out_table = Table(chip_cat) out_table.write(regfilename, include_names=["xcentroid", "ycentroid"], format="ascii.fast_commented_header") log.info("Wrote region file {}\n".format(regfilename)) imghdu.close() return(sourcecatalogdict)
python
def generate_source_catalogs(imglist, **pars): """Generates a dictionary of source catalogs keyed by image name. Parameters ---------- imglist : list List of one or more calibrated fits images that will be used for source detection. Returns ------- sourcecatalogdict : dictionary a dictionary (keyed by image name) of two element dictionaries which in tern contain 1) a dictionary of the detector-specific processing parameters and 2) an astropy table of position and photometry information of all detected sources """ output = pars.get('output', False) sourcecatalogdict = {} for imgname in imglist: log.info("Image name: {}".format(imgname)) sourcecatalogdict[imgname] = {} # open image imghdu = fits.open(imgname) imgprimaryheader = imghdu[0].header instrument = imgprimaryheader['INSTRUME'].lower() detector = imgprimaryheader['DETECTOR'].lower() # get instrument/detector-specific image alignment parameters if instrument in detector_specific_params.keys(): if detector in detector_specific_params[instrument].keys(): detector_pars = detector_specific_params[instrument][detector] # to allow generate_source_catalog to get detector specific parameters detector_pars.update(pars) sourcecatalogdict[imgname]["params"] = detector_pars else: sys.exit("ERROR! Unrecognized detector '{}'. Exiting...".format(detector)) log.error("ERROR! Unrecognized detector '{}'. Exiting...".format(detector)) else: sys.exit("ERROR! Unrecognized instrument '{}'. Exiting...".format(instrument)) log.error("ERROR! Unrecognized instrument '{}'. Exiting...".format(instrument)) # Identify sources in image, convert coords from chip x, y form to reference WCS sky RA, Dec form. imgwcs = HSTWCS(imghdu, 1) fwhmpsf_pix = sourcecatalogdict[imgname]["params"]['fwhmpsf']/imgwcs.pscale #Convert fwhmpsf from arsec to pixels sourcecatalogdict[imgname]["catalog_table"] = amutils.generate_source_catalog(imghdu, fwhm=fwhmpsf_pix, **detector_pars) # write out coord lists to files for diagnostic purposes. Protip: To display the sources in these files in DS9, # set the "Coordinate System" option to "Physical" when loading the region file. imgroot = os.path.basename(imgname).split('_')[0] numSci = amutils.countExtn(imghdu) # Allow user to decide when and how to write out catalogs to files if output: for chip in range(1,numSci+1): chip_cat = sourcecatalogdict[imgname]["catalog_table"][chip] if chip_cat and len(chip_cat) > 0: regfilename = "{}_sci{}_src.reg".format(imgroot, chip) out_table = Table(chip_cat) out_table.write(regfilename, include_names=["xcentroid", "ycentroid"], format="ascii.fast_commented_header") log.info("Wrote region file {}\n".format(regfilename)) imghdu.close() return(sourcecatalogdict)
[ "def", "generate_source_catalogs", "(", "imglist", ",", "*", "*", "pars", ")", ":", "output", "=", "pars", ".", "get", "(", "'output'", ",", "False", ")", "sourcecatalogdict", "=", "{", "}", "for", "imgname", "in", "imglist", ":", "log", ".", "info", "...
Generates a dictionary of source catalogs keyed by image name. Parameters ---------- imglist : list List of one or more calibrated fits images that will be used for source detection. Returns ------- sourcecatalogdict : dictionary a dictionary (keyed by image name) of two element dictionaries which in tern contain 1) a dictionary of the detector-specific processing parameters and 2) an astropy table of position and photometry information of all detected sources
[ "Generates", "a", "dictionary", "of", "source", "catalogs", "keyed", "by", "image", "name", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/alignimages.py#L903-L964
train
35,500
spacetelescope/drizzlepac
drizzlepac/alignimages.py
update_image_wcs_info
def update_image_wcs_info(tweakwcs_output): """Write newly computed WCS information to image headers and write headerlet files Parameters ---------- tweakwcs_output : list output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid input image. Returns ------- out_headerlet_list : dictionary a dictionary of the headerlet files created by this subroutine, keyed by flt/flc fits filename. """ out_headerlet_dict = {} for item in tweakwcs_output: imageName = item.meta['filename'] chipnum = item.meta['chip'] if chipnum == 1: chipctr = 1 hdulist = fits.open(imageName, mode='update') num_sci_ext = amutils.countExtn(hdulist) # generate wcs name for updated image header, headerlet if not hdulist['SCI',1].header['WCSNAME'] or hdulist['SCI',1].header['WCSNAME'] =="": #Just in case header value 'wcsname' is empty. wcsName = "FIT_{}".format(item.meta['catalog_name']) else: wname = hdulist['sci', 1].header['wcsname'] if "-" in wname: wcsName = '{}-FIT_{}'.format(wname[:wname.index('-')], item.meta['fit_info']['catalog']) else: wcsName = '{}-FIT_{}'.format(wname, item.meta['fit_info']['catalog']) # establish correct mapping to the science extensions sciExtDict = {} for sciExtCtr in range(1, num_sci_ext + 1): sciExtDict["{}".format(sciExtCtr)] = fileutil.findExtname(hdulist,'sci',extver=sciExtCtr) # update header with new WCS info updatehdr.update_wcs(hdulist, sciExtDict["{}".format(item.meta['chip'])], item.wcs, wcsname=wcsName, reusename=True, verbose=True) if chipctr == num_sci_ext: # Close updated flc.fits or flt.fits file #log.info("CLOSE {}\n".format(imageName)) # TODO: Remove before deployment hdulist.flush() hdulist.close() # Create headerlet out_headerlet = headerlet.create_headerlet(imageName, hdrname=wcsName, wcsname=wcsName) # Update headerlet update_headerlet_phdu(item, out_headerlet) # Write headerlet if imageName.endswith("flc.fits"): headerlet_filename = imageName.replace("flc", "flt_hlet") if imageName.endswith("flt.fits"): headerlet_filename = imageName.replace("flt", "flt_hlet") out_headerlet.writeto(headerlet_filename, clobber=True) log.info("Wrote headerlet file {}.\n\n".format(headerlet_filename)) out_headerlet_dict[imageName] = headerlet_filename # Attach headerlet as HDRLET extension headerlet.attach_headerlet(imageName, headerlet_filename) chipctr +=1 return (out_headerlet_dict)
python
def update_image_wcs_info(tweakwcs_output): """Write newly computed WCS information to image headers and write headerlet files Parameters ---------- tweakwcs_output : list output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid input image. Returns ------- out_headerlet_list : dictionary a dictionary of the headerlet files created by this subroutine, keyed by flt/flc fits filename. """ out_headerlet_dict = {} for item in tweakwcs_output: imageName = item.meta['filename'] chipnum = item.meta['chip'] if chipnum == 1: chipctr = 1 hdulist = fits.open(imageName, mode='update') num_sci_ext = amutils.countExtn(hdulist) # generate wcs name for updated image header, headerlet if not hdulist['SCI',1].header['WCSNAME'] or hdulist['SCI',1].header['WCSNAME'] =="": #Just in case header value 'wcsname' is empty. wcsName = "FIT_{}".format(item.meta['catalog_name']) else: wname = hdulist['sci', 1].header['wcsname'] if "-" in wname: wcsName = '{}-FIT_{}'.format(wname[:wname.index('-')], item.meta['fit_info']['catalog']) else: wcsName = '{}-FIT_{}'.format(wname, item.meta['fit_info']['catalog']) # establish correct mapping to the science extensions sciExtDict = {} for sciExtCtr in range(1, num_sci_ext + 1): sciExtDict["{}".format(sciExtCtr)] = fileutil.findExtname(hdulist,'sci',extver=sciExtCtr) # update header with new WCS info updatehdr.update_wcs(hdulist, sciExtDict["{}".format(item.meta['chip'])], item.wcs, wcsname=wcsName, reusename=True, verbose=True) if chipctr == num_sci_ext: # Close updated flc.fits or flt.fits file #log.info("CLOSE {}\n".format(imageName)) # TODO: Remove before deployment hdulist.flush() hdulist.close() # Create headerlet out_headerlet = headerlet.create_headerlet(imageName, hdrname=wcsName, wcsname=wcsName) # Update headerlet update_headerlet_phdu(item, out_headerlet) # Write headerlet if imageName.endswith("flc.fits"): headerlet_filename = imageName.replace("flc", "flt_hlet") if imageName.endswith("flt.fits"): headerlet_filename = imageName.replace("flt", "flt_hlet") out_headerlet.writeto(headerlet_filename, clobber=True) log.info("Wrote headerlet file {}.\n\n".format(headerlet_filename)) out_headerlet_dict[imageName] = headerlet_filename # Attach headerlet as HDRLET extension headerlet.attach_headerlet(imageName, headerlet_filename) chipctr +=1 return (out_headerlet_dict)
[ "def", "update_image_wcs_info", "(", "tweakwcs_output", ")", ":", "out_headerlet_dict", "=", "{", "}", "for", "item", "in", "tweakwcs_output", ":", "imageName", "=", "item", ".", "meta", "[", "'filename'", "]", "chipnum", "=", "item", ".", "meta", "[", "'chi...
Write newly computed WCS information to image headers and write headerlet files Parameters ---------- tweakwcs_output : list output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid input image. Returns ------- out_headerlet_list : dictionary a dictionary of the headerlet files created by this subroutine, keyed by flt/flc fits filename.
[ "Write", "newly", "computed", "WCS", "information", "to", "image", "headers", "and", "write", "headerlet", "files" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/alignimages.py#L970-L1036
train
35,501
spacetelescope/drizzlepac
drizzlepac/alignimages.py
update_headerlet_phdu
def update_headerlet_phdu(tweakwcs_item, headerlet): """Update the primary header data unit keywords of a headerlet object in-place Parameters ========== tweakwc_item : Basically the output from tweakwcs which contains the cross match and fit information for every chip of every valid input image. headerlet : object containing WCS information """ # Get the data to be used as values for FITS keywords rms_ra = tweakwcs_item.meta['fit_info']['RMS_RA'].value rms_dec = tweakwcs_item.meta['fit_info']['RMS_DEC'].value fit_rms = tweakwcs_item.meta['fit_info']['FIT_RMS'] nmatch = tweakwcs_item.meta['fit_info']['nmatches'] catalog = tweakwcs_item.meta['fit_info']['catalog'] x_shift = (tweakwcs_item.meta['fit_info']['shift'])[0] y_shift = (tweakwcs_item.meta['fit_info']['shift'])[1] rot = tweakwcs_item.meta['fit_info']['rot'] scale = tweakwcs_item.meta['fit_info']['scale'][0] skew = tweakwcs_item.meta['fit_info']['skew'] # Update the existing FITS keywords primary_header = headerlet[0].header primary_header['RMS_RA'] = rms_ra primary_header['RMS_DEC'] = rms_dec primary_header['NMATCH'] = nmatch primary_header['CATALOG'] = catalog # Create a new FITS keyword primary_header['FIT_RMS'] = (fit_rms, 'RMS (mas) of the 2D fit of the headerlet solution') # Create the set of HISTORY keywords primary_header['HISTORY'] = '~~~~~ FIT PARAMETERS ~~~~~' primary_header['HISTORY'] = '{:>15} : {:9.4f} "/pixels'.format('platescale', tweakwcs_item.wcs.pscale) primary_header['HISTORY'] = '{:>15} : {:9.4f} pixels'.format('x_shift', x_shift) primary_header['HISTORY'] = '{:>15} : {:9.4f} pixels'.format('y_shift', y_shift) primary_header['HISTORY'] = '{:>15} : {:9.4f} degrees'.format('rotation', rot) primary_header['HISTORY'] = '{:>15} : {:9.4f}'.format('scale', scale) primary_header['HISTORY'] = '{:>15} : {:9.4f}'.format('skew', skew)
python
def update_headerlet_phdu(tweakwcs_item, headerlet): """Update the primary header data unit keywords of a headerlet object in-place Parameters ========== tweakwc_item : Basically the output from tweakwcs which contains the cross match and fit information for every chip of every valid input image. headerlet : object containing WCS information """ # Get the data to be used as values for FITS keywords rms_ra = tweakwcs_item.meta['fit_info']['RMS_RA'].value rms_dec = tweakwcs_item.meta['fit_info']['RMS_DEC'].value fit_rms = tweakwcs_item.meta['fit_info']['FIT_RMS'] nmatch = tweakwcs_item.meta['fit_info']['nmatches'] catalog = tweakwcs_item.meta['fit_info']['catalog'] x_shift = (tweakwcs_item.meta['fit_info']['shift'])[0] y_shift = (tweakwcs_item.meta['fit_info']['shift'])[1] rot = tweakwcs_item.meta['fit_info']['rot'] scale = tweakwcs_item.meta['fit_info']['scale'][0] skew = tweakwcs_item.meta['fit_info']['skew'] # Update the existing FITS keywords primary_header = headerlet[0].header primary_header['RMS_RA'] = rms_ra primary_header['RMS_DEC'] = rms_dec primary_header['NMATCH'] = nmatch primary_header['CATALOG'] = catalog # Create a new FITS keyword primary_header['FIT_RMS'] = (fit_rms, 'RMS (mas) of the 2D fit of the headerlet solution') # Create the set of HISTORY keywords primary_header['HISTORY'] = '~~~~~ FIT PARAMETERS ~~~~~' primary_header['HISTORY'] = '{:>15} : {:9.4f} "/pixels'.format('platescale', tweakwcs_item.wcs.pscale) primary_header['HISTORY'] = '{:>15} : {:9.4f} pixels'.format('x_shift', x_shift) primary_header['HISTORY'] = '{:>15} : {:9.4f} pixels'.format('y_shift', y_shift) primary_header['HISTORY'] = '{:>15} : {:9.4f} degrees'.format('rotation', rot) primary_header['HISTORY'] = '{:>15} : {:9.4f}'.format('scale', scale) primary_header['HISTORY'] = '{:>15} : {:9.4f}'.format('skew', skew)
[ "def", "update_headerlet_phdu", "(", "tweakwcs_item", ",", "headerlet", ")", ":", "# Get the data to be used as values for FITS keywords", "rms_ra", "=", "tweakwcs_item", ".", "meta", "[", "'fit_info'", "]", "[", "'RMS_RA'", "]", ".", "value", "rms_dec", "=", "tweakwc...
Update the primary header data unit keywords of a headerlet object in-place Parameters ========== tweakwc_item : Basically the output from tweakwcs which contains the cross match and fit information for every chip of every valid input image. headerlet : object containing WCS information
[ "Update", "the", "primary", "header", "data", "unit", "keywords", "of", "a", "headerlet", "object", "in", "-", "place" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/alignimages.py#L1040-L1083
train
35,502
spacetelescope/drizzlepac
drizzlepac/alignimages.py
interpret_fit_rms
def interpret_fit_rms(tweakwcs_output, reference_catalog): """Interpret the FIT information to convert RMS to physical units Parameters ---------- tweakwcs_output : list output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid input image. This list gets updated, in-place, with the new RMS values; specifically, * 'FIT_RMS': RMS of the separations between fitted image positions and reference positions * 'TOTAL_RMS': mean of the FIT_RMS values for all observations * 'NUM_FITS': number of images/group_id's with successful fits included in the TOTAL_RMS These entries are added to the 'fit_info' dictionary. reference_catalog : astropy.Table Table of reference source positions used for the fit Returns ------- Nothing """ # Start by collecting information by group_id group_ids = [info.meta['group_id'] for info in tweakwcs_output] # Compress the list to have only unique group_id values to avoid some unnecessary iterations group_ids = list(set(group_ids)) group_dict = {'avg_RMS':None} obs_rms = [] for group_id in group_ids: for item in tweakwcs_output: # When status = FAILED (fit failed) or REFERENCE (relative alignment done with first image # as the reference), skip to the beginning of the loop as there is no 'fit_info'. if item.meta['fit_info']['status'] != 'SUCCESS': continue # Make sure to store data for any particular group_id only once. if item.meta['group_id'] == group_id and \ group_id not in group_dict: group_dict[group_id] = {'ref_idx':None, 'FIT_RMS':None} log.info("fit_info: {}".format(item.meta['fit_info'])) tinfo = item.meta['fit_info'] ref_idx = tinfo['matched_ref_idx'] fitmask = tinfo['fitmask'] group_dict[group_id]['ref_idx'] = ref_idx ref_RA = reference_catalog[ref_idx]['RA'][fitmask] ref_DEC = reference_catalog[ref_idx]['DEC'][fitmask] input_RA = tinfo['fit_RA'] input_DEC = tinfo['fit_DEC'] img_coords = SkyCoord(input_RA, input_DEC, unit='deg',frame='icrs') ref_coords = SkyCoord(ref_RA, ref_DEC, unit='deg',frame='icrs') dra, ddec = img_coords.spherical_offsets_to(ref_coords) ra_rms = np.std(dra.to(u.mas)) dec_rms = np.std(ddec.to(u.mas)) fit_rms = np.std(Angle(img_coords.separation(ref_coords), unit=u.mas)).value group_dict[group_id]['FIT_RMS'] = fit_rms group_dict[group_id]['RMS_RA'] = ra_rms group_dict[group_id]['RMS_DEC'] = dec_rms obs_rms.append(fit_rms) # Compute RMS for entire ASN/observation set total_rms = np.mean(obs_rms) #total_rms = np.sqrt(np.sum(np.array(obs_rms)**2)) # Now, append computed results to tweakwcs_output for item in tweakwcs_output: group_id = item.meta['group_id'] if group_id in group_dict: fit_rms = group_dict[group_id]['FIT_RMS'] ra_rms = group_dict[group_id]['RMS_RA'] dec_rms = group_dict[group_id]['RMS_DEC'] else: fit_rms = None ra_rms = None dec_rms = None item.meta['fit_info']['FIT_RMS'] = fit_rms item.meta['fit_info']['TOTAL_RMS'] = total_rms item.meta['fit_info']['NUM_FITS'] = len(group_ids) item.meta['fit_info']['RMS_RA'] = ra_rms item.meta['fit_info']['RMS_DEC'] = dec_rms item.meta['fit_info']['catalog'] = reference_catalog.meta['catalog']
python
def interpret_fit_rms(tweakwcs_output, reference_catalog): """Interpret the FIT information to convert RMS to physical units Parameters ---------- tweakwcs_output : list output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid input image. This list gets updated, in-place, with the new RMS values; specifically, * 'FIT_RMS': RMS of the separations between fitted image positions and reference positions * 'TOTAL_RMS': mean of the FIT_RMS values for all observations * 'NUM_FITS': number of images/group_id's with successful fits included in the TOTAL_RMS These entries are added to the 'fit_info' dictionary. reference_catalog : astropy.Table Table of reference source positions used for the fit Returns ------- Nothing """ # Start by collecting information by group_id group_ids = [info.meta['group_id'] for info in tweakwcs_output] # Compress the list to have only unique group_id values to avoid some unnecessary iterations group_ids = list(set(group_ids)) group_dict = {'avg_RMS':None} obs_rms = [] for group_id in group_ids: for item in tweakwcs_output: # When status = FAILED (fit failed) or REFERENCE (relative alignment done with first image # as the reference), skip to the beginning of the loop as there is no 'fit_info'. if item.meta['fit_info']['status'] != 'SUCCESS': continue # Make sure to store data for any particular group_id only once. if item.meta['group_id'] == group_id and \ group_id not in group_dict: group_dict[group_id] = {'ref_idx':None, 'FIT_RMS':None} log.info("fit_info: {}".format(item.meta['fit_info'])) tinfo = item.meta['fit_info'] ref_idx = tinfo['matched_ref_idx'] fitmask = tinfo['fitmask'] group_dict[group_id]['ref_idx'] = ref_idx ref_RA = reference_catalog[ref_idx]['RA'][fitmask] ref_DEC = reference_catalog[ref_idx]['DEC'][fitmask] input_RA = tinfo['fit_RA'] input_DEC = tinfo['fit_DEC'] img_coords = SkyCoord(input_RA, input_DEC, unit='deg',frame='icrs') ref_coords = SkyCoord(ref_RA, ref_DEC, unit='deg',frame='icrs') dra, ddec = img_coords.spherical_offsets_to(ref_coords) ra_rms = np.std(dra.to(u.mas)) dec_rms = np.std(ddec.to(u.mas)) fit_rms = np.std(Angle(img_coords.separation(ref_coords), unit=u.mas)).value group_dict[group_id]['FIT_RMS'] = fit_rms group_dict[group_id]['RMS_RA'] = ra_rms group_dict[group_id]['RMS_DEC'] = dec_rms obs_rms.append(fit_rms) # Compute RMS for entire ASN/observation set total_rms = np.mean(obs_rms) #total_rms = np.sqrt(np.sum(np.array(obs_rms)**2)) # Now, append computed results to tweakwcs_output for item in tweakwcs_output: group_id = item.meta['group_id'] if group_id in group_dict: fit_rms = group_dict[group_id]['FIT_RMS'] ra_rms = group_dict[group_id]['RMS_RA'] dec_rms = group_dict[group_id]['RMS_DEC'] else: fit_rms = None ra_rms = None dec_rms = None item.meta['fit_info']['FIT_RMS'] = fit_rms item.meta['fit_info']['TOTAL_RMS'] = total_rms item.meta['fit_info']['NUM_FITS'] = len(group_ids) item.meta['fit_info']['RMS_RA'] = ra_rms item.meta['fit_info']['RMS_DEC'] = dec_rms item.meta['fit_info']['catalog'] = reference_catalog.meta['catalog']
[ "def", "interpret_fit_rms", "(", "tweakwcs_output", ",", "reference_catalog", ")", ":", "# Start by collecting information by group_id", "group_ids", "=", "[", "info", ".", "meta", "[", "'group_id'", "]", "for", "info", "in", "tweakwcs_output", "]", "# Compress the list...
Interpret the FIT information to convert RMS to physical units Parameters ---------- tweakwcs_output : list output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid input image. This list gets updated, in-place, with the new RMS values; specifically, * 'FIT_RMS': RMS of the separations between fitted image positions and reference positions * 'TOTAL_RMS': mean of the FIT_RMS values for all observations * 'NUM_FITS': number of images/group_id's with successful fits included in the TOTAL_RMS These entries are added to the 'fit_info' dictionary. reference_catalog : astropy.Table Table of reference source positions used for the fit Returns ------- Nothing
[ "Interpret", "the", "FIT", "information", "to", "convert", "RMS", "to", "physical", "units" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/alignimages.py#L1089-L1170
train
35,503
spacetelescope/drizzlepac
drizzlepac/sky.py
sky
def sky(input=None,outExt=None,configObj=None, group=None, editpars=False, **inputDict): """ Perform sky subtraction on input list of images Parameters ---------- input : str or list of str a python list of image filenames, or just a single filename configObj : configObject an instance of configObject inputDict : dict, optional an optional list of parameters specified by the user outExt : str The extension of the output image. If the output already exists then the input image is overwritten Notes ----- These are parameters that the configObj should contain by default, they can be altered on the fly using the inputDict Parameters that should be in configobj: ========== =================================================================== Name Definition ========== =================================================================== skymethod 'Sky computation method' skysub 'Perform sky subtraction?' skywidth 'Bin width of histogram for sampling sky statistics (in sigma)' skystat 'Sky correction statistics parameter' skylower 'Lower limit of usable data for sky (always in electrons)' skyupper 'Upper limit of usable data for sky (always in electrons)' skyclip 'Number of clipping iterations' skylsigma 'Lower side clipping factor (in sigma)' skyusigma 'Upper side clipping factor (in sigma)' skymask_cat 'Catalog file listing image masks' use_static 'Use static mask for skymatch computations?' sky_bits 'Integer mask bit values considered good pixels in DQ array' skyfile 'Name of file with user-computed sky values' skyuser 'KEYWORD indicating a sky subtraction value if done by user' in_memory 'Optimize for speed or for memory use' ========== =================================================================== The output from sky subtraction is a copy of the original input file where all the science data extensions have been sky subtracted. """ if input is not None: inputDict['input']=input inputDict['output']=None inputDict['updatewcs']=False inputDict['group']=group else: print("Please supply an input image", file=sys.stderr) raise ValueError configObj = util.getDefaultConfigObj(__taskname__,configObj,inputDict,loadOnly=(not editpars)) if configObj is None: return if not editpars: run(configObj,outExt=outExt)
python
def sky(input=None,outExt=None,configObj=None, group=None, editpars=False, **inputDict): """ Perform sky subtraction on input list of images Parameters ---------- input : str or list of str a python list of image filenames, or just a single filename configObj : configObject an instance of configObject inputDict : dict, optional an optional list of parameters specified by the user outExt : str The extension of the output image. If the output already exists then the input image is overwritten Notes ----- These are parameters that the configObj should contain by default, they can be altered on the fly using the inputDict Parameters that should be in configobj: ========== =================================================================== Name Definition ========== =================================================================== skymethod 'Sky computation method' skysub 'Perform sky subtraction?' skywidth 'Bin width of histogram for sampling sky statistics (in sigma)' skystat 'Sky correction statistics parameter' skylower 'Lower limit of usable data for sky (always in electrons)' skyupper 'Upper limit of usable data for sky (always in electrons)' skyclip 'Number of clipping iterations' skylsigma 'Lower side clipping factor (in sigma)' skyusigma 'Upper side clipping factor (in sigma)' skymask_cat 'Catalog file listing image masks' use_static 'Use static mask for skymatch computations?' sky_bits 'Integer mask bit values considered good pixels in DQ array' skyfile 'Name of file with user-computed sky values' skyuser 'KEYWORD indicating a sky subtraction value if done by user' in_memory 'Optimize for speed or for memory use' ========== =================================================================== The output from sky subtraction is a copy of the original input file where all the science data extensions have been sky subtracted. """ if input is not None: inputDict['input']=input inputDict['output']=None inputDict['updatewcs']=False inputDict['group']=group else: print("Please supply an input image", file=sys.stderr) raise ValueError configObj = util.getDefaultConfigObj(__taskname__,configObj,inputDict,loadOnly=(not editpars)) if configObj is None: return if not editpars: run(configObj,outExt=outExt)
[ "def", "sky", "(", "input", "=", "None", ",", "outExt", "=", "None", ",", "configObj", "=", "None", ",", "group", "=", "None", ",", "editpars", "=", "False", ",", "*", "*", "inputDict", ")", ":", "if", "input", "is", "not", "None", ":", "inputDict"...
Perform sky subtraction on input list of images Parameters ---------- input : str or list of str a python list of image filenames, or just a single filename configObj : configObject an instance of configObject inputDict : dict, optional an optional list of parameters specified by the user outExt : str The extension of the output image. If the output already exists then the input image is overwritten Notes ----- These are parameters that the configObj should contain by default, they can be altered on the fly using the inputDict Parameters that should be in configobj: ========== =================================================================== Name Definition ========== =================================================================== skymethod 'Sky computation method' skysub 'Perform sky subtraction?' skywidth 'Bin width of histogram for sampling sky statistics (in sigma)' skystat 'Sky correction statistics parameter' skylower 'Lower limit of usable data for sky (always in electrons)' skyupper 'Upper limit of usable data for sky (always in electrons)' skyclip 'Number of clipping iterations' skylsigma 'Lower side clipping factor (in sigma)' skyusigma 'Upper side clipping factor (in sigma)' skymask_cat 'Catalog file listing image masks' use_static 'Use static mask for skymatch computations?' sky_bits 'Integer mask bit values considered good pixels in DQ array' skyfile 'Name of file with user-computed sky values' skyuser 'KEYWORD indicating a sky subtraction value if done by user' in_memory 'Optimize for speed or for memory use' ========== =================================================================== The output from sky subtraction is a copy of the original input file where all the science data extensions have been sky subtracted.
[ "Perform", "sky", "subtraction", "on", "input", "list", "of", "images" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/sky.py#L43-L107
train
35,504
spacetelescope/drizzlepac
drizzlepac/sky.py
_skyUserFromFile
def _skyUserFromFile(imageObjList, skyFile, apply_sky=None): """ Apply sky value as read in from a user-supplied input file. """ skyKW="MDRIZSKY" #header keyword that contains the sky that's been subtracted # create dict of fname=sky pairs skyvals = {} if apply_sky is None: skyapplied = False # flag whether sky has already been applied to images else: skyapplied = apply_sky for line in open(skyFile): if apply_sky is None and line[0] == '#' and 'applied' in line: if '=' in line: linesep = '=' if ':' in line: linesep = ':' appliedstr = line.split(linesep)[1].strip() if appliedstr.lower() in ['yes','true','y','t']: skyapplied = True print('...Sky values already applied by user...') if not util.is_blank(line) and line[0] != '#': lspl = line.split() svals = [] for lvals in lspl[1:]: svals.append(float(lvals)) skyvals[lspl[0]] = svals # Apply user values to appropriate input images for imageSet in imageObjList: fname = imageSet._filename numchips=imageSet._numchips sciExt=imageSet.scienceExt if fname in skyvals: print(" ...updating MDRIZSKY with user-supplied value.") for chip in range(1,numchips+1,1): if len(skyvals[fname]) == 1: _skyValue = skyvals[fname][0] else: _skyValue = skyvals[fname][chip-1] chipext = '%s,%d'%(sciExt,chip) _updateKW(imageSet[chipext],fname,(sciExt,chip),skyKW,_skyValue) # Update internal record with subtracted sky value # # .computedSky: value to be applied by the # adrizzle/ablot steps. # .subtractedSky: value already (or will be by adrizzle/ablot) # subtracted from the image if skyapplied: imageSet[chipext].computedSky = None # used by adrizzle/ablot else: imageSet[chipext].computedSky = _skyValue imageSet[chipext].subtractedSky = _skyValue print("Setting ",skyKW,"=",_skyValue) else: print("*"*40) print("*") print("WARNING:") print(" .... NO user-supplied sky value found for ",fname) print(" .... Setting sky to a value of 0.0! ") print("*") print("*"*40)
python
def _skyUserFromFile(imageObjList, skyFile, apply_sky=None): """ Apply sky value as read in from a user-supplied input file. """ skyKW="MDRIZSKY" #header keyword that contains the sky that's been subtracted # create dict of fname=sky pairs skyvals = {} if apply_sky is None: skyapplied = False # flag whether sky has already been applied to images else: skyapplied = apply_sky for line in open(skyFile): if apply_sky is None and line[0] == '#' and 'applied' in line: if '=' in line: linesep = '=' if ':' in line: linesep = ':' appliedstr = line.split(linesep)[1].strip() if appliedstr.lower() in ['yes','true','y','t']: skyapplied = True print('...Sky values already applied by user...') if not util.is_blank(line) and line[0] != '#': lspl = line.split() svals = [] for lvals in lspl[1:]: svals.append(float(lvals)) skyvals[lspl[0]] = svals # Apply user values to appropriate input images for imageSet in imageObjList: fname = imageSet._filename numchips=imageSet._numchips sciExt=imageSet.scienceExt if fname in skyvals: print(" ...updating MDRIZSKY with user-supplied value.") for chip in range(1,numchips+1,1): if len(skyvals[fname]) == 1: _skyValue = skyvals[fname][0] else: _skyValue = skyvals[fname][chip-1] chipext = '%s,%d'%(sciExt,chip) _updateKW(imageSet[chipext],fname,(sciExt,chip),skyKW,_skyValue) # Update internal record with subtracted sky value # # .computedSky: value to be applied by the # adrizzle/ablot steps. # .subtractedSky: value already (or will be by adrizzle/ablot) # subtracted from the image if skyapplied: imageSet[chipext].computedSky = None # used by adrizzle/ablot else: imageSet[chipext].computedSky = _skyValue imageSet[chipext].subtractedSky = _skyValue print("Setting ",skyKW,"=",_skyValue) else: print("*"*40) print("*") print("WARNING:") print(" .... NO user-supplied sky value found for ",fname) print(" .... Setting sky to a value of 0.0! ") print("*") print("*"*40)
[ "def", "_skyUserFromFile", "(", "imageObjList", ",", "skyFile", ",", "apply_sky", "=", "None", ")", ":", "skyKW", "=", "\"MDRIZSKY\"", "#header keyword that contains the sky that's been subtracted", "# create dict of fname=sky pairs", "skyvals", "=", "{", "}", "if", "appl...
Apply sky value as read in from a user-supplied input file.
[ "Apply", "sky", "value", "as", "read", "in", "from", "a", "user", "-", "supplied", "input", "file", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/sky.py#L453-L518
train
35,505
spacetelescope/drizzlepac
drizzlepac/sky.py
_computeSky
def _computeSky(image, skypars, memmap=False): """ Compute the sky value for the data array passed to the function image is a fits object which contains the data and the header for one image extension skypars is passed in as paramDict """ #this object contains the returned values from the image stats routine _tmp = imagestats.ImageStats(image.data, fields = skypars['skystat'], lower = skypars['skylower'], upper = skypars['skyupper'], nclip = skypars['skyclip'], lsig = skypars['skylsigma'], usig = skypars['skyusigma'], binwidth = skypars['skywidth'] ) _skyValue = _extractSkyValue(_tmp,skypars['skystat'].lower()) log.info(" Computed sky value/pixel for %s: %s "% (image.rootname, _skyValue)) del _tmp return _skyValue
python
def _computeSky(image, skypars, memmap=False): """ Compute the sky value for the data array passed to the function image is a fits object which contains the data and the header for one image extension skypars is passed in as paramDict """ #this object contains the returned values from the image stats routine _tmp = imagestats.ImageStats(image.data, fields = skypars['skystat'], lower = skypars['skylower'], upper = skypars['skyupper'], nclip = skypars['skyclip'], lsig = skypars['skylsigma'], usig = skypars['skyusigma'], binwidth = skypars['skywidth'] ) _skyValue = _extractSkyValue(_tmp,skypars['skystat'].lower()) log.info(" Computed sky value/pixel for %s: %s "% (image.rootname, _skyValue)) del _tmp return _skyValue
[ "def", "_computeSky", "(", "image", ",", "skypars", ",", "memmap", "=", "False", ")", ":", "#this object contains the returned values from the image stats routine", "_tmp", "=", "imagestats", ".", "ImageStats", "(", "image", ".", "data", ",", "fields", "=", "skypars...
Compute the sky value for the data array passed to the function image is a fits object which contains the data and the header for one image extension skypars is passed in as paramDict
[ "Compute", "the", "sky", "value", "for", "the", "data", "array", "passed", "to", "the", "function", "image", "is", "a", "fits", "object", "which", "contains", "the", "data", "and", "the", "header", "for", "one", "image", "extension" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/sky.py#L699-L726
train
35,506
spacetelescope/drizzlepac
drizzlepac/sky.py
_subtractSky
def _subtractSky(image,skyValue,memmap=False): """ subtract the given sky value from each the data array that has been passed. image is a fits object that contains the data and header for one image extension """ try: np.subtract(image.data,skyValue,image.data) except IOError: print("Unable to perform sky subtraction on data array") raise IOError
python
def _subtractSky(image,skyValue,memmap=False): """ subtract the given sky value from each the data array that has been passed. image is a fits object that contains the data and header for one image extension """ try: np.subtract(image.data,skyValue,image.data) except IOError: print("Unable to perform sky subtraction on data array") raise IOError
[ "def", "_subtractSky", "(", "image", ",", "skyValue", ",", "memmap", "=", "False", ")", ":", "try", ":", "np", ".", "subtract", "(", "image", ".", "data", ",", "skyValue", ",", "image", ".", "data", ")", "except", "IOError", ":", "print", "(", "\"Una...
subtract the given sky value from each the data array that has been passed. image is a fits object that contains the data and header for one image extension
[ "subtract", "the", "given", "sky", "value", "from", "each", "the", "data", "array", "that", "has", "been", "passed", ".", "image", "is", "a", "fits", "object", "that", "contains", "the", "data", "and", "header", "for", "one", "image", "extension" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/sky.py#L740-L751
train
35,507
spacetelescope/drizzlepac
drizzlepac/sky.py
_updateKW
def _updateKW(image, filename, exten, skyKW, Value): """update the header with the kw,value""" # Update the value in memory image.header[skyKW] = Value # Now update the value on disk if isinstance(exten,tuple): strexten = '[%s,%s]'%(exten[0],str(exten[1])) else: strexten = '[%s]'%(exten) log.info('Updating keyword %s in %s' % (skyKW, filename + strexten)) fobj = fileutil.openImage(filename, mode='update', memmap=False) fobj[exten].header[skyKW] = (Value, 'Sky value computed by AstroDrizzle') fobj.close()
python
def _updateKW(image, filename, exten, skyKW, Value): """update the header with the kw,value""" # Update the value in memory image.header[skyKW] = Value # Now update the value on disk if isinstance(exten,tuple): strexten = '[%s,%s]'%(exten[0],str(exten[1])) else: strexten = '[%s]'%(exten) log.info('Updating keyword %s in %s' % (skyKW, filename + strexten)) fobj = fileutil.openImage(filename, mode='update', memmap=False) fobj[exten].header[skyKW] = (Value, 'Sky value computed by AstroDrizzle') fobj.close()
[ "def", "_updateKW", "(", "image", ",", "filename", ",", "exten", ",", "skyKW", ",", "Value", ")", ":", "# Update the value in memory", "image", ".", "header", "[", "skyKW", "]", "=", "Value", "# Now update the value on disk", "if", "isinstance", "(", "exten", ...
update the header with the kw,value
[ "update", "the", "header", "with", "the", "kw", "value" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/sky.py#L754-L767
train
35,508
spacetelescope/drizzlepac
drizzlepac/sky.py
_addDefaultSkyKW
def _addDefaultSkyKW(imageObjList): """Add MDRIZSKY keyword to "commanded" SCI headers of all input images, if that keyword does not already exist. """ skyKW = "MDRIZSKY" Value = 0.0 for imageSet in imageObjList: fname = imageSet._filename numchips=imageSet._numchips sciExt=imageSet.scienceExt fobj = fileutil.openImage(fname, mode='update', memmap=False) for chip in range(1,numchips+1,1): ext = (sciExt,chip) if not imageSet[ext].group_member: # skip over extensions not used in processing continue if skyKW not in fobj[ext].header: fobj[ext].header[skyKW] = (Value, 'Sky value computed by AstroDrizzle') log.info("MDRIZSKY keyword not found in the %s[%s,%d] header."%( fname,sciExt,chip)) log.info(" Adding MDRIZSKY to header with default value of 0.") fobj.close()
python
def _addDefaultSkyKW(imageObjList): """Add MDRIZSKY keyword to "commanded" SCI headers of all input images, if that keyword does not already exist. """ skyKW = "MDRIZSKY" Value = 0.0 for imageSet in imageObjList: fname = imageSet._filename numchips=imageSet._numchips sciExt=imageSet.scienceExt fobj = fileutil.openImage(fname, mode='update', memmap=False) for chip in range(1,numchips+1,1): ext = (sciExt,chip) if not imageSet[ext].group_member: # skip over extensions not used in processing continue if skyKW not in fobj[ext].header: fobj[ext].header[skyKW] = (Value, 'Sky value computed by AstroDrizzle') log.info("MDRIZSKY keyword not found in the %s[%s,%d] header."%( fname,sciExt,chip)) log.info(" Adding MDRIZSKY to header with default value of 0.") fobj.close()
[ "def", "_addDefaultSkyKW", "(", "imageObjList", ")", ":", "skyKW", "=", "\"MDRIZSKY\"", "Value", "=", "0.0", "for", "imageSet", "in", "imageObjList", ":", "fname", "=", "imageSet", ".", "_filename", "numchips", "=", "imageSet", ".", "_numchips", "sciExt", "=",...
Add MDRIZSKY keyword to "commanded" SCI headers of all input images, if that keyword does not already exist.
[ "Add", "MDRIZSKY", "keyword", "to", "commanded", "SCI", "headers", "of", "all", "input", "images", "if", "that", "keyword", "does", "not", "already", "exist", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/sky.py#L769-L790
train
35,509
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
create_astrometric_catalog
def create_astrometric_catalog(inputs, **pars): """Create an astrometric catalog that covers the inputs' field-of-view. Parameters ---------- input : str, list Filenames of images to be aligned to astrometric catalog catalog : str, optional Name of catalog to extract astrometric positions for sources in the input images' field-of-view. Default: GAIADR2. Options available are documented on the catalog web page. output : str, optional Filename to give to the astrometric catalog read in from the master catalog web service. If None, no file will be written out. gaia_only : bool, optional Specify whether or not to only use sources from GAIA in output catalog Default: False existing_wcs : ~stwcs.wcsutils.HSTWCS` existing WCS object specified by the user Notes ----- This function will point to astrometric catalog web service defined through the use of the ASTROMETRIC_CATALOG_URL environment variable. Returns ------- ref_table : ~.astropy.table.Table` Astropy Table object of the catalog """ # interpret input parameters catalog = pars.get("catalog", 'GAIADR2') output = pars.get("output", 'ref_cat.ecsv') gaia_only = pars.get("gaia_only", False) table_format = pars.get("table_format", 'ascii.ecsv') existing_wcs = pars.get("existing_wcs", None) inputs, _ = parseinput.parseinput(inputs) # start by creating a composite field-of-view for all inputs # This default output WCS will have the same plate-scale and orientation # as the first chip in the list, which for WFPC2 data means the PC. # Fortunately, for alignment, this doesn't matter since no resampling of # data will be performed if existing_wcs: outwcs = existing_wcs else: outwcs = build_reference_wcs(inputs) radius = compute_radius(outwcs) ra, dec = outwcs.wcs.crval # perform query for this field-of-view ref_dict = get_catalog(ra, dec, sr=radius, catalog=catalog) colnames = ('ra', 'dec', 'mag', 'objID', 'GaiaID') col_types = ('f8', 'f8', 'f4', 'U25', 'U25') ref_table = Table(names=colnames, dtype=col_types) # Add catalog name as meta data ref_table.meta['catalog'] = catalog ref_table.meta['gaia_only'] = gaia_only # rename coordinate columns to be consistent with tweakwcs ref_table.rename_column('ra', 'RA') ref_table.rename_column('dec', 'DEC') # extract just the columns we want... num_sources = 0 for source in ref_dict: if 'GAIAsourceID' in source: g = source['GAIAsourceID'] if gaia_only and g.strip() == '': continue else: g = "-1" # indicator for no source ID extracted r = float(source['ra']) d = float(source['dec']) m = -999.9 # float(source['mag']) o = source['objID'] num_sources += 1 ref_table.add_row((r, d, m, o, g)) # Write out table to a file, if specified if output: ref_table.write(output, format=table_format) log.info("Created catalog '{}' with {} sources".format(output, num_sources)) return ref_table
python
def create_astrometric_catalog(inputs, **pars): """Create an astrometric catalog that covers the inputs' field-of-view. Parameters ---------- input : str, list Filenames of images to be aligned to astrometric catalog catalog : str, optional Name of catalog to extract astrometric positions for sources in the input images' field-of-view. Default: GAIADR2. Options available are documented on the catalog web page. output : str, optional Filename to give to the astrometric catalog read in from the master catalog web service. If None, no file will be written out. gaia_only : bool, optional Specify whether or not to only use sources from GAIA in output catalog Default: False existing_wcs : ~stwcs.wcsutils.HSTWCS` existing WCS object specified by the user Notes ----- This function will point to astrometric catalog web service defined through the use of the ASTROMETRIC_CATALOG_URL environment variable. Returns ------- ref_table : ~.astropy.table.Table` Astropy Table object of the catalog """ # interpret input parameters catalog = pars.get("catalog", 'GAIADR2') output = pars.get("output", 'ref_cat.ecsv') gaia_only = pars.get("gaia_only", False) table_format = pars.get("table_format", 'ascii.ecsv') existing_wcs = pars.get("existing_wcs", None) inputs, _ = parseinput.parseinput(inputs) # start by creating a composite field-of-view for all inputs # This default output WCS will have the same plate-scale and orientation # as the first chip in the list, which for WFPC2 data means the PC. # Fortunately, for alignment, this doesn't matter since no resampling of # data will be performed if existing_wcs: outwcs = existing_wcs else: outwcs = build_reference_wcs(inputs) radius = compute_radius(outwcs) ra, dec = outwcs.wcs.crval # perform query for this field-of-view ref_dict = get_catalog(ra, dec, sr=radius, catalog=catalog) colnames = ('ra', 'dec', 'mag', 'objID', 'GaiaID') col_types = ('f8', 'f8', 'f4', 'U25', 'U25') ref_table = Table(names=colnames, dtype=col_types) # Add catalog name as meta data ref_table.meta['catalog'] = catalog ref_table.meta['gaia_only'] = gaia_only # rename coordinate columns to be consistent with tweakwcs ref_table.rename_column('ra', 'RA') ref_table.rename_column('dec', 'DEC') # extract just the columns we want... num_sources = 0 for source in ref_dict: if 'GAIAsourceID' in source: g = source['GAIAsourceID'] if gaia_only and g.strip() == '': continue else: g = "-1" # indicator for no source ID extracted r = float(source['ra']) d = float(source['dec']) m = -999.9 # float(source['mag']) o = source['objID'] num_sources += 1 ref_table.add_row((r, d, m, o, g)) # Write out table to a file, if specified if output: ref_table.write(output, format=table_format) log.info("Created catalog '{}' with {} sources".format(output, num_sources)) return ref_table
[ "def", "create_astrometric_catalog", "(", "inputs", ",", "*", "*", "pars", ")", ":", "# interpret input parameters", "catalog", "=", "pars", ".", "get", "(", "\"catalog\"", ",", "'GAIADR2'", ")", "output", "=", "pars", ".", "get", "(", "\"output\"", ",", "'r...
Create an astrometric catalog that covers the inputs' field-of-view. Parameters ---------- input : str, list Filenames of images to be aligned to astrometric catalog catalog : str, optional Name of catalog to extract astrometric positions for sources in the input images' field-of-view. Default: GAIADR2. Options available are documented on the catalog web page. output : str, optional Filename to give to the astrometric catalog read in from the master catalog web service. If None, no file will be written out. gaia_only : bool, optional Specify whether or not to only use sources from GAIA in output catalog Default: False existing_wcs : ~stwcs.wcsutils.HSTWCS` existing WCS object specified by the user Notes ----- This function will point to astrometric catalog web service defined through the use of the ASTROMETRIC_CATALOG_URL environment variable. Returns ------- ref_table : ~.astropy.table.Table` Astropy Table object of the catalog
[ "Create", "an", "astrometric", "catalog", "that", "covers", "the", "inputs", "field", "-", "of", "-", "view", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L94-L184
train
35,510
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
build_reference_wcs
def build_reference_wcs(inputs, sciname='sci'): """Create the reference WCS based on all the inputs for a field""" # start by creating a composite field-of-view for all inputs wcslist = [] for img in inputs: nsci = countExtn(img) for num in range(nsci): extname = (sciname, num + 1) if sciname == 'sci': extwcs = wcsutil.HSTWCS(img, ext=extname) else: # Working with HDRLET as input and do the best we can... extwcs = read_hlet_wcs(img, ext=extname) wcslist.append(extwcs) # This default output WCS will have the same plate-scale and orientation # as the first chip in the list, which for WFPC2 data means the PC. # Fortunately, for alignment, this doesn't matter since no resampling of # data will be performed outwcs = utils.output_wcs(wcslist) return outwcs
python
def build_reference_wcs(inputs, sciname='sci'): """Create the reference WCS based on all the inputs for a field""" # start by creating a composite field-of-view for all inputs wcslist = [] for img in inputs: nsci = countExtn(img) for num in range(nsci): extname = (sciname, num + 1) if sciname == 'sci': extwcs = wcsutil.HSTWCS(img, ext=extname) else: # Working with HDRLET as input and do the best we can... extwcs = read_hlet_wcs(img, ext=extname) wcslist.append(extwcs) # This default output WCS will have the same plate-scale and orientation # as the first chip in the list, which for WFPC2 data means the PC. # Fortunately, for alignment, this doesn't matter since no resampling of # data will be performed outwcs = utils.output_wcs(wcslist) return outwcs
[ "def", "build_reference_wcs", "(", "inputs", ",", "sciname", "=", "'sci'", ")", ":", "# start by creating a composite field-of-view for all inputs", "wcslist", "=", "[", "]", "for", "img", "in", "inputs", ":", "nsci", "=", "countExtn", "(", "img", ")", "for", "n...
Create the reference WCS based on all the inputs for a field
[ "Create", "the", "reference", "WCS", "based", "on", "all", "the", "inputs", "for", "a", "field" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L187-L209
train
35,511
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
get_catalog
def get_catalog(ra, dec, sr=0.1, fmt='CSV', catalog='GSC241'): """ Extract catalog from VO web service. Parameters ---------- ra : float Right Ascension (RA) of center of field-of-view (in decimal degrees) dec : float Declination (Dec) of center of field-of-view (in decimal degrees) sr : float, optional Search radius (in decimal degrees) from field-of-view center to use for sources from catalog. Default: 0.1 degrees fmt : str, optional Format of output catalog to be returned. Options are determined by web-service, and currently include (Default: CSV): VOTABLE(default) | HTML | KML | CSV | TSV | JSON | TEXT catalog : str, optional Name of catalog to query, as defined by web-service. Default: 'GSC241' Returns ------- csv : CSV object CSV object of returned sources with all columns as provided by catalog """ serviceType = 'vo/CatalogSearch.aspx' spec_str = 'RA={}&DEC={}&SR={}&FORMAT={}&CAT={}&MINDET=5' headers = {'Content-Type': 'text/csv'} spec = spec_str.format(ra, dec, sr, fmt, catalog) serviceUrl = '{}/{}?{}'.format(SERVICELOCATION, serviceType, spec) rawcat = requests.get(serviceUrl, headers=headers) r_contents = rawcat.content.decode() # convert from bytes to a String rstr = r_contents.split('\r\n') # remove initial line describing the number of sources returned # CRITICAL to proper interpretation of CSV data del rstr[0] r_csv = csv.DictReader(rstr) return r_csv
python
def get_catalog(ra, dec, sr=0.1, fmt='CSV', catalog='GSC241'): """ Extract catalog from VO web service. Parameters ---------- ra : float Right Ascension (RA) of center of field-of-view (in decimal degrees) dec : float Declination (Dec) of center of field-of-view (in decimal degrees) sr : float, optional Search radius (in decimal degrees) from field-of-view center to use for sources from catalog. Default: 0.1 degrees fmt : str, optional Format of output catalog to be returned. Options are determined by web-service, and currently include (Default: CSV): VOTABLE(default) | HTML | KML | CSV | TSV | JSON | TEXT catalog : str, optional Name of catalog to query, as defined by web-service. Default: 'GSC241' Returns ------- csv : CSV object CSV object of returned sources with all columns as provided by catalog """ serviceType = 'vo/CatalogSearch.aspx' spec_str = 'RA={}&DEC={}&SR={}&FORMAT={}&CAT={}&MINDET=5' headers = {'Content-Type': 'text/csv'} spec = spec_str.format(ra, dec, sr, fmt, catalog) serviceUrl = '{}/{}?{}'.format(SERVICELOCATION, serviceType, spec) rawcat = requests.get(serviceUrl, headers=headers) r_contents = rawcat.content.decode() # convert from bytes to a String rstr = r_contents.split('\r\n') # remove initial line describing the number of sources returned # CRITICAL to proper interpretation of CSV data del rstr[0] r_csv = csv.DictReader(rstr) return r_csv
[ "def", "get_catalog", "(", "ra", ",", "dec", ",", "sr", "=", "0.1", ",", "fmt", "=", "'CSV'", ",", "catalog", "=", "'GSC241'", ")", ":", "serviceType", "=", "'vo/CatalogSearch.aspx'", "spec_str", "=", "'RA={}&DEC={}&SR={}&FORMAT={}&CAT={}&MINDET=5'", "headers", ...
Extract catalog from VO web service. Parameters ---------- ra : float Right Ascension (RA) of center of field-of-view (in decimal degrees) dec : float Declination (Dec) of center of field-of-view (in decimal degrees) sr : float, optional Search radius (in decimal degrees) from field-of-view center to use for sources from catalog. Default: 0.1 degrees fmt : str, optional Format of output catalog to be returned. Options are determined by web-service, and currently include (Default: CSV): VOTABLE(default) | HTML | KML | CSV | TSV | JSON | TEXT catalog : str, optional Name of catalog to query, as defined by web-service. Default: 'GSC241' Returns ------- csv : CSV object CSV object of returned sources with all columns as provided by catalog
[ "Extract", "catalog", "from", "VO", "web", "service", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L212-L255
train
35,512
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
compute_radius
def compute_radius(wcs): """Compute the radius from the center to the furthest edge of the WCS.""" ra, dec = wcs.wcs.crval img_center = SkyCoord(ra=ra * u.degree, dec=dec * u.degree) wcs_foot = wcs.calc_footprint() img_corners = SkyCoord(ra=wcs_foot[:, 0] * u.degree, dec=wcs_foot[:, 1] * u.degree) radius = img_center.separation(img_corners).max().value return radius
python
def compute_radius(wcs): """Compute the radius from the center to the furthest edge of the WCS.""" ra, dec = wcs.wcs.crval img_center = SkyCoord(ra=ra * u.degree, dec=dec * u.degree) wcs_foot = wcs.calc_footprint() img_corners = SkyCoord(ra=wcs_foot[:, 0] * u.degree, dec=wcs_foot[:, 1] * u.degree) radius = img_center.separation(img_corners).max().value return radius
[ "def", "compute_radius", "(", "wcs", ")", ":", "ra", ",", "dec", "=", "wcs", ".", "wcs", ".", "crval", "img_center", "=", "SkyCoord", "(", "ra", "=", "ra", "*", "u", ".", "degree", ",", "dec", "=", "dec", "*", "u", ".", "degree", ")", "wcs_foot",...
Compute the radius from the center to the furthest edge of the WCS.
[ "Compute", "the", "radius", "from", "the", "center", "to", "the", "furthest", "edge", "of", "the", "WCS", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L258-L268
train
35,513
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
find_gsc_offset
def find_gsc_offset(image, input_catalog='GSC1', output_catalog='GAIA'): """Find the GSC to GAIA offset based on guide star coordinates Parameters ---------- image : str Filename of image to be processed. Returns ------- delta_ra, delta_dec : tuple of floats Offset in decimal degrees of image based on correction to guide star coordinates relative to GAIA. """ serviceType = "GSCConvert/GSCconvert.aspx" spec_str = "TRANSFORM={}-{}&IPPPSSOOT={}" if 'rootname' in pf.getheader(image): ippssoot = pf.getval(image, 'rootname').upper() else: ippssoot = fu.buildNewRootname(image).upper() spec = spec_str.format(input_catalog, output_catalog, ippssoot) serviceUrl = "{}/{}?{}".format(SERVICELOCATION, serviceType, spec) rawcat = requests.get(serviceUrl) if not rawcat.ok: log.info("Problem accessing service with:\n{{}".format(serviceUrl)) raise ValueError delta_ra = delta_dec = None tree = BytesIO(rawcat.content) for _, element in etree.iterparse(tree): if element.tag == 'deltaRA': delta_ra = float(element.text) elif element.tag == 'deltaDEC': delta_dec = float(element.text) return delta_ra, delta_dec
python
def find_gsc_offset(image, input_catalog='GSC1', output_catalog='GAIA'): """Find the GSC to GAIA offset based on guide star coordinates Parameters ---------- image : str Filename of image to be processed. Returns ------- delta_ra, delta_dec : tuple of floats Offset in decimal degrees of image based on correction to guide star coordinates relative to GAIA. """ serviceType = "GSCConvert/GSCconvert.aspx" spec_str = "TRANSFORM={}-{}&IPPPSSOOT={}" if 'rootname' in pf.getheader(image): ippssoot = pf.getval(image, 'rootname').upper() else: ippssoot = fu.buildNewRootname(image).upper() spec = spec_str.format(input_catalog, output_catalog, ippssoot) serviceUrl = "{}/{}?{}".format(SERVICELOCATION, serviceType, spec) rawcat = requests.get(serviceUrl) if not rawcat.ok: log.info("Problem accessing service with:\n{{}".format(serviceUrl)) raise ValueError delta_ra = delta_dec = None tree = BytesIO(rawcat.content) for _, element in etree.iterparse(tree): if element.tag == 'deltaRA': delta_ra = float(element.text) elif element.tag == 'deltaDEC': delta_dec = float(element.text) return delta_ra, delta_dec
[ "def", "find_gsc_offset", "(", "image", ",", "input_catalog", "=", "'GSC1'", ",", "output_catalog", "=", "'GAIA'", ")", ":", "serviceType", "=", "\"GSCConvert/GSCconvert.aspx\"", "spec_str", "=", "\"TRANSFORM={}-{}&IPPPSSOOT={}\"", "if", "'rootname'", "in", "pf", ".",...
Find the GSC to GAIA offset based on guide star coordinates Parameters ---------- image : str Filename of image to be processed. Returns ------- delta_ra, delta_dec : tuple of floats Offset in decimal degrees of image based on correction to guide star coordinates relative to GAIA.
[ "Find", "the", "GSC", "to", "GAIA", "offset", "based", "on", "guide", "star", "coordinates" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L271-L308
train
35,514
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
generate_source_catalog
def generate_source_catalog(image, **kwargs): """ Build source catalogs for each chip using photutils. The catalog returned by this function includes sources found in all chips of the input image with the positions translated to the coordinate frame defined by the reference WCS `refwcs`. The sources will be - identified using photutils segmentation-based source finding code - ignore any input pixel which has been flagged as 'bad' in the DQ array, should a DQ array be found in the input HDUList. - classified as probable cosmic-rays (if enabled) using central_moments properties of each source, with these sources being removed from the catalog. Parameters ---------- image : `~astropy.io.fits.HDUList` Input image as an astropy.io.fits HDUList. dqname : str EXTNAME for the DQ array, if present, in the input image HDUList. output : bool Specify whether or not to write out a separate catalog file for all the sources found in each chip. Default: None (False) threshold : float, optional This parameter controls the threshold used for identifying sources in the image relative to the background RMS. If None, compute a default value of (background+3*rms(background)). If threshold < 0.0, use absolute value as scaling factor for default value. fwhm : float, optional FWHM (in pixels) of the expected sources from the image, comparable to the 'conv_width' parameter from 'tweakreg'. Objects with FWHM closest to this value will be identified as sources in the catalog. Returns ------- source_cats : dict Dict of astropy Tables identified by chip number with each table containing sources from image extension ``('sci', chip)``. """ if not isinstance(image, pf.HDUList): raise ValueError("Input {} not fits.HDUList object".format(image)) dqname = kwargs.get('dqname', 'DQ') output = kwargs.get('output', None) # Build source catalog for entire image source_cats = {} numSci = countExtn(image, extname='SCI') for chip in range(numSci): chip += 1 # find sources in image if output: rootname = image[0].header['rootname'] outroot = '{}_sci{}_src'.format(rootname, chip) kwargs['output'] = outroot imgarr = image['sci', chip].data # apply any DQ array, if available dqmask = None if image.index_of(dqname): dqarr = image[dqname, chip].data # "grow out" regions in DQ mask flagged as saturated by several # pixels in every direction to prevent the # source match algorithm from trying to match multiple sources # from one image to a single source in the # other or vice-versa. # Create temp DQ mask containing all pixels flagged with any value EXCEPT 256 non_sat_mask = bitfield_to_boolean_mask(dqarr, ignore_flags=256) # Create temp DQ mask containing saturated pixels ONLY sat_mask = bitfield_to_boolean_mask(dqarr, ignore_flags=~256) # Grow out saturated pixels by a few pixels in every direction grown_sat_mask = ndimage.binary_dilation(sat_mask, iterations=5) # combine the two temporary DQ masks into a single composite DQ mask. dqmask = np.bitwise_or(non_sat_mask, grown_sat_mask) # dqmask = bitfield_to_boolean_mask(dqarr, good_mask_value=False) # TODO: <---Remove this old no-sat bit grow line once this # thing works seg_tab, segmap = extract_sources(imgarr, dqmask=dqmask, **kwargs) seg_tab_phot = seg_tab source_cats[chip] = seg_tab_phot return source_cats
python
def generate_source_catalog(image, **kwargs): """ Build source catalogs for each chip using photutils. The catalog returned by this function includes sources found in all chips of the input image with the positions translated to the coordinate frame defined by the reference WCS `refwcs`. The sources will be - identified using photutils segmentation-based source finding code - ignore any input pixel which has been flagged as 'bad' in the DQ array, should a DQ array be found in the input HDUList. - classified as probable cosmic-rays (if enabled) using central_moments properties of each source, with these sources being removed from the catalog. Parameters ---------- image : `~astropy.io.fits.HDUList` Input image as an astropy.io.fits HDUList. dqname : str EXTNAME for the DQ array, if present, in the input image HDUList. output : bool Specify whether or not to write out a separate catalog file for all the sources found in each chip. Default: None (False) threshold : float, optional This parameter controls the threshold used for identifying sources in the image relative to the background RMS. If None, compute a default value of (background+3*rms(background)). If threshold < 0.0, use absolute value as scaling factor for default value. fwhm : float, optional FWHM (in pixels) of the expected sources from the image, comparable to the 'conv_width' parameter from 'tweakreg'. Objects with FWHM closest to this value will be identified as sources in the catalog. Returns ------- source_cats : dict Dict of astropy Tables identified by chip number with each table containing sources from image extension ``('sci', chip)``. """ if not isinstance(image, pf.HDUList): raise ValueError("Input {} not fits.HDUList object".format(image)) dqname = kwargs.get('dqname', 'DQ') output = kwargs.get('output', None) # Build source catalog for entire image source_cats = {} numSci = countExtn(image, extname='SCI') for chip in range(numSci): chip += 1 # find sources in image if output: rootname = image[0].header['rootname'] outroot = '{}_sci{}_src'.format(rootname, chip) kwargs['output'] = outroot imgarr = image['sci', chip].data # apply any DQ array, if available dqmask = None if image.index_of(dqname): dqarr = image[dqname, chip].data # "grow out" regions in DQ mask flagged as saturated by several # pixels in every direction to prevent the # source match algorithm from trying to match multiple sources # from one image to a single source in the # other or vice-versa. # Create temp DQ mask containing all pixels flagged with any value EXCEPT 256 non_sat_mask = bitfield_to_boolean_mask(dqarr, ignore_flags=256) # Create temp DQ mask containing saturated pixels ONLY sat_mask = bitfield_to_boolean_mask(dqarr, ignore_flags=~256) # Grow out saturated pixels by a few pixels in every direction grown_sat_mask = ndimage.binary_dilation(sat_mask, iterations=5) # combine the two temporary DQ masks into a single composite DQ mask. dqmask = np.bitwise_or(non_sat_mask, grown_sat_mask) # dqmask = bitfield_to_boolean_mask(dqarr, good_mask_value=False) # TODO: <---Remove this old no-sat bit grow line once this # thing works seg_tab, segmap = extract_sources(imgarr, dqmask=dqmask, **kwargs) seg_tab_phot = seg_tab source_cats[chip] = seg_tab_phot return source_cats
[ "def", "generate_source_catalog", "(", "image", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "image", ",", "pf", ".", "HDUList", ")", ":", "raise", "ValueError", "(", "\"Input {} not fits.HDUList object\"", ".", "format", "(", "image", ...
Build source catalogs for each chip using photutils. The catalog returned by this function includes sources found in all chips of the input image with the positions translated to the coordinate frame defined by the reference WCS `refwcs`. The sources will be - identified using photutils segmentation-based source finding code - ignore any input pixel which has been flagged as 'bad' in the DQ array, should a DQ array be found in the input HDUList. - classified as probable cosmic-rays (if enabled) using central_moments properties of each source, with these sources being removed from the catalog. Parameters ---------- image : `~astropy.io.fits.HDUList` Input image as an astropy.io.fits HDUList. dqname : str EXTNAME for the DQ array, if present, in the input image HDUList. output : bool Specify whether or not to write out a separate catalog file for all the sources found in each chip. Default: None (False) threshold : float, optional This parameter controls the threshold used for identifying sources in the image relative to the background RMS. If None, compute a default value of (background+3*rms(background)). If threshold < 0.0, use absolute value as scaling factor for default value. fwhm : float, optional FWHM (in pixels) of the expected sources from the image, comparable to the 'conv_width' parameter from 'tweakreg'. Objects with FWHM closest to this value will be identified as sources in the catalog. Returns ------- source_cats : dict Dict of astropy Tables identified by chip number with each table containing sources from image extension ``('sci', chip)``.
[ "Build", "source", "catalogs", "for", "each", "chip", "using", "photutils", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L554-L645
train
35,515
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
generate_sky_catalog
def generate_sky_catalog(image, refwcs, **kwargs): """Build source catalog from input image using photutils. This script borrows heavily from build_source_catalog. The catalog returned by this function includes sources found in all chips of the input image with the positions translated to the coordinate frame defined by the reference WCS `refwcs`. The sources will be - identified using photutils segmentation-based source finding code - ignore any input pixel which has been flagged as 'bad' in the DQ array, should a DQ array be found in the input HDUList. - classified as probable cosmic-rays (if enabled) using central_moments properties of each source, with these sources being removed from the catalog. Parameters ---------- image : ~astropy.io.fits.HDUList` Input image. refwcs : `~stwcs.wcsutils.HSTWCS` Definition of the reference frame WCS. dqname : str EXTNAME for the DQ array, if present, in the input image. output : bool Specify whether or not to write out a separate catalog file for all the sources found in each chip. Default: None (False) threshold : float, optional This parameter controls the S/N threshold used for identifying sources in the image relative to the background RMS in much the same way that the 'threshold' parameter in 'tweakreg' works. fwhm : float, optional FWHM (in pixels) of the expected sources from the image, comparable to the 'conv_width' parameter from 'tweakreg'. Objects with FWHM closest to this value will be identified as sources in the catalog. Returns -------- master_cat : `~astropy.table.Table` Source catalog for all 'valid' sources identified from all chips of the input image with positions translated to the reference WCS coordinate frame. """ # Extract source catalogs for each chip source_cats = generate_source_catalog(image, **kwargs) # Build source catalog for entire image master_cat = None numSci = countExtn(image, extname='SCI') # if no refwcs specified, build one now... if refwcs is None: refwcs = build_reference_wcs([image]) for chip in range(numSci): chip += 1 # work with sources identified from this specific chip seg_tab_phot = source_cats[chip] if seg_tab_phot is None: continue # Convert pixel coordinates from this chip to sky coordinates chip_wcs = wcsutil.HSTWCS(image, ext=('sci', chip)) seg_ra, seg_dec = chip_wcs.all_pix2world(seg_tab_phot['xcentroid'], seg_tab_phot['ycentroid'], 1) # Convert sky positions to pixel positions in the reference WCS frame seg_xy_out = refwcs.all_world2pix(seg_ra, seg_dec, 1) seg_tab_phot['xcentroid'] = seg_xy_out[0] seg_tab_phot['ycentroid'] = seg_xy_out[1] if master_cat is None: master_cat = seg_tab_phot else: master_cat = vstack([master_cat, seg_tab_phot]) return master_cat
python
def generate_sky_catalog(image, refwcs, **kwargs): """Build source catalog from input image using photutils. This script borrows heavily from build_source_catalog. The catalog returned by this function includes sources found in all chips of the input image with the positions translated to the coordinate frame defined by the reference WCS `refwcs`. The sources will be - identified using photutils segmentation-based source finding code - ignore any input pixel which has been flagged as 'bad' in the DQ array, should a DQ array be found in the input HDUList. - classified as probable cosmic-rays (if enabled) using central_moments properties of each source, with these sources being removed from the catalog. Parameters ---------- image : ~astropy.io.fits.HDUList` Input image. refwcs : `~stwcs.wcsutils.HSTWCS` Definition of the reference frame WCS. dqname : str EXTNAME for the DQ array, if present, in the input image. output : bool Specify whether or not to write out a separate catalog file for all the sources found in each chip. Default: None (False) threshold : float, optional This parameter controls the S/N threshold used for identifying sources in the image relative to the background RMS in much the same way that the 'threshold' parameter in 'tweakreg' works. fwhm : float, optional FWHM (in pixels) of the expected sources from the image, comparable to the 'conv_width' parameter from 'tweakreg'. Objects with FWHM closest to this value will be identified as sources in the catalog. Returns -------- master_cat : `~astropy.table.Table` Source catalog for all 'valid' sources identified from all chips of the input image with positions translated to the reference WCS coordinate frame. """ # Extract source catalogs for each chip source_cats = generate_source_catalog(image, **kwargs) # Build source catalog for entire image master_cat = None numSci = countExtn(image, extname='SCI') # if no refwcs specified, build one now... if refwcs is None: refwcs = build_reference_wcs([image]) for chip in range(numSci): chip += 1 # work with sources identified from this specific chip seg_tab_phot = source_cats[chip] if seg_tab_phot is None: continue # Convert pixel coordinates from this chip to sky coordinates chip_wcs = wcsutil.HSTWCS(image, ext=('sci', chip)) seg_ra, seg_dec = chip_wcs.all_pix2world(seg_tab_phot['xcentroid'], seg_tab_phot['ycentroid'], 1) # Convert sky positions to pixel positions in the reference WCS frame seg_xy_out = refwcs.all_world2pix(seg_ra, seg_dec, 1) seg_tab_phot['xcentroid'] = seg_xy_out[0] seg_tab_phot['ycentroid'] = seg_xy_out[1] if master_cat is None: master_cat = seg_tab_phot else: master_cat = vstack([master_cat, seg_tab_phot]) return master_cat
[ "def", "generate_sky_catalog", "(", "image", ",", "refwcs", ",", "*", "*", "kwargs", ")", ":", "# Extract source catalogs for each chip", "source_cats", "=", "generate_source_catalog", "(", "image", ",", "*", "*", "kwargs", ")", "# Build source catalog for entire image"...
Build source catalog from input image using photutils. This script borrows heavily from build_source_catalog. The catalog returned by this function includes sources found in all chips of the input image with the positions translated to the coordinate frame defined by the reference WCS `refwcs`. The sources will be - identified using photutils segmentation-based source finding code - ignore any input pixel which has been flagged as 'bad' in the DQ array, should a DQ array be found in the input HDUList. - classified as probable cosmic-rays (if enabled) using central_moments properties of each source, with these sources being removed from the catalog. Parameters ---------- image : ~astropy.io.fits.HDUList` Input image. refwcs : `~stwcs.wcsutils.HSTWCS` Definition of the reference frame WCS. dqname : str EXTNAME for the DQ array, if present, in the input image. output : bool Specify whether or not to write out a separate catalog file for all the sources found in each chip. Default: None (False) threshold : float, optional This parameter controls the S/N threshold used for identifying sources in the image relative to the background RMS in much the same way that the 'threshold' parameter in 'tweakreg' works. fwhm : float, optional FWHM (in pixels) of the expected sources from the image, comparable to the 'conv_width' parameter from 'tweakreg'. Objects with FWHM closest to this value will be identified as sources in the catalog. Returns -------- master_cat : `~astropy.table.Table` Source catalog for all 'valid' sources identified from all chips of the input image with positions translated to the reference WCS coordinate frame.
[ "Build", "source", "catalog", "from", "input", "image", "using", "photutils", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L648-L723
train
35,516
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
compute_photometry
def compute_photometry(catalog, photmode): """ Compute magnitudes for sources from catalog based on observations photmode. Parameters ---------- catalog : `~astropy.table.Table` Astropy Table with 'source_sum' column for the measured flux for each source. photmode : str Specification of the observation filter configuration used for the exposure as reported by the 'PHOTMODE' keyword from the PRIMARY header. Returns ------- phot_cat : `~astropy.table.Table` Astropy Table object of input source catalog with added column for VEGAMAG photometry (in magnitudes). """ # Determine VEGAMAG zero-point using pysynphot for this photmode photmode = photmode.replace(' ', ', ') vega = S.FileSpectrum(VEGASPEC) bp = S.ObsBandpass(photmode) vegauvis = S.Observation(vega, bp) vegazpt = 2.5 * np.log10(vegauvis.countrate()) # Use zero-point to convert flux values from catalog into magnitudes # source_phot = vegazpt - 2.5*np.log10(catalog['source_sum']) source_phot = vegazpt - 2.5 * np.log10(catalog['flux']) source_phot.name = 'vegamag' # Now add this new column to the catalog table catalog.add_column(source_phot) return catalog
python
def compute_photometry(catalog, photmode): """ Compute magnitudes for sources from catalog based on observations photmode. Parameters ---------- catalog : `~astropy.table.Table` Astropy Table with 'source_sum' column for the measured flux for each source. photmode : str Specification of the observation filter configuration used for the exposure as reported by the 'PHOTMODE' keyword from the PRIMARY header. Returns ------- phot_cat : `~astropy.table.Table` Astropy Table object of input source catalog with added column for VEGAMAG photometry (in magnitudes). """ # Determine VEGAMAG zero-point using pysynphot for this photmode photmode = photmode.replace(' ', ', ') vega = S.FileSpectrum(VEGASPEC) bp = S.ObsBandpass(photmode) vegauvis = S.Observation(vega, bp) vegazpt = 2.5 * np.log10(vegauvis.countrate()) # Use zero-point to convert flux values from catalog into magnitudes # source_phot = vegazpt - 2.5*np.log10(catalog['source_sum']) source_phot = vegazpt - 2.5 * np.log10(catalog['flux']) source_phot.name = 'vegamag' # Now add this new column to the catalog table catalog.add_column(source_phot) return catalog
[ "def", "compute_photometry", "(", "catalog", ",", "photmode", ")", ":", "# Determine VEGAMAG zero-point using pysynphot for this photmode", "photmode", "=", "photmode", ".", "replace", "(", "' '", ",", "', '", ")", "vega", "=", "S", ".", "FileSpectrum", "(", "VEGASP...
Compute magnitudes for sources from catalog based on observations photmode. Parameters ---------- catalog : `~astropy.table.Table` Astropy Table with 'source_sum' column for the measured flux for each source. photmode : str Specification of the observation filter configuration used for the exposure as reported by the 'PHOTMODE' keyword from the PRIMARY header. Returns ------- phot_cat : `~astropy.table.Table` Astropy Table object of input source catalog with added column for VEGAMAG photometry (in magnitudes).
[ "Compute", "magnitudes", "for", "sources", "from", "catalog", "based", "on", "observations", "photmode", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L726-L758
train
35,517
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
filter_catalog
def filter_catalog(catalog, **kwargs): """ Create a new catalog selected from input based on photometry. Parameters ---------- bright_limit : float Fraction of catalog based on brightness that should be retained. Value of 1.00 means full catalog. max_bright : int Maximum number of sources to keep regardless of `bright_limit`. min_bright : int Minimum number of sources to keep regardless of `bright_limit`. colname : str Name of column to use for selection/sorting. Returns ------- new_catalog : `~astropy.table.Table` New table which only has the sources that meet the selection criteria. """ # interpret input pars bright_limit = kwargs.get('bright_limit', 1.00) max_bright = kwargs.get('max_bright', None) min_bright = kwargs.get('min_bright', 20) colname = kwargs.get('colname', 'vegamag') # sort by magnitude phot_column = catalog[colname] num_sources = len(phot_column) sort_indx = np.argsort(phot_column) if max_bright is None: max_bright = num_sources # apply limits, insuring no more than full catalog gets selected limit_num = max(int(num_sources * bright_limit), min_bright) limit_num = min(max_bright, limit_num, num_sources) # Extract sources identified by selection new_catalog = catalog[sort_indx[:limit_num]] return new_catalog
python
def filter_catalog(catalog, **kwargs): """ Create a new catalog selected from input based on photometry. Parameters ---------- bright_limit : float Fraction of catalog based on brightness that should be retained. Value of 1.00 means full catalog. max_bright : int Maximum number of sources to keep regardless of `bright_limit`. min_bright : int Minimum number of sources to keep regardless of `bright_limit`. colname : str Name of column to use for selection/sorting. Returns ------- new_catalog : `~astropy.table.Table` New table which only has the sources that meet the selection criteria. """ # interpret input pars bright_limit = kwargs.get('bright_limit', 1.00) max_bright = kwargs.get('max_bright', None) min_bright = kwargs.get('min_bright', 20) colname = kwargs.get('colname', 'vegamag') # sort by magnitude phot_column = catalog[colname] num_sources = len(phot_column) sort_indx = np.argsort(phot_column) if max_bright is None: max_bright = num_sources # apply limits, insuring no more than full catalog gets selected limit_num = max(int(num_sources * bright_limit), min_bright) limit_num = min(max_bright, limit_num, num_sources) # Extract sources identified by selection new_catalog = catalog[sort_indx[:limit_num]] return new_catalog
[ "def", "filter_catalog", "(", "catalog", ",", "*", "*", "kwargs", ")", ":", "# interpret input pars", "bright_limit", "=", "kwargs", ".", "get", "(", "'bright_limit'", ",", "1.00", ")", "max_bright", "=", "kwargs", ".", "get", "(", "'max_bright'", ",", "None...
Create a new catalog selected from input based on photometry. Parameters ---------- bright_limit : float Fraction of catalog based on brightness that should be retained. Value of 1.00 means full catalog. max_bright : int Maximum number of sources to keep regardless of `bright_limit`. min_bright : int Minimum number of sources to keep regardless of `bright_limit`. colname : str Name of column to use for selection/sorting. Returns ------- new_catalog : `~astropy.table.Table` New table which only has the sources that meet the selection criteria.
[ "Create", "a", "new", "catalog", "selected", "from", "input", "based", "on", "photometry", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L761-L804
train
35,518
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
build_self_reference
def build_self_reference(filename, clean_wcs=False): """ This function creates a reference, undistorted WCS that can be used to apply a correction to the WCS of the input file. Parameters ---------- filename : str Filename of image which will be corrected, and which will form the basis of the undistorted WCS. clean_wcs : bool Specify whether or not to return the WCS object without any distortion information, or any history of the original input image. This converts the output from `utils.output_wcs()` into a pristine `~stwcs.wcsutils.HSTWCS` object. Returns ------- customwcs : `stwcs.wcsutils.HSTWCS` HSTWCS object which contains the undistorted WCS representing the entire field-of-view for the input image. Examples -------- This function can be used with the following syntax to apply a shift/rot/scale change to the same image: >>> import buildref >>> from drizzlepac import updatehdr >>> filename = "jce501erq_flc.fits" >>> wcslin = buildref.build_self_reference(filename) >>> updatehdr.updatewcs_with_shift(filename, wcslin, xsh=49.5694, ... ysh=19.2203, rot = 359.998, scale = 0.9999964) """ if 'sipwcs' in filename: sciname = 'sipwcs' else: sciname = 'sci' wcslin = build_reference_wcs([filename], sciname=sciname) if clean_wcs: wcsbase = wcslin.wcs customwcs = build_hstwcs(wcsbase.crval[0], wcsbase.crval[1], wcsbase.crpix[0], wcsbase.crpix[1], wcslin._naxis1, wcslin._naxis2, wcslin.pscale, wcslin.orientat) else: customwcs = wcslin return customwcs
python
def build_self_reference(filename, clean_wcs=False): """ This function creates a reference, undistorted WCS that can be used to apply a correction to the WCS of the input file. Parameters ---------- filename : str Filename of image which will be corrected, and which will form the basis of the undistorted WCS. clean_wcs : bool Specify whether or not to return the WCS object without any distortion information, or any history of the original input image. This converts the output from `utils.output_wcs()` into a pristine `~stwcs.wcsutils.HSTWCS` object. Returns ------- customwcs : `stwcs.wcsutils.HSTWCS` HSTWCS object which contains the undistorted WCS representing the entire field-of-view for the input image. Examples -------- This function can be used with the following syntax to apply a shift/rot/scale change to the same image: >>> import buildref >>> from drizzlepac import updatehdr >>> filename = "jce501erq_flc.fits" >>> wcslin = buildref.build_self_reference(filename) >>> updatehdr.updatewcs_with_shift(filename, wcslin, xsh=49.5694, ... ysh=19.2203, rot = 359.998, scale = 0.9999964) """ if 'sipwcs' in filename: sciname = 'sipwcs' else: sciname = 'sci' wcslin = build_reference_wcs([filename], sciname=sciname) if clean_wcs: wcsbase = wcslin.wcs customwcs = build_hstwcs(wcsbase.crval[0], wcsbase.crval[1], wcsbase.crpix[0], wcsbase.crpix[1], wcslin._naxis1, wcslin._naxis2, wcslin.pscale, wcslin.orientat) else: customwcs = wcslin return customwcs
[ "def", "build_self_reference", "(", "filename", ",", "clean_wcs", "=", "False", ")", ":", "if", "'sipwcs'", "in", "filename", ":", "sciname", "=", "'sipwcs'", "else", ":", "sciname", "=", "'sci'", "wcslin", "=", "build_reference_wcs", "(", "[", "filename", "...
This function creates a reference, undistorted WCS that can be used to apply a correction to the WCS of the input file. Parameters ---------- filename : str Filename of image which will be corrected, and which will form the basis of the undistorted WCS. clean_wcs : bool Specify whether or not to return the WCS object without any distortion information, or any history of the original input image. This converts the output from `utils.output_wcs()` into a pristine `~stwcs.wcsutils.HSTWCS` object. Returns ------- customwcs : `stwcs.wcsutils.HSTWCS` HSTWCS object which contains the undistorted WCS representing the entire field-of-view for the input image. Examples -------- This function can be used with the following syntax to apply a shift/rot/scale change to the same image: >>> import buildref >>> from drizzlepac import updatehdr >>> filename = "jce501erq_flc.fits" >>> wcslin = buildref.build_self_reference(filename) >>> updatehdr.updatewcs_with_shift(filename, wcslin, xsh=49.5694, ... ysh=19.2203, rot = 359.998, scale = 0.9999964)
[ "This", "function", "creates", "a", "reference", "undistorted", "WCS", "that", "can", "be", "used", "to", "apply", "a", "correction", "to", "the", "WCS", "of", "the", "input", "file", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L807-L855
train
35,519
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
read_hlet_wcs
def read_hlet_wcs(filename, ext): """Insure `stwcs.wcsutil.HSTWCS` includes all attributes of a full image WCS. For headerlets, the WCS does not contain information about the size of the image, as the image array is not present in the headerlet. """ hstwcs = wcsutil.HSTWCS(filename, ext=ext) if hstwcs.naxis1 is None: hstwcs.naxis1 = int(hstwcs.wcs.crpix[0] * 2.) # Assume crpix is center of chip hstwcs.naxis2 = int(hstwcs.wcs.crpix[1] * 2.) return hstwcs
python
def read_hlet_wcs(filename, ext): """Insure `stwcs.wcsutil.HSTWCS` includes all attributes of a full image WCS. For headerlets, the WCS does not contain information about the size of the image, as the image array is not present in the headerlet. """ hstwcs = wcsutil.HSTWCS(filename, ext=ext) if hstwcs.naxis1 is None: hstwcs.naxis1 = int(hstwcs.wcs.crpix[0] * 2.) # Assume crpix is center of chip hstwcs.naxis2 = int(hstwcs.wcs.crpix[1] * 2.) return hstwcs
[ "def", "read_hlet_wcs", "(", "filename", ",", "ext", ")", ":", "hstwcs", "=", "wcsutil", ".", "HSTWCS", "(", "filename", ",", "ext", "=", "ext", ")", "if", "hstwcs", ".", "naxis1", "is", "None", ":", "hstwcs", ".", "naxis1", "=", "int", "(", "hstwcs"...
Insure `stwcs.wcsutil.HSTWCS` includes all attributes of a full image WCS. For headerlets, the WCS does not contain information about the size of the image, as the image array is not present in the headerlet.
[ "Insure", "stwcs", ".", "wcsutil", ".", "HSTWCS", "includes", "all", "attributes", "of", "a", "full", "image", "WCS", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L858-L869
train
35,520
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
build_hstwcs
def build_hstwcs(crval1, crval2, crpix1, crpix2, naxis1, naxis2, pscale, orientat): """ Create an `stwcs.wcsutil.HSTWCS` object for a default instrument without distortion based on user provided parameter values. """ wcsout = wcsutil.HSTWCS() wcsout.wcs.crval = np.array([crval1, crval2]) wcsout.wcs.crpix = np.array([crpix1, crpix2]) wcsout.naxis1 = naxis1 wcsout.naxis2 = naxis2 wcsout.wcs.cd = buildRotMatrix(orientat) * [-1, 1] * pscale / 3600.0 # Synchronize updates with astropy.wcs objects wcsout.wcs.set() wcsout.setPscale() wcsout.setOrient() wcsout.wcs.ctype = ['RA---TAN', 'DEC--TAN'] return wcsout
python
def build_hstwcs(crval1, crval2, crpix1, crpix2, naxis1, naxis2, pscale, orientat): """ Create an `stwcs.wcsutil.HSTWCS` object for a default instrument without distortion based on user provided parameter values. """ wcsout = wcsutil.HSTWCS() wcsout.wcs.crval = np.array([crval1, crval2]) wcsout.wcs.crpix = np.array([crpix1, crpix2]) wcsout.naxis1 = naxis1 wcsout.naxis2 = naxis2 wcsout.wcs.cd = buildRotMatrix(orientat) * [-1, 1] * pscale / 3600.0 # Synchronize updates with astropy.wcs objects wcsout.wcs.set() wcsout.setPscale() wcsout.setOrient() wcsout.wcs.ctype = ['RA---TAN', 'DEC--TAN'] return wcsout
[ "def", "build_hstwcs", "(", "crval1", ",", "crval2", ",", "crpix1", ",", "crpix2", ",", "naxis1", ",", "naxis2", ",", "pscale", ",", "orientat", ")", ":", "wcsout", "=", "wcsutil", ".", "HSTWCS", "(", ")", "wcsout", ".", "wcs", ".", "crval", "=", "np...
Create an `stwcs.wcsutil.HSTWCS` object for a default instrument without distortion based on user provided parameter values.
[ "Create", "an", "stwcs", ".", "wcsutil", ".", "HSTWCS", "object", "for", "a", "default", "instrument", "without", "distortion", "based", "on", "user", "provided", "parameter", "values", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L872-L888
train
35,521
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
within_footprint
def within_footprint(img, wcs, x, y): """Determine whether input x, y fall in the science area of the image. Parameters ---------- img : ndarray ndarray of image where non-science areas are marked with value of NaN. wcs : `stwcs.wcsutil.HSTWCS` HSTWCS or WCS object with naxis terms defined. x, y : ndarray arrays of x, y positions for sources to be checked. Returns ------- x, y : ndarray New arrays which have been trimmed of all sources that fall outside the science areas of the image """ # start with limits of WCS shape if hasattr(wcs, 'naxis1'): naxis1 = wcs.naxis1 naxis2 = wcs.naxis2 elif hasattr(wcs, 'pixel_shape'): naxis1, naxis2 = wcs.pixel_shape else: naxis1 = wcs._naxis1 naxis2 = wcs._naxis2 maskx = np.bitwise_or(x < 0, x > naxis1) masky = np.bitwise_or(y < 0, y > naxis2) mask = ~np.bitwise_or(maskx, masky) x = x[mask] y = y[mask] # Now, confirm that these points fall within actual science area of WCS img_mask = create_image_footprint(img, wcs, border=1.0) inmask = np.where(img_mask[y.astype(np.int32), x.astype(np.int32)])[0] x = x[inmask] y = y[inmask] return x, y
python
def within_footprint(img, wcs, x, y): """Determine whether input x, y fall in the science area of the image. Parameters ---------- img : ndarray ndarray of image where non-science areas are marked with value of NaN. wcs : `stwcs.wcsutil.HSTWCS` HSTWCS or WCS object with naxis terms defined. x, y : ndarray arrays of x, y positions for sources to be checked. Returns ------- x, y : ndarray New arrays which have been trimmed of all sources that fall outside the science areas of the image """ # start with limits of WCS shape if hasattr(wcs, 'naxis1'): naxis1 = wcs.naxis1 naxis2 = wcs.naxis2 elif hasattr(wcs, 'pixel_shape'): naxis1, naxis2 = wcs.pixel_shape else: naxis1 = wcs._naxis1 naxis2 = wcs._naxis2 maskx = np.bitwise_or(x < 0, x > naxis1) masky = np.bitwise_or(y < 0, y > naxis2) mask = ~np.bitwise_or(maskx, masky) x = x[mask] y = y[mask] # Now, confirm that these points fall within actual science area of WCS img_mask = create_image_footprint(img, wcs, border=1.0) inmask = np.where(img_mask[y.astype(np.int32), x.astype(np.int32)])[0] x = x[inmask] y = y[inmask] return x, y
[ "def", "within_footprint", "(", "img", ",", "wcs", ",", "x", ",", "y", ")", ":", "# start with limits of WCS shape", "if", "hasattr", "(", "wcs", ",", "'naxis1'", ")", ":", "naxis1", "=", "wcs", ".", "naxis1", "naxis2", "=", "wcs", ".", "naxis2", "elif",...
Determine whether input x, y fall in the science area of the image. Parameters ---------- img : ndarray ndarray of image where non-science areas are marked with value of NaN. wcs : `stwcs.wcsutil.HSTWCS` HSTWCS or WCS object with naxis terms defined. x, y : ndarray arrays of x, y positions for sources to be checked. Returns ------- x, y : ndarray New arrays which have been trimmed of all sources that fall outside the science areas of the image
[ "Determine", "whether", "input", "x", "y", "fall", "in", "the", "science", "area", "of", "the", "image", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L891-L932
train
35,522
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
create_image_footprint
def create_image_footprint(image, refwcs, border=0.): """ Create the footprint of the image in the reference WCS frame. Parameters ---------- image : `astropy.io.fits.HDUList` or str Image to extract sources for matching to the external astrometric catalog. refwcs : `stwcs.wcsutil.HSTWCS` Reference WCS for coordinate frame of image. border : float Buffer (in arcseconds) around edge of image to exclude astrometric sources. """ # Interpret input image to generate initial source catalog and WCS if isinstance(image, str): image = pf.open(image) numSci = countExtn(image, extname='SCI') ref_x = refwcs._naxis1 ref_y = refwcs._naxis2 # convert border value into pixels border_pixels = int(border / refwcs.pscale) mask_arr = np.zeros((ref_y, ref_x), dtype=int) for chip in range(numSci): chip += 1 # Build arrays of pixel positions for all edges of chip chip_y, chip_x = image['sci', chip].data.shape chipwcs = wcsutil.HSTWCS(image, ext=('sci', chip)) xpix = np.arange(chip_x) + 1 ypix = np.arange(chip_y) + 1 edge_x = np.hstack([[1] * chip_y, xpix, [chip_x] * chip_y, xpix]) edge_y = np.hstack([ypix, [1] * chip_x, ypix, [chip_y] * chip_x]) edge_ra, edge_dec = chipwcs.all_pix2world(edge_x, edge_y, 1) edge_x_out, edge_y_out = refwcs.all_world2pix(edge_ra, edge_dec, 0) edge_x_out = np.clip(edge_x_out.astype(np.int32), 0, ref_x - 1) edge_y_out = np.clip(edge_y_out.astype(np.int32), 0, ref_y - 1) mask_arr[edge_y_out, edge_x_out] = 1 # Fill in outline of each chip mask_arr = ndimage.binary_fill_holes(ndimage.binary_dilation(mask_arr, iterations=2)) if border > 0.: mask_arr = ndimage.binary_erosion(mask_arr, iterations=border_pixels) return mask_arr
python
def create_image_footprint(image, refwcs, border=0.): """ Create the footprint of the image in the reference WCS frame. Parameters ---------- image : `astropy.io.fits.HDUList` or str Image to extract sources for matching to the external astrometric catalog. refwcs : `stwcs.wcsutil.HSTWCS` Reference WCS for coordinate frame of image. border : float Buffer (in arcseconds) around edge of image to exclude astrometric sources. """ # Interpret input image to generate initial source catalog and WCS if isinstance(image, str): image = pf.open(image) numSci = countExtn(image, extname='SCI') ref_x = refwcs._naxis1 ref_y = refwcs._naxis2 # convert border value into pixels border_pixels = int(border / refwcs.pscale) mask_arr = np.zeros((ref_y, ref_x), dtype=int) for chip in range(numSci): chip += 1 # Build arrays of pixel positions for all edges of chip chip_y, chip_x = image['sci', chip].data.shape chipwcs = wcsutil.HSTWCS(image, ext=('sci', chip)) xpix = np.arange(chip_x) + 1 ypix = np.arange(chip_y) + 1 edge_x = np.hstack([[1] * chip_y, xpix, [chip_x] * chip_y, xpix]) edge_y = np.hstack([ypix, [1] * chip_x, ypix, [chip_y] * chip_x]) edge_ra, edge_dec = chipwcs.all_pix2world(edge_x, edge_y, 1) edge_x_out, edge_y_out = refwcs.all_world2pix(edge_ra, edge_dec, 0) edge_x_out = np.clip(edge_x_out.astype(np.int32), 0, ref_x - 1) edge_y_out = np.clip(edge_y_out.astype(np.int32), 0, ref_y - 1) mask_arr[edge_y_out, edge_x_out] = 1 # Fill in outline of each chip mask_arr = ndimage.binary_fill_holes(ndimage.binary_dilation(mask_arr, iterations=2)) if border > 0.: mask_arr = ndimage.binary_erosion(mask_arr, iterations=border_pixels) return mask_arr
[ "def", "create_image_footprint", "(", "image", ",", "refwcs", ",", "border", "=", "0.", ")", ":", "# Interpret input image to generate initial source catalog and WCS", "if", "isinstance", "(", "image", ",", "str", ")", ":", "image", "=", "pf", ".", "open", "(", ...
Create the footprint of the image in the reference WCS frame. Parameters ---------- image : `astropy.io.fits.HDUList` or str Image to extract sources for matching to the external astrometric catalog. refwcs : `stwcs.wcsutil.HSTWCS` Reference WCS for coordinate frame of image. border : float Buffer (in arcseconds) around edge of image to exclude astrometric sources.
[ "Create", "the", "footprint", "of", "the", "image", "in", "the", "reference", "WCS", "frame", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L935-L984
train
35,523
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
find_hist2d_offset
def find_hist2d_offset(filename, reference, refwcs=None, refnames=['ra', 'dec'], match_tolerance=5., chip_catalog=True, search_radius=15.0, min_match=10, classify=True): """Iteratively look for the best cross-match between the catalog and ref. Parameters ---------- filename : `~astropy.io.fits.HDUList` or str Single image to extract sources for matching to the external astrometric catalog. reference : str or `~astropy.table.Table` Reference catalog, either as a filename or ``astropy.Table`` containing astrometrically accurate sky coordinates for astrometric standard sources. refwcs : `~stwcs.wcsutil.HSTWCS` This WCS will define the coordinate frame which will be used to determine the offset. If None is specified, use the WCS from the input image `filename` to build this WCS using `build_self_reference()`. refnames : list List of table column names for sky coordinates of astrometric standard sources from reference catalog. match_tolerance : float Tolerance (in pixels) for recognizing that a source position matches an astrometric catalog position. Larger values allow for lower accuracy source positions to be compared to astrometric catalog chip_catalog : bool Specify whether or not to write out individual source catalog for each chip in the image. search_radius : float Maximum separation (in arcseconds) from source positions to look for valid cross-matches with reference source positions. min_match : int Minimum number of cross-matches for an acceptable determination of the offset. classify : bool Specify whether or not to use central_moments classification to ignore likely cosmic-rays/bad-pixels when generating the source catalog. Returns ------- best_offset : tuple Offset in input image pixels between image source positions and astrometric catalog positions that results in largest number of matches of astrometric sources with image sources seg_xy, ref_xy : astropy.Table Source catalog and reference catalog, respectively, used for determining the offset. Each catalog includes sources for the entire field-of-view, not just a single chip. """ # Interpret input image to generate initial source catalog and WCS if isinstance(filename, str): image = pf.open(filename) rootname = filename.split("_")[0] else: image = filename rootname = image[0].header['rootname'] # check to see whether reference catalog can be found if not os.path.exists(reference): log.info("Could not find input reference catalog: {}".format(reference)) raise FileNotFoundError # Extract reference WCS from image if refwcs is None: refwcs = build_self_reference(image, clean_wcs=True) log.info("Computing offset for field-of-view defined by:") log.info(refwcs) # read in reference catalog if isinstance(reference, str): refcat = ascii.read(reference) else: refcat = reference log.info("\nRead in reference catalog with {} sources.".format(len(refcat))) ref_ra = refcat[refnames[0]] ref_dec = refcat[refnames[1]] # Build source catalog for entire image img_cat = generate_source_catalog(image, refwcs, output=chip_catalog, classify=classify) img_cat.write(filename.replace(".fits", "_xy.cat"), format='ascii.no_header', overwrite=True) # Retrieve source XY positions in reference frame seg_xy = np.column_stack((img_cat['xcentroid'], img_cat['ycentroid'])) seg_xy = seg_xy[~np.isnan(seg_xy[:, 0])] # Translate reference catalog positions into input image coordinate frame xref, yref = refwcs.all_world2pix(ref_ra, ref_dec, 1) # look for only sources within the viewable area of the exposure to # determine the offset xref, yref = within_footprint(image, refwcs, xref, yref) ref_xy = np.column_stack((xref, yref)) log.info("\nWorking with {} astrometric sources for this field".format(len(ref_xy))) # write out astrometric reference catalog that was actually used ref_ra_img, ref_dec_img = refwcs.all_pix2world(xref, yref, 1) ref_tab = Table([ref_ra_img, ref_dec_img, xref, yref], names=['ra', 'dec', 'x', 'y']) ref_tab.write(reference.replace('.cat', '_{}.cat'.format(rootname)), format='ascii.fast_commented_header', overwrite=True) searchrad = search_radius / refwcs.pscale # Use 2d-Histogram builder from drizzlepac.tweakreg -- for demo only... xp, yp, nmatches, zpqual = build_xy_zeropoint(seg_xy, ref_xy, searchrad=searchrad, histplot=False, figure_id=1, plotname=None, interactive=False) hist2d_offset = (xp, yp) log.info('best offset {} based on {} cross-matches'.format(hist2d_offset, nmatches)) return hist2d_offset, seg_xy, ref_xy
python
def find_hist2d_offset(filename, reference, refwcs=None, refnames=['ra', 'dec'], match_tolerance=5., chip_catalog=True, search_radius=15.0, min_match=10, classify=True): """Iteratively look for the best cross-match between the catalog and ref. Parameters ---------- filename : `~astropy.io.fits.HDUList` or str Single image to extract sources for matching to the external astrometric catalog. reference : str or `~astropy.table.Table` Reference catalog, either as a filename or ``astropy.Table`` containing astrometrically accurate sky coordinates for astrometric standard sources. refwcs : `~stwcs.wcsutil.HSTWCS` This WCS will define the coordinate frame which will be used to determine the offset. If None is specified, use the WCS from the input image `filename` to build this WCS using `build_self_reference()`. refnames : list List of table column names for sky coordinates of astrometric standard sources from reference catalog. match_tolerance : float Tolerance (in pixels) for recognizing that a source position matches an astrometric catalog position. Larger values allow for lower accuracy source positions to be compared to astrometric catalog chip_catalog : bool Specify whether or not to write out individual source catalog for each chip in the image. search_radius : float Maximum separation (in arcseconds) from source positions to look for valid cross-matches with reference source positions. min_match : int Minimum number of cross-matches for an acceptable determination of the offset. classify : bool Specify whether or not to use central_moments classification to ignore likely cosmic-rays/bad-pixels when generating the source catalog. Returns ------- best_offset : tuple Offset in input image pixels between image source positions and astrometric catalog positions that results in largest number of matches of astrometric sources with image sources seg_xy, ref_xy : astropy.Table Source catalog and reference catalog, respectively, used for determining the offset. Each catalog includes sources for the entire field-of-view, not just a single chip. """ # Interpret input image to generate initial source catalog and WCS if isinstance(filename, str): image = pf.open(filename) rootname = filename.split("_")[0] else: image = filename rootname = image[0].header['rootname'] # check to see whether reference catalog can be found if not os.path.exists(reference): log.info("Could not find input reference catalog: {}".format(reference)) raise FileNotFoundError # Extract reference WCS from image if refwcs is None: refwcs = build_self_reference(image, clean_wcs=True) log.info("Computing offset for field-of-view defined by:") log.info(refwcs) # read in reference catalog if isinstance(reference, str): refcat = ascii.read(reference) else: refcat = reference log.info("\nRead in reference catalog with {} sources.".format(len(refcat))) ref_ra = refcat[refnames[0]] ref_dec = refcat[refnames[1]] # Build source catalog for entire image img_cat = generate_source_catalog(image, refwcs, output=chip_catalog, classify=classify) img_cat.write(filename.replace(".fits", "_xy.cat"), format='ascii.no_header', overwrite=True) # Retrieve source XY positions in reference frame seg_xy = np.column_stack((img_cat['xcentroid'], img_cat['ycentroid'])) seg_xy = seg_xy[~np.isnan(seg_xy[:, 0])] # Translate reference catalog positions into input image coordinate frame xref, yref = refwcs.all_world2pix(ref_ra, ref_dec, 1) # look for only sources within the viewable area of the exposure to # determine the offset xref, yref = within_footprint(image, refwcs, xref, yref) ref_xy = np.column_stack((xref, yref)) log.info("\nWorking with {} astrometric sources for this field".format(len(ref_xy))) # write out astrometric reference catalog that was actually used ref_ra_img, ref_dec_img = refwcs.all_pix2world(xref, yref, 1) ref_tab = Table([ref_ra_img, ref_dec_img, xref, yref], names=['ra', 'dec', 'x', 'y']) ref_tab.write(reference.replace('.cat', '_{}.cat'.format(rootname)), format='ascii.fast_commented_header', overwrite=True) searchrad = search_radius / refwcs.pscale # Use 2d-Histogram builder from drizzlepac.tweakreg -- for demo only... xp, yp, nmatches, zpqual = build_xy_zeropoint(seg_xy, ref_xy, searchrad=searchrad, histplot=False, figure_id=1, plotname=None, interactive=False) hist2d_offset = (xp, yp) log.info('best offset {} based on {} cross-matches'.format(hist2d_offset, nmatches)) return hist2d_offset, seg_xy, ref_xy
[ "def", "find_hist2d_offset", "(", "filename", ",", "reference", ",", "refwcs", "=", "None", ",", "refnames", "=", "[", "'ra'", ",", "'dec'", "]", ",", "match_tolerance", "=", "5.", ",", "chip_catalog", "=", "True", ",", "search_radius", "=", "15.0", ",", ...
Iteratively look for the best cross-match between the catalog and ref. Parameters ---------- filename : `~astropy.io.fits.HDUList` or str Single image to extract sources for matching to the external astrometric catalog. reference : str or `~astropy.table.Table` Reference catalog, either as a filename or ``astropy.Table`` containing astrometrically accurate sky coordinates for astrometric standard sources. refwcs : `~stwcs.wcsutil.HSTWCS` This WCS will define the coordinate frame which will be used to determine the offset. If None is specified, use the WCS from the input image `filename` to build this WCS using `build_self_reference()`. refnames : list List of table column names for sky coordinates of astrometric standard sources from reference catalog. match_tolerance : float Tolerance (in pixels) for recognizing that a source position matches an astrometric catalog position. Larger values allow for lower accuracy source positions to be compared to astrometric catalog chip_catalog : bool Specify whether or not to write out individual source catalog for each chip in the image. search_radius : float Maximum separation (in arcseconds) from source positions to look for valid cross-matches with reference source positions. min_match : int Minimum number of cross-matches for an acceptable determination of the offset. classify : bool Specify whether or not to use central_moments classification to ignore likely cosmic-rays/bad-pixels when generating the source catalog. Returns ------- best_offset : tuple Offset in input image pixels between image source positions and astrometric catalog positions that results in largest number of matches of astrometric sources with image sources seg_xy, ref_xy : astropy.Table Source catalog and reference catalog, respectively, used for determining the offset. Each catalog includes sources for the entire field-of-view, not just a single chip.
[ "Iteratively", "look", "for", "the", "best", "cross", "-", "match", "between", "the", "catalog", "and", "ref", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L987-L1109
train
35,524
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
build_wcscat
def build_wcscat(image, group_id, source_catalog): """ Return a list of `~tweakwcs.tpwcs.FITSWCS` objects for all chips in an image. Parameters ---------- image : str, ~astropy.io.fits.HDUList` Either filename or HDUList of a single HST observation. group_id : int Integer ID for group this image should be associated with; primarily used when separate chips are in separate files to treat them all as one exposure. source_catalog : dict If provided, these catalogs will be attached as `catalog` entries in each chip's ``FITSWCS`` object. It should be provided as a dict of astropy Tables identified by chip number with each table containing sources from image extension ``('sci', chip)`` as generated by `generate_source_catalog()`. Returns ------- wcs_catalogs : list of `~tweakwcs.tpwcs.FITSWCS` List of `~tweakwcs.tpwcs.FITSWCS` objects defined for all chips in input image. """ open_file = False if isinstance(image, str): hdulist = pf.open(image) open_file = True elif isinstance(image, pf.HDUList): hdulist = image else: log.info("Wrong type of input, {}, for build_wcscat...".format(type(image))) raise ValueError wcs_catalogs = [] numsci = countExtn(hdulist) for chip in range(1, numsci + 1): w = wcsutil.HSTWCS(hdulist, ('SCI', chip)) imcat = source_catalog[chip] # rename xcentroid/ycentroid columns, if necessary, to be consistent with tweakwcs if 'xcentroid' in imcat.colnames: imcat.rename_column('xcentroid', 'x') imcat.rename_column('ycentroid', 'y') wcscat = FITSWCS( w, meta={ 'chip': chip, 'group_id': group_id, 'filename': image, 'catalog': imcat, 'name': image } ) wcs_catalogs.append(wcscat) if open_file: hdulist.close() return wcs_catalogs
python
def build_wcscat(image, group_id, source_catalog): """ Return a list of `~tweakwcs.tpwcs.FITSWCS` objects for all chips in an image. Parameters ---------- image : str, ~astropy.io.fits.HDUList` Either filename or HDUList of a single HST observation. group_id : int Integer ID for group this image should be associated with; primarily used when separate chips are in separate files to treat them all as one exposure. source_catalog : dict If provided, these catalogs will be attached as `catalog` entries in each chip's ``FITSWCS`` object. It should be provided as a dict of astropy Tables identified by chip number with each table containing sources from image extension ``('sci', chip)`` as generated by `generate_source_catalog()`. Returns ------- wcs_catalogs : list of `~tweakwcs.tpwcs.FITSWCS` List of `~tweakwcs.tpwcs.FITSWCS` objects defined for all chips in input image. """ open_file = False if isinstance(image, str): hdulist = pf.open(image) open_file = True elif isinstance(image, pf.HDUList): hdulist = image else: log.info("Wrong type of input, {}, for build_wcscat...".format(type(image))) raise ValueError wcs_catalogs = [] numsci = countExtn(hdulist) for chip in range(1, numsci + 1): w = wcsutil.HSTWCS(hdulist, ('SCI', chip)) imcat = source_catalog[chip] # rename xcentroid/ycentroid columns, if necessary, to be consistent with tweakwcs if 'xcentroid' in imcat.colnames: imcat.rename_column('xcentroid', 'x') imcat.rename_column('ycentroid', 'y') wcscat = FITSWCS( w, meta={ 'chip': chip, 'group_id': group_id, 'filename': image, 'catalog': imcat, 'name': image } ) wcs_catalogs.append(wcscat) if open_file: hdulist.close() return wcs_catalogs
[ "def", "build_wcscat", "(", "image", ",", "group_id", ",", "source_catalog", ")", ":", "open_file", "=", "False", "if", "isinstance", "(", "image", ",", "str", ")", ":", "hdulist", "=", "pf", ".", "open", "(", "image", ")", "open_file", "=", "True", "e...
Return a list of `~tweakwcs.tpwcs.FITSWCS` objects for all chips in an image. Parameters ---------- image : str, ~astropy.io.fits.HDUList` Either filename or HDUList of a single HST observation. group_id : int Integer ID for group this image should be associated with; primarily used when separate chips are in separate files to treat them all as one exposure. source_catalog : dict If provided, these catalogs will be attached as `catalog` entries in each chip's ``FITSWCS`` object. It should be provided as a dict of astropy Tables identified by chip number with each table containing sources from image extension ``('sci', chip)`` as generated by `generate_source_catalog()`. Returns ------- wcs_catalogs : list of `~tweakwcs.tpwcs.FITSWCS` List of `~tweakwcs.tpwcs.FITSWCS` objects defined for all chips in input image.
[ "Return", "a", "list", "of", "~tweakwcs", ".", "tpwcs", ".", "FITSWCS", "objects", "for", "all", "chips", "in", "an", "image", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L1117-L1180
train
35,525
spacetelescope/drizzlepac
drizzlepac/updatehdr.py
update_from_shiftfile
def update_from_shiftfile(shiftfile,wcsname=None,force=False): """ Update headers of all images specified in shiftfile with shifts from shiftfile. Parameters ---------- shiftfile : str Filename of shiftfile. wcsname : str Label to give to new WCS solution being created by this fit. If a value of None is given, it will automatically use 'TWEAK' as the label. [Default =None] force : bool Update header even though WCS already exists with this solution or wcsname? [Default=False] """ f = open(fileutil.osfn(shiftfile)) shift_lines = [x.strip() for x in f.readlines()] f.close() # interpret header of shift file for line in shift_lines: if 'refimage' in line or 'reference' in line: refimage = line.split(':')[-1] refimage = refimage[:refimage.find('[wcs]')].lstrip() break # Determine the max length in the first column (filenames) fnames = [] for row in shift_lines: if row[0] == '#': continue fnames.append(len(row.split(' ')[0])) fname_fmt = 'S{0}'.format(max(fnames)) # Now read in numerical values from shiftfile type_list = {'names':('fnames','xsh','ysh','rot','scale','xrms','yrms'), 'formats':(fname_fmt,'f4','f4','f4','f4','f4','f4')} try: sdict = np.loadtxt(shiftfile,dtype=type_list,unpack=False) except IndexError: tlist = {'names':('fnames','xsh','ysh','rot','scale'), 'formats':(fname_fmt,'f4','f4','f4','f4')} s = np.loadtxt(shiftfile,dtype=tlist,unpack=False) sdict = np.zeros([s['fnames'].shape[0],],dtype=type_list) for sname in s.dtype.names: sdict[sname] = s[sname] for img in sdict: updatewcs_with_shift(img['fnames'], refimage, wcsname=wcsname, rot=img['rot'], scale=img['scale'], xsh=img['xsh'], ysh=img['ysh'], xrms=img['xrms'], yrms=img['yrms'], force=force)
python
def update_from_shiftfile(shiftfile,wcsname=None,force=False): """ Update headers of all images specified in shiftfile with shifts from shiftfile. Parameters ---------- shiftfile : str Filename of shiftfile. wcsname : str Label to give to new WCS solution being created by this fit. If a value of None is given, it will automatically use 'TWEAK' as the label. [Default =None] force : bool Update header even though WCS already exists with this solution or wcsname? [Default=False] """ f = open(fileutil.osfn(shiftfile)) shift_lines = [x.strip() for x in f.readlines()] f.close() # interpret header of shift file for line in shift_lines: if 'refimage' in line or 'reference' in line: refimage = line.split(':')[-1] refimage = refimage[:refimage.find('[wcs]')].lstrip() break # Determine the max length in the first column (filenames) fnames = [] for row in shift_lines: if row[0] == '#': continue fnames.append(len(row.split(' ')[0])) fname_fmt = 'S{0}'.format(max(fnames)) # Now read in numerical values from shiftfile type_list = {'names':('fnames','xsh','ysh','rot','scale','xrms','yrms'), 'formats':(fname_fmt,'f4','f4','f4','f4','f4','f4')} try: sdict = np.loadtxt(shiftfile,dtype=type_list,unpack=False) except IndexError: tlist = {'names':('fnames','xsh','ysh','rot','scale'), 'formats':(fname_fmt,'f4','f4','f4','f4')} s = np.loadtxt(shiftfile,dtype=tlist,unpack=False) sdict = np.zeros([s['fnames'].shape[0],],dtype=type_list) for sname in s.dtype.names: sdict[sname] = s[sname] for img in sdict: updatewcs_with_shift(img['fnames'], refimage, wcsname=wcsname, rot=img['rot'], scale=img['scale'], xsh=img['xsh'], ysh=img['ysh'], xrms=img['xrms'], yrms=img['yrms'], force=force)
[ "def", "update_from_shiftfile", "(", "shiftfile", ",", "wcsname", "=", "None", ",", "force", "=", "False", ")", ":", "f", "=", "open", "(", "fileutil", ".", "osfn", "(", "shiftfile", ")", ")", "shift_lines", "=", "[", "x", ".", "strip", "(", ")", "fo...
Update headers of all images specified in shiftfile with shifts from shiftfile. Parameters ---------- shiftfile : str Filename of shiftfile. wcsname : str Label to give to new WCS solution being created by this fit. If a value of None is given, it will automatically use 'TWEAK' as the label. [Default =None] force : bool Update header even though WCS already exists with this solution or wcsname? [Default=False]
[ "Update", "headers", "of", "all", "images", "specified", "in", "shiftfile", "with", "shifts", "from", "shiftfile", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/updatehdr.py#L41-L97
train
35,526
spacetelescope/drizzlepac
drizzlepac/updatehdr.py
linearize
def linearize(wcsim, wcsima, wcsref, imcrpix, f, shift, hx=1.0, hy=1.0): """ linearization using 5-point formula for first order derivative """ x0 = imcrpix[0] y0 = imcrpix[1] p = np.asarray([[x0, y0], [x0 - hx, y0], [x0 - hx * 0.5, y0], [x0 + hx * 0.5, y0], [x0 + hx, y0], [x0, y0 - hy], [x0, y0 - hy * 0.5], [x0, y0 + hy * 0.5], [x0, y0 + hy]], dtype=np.float64) # convert image coordinates to reference image coordinates: p = wcsref.wcs_world2pix(wcsim.wcs_pix2world(p, 1), 1).astype(ndfloat128) # apply linear fit transformation: p = np.dot(f, (p - shift).T).T # convert back to image coordinate system: p = wcsima.wcs_world2pix( wcsref.wcs_pix2world(p.astype(np.float64), 1), 1).astype(ndfloat128) # derivative with regard to x: u1 = ((p[1] - p[4]) + 8 * (p[3] - p[2])) / (6*hx) # derivative with regard to y: u2 = ((p[5] - p[8]) + 8 * (p[7] - p[6])) / (6*hy) return (np.asarray([u1, u2]).T, p[0])
python
def linearize(wcsim, wcsima, wcsref, imcrpix, f, shift, hx=1.0, hy=1.0): """ linearization using 5-point formula for first order derivative """ x0 = imcrpix[0] y0 = imcrpix[1] p = np.asarray([[x0, y0], [x0 - hx, y0], [x0 - hx * 0.5, y0], [x0 + hx * 0.5, y0], [x0 + hx, y0], [x0, y0 - hy], [x0, y0 - hy * 0.5], [x0, y0 + hy * 0.5], [x0, y0 + hy]], dtype=np.float64) # convert image coordinates to reference image coordinates: p = wcsref.wcs_world2pix(wcsim.wcs_pix2world(p, 1), 1).astype(ndfloat128) # apply linear fit transformation: p = np.dot(f, (p - shift).T).T # convert back to image coordinate system: p = wcsima.wcs_world2pix( wcsref.wcs_pix2world(p.astype(np.float64), 1), 1).astype(ndfloat128) # derivative with regard to x: u1 = ((p[1] - p[4]) + 8 * (p[3] - p[2])) / (6*hx) # derivative with regard to y: u2 = ((p[5] - p[8]) + 8 * (p[7] - p[6])) / (6*hy) return (np.asarray([u1, u2]).T, p[0])
[ "def", "linearize", "(", "wcsim", ",", "wcsima", ",", "wcsref", ",", "imcrpix", ",", "f", ",", "shift", ",", "hx", "=", "1.0", ",", "hy", "=", "1.0", ")", ":", "x0", "=", "imcrpix", "[", "0", "]", "y0", "=", "imcrpix", "[", "1", "]", "p", "="...
linearization using 5-point formula for first order derivative
[ "linearization", "using", "5", "-", "point", "formula", "for", "first", "order", "derivative" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/updatehdr.py#L283-L312
train
35,527
spacetelescope/drizzlepac
drizzlepac/updatehdr.py
update_wcs
def update_wcs(image,extnum,new_wcs,wcsname="",reusename=False,verbose=False): """ Updates the WCS of the specified extension number with the new WCS after archiving the original WCS. The value of 'new_wcs' needs to be the full HSTWCS object. Parameters ---------- image : str Filename of image with WCS that needs to be updated extnum : int Extension number for extension with WCS to be updated/replaced new_wcs : object Full HSTWCS object which will replace/update the existing WCS wcsname : str Label to give newly updated WCS reusename : bool User can choose whether to over-write WCS with same name or not. [Default: False] verbose : bool, int Print extra messages during processing? [Default: False] """ # Start by insuring that the correct value of 'orientat' has been computed new_wcs.setOrient() fimg_open=False if not isinstance(image, fits.HDUList): fimg = fits.open(image, mode='update', memmap=False) fimg_open = True fimg_update = True else: fimg = image if fimg.fileinfo(0)['filemode'] is 'update': fimg_update = True else: fimg_update = False # Determine final (unique) WCSNAME value, either based on the default or # user-provided name if util.is_blank(wcsname): wcsname = 'TWEAK' if not reusename: wcsname = create_unique_wcsname(fimg, extnum, wcsname) idchdr = True if new_wcs.idcscale is None: idchdr = False # Open the file for updating the WCS try: logstr = 'Updating header for %s[%s]'%(fimg.filename(),str(extnum)) if verbose: print(logstr) else: log.info(logstr) hdr = fimg[extnum].header if verbose: log.info(' with WCS of') new_wcs.printwcs() print("WCSNAME : ",wcsname) # Insure that if a copy of the WCS has not been created yet, it will be now wcs_hdr = new_wcs.wcs2header(idc2hdr=idchdr, relax=True) for key in wcs_hdr: hdr[key] = wcs_hdr[key] hdr['ORIENTAT'] = new_wcs.orientat hdr['WCSNAME'] = wcsname util.updateNEXTENDKw(fimg) # Only if this image was opened in update mode should this # newly updated WCS be archived, as it will never be written out # to a file otherwise. if fimg_update: if not reusename: # Save the newly updated WCS as an alternate WCS as well wkey = wcsutil.altwcs.next_wcskey(fimg,ext=extnum) else: wkey = wcsutil.altwcs.getKeyFromName(hdr,wcsname) # wcskey needs to be specified so that archiveWCS will create a # duplicate WCS with the same WCSNAME as the Primary WCS wcsutil.altwcs.archiveWCS(fimg,[extnum],wcsname=wcsname, wcskey=wkey, reusekey=reusename) finally: if fimg_open: # finish up by closing the file now fimg.close()
python
def update_wcs(image,extnum,new_wcs,wcsname="",reusename=False,verbose=False): """ Updates the WCS of the specified extension number with the new WCS after archiving the original WCS. The value of 'new_wcs' needs to be the full HSTWCS object. Parameters ---------- image : str Filename of image with WCS that needs to be updated extnum : int Extension number for extension with WCS to be updated/replaced new_wcs : object Full HSTWCS object which will replace/update the existing WCS wcsname : str Label to give newly updated WCS reusename : bool User can choose whether to over-write WCS with same name or not. [Default: False] verbose : bool, int Print extra messages during processing? [Default: False] """ # Start by insuring that the correct value of 'orientat' has been computed new_wcs.setOrient() fimg_open=False if not isinstance(image, fits.HDUList): fimg = fits.open(image, mode='update', memmap=False) fimg_open = True fimg_update = True else: fimg = image if fimg.fileinfo(0)['filemode'] is 'update': fimg_update = True else: fimg_update = False # Determine final (unique) WCSNAME value, either based on the default or # user-provided name if util.is_blank(wcsname): wcsname = 'TWEAK' if not reusename: wcsname = create_unique_wcsname(fimg, extnum, wcsname) idchdr = True if new_wcs.idcscale is None: idchdr = False # Open the file for updating the WCS try: logstr = 'Updating header for %s[%s]'%(fimg.filename(),str(extnum)) if verbose: print(logstr) else: log.info(logstr) hdr = fimg[extnum].header if verbose: log.info(' with WCS of') new_wcs.printwcs() print("WCSNAME : ",wcsname) # Insure that if a copy of the WCS has not been created yet, it will be now wcs_hdr = new_wcs.wcs2header(idc2hdr=idchdr, relax=True) for key in wcs_hdr: hdr[key] = wcs_hdr[key] hdr['ORIENTAT'] = new_wcs.orientat hdr['WCSNAME'] = wcsname util.updateNEXTENDKw(fimg) # Only if this image was opened in update mode should this # newly updated WCS be archived, as it will never be written out # to a file otherwise. if fimg_update: if not reusename: # Save the newly updated WCS as an alternate WCS as well wkey = wcsutil.altwcs.next_wcskey(fimg,ext=extnum) else: wkey = wcsutil.altwcs.getKeyFromName(hdr,wcsname) # wcskey needs to be specified so that archiveWCS will create a # duplicate WCS with the same WCSNAME as the Primary WCS wcsutil.altwcs.archiveWCS(fimg,[extnum],wcsname=wcsname, wcskey=wkey, reusekey=reusename) finally: if fimg_open: # finish up by closing the file now fimg.close()
[ "def", "update_wcs", "(", "image", ",", "extnum", ",", "new_wcs", ",", "wcsname", "=", "\"\"", ",", "reusename", "=", "False", ",", "verbose", "=", "False", ")", ":", "# Start by insuring that the correct value of 'orientat' has been computed", "new_wcs", ".", "setO...
Updates the WCS of the specified extension number with the new WCS after archiving the original WCS. The value of 'new_wcs' needs to be the full HSTWCS object. Parameters ---------- image : str Filename of image with WCS that needs to be updated extnum : int Extension number for extension with WCS to be updated/replaced new_wcs : object Full HSTWCS object which will replace/update the existing WCS wcsname : str Label to give newly updated WCS reusename : bool User can choose whether to over-write WCS with same name or not. [Default: False] verbose : bool, int Print extra messages during processing? [Default: False]
[ "Updates", "the", "WCS", "of", "the", "specified", "extension", "number", "with", "the", "new", "WCS", "after", "archiving", "the", "original", "WCS", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/updatehdr.py#L424-L520
train
35,528
spacetelescope/drizzlepac
drizzlepac/updatehdr.py
create_unique_wcsname
def create_unique_wcsname(fimg, extnum, wcsname): """ This function evaluates whether the specified wcsname value has already been used in this image. If so, it automatically modifies the name with a simple version ID using wcsname_NNN format. Parameters ---------- fimg : obj PyFITS object of image with WCS information to be updated extnum : int Index of extension with WCS information to be updated wcsname : str Value of WCSNAME specified by user for labelling the new WCS Returns ------- uniqname : str Unique WCSNAME value """ wnames = list(wcsutil.altwcs.wcsnames(fimg, ext=extnum).values()) if wcsname not in wnames: uniqname = wcsname else: # setup pattern to match rpatt = re.compile(wcsname+'_\d') index = 0 for wname in wnames: rmatch = rpatt.match(wname) if rmatch: # get index n = int(wname[wname.rfind('_')+1:]) if n > index: index = 1 index += 1 # for use with new name uniqname = "%s_%d"%(wcsname,index) return uniqname
python
def create_unique_wcsname(fimg, extnum, wcsname): """ This function evaluates whether the specified wcsname value has already been used in this image. If so, it automatically modifies the name with a simple version ID using wcsname_NNN format. Parameters ---------- fimg : obj PyFITS object of image with WCS information to be updated extnum : int Index of extension with WCS information to be updated wcsname : str Value of WCSNAME specified by user for labelling the new WCS Returns ------- uniqname : str Unique WCSNAME value """ wnames = list(wcsutil.altwcs.wcsnames(fimg, ext=extnum).values()) if wcsname not in wnames: uniqname = wcsname else: # setup pattern to match rpatt = re.compile(wcsname+'_\d') index = 0 for wname in wnames: rmatch = rpatt.match(wname) if rmatch: # get index n = int(wname[wname.rfind('_')+1:]) if n > index: index = 1 index += 1 # for use with new name uniqname = "%s_%d"%(wcsname,index) return uniqname
[ "def", "create_unique_wcsname", "(", "fimg", ",", "extnum", ",", "wcsname", ")", ":", "wnames", "=", "list", "(", "wcsutil", ".", "altwcs", ".", "wcsnames", "(", "fimg", ",", "ext", "=", "extnum", ")", ".", "values", "(", ")", ")", "if", "wcsname", "...
This function evaluates whether the specified wcsname value has already been used in this image. If so, it automatically modifies the name with a simple version ID using wcsname_NNN format. Parameters ---------- fimg : obj PyFITS object of image with WCS information to be updated extnum : int Index of extension with WCS information to be updated wcsname : str Value of WCSNAME specified by user for labelling the new WCS Returns ------- uniqname : str Unique WCSNAME value
[ "This", "function", "evaluates", "whether", "the", "specified", "wcsname", "value", "has", "already", "been", "used", "in", "this", "image", ".", "If", "so", "it", "automatically", "modifies", "the", "name", "with", "a", "simple", "version", "ID", "using", "...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/updatehdr.py#L523-L561
train
35,529
spacetelescope/drizzlepac
drizzlepac/util.py
end_logging
def end_logging(filename=None): """ Close log file and restore system defaults. """ if logutil.global_logging_started: if filename: print('Trailer file written to: ', filename) else: # This generally shouldn't happen if logging was started with # init_logging and a filename was given... print('No trailer file saved...') logutil.teardown_global_logging() else: print('No trailer file saved...')
python
def end_logging(filename=None): """ Close log file and restore system defaults. """ if logutil.global_logging_started: if filename: print('Trailer file written to: ', filename) else: # This generally shouldn't happen if logging was started with # init_logging and a filename was given... print('No trailer file saved...') logutil.teardown_global_logging() else: print('No trailer file saved...')
[ "def", "end_logging", "(", "filename", "=", "None", ")", ":", "if", "logutil", ".", "global_logging_started", ":", "if", "filename", ":", "print", "(", "'Trailer file written to: '", ",", "filename", ")", "else", ":", "# This generally shouldn't happen if logging was ...
Close log file and restore system defaults.
[ "Close", "log", "file", "and", "restore", "system", "defaults", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L149-L164
train
35,530
spacetelescope/drizzlepac
drizzlepac/util.py
findrootname
def findrootname(filename): """ Return the rootname of the given file. """ puncloc = [filename.find(char) for char in string.punctuation] if sys.version_info[0] >= 3: val = sys.maxsize else: val = sys.maxint for num in puncloc: if num !=-1 and num < val: val = num return filename[0:val]
python
def findrootname(filename): """ Return the rootname of the given file. """ puncloc = [filename.find(char) for char in string.punctuation] if sys.version_info[0] >= 3: val = sys.maxsize else: val = sys.maxint for num in puncloc: if num !=-1 and num < val: val = num return filename[0:val]
[ "def", "findrootname", "(", "filename", ")", ":", "puncloc", "=", "[", "filename", ".", "find", "(", "char", ")", "for", "char", "in", "string", ".", "punctuation", "]", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "val", "=", "...
Return the rootname of the given file.
[ "Return", "the", "rootname", "of", "the", "given", "file", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L390-L403
train
35,531
spacetelescope/drizzlepac
drizzlepac/util.py
removeFileSafely
def removeFileSafely(filename,clobber=True): """ Delete the file specified, but only if it exists and clobber is True. """ if filename is not None and filename.strip() != '': if os.path.exists(filename) and clobber: os.remove(filename)
python
def removeFileSafely(filename,clobber=True): """ Delete the file specified, but only if it exists and clobber is True. """ if filename is not None and filename.strip() != '': if os.path.exists(filename) and clobber: os.remove(filename)
[ "def", "removeFileSafely", "(", "filename", ",", "clobber", "=", "True", ")", ":", "if", "filename", "is", "not", "None", "and", "filename", ".", "strip", "(", ")", "!=", "''", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", "and",...
Delete the file specified, but only if it exists and clobber is True.
[ "Delete", "the", "file", "specified", "but", "only", "if", "it", "exists", "and", "clobber", "is", "True", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L406-L410
train
35,532
spacetelescope/drizzlepac
drizzlepac/util.py
displayEmptyInputWarningBox
def displayEmptyInputWarningBox(display=True, parent=None): """ Displays a warning box for the 'input' parameter. """ if sys.version_info[0] >= 3: from tkinter.messagebox import showwarning else: from tkMessageBox import showwarning if display: msg = 'No valid input files found! '+\ 'Please check the value for the "input" parameter.' showwarning(parent=parent,message=msg, title="No valid inputs!") return "yes"
python
def displayEmptyInputWarningBox(display=True, parent=None): """ Displays a warning box for the 'input' parameter. """ if sys.version_info[0] >= 3: from tkinter.messagebox import showwarning else: from tkMessageBox import showwarning if display: msg = 'No valid input files found! '+\ 'Please check the value for the "input" parameter.' showwarning(parent=parent,message=msg, title="No valid inputs!") return "yes"
[ "def", "displayEmptyInputWarningBox", "(", "display", "=", "True", ",", "parent", "=", "None", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "from", "tkinter", ".", "messagebox", "import", "showwarning", "else", ":", "from", ...
Displays a warning box for the 'input' parameter.
[ "Displays", "a", "warning", "box", "for", "the", "input", "parameter", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L412-L424
train
35,533
spacetelescope/drizzlepac
drizzlepac/util.py
count_sci_extensions
def count_sci_extensions(filename): """ Return the number of SCI extensions and the EXTNAME from a input MEF file. """ num_sci = 0 extname = 'SCI' hdu_list = fileutil.openImage(filename, memmap=False) for extn in hdu_list: if 'extname' in extn.header and extn.header['extname'] == extname: num_sci += 1 if num_sci == 0: extname = 'PRIMARY' num_sci = 1 hdu_list.close() return num_sci,extname
python
def count_sci_extensions(filename): """ Return the number of SCI extensions and the EXTNAME from a input MEF file. """ num_sci = 0 extname = 'SCI' hdu_list = fileutil.openImage(filename, memmap=False) for extn in hdu_list: if 'extname' in extn.header and extn.header['extname'] == extname: num_sci += 1 if num_sci == 0: extname = 'PRIMARY' num_sci = 1 hdu_list.close() return num_sci,extname
[ "def", "count_sci_extensions", "(", "filename", ")", ":", "num_sci", "=", "0", "extname", "=", "'SCI'", "hdu_list", "=", "fileutil", ".", "openImage", "(", "filename", ",", "memmap", "=", "False", ")", "for", "extn", "in", "hdu_list", ":", "if", "'extname'...
Return the number of SCI extensions and the EXTNAME from a input MEF file.
[ "Return", "the", "number", "of", "SCI", "extensions", "and", "the", "EXTNAME", "from", "a", "input", "MEF", "file", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L451-L469
train
35,534
spacetelescope/drizzlepac
drizzlepac/util.py
verifyUniqueWcsname
def verifyUniqueWcsname(fname,wcsname): """ Report whether or not the specified WCSNAME already exists in the file """ uniq = True numsci,extname = count_sci_extensions(fname) wnames = altwcs.wcsnames(fname,ext=(extname,1)) if wcsname in wnames.values(): uniq = False return uniq
python
def verifyUniqueWcsname(fname,wcsname): """ Report whether or not the specified WCSNAME already exists in the file """ uniq = True numsci,extname = count_sci_extensions(fname) wnames = altwcs.wcsnames(fname,ext=(extname,1)) if wcsname in wnames.values(): uniq = False return uniq
[ "def", "verifyUniqueWcsname", "(", "fname", ",", "wcsname", ")", ":", "uniq", "=", "True", "numsci", ",", "extname", "=", "count_sci_extensions", "(", "fname", ")", "wnames", "=", "altwcs", ".", "wcsnames", "(", "fname", ",", "ext", "=", "(", "extname", ...
Report whether or not the specified WCSNAME already exists in the file
[ "Report", "whether", "or", "not", "the", "specified", "WCSNAME", "already", "exists", "in", "the", "file" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L471-L482
train
35,535
spacetelescope/drizzlepac
drizzlepac/util.py
verifyUpdatewcs
def verifyUpdatewcs(fname): """ Verify the existence of WCSNAME in the file. If it is not present, report this to the user and raise an exception. Returns True if WCSNAME was found in all SCI extensions. """ updated = True numsci,extname = count_sci_extensions(fname) for n in range(1,numsci+1): hdr = fits.getheader(fname, extname=extname, extver=n, memmap=False) if 'wcsname' not in hdr: updated = False break return updated
python
def verifyUpdatewcs(fname): """ Verify the existence of WCSNAME in the file. If it is not present, report this to the user and raise an exception. Returns True if WCSNAME was found in all SCI extensions. """ updated = True numsci,extname = count_sci_extensions(fname) for n in range(1,numsci+1): hdr = fits.getheader(fname, extname=extname, extver=n, memmap=False) if 'wcsname' not in hdr: updated = False break return updated
[ "def", "verifyUpdatewcs", "(", "fname", ")", ":", "updated", "=", "True", "numsci", ",", "extname", "=", "count_sci_extensions", "(", "fname", ")", "for", "n", "in", "range", "(", "1", ",", "numsci", "+", "1", ")", ":", "hdr", "=", "fits", ".", "geth...
Verify the existence of WCSNAME in the file. If it is not present, report this to the user and raise an exception. Returns True if WCSNAME was found in all SCI extensions.
[ "Verify", "the", "existence", "of", "WCSNAME", "in", "the", "file", ".", "If", "it", "is", "not", "present", "report", "this", "to", "the", "user", "and", "raise", "an", "exception", ".", "Returns", "True", "if", "WCSNAME", "was", "found", "in", "all", ...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L484-L497
train
35,536
spacetelescope/drizzlepac
drizzlepac/util.py
verifyRefimage
def verifyRefimage(refimage): """ Verify that the value of refimage specified by the user points to an extension with a proper WCS defined. It starts by making sure an extension gets specified by the user when using a MEF file. The final check comes by looking for a CD matrix in the WCS object itself. If either test fails, it returns a value of False. """ valid = True # start by trying to see whether the code can even find the file if is_blank(refimage): valid=True return valid refroot,extroot = fileutil.parseFilename(refimage) if not os.path.exists(refroot): valid = False return valid # if a MEF has been specified, make sure extension contains a valid WCS if valid: if extroot is None: extn = findWCSExtn(refimage) if extn is None: valid = False else: valid = True else: # check for CD matrix in WCS object refwcs = wcsutil.HSTWCS(refimage) if not refwcs.wcs.has_cd(): valid = False else: valid = True del refwcs return valid
python
def verifyRefimage(refimage): """ Verify that the value of refimage specified by the user points to an extension with a proper WCS defined. It starts by making sure an extension gets specified by the user when using a MEF file. The final check comes by looking for a CD matrix in the WCS object itself. If either test fails, it returns a value of False. """ valid = True # start by trying to see whether the code can even find the file if is_blank(refimage): valid=True return valid refroot,extroot = fileutil.parseFilename(refimage) if not os.path.exists(refroot): valid = False return valid # if a MEF has been specified, make sure extension contains a valid WCS if valid: if extroot is None: extn = findWCSExtn(refimage) if extn is None: valid = False else: valid = True else: # check for CD matrix in WCS object refwcs = wcsutil.HSTWCS(refimage) if not refwcs.wcs.has_cd(): valid = False else: valid = True del refwcs return valid
[ "def", "verifyRefimage", "(", "refimage", ")", ":", "valid", "=", "True", "# start by trying to see whether the code can even find the file", "if", "is_blank", "(", "refimage", ")", ":", "valid", "=", "True", "return", "valid", "refroot", ",", "extroot", "=", "fileu...
Verify that the value of refimage specified by the user points to an extension with a proper WCS defined. It starts by making sure an extension gets specified by the user when using a MEF file. The final check comes by looking for a CD matrix in the WCS object itself. If either test fails, it returns a value of False.
[ "Verify", "that", "the", "value", "of", "refimage", "specified", "by", "the", "user", "points", "to", "an", "extension", "with", "a", "proper", "WCS", "defined", ".", "It", "starts", "by", "making", "sure", "an", "extension", "gets", "specified", "by", "th...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L499-L536
train
35,537
spacetelescope/drizzlepac
drizzlepac/util.py
findWCSExtn
def findWCSExtn(filename): """ Return new filename with extension that points to an extension with a valid WCS. Returns ======= extnum : str, None Value of extension name as a string either as provided by the user or based on the extension number for the first extension which contains a valid HSTWCS object. Returns None if no extension can be found with a valid WCS. Notes ===== The return value from this function can be used as input to create another HSTWCS with the syntax:: `HSTWCS('{}[{}]'.format(filename,extnum)) """ rootname,extroot = fileutil.parseFilename(filename) extnum = None if extroot is None: fimg = fits.open(rootname, memmap=False) for i,extn in enumerate(fimg): if 'crval1' in extn.header: refwcs = wcsutil.HSTWCS('{}[{}]'.format(rootname,i)) if refwcs.wcs.has_cd(): extnum = '{}'.format(i) break fimg.close() else: try: refwcs = wcsutil.HSTWCS(filename) if refwcs.wcs.has_cd(): extnum = extroot except: extnum = None return extnum
python
def findWCSExtn(filename): """ Return new filename with extension that points to an extension with a valid WCS. Returns ======= extnum : str, None Value of extension name as a string either as provided by the user or based on the extension number for the first extension which contains a valid HSTWCS object. Returns None if no extension can be found with a valid WCS. Notes ===== The return value from this function can be used as input to create another HSTWCS with the syntax:: `HSTWCS('{}[{}]'.format(filename,extnum)) """ rootname,extroot = fileutil.parseFilename(filename) extnum = None if extroot is None: fimg = fits.open(rootname, memmap=False) for i,extn in enumerate(fimg): if 'crval1' in extn.header: refwcs = wcsutil.HSTWCS('{}[{}]'.format(rootname,i)) if refwcs.wcs.has_cd(): extnum = '{}'.format(i) break fimg.close() else: try: refwcs = wcsutil.HSTWCS(filename) if refwcs.wcs.has_cd(): extnum = extroot except: extnum = None return extnum
[ "def", "findWCSExtn", "(", "filename", ")", ":", "rootname", ",", "extroot", "=", "fileutil", ".", "parseFilename", "(", "filename", ")", "extnum", "=", "None", "if", "extroot", "is", "None", ":", "fimg", "=", "fits", ".", "open", "(", "rootname", ",", ...
Return new filename with extension that points to an extension with a valid WCS. Returns ======= extnum : str, None Value of extension name as a string either as provided by the user or based on the extension number for the first extension which contains a valid HSTWCS object. Returns None if no extension can be found with a valid WCS. Notes ===== The return value from this function can be used as input to create another HSTWCS with the syntax:: `HSTWCS('{}[{}]'.format(filename,extnum))
[ "Return", "new", "filename", "with", "extension", "that", "points", "to", "an", "extension", "with", "a", "valid", "WCS", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L538-L577
train
35,538
spacetelescope/drizzlepac
drizzlepac/util.py
verifyFilePermissions
def verifyFilePermissions(filelist, chmod=True): """ Verify that images specified in 'filelist' can be updated. A message will be printed reporting the names of any images which do not have write-permission, then quit. """ badfiles = [] archive_dir = False for img in filelist: fname = fileutil.osfn(img) if 'OrIg_files' in os.path.split(fname)[0]: archive_dir = True try: fp = open(fname,mode='a') fp.close() except IOError as e: if e.errno == errno.EACCES: badfiles.append(img) # Not a permission error. pass num_bad = len(badfiles) if num_bad > 0: if archive_dir: print('\n') print('#'*40) print(' Working in "OrIg_files" (archive) directory. ') print(' This directory has been created to serve as an archive') print(' for the original input images. ') print('\n These files should be copied into another directory') print(' for processing. ') print('#'*40) print('\n') print('#'*40) print('Found %d files which can not be updated!'%(num_bad)) for img in badfiles: print(' %s'%(img)) print('\nPlease reset permissions for these files and restart...') print('#'*40) print('\n') filelist = None return filelist
python
def verifyFilePermissions(filelist, chmod=True): """ Verify that images specified in 'filelist' can be updated. A message will be printed reporting the names of any images which do not have write-permission, then quit. """ badfiles = [] archive_dir = False for img in filelist: fname = fileutil.osfn(img) if 'OrIg_files' in os.path.split(fname)[0]: archive_dir = True try: fp = open(fname,mode='a') fp.close() except IOError as e: if e.errno == errno.EACCES: badfiles.append(img) # Not a permission error. pass num_bad = len(badfiles) if num_bad > 0: if archive_dir: print('\n') print('#'*40) print(' Working in "OrIg_files" (archive) directory. ') print(' This directory has been created to serve as an archive') print(' for the original input images. ') print('\n These files should be copied into another directory') print(' for processing. ') print('#'*40) print('\n') print('#'*40) print('Found %d files which can not be updated!'%(num_bad)) for img in badfiles: print(' %s'%(img)) print('\nPlease reset permissions for these files and restart...') print('#'*40) print('\n') filelist = None return filelist
[ "def", "verifyFilePermissions", "(", "filelist", ",", "chmod", "=", "True", ")", ":", "badfiles", "=", "[", "]", "archive_dir", "=", "False", "for", "img", "in", "filelist", ":", "fname", "=", "fileutil", ".", "osfn", "(", "img", ")", "if", "'OrIg_files'...
Verify that images specified in 'filelist' can be updated. A message will be printed reporting the names of any images which do not have write-permission, then quit.
[ "Verify", "that", "images", "specified", "in", "filelist", "can", "be", "updated", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L580-L623
train
35,539
spacetelescope/drizzlepac
drizzlepac/util.py
getFullParList
def getFullParList(configObj): """ Return a single list of all parameter names included in the configObj regardless of which section the parameter was stored """ plist = [] for par in configObj.keys(): if isinstance(configObj[par],configobj.Section): plist.extend(getFullParList(configObj[par])) else: plist.append(par) return plist
python
def getFullParList(configObj): """ Return a single list of all parameter names included in the configObj regardless of which section the parameter was stored """ plist = [] for par in configObj.keys(): if isinstance(configObj[par],configobj.Section): plist.extend(getFullParList(configObj[par])) else: plist.append(par) return plist
[ "def", "getFullParList", "(", "configObj", ")", ":", "plist", "=", "[", "]", "for", "par", "in", "configObj", ".", "keys", "(", ")", ":", "if", "isinstance", "(", "configObj", "[", "par", "]", ",", "configobj", ".", "Section", ")", ":", "plist", ".",...
Return a single list of all parameter names included in the configObj regardless of which section the parameter was stored
[ "Return", "a", "single", "list", "of", "all", "parameter", "names", "included", "in", "the", "configObj", "regardless", "of", "which", "section", "the", "parameter", "was", "stored" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L625-L636
train
35,540
spacetelescope/drizzlepac
drizzlepac/util.py
validateUserPars
def validateUserPars(configObj,input_dict): """ Compares input parameter names specified by user with those already recognized by the task. Any parameters provided by the user that does not match a known task parameter will be reported and a ValueError exception will be raised. """ # check to see whether any input parameters are unexpected. # Any unexpected parameters provided on input should be reported and # the code should stop plist = getFullParList(configObj) extra_pars = [] for kw in input_dict: if kw not in plist: extra_pars.append(kw) if len(extra_pars) > 0: print ('='*40) print ('The following input parameters were not recognized as valid inputs:') for p in extra_pars: print(" %s"%(p)) print('\nPlease check the spelling of the parameter(s) and try again...') print('='*40) raise ValueError
python
def validateUserPars(configObj,input_dict): """ Compares input parameter names specified by user with those already recognized by the task. Any parameters provided by the user that does not match a known task parameter will be reported and a ValueError exception will be raised. """ # check to see whether any input parameters are unexpected. # Any unexpected parameters provided on input should be reported and # the code should stop plist = getFullParList(configObj) extra_pars = [] for kw in input_dict: if kw not in plist: extra_pars.append(kw) if len(extra_pars) > 0: print ('='*40) print ('The following input parameters were not recognized as valid inputs:') for p in extra_pars: print(" %s"%(p)) print('\nPlease check the spelling of the parameter(s) and try again...') print('='*40) raise ValueError
[ "def", "validateUserPars", "(", "configObj", ",", "input_dict", ")", ":", "# check to see whether any input parameters are unexpected.", "# Any unexpected parameters provided on input should be reported and", "# the code should stop", "plist", "=", "getFullParList", "(", "configObj", ...
Compares input parameter names specified by user with those already recognized by the task. Any parameters provided by the user that does not match a known task parameter will be reported and a ValueError exception will be raised.
[ "Compares", "input", "parameter", "names", "specified", "by", "user", "with", "those", "already", "recognized", "by", "the", "task", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L638-L661
train
35,541
spacetelescope/drizzlepac
drizzlepac/util.py
applyUserPars_steps
def applyUserPars_steps(configObj, input_dict, step='3a'): """ Apply logic to turn on use of user-specified output WCS if user provides any parameter on command-line regardless of how final_wcs was set. """ step_kws = {'7a': 'final_wcs', '3a': 'driz_sep_wcs'} stepname = getSectionName(configObj,step) finalParDict = configObj[stepname].copy() del finalParDict[step_kws[step]] # interpret input_dict to find any parameters for this step specified by the user user_pars = {} for kw in finalParDict: if kw in input_dict: user_pars[kw] = input_dict[kw] if len(user_pars) > 0: configObj[stepname][step_kws[step]] = True
python
def applyUserPars_steps(configObj, input_dict, step='3a'): """ Apply logic to turn on use of user-specified output WCS if user provides any parameter on command-line regardless of how final_wcs was set. """ step_kws = {'7a': 'final_wcs', '3a': 'driz_sep_wcs'} stepname = getSectionName(configObj,step) finalParDict = configObj[stepname].copy() del finalParDict[step_kws[step]] # interpret input_dict to find any parameters for this step specified by the user user_pars = {} for kw in finalParDict: if kw in input_dict: user_pars[kw] = input_dict[kw] if len(user_pars) > 0: configObj[stepname][step_kws[step]] = True
[ "def", "applyUserPars_steps", "(", "configObj", ",", "input_dict", ",", "step", "=", "'3a'", ")", ":", "step_kws", "=", "{", "'7a'", ":", "'final_wcs'", ",", "'3a'", ":", "'driz_sep_wcs'", "}", "stepname", "=", "getSectionName", "(", "configObj", ",", "step"...
Apply logic to turn on use of user-specified output WCS if user provides any parameter on command-line regardless of how final_wcs was set.
[ "Apply", "logic", "to", "turn", "on", "use", "of", "user", "-", "specified", "output", "WCS", "if", "user", "provides", "any", "parameter", "on", "command", "-", "line", "regardless", "of", "how", "final_wcs", "was", "set", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L663-L677
train
35,542
spacetelescope/drizzlepac
drizzlepac/util.py
getDefaultConfigObj
def getDefaultConfigObj(taskname,configObj,input_dict={},loadOnly=True): """ Return default configObj instance for task updated with user-specified values from input_dict. Parameters ---------- taskname : string Name of task to load into TEAL configObj : string The valid values for 'configObj' would be:: None - loads last saved user .cfg file 'defaults' - loads task default .cfg file name of .cfg file (string)- loads user-specified .cfg file input_dict : dict Set of parameters and values specified by user to be different from what gets loaded in from the .cfg file for the task loadOnly : bool Setting 'loadOnly' to False causes the TEAL GUI to start allowing the user to edit the values further and then run the task if desired. """ if configObj is None: # Start by grabbing the default values without using the GUI # This insures that all subsequent use of the configObj includes # all parameters and their last saved values configObj = teal.load(taskname) elif isinstance(configObj,str): if configObj.lower().strip() == 'defaults': # Load task default .cfg file with all default values configObj = teal.load(taskname,defaults=True) # define default filename for configObj configObj.filename = taskname.lower()+'.cfg' else: # Load user-specified .cfg file with its special default values # we need to call 'fileutil.osfn()' to insure all environment # variables specified by the user in the configObj filename are # expanded to the full path configObj = teal.load(fileutil.osfn(configObj)) # merge in the user values for this run # this, though, does not save the results for use later if input_dict not in [None,{}]:# and configObj not in [None, {}]: # check to see whether any input parameters are unexpected. # Any unexpected parameters provided on input should be reported and # the code should stop validateUserPars(configObj,input_dict) # If everything looks good, merge user inputs with configObj and continue cfgpars.mergeConfigObj(configObj, input_dict) # Update the input .cfg file with the updated parameter values #configObj.filename = os.path.join(cfgpars.getAppDir(),os.path.basename(configObj.filename)) #configObj.write() if not loadOnly: # We want to run the GUI AFTER merging in any parameters # specified by the user on the command-line and provided in # input_dict configObj = teal.teal(configObj,loadOnly=False) return configObj
python
def getDefaultConfigObj(taskname,configObj,input_dict={},loadOnly=True): """ Return default configObj instance for task updated with user-specified values from input_dict. Parameters ---------- taskname : string Name of task to load into TEAL configObj : string The valid values for 'configObj' would be:: None - loads last saved user .cfg file 'defaults' - loads task default .cfg file name of .cfg file (string)- loads user-specified .cfg file input_dict : dict Set of parameters and values specified by user to be different from what gets loaded in from the .cfg file for the task loadOnly : bool Setting 'loadOnly' to False causes the TEAL GUI to start allowing the user to edit the values further and then run the task if desired. """ if configObj is None: # Start by grabbing the default values without using the GUI # This insures that all subsequent use of the configObj includes # all parameters and their last saved values configObj = teal.load(taskname) elif isinstance(configObj,str): if configObj.lower().strip() == 'defaults': # Load task default .cfg file with all default values configObj = teal.load(taskname,defaults=True) # define default filename for configObj configObj.filename = taskname.lower()+'.cfg' else: # Load user-specified .cfg file with its special default values # we need to call 'fileutil.osfn()' to insure all environment # variables specified by the user in the configObj filename are # expanded to the full path configObj = teal.load(fileutil.osfn(configObj)) # merge in the user values for this run # this, though, does not save the results for use later if input_dict not in [None,{}]:# and configObj not in [None, {}]: # check to see whether any input parameters are unexpected. # Any unexpected parameters provided on input should be reported and # the code should stop validateUserPars(configObj,input_dict) # If everything looks good, merge user inputs with configObj and continue cfgpars.mergeConfigObj(configObj, input_dict) # Update the input .cfg file with the updated parameter values #configObj.filename = os.path.join(cfgpars.getAppDir(),os.path.basename(configObj.filename)) #configObj.write() if not loadOnly: # We want to run the GUI AFTER merging in any parameters # specified by the user on the command-line and provided in # input_dict configObj = teal.teal(configObj,loadOnly=False) return configObj
[ "def", "getDefaultConfigObj", "(", "taskname", ",", "configObj", ",", "input_dict", "=", "{", "}", ",", "loadOnly", "=", "True", ")", ":", "if", "configObj", "is", "None", ":", "# Start by grabbing the default values without using the GUI", "# This insures that all subs...
Return default configObj instance for task updated with user-specified values from input_dict. Parameters ---------- taskname : string Name of task to load into TEAL configObj : string The valid values for 'configObj' would be:: None - loads last saved user .cfg file 'defaults' - loads task default .cfg file name of .cfg file (string)- loads user-specified .cfg file input_dict : dict Set of parameters and values specified by user to be different from what gets loaded in from the .cfg file for the task loadOnly : bool Setting 'loadOnly' to False causes the TEAL GUI to start allowing the user to edit the values further and then run the task if desired.
[ "Return", "default", "configObj", "instance", "for", "task", "updated", "with", "user", "-", "specified", "values", "from", "input_dict", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L680-L743
train
35,543
spacetelescope/drizzlepac
drizzlepac/util.py
getSectionName
def getSectionName(configObj,stepnum): """ Return section label based on step number. """ for key in configObj.keys(): if key.find('STEP '+str(stepnum)+':') >= 0: return key
python
def getSectionName(configObj,stepnum): """ Return section label based on step number. """ for key in configObj.keys(): if key.find('STEP '+str(stepnum)+':') >= 0: return key
[ "def", "getSectionName", "(", "configObj", ",", "stepnum", ")", ":", "for", "key", "in", "configObj", ".", "keys", "(", ")", ":", "if", "key", ".", "find", "(", "'STEP '", "+", "str", "(", "stepnum", ")", "+", "':'", ")", ">=", "0", ":", "return", ...
Return section label based on step number.
[ "Return", "section", "label", "based", "on", "step", "number", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L745-L750
train
35,544
spacetelescope/drizzlepac
drizzlepac/util.py
displayMakewcsWarningBox
def displayMakewcsWarningBox(display=True, parent=None): """ Displays a warning box for the 'makewcs' parameter. """ if sys.version_info[0] >= 3: from tkinter.messagebox import showwarning else: from tkMessageBox import showwarning ans = {'yes':True,'no':False} if ans[display]: msg = 'Setting "updatewcs=yes" will result '+ \ 'in all input WCS values to be recomputed '+ \ 'using the original distortion model and alignment.' showwarning(parent=parent,message=msg, title="WCS will be overwritten!") return True
python
def displayMakewcsWarningBox(display=True, parent=None): """ Displays a warning box for the 'makewcs' parameter. """ if sys.version_info[0] >= 3: from tkinter.messagebox import showwarning else: from tkMessageBox import showwarning ans = {'yes':True,'no':False} if ans[display]: msg = 'Setting "updatewcs=yes" will result '+ \ 'in all input WCS values to be recomputed '+ \ 'using the original distortion model and alignment.' showwarning(parent=parent,message=msg, title="WCS will be overwritten!") return True
[ "def", "displayMakewcsWarningBox", "(", "display", "=", "True", ",", "parent", "=", "None", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "from", "tkinter", ".", "messagebox", "import", "showwarning", "else", ":", "from", "tk...
Displays a warning box for the 'makewcs' parameter.
[ "Displays", "a", "warning", "box", "for", "the", "makewcs", "parameter", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L758-L772
train
35,545
spacetelescope/drizzlepac
drizzlepac/util.py
printParams
def printParams(paramDictionary, all=False, log=None): """ Print nicely the parameters from the dictionary. """ if log is not None: def output(msg): log.info(msg) else: def output(msg): print(msg) if not paramDictionary: output('No parameters were supplied') else: for key in sorted(paramDictionary): if all or (not isinstance(paramDictionary[key], dict)) \ and key[0] != '_': output('\t' + '\t'.join([str(key) + ' :', str(paramDictionary[key])])) if log is None: output('\n')
python
def printParams(paramDictionary, all=False, log=None): """ Print nicely the parameters from the dictionary. """ if log is not None: def output(msg): log.info(msg) else: def output(msg): print(msg) if not paramDictionary: output('No parameters were supplied') else: for key in sorted(paramDictionary): if all or (not isinstance(paramDictionary[key], dict)) \ and key[0] != '_': output('\t' + '\t'.join([str(key) + ' :', str(paramDictionary[key])])) if log is None: output('\n')
[ "def", "printParams", "(", "paramDictionary", ",", "all", "=", "False", ",", "log", "=", "None", ")", ":", "if", "log", "is", "not", "None", ":", "def", "output", "(", "msg", ")", ":", "log", ".", "info", "(", "msg", ")", "else", ":", "def", "out...
Print nicely the parameters from the dictionary.
[ "Print", "nicely", "the", "parameters", "from", "the", "dictionary", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L799-L820
train
35,546
spacetelescope/drizzlepac
drizzlepac/util.py
isCommaList
def isCommaList(inputFilelist): """Return True if the input is a comma separated list of names.""" if isinstance(inputFilelist, int) or isinstance(inputFilelist, np.int32): ilist = str(inputFilelist) else: ilist = inputFilelist if "," in ilist: return True return False
python
def isCommaList(inputFilelist): """Return True if the input is a comma separated list of names.""" if isinstance(inputFilelist, int) or isinstance(inputFilelist, np.int32): ilist = str(inputFilelist) else: ilist = inputFilelist if "," in ilist: return True return False
[ "def", "isCommaList", "(", "inputFilelist", ")", ":", "if", "isinstance", "(", "inputFilelist", ",", "int", ")", "or", "isinstance", "(", "inputFilelist", ",", "np", ".", "int32", ")", ":", "ilist", "=", "str", "(", "inputFilelist", ")", "else", ":", "il...
Return True if the input is a comma separated list of names.
[ "Return", "True", "if", "the", "input", "is", "a", "comma", "separated", "list", "of", "names", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L860-L868
train
35,547
spacetelescope/drizzlepac
drizzlepac/util.py
loadFileList
def loadFileList(inputFilelist): """Open up the '@ file' and read in the science and possible ivm filenames from the first two columns. """ f = open(inputFilelist[1:]) # check the first line in order to determine whether # IVM files have been specified in a second column... lines = f.readline() f.close() # 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=atfile_ivm) # Parse the @-file with irafglob to extract the input filename filelist = irafglob.irafglob(input, atfile=atfile_sci) return filelist
python
def loadFileList(inputFilelist): """Open up the '@ file' and read in the science and possible ivm filenames from the first two columns. """ f = open(inputFilelist[1:]) # check the first line in order to determine whether # IVM files have been specified in a second column... lines = f.readline() f.close() # 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=atfile_ivm) # Parse the @-file with irafglob to extract the input filename filelist = irafglob.irafglob(input, atfile=atfile_sci) return filelist
[ "def", "loadFileList", "(", "inputFilelist", ")", ":", "f", "=", "open", "(", "inputFilelist", "[", "1", ":", "]", ")", "# check the first line in order to determine whether", "# IVM files have been specified in a second column...", "lines", "=", "f", ".", "readline", "...
Open up the '@ file' and read in the science and possible ivm filenames from the first two columns.
[ "Open", "up", "the" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L870-L887
train
35,548
spacetelescope/drizzlepac
drizzlepac/util.py
readCommaList
def readCommaList(fileList): """ Return a list of the files with the commas removed. """ names=fileList.split(',') fileList=[] for item in names: fileList.append(item) return fileList
python
def readCommaList(fileList): """ Return a list of the files with the commas removed. """ names=fileList.split(',') fileList=[] for item in names: fileList.append(item) return fileList
[ "def", "readCommaList", "(", "fileList", ")", ":", "names", "=", "fileList", ".", "split", "(", "','", ")", "fileList", "=", "[", "]", "for", "item", "in", "names", ":", "fileList", ".", "append", "(", "item", ")", "return", "fileList" ]
Return a list of the files with the commas removed.
[ "Return", "a", "list", "of", "the", "files", "with", "the", "commas", "removed", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L890-L896
train
35,549
spacetelescope/drizzlepac
drizzlepac/util.py
update_input
def update_input(filelist, ivmlist=None, removed_files=None): """ Removes files flagged to be removed from the input filelist. Removes the corresponding ivm files if present. """ newfilelist = [] if removed_files == []: return filelist, ivmlist else: sci_ivm = list(zip(filelist, ivmlist)) for f in removed_files: result=[sci_ivm.remove(t) for t in sci_ivm if t[0] == f ] ivmlist = [el[1] for el in sci_ivm] newfilelist = [el[0] for el in sci_ivm] return newfilelist, ivmlist
python
def update_input(filelist, ivmlist=None, removed_files=None): """ Removes files flagged to be removed from the input filelist. Removes the corresponding ivm files if present. """ newfilelist = [] if removed_files == []: return filelist, ivmlist else: sci_ivm = list(zip(filelist, ivmlist)) for f in removed_files: result=[sci_ivm.remove(t) for t in sci_ivm if t[0] == f ] ivmlist = [el[1] for el in sci_ivm] newfilelist = [el[0] for el in sci_ivm] return newfilelist, ivmlist
[ "def", "update_input", "(", "filelist", ",", "ivmlist", "=", "None", ",", "removed_files", "=", "None", ")", ":", "newfilelist", "=", "[", "]", "if", "removed_files", "==", "[", "]", ":", "return", "filelist", ",", "ivmlist", "else", ":", "sci_ivm", "=",...
Removes files flagged to be removed from the input filelist. Removes the corresponding ivm files if present.
[ "Removes", "files", "flagged", "to", "be", "removed", "from", "the", "input", "filelist", ".", "Removes", "the", "corresponding", "ivm", "files", "if", "present", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L920-L935
train
35,550
spacetelescope/drizzlepac
drizzlepac/util.py
get_expstart
def get_expstart(header,primary_hdr): """shouldn't this just be defined in the instrument subclass of imageobject?""" if 'expstart' in primary_hdr: exphdr = primary_hdr else: exphdr = header if 'EXPSTART' in exphdr: expstart = float(exphdr['EXPSTART']) expend = float(exphdr['EXPEND']) else: expstart = 0. expend = 0.0 return (expstart,expend)
python
def get_expstart(header,primary_hdr): """shouldn't this just be defined in the instrument subclass of imageobject?""" if 'expstart' in primary_hdr: exphdr = primary_hdr else: exphdr = header if 'EXPSTART' in exphdr: expstart = float(exphdr['EXPSTART']) expend = float(exphdr['EXPEND']) else: expstart = 0. expend = 0.0 return (expstart,expend)
[ "def", "get_expstart", "(", "header", ",", "primary_hdr", ")", ":", "if", "'expstart'", "in", "primary_hdr", ":", "exphdr", "=", "primary_hdr", "else", ":", "exphdr", "=", "header", "if", "'EXPSTART'", "in", "exphdr", ":", "expstart", "=", "float", "(", "e...
shouldn't this just be defined in the instrument subclass of imageobject?
[ "shouldn", "t", "this", "just", "be", "defined", "in", "the", "instrument", "subclass", "of", "imageobject?" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L967-L982
train
35,551
spacetelescope/drizzlepac
drizzlepac/util.py
compute_texptime
def compute_texptime(imageObjectList): """ Add up the exposure time for all the members in the pattern, since 'drizzle' doesn't have the necessary information to correctly set this itself. """ expnames = [] exptimes = [] start = [] end = [] for img in imageObjectList: expnames += img.getKeywordList('_expname') exptimes += img.getKeywordList('_exptime') start += img.getKeywordList('_expstart') end += img.getKeywordList('_expend') exptime = 0. expstart = min(start) expend = max(end) exposure = None for n in range(len(expnames)): if expnames[n] != exposure: exposure = expnames[n] exptime += exptimes[n] return (exptime,expstart,expend)
python
def compute_texptime(imageObjectList): """ Add up the exposure time for all the members in the pattern, since 'drizzle' doesn't have the necessary information to correctly set this itself. """ expnames = [] exptimes = [] start = [] end = [] for img in imageObjectList: expnames += img.getKeywordList('_expname') exptimes += img.getKeywordList('_exptime') start += img.getKeywordList('_expstart') end += img.getKeywordList('_expend') exptime = 0. expstart = min(start) expend = max(end) exposure = None for n in range(len(expnames)): if expnames[n] != exposure: exposure = expnames[n] exptime += exptimes[n] return (exptime,expstart,expend)
[ "def", "compute_texptime", "(", "imageObjectList", ")", ":", "expnames", "=", "[", "]", "exptimes", "=", "[", "]", "start", "=", "[", "]", "end", "=", "[", "]", "for", "img", "in", "imageObjectList", ":", "expnames", "+=", "img", ".", "getKeywordList", ...
Add up the exposure time for all the members in the pattern, since 'drizzle' doesn't have the necessary information to correctly set this itself.
[ "Add", "up", "the", "exposure", "time", "for", "all", "the", "members", "in", "the", "pattern", "since", "drizzle", "doesn", "t", "have", "the", "necessary", "information", "to", "correctly", "set", "this", "itself", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L984-L1009
train
35,552
spacetelescope/drizzlepac
drizzlepac/util.py
computeRange
def computeRange(corners): """ Determine the range spanned by an array of pixel positions. """ x = corners[:, 0] y = corners[:, 1] _xrange = (np.minimum.reduce(x), np.maximum.reduce(x)) _yrange = (np.minimum.reduce(y), np.maximum.reduce(y)) return _xrange, _yrange
python
def computeRange(corners): """ Determine the range spanned by an array of pixel positions. """ x = corners[:, 0] y = corners[:, 1] _xrange = (np.minimum.reduce(x), np.maximum.reduce(x)) _yrange = (np.minimum.reduce(y), np.maximum.reduce(y)) return _xrange, _yrange
[ "def", "computeRange", "(", "corners", ")", ":", "x", "=", "corners", "[", ":", ",", "0", "]", "y", "=", "corners", "[", ":", ",", "1", "]", "_xrange", "=", "(", "np", ".", "minimum", ".", "reduce", "(", "x", ")", ",", "np", ".", "maximum", "...
Determine the range spanned by an array of pixel positions.
[ "Determine", "the", "range", "spanned", "by", "an", "array", "of", "pixel", "positions", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L1012-L1018
train
35,553
spacetelescope/drizzlepac
drizzlepac/util.py
readcols
def readcols(infile, cols=[0, 1, 2, 3], hms=False): """ Read the columns from an ASCII file as numpy arrays. Parameters ---------- infile : str Filename of ASCII file with array data as columns. cols : list of int List of 0-indexed column numbers for columns to be turned into numpy arrays (DEFAULT- [0,1,2,3]). Returns ------- outarr : list of numpy arrays Simple list of numpy arrays in the order as specifed in the 'cols' parameter. """ fin = open(infile,'r') outarr = [] for l in fin.readlines(): l = l.strip() if len(l) == 0 or len(l.split()) < len(cols) or (len(l) > 0 and l[0] == '#' or (l.find("INDEF") > -1)): continue for i in range(10): lnew = l.replace(" "," ") if lnew == l: break else: l = lnew lspl = lnew.split(" ") if len(outarr) == 0: for c in range(len(cols)): outarr.append([]) for c,n in zip(cols,list(range(len(cols)))): if not hms: val = float(lspl[c]) else: val = lspl[c] outarr[n].append(val) fin.close() for n in range(len(cols)): outarr[n] = np.array(outarr[n]) return outarr
python
def readcols(infile, cols=[0, 1, 2, 3], hms=False): """ Read the columns from an ASCII file as numpy arrays. Parameters ---------- infile : str Filename of ASCII file with array data as columns. cols : list of int List of 0-indexed column numbers for columns to be turned into numpy arrays (DEFAULT- [0,1,2,3]). Returns ------- outarr : list of numpy arrays Simple list of numpy arrays in the order as specifed in the 'cols' parameter. """ fin = open(infile,'r') outarr = [] for l in fin.readlines(): l = l.strip() if len(l) == 0 or len(l.split()) < len(cols) or (len(l) > 0 and l[0] == '#' or (l.find("INDEF") > -1)): continue for i in range(10): lnew = l.replace(" "," ") if lnew == l: break else: l = lnew lspl = lnew.split(" ") if len(outarr) == 0: for c in range(len(cols)): outarr.append([]) for c,n in zip(cols,list(range(len(cols)))): if not hms: val = float(lspl[c]) else: val = lspl[c] outarr[n].append(val) fin.close() for n in range(len(cols)): outarr[n] = np.array(outarr[n]) return outarr
[ "def", "readcols", "(", "infile", ",", "cols", "=", "[", "0", ",", "1", ",", "2", ",", "3", "]", ",", "hms", "=", "False", ")", ":", "fin", "=", "open", "(", "infile", ",", "'r'", ")", "outarr", "=", "[", "]", "for", "l", "in", "fin", ".", ...
Read the columns from an ASCII file as numpy arrays. Parameters ---------- infile : str Filename of ASCII file with array data as columns. cols : list of int List of 0-indexed column numbers for columns to be turned into numpy arrays (DEFAULT- [0,1,2,3]). Returns ------- outarr : list of numpy arrays Simple list of numpy arrays in the order as specifed in the 'cols' parameter.
[ "Read", "the", "columns", "from", "an", "ASCII", "file", "as", "numpy", "arrays", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L1034-L1077
train
35,554
spacetelescope/drizzlepac
drizzlepac/util.py
parse_colnames
def parse_colnames(colnames,coords=None): """ Convert colnames input into list of column numbers. """ cols = [] if not isinstance(colnames,list): colnames = colnames.split(',') # parse column names from coords file and match to input values if coords is not None and fileutil.isFits(coords)[0]: # Open FITS file with table ftab = fits.open(coords, memmap=False) # determine which extension has the table for extn in ftab: if isinstance(extn, fits.BinTableHDU): # parse column names from table and match to inputs cnames = extn.columns.names if colnames is not None: for c in colnames: for name,i in zip(cnames,list(range(len(cnames)))): if c == name.lower(): cols.append(i) if len(cols) < len(colnames): errmsg = "Not all input columns found in table..." ftab.close() raise ValueError(errmsg) else: cols = cnames[:2] break ftab.close() else: for c in colnames: if isinstance(c, str): if c[0].lower() == 'c': cols.append(int(c[1:])-1) else: cols.append(int(c)) else: if isinstance(c, int): cols.append(c) else: errmsg = "Unsupported column names..." raise ValueError(errmsg) return cols
python
def parse_colnames(colnames,coords=None): """ Convert colnames input into list of column numbers. """ cols = [] if not isinstance(colnames,list): colnames = colnames.split(',') # parse column names from coords file and match to input values if coords is not None and fileutil.isFits(coords)[0]: # Open FITS file with table ftab = fits.open(coords, memmap=False) # determine which extension has the table for extn in ftab: if isinstance(extn, fits.BinTableHDU): # parse column names from table and match to inputs cnames = extn.columns.names if colnames is not None: for c in colnames: for name,i in zip(cnames,list(range(len(cnames)))): if c == name.lower(): cols.append(i) if len(cols) < len(colnames): errmsg = "Not all input columns found in table..." ftab.close() raise ValueError(errmsg) else: cols = cnames[:2] break ftab.close() else: for c in colnames: if isinstance(c, str): if c[0].lower() == 'c': cols.append(int(c[1:])-1) else: cols.append(int(c)) else: if isinstance(c, int): cols.append(c) else: errmsg = "Unsupported column names..." raise ValueError(errmsg) return cols
[ "def", "parse_colnames", "(", "colnames", ",", "coords", "=", "None", ")", ":", "cols", "=", "[", "]", "if", "not", "isinstance", "(", "colnames", ",", "list", ")", ":", "colnames", "=", "colnames", ".", "split", "(", "','", ")", "# parse column names fr...
Convert colnames input into list of column numbers.
[ "Convert", "colnames", "input", "into", "list", "of", "column", "numbers", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L1079-L1118
train
35,555
spacetelescope/drizzlepac
drizzlepac/util.py
createFile
def createFile(dataArray=None, outfile=None, header=None): """ Create a simple fits file for the given data array and header. Returns either the FITS object in-membory when outfile==None or None when the FITS file was written out to a file. """ # Insure that at least a data-array has been provided to create the file assert(dataArray is not None), "Please supply a data array for createFiles" try: # Create the output file fitsobj = fits.HDUList() if header is not None: try: del(header['NAXIS1']) del(header['NAXIS2']) if 'XTENSION' in header: del(header['XTENSION']) if 'EXTNAME' in header: del(header['EXTNAME']) if 'EXTVER' in header: del(header['EXTVER']) except KeyError: pass if 'NEXTEND' in header: header['NEXTEND'] = 0 hdu = fits.PrimaryHDU(data=dataArray, header=header) try: del hdu.header['PCOUNT'] del hdu.header['GCOUNT'] except KeyError: pass else: hdu = fits.PrimaryHDU(data=dataArray) fitsobj.append(hdu) if outfile is not None: fitsobj.writeto(outfile) finally: # CLOSE THE IMAGE FILES fitsobj.close() if outfile is not None: del fitsobj fitsobj = None return fitsobj
python
def createFile(dataArray=None, outfile=None, header=None): """ Create a simple fits file for the given data array and header. Returns either the FITS object in-membory when outfile==None or None when the FITS file was written out to a file. """ # Insure that at least a data-array has been provided to create the file assert(dataArray is not None), "Please supply a data array for createFiles" try: # Create the output file fitsobj = fits.HDUList() if header is not None: try: del(header['NAXIS1']) del(header['NAXIS2']) if 'XTENSION' in header: del(header['XTENSION']) if 'EXTNAME' in header: del(header['EXTNAME']) if 'EXTVER' in header: del(header['EXTVER']) except KeyError: pass if 'NEXTEND' in header: header['NEXTEND'] = 0 hdu = fits.PrimaryHDU(data=dataArray, header=header) try: del hdu.header['PCOUNT'] del hdu.header['GCOUNT'] except KeyError: pass else: hdu = fits.PrimaryHDU(data=dataArray) fitsobj.append(hdu) if outfile is not None: fitsobj.writeto(outfile) finally: # CLOSE THE IMAGE FILES fitsobj.close() if outfile is not None: del fitsobj fitsobj = None return fitsobj
[ "def", "createFile", "(", "dataArray", "=", "None", ",", "outfile", "=", "None", ",", "header", "=", "None", ")", ":", "# Insure that at least a data-array has been provided to create the file", "assert", "(", "dataArray", "is", "not", "None", ")", ",", "\"Please su...
Create a simple fits file for the given data array and header. Returns either the FITS object in-membory when outfile==None or None when the FITS file was written out to a file.
[ "Create", "a", "simple", "fits", "file", "for", "the", "given", "data", "array", "and", "header", ".", "Returns", "either", "the", "FITS", "object", "in", "-", "membory", "when", "outfile", "==", "None", "or", "None", "when", "the", "FITS", "file", "was"...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L1121-L1169
train
35,556
spacetelescope/drizzlepac
drizzlepac/util.py
base_taskname
def base_taskname(taskname, packagename=None): """ Extract the base name of the task. Many tasks in the `drizzlepac` have "compound" names such as 'drizzlepac.sky'. This function will search for the presence of a dot in the input `taskname` and if found, it will return the string to the right of the right-most dot. If a dot is not found, it will return the input string. Parameters ---------- taskname : str, None Full task name. If it is `None`, :py:func:`base_taskname` will return `None`\ . packagename : str, None (Default = None) Package name. It is assumed that a compound task name is formed by concatenating `packagename` + '.' + `taskname`\ . If `packagename` is not `None`, :py:func:`base_taskname` will check that the string to the left of the right-most dot matches `packagename` and will raise an `AssertionError` if the package name derived from the input `taskname` does not match the supplied `packagename`\ . This is intended as a check for discrepancies that may arise during the development of the tasks. If `packagename` is `None`, no such check will be performed. Raises ------ AssertionError Raised when package name derived from the input `taskname` does not match the supplied `packagename` """ if not isinstance(taskname, str): return taskname indx = taskname.rfind('.') if indx >= 0: base_taskname = taskname[(indx+1):] pkg_name = taskname[:indx] else: base_taskname = taskname pkg_name = '' assert(True if packagename is None else (packagename == pkg_name)) return base_taskname
python
def base_taskname(taskname, packagename=None): """ Extract the base name of the task. Many tasks in the `drizzlepac` have "compound" names such as 'drizzlepac.sky'. This function will search for the presence of a dot in the input `taskname` and if found, it will return the string to the right of the right-most dot. If a dot is not found, it will return the input string. Parameters ---------- taskname : str, None Full task name. If it is `None`, :py:func:`base_taskname` will return `None`\ . packagename : str, None (Default = None) Package name. It is assumed that a compound task name is formed by concatenating `packagename` + '.' + `taskname`\ . If `packagename` is not `None`, :py:func:`base_taskname` will check that the string to the left of the right-most dot matches `packagename` and will raise an `AssertionError` if the package name derived from the input `taskname` does not match the supplied `packagename`\ . This is intended as a check for discrepancies that may arise during the development of the tasks. If `packagename` is `None`, no such check will be performed. Raises ------ AssertionError Raised when package name derived from the input `taskname` does not match the supplied `packagename` """ if not isinstance(taskname, str): return taskname indx = taskname.rfind('.') if indx >= 0: base_taskname = taskname[(indx+1):] pkg_name = taskname[:indx] else: base_taskname = taskname pkg_name = '' assert(True if packagename is None else (packagename == pkg_name)) return base_taskname
[ "def", "base_taskname", "(", "taskname", ",", "packagename", "=", "None", ")", ":", "if", "not", "isinstance", "(", "taskname", ",", "str", ")", ":", "return", "taskname", "indx", "=", "taskname", ".", "rfind", "(", "'.'", ")", "if", "indx", ">=", "0",...
Extract the base name of the task. Many tasks in the `drizzlepac` have "compound" names such as 'drizzlepac.sky'. This function will search for the presence of a dot in the input `taskname` and if found, it will return the string to the right of the right-most dot. If a dot is not found, it will return the input string. Parameters ---------- taskname : str, None Full task name. If it is `None`, :py:func:`base_taskname` will return `None`\ . packagename : str, None (Default = None) Package name. It is assumed that a compound task name is formed by concatenating `packagename` + '.' + `taskname`\ . If `packagename` is not `None`, :py:func:`base_taskname` will check that the string to the left of the right-most dot matches `packagename` and will raise an `AssertionError` if the package name derived from the input `taskname` does not match the supplied `packagename`\ . This is intended as a check for discrepancies that may arise during the development of the tasks. If `packagename` is `None`, no such check will be performed. Raises ------ AssertionError Raised when package name derived from the input `taskname` does not match the supplied `packagename`
[ "Extract", "the", "base", "name", "of", "the", "task", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L1171-L1219
train
35,557
spacetelescope/drizzlepac
drizzlepac/util.py
ProcSteps.endStep
def endStep(self,key): """ Record the end time for the step. If key==None, simply record ptime as end time for class to represent the overall runtime since the initialization of the class. """ ptime = _ptime() if key is not None: self.steps[key]['end'] = ptime self.steps[key]['elapsed'] = ptime[1] - self.steps[key]['start'][1] self.end = ptime print('==== Processing Step ',key,' finished at ',ptime[0]) print('')
python
def endStep(self,key): """ Record the end time for the step. If key==None, simply record ptime as end time for class to represent the overall runtime since the initialization of the class. """ ptime = _ptime() if key is not None: self.steps[key]['end'] = ptime self.steps[key]['elapsed'] = ptime[1] - self.steps[key]['start'][1] self.end = ptime print('==== Processing Step ',key,' finished at ',ptime[0]) print('')
[ "def", "endStep", "(", "self", ",", "key", ")", ":", "ptime", "=", "_ptime", "(", ")", "if", "key", "is", "not", "None", ":", "self", ".", "steps", "[", "key", "]", "[", "'end'", "]", "=", "ptime", "self", ".", "steps", "[", "key", "]", "[", ...
Record the end time for the step. If key==None, simply record ptime as end time for class to represent the overall runtime since the initialization of the class.
[ "Record", "the", "end", "time", "for", "the", "step", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L329-L343
train
35,558
spacetelescope/drizzlepac
drizzlepac/util.py
ProcSteps.reportTimes
def reportTimes(self): """ Print out a formatted summary of the elapsed times for all the performed steps. """ self.end = _ptime() total_time = 0 print(ProcSteps.__report_header) for step in self.order: if 'elapsed' in self.steps[step]: _time = self.steps[step]['elapsed'] else: _time = 0.0 total_time += _time print(' %20s %0.4f sec.' % (step, _time)) print(' %20s %s' % ('=' * 20, '=' * 20)) print(' %20s %0.4f sec.' % ('Total', total_time))
python
def reportTimes(self): """ Print out a formatted summary of the elapsed times for all the performed steps. """ self.end = _ptime() total_time = 0 print(ProcSteps.__report_header) for step in self.order: if 'elapsed' in self.steps[step]: _time = self.steps[step]['elapsed'] else: _time = 0.0 total_time += _time print(' %20s %0.4f sec.' % (step, _time)) print(' %20s %s' % ('=' * 20, '=' * 20)) print(' %20s %0.4f sec.' % ('Total', total_time))
[ "def", "reportTimes", "(", "self", ")", ":", "self", ".", "end", "=", "_ptime", "(", ")", "total_time", "=", "0", "print", "(", "ProcSteps", ".", "__report_header", ")", "for", "step", "in", "self", ".", "order", ":", "if", "'elapsed'", "in", "self", ...
Print out a formatted summary of the elapsed times for all the performed steps.
[ "Print", "out", "a", "formatted", "summary", "of", "the", "elapsed", "times", "for", "all", "the", "performed", "steps", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/util.py#L345-L363
train
35,559
spacetelescope/drizzlepac
drizzlepac/buildmask.py
buildDQMasks
def buildDQMasks(imageObjectList,configObj): """ Build DQ masks for all input images. """ # Insure that input imageObject is a list if not isinstance(imageObjectList, list): imageObjectList = [imageObjectList] for img in imageObjectList: img.buildMask(configObj['single'], configObj['bits'])
python
def buildDQMasks(imageObjectList,configObj): """ Build DQ masks for all input images. """ # Insure that input imageObject is a list if not isinstance(imageObjectList, list): imageObjectList = [imageObjectList] for img in imageObjectList: img.buildMask(configObj['single'], configObj['bits'])
[ "def", "buildDQMasks", "(", "imageObjectList", ",", "configObj", ")", ":", "# Insure that input imageObject is a list", "if", "not", "isinstance", "(", "imageObjectList", ",", "list", ")", ":", "imageObjectList", "=", "[", "imageObjectList", "]", "for", "img", "in",...
Build DQ masks for all input images.
[ "Build", "DQ", "masks", "for", "all", "input", "images", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildmask.py#L71-L79
train
35,560
spacetelescope/drizzlepac
drizzlepac/buildmask.py
buildMask
def buildMask(dqarr, bitvalue): """ Builds a bit-mask from an input DQ array and a bitvalue flag """ return bitfield_to_boolean_mask(dqarr, bitvalue, good_mask_value=1, dtype=np.uint8)
python
def buildMask(dqarr, bitvalue): """ Builds a bit-mask from an input DQ array and a bitvalue flag """ return bitfield_to_boolean_mask(dqarr, bitvalue, good_mask_value=1, dtype=np.uint8)
[ "def", "buildMask", "(", "dqarr", ",", "bitvalue", ")", ":", "return", "bitfield_to_boolean_mask", "(", "dqarr", ",", "bitvalue", ",", "good_mask_value", "=", "1", ",", "dtype", "=", "np", ".", "uint8", ")" ]
Builds a bit-mask from an input DQ array and a bitvalue flag
[ "Builds", "a", "bit", "-", "mask", "from", "an", "input", "DQ", "array", "and", "a", "bitvalue", "flag" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildmask.py#L82-L85
train
35,561
spacetelescope/drizzlepac
drizzlepac/buildmask.py
buildMaskImage
def buildMaskImage(rootname, bitvalue, output, extname='DQ', extver=1): """ Builds mask image from rootname's DQ array If there is no valid 'DQ' array in image, then return an empty string. """ # If no bitvalue is set or rootname given, assume no mask is desired # However, this name would be useful as the output mask from # other processing, such as MultiDrizzle, so return it anyway. #if bitvalue == None or rootname == None: # return None # build output name maskname = output # If an old version of the maskfile was present, remove it and rebuild it. if fileutil.findFile(maskname): fileutil.removeFile(maskname) # Open input file with DQ array fdq = fileutil.openImage(rootname, mode='readonly', memmap=False) try: _extn = fileutil.findExtname(fdq, extname, extver=extver) if _extn is not None: # Read in DQ array dqarr = fdq[_extn].data else: dqarr = None # For the case where there is no DQ array, # create a mask image of all ones. if dqarr is None: # We need to get the dimensions of the output DQ array # Since the DQ array is non-existent, look for the SCI extension _sci_extn = fileutil.findExtname(fdq,'SCI',extver=extver) if _sci_extn is not None: _shape = fdq[_sci_extn].data.shape dqarr = np.zeros(_shape,dtype=np.uint16) else: raise Exception # Build mask array from DQ array maskarr = buildMask(dqarr,bitvalue) #Write out the mask file as simple FITS file fmask = fits.open(maskname, mode='append', memmap=False) maskhdu = fits.PrimaryHDU(data = maskarr) fmask.append(maskhdu) #Close files fmask.close() del fmask fdq.close() del fdq except: fdq.close() del fdq # Safeguard against leaving behind an incomplete file if fileutil.findFile(maskname): os.remove(maskname) _errstr = "\nWarning: Problem creating MASK file for "+rootname+".\n" #raise IOError, _errstr print(_errstr) return None # Return the name of the mask image written out return maskname
python
def buildMaskImage(rootname, bitvalue, output, extname='DQ', extver=1): """ Builds mask image from rootname's DQ array If there is no valid 'DQ' array in image, then return an empty string. """ # If no bitvalue is set or rootname given, assume no mask is desired # However, this name would be useful as the output mask from # other processing, such as MultiDrizzle, so return it anyway. #if bitvalue == None or rootname == None: # return None # build output name maskname = output # If an old version of the maskfile was present, remove it and rebuild it. if fileutil.findFile(maskname): fileutil.removeFile(maskname) # Open input file with DQ array fdq = fileutil.openImage(rootname, mode='readonly', memmap=False) try: _extn = fileutil.findExtname(fdq, extname, extver=extver) if _extn is not None: # Read in DQ array dqarr = fdq[_extn].data else: dqarr = None # For the case where there is no DQ array, # create a mask image of all ones. if dqarr is None: # We need to get the dimensions of the output DQ array # Since the DQ array is non-existent, look for the SCI extension _sci_extn = fileutil.findExtname(fdq,'SCI',extver=extver) if _sci_extn is not None: _shape = fdq[_sci_extn].data.shape dqarr = np.zeros(_shape,dtype=np.uint16) else: raise Exception # Build mask array from DQ array maskarr = buildMask(dqarr,bitvalue) #Write out the mask file as simple FITS file fmask = fits.open(maskname, mode='append', memmap=False) maskhdu = fits.PrimaryHDU(data = maskarr) fmask.append(maskhdu) #Close files fmask.close() del fmask fdq.close() del fdq except: fdq.close() del fdq # Safeguard against leaving behind an incomplete file if fileutil.findFile(maskname): os.remove(maskname) _errstr = "\nWarning: Problem creating MASK file for "+rootname+".\n" #raise IOError, _errstr print(_errstr) return None # Return the name of the mask image written out return maskname
[ "def", "buildMaskImage", "(", "rootname", ",", "bitvalue", ",", "output", ",", "extname", "=", "'DQ'", ",", "extver", "=", "1", ")", ":", "# If no bitvalue is set or rootname given, assume no mask is desired", "# However, this name would be useful as the output mask from", "#...
Builds mask image from rootname's DQ array If there is no valid 'DQ' array in image, then return an empty string.
[ "Builds", "mask", "image", "from", "rootname", "s", "DQ", "array", "If", "there", "is", "no", "valid", "DQ", "array", "in", "image", "then", "return", "an", "empty", "string", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildmask.py#L88-L153
train
35,562
spacetelescope/drizzlepac
drizzlepac/buildmask.py
buildShadowMaskImage
def buildShadowMaskImage(dqfile,detnum,extnum,maskname,bitvalue=None,binned=1): """ Builds mask image from WFPC2 shadow calibrations. detnum - string value for 'DETECTOR' detector """ # insure detnum is a string if type(detnum) != type(''): detnum = repr(detnum) _funcroot = '_func_Shadow_WF' # build template shadow mask's filename # If an old version of the maskfile was present, remove it and rebuild it. if fileutil.findFile(maskname): fileutil.removeFile(maskname) _use_inmask = not fileutil.findFile(dqfile) or bitvalue is None # Check for existance of input .c1h file for use in making inmask file if _use_inmask: #_mask = 'wfpc2_inmask'+detnum+'.fits' _mask = maskname # Check to see if file exists... if not fileutil.findFile(_mask): # If not, create the file. # This takes a long time to run, so it should be done # only when absolutely necessary... try: _funcx = _funcroot+detnum+'x' _funcy = _funcroot+detnum+'y' _xarr = np.clip(np.fromfunction(eval(_funcx),(800,800)),0.0,1.0).astype(np.uint8) _yarr = np.clip(np.fromfunction(eval(_funcy),(800,800)),0.0,1.0).astype(np.uint8) maskarr = _xarr * _yarr if binned !=1: bmaskarr = maskarr[::2,::2] bmaskarr *= maskarr[1::2,::2] bmaskarr *= maskarr[::2,1::2] bmaskarr *= maskarr[1::2,1::2] maskarr = bmaskarr.copy() del bmaskarr #Write out the mask file as simple FITS file fmask = fits.open(_mask, mode='append', memmap=False) maskhdu = fits.PrimaryHDU(data=maskarr) fmask.append(maskhdu) #Close files fmask.close() del fmask except: return None else: # # Build full mask based on .c1h and shadow mask # fdq = fileutil.openImage(dqfile, mode='readonly', memmap=False) try: # Read in DQ array from .c1h and from shadow mask files dqarr = fdq[int(extnum)].data #maskarr = fsmask[0].data # Build mask array from DQ array dqmaskarr = buildMask(dqarr,bitvalue) #Write out the mask file as simple FITS file fdqmask = fits.open(maskname, mode='append', memmap=False) maskhdu = fits.PrimaryHDU(data=dqmaskarr) fdqmask.append(maskhdu) #Close files fdqmask.close() del fdqmask fdq.close() del fdq except: fdq.close() del fdq # Safeguard against leaving behind an incomplete file if fileutil.findFile(maskname): os.remove(maskname) _errstr = "\nWarning: Problem creating DQMASK file for "+rootname+".\n" #raise IOError, _errstr print(_errstr) return None # Return the name of the mask image written out return maskname
python
def buildShadowMaskImage(dqfile,detnum,extnum,maskname,bitvalue=None,binned=1): """ Builds mask image from WFPC2 shadow calibrations. detnum - string value for 'DETECTOR' detector """ # insure detnum is a string if type(detnum) != type(''): detnum = repr(detnum) _funcroot = '_func_Shadow_WF' # build template shadow mask's filename # If an old version of the maskfile was present, remove it and rebuild it. if fileutil.findFile(maskname): fileutil.removeFile(maskname) _use_inmask = not fileutil.findFile(dqfile) or bitvalue is None # Check for existance of input .c1h file for use in making inmask file if _use_inmask: #_mask = 'wfpc2_inmask'+detnum+'.fits' _mask = maskname # Check to see if file exists... if not fileutil.findFile(_mask): # If not, create the file. # This takes a long time to run, so it should be done # only when absolutely necessary... try: _funcx = _funcroot+detnum+'x' _funcy = _funcroot+detnum+'y' _xarr = np.clip(np.fromfunction(eval(_funcx),(800,800)),0.0,1.0).astype(np.uint8) _yarr = np.clip(np.fromfunction(eval(_funcy),(800,800)),0.0,1.0).astype(np.uint8) maskarr = _xarr * _yarr if binned !=1: bmaskarr = maskarr[::2,::2] bmaskarr *= maskarr[1::2,::2] bmaskarr *= maskarr[::2,1::2] bmaskarr *= maskarr[1::2,1::2] maskarr = bmaskarr.copy() del bmaskarr #Write out the mask file as simple FITS file fmask = fits.open(_mask, mode='append', memmap=False) maskhdu = fits.PrimaryHDU(data=maskarr) fmask.append(maskhdu) #Close files fmask.close() del fmask except: return None else: # # Build full mask based on .c1h and shadow mask # fdq = fileutil.openImage(dqfile, mode='readonly', memmap=False) try: # Read in DQ array from .c1h and from shadow mask files dqarr = fdq[int(extnum)].data #maskarr = fsmask[0].data # Build mask array from DQ array dqmaskarr = buildMask(dqarr,bitvalue) #Write out the mask file as simple FITS file fdqmask = fits.open(maskname, mode='append', memmap=False) maskhdu = fits.PrimaryHDU(data=dqmaskarr) fdqmask.append(maskhdu) #Close files fdqmask.close() del fdqmask fdq.close() del fdq except: fdq.close() del fdq # Safeguard against leaving behind an incomplete file if fileutil.findFile(maskname): os.remove(maskname) _errstr = "\nWarning: Problem creating DQMASK file for "+rootname+".\n" #raise IOError, _errstr print(_errstr) return None # Return the name of the mask image written out return maskname
[ "def", "buildShadowMaskImage", "(", "dqfile", ",", "detnum", ",", "extnum", ",", "maskname", ",", "bitvalue", "=", "None", ",", "binned", "=", "1", ")", ":", "# insure detnum is a string", "if", "type", "(", "detnum", ")", "!=", "type", "(", "''", ")", "...
Builds mask image from WFPC2 shadow calibrations. detnum - string value for 'DETECTOR' detector
[ "Builds", "mask", "image", "from", "WFPC2", "shadow", "calibrations", ".", "detnum", "-", "string", "value", "for", "DETECTOR", "detector" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/buildmask.py#L187-L278
train
35,563
spacetelescope/drizzlepac
drizzlepac/adrizzle.py
mergeDQarray
def mergeDQarray(maskname,dqarr): """ Merge static or CR mask with mask created from DQ array on-the-fly here. """ maskarr = None if maskname is not None: if isinstance(maskname, str): # working with file on disk (default case) if os.path.exists(maskname): mask = fileutil.openImage(maskname, memmap=False) maskarr = mask[0].data.astype(np.bool) mask.close() else: if isinstance(maskname, fits.HDUList): # working with a virtual input file maskarr = maskname[0].data.astype(np.bool) else: maskarr = maskname.data.astype(np.bool) if maskarr is not None: # merge array with dqarr now np.bitwise_and(dqarr,maskarr,dqarr)
python
def mergeDQarray(maskname,dqarr): """ Merge static or CR mask with mask created from DQ array on-the-fly here. """ maskarr = None if maskname is not None: if isinstance(maskname, str): # working with file on disk (default case) if os.path.exists(maskname): mask = fileutil.openImage(maskname, memmap=False) maskarr = mask[0].data.astype(np.bool) mask.close() else: if isinstance(maskname, fits.HDUList): # working with a virtual input file maskarr = maskname[0].data.astype(np.bool) else: maskarr = maskname.data.astype(np.bool) if maskarr is not None: # merge array with dqarr now np.bitwise_and(dqarr,maskarr,dqarr)
[ "def", "mergeDQarray", "(", "maskname", ",", "dqarr", ")", ":", "maskarr", "=", "None", "if", "maskname", "is", "not", "None", ":", "if", "isinstance", "(", "maskname", ",", "str", ")", ":", "# working with file on disk (default case)", "if", "os", ".", "pat...
Merge static or CR mask with mask created from DQ array on-the-fly here.
[ "Merge", "static", "or", "CR", "mask", "with", "mask", "created", "from", "DQ", "array", "on", "-", "the", "-", "fly", "here", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/adrizzle.py#L396-L416
train
35,564
spacetelescope/drizzlepac
drizzlepac/adrizzle.py
_setDefaults
def _setDefaults(configObj={}): """set up the default parameters to run drizzle build,single,units,wt_scl,pixfrac,kernel,fillval, rot,scale,xsh,ysh,blotnx,blotny,outnx,outny,data Used exclusively for unit-testing, if any are defined. """ paramDict={"build":True, "single":True, "stepsize":10, "in_units":"cps", "wt_scl":1., "pixfrac":1., "kernel":"square", "fillval":999., "maskval": None, "rot":0., "scale":1., "xsh":0., "ysh":0., "blotnx":2048, "blotny":2048, "outnx":4096, "outny":4096, "data":None, "driz_separate":True, "driz_combine":False} if(len(configObj) !=0): for key in configObj.keys(): paramDict[key]=configObj[key] return paramDict
python
def _setDefaults(configObj={}): """set up the default parameters to run drizzle build,single,units,wt_scl,pixfrac,kernel,fillval, rot,scale,xsh,ysh,blotnx,blotny,outnx,outny,data Used exclusively for unit-testing, if any are defined. """ paramDict={"build":True, "single":True, "stepsize":10, "in_units":"cps", "wt_scl":1., "pixfrac":1., "kernel":"square", "fillval":999., "maskval": None, "rot":0., "scale":1., "xsh":0., "ysh":0., "blotnx":2048, "blotny":2048, "outnx":4096, "outny":4096, "data":None, "driz_separate":True, "driz_combine":False} if(len(configObj) !=0): for key in configObj.keys(): paramDict[key]=configObj[key] return paramDict
[ "def", "_setDefaults", "(", "configObj", "=", "{", "}", ")", ":", "paramDict", "=", "{", "\"build\"", ":", "True", ",", "\"single\"", ":", "True", ",", "\"stepsize\"", ":", "10", ",", "\"in_units\"", ":", "\"cps\"", ",", "\"wt_scl\"", ":", "1.", ",", "...
set up the default parameters to run drizzle build,single,units,wt_scl,pixfrac,kernel,fillval, rot,scale,xsh,ysh,blotnx,blotny,outnx,outny,data Used exclusively for unit-testing, if any are defined.
[ "set", "up", "the", "default", "parameters", "to", "run", "drizzle", "build", "single", "units", "wt_scl", "pixfrac", "kernel", "fillval", "rot", "scale", "xsh", "ysh", "blotnx", "blotny", "outnx", "outny", "data" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/adrizzle.py#L473-L507
train
35,565
spacetelescope/drizzlepac
drizzlepac/adrizzle.py
interpret_maskval
def interpret_maskval(paramDict): """ Apply logic for interpreting final_maskval value... """ # interpret user specified final_maskval value to use for initializing # output SCI array... if 'maskval' not in paramDict: return 0 maskval = paramDict['maskval'] if maskval is None: maskval = np.nan else: maskval = float(maskval) # just to be clear and absolutely sure... return maskval
python
def interpret_maskval(paramDict): """ Apply logic for interpreting final_maskval value... """ # interpret user specified final_maskval value to use for initializing # output SCI array... if 'maskval' not in paramDict: return 0 maskval = paramDict['maskval'] if maskval is None: maskval = np.nan else: maskval = float(maskval) # just to be clear and absolutely sure... return maskval
[ "def", "interpret_maskval", "(", "paramDict", ")", ":", "# interpret user specified final_maskval value to use for initializing", "# output SCI array...", "if", "'maskval'", "not", "in", "paramDict", ":", "return", "0", "maskval", "=", "paramDict", "[", "'maskval'", "]", ...
Apply logic for interpreting final_maskval value...
[ "Apply", "logic", "for", "interpreting", "final_maskval", "value", "..." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/adrizzle.py#L509-L521
train
35,566
spacetelescope/drizzlepac
drizzlepac/mapreg.py
_regwrite
def _regwrite(shapelist,outfile): """ Writes the current shape list out as a region file """ # This function corrects bugs and provides improvements over the pyregion's # ShapeList.write method in the following: # # 1. ShapeList.write crashes if regions have no comments; # 2. ShapeList.write converts 'exclude' ("-") regions to normal regions ("+"); # 3. ShapeList.write does not support mixed coordinate systems in a # region list. # # NOTE: This function is provided as a temoprary workaround for the above # listed problems of the ShapeList.write. We hope that a future version # of pyregion will address all these issues. # #TODO: Push these changes to pyregion. if len(shapelist) < 1: _print_warning("The region list is empty. The region file \"%s\" "\ "will be empty." % outfile) try: outf = open(outfile,'w') outf.close() return except IOError as e: cmsg = "Unable to create region file \'%s\'." % outfile if e.args: e.args = (e.args[0] + "\n" + cmsg,) + e.args[1:] else: e.args=(cmsg,) raise e except: raise prev_cs = shapelist[0].coord_format outf = None try: outf = open(outfile,'w') attr0 = shapelist[0].attr[1] defaultline = " ".join(["%s=%s" % (a,attr0[a]) for a in attr0 \ if a!='text']) # first line is globals print("global", defaultline, file=outf) # second line must be a coordinate format print(prev_cs, file=outf) for shape in shapelist: shape_attr = '' if prev_cs == shape.coord_format \ else shape.coord_format+"; " shape_excl = '-' if shape.exclude else '' text_coordlist = ["%f" % f for f in shape.coord_list] shape_coords = "(" + ",".join(text_coordlist) + ")" shape_comment = " # " + shape.comment if shape.comment else '' shape_str = shape_attr + shape_excl + shape.name + shape_coords + \ shape_comment print(shape_str, file=outf) except IOError as e: cmsg = "Unable to create region file \'%s\'." % outfile if e.args: e.args = (e.args[0] + "\n" + cmsg,) + e.args[1:] else: e.args=(cmsg,) if outf: outf.close() raise e except: if outf: outf.close() raise outf.close()
python
def _regwrite(shapelist,outfile): """ Writes the current shape list out as a region file """ # This function corrects bugs and provides improvements over the pyregion's # ShapeList.write method in the following: # # 1. ShapeList.write crashes if regions have no comments; # 2. ShapeList.write converts 'exclude' ("-") regions to normal regions ("+"); # 3. ShapeList.write does not support mixed coordinate systems in a # region list. # # NOTE: This function is provided as a temoprary workaround for the above # listed problems of the ShapeList.write. We hope that a future version # of pyregion will address all these issues. # #TODO: Push these changes to pyregion. if len(shapelist) < 1: _print_warning("The region list is empty. The region file \"%s\" "\ "will be empty." % outfile) try: outf = open(outfile,'w') outf.close() return except IOError as e: cmsg = "Unable to create region file \'%s\'." % outfile if e.args: e.args = (e.args[0] + "\n" + cmsg,) + e.args[1:] else: e.args=(cmsg,) raise e except: raise prev_cs = shapelist[0].coord_format outf = None try: outf = open(outfile,'w') attr0 = shapelist[0].attr[1] defaultline = " ".join(["%s=%s" % (a,attr0[a]) for a in attr0 \ if a!='text']) # first line is globals print("global", defaultline, file=outf) # second line must be a coordinate format print(prev_cs, file=outf) for shape in shapelist: shape_attr = '' if prev_cs == shape.coord_format \ else shape.coord_format+"; " shape_excl = '-' if shape.exclude else '' text_coordlist = ["%f" % f for f in shape.coord_list] shape_coords = "(" + ",".join(text_coordlist) + ")" shape_comment = " # " + shape.comment if shape.comment else '' shape_str = shape_attr + shape_excl + shape.name + shape_coords + \ shape_comment print(shape_str, file=outf) except IOError as e: cmsg = "Unable to create region file \'%s\'." % outfile if e.args: e.args = (e.args[0] + "\n" + cmsg,) + e.args[1:] else: e.args=(cmsg,) if outf: outf.close() raise e except: if outf: outf.close() raise outf.close()
[ "def", "_regwrite", "(", "shapelist", ",", "outfile", ")", ":", "# This function corrects bugs and provides improvements over the pyregion's", "# ShapeList.write method in the following:", "#", "# 1. ShapeList.write crashes if regions have no comments;", "# 2. ShapeList.write converts 'exclu...
Writes the current shape list out as a region file
[ "Writes", "the", "current", "shape", "list", "out", "as", "a", "region", "file" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/mapreg.py#L296-L369
train
35,567
spacetelescope/drizzlepac
drizzlepac/mapreg.py
_needs_ref_WCS
def _needs_ref_WCS(reglist): """ Check if the region list contains shapes in image-like coordinates """ from pyregion.wcs_helper import image_like_coordformats for r in reglist: if r.coord_format in image_like_coordformats: return True return False
python
def _needs_ref_WCS(reglist): """ Check if the region list contains shapes in image-like coordinates """ from pyregion.wcs_helper import image_like_coordformats for r in reglist: if r.coord_format in image_like_coordformats: return True return False
[ "def", "_needs_ref_WCS", "(", "reglist", ")", ":", "from", "pyregion", ".", "wcs_helper", "import", "image_like_coordformats", "for", "r", "in", "reglist", ":", "if", "r", ".", "coord_format", "in", "image_like_coordformats", ":", "return", "True", "return", "Fa...
Check if the region list contains shapes in image-like coordinates
[ "Check", "if", "the", "region", "list", "contains", "shapes", "in", "image", "-", "like", "coordinates" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/mapreg.py#L746-L754
train
35,568
spacetelescope/drizzlepac
drizzlepac/generate_final_product_filenames.py
run_generator
def run_generator(product_category,obs_info): """ This is the main calling subroutine. It decides which filename generation subroutine should be run based on the input product_category, and then passes the information stored in input obs_info to the subroutine so that the appropriate filenames can be generated. Parameters ---------- product_category : string The type of final output product which filenames will be generated for obs_info : string A string containing space-separated items that will be used to generate the filenames. Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ category_generator_mapping = {'single exposure product': single_exposure_product_filename_generator, 'filter product': filter_product_filename_generator, 'total detection product': total_detection_product_filename_generator, 'multivisit mosaic product': multivisit_mosaic_product_filename_generator} # Determine which name generator to use based on input product_category for key in category_generator_mapping.keys(): if product_category.startswith(key): generator_name = category_generator_mapping[key] category_num = product_category.replace(key+" ","") break # parse out obs_info into a list obs_info = obs_info.split(" ") # pad 4-character proposal_id values with leading 0s so that proposal_id is # a 5-character sting. if key != "multivisit mosaic product": # pad obs_info[0] = "{}{}".format("0"*(5-len(obs_info[0])),obs_info[0]) # generate and return filenames product_filename_dict=generator_name(obs_info,category_num) return(product_filename_dict)
python
def run_generator(product_category,obs_info): """ This is the main calling subroutine. It decides which filename generation subroutine should be run based on the input product_category, and then passes the information stored in input obs_info to the subroutine so that the appropriate filenames can be generated. Parameters ---------- product_category : string The type of final output product which filenames will be generated for obs_info : string A string containing space-separated items that will be used to generate the filenames. Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ category_generator_mapping = {'single exposure product': single_exposure_product_filename_generator, 'filter product': filter_product_filename_generator, 'total detection product': total_detection_product_filename_generator, 'multivisit mosaic product': multivisit_mosaic_product_filename_generator} # Determine which name generator to use based on input product_category for key in category_generator_mapping.keys(): if product_category.startswith(key): generator_name = category_generator_mapping[key] category_num = product_category.replace(key+" ","") break # parse out obs_info into a list obs_info = obs_info.split(" ") # pad 4-character proposal_id values with leading 0s so that proposal_id is # a 5-character sting. if key != "multivisit mosaic product": # pad obs_info[0] = "{}{}".format("0"*(5-len(obs_info[0])),obs_info[0]) # generate and return filenames product_filename_dict=generator_name(obs_info,category_num) return(product_filename_dict)
[ "def", "run_generator", "(", "product_category", ",", "obs_info", ")", ":", "category_generator_mapping", "=", "{", "'single exposure product'", ":", "single_exposure_product_filename_generator", ",", "'filter product'", ":", "filter_product_filename_generator", ",", "'total de...
This is the main calling subroutine. It decides which filename generation subroutine should be run based on the input product_category, and then passes the information stored in input obs_info to the subroutine so that the appropriate filenames can be generated. Parameters ---------- product_category : string The type of final output product which filenames will be generated for obs_info : string A string containing space-separated items that will be used to generate the filenames. Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames.
[ "This", "is", "the", "main", "calling", "subroutine", ".", "It", "decides", "which", "filename", "generation", "subroutine", "should", "be", "run", "based", "on", "the", "input", "product_category", "and", "then", "passes", "the", "information", "stored", "in", ...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/generate_final_product_filenames.py#L8-L49
train
35,569
spacetelescope/drizzlepac
drizzlepac/generate_final_product_filenames.py
single_exposure_product_filename_generator
def single_exposure_product_filename_generator(obs_info,nn): """ Generate image and sourcelist filenames for single-exposure products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, detector, filter, and ipppssoot nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ proposal_id = obs_info[0] visit_id = obs_info[1] instrument = obs_info[2] detector = obs_info[3] filter = obs_info[4] ipppssoot = obs_info[5] product_filename_dict = {} product_filename_dict["image"] = "hst_{}_{}_{}_{}_{}_{}_{}.fits".format(proposal_id,visit_id,instrument,detector,filter,ipppssoot,nn) product_filename_dict["source catalog"]= product_filename_dict["image"].replace(".fits",".cat") return(product_filename_dict)
python
def single_exposure_product_filename_generator(obs_info,nn): """ Generate image and sourcelist filenames for single-exposure products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, detector, filter, and ipppssoot nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ proposal_id = obs_info[0] visit_id = obs_info[1] instrument = obs_info[2] detector = obs_info[3] filter = obs_info[4] ipppssoot = obs_info[5] product_filename_dict = {} product_filename_dict["image"] = "hst_{}_{}_{}_{}_{}_{}_{}.fits".format(proposal_id,visit_id,instrument,detector,filter,ipppssoot,nn) product_filename_dict["source catalog"]= product_filename_dict["image"].replace(".fits",".cat") return(product_filename_dict)
[ "def", "single_exposure_product_filename_generator", "(", "obs_info", ",", "nn", ")", ":", "proposal_id", "=", "obs_info", "[", "0", "]", "visit_id", "=", "obs_info", "[", "1", "]", "instrument", "=", "obs_info", "[", "2", "]", "detector", "=", "obs_info", "...
Generate image and sourcelist filenames for single-exposure products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, detector, filter, and ipppssoot nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames.
[ "Generate", "image", "and", "sourcelist", "filenames", "for", "single", "-", "exposure", "products" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/generate_final_product_filenames.py#L52-L81
train
35,570
spacetelescope/drizzlepac
drizzlepac/generate_final_product_filenames.py
filter_product_filename_generator
def filter_product_filename_generator(obs_info,nn): """ Generate image and sourcelist filenames for filter products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, detector, and filter nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ proposal_id = obs_info[0] visit_id = obs_info[1] instrument = obs_info[2] detector = obs_info[3] filter = obs_info[4] product_filename_dict = {} product_filename_dict["image"] = "hst_{}_{}_{}_{}_{}.fits".format(proposal_id,visit_id,instrument,detector,filter) product_filename_dict["source catalog"] = product_filename_dict["image"].replace(".fits",".cat") return(product_filename_dict)
python
def filter_product_filename_generator(obs_info,nn): """ Generate image and sourcelist filenames for filter products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, detector, and filter nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ proposal_id = obs_info[0] visit_id = obs_info[1] instrument = obs_info[2] detector = obs_info[3] filter = obs_info[4] product_filename_dict = {} product_filename_dict["image"] = "hst_{}_{}_{}_{}_{}.fits".format(proposal_id,visit_id,instrument,detector,filter) product_filename_dict["source catalog"] = product_filename_dict["image"].replace(".fits",".cat") return(product_filename_dict)
[ "def", "filter_product_filename_generator", "(", "obs_info", ",", "nn", ")", ":", "proposal_id", "=", "obs_info", "[", "0", "]", "visit_id", "=", "obs_info", "[", "1", "]", "instrument", "=", "obs_info", "[", "2", "]", "detector", "=", "obs_info", "[", "3"...
Generate image and sourcelist filenames for filter products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, detector, and filter nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames.
[ "Generate", "image", "and", "sourcelist", "filenames", "for", "filter", "products" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/generate_final_product_filenames.py#L85-L113
train
35,571
spacetelescope/drizzlepac
drizzlepac/generate_final_product_filenames.py
total_detection_product_filename_generator
def total_detection_product_filename_generator(obs_info,nn): """ Generate image and sourcelist filenames for total detection products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, and detector nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ proposal_id = obs_info[0] visit_id = obs_info[1] instrument = obs_info[2] detector = obs_info[3] product_filename_dict = {} product_filename_dict["image"] = "hst_{}_{}_{}_{}.fits".format(proposal_id, visit_id, instrument, detector) product_filename_dict["source catalog"] = product_filename_dict["image"].replace(".fits",".cat") return (product_filename_dict)
python
def total_detection_product_filename_generator(obs_info,nn): """ Generate image and sourcelist filenames for total detection products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, and detector nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ proposal_id = obs_info[0] visit_id = obs_info[1] instrument = obs_info[2] detector = obs_info[3] product_filename_dict = {} product_filename_dict["image"] = "hst_{}_{}_{}_{}.fits".format(proposal_id, visit_id, instrument, detector) product_filename_dict["source catalog"] = product_filename_dict["image"].replace(".fits",".cat") return (product_filename_dict)
[ "def", "total_detection_product_filename_generator", "(", "obs_info", ",", "nn", ")", ":", "proposal_id", "=", "obs_info", "[", "0", "]", "visit_id", "=", "obs_info", "[", "1", "]", "instrument", "=", "obs_info", "[", "2", "]", "detector", "=", "obs_info", "...
Generate image and sourcelist filenames for total detection products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: proposal_id, visit_id, instrument, and detector nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames.
[ "Generate", "image", "and", "sourcelist", "filenames", "for", "total", "detection", "products" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/generate_final_product_filenames.py#L118-L145
train
35,572
spacetelescope/drizzlepac
drizzlepac/generate_final_product_filenames.py
multivisit_mosaic_product_filename_generator
def multivisit_mosaic_product_filename_generator(obs_info,nn): """ Generate image and sourcelist filenames for multi-visit mosaic products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: group_id, instrument, detector, and filter nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ group_num = obs_info[0] instrument = obs_info[1] detector = obs_info[2] filter = obs_info[3] product_filename_dict = {} product_filename_dict["image"] = "hst_mos_{}_{}_{}_{}.fits".format(group_num,instrument,detector,filter) product_filename_dict["source catalog"] = product_filename_dict["image"].replace(".fits",".cat") return (product_filename_dict)
python
def multivisit_mosaic_product_filename_generator(obs_info,nn): """ Generate image and sourcelist filenames for multi-visit mosaic products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: group_id, instrument, detector, and filter nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames. """ group_num = obs_info[0] instrument = obs_info[1] detector = obs_info[2] filter = obs_info[3] product_filename_dict = {} product_filename_dict["image"] = "hst_mos_{}_{}_{}_{}.fits".format(group_num,instrument,detector,filter) product_filename_dict["source catalog"] = product_filename_dict["image"].replace(".fits",".cat") return (product_filename_dict)
[ "def", "multivisit_mosaic_product_filename_generator", "(", "obs_info", ",", "nn", ")", ":", "group_num", "=", "obs_info", "[", "0", "]", "instrument", "=", "obs_info", "[", "1", "]", "detector", "=", "obs_info", "[", "2", "]", "filter", "=", "obs_info", "["...
Generate image and sourcelist filenames for multi-visit mosaic products Parameters ---------- obs_info : list list of items that will be used to generate the filenames: group_id, instrument, detector, and filter nn : string the single-exposure image number (NOTE: only used in single_exposure_product_filename_generator()) Returns -------- product_filename_dict : dictionary A dictionary containing the generated filenames.
[ "Generate", "image", "and", "sourcelist", "filenames", "for", "multi", "-", "visit", "mosaic", "products" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/generate_final_product_filenames.py#L149-L176
train
35,573
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
build_referenceWCS
def build_referenceWCS(catalog_list): """ Compute default reference WCS from list of Catalog objects. """ wcslist = [] for catalog in catalog_list: for scichip in catalog.catalogs: wcslist.append(catalog.catalogs[scichip]['wcs']) return utils.output_wcs(wcslist)
python
def build_referenceWCS(catalog_list): """ Compute default reference WCS from list of Catalog objects. """ wcslist = [] for catalog in catalog_list: for scichip in catalog.catalogs: wcslist.append(catalog.catalogs[scichip]['wcs']) return utils.output_wcs(wcslist)
[ "def", "build_referenceWCS", "(", "catalog_list", ")", ":", "wcslist", "=", "[", "]", "for", "catalog", "in", "catalog_list", ":", "for", "scichip", "in", "catalog", ".", "catalogs", ":", "wcslist", ".", "append", "(", "catalog", ".", "catalogs", "[", "sci...
Compute default reference WCS from list of Catalog objects.
[ "Compute", "default", "reference", "WCS", "from", "list", "of", "Catalog", "objects", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L1453-L1460
train
35,574
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
convex_hull
def convex_hull(points): """Computes the convex hull of a set of 2D points. Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_. The algorithm has O(n log n) complexity. Credit: `<http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_ Parameters ---------- points : list of tuples An iterable sequence of (x, y) pairs representing the points. Returns ------- Output : list A list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates. """ # Sort the points lexicographically (tuples are compared lexicographically). # Remove duplicates to detect the case we have just one unique point. points = sorted(set(points)) # Boring case: no points or a single point, possibly repeated multiple times. if len(points) <= 1: return points # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product. # Returns a positive value, if OAB makes a counter-clockwise turn, # negative for clockwise turn, and zero if the points are collinear. def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) # Build lower hull lower = [] for p in points: while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: lower.pop() lower.append(p) # Build upper hull upper = [] for p in reversed(points): while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: upper.pop() upper.append(p) # Concatenation of the lower and upper hulls gives the convex hull. # Last point of each list is omitted because it is repeated at the beginning of the other list. return lower[:-1] + upper
python
def convex_hull(points): """Computes the convex hull of a set of 2D points. Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_. The algorithm has O(n log n) complexity. Credit: `<http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_ Parameters ---------- points : list of tuples An iterable sequence of (x, y) pairs representing the points. Returns ------- Output : list A list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates. """ # Sort the points lexicographically (tuples are compared lexicographically). # Remove duplicates to detect the case we have just one unique point. points = sorted(set(points)) # Boring case: no points or a single point, possibly repeated multiple times. if len(points) <= 1: return points # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product. # Returns a positive value, if OAB makes a counter-clockwise turn, # negative for clockwise turn, and zero if the points are collinear. def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) # Build lower hull lower = [] for p in points: while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: lower.pop() lower.append(p) # Build upper hull upper = [] for p in reversed(points): while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: upper.pop() upper.append(p) # Concatenation of the lower and upper hulls gives the convex hull. # Last point of each list is omitted because it is repeated at the beginning of the other list. return lower[:-1] + upper
[ "def", "convex_hull", "(", "points", ")", ":", "# Sort the points lexicographically (tuples are compared lexicographically).", "# Remove duplicates to detect the case we have just one unique point.", "points", "=", "sorted", "(", "set", "(", "points", ")", ")", "# Boring case: no p...
Computes the convex hull of a set of 2D points. Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_. The algorithm has O(n log n) complexity. Credit: `<http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_ Parameters ---------- points : list of tuples An iterable sequence of (x, y) pairs representing the points. Returns ------- Output : list A list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates.
[ "Computes", "the", "convex", "hull", "of", "a", "set", "of", "2D", "points", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L1506-L1558
train
35,575
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
_estimate_2dhist_shift
def _estimate_2dhist_shift(imgxy, refxy, searchrad=3.0): """ Create a 2D matrix-histogram which contains the delta between each XY position and each UV position. Then estimate initial offset between catalogs. """ print("Computing initial guess for X and Y shifts...") # create ZP matrix zpmat = _xy_2dhist(imgxy, refxy, r=searchrad) nonzeros = np.count_nonzero(zpmat) if nonzeros == 0: # no matches within search radius. Return (0, 0): print("WARNING: No matches found within a search radius of {:g} " "pixels.".format(searchrad)) return 0.0, 0.0, 0, 0, zpmat, False elif nonzeros == 1: # only one non-zero bin: yp, xp = np.unravel_index(np.argmax(zpmat), zpmat.shape) maxval = int(np.ceil(zpmat[yp, xp])) xp -= searchrad yp -= searchrad print("Found initial X and Y shifts of {:.4g}, {:.4g} " "based on a single non-zero bin and {} matches" .format(xp, yp, maxval)) return xp, yp, maxval, maxval, zpmat, True (xp, yp), fit_status, fit_sl = _find_peak(zpmat, peak_fit_box=5, mask=zpmat > 0) if fit_status.startswith('ERROR'): print("WARNING: No valid shift found within a search radius of {:g} " "pixels.".format(searchrad)) maxval = int(np.ceil(zpmat.max())) return 0.0, 0.0, maxval, maxval, zpmat, False xp -= searchrad yp -= searchrad if fit_status == 'WARNING:EDGE': print( "WARNING: Found peak in the 2D histogram lies at the edge of " "the histogram. Try increasing 'searchrad' for improved results." ) # Attempt to estimate "significance of detection": maxval = zpmat.max() zpmat_mask = (zpmat > 0) & (zpmat < maxval) if np.any(zpmat_mask): bkg = zpmat[zpmat_mask].mean() sig = maxval / np.sqrt(bkg) flux = int(zpmat[fit_sl].sum()) print("Found initial X and Y shifts of {:.4g}, {:.4g} " "with significance of {:.4g} and {:d} matches" .format(xp, yp, sig, flux)) return xp, yp, int(np.ceil(maxval)), flux, zpmat, True
python
def _estimate_2dhist_shift(imgxy, refxy, searchrad=3.0): """ Create a 2D matrix-histogram which contains the delta between each XY position and each UV position. Then estimate initial offset between catalogs. """ print("Computing initial guess for X and Y shifts...") # create ZP matrix zpmat = _xy_2dhist(imgxy, refxy, r=searchrad) nonzeros = np.count_nonzero(zpmat) if nonzeros == 0: # no matches within search radius. Return (0, 0): print("WARNING: No matches found within a search radius of {:g} " "pixels.".format(searchrad)) return 0.0, 0.0, 0, 0, zpmat, False elif nonzeros == 1: # only one non-zero bin: yp, xp = np.unravel_index(np.argmax(zpmat), zpmat.shape) maxval = int(np.ceil(zpmat[yp, xp])) xp -= searchrad yp -= searchrad print("Found initial X and Y shifts of {:.4g}, {:.4g} " "based on a single non-zero bin and {} matches" .format(xp, yp, maxval)) return xp, yp, maxval, maxval, zpmat, True (xp, yp), fit_status, fit_sl = _find_peak(zpmat, peak_fit_box=5, mask=zpmat > 0) if fit_status.startswith('ERROR'): print("WARNING: No valid shift found within a search radius of {:g} " "pixels.".format(searchrad)) maxval = int(np.ceil(zpmat.max())) return 0.0, 0.0, maxval, maxval, zpmat, False xp -= searchrad yp -= searchrad if fit_status == 'WARNING:EDGE': print( "WARNING: Found peak in the 2D histogram lies at the edge of " "the histogram. Try increasing 'searchrad' for improved results." ) # Attempt to estimate "significance of detection": maxval = zpmat.max() zpmat_mask = (zpmat > 0) & (zpmat < maxval) if np.any(zpmat_mask): bkg = zpmat[zpmat_mask].mean() sig = maxval / np.sqrt(bkg) flux = int(zpmat[fit_sl].sum()) print("Found initial X and Y shifts of {:.4g}, {:.4g} " "with significance of {:.4g} and {:d} matches" .format(xp, yp, sig, flux)) return xp, yp, int(np.ceil(maxval)), flux, zpmat, True
[ "def", "_estimate_2dhist_shift", "(", "imgxy", ",", "refxy", ",", "searchrad", "=", "3.0", ")", ":", "print", "(", "\"Computing initial guess for X and Y shifts...\"", ")", "# create ZP matrix", "zpmat", "=", "_xy_2dhist", "(", "imgxy", ",", "refxy", ",", "r", "="...
Create a 2D matrix-histogram which contains the delta between each XY position and each UV position. Then estimate initial offset between catalogs.
[ "Create", "a", "2D", "matrix", "-", "histogram", "which", "contains", "the", "delta", "between", "each", "XY", "position", "and", "each", "UV", "position", ".", "Then", "estimate", "initial", "offset", "between", "catalogs", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L1613-L1672
train
35,576
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
Image.openFile
def openFile(self, openDQ=False): """ Open file and set up filehandle for image file """ if self._im.closed: if not self._dq.closed: self._dq.release() assert(self._dq.closed) fi = FileExtMaskInfo(clobber=False, doNotOpenDQ=not openDQ, im_fmode=self.open_mode) fi.image = self.name self._im = fi.image fi.append_ext(spu.get_ext_list(self._im, extname='SCI')) fi.finalize() self._im = fi.image self._dq = fi.DQimage self._imext = fi.fext self._dqext = fi.dqext
python
def openFile(self, openDQ=False): """ Open file and set up filehandle for image file """ if self._im.closed: if not self._dq.closed: self._dq.release() assert(self._dq.closed) fi = FileExtMaskInfo(clobber=False, doNotOpenDQ=not openDQ, im_fmode=self.open_mode) fi.image = self.name self._im = fi.image fi.append_ext(spu.get_ext_list(self._im, extname='SCI')) fi.finalize() self._im = fi.image self._dq = fi.DQimage self._imext = fi.fext self._dqext = fi.dqext
[ "def", "openFile", "(", "self", ",", "openDQ", "=", "False", ")", ":", "if", "self", ".", "_im", ".", "closed", ":", "if", "not", "self", ".", "_dq", ".", "closed", ":", "self", ".", "_dq", ".", "release", "(", ")", "assert", "(", "self", ".", ...
Open file and set up filehandle for image file
[ "Open", "file", "and", "set", "up", "filehandle", "for", "image", "file" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L311-L329
train
35,577
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
Image.get_wcs
def get_wcs(self): """ Helper method to return a list of all the input WCS objects associated with this image. """ wcslist = [] for chip in self.chip_catalogs: wcslist.append(self.chip_catalogs[chip]['wcs']) return wcslist
python
def get_wcs(self): """ Helper method to return a list of all the input WCS objects associated with this image. """ wcslist = [] for chip in self.chip_catalogs: wcslist.append(self.chip_catalogs[chip]['wcs']) return wcslist
[ "def", "get_wcs", "(", "self", ")", ":", "wcslist", "=", "[", "]", "for", "chip", "in", "self", ".", "chip_catalogs", ":", "wcslist", ".", "append", "(", "self", ".", "chip_catalogs", "[", "chip", "]", "[", "'wcs'", "]", ")", "return", "wcslist" ]
Helper method to return a list of all the input WCS objects associated with this image.
[ "Helper", "method", "to", "return", "a", "list", "of", "all", "the", "input", "WCS", "objects", "associated", "with", "this", "image", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L331-L338
train
35,578
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
Image.buildSkyCatalog
def buildSkyCatalog(self): """ Convert sky catalog for all chips into a single catalog for the entire field-of-view of this image. """ self.all_radec = None self.all_radec_orig = None ralist = [] declist = [] fluxlist = [] idlist = [] for scichip in self.chip_catalogs: skycat = self.chip_catalogs[scichip]['catalog'].radec xycat = self.chip_catalogs[scichip]['catalog'].xypos if skycat is not None: ralist.append(skycat[0]) declist.append(skycat[1]) if xycat is not None and len(xycat) > 2: fluxlist.append(xycat[2]) idlist.append(xycat[3]) elif len(skycat) > 2: fluxlist.append(skycat[2]) idlist.append(skycat[3]) else: fluxlist.append([999.0]*len(skycat[0])) idlist.append(np.arange(len(skycat[0]))) self.all_radec = [np.concatenate(ralist),np.concatenate(declist), np.concatenate(fluxlist),np.concatenate(idlist)] self.all_radec_orig = copy.deepcopy(self.all_radec)
python
def buildSkyCatalog(self): """ Convert sky catalog for all chips into a single catalog for the entire field-of-view of this image. """ self.all_radec = None self.all_radec_orig = None ralist = [] declist = [] fluxlist = [] idlist = [] for scichip in self.chip_catalogs: skycat = self.chip_catalogs[scichip]['catalog'].radec xycat = self.chip_catalogs[scichip]['catalog'].xypos if skycat is not None: ralist.append(skycat[0]) declist.append(skycat[1]) if xycat is not None and len(xycat) > 2: fluxlist.append(xycat[2]) idlist.append(xycat[3]) elif len(skycat) > 2: fluxlist.append(skycat[2]) idlist.append(skycat[3]) else: fluxlist.append([999.0]*len(skycat[0])) idlist.append(np.arange(len(skycat[0]))) self.all_radec = [np.concatenate(ralist),np.concatenate(declist), np.concatenate(fluxlist),np.concatenate(idlist)] self.all_radec_orig = copy.deepcopy(self.all_radec)
[ "def", "buildSkyCatalog", "(", "self", ")", ":", "self", ".", "all_radec", "=", "None", "self", ".", "all_radec_orig", "=", "None", "ralist", "=", "[", "]", "declist", "=", "[", "]", "fluxlist", "=", "[", "]", "idlist", "=", "[", "]", "for", "scichip...
Convert sky catalog for all chips into a single catalog for the entire field-of-view of this image.
[ "Convert", "sky", "catalog", "for", "all", "chips", "into", "a", "single", "catalog", "for", "the", "entire", "field", "-", "of", "-", "view", "of", "this", "image", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L340-L368
train
35,579
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
Image.buildDefaultRefWCS
def buildDefaultRefWCS(self): """ Generate a default reference WCS for this image. """ self.default_refWCS = None if self.use_wcs: wcslist = [] for scichip in self.chip_catalogs: wcslist.append(self.chip_catalogs[scichip]['wcs']) self.default_refWCS = utils.output_wcs(wcslist)
python
def buildDefaultRefWCS(self): """ Generate a default reference WCS for this image. """ self.default_refWCS = None if self.use_wcs: wcslist = [] for scichip in self.chip_catalogs: wcslist.append(self.chip_catalogs[scichip]['wcs']) self.default_refWCS = utils.output_wcs(wcslist)
[ "def", "buildDefaultRefWCS", "(", "self", ")", ":", "self", ".", "default_refWCS", "=", "None", "if", "self", ".", "use_wcs", ":", "wcslist", "=", "[", "]", "for", "scichip", "in", "self", ".", "chip_catalogs", ":", "wcslist", ".", "append", "(", "self",...
Generate a default reference WCS for this image.
[ "Generate", "a", "default", "reference", "WCS", "for", "this", "image", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L370-L377
train
35,580
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
Image.transformToRef
def transformToRef(self,ref_wcs,force=False): """ Transform sky coords from ALL chips into X,Y coords in reference WCS. """ if not isinstance(ref_wcs, pywcs.WCS): print(textutil.textbox('Reference WCS not a valid HSTWCS object'), file=sys.stderr) raise ValueError # Need to concatenate catalogs from each input if self.outxy is None or force: outxy = ref_wcs.wcs_world2pix(self.all_radec[0],self.all_radec[1],self.origin) # convert outxy list to a Nx2 array self.outxy = np.column_stack([outxy[0][:,np.newaxis],outxy[1][:,np.newaxis]]) if self.pars['writecat']: catname = self.rootname+"_refxy_catalog.coo" self.write_outxy(catname) self.catalog_names['ref_xy'] = catname
python
def transformToRef(self,ref_wcs,force=False): """ Transform sky coords from ALL chips into X,Y coords in reference WCS. """ if not isinstance(ref_wcs, pywcs.WCS): print(textutil.textbox('Reference WCS not a valid HSTWCS object'), file=sys.stderr) raise ValueError # Need to concatenate catalogs from each input if self.outxy is None or force: outxy = ref_wcs.wcs_world2pix(self.all_radec[0],self.all_radec[1],self.origin) # convert outxy list to a Nx2 array self.outxy = np.column_stack([outxy[0][:,np.newaxis],outxy[1][:,np.newaxis]]) if self.pars['writecat']: catname = self.rootname+"_refxy_catalog.coo" self.write_outxy(catname) self.catalog_names['ref_xy'] = catname
[ "def", "transformToRef", "(", "self", ",", "ref_wcs", ",", "force", "=", "False", ")", ":", "if", "not", "isinstance", "(", "ref_wcs", ",", "pywcs", ".", "WCS", ")", ":", "print", "(", "textutil", ".", "textbox", "(", "'Reference WCS not a valid HSTWCS objec...
Transform sky coords from ALL chips into X,Y coords in reference WCS.
[ "Transform", "sky", "coords", "from", "ALL", "chips", "into", "X", "Y", "coords", "in", "reference", "WCS", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L379-L394
train
35,581
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
Image.get_xy_catnames
def get_xy_catnames(self): """ Return a string with the names of input_xy catalog names """ catstr = self.name+' ' if 'input_xy' in self.catalog_names: for xycat in self.catalog_names['input_xy']: catstr += ' '+xycat return catstr + '\n'
python
def get_xy_catnames(self): """ Return a string with the names of input_xy catalog names """ catstr = self.name+' ' if 'input_xy' in self.catalog_names: for xycat in self.catalog_names['input_xy']: catstr += ' '+xycat return catstr + '\n'
[ "def", "get_xy_catnames", "(", "self", ")", ":", "catstr", "=", "self", ".", "name", "+", "' '", "if", "'input_xy'", "in", "self", ".", "catalog_names", ":", "for", "xycat", "in", "self", ".", "catalog_names", "[", "'input_xy'", "]", ":", "catstr", "+="...
Return a string with the names of input_xy catalog names
[ "Return", "a", "string", "with", "the", "names", "of", "input_xy", "catalog", "names" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L960-L967
train
35,582
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
Image.get_shiftfile_row
def get_shiftfile_row(self): """ Return the information for a shiftfile for this image to provide compatability with the IRAF-based MultiDrizzle. """ if self.fit is not None: rowstr = '%s %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f\n'%( self.name,self.fit['offset'][0],self.fit['offset'][1], self.fit['rot'],self.fit['scale'][0], self.fit['rms'][0],self.fit['rms'][1]) else: rowstr = None return rowstr
python
def get_shiftfile_row(self): """ Return the information for a shiftfile for this image to provide compatability with the IRAF-based MultiDrizzle. """ if self.fit is not None: rowstr = '%s %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f\n'%( self.name,self.fit['offset'][0],self.fit['offset'][1], self.fit['rot'],self.fit['scale'][0], self.fit['rms'][0],self.fit['rms'][1]) else: rowstr = None return rowstr
[ "def", "get_shiftfile_row", "(", "self", ")", ":", "if", "self", ".", "fit", "is", "not", "None", ":", "rowstr", "=", "'%s %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f\\n'", "%", "(", "self", ".", "name", ",", "self", ".", "fit", "[", "'offset'", "]", "...
Return the information for a shiftfile for this image to provide compatability with the IRAF-based MultiDrizzle.
[ "Return", "the", "information", "for", "a", "shiftfile", "for", "this", "image", "to", "provide", "compatability", "with", "the", "IRAF", "-", "based", "MultiDrizzle", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L1053-L1064
train
35,583
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
Image.clean
def clean(self): """ Remove intermediate files created. """ #TODO: add cleaning of mask files, *if* created ... for f in self.catalog_names: if 'match' in f: if os.path.exists(self.catalog_names[f]): log.info('Deleting intermediate match file: %s'% self.catalog_names[f]) os.remove(self.catalog_names[f]) else: for extn in f: if os.path.exists(extn): log.info('Deleting intermediate catalog: %d'%extn) os.remove(extn)
python
def clean(self): """ Remove intermediate files created. """ #TODO: add cleaning of mask files, *if* created ... for f in self.catalog_names: if 'match' in f: if os.path.exists(self.catalog_names[f]): log.info('Deleting intermediate match file: %s'% self.catalog_names[f]) os.remove(self.catalog_names[f]) else: for extn in f: if os.path.exists(extn): log.info('Deleting intermediate catalog: %d'%extn) os.remove(extn)
[ "def", "clean", "(", "self", ")", ":", "#TODO: add cleaning of mask files, *if* created ...", "for", "f", "in", "self", ".", "catalog_names", ":", "if", "'match'", "in", "f", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "catalog_names", "["...
Remove intermediate files created.
[ "Remove", "intermediate", "files", "created", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L1066-L1080
train
35,584
spacetelescope/drizzlepac
drizzlepac/imgclasses.py
RefImage.clean
def clean(self): """ Remove intermediate files created """ if not util.is_blank(self.catalog.catname) and os.path.exists(self.catalog.catname): os.remove(self.catalog.catname)
python
def clean(self): """ Remove intermediate files created """ if not util.is_blank(self.catalog.catname) and os.path.exists(self.catalog.catname): os.remove(self.catalog.catname)
[ "def", "clean", "(", "self", ")", ":", "if", "not", "util", ".", "is_blank", "(", "self", ".", "catalog", ".", "catname", ")", "and", "os", ".", "path", ".", "exists", "(", "self", ".", "catalog", ".", "catname", ")", ":", "os", ".", "remove", "(...
Remove intermediate files created
[ "Remove", "intermediate", "files", "created" ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L1443-L1447
train
35,585
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.close
def close(self): """ Close the object nicely and release all the data arrays from memory YOU CANT GET IT BACK, the pointers and data are gone so use the getData method to get the data array returned for future use. You can use putData to reattach a new data array to the imageObject. """ if self._image is None: return # mcara: I think the code below is not necessary but in order to # preserve the same functionality as the code removed below, # I make an empty copy of the image object: empty_image = fits.HDUList() for u in self._image: empty_image.append(u.__class__(data=None, header=None)) # mcara: END unnecessary code self._image.close() #calls fits.close() self._image = empty_image
python
def close(self): """ Close the object nicely and release all the data arrays from memory YOU CANT GET IT BACK, the pointers and data are gone so use the getData method to get the data array returned for future use. You can use putData to reattach a new data array to the imageObject. """ if self._image is None: return # mcara: I think the code below is not necessary but in order to # preserve the same functionality as the code removed below, # I make an empty copy of the image object: empty_image = fits.HDUList() for u in self._image: empty_image.append(u.__class__(data=None, header=None)) # mcara: END unnecessary code self._image.close() #calls fits.close() self._image = empty_image
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_image", "is", "None", ":", "return", "# mcara: I think the code below is not necessary but in order to", "# preserve the same functionality as the code removed below,", "# I make an empty copy of the image obje...
Close the object nicely and release all the data arrays from memory YOU CANT GET IT BACK, the pointers and data are gone so use the getData method to get the data array returned for future use. You can use putData to reattach a new data array to the imageObject.
[ "Close", "the", "object", "nicely", "and", "release", "all", "the", "data", "arrays", "from", "memory", "YOU", "CANT", "GET", "IT", "BACK", "the", "pointers", "and", "data", "are", "gone", "so", "use", "the", "getData", "method", "to", "get", "the", "dat...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L93-L113
train
35,586
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.clean
def clean(self): """ Deletes intermediate products generated for this imageObject. """ clean_files = ['blotImage','crmaskImage','finalMask', 'staticMask','singleDrizMask','outSky', 'outSContext','outSWeight','outSingle', 'outMedian','dqmask','tmpmask', 'skyMatchMask'] log.info('Removing intermediate files for %s' % self._filename) # We need to remove the combined products first; namely, median image util.removeFileSafely(self.outputNames['outMedian']) # Now remove chip-specific intermediate files, if any were created. for chip in self.returnAllChips(extname='SCI'): for fname in clean_files: if fname in chip.outputNames: util.removeFileSafely(chip.outputNames[fname])
python
def clean(self): """ Deletes intermediate products generated for this imageObject. """ clean_files = ['blotImage','crmaskImage','finalMask', 'staticMask','singleDrizMask','outSky', 'outSContext','outSWeight','outSingle', 'outMedian','dqmask','tmpmask', 'skyMatchMask'] log.info('Removing intermediate files for %s' % self._filename) # We need to remove the combined products first; namely, median image util.removeFileSafely(self.outputNames['outMedian']) # Now remove chip-specific intermediate files, if any were created. for chip in self.returnAllChips(extname='SCI'): for fname in clean_files: if fname in chip.outputNames: util.removeFileSafely(chip.outputNames[fname])
[ "def", "clean", "(", "self", ")", ":", "clean_files", "=", "[", "'blotImage'", ",", "'crmaskImage'", ",", "'finalMask'", ",", "'staticMask'", ",", "'singleDrizMask'", ",", "'outSky'", ",", "'outSContext'", ",", "'outSWeight'", ",", "'outSingle'", ",", "'outMedia...
Deletes intermediate products generated for this imageObject.
[ "Deletes", "intermediate", "products", "generated", "for", "this", "imageObject", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L131-L147
train
35,587
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.getData
def getData(self,exten=None): """ Return just the data array from the specified extension fileutil is used instead of fits to account for non- FITS input images. openImage returns a fits object. """ if exten.lower().find('sci') > -1: # For SCI extensions, the current file will have the data fname = self._filename else: # otherwise, the data being requested may need to come from a # separate file, as is the case with WFPC2 DQ data. # # convert exten to 'sci',extver to get the DQ info for that chip extn = exten.split(',') sci_chip = self._image[self.scienceExt,int(extn[1])] fname = sci_chip.dqfile extnum = self._interpretExten(exten) if self._image[extnum].data is None: if os.path.exists(fname): _image=fileutil.openImage(fname, clobber=False, memmap=False) _data=fileutil.getExtn(_image, extn=exten).data _image.close() del _image self._image[extnum].data = _data else: _data = None else: _data = self._image[extnum].data return _data
python
def getData(self,exten=None): """ Return just the data array from the specified extension fileutil is used instead of fits to account for non- FITS input images. openImage returns a fits object. """ if exten.lower().find('sci') > -1: # For SCI extensions, the current file will have the data fname = self._filename else: # otherwise, the data being requested may need to come from a # separate file, as is the case with WFPC2 DQ data. # # convert exten to 'sci',extver to get the DQ info for that chip extn = exten.split(',') sci_chip = self._image[self.scienceExt,int(extn[1])] fname = sci_chip.dqfile extnum = self._interpretExten(exten) if self._image[extnum].data is None: if os.path.exists(fname): _image=fileutil.openImage(fname, clobber=False, memmap=False) _data=fileutil.getExtn(_image, extn=exten).data _image.close() del _image self._image[extnum].data = _data else: _data = None else: _data = self._image[extnum].data return _data
[ "def", "getData", "(", "self", ",", "exten", "=", "None", ")", ":", "if", "exten", ".", "lower", "(", ")", ".", "find", "(", "'sci'", ")", ">", "-", "1", ":", "# For SCI extensions, the current file will have the data", "fname", "=", "self", ".", "_filenam...
Return just the data array from the specified extension fileutil is used instead of fits to account for non- FITS input images. openImage returns a fits object.
[ "Return", "just", "the", "data", "array", "from", "the", "specified", "extension", "fileutil", "is", "used", "instead", "of", "fits", "to", "account", "for", "non", "-", "FITS", "input", "images", ".", "openImage", "returns", "a", "fits", "object", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L149-L179
train
35,588
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.getHeader
def getHeader(self,exten=None): """ Return just the specified header extension fileutil is used instead of fits to account for non-FITS input images. openImage returns a fits object. """ _image=fileutil.openImage(self._filename, clobber=False, memmap=False) _header=fileutil.getExtn(_image,extn=exten).header _image.close() del _image return _header
python
def getHeader(self,exten=None): """ Return just the specified header extension fileutil is used instead of fits to account for non-FITS input images. openImage returns a fits object. """ _image=fileutil.openImage(self._filename, clobber=False, memmap=False) _header=fileutil.getExtn(_image,extn=exten).header _image.close() del _image return _header
[ "def", "getHeader", "(", "self", ",", "exten", "=", "None", ")", ":", "_image", "=", "fileutil", ".", "openImage", "(", "self", ".", "_filename", ",", "clobber", "=", "False", ",", "memmap", "=", "False", ")", "_header", "=", "fileutil", ".", "getExtn"...
Return just the specified header extension fileutil is used instead of fits to account for non-FITS input images. openImage returns a fits object.
[ "Return", "just", "the", "specified", "header", "extension", "fileutil", "is", "used", "instead", "of", "fits", "to", "account", "for", "non", "-", "FITS", "input", "images", ".", "openImage", "returns", "a", "fits", "object", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L181-L190
train
35,589
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.updateData
def updateData(self,exten,data): """ Write out updated data and header to the original input file for this object. """ _extnum=self._interpretExten(exten) fimg = fileutil.openImage(self._filename, mode='update', memmap=False) fimg[_extnum].data = data fimg[_extnum].header = self._image[_extnum].header fimg.close()
python
def updateData(self,exten,data): """ Write out updated data and header to the original input file for this object. """ _extnum=self._interpretExten(exten) fimg = fileutil.openImage(self._filename, mode='update', memmap=False) fimg[_extnum].data = data fimg[_extnum].header = self._image[_extnum].header fimg.close()
[ "def", "updateData", "(", "self", ",", "exten", ",", "data", ")", ":", "_extnum", "=", "self", ".", "_interpretExten", "(", "exten", ")", "fimg", "=", "fileutil", ".", "openImage", "(", "self", ".", "_filename", ",", "mode", "=", "'update'", ",", "memm...
Write out updated data and header to the original input file for this object.
[ "Write", "out", "updated", "data", "and", "header", "to", "the", "original", "input", "file", "for", "this", "object", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L212-L220
train
35,590
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.getAllData
def getAllData(self,extname=None,exclude=None): """ This function is meant to make it easier to attach ALL the data extensions of the image object so that we can write out copies of the original image nicer. If no extname is given, the it retrieves all data from the original file and attaches it. Otherwise, give the name of the extensions you want and all of those will be restored. Ok, I added another option. If you want to get all the data extensions EXCEPT a particular one, leave extname=NONE and set exclude=EXTNAME. This is helpfull cause you might not know all the extnames the image has, this will find out and exclude the one you do not want overwritten. """ extensions = self._findExtnames(extname=extname,exclude=exclude) for i in range(1,self._nextend+1,1): if hasattr(self._image[i],'_extension') and \ "IMAGE" in self._image[i]._extension: extver = self._image[i].header['extver'] if (self._image[i].extname in extensions) and self._image[self.scienceExt,extver].group_member: self._image[i].data=self.getData(self._image[i].extname + ','+str(self._image[i].extver))
python
def getAllData(self,extname=None,exclude=None): """ This function is meant to make it easier to attach ALL the data extensions of the image object so that we can write out copies of the original image nicer. If no extname is given, the it retrieves all data from the original file and attaches it. Otherwise, give the name of the extensions you want and all of those will be restored. Ok, I added another option. If you want to get all the data extensions EXCEPT a particular one, leave extname=NONE and set exclude=EXTNAME. This is helpfull cause you might not know all the extnames the image has, this will find out and exclude the one you do not want overwritten. """ extensions = self._findExtnames(extname=extname,exclude=exclude) for i in range(1,self._nextend+1,1): if hasattr(self._image[i],'_extension') and \ "IMAGE" in self._image[i]._extension: extver = self._image[i].header['extver'] if (self._image[i].extname in extensions) and self._image[self.scienceExt,extver].group_member: self._image[i].data=self.getData(self._image[i].extname + ','+str(self._image[i].extver))
[ "def", "getAllData", "(", "self", ",", "extname", "=", "None", ",", "exclude", "=", "None", ")", ":", "extensions", "=", "self", ".", "_findExtnames", "(", "extname", "=", "extname", ",", "exclude", "=", "exclude", ")", "for", "i", "in", "range", "(", ...
This function is meant to make it easier to attach ALL the data extensions of the image object so that we can write out copies of the original image nicer. If no extname is given, the it retrieves all data from the original file and attaches it. Otherwise, give the name of the extensions you want and all of those will be restored. Ok, I added another option. If you want to get all the data extensions EXCEPT a particular one, leave extname=NONE and set exclude=EXTNAME. This is helpfull cause you might not know all the extnames the image has, this will find out and exclude the one you do not want overwritten.
[ "This", "function", "is", "meant", "to", "make", "it", "easier", "to", "attach", "ALL", "the", "data", "extensions", "of", "the", "image", "object", "so", "that", "we", "can", "write", "out", "copies", "of", "the", "original", "image", "nicer", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L246-L269
train
35,591
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject._findExtnames
def _findExtnames(self, extname=None, exclude=None): """ This method builds a list of all extensions which have 'EXTNAME'==extname and do not include any extensions with 'EXTNAME'==exclude, if any are specified for exclusion at all. """ #make a list of the available extension names for the object extensions=[] if extname is not None: if not isinstance(extname,list): extname=[extname] for extn in extname: extensions.append(extn.upper()) else: #restore all the extensions data from the original file, be careful here #if you've altered data in memory you want to keep! for i in range(1,self._nextend+1,1): if hasattr(self._image[i],'_extension') and \ "IMAGE" in self._image[i]._extension: if self._image[i].extname.upper() not in extensions: extensions.append(self._image[i].extname) #remove this extension from the list if exclude is not None: exclude.upper() if exclude in extensions: newExt=[] for item in extensions: if item != exclude: newExt.append(item) extensions=newExt del newExt return extensions
python
def _findExtnames(self, extname=None, exclude=None): """ This method builds a list of all extensions which have 'EXTNAME'==extname and do not include any extensions with 'EXTNAME'==exclude, if any are specified for exclusion at all. """ #make a list of the available extension names for the object extensions=[] if extname is not None: if not isinstance(extname,list): extname=[extname] for extn in extname: extensions.append(extn.upper()) else: #restore all the extensions data from the original file, be careful here #if you've altered data in memory you want to keep! for i in range(1,self._nextend+1,1): if hasattr(self._image[i],'_extension') and \ "IMAGE" in self._image[i]._extension: if self._image[i].extname.upper() not in extensions: extensions.append(self._image[i].extname) #remove this extension from the list if exclude is not None: exclude.upper() if exclude in extensions: newExt=[] for item in extensions: if item != exclude: newExt.append(item) extensions=newExt del newExt return extensions
[ "def", "_findExtnames", "(", "self", ",", "extname", "=", "None", ",", "exclude", "=", "None", ")", ":", "#make a list of the available extension names for the object", "extensions", "=", "[", "]", "if", "extname", "is", "not", "None", ":", "if", "not", "isinsta...
This method builds a list of all extensions which have 'EXTNAME'==extname and do not include any extensions with 'EXTNAME'==exclude, if any are specified for exclusion at all.
[ "This", "method", "builds", "a", "list", "of", "all", "extensions", "which", "have", "EXTNAME", "==", "extname", "and", "do", "not", "include", "any", "extensions", "with", "EXTNAME", "==", "exclude", "if", "any", "are", "specified", "for", "exclusion", "at"...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L288-L317
train
35,592
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.findExtNum
def findExtNum(self, extname=None, extver=1): """Find the extension number of the give extname and extver.""" extnum = None extname = extname.upper() if not self._isSimpleFits: for ext in self._image: if (hasattr(ext,'_extension') and 'IMAGE' in ext._extension and (ext.extname == extname) and (ext.extver == extver)): extnum = ext.extnum else: log.info("Image is simple fits") return extnum
python
def findExtNum(self, extname=None, extver=1): """Find the extension number of the give extname and extver.""" extnum = None extname = extname.upper() if not self._isSimpleFits: for ext in self._image: if (hasattr(ext,'_extension') and 'IMAGE' in ext._extension and (ext.extname == extname) and (ext.extver == extver)): extnum = ext.extnum else: log.info("Image is simple fits") return extnum
[ "def", "findExtNum", "(", "self", ",", "extname", "=", "None", ",", "extver", "=", "1", ")", ":", "extnum", "=", "None", "extname", "=", "extname", ".", "upper", "(", ")", "if", "not", "self", ".", "_isSimpleFits", ":", "for", "ext", "in", "self", ...
Find the extension number of the give extname and extver.
[ "Find", "the", "extension", "number", "of", "the", "give", "extname", "and", "extver", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L319-L332
train
35,593
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject._assignRootname
def _assignRootname(self, chip): """ Assign a unique rootname for the image based in the expname. """ extname=self._image[self.scienceExt,chip].header["EXTNAME"].lower() extver=self._image[self.scienceExt,chip].header["EXTVER"] expname = self._rootname # record extension-based name to reflect what extension a mask file corresponds to self._image[self.scienceExt,chip].rootname=expname + "_" + extname + str(extver) self._image[self.scienceExt,chip].sciname=self._filename + "[" + extname +","+str(extver)+"]" self._image[self.scienceExt,chip].dqrootname=self._rootname + "_" + extname + str(extver) # Needed to keep EXPNAMEs associated properly (1 EXPNAME for all chips) self._image[self.scienceExt,chip]._expname=expname self._image[self.scienceExt,chip]._chip =chip
python
def _assignRootname(self, chip): """ Assign a unique rootname for the image based in the expname. """ extname=self._image[self.scienceExt,chip].header["EXTNAME"].lower() extver=self._image[self.scienceExt,chip].header["EXTVER"] expname = self._rootname # record extension-based name to reflect what extension a mask file corresponds to self._image[self.scienceExt,chip].rootname=expname + "_" + extname + str(extver) self._image[self.scienceExt,chip].sciname=self._filename + "[" + extname +","+str(extver)+"]" self._image[self.scienceExt,chip].dqrootname=self._rootname + "_" + extname + str(extver) # Needed to keep EXPNAMEs associated properly (1 EXPNAME for all chips) self._image[self.scienceExt,chip]._expname=expname self._image[self.scienceExt,chip]._chip =chip
[ "def", "_assignRootname", "(", "self", ",", "chip", ")", ":", "extname", "=", "self", ".", "_image", "[", "self", ".", "scienceExt", ",", "chip", "]", ".", "header", "[", "\"EXTNAME\"", "]", ".", "lower", "(", ")", "extver", "=", "self", ".", "_image...
Assign a unique rootname for the image based in the expname.
[ "Assign", "a", "unique", "rootname", "for", "the", "image", "based", "in", "the", "expname", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L334-L346
train
35,594
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject._setOutputNames
def _setOutputNames(self,rootname,suffix='_drz'): """ Define the default output filenames for drizzle products, these are based on the original rootname of the image filename should be just 1 filename, so call this in a loop for chip names contained inside a file. """ # Define FITS output filenames for intermediate products # Build names based on final DRIZZLE output name # where 'output' normally would have been created # by 'process_input()' # outFinal = rootname+suffix+'.fits' outSci = rootname+suffix+'_sci.fits' outWeight = rootname+suffix+'_wht.fits' outContext = rootname+suffix+'_ctx.fits' outMedian = rootname+'_med.fits' # Build names based on input name origFilename = self._filename.replace('.fits','_OrIg.fits') outSky = rootname + '_sky.fits' outSingle = rootname+'_single_sci.fits' outSWeight = rootname+'_single_wht.fits' crCorImage = rootname+'_crclean.fits' # Build outputNames dictionary fnames={ 'origFilename': origFilename, 'outFinal': outFinal, 'outMedian': outMedian, 'outSci': outSci, 'outWeight': outWeight, 'outContext': outContext, 'outSingle': outSingle, 'outSWeight': outSWeight, 'outSContext': None, 'outSky': outSky, 'crcorImage': crCorImage, 'ivmFile': None } return fnames
python
def _setOutputNames(self,rootname,suffix='_drz'): """ Define the default output filenames for drizzle products, these are based on the original rootname of the image filename should be just 1 filename, so call this in a loop for chip names contained inside a file. """ # Define FITS output filenames for intermediate products # Build names based on final DRIZZLE output name # where 'output' normally would have been created # by 'process_input()' # outFinal = rootname+suffix+'.fits' outSci = rootname+suffix+'_sci.fits' outWeight = rootname+suffix+'_wht.fits' outContext = rootname+suffix+'_ctx.fits' outMedian = rootname+'_med.fits' # Build names based on input name origFilename = self._filename.replace('.fits','_OrIg.fits') outSky = rootname + '_sky.fits' outSingle = rootname+'_single_sci.fits' outSWeight = rootname+'_single_wht.fits' crCorImage = rootname+'_crclean.fits' # Build outputNames dictionary fnames={ 'origFilename': origFilename, 'outFinal': outFinal, 'outMedian': outMedian, 'outSci': outSci, 'outWeight': outWeight, 'outContext': outContext, 'outSingle': outSingle, 'outSWeight': outSWeight, 'outSContext': None, 'outSky': outSky, 'crcorImage': crCorImage, 'ivmFile': None } return fnames
[ "def", "_setOutputNames", "(", "self", ",", "rootname", ",", "suffix", "=", "'_drz'", ")", ":", "# Define FITS output filenames for intermediate products", "# Build names based on final DRIZZLE output name", "# where 'output' normally would have been created", "# by 'process_input()'...
Define the default output filenames for drizzle products, these are based on the original rootname of the image filename should be just 1 filename, so call this in a loop for chip names contained inside a file.
[ "Define", "the", "default", "output", "filenames", "for", "drizzle", "products", "these", "are", "based", "on", "the", "original", "rootname", "of", "the", "image", "filename", "should", "be", "just", "1", "filename", "so", "call", "this", "in", "a", "loop",...
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L348-L389
train
35,595
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject._initVirtualOutputs
def _initVirtualOutputs(self): """ Sets up the structure to hold all the output data arrays for this image in memory. """ self.virtualOutputs = {} for product in self.outputNames: self.virtualOutputs[product] = None
python
def _initVirtualOutputs(self): """ Sets up the structure to hold all the output data arrays for this image in memory. """ self.virtualOutputs = {} for product in self.outputNames: self.virtualOutputs[product] = None
[ "def", "_initVirtualOutputs", "(", "self", ")", ":", "self", ".", "virtualOutputs", "=", "{", "}", "for", "product", "in", "self", ".", "outputNames", ":", "self", ".", "virtualOutputs", "[", "product", "]", "=", "None" ]
Sets up the structure to hold all the output data arrays for this image in memory.
[ "Sets", "up", "the", "structure", "to", "hold", "all", "the", "output", "data", "arrays", "for", "this", "image", "in", "memory", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L417-L423
train
35,596
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.saveVirtualOutputs
def saveVirtualOutputs(self,outdict): """ Assign in-memory versions of generated products for this ``imageObject`` based on dictionary 'outdict'. """ if not self.inmemory: return for outname in outdict: self.virtualOutputs[outname] = outdict[outname]
python
def saveVirtualOutputs(self,outdict): """ Assign in-memory versions of generated products for this ``imageObject`` based on dictionary 'outdict'. """ if not self.inmemory: return for outname in outdict: self.virtualOutputs[outname] = outdict[outname]
[ "def", "saveVirtualOutputs", "(", "self", ",", "outdict", ")", ":", "if", "not", "self", ".", "inmemory", ":", "return", "for", "outname", "in", "outdict", ":", "self", ".", "virtualOutputs", "[", "outname", "]", "=", "outdict", "[", "outname", "]" ]
Assign in-memory versions of generated products for this ``imageObject`` based on dictionary 'outdict'.
[ "Assign", "in", "-", "memory", "versions", "of", "generated", "products", "for", "this", "imageObject", "based", "on", "dictionary", "outdict", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L425-L432
train
35,597
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.getOutputName
def getOutputName(self,name): """ Return the name of the file or PyFITS object associated with that name, depending on the setting of self.inmemory. """ val = self.outputNames[name] if self.inmemory: # if inmemory was turned on... # return virtualOutput object saved with that name val = self.virtualOutputs[val] return val
python
def getOutputName(self,name): """ Return the name of the file or PyFITS object associated with that name, depending on the setting of self.inmemory. """ val = self.outputNames[name] if self.inmemory: # if inmemory was turned on... # return virtualOutput object saved with that name val = self.virtualOutputs[val] return val
[ "def", "getOutputName", "(", "self", ",", "name", ")", ":", "val", "=", "self", ".", "outputNames", "[", "name", "]", "if", "self", ".", "inmemory", ":", "# if inmemory was turned on...", "# return virtualOutput object saved with that name", "val", "=", "self", "....
Return the name of the file or PyFITS object associated with that name, depending on the setting of self.inmemory.
[ "Return", "the", "name", "of", "the", "file", "or", "PyFITS", "object", "associated", "with", "that", "name", "depending", "on", "the", "setting", "of", "self", ".", "inmemory", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L434-L442
train
35,598
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.updateOutputValues
def updateOutputValues(self,output_wcs): """ Copy info from output WCSObject into outputnames for each chip for use in creating outputimage object. """ outputvals = self.outputValues outputvals['output'] = output_wcs.outputNames['outFinal'] outputvals['outnx'], outputvals['outny'] = output_wcs.wcs.pixel_shape outputvals['texptime'] = output_wcs._exptime outputvals['texpstart'] = output_wcs._expstart outputvals['texpend'] = output_wcs._expend outputvals['nimages'] = output_wcs.nimages outputvals['scale'] = output_wcs.wcs.pscale #/ self._image[self.scienceExt,1].wcs.pscale outputvals['exptime'] = self._exptime outnames = self.outputNames outnames['outMedian'] = output_wcs.outputNames['outMedian'] outnames['outFinal'] = output_wcs.outputNames['outFinal'] outnames['outSci'] = output_wcs.outputNames['outSci'] outnames['outWeight'] = output_wcs.outputNames['outWeight'] outnames['outContext'] = output_wcs.outputNames['outContext']
python
def updateOutputValues(self,output_wcs): """ Copy info from output WCSObject into outputnames for each chip for use in creating outputimage object. """ outputvals = self.outputValues outputvals['output'] = output_wcs.outputNames['outFinal'] outputvals['outnx'], outputvals['outny'] = output_wcs.wcs.pixel_shape outputvals['texptime'] = output_wcs._exptime outputvals['texpstart'] = output_wcs._expstart outputvals['texpend'] = output_wcs._expend outputvals['nimages'] = output_wcs.nimages outputvals['scale'] = output_wcs.wcs.pscale #/ self._image[self.scienceExt,1].wcs.pscale outputvals['exptime'] = self._exptime outnames = self.outputNames outnames['outMedian'] = output_wcs.outputNames['outMedian'] outnames['outFinal'] = output_wcs.outputNames['outFinal'] outnames['outSci'] = output_wcs.outputNames['outSci'] outnames['outWeight'] = output_wcs.outputNames['outWeight'] outnames['outContext'] = output_wcs.outputNames['outContext']
[ "def", "updateOutputValues", "(", "self", ",", "output_wcs", ")", ":", "outputvals", "=", "self", ".", "outputValues", "outputvals", "[", "'output'", "]", "=", "output_wcs", ".", "outputNames", "[", "'outFinal'", "]", "outputvals", "[", "'outnx'", "]", ",", ...
Copy info from output WCSObject into outputnames for each chip for use in creating outputimage object.
[ "Copy", "info", "from", "output", "WCSObject", "into", "outputnames", "for", "each", "chip", "for", "use", "in", "creating", "outputimage", "object", "." ]
15bec3c929a6a869d9e71b9398ced43ede0620f1
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L447-L468
train
35,599