Exemple #1
0
def coords_in_image(xc,yc,header,coordsys='celestial'):
    """
    Determine whether the coordinates are within the boundaries of the image
    """
    try:
        wcs = pywcs.WCS(header)
    except: # if the header isn't WCS compatible, we don't want it
        return False

    try:
        if coordsys=='celestial' and wcs.wcs.lngtyp=='GLON':
            xc,yc = coords.Position((xc,yc),system=coordsys).galactic()
        elif coordsys=='galactic' and wcs.wcs.lngtyp=='RA':
            xc,yc = coords.Position((xc,yc),system=coordsys).j2000()

        xp,yp = wcs.wcs_sky2pix(xc,yc,0)
    except:
        return False

    if xp > wcs.naxis1 or xp < 0:
        return False
    elif yp > wcs.naxis2 or yp < 0:
        return False
    else:
        return True
Exemple #2
0
def posang(l1, b1, l2, b2, system='galactic', **kwargs):
    """
    Return the position angle between two points assuming a rectilinear
    coordinate system (I think; at the very least I am making no corrections
    for wcs).

    INPUT:
    longitude1, latitude1, longitude2, latitude2

    Defaults to GALACTIC coordinates.  **kwargs are passed to coords.Position
    """
    if not coordsOK:
        raise ImportError("posang requires coords.")
    pos1 = coords.Position([l1, b1], system=system, **kwargs)
    ra1, dec1 = pos1.j2000()
    pos2 = coords.Position([l2, b2], system=system, **kwargs)
    ra2, dec2 = pos2.j2000()

    radiff = (ra1 - ra2) / 180. * pi

    angle = arctan2(
        sin(radiff),
        cos(dec1 * pi / 180.) * tan(dec2 * pi / 180.) -
        sin(dec1 * pi / 180.) * cos(radiff)) / pi * 180

    return angle
Exemple #3
0
def cenfile_overlays(cenfile):
    cen = readcol(cenfile, comment="#", asStruct=True)

    for name, ra, dec, obra, obdec in zip(cen.filename, cen.radeg, cen.decdeg,
                                          cen.obj_ra, cen.obj_dec):
        print name
        pos = coords.Position((ra, dec))
        xc, yc = pos.galactic()
        objpos = coords.Position((obra, obdec))
        xtr, ytr = objpos.galactic()

        make_overlay(name.tolist(), xc, yc, xtr, ytr)
        pylab.figure(0)
        pylab.clf()
Exemple #4
0
    def position_region(reg):
        """
        small wrapper to get a Position object using the correct coordinate system

        reg must by a pyregion Shape instance
        """
        x, y = reg.coord_list[:2]
        posn = coords.Position([x, y], system=coords_format(reg.coord_format))
        return posn
Exemple #5
0
def list_targets(sdfitsfile, doprint=True):
    """
    List the targets, their location on the sky...
    """
    bintable = _get_bintable(sdfitsfile)

    # Things to include:
    #   Scan           Source      Vel    Proc Seqn   RestF nIF nInt nFd     Az    El
    #        1      G33.13-0.09     87.4     Nod    1  14.488   4   15   2  209.7  47.9
    strings = [
        "\n%18s  %10s %10s %26s%8s %9s %9s %9s" %
        ("Object Name", "RA", "DEC", "%12s%14s" %
         ("RA", "DEC"), "N(ptgs)", "Exp.Time", "requested", "n(ints)")
    ]
    for objectname in uniq(bintable.data['OBJECT']):
        whobject = bintable.data['OBJECT'] == objectname
        RA, DEC = bintable.data['TRGTLONG'][whobject], bintable.data[
            'TRGTLAT'][whobject]
        RADEC = zip(RA, DEC)
        midRA, midDEC = np.median(RA), np.median(DEC)
        npointings = len(set(RADEC))
        if coords is not None:
            sexagesimal = coords.Position((midRA, midDEC)).hmsdms()
        else:
            sexagesimal = ""
        firstsampler = bintable.data['SAMPLER'][whobject][0]
        whfirstsampler = bintable.data['SAMPLER'] == firstsampler
        exptime = bintable.data['EXPOSURE'][whobject * whfirstsampler].sum()
        duration = bintable.data['DURATION'][whobject * whfirstsampler].sum()
        n_ints = count_integrations(bintable, objectname)
        strings.append("%18s  %10f %10f %26s%8i %9g %9g %9i" %
                       (objectname, midRA, midDEC, sexagesimal, npointings,
                        exptime, duration, n_ints))

    if doprint:
        print "\n".join(strings)

    return strings
Exemple #6
0
def cutout(filename,
           xc,
           yc,
           xw=25,
           yw=25,
           units='pixels',
           outfile=None,
           clobber=True,
           coordsys='celestial',
           verbose=False):
    """
    Inputs:
        file  - .fits filename or pyfits HDUList (must be 2D)
        xc,yc - x and y coordinates in the fits files' coordinate system (CTYPE)
        xw,yw - x and y width (pixels or wcs)
        units - specify units to use: either pixels or wcs
        outfile - optional output file
    """

    if isinstance(filename, str):
        file = pyfits.open(filename)
        opened = True
    elif (isinstance(filename, pyfits.HDUList)
          or isinstance(filename, pyfits.hdu.hdulist.HDUList)):
        file = filename
        opened = False
    else:
        raise Exception(
            "cutout: Input file is wrong type (string or HDUList are acceptable)."
        )

    head = file[0].header.copy()

    if head['NAXIS'] > 2:
        raise DimensionError("Too many (%i) dimensions!" % head['NAXIS'])

    cd1 = head.get('CDELT1') if head.get('CDELT1') else head.get('CD1_1')
    cd2 = head.get('CDELT2') if head.get('CDELT2') else head.get('CD2_2')

    if (cd1 is None or cd2 is None) and units == 'wcs':
        raise Exception("Missing CD or CDELT keywords in header")
    wcs = pywcs.WCS(head)

    if units == 'wcs':
        if coordsys == 'celestial' and wcs.wcs.lngtyp == 'GLON':
            xc, yc = coords.Position((xc, yc), system=coordsys).galactic()
        elif coordsys == 'galactic' and wcs.wcs.lngtyp == 'RA':
            xc, yc = coords.Position((xc, yc), system=coordsys).j2000()

    if units == 'pixels':
        xx, yy = xc, yc
        xmin, xmax = numpy.max([0,
                                xx - xw]), numpy.min([head['NAXIS1'], xx + xw])
        ymin, ymax = numpy.max([0,
                                yy - yw]), numpy.min([head['NAXIS2'], yy + yw])
    elif units == 'wcs':
        xx, yy = wcs.wcs_sky2pix(xc, yc, 0)

        xmin, xmax = numpy.max([0, xx - xw / numpy.abs(cd1)]), numpy.min(
            [head['NAXIS1'], xx + xw / numpy.abs(cd1)])
        ymin, ymax = numpy.max([0, yy - yw / numpy.abs(cd2)]), numpy.min(
            [head['NAXIS2'], yy + yw / numpy.abs(cd2)])
    else:
        raise Exception("Can't use units %s." % units)

    if xmax < 0 or ymax < 0:
        raise ValueError("Max Coordinate is outside of map: %f,%f." %
                         (xmax, ymax))
    if ymin >= head.get('NAXIS2') or xmin >= head.get('NAXIS1'):
        raise ValueError("Min Coordinate is outside of map: %f,%f." %
                         (xmin, ymin))

    if head.get('CRPIX1'):
        head['CRPIX1'] -= xmin
        head['CRPIX2'] -= ymin

    head['NAXIS1'] = int(xmax - xmin)
    head['NAXIS2'] = int(ymax - ymin)

    if head.get('NAXIS1') == 0 or head.get('NAXIS2') == 0:
        raise ValueError("Map has a 0 dimension: %i,%i." %
                         (head.get('NAXIS1'), head.get('NAXIS2')))

    img = file[0].data[ymin:ymax, xmin:xmax]
    newfile = pyfits.PrimaryHDU(data=img, header=head)

    if verbose:
        print "Cut image %s with dims %s to %s.  xrange: %f:%f, yrange: %f:%f" % (
            filename, file[0].data.shape, img.shape, xmin, xmax, ymin, ymax)

    head['comment'] = "Original: %s" % (file.filename())
    head['comment'] = "Cropped: %d %d - %d %d" % (xmin, xmax, ymin, ymax)

    if isinstance(outfile, str):
        newfile.writeto(outfile, clobber=clobber)

    if opened:
        file.close()

    return newfile
