Ejemplo n.º 1
0
def update_image_wcs_info(tweakwcs_output,imagelist):
    """Write newly computed WCS information to image headers

    Parameters
    ----------
    tweakwcs_output : list
        output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid
        input image.

    imagelist : list
        list of valid processed images to be updated

    Returns
    -------
    Nothing!
    """
    imgctr = 0
    for item in tweakwcs_output:
        #print('YYYYYYYYY',item.wcs.pscale)
        if item.meta['chip'] == 1:  # to get the image name straight regardless of the number of chips
            image_name = imagelist[imgctr]
            if imgctr > 0: #close previously opened image
                print("CLOSE {}".format(hdulist[0].header['FILENAME'])) #TODO: Remove before deployment
                hdulist.flush()
                hdulist.close()
            hdulist = fits.open(image_name, mode='update')
            sciExtDict = {}
            for sciExtCtr in range(1, amutils.countExtn(hdulist) + 1): #establish correct mapping to the science extensions
                sciExtDict["{}".format(sciExtCtr)] = fileutil.findExtname(hdulist,'sci',extver=sciExtCtr)
            imgctr += 1
        updatehdr.update_wcs(hdulist, sciExtDict["{}".format(item.meta['chip'])], item.wcs, wcsname='TWEAKDEV', reusename=True, verbose=True) #TODO: May want to settle on a better name for 'wcsname'
        print()
    print("CLOSE {}".format(hdulist[0].header['FILENAME'])) #TODO: Remove before deployment
    hdulist.flush() #close last image
    hdulist.close()
Ejemplo n.º 2
0
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['tweakwcs_info']['catalog'])
                else:
                    wcsName = '{}-FIT_{}'.format(
                        wname, item.meta['tweakwcs_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
            print("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)
            print("Wrote headerlet file {}.\n\n".format(headerlet_filename))
            out_headerlet_dict[imageName] = headerlet_filename

        chipctr += 1
    return (out_headerlet_dict)
Ejemplo n.º 3
0
def update_image_wcs_info(tweakwcs_output,
                          headerlet_filenames=None,
                          fit_label=None):
    """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
            every valid input image.

        headerlet_filenames : dictionary, optional
            dictionary that maps the flt/flc.fits file name to the corresponding custom headerlet filename.

        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:
        image_name = item.meta['filename']
        chipnum = item.meta['chip']
        hdulist = fits.open(image_name, mode='update')
        if chipnum == 1:
            chipctr = 1
            num_sci_ext = amutils.countExtn(hdulist)

            # generate wcs name for updated image header, headerlet
            # Just in case header value 'wcs_name' is empty.
            if fit_label is None:
                if 'relative' in item.meta['fit method']:
                    fit_label = 'REL'
                else:
                    fit_label = 'IMG'

            if not hdulist['SCI', 1].header['WCSNAME'] or hdulist[
                    'SCI', 1].header['WCSNAME'] == "":
                wcs_name = "FIT_{}_{}".format(fit_label,
                                              item.meta['catalog_name'])
            else:
                wname = hdulist['sci', 1].header['wcsname']
                if "-" in wname:
                    wcs_name = '{}-FIT_{}_{}'.format(
                        wname[:wname.index('-')], fit_label,
                        item.meta['fit_info']['catalog'])
                else:
                    wcs_name = '{}-FIT_{}_{}'.format(
                        wname, fit_label, item.meta['fit_info']['catalog'])

            # establish correct mapping to the science extensions
            sci_ext_dict = {}
            for sci_ext_ctr in range(1, num_sci_ext + 1):
                sci_ext_dict["{}".format(sci_ext_ctr)] = fileutil.findExtname(
                    hdulist, 'sci', extver=sci_ext_ctr)

        # update header with new WCS info
        sci_extn = sci_ext_dict["{}".format(item.meta['chip'])]
        hdr_name = "{}_{}-hlet.fits".format(image_name.rstrip(".fits"),
                                            wcs_name)
        updatehdr.update_wcs(hdulist,
                             sci_extn,
                             item.wcs,
                             wcsname=wcs_name,
                             reusename=True)
        info = item.meta['fit_info']
        hdulist[sci_extn].header['RMS_RA'] = info['RMS_RA'].value if info[
            'RMS_RA'] is not None else -1.0
        hdulist[sci_extn].header['RMS_DEC'] = info['RMS_DEC'].value if info[
            'RMS_DEC'] is not None else -1.0
        hdulist[sci_extn].header['CRDER1'] = info['RMS_RA'].value if info[
            'RMS_RA'] is not None else -1.0
        hdulist[sci_extn].header['CRDER2'] = info['RMS_DEC'].value if info[
            'RMS_DEC'] is not None else -1.0
        hdulist[sci_extn].header['NMATCHES'] = len(
            info['ref_mag']) if info['ref_mag'] is not None else -1.0
        if 'HDRNAME' in hdulist[sci_extn].header:
            del hdulist[sci_extn].header['HDRNAME']
        hdulist[sci_extn].header['HDRNAME'] = hdr_name
        hdulist.flush()
        hdulist.close()

        # Create headerlet
        out_headerlet = headerlet.create_headerlet(image_name,
                                                   hdrname=hdr_name,
                                                   wcsname=wcs_name,
                                                   logging=False)

        # Update headerlet
        update_headerlet_phdu(item, out_headerlet)

        # Write headerlet
        if headerlet_filenames:
            headerlet_filename = headerlet_filenames[
                image_name]  # Use HAP-compatible filename defined in runhlaprocessing.py
        else:
            if image_name.endswith("flc.fits"):
                headerlet_filename = image_name.replace("flc", "flt_hlet")
            if image_name.endswith("flt.fits"):
                headerlet_filename = image_name.replace("flt", "flt_hlet")
        out_headerlet.writeto(headerlet_filename, overwrite=True)
        log.info("Wrote headerlet file {}.\n\n".format(headerlet_filename))
        out_headerlet_dict[image_name] = headerlet_filename

        # Attach headerlet as HDRLET extension
        if headerlet.verify_hdrname_is_unique(hdulist, hdr_name):
            headerlet.attach_headerlet(image_name,
                                       headerlet_filename,
                                       logging=False)

        chipctr += 1
    return (out_headerlet_dict)
Ejemplo n.º 4
0
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,memmap=0,mode='readonly')
    try:
        _extn = fileutil.findExtname(fdq,extname,extver=extver)
        if _extn != 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 == 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 != 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, 'append')
        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
Ejemplo n.º 5
0
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