Example #1
0
def galex_tractor_image(tile, band, galex_dir, radecbox, bandname):
    from tractor import (NanoMaggies, Image, LinearPhotoCal,
                         ConstantFitsWcs, ConstantSky)

    assert(band in ['n','f'])

    #nicegbands = ['NUV', 'FUV']
    #zps = dict(n=20.08, f=18.82)
    #zp = zps[band]
    
    imfn = os.path.join(galex_dir, tile.tilename.strip(),
                        '%s-%sd-intbgsub.fits.gz' % (tile.visitname.strip(), band))
    gwcs = Tan(*[float(f) for f in
                 [tile.crval1, tile.crval2, tile.crpix1, tile.crpix2,
                  tile.cdelt1, 0., 0., tile.cdelt2, 3840., 3840.]])
    (r0,r1,d0,d1) = radecbox
    H,W = gwcs.shape
    ok,xx,yy = gwcs.radec2pixelxy([r0,r0,r1,r1], [d0,d1,d1,d0])
    #print('GALEX WCS pixel positions of RA,Dec box:', xx, yy)
    if np.any(np.logical_not(ok)):
        return None
    x0 = np.clip(np.floor(xx-1).astype(int).min(), 0, W-1)
    x1 = np.clip(np.ceil (xx-1).astype(int).max(), 0, W)
    if x1-x0 <= 1:
        return None
    y0 = np.clip(np.floor(yy-1).astype(int).min(), 0, H-1)
    y1 = np.clip(np.ceil (yy-1).astype(int).max(), 0, H)
    if y1-y0 <= 1:
        return None
    debug('Reading GALEX subimage x0,y0', x0,y0, 'size', x1-x0, y1-y0)
    gwcs = gwcs.get_subimage(x0, y0, x1 - x0, y1 - y0)
    twcs = ConstantFitsWcs(gwcs)
    roislice = (slice(y0, y1), slice(x0, x1))
    
    fitsimg = fitsio.FITS(imfn)[0]
    hdr = fitsimg.read_header()
    img = fitsimg[roislice]

    inverr = np.ones_like(img)
    inverr[img == 0.] = 0.

    zp = tile.get('%s_zpmag' % band)
    
    photocal = LinearPhotoCal(NanoMaggies.zeropointToScale(zp), band=bandname)

    tsky = ConstantSky(0.)

    name = 'GALEX ' + hdr['OBJECT'] + ' ' + band

    psfimg = galex_psf(band, galex_dir)
    tpsf = PixelizedPSF(psfimg)

    tim = Image(data=img, inverr=inverr, psf=tpsf, wcs=twcs,
                sky=tsky, photocal=photocal, name=name)
    tim.roi = [x0,x1,y0,y1]
    return tim
Example #2
0
def get_unwise_tractor_image(basedir,
                             tile,
                             band,
                             bandname=None,
                             masked=True,
                             **kwargs):
    '''
    masked: read "-m" images, or "-u"?

    bandname: PhotoCal band name to use: default: "w%i" % band
    '''

    if bandname is None:
        bandname = 'w%i' % band

    mu = 'm' if masked else 'u'

    # Allow multiple colon-separated unwise-coadd directories.
    basedirs = basedir.split(':')
    foundFiles = False
    for basedir in basedirs:
        thisdir = get_unwise_tile_dir(basedir, tile)
        base = os.path.join(thisdir, 'unwise-%s-w%i-' % (tile, band))

        imfn = base + 'img-%s.fits' % mu
        ivfn = base + 'invvar-%s.fits.gz' % mu
        # ppfn = base + 'std-%s.fits.gz'    % mu
        nifn = base + 'n-%s.fits.gz' % mu
        nufn = base + 'n-u.fits.gz'

        if not os.path.exists(imfn):
            print('Does not exist:', imfn)
            continue
        print('Reading', imfn)
        wcs = Tan(imfn)
        twcs = ConstantFitsWcs(wcs)

        F = fitsio.FITS(imfn)
        img = F[0]
        hdr = img.read_header()
        H, W = img.get_info()['dims']
        H, W = int(H), int(W)

        roi = interpret_roi(twcs, (H, W), **kwargs)
        if roi is None:
            # No overlap with ROI
            return None
        # interpret_roi returns None or a tuple; drop the second element in the tuple.
        roi, nil = roi
        (x0, x1, y0, y1) = roi

        wcs = wcs.get_subimage(x0, y0, x1 - x0, y1 - y0)
        twcs = ConstantFitsWcs(wcs)
        roislice = (slice(y0, y1), slice(x0, x1))
        img = img[roislice]

        if not os.path.exists(ivfn) and os.path.exists(
                ivfn.replace('.fits.gz', '.fits')):
            ivfn = ivfn.replace('.fits.gz', '.fits')
        if not os.path.exists(nifn) and os.path.exists(
                nifn.replace('.fits.gz', '.fits')):
            nifn = nifn.replace('.fits.gz', '.fits')
        if not os.path.exists(nufn) and os.path.exists(
                nufn.replace('.fits.gz', '.fits')):
            nufn = nufn.replace('.fits.gz', '.fits')

        if not (os.path.exists(ivfn) and os.path.exists(nifn)
                and os.path.exists(nufn)):
            print('Files do not exist:', ivfn, nifn, nufn)
            continue

        foundFiles = True
        break

    if not foundFiles:
        raise IOError('unWISE files not found in ' + str(basedirs) +
                      ' for tile ' + tile)

    print('Reading', ivfn)
    invvar = fitsio.FITS(ivfn)[0][roislice]

    if band == 4:
        # due to upsampling, effective invvar is smaller (the pixels
        # are correlated)
        invvar *= 0.25

    # print 'Reading', ppfn
    #pp = fitsio.FITS(ppfn)[0][roislice]
    print('Reading', nifn)
    nims = fitsio.FITS(nifn)[0][roislice]

    if nufn == nifn:
        nuims = nims
    else:
        print('Reading', nufn)
        nuims = fitsio.FITS(nufn)[0][roislice]

    # print 'Median # ims:', np.median(nims)
    good = (nims > 0)
    invvar[np.logical_not(good)] = 0.
    sig1 = 1. / np.sqrt(np.median(invvar[good]))

    # Load the average PSF model (generated by wise_psf.py)
    psffn = os.path.join(os.path.dirname(__file__), 'wise-psf-avg.fits')
    print('Reading', psffn)
    P = fits_table(psffn, hdu=band)
    psf = GaussianMixturePSF(P.amp, P.mean, P.var)

    sky = 0.
    tsky = ConstantSky(sky)

    # if opt.errfrac > 0:
    #     nz = (iv > 0)
    #     iv2 = np.zeros_like(invvar)
    #     iv2[nz] = 1./(1./invvar[nz] + (img[nz] * opt.errfrac)**2)
    #     print 'Increasing error estimate by', opt.errfrac, 'of image flux'
    #     invvar = iv2

    tim = Image(data=img,
                invvar=invvar,
                psf=psf,
                wcs=twcs,
                sky=tsky,
                photocal=LinearPhotoCal(1., band=bandname),
                name='unWISE %s W%i' % (tile, band))
    tim.sig1 = sig1
    tim.roi = roi
    tim.nims = nims
    tim.nuims = nuims
    tim.hdr = hdr

    if 'MJDMIN' in hdr and 'MJDMAX' in hdr:
        from tractor.tractortime import TAITime
        tim.mjdmin = hdr['MJDMIN']
        tim.mjdmax = hdr['MJDMAX']
        tim.time = TAITime(None, mjd=(tim.mjdmin + tim.mjdmax) / 2.)

    return tim