Exemple #7
0
def cutoutimg(filename,
              xc,
              yc,
              xw=25,
              yw=25,
              units='pixels',
              outfile=None,
              overwrite=True,
              useMontage=False,
              coordsys='celestial',
              verbose=False,
              centerunits=None):
    """
    Simple cutout function.  Should be replaced by a function in astropy
    eventually - keep an eye on
    https://github.com/astropy/astropy/pull/3823
    Parameters
    ----------
    file : str or fits.HDUList
        .fits filename or pyfits HDUList (must be 2D)
    xc,yc : float,float
        x and y coordinates in the fits files' coordinate system (CTYPE)
        or in pixel units
    xw,yw : float
        x and y half-width (pixels or wcs)
        (the output file will be size xw*2 * yw*2)
    units : str
        specify units to use: either pixels or wcs
    outfile : str
        optional output file
    centerunits : None or str
        If None, is the same as 'units'.  Can be 'wcs' or 'pixels'
    """

    if centerunits is None:
        centerunits = units

    if units not in ('wcs', 'pixels'):
        raise ValueError("units must be wcs or pixels")

    if isinstance(filename, str):
        file = pyfits.open(filename)
        opened = True
    elif isinstance(filename, pyfits.HDUList):
        file = filename
        opened = False
    else:
        raise Exception(
            "cutout: Input file is wrong type (string or HDUList are acceptable)."
        )

    head = file[0].header.copy()

    if head['NAXIS'] > 2:
        raise DimensionError("Too many (%i) dimensions!" % head['NAXIS'])
    cd1 = head.get('CDELT1') if head.get('CDELT1') else head.get('CD1_1')
    cd2 = head.get('CDELT2') if head.get('CDELT2') else head.get('CD2_2')
    if cd1 is None or cd2 is None:
        raise Exception("Missing CD or CDELT keywords in header")
    wcs = pywcs.WCS(head)

    if units == 'wcs':
        if coordsys == 'celestial' and wcs.wcs.lngtyp == 'GLON':
            xc, yc = coords.Position((xc, yc), system=coordsys).galactic()
        elif coordsys == 'galactic' and wcs.wcs.lngtyp == 'RA':
            xc, yc = coords.Position((xc, yc), system=coordsys).j2000()

    if useMontage and CanUseMontage:
        head['CRVAL1'] = xc
        head['CRVAL2'] = yc
        if units == 'pixels':
            head['CRPIX1'] = xw
            head['CRPIX2'] = yw
            head['NAXIS1'] = int(xw * 2)
            head['NAXIS2'] = int(yw * 2)
        elif units == 'wcs':

            cdelt = numpy.sqrt(cd1**2 + cd2**2)
            head['CRPIX1'] = xw / cdelt
            head['CRPIX2'] = yw / cdelt
            head['NAXIS1'] = int(xw * 2 / cdelt)
            head['NAXIS2'] = int(yw * 2 / cdelt)

        head.toTxtFile('temp_montage.hdr', overwrite=True)
        newfile = montage.wrappers.reproject_hdu(file[0],
                                                 header='temp_montage.hdr',
                                                 exact_size=True)
        os.remove('temp_montage.hdr')
    else:

        if centerunits == 'wcs':
            xx, yy = wcs.wcs_world2pix(xc, yc, 0)
        else:
            xx, yy = xc, yc

        if units == 'pixels':
            xmin, xmax = numpy.max([0, xx - xw
                                    ]), numpy.min([head['NAXIS1'], xx + xw])
            ymin, ymax = numpy.max([0, yy - yw
                                    ]), numpy.min([head['NAXIS2'], yy + yw])
        elif units == 'wcs':
            xmin, xmax = numpy.max([0, xx - xw / numpy.abs(cd1)]), numpy.min(
                [head['NAXIS1'], xx + xw / numpy.abs(cd1)])
            ymin, ymax = numpy.max([0, yy - yw / numpy.abs(cd2)]), numpy.min(
                [head['NAXIS2'], yy + yw / numpy.abs(cd2)])
        else:
            raise Exception("Can't use units %s." % units)

        if xmax < 0 or ymax < 0:
            raise ValueError("Max Coordinate is outside of map: %f,%f." %
                             (xmax, ymax))
        if ymin >= head.get('NAXIS2') or xmin >= head.get('NAXIS1'):
            raise ValueError("Min Coordinate is outside of map: %f,%f." %
                             (xmin, ymin))

        head['CRPIX1'] -= xmin
        head['CRPIX2'] -= ymin
        head['NAXIS1'] = int(xmax - xmin)
        head['NAXIS2'] = int(ymax - ymin)

        if head.get('NAXIS1') == 0 or head.get('NAXIS2') == 0:
            raise ValueError("Map has a 0 dimension: %i,%i." %
                             (head.get('NAXIS1'), head.get('NAXIS2')))

        img = file[0].data[int(ymin):int(ymax), int(xmin):int(xmax)]
        newfile = pyfits.PrimaryHDU(data=img, header=head)
        if verbose:
            print(
                "Cut image %s with dims %s to %s.  xrange: %f:%f, yrange: %f:%f"
                % (filename, file[0].data.shape, img.shape, xmin, xmax, ymin,
                   ymax))

    if isinstance(outfile, str):
        newfile.writeto(outfile, overwrite=overwrite)

    if opened:
        file.close()

    return newfile
