def get_data(glon,glat,radius=20,save=True,overwrite=False,get_images=True,directory='./'):
    """
    Download UKIDSS data at specified GLON/GLAT with specified size

    Parameters
    ----------
    glon : float
    glat : float
        Galactic latitude and longitude at the center
    radius : float
        Size of cutout (symmetric) in arcminutes
    save : bool
        Save FITS and catalog files?
    get_images : bool
        Download the images in addition to the catalog?
    """

    R = ukidss.Ukidss(programme_id='GPS')
    R.directory = directory
    c = coords.GalacticCoordinates(glon,glat,unit=('deg','deg'))
    r = radius * u.arcmin
    if get_images and save:
        images = R.get_images(c,image_width=r)
        for i in images:
            i.writeto(directory+"%0.3f%+0.3f_%s.fits" % (c.l.degree,c.b.degree,i.header['FILTER']))
    cat = R.query_region(c,r,programme_id='GPS')
    if save:
        cat.write(directory+"%0.3f%+0.3f_r%0.1f_catalog.fits" % (c.l.degree,c.b.degree,radius))
    try:
        cleancat = ukidss.clean_catalog(cat)
    except Exception as e:
        print e
        cleancat = cat

    return cleancat
Beispiel #2
0
def sgr_to_galactic(sgr_coord):
    """ Compute the transformation from Sgr coordinates to spherical Galactic.
    """
    L = sgr_coord.Lambda.radian
    B = sgr_coord.Beta.radian

    Xs = cos(B) * cos(L)
    Ys = cos(B) * sin(L)
    Zs = sin(B)
    Zs = -Zs

    X, Y, Z = sgr_matrix.T.dot(np.array([Xs, Ys, Zs]))

    l = degrees(np.arctan2(Y, X))
    b = degrees(np.arcsin(Z / np.sqrt(X * X + Y * Y + Z * Z)))

    if l < 0:
        l += 360

    return coord.GalacticCoordinates(l,
                                     b,
                                     distance=sgr_coord.distance,
                                     unit=(u.degree, u.degree))
Beispiel #3
0
    parser.add_argument('--dist',
                        type=str,
                        dest='dist',
                        help='Heliocentric distance in kpc.')

    parser.add_argument('--test',
                        dest='test',
                        default=False,
                        action="store_true",
                        help='Run tests.')

    args = parser.parse_args()

    if args.test:
        test_table()
        sys.exit(0)

    if args.dist == None:
        raise ValueError("dist is required!")

    if args.ra != None and args.dec != None:
        print(distance_to_orphan_plane(args.ra, args.dec, float(args.dist)))

    elif args.l != None and args.b != None:
        galactic = coord.GalacticCoordinates(args.l, args.b, unit=(u.degree, \
                                                                   u.degree))
        icrs = galactic.icrs
        print(distance_to_orphan_plane(icrs.ra, icrs.dec, float(args.dist)))

    else:
        raise ValueError("You must specify either RA/Dec or Galactic l/b")
Beispiel #4
0
from astropy import coordinates as coords
import pylab as pl
import sys
import os
sys.path.append(os.path.split(__file__)[0] + "/../nirex/")
from UKIDSS_extmap import show_contours_on_extinction, make_densitymap, get_contours, get_data
from astropy.io import fits
from astropy.table import Table

example_sources = [
    'G28.865+0.203', 'G29.841-0.476', 'G29.859-0.490', 'G30.397-0.466',
    'G28.767-0.186', 'G29.277-0.131', 'G30.330+0.116'
]

coords = {
    x: coords.GalacticCoordinates(x[1:7], x[7:], unit=('deg', 'deg'))
    for x in example_sources
}

C = get_contours(fits.open('v2.0_ds2_l029_13pca_map20_crop.fits'))
C30 = get_contours(fits.open('v2.0_ds2_l030_13pca_map20_crop.fits'))
label30 = fits.open('v2.0_ds2_l030_13pca_labelmask.fits')
label30[0].data = np.array((label30[0].data > 0), dtype='float')
C30l = get_contours(label30, contour_level=0.5)

r = 20  # arcmin
for c in coords:

    print "Loading coordinate ", c, '...',

    l, b = coords[c].l.degree, coords[c].b.degree
def make_plots(dirname, fnames):
    # get the highest-level directory, assume it is the target source ID
    obj = os.path.split(dirname)[-1]

    files = {}
    data = {}

    for fn in fnames:
        for k,v in keys.iteritems():
            if v in fn:
                if k in files and not 'coadd' in fn:
                    continue
                files[k] = os.path.join(dirname,fn)
                data[k] = fits.getdata(os.path.join(dirname,fn))

    if len(files) == 0:
        return

    if 'SCUBA' in files and 'ATLASGAL' in files:
        del files['SCUBA']
        del data['SCUBA']

    print "Making figures for ",dirname, files

    if 'Band0' in files:
        header0 = fits.getheader(files['Band0'])
        center = coords.ICRSCoordinates("%s %s" % (header0['CRVAL1'],header0['CRVAL2']),unit=('deg','deg'))
    elif 'BGPS' in files:
        header0 = fits.getheader(files['BGPS'])
        center = coords.GalacticCoordinates("%s %s" % (header0['CRVAL1'],header0['CRVAL2']),unit=('deg','deg')).fk5
    elif 'ATLASGAL' in files:
        header0 = fits.getheader(files['ATLASGAL'])
        center = coords.GalacticCoordinates("%s %s" % (header0['CRVAL1'],header0['CRVAL2']),unit=('deg','deg')).fk5
    else:
        raise ValueError("Really?  No BGPS, MUSIC, or ATLASGAL?  WTF.  BRB.  BBQ.")

    for ii,(k,fn) in enumerate(files.iteritems()):
        print k,fn,data[k][data[k]==data[k]].max()

    fig = pl.figure(1)
    pl.clf()
    for ii,(k,fn) in enumerate(files.iteritems()):
        #print k,fn,data[k][data[k]==data[k]].max()
        try:
            F = aplpy.FITSFigure(fn, subplot=(2,3,ii+1), convention='calabretta', figure=fig, north=True)
            F.show_colorscale(vmin=-0.5,vmax=5,cmap=pl.cm.hot)
            F._ax1.set_title(k)
            F.tick_labels.set_xformat('d.dd')
            if (ii) % 3 == 0:
                F.tick_labels.set_yformat('d.dd')
            else:
                F.tick_labels.hide_y()
            F.add_colorbar()
        except Exception as e:
            print "Montage error: ",e
            continue
        try:
            F.recenter(center.ra.degree, center.dec.degree, 5/60.)
        except:
            continue
        #pl.subplot(2,3,ii+1)
        #pl.imshow(data[k], vmin=-0.5, vmax=5)
        #pl.title(k)
        #pl.colorbar()

    prefix = os.path.join(dirname,obj)
    pl.savefig(prefix+"_compare_MUSIC_BGPS.png",bbox_inches='tight')