Exemple #8
0
def cutout(filename, xc, yc, xw=25, yw=25, units='pixels', outfile=None,
        clobber=True, useMontage=False, coordsys='celestial', verbose=False, extension=0):
    """
    Inputs:
        file  - .fits filename or pyfits HDUList (must be 2D)
        xc,yc - x and y coordinates in the fits files' coordinate system (CTYPE)
        xw,yw - x and y width (pixels or wcs)
        units - specify units to use: either pixels or wcs
        outfile - optional output file

        KBS:
        For wcs mode use xy,xc,xw,xy (width is actually "radius") in degrees, e.g.,
          >>> import cutout
          >>> cutout.cutout('image.fits',189.24,62.23,xw=0.00139,yw=0.00139,units='wcs',outfile='testfile.fits')
        gives a cutout of 10x10 arcsec 2*5/3600x2*5/3600)

        140227 Added extension keyword for multi-extension fits Kasper B. Schmidt (UCSB)
    """

    if isinstance(filename,str):
        file = pyfits.open(filename)
        opened=True
    elif isinstance(filename,pyfits.HDUList):
        file = filename
        opened=False
    else:
        raise Exception("cutout: Input file is wrong type (string or HDUList are acceptable).")

    head = file[extension].header.copy()

    if head['NAXIS'] > 2:
        raise DimensionError("Too many (%i) dimensions!" % head['NAXIS'])

    # KBS cd1 = head.get('CDELT1') if head.get('CDELT1') else head.get('CD1_1')
    # KBS cd2 = head.get('CDELT2') if head.get('CDELT2') else head.get('CD2_2')
    # KBS --- use CD1_1 and CD2_2 over CDELT1 and CDELT2 ---
    cd1 = head.get('CD1_1') if head.get('CD1_1') else head.get('CDELT1')
    cd2 = head.get('CD2_2') if head.get('CD2_2') else head.get('CDELT2')

    if cd1 is None or cd2 is None:
        raise Exception("Missing CD or CDELT keywords in header")
    wcs = pywcs.WCS(head)

    if units == 'wcs':
        if coordsys=='celestial' and wcs.wcs.lngtyp=='GLON':
            xc,yc = coords.Position((xc,yc),system=coordsys).galactic()
        elif coordsys=='galactic' and wcs.wcs.lngtyp=='RA':
            xc,yc = coords.Position((xc,yc),system=coordsys).j2000()

    if useMontage and CanUseMontage:
        head['CRVAL1'] = xc
        head['CRVAL2'] = yc
        if units == 'pixels':
            head['CRPIX1'] = xw
            head['CRPIX2'] = yw
            head['NAXIS1'] = int(xw*2)
            head['NAXIS2'] = int(yw*2)
        elif units == 'wcs':
            
            cdelt = numpy.sqrt(cd1**2+cd2**2)
            head['CRPIX1'] = xw   / cdelt
            head['CRPIX2'] = yw   / cdelt
            head['NAXIS1'] = int(xw*2 / cdelt)
            head['NAXIS2'] = int(yw*2 / cdelt)

        head.toTxtFile('temp_montage.hdr',clobber=True)
        newfile = montage.wrappers.reproject_hdu(file[extension],header='temp_montage.hdr',exact_size=True)
        os.remove('temp_montage.hdr')
    else:

        #KBS160818 xx,yy = wcs.wcs_sky2pix(xc,yc,0)
        xx,yy = wcs.wcs_world2pix(xc,yc,0)

        if units=='pixels':
            xmin,xmax = numpy.max([0,xx-xw]),numpy.min([head['NAXIS1'],xx+xw])
            ymin,ymax = numpy.max([0,yy-yw]),numpy.min([head['NAXIS2'],yy+yw])
        elif units=='wcs':
            xmin,xmax = numpy.max([0,xx-xw/numpy.abs(cd1)]),numpy.min([head['NAXIS1'],xx+xw/numpy.abs(cd1)])
            ymin,ymax = numpy.max([0,yy-yw/numpy.abs(cd2)]),numpy.min([head['NAXIS2'],yy+yw/numpy.abs(cd2)])
        else:
            raise Exception("Can't use units %s." % units)

        if xmax < 0 or ymax < 0:
            raise ValueError("Max Coordinate is outside of map: %f,%f." % (xmax,ymax))
        if ymin >= head.get('NAXIS2') or xmin >= head.get('NAXIS1'):
            raise ValueError("Min Coordinate is outside of map: %f,%f." % (xmin,ymin))

        head['CRPIX1']-=xmin
        head['CRPIX2']-=ymin
        head['NAXIS1']=int(xmax-xmin)
        head['NAXIS2']=int(ymax-ymin)

        if head.get('NAXIS1') == 0 or head.get('NAXIS2') == 0:
            raise ValueError("Map has a 0 dimension: %i,%i." % (head.get('NAXIS1'),head.get('NAXIS2')))

        img = file[extension].data[ymin:ymax,xmin:xmax]
        newfile = pyfits.PrimaryHDU(data=img,header=head)
        if verbose: print "Cut image %s with dims %s to %s.  xrange: %f:%f, yrange: %f:%f" % (filename, file[extension].data.shape,img.shape,xmin,xmax,ymin,ymax)

    if isinstance(outfile,str):
        newfile.writeto(outfile,clobber=clobber)

    if opened:
        file.close()

    return newfile
Exemple #9
0
def cempno_control_starlist():
    names = np.array([
        'HE0132-2429', 'HE1347-1025', 'HE1356-0622', 'HE1424-0241',
        'BS16467-062', 'G64-12', 'CS29518-051', 'CS29502-042', 'CS22953-003',
        'CS22896-154', 'CS22183-031', 'CS29491-069', 'CS29497-004',
        'CS31082-001', 'HE0430-4901', 'HE0432-0923', 'HE1127-1143',
        'HE1219-0312', 'HE2224+0143', 'HE2327-5642'
    ])

    d = load_frebel_table()

    idx = np.array([], dtype=int)
    for ii in range(len(names)):
        foo = np.where(d.name == names[ii])[0]

        if len(foo) == 0:
            print 'No star %s' % names[ii]
        idx = np.append(idx, foo)
    sdx = d.ra[idx].argsort()
    idx = idx[sdx]

    # Trim out what we need
    ra = d.ra[idx]
    dec = d.dec[idx]
    V = d.V[idx]
    B = d.B[idx]
    R = d.R[idx]
    FeH = d.FeH[idx]
    CFe = d.CFe[idx]
    BaFe = d.BaFe[idx]
    simbad = d.simbad[idx]

    # Fix the RA and Dec for CEMP-s and CEMP-no stars
    ra, dec = getCoordsFromSimbad(d.simbad[idx])

    # Make a LaTeX table of the targets we want to observe
    _out = open('control_starlist.tel', 'w')
    _out2 = open('control_simbadnames.tel', 'w')

    for ii in range(len(names)):
        hmsdms = coords.Position((ra[ii], dec[ii])).hmsdms().split()
        ra_hex = hmsdms[0].replace(':', ' ')
        dec_hex = hmsdms[1].replace(':', ' ')

        print ii, names[ii], simbad[ii]

        _out.write('%-16s %12s %12s 2000.0 vmag=%5.2f\n' %
                   (names[ii], ra_hex, dec_hex, V[ii]))
        _out2.write('%s\n' % simbad[ii])

    _out.close()
    _out2.close()

    # Now lets loop through and plot when these targets are observable.
    py.clf()
    py.subplots_adjust(left=0.05, right=0.95, top=0.95)

    # Calculate the hour angle at which the object goes above airmass = 2.
    # Relevant equations are:
    #   airmass = 1 / cos(z)
    #   hour angle = sidereal time - RA
    #   cos z = sin L sin Dec + cos L cos Dec cos HA
    # We will solve for HA.
    iraf.noao()
    obs = iraf.noao.observatory
    obs(command="set", obsid="keck")
    airmassLim = 2.0

    latRad = np.radians(obs.latitude)
    decRad = np.radians(dec)

    top = (1.0 / airmassLim) - np.sin(latRad) * np.sin(decRad)
    bot = np.cos(latRad) * np.cos(decRad)

    hangle = np.degrees(np.arccos(top / bot))

    madeLegend = False
    for ii in range(len(names)):
        minLST = (ra[ii] - hangle[ii]) / 15.
        maxLST = (ra[ii] + hangle[ii]) / 15.

        hix = 360.0 / 15.0

        if (minLST >= 0) and (maxLST < hix):
            if madeLegend == True:
                py.plot([minLST, maxLST], [ii + 1, ii + 1],
                        linewidth=5,
                        color='black')
            else:
                py.plot([minLST, maxLST], [ii + 1, ii + 1],
                        linewidth=5,
                        color='black',
                        label='CEMP-no stars')
                madeLegend = True

        if minLST < 0:
            py.plot([0, maxLST], [ii + 1, ii + 1], linewidth=5, color='black')
            py.plot([minLST + hix, hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')

        if maxLST > hix:
            py.plot([minLST, hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')
            py.plot([0, maxLST - hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')

    py.xlim(0, hix)

    # Get the LST ranges for March, May, July
    months = np.array([3, 5, 7])
    days = np.array([1, 1, 1])
    years = np.array([2012, 2012, 2012])
    colors = ['red', 'green', 'blue']
    labels = ['Mar 1, 2012 (HST)', 'May 1, 2012 (HST)', 'Jul 1, 2012 (HST)']

    rng = py.axis()
    for ii in range(len(months)):
        twi = get_twilight_lst(years[ii], months[ii], days[ii])

        minLST = twi[0] * 15.0
        maxLST = twi[1] * 15.0

        ypos = rng[3] + 2 * (len(months) - ii)

        if minLST < 0:
            minLST += 360.0
        if maxLST > 360:
            maxLST -= 360.0

        x1 = np.array([minLST, maxLST]) / 15.0
        x2 = None
        y = np.array([ypos, ypos])

        if minLST > 0 and maxLST < 360 and minLST > maxLST:
            x1 = np.array([0, maxLST]) / 15.0
            x2 = np.array([minLST, 360]) / 15.0

        py.plot(x1, y, linewidth=10, color=colors[ii], label=labels[ii])

        if x2 != None:
            py.plot(x2, y, linewidth=10, color=colors[ii])

    py.ylim(0, rng[3] + 7 * len(months))
    py.legend(loc='upper left')
    #     py.xlim(0, 360)
    py.xlim(0, 24)
    py.xlabel('LST (hours)')
    py.gca().yaxis.set_visible(False)
    py.savefig('obs_ra_v_control_new.png')
Exemple #10
0
import numpy as np

import coords

# Read in initial coordinates as J2000 coordinates
data_j2000 = np.loadtxt('../initial_coords.txt')

f = {}
f['galactic'] = open('coords_galactic.txt', 'wb')
f['b1950'] = open('coords_b1950.txt', 'wb')
f['ecliptic'] = open('coords_ecliptic.txt', 'wb')

for i in range(len(data_j2000)):

    ra_j2000, dec_j2000 = data_j2000[i, 0], data_j2000[i, 1]
    j2000 = coords.Position((ra_j2000, dec_j2000))

    # Convert to Galactic coordinates
    l, b = j2000.galactic()
    f['galactic'].write("%20.15f %20.15f\n" % (l, b))

    # Convert to B1950
    ra_b1950, dec_b1950 = j2000.b1950()
    f['b1950'].write("%20.15f %20.15f\n" % (ra_b1950, dec_b1950))

    # Convert to ecliptic
    elon, elat = j2000.ecliptic()
    f['ecliptic'].write("%20.15f %20.15f\n" % (elon, elat))

for system in f:
    f[system].close()
Exemple #11
0
def cemp_no_properties():
    d = load_frebel_table()

    # Lets identify some sub-samples. Criteria from Beers 2008.
    emp = np.where((d.CFe < 0.9) & (d.ra != -999) & (d.V > 0) & (d.FeH != -999)
                   & (d.CFe != -999) & (d.BaFe != -999))[0]
    empr = np.where((d.CFe < 0.9) & (d.ra != -999) & (d.V > 0)
                    & (d.FeH != -999) & (d.CFe != -999) & (d.BaFe != -999)
                    & (d.BaEu < 0))[0]
    cemp = np.where(d.CFe >= 0.9)[0]
    cempr = np.where((d.CFe >= 0.9) & (d.EuFe > 1))[0]
    cemps = np.where((d.CFe >= 0.9) & (d.BaFe > 1) & (d.EuFe > -999)
                     & (d.BaEu > 0.5))[0]
    cempno = np.where((d.CFe >= 0.9) & (d.BaFe > -999) & (d.BaFe < 0))[0]

    # Plot up the histogram of Iron abundances:
    bins_FeH = np.arange(-7, 1, 0.5)
    py.clf()
    py.hist(d.FeH,
            histtype='step',
            bins=bins_FeH,
            label='%d stars' % len(d.name))
    py.hist(d.FeH[cemp],
            histtype='step',
            bins=bins_FeH,
            label='%d CEMP' % len(cemp))
    py.hist(d.FeH[cemps],
            histtype='step',
            bins=bins_FeH,
            label='%d CEMP-s' % len(cemps))
    py.hist(d.FeH[cempno],
            histtype='step',
            bins=bins_FeH,
            label='%d CEMP-no' % len(cempno))
    py.xlabel('[Fe/H]')
    py.ylabel('Number')
    py.legend(loc='upper left')
    py.ylim(0, 100)
    py.savefig(dir + 'hist_FeH.png')

    # Fix the ones with no V-band magnitudes
    bad_s = np.where(d.V[cemps] < 0)[0]
    bad_no = np.where(d.V[cempno] < 0)[0]

    # Bad CEMP-s stars
    print ''
    print '## Bad CEMP-s'
    for ii in bad_s:
        print '%20s  %10.5f  %10.5f  %5.2f' % \
            (d.name[cemps[ii]], d.ra[cemps[ii]],
             d.dec[cemps[ii]], d.V[cemps[ii]])

    print '## Bad CEMP-no'
    for ii in bad_no:
        print '%20s  %10.5f  %10.5f  %5.2f' % \
            (d.name[cempno[ii]], d.ra[cempno[ii]],
             d.dec[cempno[ii]], d.V[cempno[ii]])

    # Get rid of the stars without info.
    cemps = np.delete(cemps, bad_s)
    cempno = np.delete(cempno, bad_no)

    # Fix the RA and Dec for CEMP-s and CEMP-no stars
    d.ra[cemps], d.dec[cemps] = getCoordsFromSimbad(d.simbad[cemps])
    d.ra[cempno], d.dec[cempno] = getCoordsFromSimbad(d.simbad[cempno])

    py.clf()
    py.plot(d.V[cemps], d.FeH[cemps], 'rs', label='CEMP-s')
    py.plot(d.V[cempno], d.FeH[cempno], 'bo', label='CEMP-no')
    py.legend(loc='upper left', numpoints=1)
    py.xlabel('V magnitude')
    py.ylabel('[Fe/H]')
    py.savefig('v_vs_feh_cemp_s_no.png')

    # Now lets figure out what is observable this semester.
    py.clf()
    py.plot(d.ra[cemps], d.dec[cemps], 'rs', label='CEMP-s')
    py.plot(d.ra[cempno], d.dec[cempno], 'bo', label='CEMP-no')
    py.xlabel('R.A. (degrees)')
    py.ylabel('Dec. (degrees)')
    py.legend(loc='upper right', numpoints=1)

    lim_RA_mar01 = [90, 237]
    lim_RA_may01 = [156, 284]
    lim_RA_jul01 = [223, 342]

    py.plot(lim_RA_mar01, [10, 10], 'm-', linewidth=3)
    py.plot(lim_RA_may01, [20, 20], 'k-', linewidth=3, color='cyan')
    py.plot(lim_RA_jul01, [30, 30], 'g-', linewidth=3)
    py.text(95, 12, 'Mar 01, 2012', color='magenta')
    py.text(160, 22, 'May 01, 2012', color='cyan')
    py.text(235, 32, 'Jul 01, 2011', color='green')
    py.xlim(0, 360)
    py.ylim(-30, 70)
    py.savefig('ra_dec_cemp_s_no.png')

    # RA vs. V-band
    py.clf()
    py.plot(d.ra[cemps], d.V[cemps], 'rs', label='CEMP-s')
    py.plot(d.ra[cempno], d.V[cempno], 'bo', label='CEMP-no')
    py.xlabel('R.A. (degrees)')
    py.ylabel('V Magnitude')
    py.gca().set_ylim(py.gca().get_ylim()[::-1])
    py.legend(loc='upper right', numpoints=1)

    py.plot(lim_RA_mar01, [12, 12], 'm-', linewidth=3)
    py.plot(lim_RA_may01, [11, 11], 'k-', linewidth=3, color='cyan')
    py.plot(lim_RA_jul01, [10, 10], 'g-', linewidth=3)
    py.text(95, 11.9, 'Mar 01, 2012', color='magenta')
    py.text(160, 10.9, 'May 01, 2012', color='cyan')
    py.text(235, 9.9, 'Jul 01, 2011', color='green')
    py.xlim(0, 360)
    py.ylim(17, 6)
    py.savefig('ra_v_cemp_s_no.png')

    print('')
    print 'After removing stars without info:'

    hdrfmt = '{:16s} {:^15s}  {:^15s}  {:^5s}  {:^5s}  {:^5s}  {:^5s}'
    starfmt = '{:<16s} {:15s}  {:15s}  {:5.2f}  {:5.2f}  {:5.2f}  {:5.2f}'

    # Print out all the emp-r stars
    print('')
    print('  {:d} EMP-r stars (non-Carbon enhanced)'.format(len(empr)))
    print(hdrfmt.format('Name', 'RA', 'Dec', 'Vmag', 'Fe/H', 'C/Fe', 'Ba/Fe'))
    for ii in empr:
        hmsdms = coords.Position((d.ra[ii], d.dec[ii])).hmsdms().split()
        ra_hex = hmsdms[0].replace(':', ' ')
        dec_hex = hmsdms[1].replace(':', ' ')

        print(
            starfmt.format(d.name[ii], ra_hex, dec_hex, d.V[ii], d.FeH[ii],
                           d.CFe[ii], d.BaFe[ii]))

    print('')
    print('  {:d} CEMP-s stars'.format(len(cemps)))
    print(hdrfmt.format('Name', 'RA', 'Dec', 'Vmag', 'Fe/H', 'C/Fe', 'Ba/Fe'))
    for ii in cemps:
        hmsdms = coords.Position((d.ra[ii], d.dec[ii])).hmsdms().split()
        ra_hex = hmsdms[0].replace(':', ' ')
        dec_hex = hmsdms[1].replace(':', ' ')

        print(
            starfmt.format(d.name[ii], ra_hex, dec_hex, d.V[ii], d.FeH[ii],
                           d.CFe[ii], d.BaFe[ii]))

    # Print out all the cemp-no stars
    print('')
    print('  {:d} CEMP-no stars'.format(len(cempno)))
    print(hdrfmt.format('Name', 'RA', 'Dec', 'Vmag', 'Fe/H', 'C/Fe', 'Ba/Fe'))
    for ii in cempno:
        print ii, d.ra[ii], d.dec[ii]
        hmsdms = coords.Position((d.ra[ii], d.dec[ii])).hmsdms().split()
        ra_hex = hmsdms[0].replace(':', ' ')
        dec_hex = hmsdms[1].replace(':', ' ')

        print(
            starfmt.format(d.name[ii], ra_hex, dec_hex, d.V[ii], d.FeH[ii],
                           d.CFe[ii], d.BaFe[ii]))
Exemple #12
0
def cempno_table():
    names = [
        'CD-38_245', 'CS22942-019', 'HD6755', 'CS22958-042', 'BD+44_493',
        'BS16545-089', 'HE1150-0428', 'BS16920-005', 'HE1300+0157',
        'BS16929-005', 'HE1300-0641', 'CS22877-001', 'CS22880-074',
        'CS29498-043', 'CS29502-092', 'CS22949-037', 'CS22957-027',
        'HE2356-0410', 'HE1012-1540', 'HE1330-0354'
    ]

    d = load_frebel_table()

    idx = np.array([], dtype=int)
    for ii in range(len(names)):
        foo = np.where(d.name == names[ii])[0]

        idx = np.append(idx, foo)

    sdx = d.ra[idx].argsort()
    idx = idx[sdx]

    # Trim out what we need
    ra = d.ra[idx]
    dec = d.dec[idx]
    V = d.V[idx]
    B = d.B[idx]
    R = d.R[idx]
    FeH = d.FeH[idx]
    CFe = d.CFe[idx]
    BaFe = d.BaFe[idx]

    # Fix the RA and Dec for CEMP-s and CEMP-no stars
    ra, dec = getCoordsFromSimbad(d.simbad[idx])

    # Make a LaTeX table of the targets we want to observe
    _out = open('table_cemp_no.tex', 'w')
    _out.write('\\begin{deluxetable}{lrrrrrr}\n')
    _out.write('\\tablewidth{0pt}\n')
    _out.write('\\tablecaption{CEMP-no Stars}\n')
    _out.write('\\tablehead{\n')
    _out.write('  \\colhead{Name} &\n')
    _out.write('  \\colhead{R.A. (J2000)} &\n')
    _out.write('  \\colhead{Dec. (J2000)} &\n')
    _out.write('  \\colhead{V} &\n')
    _out.write('  \\colhead{[Fe/H]} &\n')
    _out.write('  \\colhead{[C/Fe]} &\n')
    _out.write('  \\colhead{[Ba/Fe]}\n')
    _out.write('}\n')
    _out.write('\\startdata\n')

    for ii in range(len(names)):
        hmsdms = coords.Position((ra[ii], dec[ii])).hmsdms().split()
        ra_hex = hmsdms[0]
        dec_hex = hmsdms[1]

        _out.write('%25s  & %15s  & %15s & ' %
                   (names[ii].replace('_', '\_'), ra_hex, dec_hex))
        _out.write('%5.2f  & %5.2f  & %5.2f  & %5.2f \\\\ \n' %
                   (V[ii], FeH[ii], CFe[ii], BaFe[ii]))

    _out.write('\\enddata\n')
    _out.write('\\end{deluxetable}\n')
    _out.close()

    # Now lets loop through and plot when these targets are observable.
    py.clf()
    py.subplots_adjust(left=0.05, right=0.95, top=0.95)

    # Calculate the hour angle at which the object goes above airmass = 2.
    # Relevant equations are:
    #   airmass = 1 / cos(z)
    #   hour angle = sidereal time - RA
    #   cos z = sin L sin Dec + cos L cos Dec cos HA
    # We will solve for HA.
    iraf.noao()
    obs = iraf.noao.observatory
    obs(command="set", obsid="keck")
    airmassLim = 2.0

    latRad = np.radians(obs.latitude)
    decRad = np.radians(dec)

    top = (1.0 / airmassLim) - np.sin(latRad) * np.sin(decRad)
    bot = np.cos(latRad) * np.cos(decRad)

    hangle = np.degrees(np.arccos(top / bot))

    madeLegend = False
    for ii in range(len(names)):
        minLST = (ra[ii] - hangle[ii]) / 15.
        maxLST = (ra[ii] + hangle[ii]) / 15.

        hix = 360.0 / 15.0

        if (minLST >= 0) and (maxLST < hix):
            if madeLegend == True:
                py.plot([minLST, maxLST], [ii + 1, ii + 1],
                        linewidth=5,
                        color='black')
            else:
                py.plot([minLST, maxLST], [ii + 1, ii + 1],
                        linewidth=5,
                        color='black',
                        label='CEMP-no stars')
                madeLegend = True

        if minLST < 0:
            py.plot([0, maxLST], [ii + 1, ii + 1], linewidth=5, color='black')
            py.plot([minLST + hix, hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')

        if maxLST > hix:
            py.plot([minLST, hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')
            py.plot([0, maxLST - hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')

    py.xlim(0, hix)

    # Get the LST ranges for March, May, July
    months = np.array([3, 5, 7])
    days = np.array([1, 1, 1])
    years = np.array([2012, 2012, 2012])
    colors = ['red', 'green', 'blue']
    labels = ['Mar 1, 2012 (HST)', 'May 1, 2012 (HST)', 'Jul 1, 2012 (HST)']

    rng = py.axis()
    for ii in range(len(months)):
        twi = get_twilight_lst(years[ii], months[ii], days[ii])

        minLST = twi[0] * 15.0
        maxLST = twi[1] * 15.0

        ypos = rng[3] + 2 * (len(months) - ii)

        if minLST < 0:
            minLST += 360.0
        if maxLST > 360:
            maxLST -= 360.0

        x1 = np.array([minLST, maxLST]) / 15.0
        x2 = None
        y = np.array([ypos, ypos])

        if minLST > 0 and maxLST < 360 and minLST > maxLST:
            x1 = np.array([0, maxLST]) / 15.0
            x2 = np.array([minLST, 360]) / 15.0

        py.plot(x1, y, linewidth=10, color=colors[ii], label=labels[ii])

        if x2 != None:
            py.plot(x2, y, linewidth=10, color=colors[ii])

    py.ylim(0, rng[3] + 7 * len(months))
    py.legend(loc='upper left')
    #     py.xlim(0, 360)
    py.xlim(0, 24)
    py.xlabel('LST (hours)')
    py.gca().yaxis.set_visible(False)
    py.savefig('obs_ra_v_cemp_s_no.png')
Exemple #13
0
def cutout(filename,
           outfile,
           xc,
           yc,
           xw=25,
           yw=25,
           units='pixels',
           clobber=True,
           coordsys='celestial',
           verbose=False):
    """
    Inputs:
        file  - .fits filename or pyfits HDUList (must be 2D)
        xc,yc - x and y coordinates in the fits files' coordinate system (CTYPE)
        xw,yw - x and y width (pixels or wcs)
        units - specify units to use: either pixels or wcs
        outfile - optional output file

    """

    if isinstance(filename, str):
        file = pyfits.open(filename)
        opened = True
    elif isinstance(filename, pyfits.HDUList):
        file = filename
        opened = False
    else:
        raise Exception(
            "cutout: Input file is wrong type (string or HDUList are acceptable)."
        )

    head = file[0].header.copy()

    if head['NAXIS'] > 2:
        raise DimensionError("Too many (%i) dimensions!" % head['NAXIS'])
    cd1 = head.get('CDELT1') if head.get('CDELT1') else head.get('CD1_1')
    cd2 = head.get('CDELT2') if head.get('CDELT2') else head.get('CD2_2')
    if cd1 is None or cd2 is None:
        raise Exception("Missing CD or CDELT keywords in header")
    wcs = pywcs.WCS(head)

    if units == 'wcs':
        print 'using wcs conversion'
        if coordsys == 'celestial' and wcs.wcs.lngtyp == 'GLON':
            xc, yc = coords.Position((xc, yc), system=coordsys).galactic()
        elif coordsys == 'galactic' and wcs.wcs.lngtyp == 'RA':
            xc, yc = coords.Position((xc, yc), system=coordsys).j2000()
        xx, yy = wcs.wcs_sky2pix(xc, yc, 0)
    elif units == 'pixels':
        xx, yy = xc, yc

    if units == 'pixels':
        xmin, xmax = numpy.max([0,
                                xx - xw]), numpy.min([head['NAXIS1'], xx + xw])
        ymin, ymax = numpy.max([0,
                                yy - yw]), numpy.min([head['NAXIS2'], yy + yw])
    elif units == 'wcs':
        xmin, xmax = numpy.max([0, xx - xw / numpy.abs(cd1)]), numpy.min(
            [head['NAXIS1'], xx + xw / numpy.abs(cd1)])
        ymin, ymax = numpy.max([0, yy - yw / numpy.abs(cd2)]), numpy.min(
            [head['NAXIS2'], yy + yw / numpy.abs(cd2)])
    else:
        raise Exception("Can't use units %s." % units)

    if xmax < 0 or ymax < 0:
        raise ValueError("Max Coordinate is outside of map: %f,%f." %
                         (xmax, ymax))
    if ymin >= head.get('NAXIS2') or xmin >= head.get('NAXIS1'):
        raise ValueError("Min Coordinate is outside of map: %f,%f." %
                         (xmin, ymin))

    head['CRPIX1'] -= xmin
    head['CRPIX2'] -= ymin
    head['NAXIS1'] = int(xmax - xmin)
    head['NAXIS2'] = int(ymax - ymin)

    if head.get('NAXIS1') == 0 or head.get('NAXIS2') == 0:
        raise ValueError("Map has a 0 dimension: %i,%i." %
                         (head.get('NAXIS1'), head.get('NAXIS2')))

    # use imcopy insstead
    filesection = filename + '[%i:%i,%i:%i]' % (xmin, xmax, ymin, ymax)
    print filesection, xc, yc
    if os.path.exists(outfile):
        os.remove(outfile)
    imcopy(filesection, outfile)
def cempno_starlist():
    names = np.array([
        'CD-38_245', 'CS22942-019', 'HD6755', 'CS22958-042', 'BD+44_493',
        'BS16545-089', 'HE1150-0428', 'BS16920-005', 'HE1300+0157',
        'BS16929-005', 'HE1300-0641', 'CS22877-001', 'CS22880-074',
        'CS29498-043', 'CS29502-092', 'CS22949-037', 'CS22957-027',
        'HE2356-0410', 'HE1012-1540', 'HE1330-0354'
    ])

    d = load_frebel_table()

    idx = np.array([], dtype=int)
    for ii in range(len(names)):
        foo = np.where(d.name == names[ii])[0]

        idx = np.append(idx, foo)


#    sdx = d.ra[idx].argsort()
#    idx = idx[sdx]

# Trim out what we need
    ra = d.ra[idx]
    dec = d.dec[idx]
    V = d.V[idx]
    B = d.B[idx]
    R = d.R[idx]
    FeH = d.FeH[idx]
    CFe = d.CFe[idx]
    BaFe = d.BaFe[idx]
    simbad = d.simbad[idx]

    # Make a LaTeX table of the targets we want to observe
    _out = open('cemp_no_starlist.tel', 'w')
    _out2 = open('cemp_no_simbadnames.tel', 'w')

    for ii in range(len(names)):
        hmsdms = coords.Position((ra[ii], dec[ii])).hmsdms().split()
        ra_hex = hmsdms[0].replace(':', ' ')
        dec_hex = hmsdms[1].replace(':', ' ')

        print ii, names[ii], simbad[ii]

        _out.write('%-16s %12s %12s 2000.0 vmag=%5.2f\n' %
                   (names[ii], ra_hex, dec_hex, V[ii]))
        _out2.write('%s\n' % simbad[ii])

    _out.close()
    _out2.close()

    # Now lets loop through and plot when these targets are observable.
    py.clf()
    py.subplots_adjust(left=0.05, right=0.95, top=0.95)

    # Calculate the hour angle at which the object goes above airmass = 2.
    # Relevant equations are:
    #   airmass = 1 / cos(z)
    #   hour angle = sidereal time - RA
    #   cos z = sin L sin Dec + cos L cos Dec cos HA
    # We will solve for HA.
    iraf.noao()
    obs = iraf.noao.observatory
    obs(command="set", obsid="keck")
    airmassLim = 2.0

    latRad = np.radians(obs.latitude)
    decRad = np.radians(dec)

    top = (1.0 / airmassLim) - np.sin(latRad) * np.sin(decRad)
    bot = np.cos(latRad) * np.cos(decRad)

    hangle = np.degrees(np.arccos(top / bot))

    madeLegend = False
    for ii in range(len(names)):
        minLST = (ra[ii] - hangle[ii]) / 15.
        maxLST = (ra[ii] + hangle[ii]) / 15.

        hix = 360.0 / 15.0

        if (minLST >= 0) and (maxLST < hix):
            if madeLegend == True:
                py.plot([minLST, maxLST], [ii + 1, ii + 1],
                        linewidth=5,
                        color='black')
            else:
                py.plot([minLST, maxLST], [ii + 1, ii + 1],
                        linewidth=5,
                        color='black',
                        label='CEMP-no stars')
                madeLegend = True

        if minLST < 0:
            py.plot([0, maxLST], [ii + 1, ii + 1], linewidth=5, color='black')
            py.plot([minLST + hix, hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')

        if maxLST > hix:
            py.plot([minLST, hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')
            py.plot([0, maxLST - hix], [ii + 1, ii + 1],
                    linewidth=5,
                    color='black')

    py.xlim(0, hix)

    # Get the LST ranges for mid-August, early-November, and mid-January.
    months = np.array([8, 11, 1])
    days = np.array([1, 1, 31])
    years = np.array([2011, 2011, 2012])
    colors = ['red', 'green', 'blue']
    labels = ['Aug 1, 2011 (HST)', 'Nov 1, 2011 (HST)', 'Jan 31, 2012 (HST)']

    rng = py.axis()
    for ii in range(len(months)):
        twi = get_twilight_lst(years[ii], months[ii], days[ii])

        minLST = twi[0] * 15.0
        maxLST = twi[1] * 15.0

        ypos = rng[3] + 2 * (len(months) - ii)

        if minLST < 0:
            minLST += 360.0
        if maxLST > 360:
            maxLST -= 360.0

        x1 = np.array([minLST, maxLST]) / 15.0
        x2 = None
        y = np.array([ypos, ypos])

        if minLST > 0 and maxLST < 360 and minLST > maxLST:
            x1 = np.array([0, maxLST]) / 15.0
            x2 = np.array([minLST, 360]) / 15.0

        py.plot(x1, y, linewidth=10, color=colors[ii], label=labels[ii])

        if x2 != None:
            py.plot(x2, y, linewidth=10, color=colors[ii])

    py.ylim(0, rng[3] + 7 * len(months))
    py.legend(loc='upper left')
    #     py.xlim(0, 360)
    py.xlim(0, 24)
    py.xlabel('LST (hours)')
    py.gca().yaxis.set_visible(False)
    py.savefig('obs_ra_v_cemp_s_no_new.png')
        stddc = header['STDDC']
        try:
            rad_as = header['MASKRAD']
            masked = True
        except:
            try:
                rad_as = float(
                    re.compile('maske?d?([0-9]*)').search(file).groups()[0])
                masked = True
            except:
                rad_as = 80.0
                masked = False
        try:
            tgtra = header['TGT_RA']
            tgtdec = header['TGT_DEC']
            l, b = coords.Position([tgtra, tgtdec]).galactic()
            if masked:
                ff.show_circles(numpy.array([l]),
                                numpy.array([b]),
                                rad_as / 3600.0,
                                edgecolor='blue')
            ff.show_circles(numpy.array([l]),
                            numpy.array([b]),
                            300.0 / 3600.0,
                            edgecolor='purple')
        except KeyError:
            print "No TGT_RA found"

        wcshead = pywcs.WCS(header)
        lbfit = wcshead.wcs_pix2sky(fitpars[2:3], fitpars[3:4], 0)
Exemple #16
0
def cutout(filename,
           xc,
           yc,
           xw=25,
           yw=25,
           units='pixels',
           outfile=None,
           clobber=True,
           useMontage=False,
           coordsys='celestial',
           verbose=False):

    #Inputs:
    #file  - .fits filename or pyfits HDUList (must be 2D)
    #xc,yc - x and y coordinates in the fits files' coordinate system (CTYPE)
    #xw,yw - x and y width (pixels or wcs)
    #units - specify units to use: either pixels or wcs
    #outfile - optional output file

    if isinstance(filename, str):
        file = pyfits.open(filename)
        opened = True
    elif isinstance(filename, pyfits.HDUList):
        file = filename
        opened = False
    else:
        raise Exception(
            "cutout: Input file is wrong type (string or HDUList are acceptable)."
        )

    head = file[0].header.copy()

    if head['NAXIS'] > 2:
        raise DimensionError("Too many (%i) dimensions!" % head['NAXIS'])
    cd1 = head.get('CDELT1') if head.get('CDELT1') else head.get('CD1_1')
    cd2 = head.get('CDELT2') if head.get('CDELT2') else head.get('CD2_2')
    if cd1 is None or cd2 is None:
        raise Exception("Missing CD or CDELT keywords in header")
    wcs = pywcs.WCS(head)

    if units == 'wcs':
        if coordsys == 'celestial' and wcs.wcs.lngtyp == 'GLON':
            xc, yc = coords.Position((xc, yc), system=coordsys).galactic()
        elif coordsys == 'galactic' and wcs.wcs.lngtyp == 'RA':
            xc, yc = coords.Position((xc, yc), system=coordsys).j2000()

    if useMontage and CanUseMontage:
        head['CRVAL1'] = xc
        head['CRVAL2'] = yc
        if units == 'pixels':
            head['CRPIX1'] = xw
            head['CRPIX2'] = yw
            head['NAXIS1'] = int(xw * 2)
            head['NAXIS2'] = int(yw * 2)
        elif units == 'wcs':

            cdelt = numpy.sqrt(cd1**2 + cd2**2)
            head['CRPIX1'] = xw / cdelt
            head['CRPIX2'] = yw / cdelt
            head['NAXIS1'] = int(xw * 2 / cdelt)
            head['NAXIS2'] = int(yw * 2 / cdelt)

        head.toTxtFile('temp_montage.hdr', clobber=True)
        newfile = montage.wrappers.reproject_hdu(file[0],
                                                 header='temp_montage.hdr',
                                                 exact_size=True)
        os.remove('temp_montage.hdr')
    else:

        xx, yy = wcs.wcs_world2pix(xc, yc, 0)

        if units == 'pixels':
            xmin, xmax = numpy.max([0, xx - xw
                                    ]), numpy.min([head['NAXIS1'], xx + xw])
            ymin, ymax = numpy.max([0, yy - yw
                                    ]), numpy.min([head['NAXIS2'], yy + yw])
        elif units == 'wcs':
            xmin, xmax = numpy.max([0, xx - xw / numpy.abs(cd1)]), numpy.min(
                [head['NAXIS1'], xx + xw / numpy.abs(cd1)])
            ymin, ymax = numpy.max([0, yy - yw / numpy.abs(cd2)]), numpy.min(
                [head['NAXIS2'], yy + yw / numpy.abs(cd2)])
        else:
            raise Exception("Can't use units %s." % units)

        if xmax < 0 or ymax < 0:
            raise ValueError("Max Coordinate is outside of map: %f,%f." %
                             (xmax, ymax))
        if ymin >= head.get('NAXIS2') or xmin >= head.get('NAXIS1'):
            raise ValueError("Min Coordinate is outside of map: %f,%f." %
                             (xmin, ymin))

        head['CRPIX1'] -= xmin
        head['CRPIX2'] -= ymin
        head['NAXIS1'] = int(xmax - xmin)
        head['NAXIS2'] = int(ymax - ymin)

        if head.get('NAXIS1') == 0 or head.get('NAXIS2') == 0:
            raise ValueError("Map has a 0 dimension: %i,%i." %
                             (head.get('NAXIS1'), head.get('NAXIS2')))

        img = file[0].data[ymin:ymax, xmin:xmax]
        newfile = pyfits.PrimaryHDU(data=img, header=head)
        if verbose:
            print "Cut image %s with dims %s to %s.  xrange: %f:%f, yrange: %f:%f" % (
                filename, file[0].data.shape, img.shape, xmin, xmax, ymin,
                ymax)

    if isinstance(outfile, str):
        newfile.writeto(outfile, clobber=clobber)

    if opened:
        file.close()

    return newfile
Exemple #17
0
def cut_fits_downloaded(filename, xc, yc, xw=1, yw=1, units='pixels', outfile=None, clobber=True, useMontage=False, coordsys='celestial', verbose=False):
    """
    credit: http://code.google.com/p/agpy/source/browse/trunk/agpy/cutout.py
    changed by Hongquan on 25 May 2015: move the imports into the defination part
    Generate a cutout image from a .fits file
    Inputs:
        file  - .fits filename or pyfits HDUList (must be 2D)
        xc,yc - x and y coordinates in the fits files' coordinate system (CTYPE)
        xw,yw - x and y width (pixels or wcs); xw and yw is half width of the output file
        units - specify units to use: either pixels or wcs
        outfile - optional output file
    """     
    try:
        import astropy.io.fits as pyfits
        import astropy.wcs as pywcs
    except ImportError:
        import pyfits
        import pywcs
    import numpy
    try:
        import coords
    except ImportError:
        pass # maybe should do something smarter here, but I want agpy to install...
    try:
        import montage_wrapper as montage
        import os
        CanUseMontage=True
    except ImportError:
        CanUseMontage=False

    class DimensionError(ValueError):
        pass

    if isinstance(filename,str):
        file = pyfits.open(filename)
        opened=True
    elif isinstance(filename,pyfits.HDUList):
        file = filename
        opened=False
    else:
        raise Exception("cutout: Input file is wrong type (string or HDUList are acceptable).")

    head = file[0].header.copy()

    if head['NAXIS'] > 2:
        raise DimensionError("Too many (%i) dimensions!" % head['NAXIS'])
    cd1 = head.get('CDELT1') if head.get('CDELT1') else head.get('CD1_1')
    cd2 = head.get('CDELT2') if head.get('CDELT2') else head.get('CD2_2')
    if cd1 is None or cd2 is None:
        raise Exception("Missing CD or CDELT keywords in header")
    wcs = pywcs.WCS(head)

    if units == 'wcs':
        if coordsys=='celestial' and wcs.wcs.lngtyp=='GLON':
            xc,yc = coords.Position((xc,yc),system=coordsys).galactic()
        elif coordsys=='galactic' and wcs.wcs.lngtyp=='RA':
            xc,yc = coords.Position((xc,yc),system=coordsys).j2000()

    if useMontage and CanUseMontage:
        head['CRVAL1'] = xc
        head['CRVAL2'] = yc
        if units == 'pixels':
            head['CRPIX1'] = xw
            head['CRPIX2'] = yw
            head['NAXIS1'] = int(xw*2)
            head['NAXIS2'] = int(yw*2)
        elif units == 'wcs':
            
            cdelt = numpy.sqrt(cd1**2+cd2**2)
            head['CRPIX1'] = xw   / cdelt
            head['CRPIX2'] = yw   / cdelt
            head['NAXIS1'] = int(xw*2 / cdelt)
            head['NAXIS2'] = int(yw*2 / cdelt)

        head.toTxtFile('temp_montage.hdr',clobber=True)
        newfile = montage.wrappers.reproject_hdu(file[0],header='temp_montage.hdr',exact_size=True)
        os.remove('temp_montage.hdr')
    else:

        xx,yy = wcs.wcs_world2pix(xc,yc,0)

        if units=='pixels':
            xmin,xmax = numpy.max([0,xx-xw]),numpy.min([head['NAXIS1'],xx+xw])
            ymin,ymax = numpy.max([0,yy-yw]),numpy.min([head['NAXIS2'],yy+yw])
        elif units=='wcs':
            xmin,xmax = numpy.max([0,xx-xw/numpy.abs(cd1)]),numpy.min([head['NAXIS1'],xx+xw/numpy.abs(cd1)])
            ymin,ymax = numpy.max([0,yy-yw/numpy.abs(cd2)]),numpy.min([head['NAXIS2'],yy+yw/numpy.abs(cd2)])
        else:
            raise Exception("Can't use units %s." % units)

        if xmax < 0 or ymax < 0:
            raise ValueError("Max Coordinate is outside of map: %f,%f." % (xmax,ymax))
        if ymin >= head.get('NAXIS2') or xmin >= head.get('NAXIS1'):
            raise ValueError("Min Coordinate is outside of map: %f,%f." % (xmin,ymin))

        head['CRPIX1']-=xmin
        head['CRPIX2']-=ymin
        head['NAXIS1']=int(xmax-xmin)
        head['NAXIS2']=int(ymax-ymin)

        if head.get('NAXIS1') == 0 or head.get('NAXIS2') == 0:
            raise ValueError("Map has a 0 dimension: %i,%i." % (head.get('NAXIS1'),head.get('NAXIS2')))

        img = file[0].data[ymin:ymax,xmin:xmax]
        newfile = pyfits.PrimaryHDU(data=img,header=head)
        if verbose: print("Cut image %s with dims %s to %s.  xrange: %f:%f, yrange: %f:%f" % (filename, file[0].data.shape,img.shape,xmin,xmax,ymin,ymax))

    if isinstance(outfile,str):
        newfile.writeto(outfile,clobber=clobber)

    if opened:
        file.close()

    return newfile