Beispiel #6
0
def get_nrao_image(lon,
                   lat,
                   system='galactic',
                   epoch='J2000',
                   size=1.0,
                   max_rms=1e4,
                   band="",
                   verbose=True,
                   savename=None,
                   save=True,
                   overwrite=False,
                   directory='./',
                   get_uvfits=False):
    """
    Search for and download

    Parameters
    ----------
    lon : float
    lat : float
        Right ascension and declination or glon/glat
    system : ['celestial','galactic']
        System of lon/lat.  Can be any valid coordinate system supported by the
        astropy.coordinates package
    epoch : string
        Epoch of the coordinate system (e.g., B1950, J2000)
    savename : None or string
        filename to save fits file as.  If None, will become G###.###p###.###_(survey).fits
    size : float
        Size of search radius (arcminutes)
    max_rms : float
        Maximum allowable noise level in the image (mJy)
    verbose : bool
        Print out extra error messages?
    save : bool
        Save FITS file?
    overwrite : bool
        Overwrite if file already exists?
    directory : string
        Directory to store file in.  Defaults to './'.  
    get_uvfits : bool
        Get the UVfits files instead of the IMfits files?

    Examples
    --------
    >>> fitsfile = get_nrao_image(49.489,-0.37)
    """

    if band not in valid_bands:
        raise ValueError("Invalid band.  Valid bands are: %s" % valid_bands)

    if system == 'celestial':
        radec = coord.FK5Coordinates(lon, lat, unit=('deg', 'deg'))
        galactic = radec.galactic
    elif system == 'galactic':
        galactic = coord.GalacticCoordinates(lon, lat, unit=('deg', 'deg'))
        radec = galactic.fk5

    radecstr = radec.ra.format(sep=' ') + ' ' + radec.dec.format(sep=' ')
    glon, glat = galactic.lonangle.degrees, galactic.latangle.degrees

    # Construct request
    request = {}
    request["nvas_pos"] = radecstr
    request["nvas_rad"] = size
    request["nvas_rms"] = max_rms
    request["nvas_scl"] = size
    request["submit"] = "Search"
    request["nvas_bnd"] = band

    # create the request header data
    request = urllib.urlencode(request)
    # load the URL as text
    U = urllib.urlopen(request_URL, request)
    # read results with progressbar
    results = progressbar.chunk_read(U, report_hook=progressbar.chunk_report)

    if get_uvfits:
        links = uvfits_re.findall(results)
    else:
        links = imfits_re.findall(results)
    configurations = config_re.findall(results)

    if len(links) == 0:
        if verbose:
            print "No matches found at ra,dec = %s." % (radecstr)
        return []

    if verbose > 1:
        print "Configurations: "
        print "\n".join(
            ["%40s: %20s" % (L, C) for L, C in zip(links, configurations)])

    if save and not os.path.exists(directory):
        os.mkdir(directory)
    if save:
        opener = urllib2.build_opener()

    if verbose:
        print "Found %i imfits files" % len(links)

    images = []

    for link, config in zip(links, configurations):

        # Get the file
        U = opener.open(link)
        with aud.get_readable_fileobj(U) as f:
            results = f.read()
        S = StringIO.StringIO(results)
        try:
            fitsfile = fits.open(S, ignore_missing_end=True)
        except IOError:
            S.seek(0)
            G = gzip.GzipFile(fileobj=S)
            fitsfile = fits.open(G, ignore_missing_end=True)

        # Get Multiframe ID from the header
        images.append(fitsfile)

        if save:
            h0 = fitsfile[0].header
            freq_ghz = h0['CRVAL3'] / 1e9
            for bn, bandlimits in band_freqs.iteritems():
                if freq_ghz < bandlimits[1] and freq_ghz > bandlimits[0]:
                    bandname = bn
            obj = str(h0['OBJECT']).strip()
            program = h0['OBSERVER'].strip()
            h0['CONFIG'] = config

            if savename is None:
                if get_uvfits:
                    filename = "VLA_%s_G%07.3f%+08.3f_%s_%s.uvfits" % (
                        bandname, glon, glat, obj, program)
                else:
                    filename = "VLA_%s_G%07.3f%+08.3f_%s_%s.fits" % (
                        bandname, glon, glat, obj, program)
            else:
                filename = savename

            # Set final directory and file names
            final_file = directory + '/' + filename

            if verbose:
                print "Saving file %s" % final_file

            fitsfile.writeto(final_file, clobber=overwrite)

    return images