Example #1
0
def lookuptarget(name):
    """
    Wraps get_icrs_coordinates, but caches values 
    in .coordCache.txt to reduce internet lookups.
    Returns astropy SkyCoord
  """
    result = None
    filename = UserDataFileBase("astro-observability-planner",
                                "targetcoordcache.txt").getFileName()
    with open(filename, "a+") as coordCacheFile:
        coordCacheFile.seek(0)
        coordCacheReader = csv.reader(coordCacheFile, dialect='excel')
        for entry in coordCacheReader:
            if name.lower() == entry[0]:
                result = SkyCoord(entry[1])
        if not result:
            try:
                mapname = CALDWELL_MAP[name.lower()]
                result = get_icrs_coordinates(mapname)
            except KeyError:
                result = get_icrs_coordinates(name)
            finally:
                coordCacheWriter = csv.writer(coordCacheFile, dialect='excel')
                coordCacheWriter.writerow(
                    [name.lower(), result.to_string("hmsdms")])
    return result
Example #2
0
def sky_coord_from_str(s):
    s = s.strip()
    if s.upper().startswith('SNAD'):
        try:
            return SnadCatalogSource(s).coord
        except KeyError:
            raise ValueError(f"ID {s} isn't found in the SNAD catalog")
    try:
        return SkyCoord(s)
    except ValueError:
        pass
    try:
        return get_icrs_coordinates(s)
    except NameResolveError:
        raise ValueError(f'Cannot parse given coordinates or a name: "{s}"')
Example #3
0
    def __init__(self, object_name, time, time_format, duration,
                 frequency) -> None:
        self.name = object_name
        self.time = Time.Time(time, format=time_format)

        if self.name in coords.solar_system_ephemeris.bodies:
            self.coords = coords.get_body(self.name, self.time)
        elif self.name == 'moon':
            self.coords = coords.get_moon(self.time)
        elif self.name == 'sun':
            self.coords = coords.get_sun(self.time)
        else:
            try:
                self.coords = coords.get_icrs_coordinates(self.name)
            except coords.name_resolve.NameResolveError:
                print('I could not find that object...')
                print('Please manually set coordinates')

        self.duration = duration * u.second
        self.frequency = frequency * u.MHz
Example #4
0
    '''
    custom_ap = np.zeros(matrix_size)
    for row in pixel_list:
        xval = int(row[0])
        yval = int(row[1])
        custom_ap[yval, xval] = 1
    return (custom_ap)


##########################################################

#Module for manual entry of object name.

if input_is_name == 1:
    source_common_name = input('Common name of source: ')
    source_coordinates = get_icrs_coordinates(source_common_name)

#Module for manual entry of target coordinates.
if input_is_coords == 1:

    source_coords = input('Source coordinates as ra_deg,dec_deg: ')
    source_ra = float(source_coords.split(',')[0])
    source_dec = float(source_coords.split(',')[1])
    source_coordinates = SkyCoord(source_ra, source_dec, unit=u.deg)

#Execute astroquery for the DSS image with the requested number of pixels.

if input_is_coords == 1:
    dss_image = SkyView.get_images(
        position=source_coords, survey='DSS', pixels=str(dss_pixel_size)
    )  #Use this line for the dss query if the input is manual coor#Use this line for thedinates in decimal degrees.
Example #5
0
def extract_and_save(filename,ra,dec,size,outname='cutout.fits',cubemode=False):
    hdu=extract_subim(filename,ra,dec,size,verbose=False,cubemode=cubemode)
    hdu.writeto(outname,clobber=True)


if __name__=='__main__':
    filename=sys.argv[1]
    size=float(sys.argv[2])
    if len(sys.argv)==5:
        try:
            ra=float(sys.argv[3])
            dec=float(sys.argv[4])
        except ValueError:
            if sys.argv[3]=='object':
                c=get_icrs_coordinates(sys.argv[4])
            else:
                c = SkyCoord(sys.argv[3],sys.argv[4], frame='icrs',unit=(u.hourangle, u.deg))
            ra=float(c.ra.degree)
            dec=float(c.dec.degree)
            print ra,dec
        extract_and_save(filename,ra,dec,size)
    elif len(sys.argv)==4:
        s=sys.argv[3][4:]
        coord=s[0:2]+':'+s[2:4]+':'+s[4:9]+' '+s[9:12]+':'+s[12:14]+':'+s[14:]
        sc = SkyCoord(coord,unit=(u.hourangle,u.deg))
        ra=sc.ra.value
        dec=sc.dec.value
        print 'Parsed coordinates to ra=%f, dec=%f' % (ra,dec)
        name=sys.argv[1]
        extract_and_save(filename,ra,dec,size)
Example #6
0
             np.radians(dec2)))


f = Finder()

os.chdir('/data/lofar/mjh/3crr')
lines = open('3crr.txt').readlines()
names = [l[:10].rstrip() for l in lines[2:]]
t = Table.read('/data/lofar/lbcs/lbcs_stats.sum', format='ascii')
t['col10'].name = 'ra'
t['col11'].name = 'dec'

for l in lines:
    bits = l.split()
    n = bits[0]
    c = get_icrs_coordinates(n)
    ra = float(c.ra.degree)
    dec = float(c.dec.degree)

    bf = f.find(ra, dec)
    if bf is None:
        continue
    field = bf['id']
    if bf['sep'] < 1.25:
        # Now look for an LBCS calibrator which is both (1) 1.25
        # degrees or less from the pointing centre and (2) 0.5 degrees
        # from the target.
        r = f.t[f.t['id'] == field][0]
        fra = r['ra']
        fdec = r['decl']
        sep1 = separation(ra, dec, t['ra'], t['dec'])
Example #7
0
    if minoffset is None:
        return None
    else:
        return bestfield


if __name__ == '__main__':

    retval = None
    if len(sys.argv) == 3:
        try:
            ra = float(sys.argv[1])
            dec = float(sys.argv[2])
        except ValueError:
            if sys.argv[1] == 'object':
                c = get_icrs_coordinates(sys.argv[2])
            else:
                c = SkyCoord(sys.argv[1],
                             sys.argv[2],
                             frame='icrs',
                             unit=(u.hourangle, u.deg))
            ra = float(c.ra.degree)
            dec = float(c.dec.degree)
            print ra, dec
        retval = find_pos(ra, dec)
    elif len(sys.argv) == 2:
        s = sys.argv[1][4:]
        coord = s[0:2] + ':' + s[2:4] + ':' + s[4:9] + ' ' + s[9:12] + ':' + s[
            12:14] + ':' + s[14:]
        sc = SkyCoord(coord, unit=(u.hourangle, u.deg))
        ra = sc.ra.value
objname=sys.argv[1]
try:
    imsize=float(sys.argv[2])
except:
    imsize=0.5

if 'ILTJ' in objname:
    s=objname[4:]
    coord=s[0:2]+':'+s[2:4]+':'+s[4:9]+' '+s[9:12]+':'+s[12:14]+':'+s[14:]
    sc = SkyCoord(coord,unit=(u.hourangle,u.deg))
    ra=sc.ra.value
    dec=sc.dec.value
    print 'Parsed coordinates to ra=%f, dec=%f' % (ra,dec)
else:
    c=get_icrs_coordinates(objname)
    ra=float(c.ra.degree)
    dec=float(c.dec.degree)
    print 'Coordinate lookup gives ra=%f, dec=%f' % (ra,dec)

field=find_pos(ra,dec,offset=2.5)

if field is None:
    print 'Archived image does not exist'
else:
    wd='/data/lofar/DR2/fields/'+field
    if not os.path.isdir(wd):
        print 'DR2 directory does not exist'
    else:
        print 'Extracting LOW total intensity cutout'
        extract_and_save(wd+'/image_full_low_m.int.restored.fits',ra,dec,imsize,outname=objname+'_I.fits')
Example #9
0
objname = sys.argv[1]
try:
    imsize = float(sys.argv[2])
except:
    imsize = 0.5

if 'ILTJ' in objname:
    s = objname[4:]
    coord = s[0:2] + ':' + s[2:4] + ':' + s[4:9] + ' ' + s[9:12] + ':' + s[
        12:14] + ':' + s[14:]
    sc = SkyCoord(coord, unit=(u.hourangle, u.deg))
    ra = sc.ra.value
    dec = sc.dec.value
    print 'Parsed coordinates to ra=%f, dec=%f' % (ra, dec)
else:
    c = get_icrs_coordinates(objname)
    ra = float(c.ra.degree)
    dec = float(c.dec.degree)
    print 'Coordinate lookup gives ra=%f, dec=%f' % (ra, dec)

field = find_pos(ra, dec, offset=2.5)

if field is None:
    print 'Archived image does not exist'
else:
    wd = '/data/lofar/DR2/fields/' + field
    if not os.path.isdir(wd):
        print 'DR2 directory does not exist'
    else:
        print 'Extracting LOW total intensity cutout'
        extract_and_save(wd + '/image_full_low_m.int.restored.fits',
Example #10
0
def ra_ow(ra):
    """Convert astropy.coordinates RA to OW96 scheme"""
    h, m, s = ra.hms
    assert(int(h) == 5 and int(m/10) == 3)
    ra_code = "{:04d}".format(int((m - 30)*1000 + 10*(s + 0.05)))
    if ra_code.startswith('5'):
        ra_code = ra_code[1:]
    return ra_code

def dec_ow(dec):
    """Convert astropy.coordinates Dec to OW96 scheme"""
    d, m, s = dec.dms
    assert(int(d) == -5)
    dec_code = "{:04d}".format(int(abs(m)*100 + abs(s) + 0.5))
    if dec_code.startswith('2'):
        dec_code = dec_code[1:]
    return dec_code


def ow_from_coord(c):
    return "{}-{}".format(ra_ow(c.ra), dec_ow(c.dec))


if __name__ == '__main__':
    from astropy import coordinates as coord

    c = coord.get_icrs_coordinates('tet01 ori c')

    print('theta 1 C Ori is', ow_from_coord(c))
Example #11
0
def paysttrim(catalog):
	'''
	SUBROUTINE:			PAYSTTRIM
	DESCRIPTION: Trims matched PAYST dataset
	INPUT:       catalog -- filename of matched dataset from PAYSTMATCH
	OUTPUT:      NONE
	FILE OUTPUT: '[cluster].Trimmed.txt' -- Trimmed dataset. Same format as PAYSTMATCH output file. Format specified in main PAYST routine.
	'''
	# Define variables
	masterfilters = ['U', 'B', 'V', 'R', 'I', 'SU', 'SG', 'SR', 'SI', 'SZ', 'J', 'H', 'K', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6']
	ak = [1.531, 1.324, 1.000, 0.748, 0.482, 1.593, 1.199, 0.858, 0.639, 0.459, 0.282, 0.175, 0.112, 0.0627, 0.0482, 0.0482, 0.0482]

	print("==== PAYST ====")
	print("    Input Catalog: %s" % catalog)
	catf = open(catalog, "r")
	lines = catf.read().splitlines()
	catf.close()
	print("    Original Catalog Contains %d stars" % len(lines))
	
	# Create arrays
	id2mass = []
	ra, dec = np.zeros(len(lines)), np.zeros(len(lines))
	mags = np.zeros([len(lines), 44])
	mempct, memchar, member = np.zeros(len(lines)), [], np.zeros(len(lines))
	
	# Loop through file and read in data
	for l in range(len(lines)):
		tmp = lines[l].split()
		id2mass.append(tmp[0])
		ra[l], dec[l] = float(tmp[1]), float(tmp[2])
		for i in range(44): mags[l,i] = float(tmp[i+3])
		mempct[l] = float(tmp[47])
		memchar.append(tmp[48])
		member[l] = 1
		
	# Begin Menu Loop
	choice, isoplot = 100, 0
	pmag, pcol = -1, [0, 0]
	while choice != 0:
		# Check to see whether CMD can be plotted
		if pmag < 0:
			# Ask for new CMD choice
			pmagstr = raw_input('\nWhat is the CMD magnitude? ')
			pcolstr = raw_input('What is the CMD color? ')
			pmag = ([x for x in range(len(masterfilters)) if pmagstr == masterfilters[x]])[0]
			pcol[0] = ([x for x in range(len(masterfilters)) if (pcolstr.split('-'))[0] == masterfilters[x]])[0]
			pcol[1] = ([x for x in range(len(masterfilters)) if (pcolstr.split('-'))[1] == masterfilters[x]])[0]
			
		# Plot CMD
		try:
			cmdmag = [mags[x, 2*pmag] for x in range(len(lines)) if mags[x, 2*pmag] < 80 and mags[x, 2*pcol[0]] < 80 and mags[x, 2*pcol[1]] < 80 and member[x] == 1]
			cmdcol = [mags[x, 2*pcol[0]] - mags[x, 2*pcol[1]] for x in range(len(lines)) if mags[x, 2*pmag] < 80 and mags[x, 2*pcol[0]] < 80 and mags[x, 2*pcol[1]] < 80  and member[x] == 1]
			plt.clf()
			plt.plot(cmdcol, cmdmag, "ko", markersize=1)
			if isoplot == 1:
				isomag = [isodata[x,pmag+1] + isod + ak[pmag]/0.324*isoebv for x in range(len(isolines)) if isodata[x,0] == isoage]
				isocol = [isodata[x,pcol[0]+1] - isodata[x,pcol[1]+1] + (ak[pcol[0]] - ak[pcol[1]])/0.324*isoebv for x in range(len(isolines)) if isodata[x,0] == isoage]
				plt.plot(isocol, isomag, "b-")
			plt.axis([min(cmdcol)-0.1, max(cmdcol)+0.1, max(cmdmag)+0.5, min(cmdmag)-0.5])
			plt.ylabel(pmagstr)
			plt.xlabel(pcolstr)
			plt.show(block=False)
			plt.draw()
		except:
			print("Plotting Error. Re-choose CMD magnitudes, or revert trimming.")
			
		# Print Menu
		print("\n")
		print("1) RA / Dec Cut          2) Membership Cut")
		print("3) A_K Cut               4) Full Photometry Cut")
		print("")
		print("8) Change CMD Options    9) Reset Trimming")
		print("0) Complete             -1) Abort")
		choice = input(': ')
		print("\n")
		
		# Emergency Break
		if choice == -1: sys.exit(0)
		
		# Spatial RA/Dec Trim
		if choice == 1:
			dirsplit = catalog.split('/')
			namesplit = dirsplit[len(dirsplit)-1].split('.')
			try:
				import astropy.coordinates as astrocoo
				c = astrocoo.get_icrs_coordinates(namesplit[0])
				clra = c.ra.deg
				cldec = c.dec.deg
				print("Cluster coordinates: %9.5f  %9.5f" % (clra, cldec))
			except:
				print("Cannot find cluster '%s'" % namesplit[0])
				clra = float(input("Enter cluster RA: "))
				cldec = float(input("Enter cluster DEC: "))
				
			# Generate Spatial Plot for Cluster
			cutset = 0
			while cutset != 1:
				gra = [ra[x] for x in range(len(lines)) if member[x] == 1]
				gdec = [dec[x] for x in range(len(lines)) if member[x] == 1]
				plt.clf()
				plt.plot(gra, gdec, "ko", markersize=1)
				plt.plot(clra, cldec, "bo", markersize=4)
				if max(gdec) - min(gdec) > 2: plt.axis([clra-1, clra+1, cldec-1, cldec+1])
				else: plt.axis([min(gra)-0.1, max(gra)+0.1, min(gdec)-0.1, max(gdec)+0.1])
				plt.show(block=False)
				plt.draw()
				
				# Ask for trimming radius
				clrad = input('Enter cluster radius (arcmin): ') / 60.0
				
				# Show trimming radius on plot
				radra, raddec = [], []
				for e in range(100):
					angle = 2.0*np.pi * (float(e)/100.0)
					radra.append(clra + np.cos(angle) * clrad)
					raddec.append(cldec + np.sin(angle) * clrad)
				plt.clf()
				plt.plot(gra, gdec, "ko", markersize=1)
				plt.plot(clra, cldec, "bo", markersize=4)
				plt.plot(radra, raddec, "b-")
				if max(gdec) - min(gdec) > 2: plt.axis([clra-1, clra+1, cldec-1, cldec+1])
				else: plt.axis([min(gra)-0.1, max(gra)+0.1, min(gdec)-0.1, max(gdec)+0.1])
				plt.show(block=False)
				plt.draw()
				
				cutchoice = raw_input('Radius ok? (y|n)  ')
				if cutchoice == 'y': cutset = 1
				
			# Loop through and deselect stars outside radius
			trimmed = 0
			for s in range(len(ra)):
				if member[s] == 0: continue
				dist = np.sqrt((ra[s] - clra)**2 + (dec[s] - cldec)**2)
				if dist > clrad:
					trimmed += 1
					member[s] = 0
			print("Removed %d stars.  %d remaining." % (trimmed, len(member[member>0])))
			
		# Membership Selection
		if choice == 2:
			print("Qualitative Selection:")
			print("  1) Select only Members")
			print("  2) Select only Single Members")
			print("  3) Deselect only Non-Members")
			print("  4) No Selection")
			charchoice = input(': ')
			print("\nQuantitative Selection:")
			print("  1) Select only Stars > %")
			print("  2) Deselect only Stars < %")
			print("  3) No Selection")
			pctchoice = input(': ')
			if pctchoice < 3: pctcut = input('Enter % cutoff: ')
			
			# Loop through stars and select necessary stars
			trimmed = 0
			for s in range(len(member)):
				if member[s] == 0: continue
				ccut, pcut = 0, 0
				# Go through qualitative selection criteria
				if charchoice == 1:
					if memchar[s].find('M') < 0: ccut = 1
				elif charchoice == 2:
					if memchar[s].find('M') < 0 or memchar[s].find('S') < 0: ccut = 1
				elif charchoice == 3:
					if memchar[s].find('N') >= 0: ccut = 1
				else:
					ccut = -1
				# Go through quantitative selection criteria
				if pctchoice == 1:
					if mempct[s] < pctcut: pcut = 1
				elif pctchoice == 2:
					if mempct[s] < pctcut and mempct[s] >= 0: pcut = 1
				else:
					pcut = -1
				# Make choice to trim or not
				if ccut > 0:
					member[s] = 0
					trimmed += 1
				elif pcut > 0:
					member[s] = 0
					trimmed += 1
					
			print("Removed %d stars.  %d remaining." % (trimmed, len(member[member>0])))
			
		# A_K Cut
		#if choice == 3:
					
		# Photometry Cut
		if choice == 4:
			nvis, nnir, nmir = np.zeros(len(ra)), np.zeros(len(ra)), np.zeros(len(ra))
			nfilt = np.zeros(16)
			for s in range(len(ra)):
				# Calculate number of good visual filters
				gjc = [x for x in range(5) if mags[s, 2*x] < 80]
				gtg = [x for x in range(5,10) if mags[s, 2*x] < 80]
				# N_VIS is maximum of either visual set
				nvis[s] = max([len(gjc), len(gtg)])
				
				# Calculate number of good 2MASS filters
				g2m = [x for x in range(10,13) if mags[s, 2*x] < 80]
				nnir[s] = len(g2m)
				
				# Calculate number of good IRAC filters
				gir = [x for x in range(13, 17) if mags[s, 2*x] < 80]
				nmir[s] = len(gir)
				
				# Adjust count for filters
				nfilt[0:nvis[s]+nnir[s]+nmir[s]+1] += 1
				# Adjust for SED filter combinations
				if nvis[s] >= 3 and nnir[s] >= 3 and nmir[s] >= 3: nfilt[13] += 1
				if nvis[s] >= 3 and nnir[s] >= 3 and nmir[s] >= 2: nfilt[14] += 1
				if nvis[s] >= 3 and nnir[s] >= 2 and nmir[s] >= 2: nfilt[15] += 1
				
			# Print out options for filter counts
			print("# Filters    # Stars")
			for f in range(13):
				if nfilt[f] == 0: continue
				print("   %3d       %7d" % (f, nfilt[f]))
			print("\nSED FITTING")
			print("   %3d       %7d" % (333, nfilt[13]))
			print("   %3d       %7d" % (332, nfilt[14]))
			print("   %3d       %7d" % (322, nfilt[15]))
			minfilt = input('\nMinimum number of filters: ')
			minfilt_str = "%03d" % minfilt
			
			# Trim stars
			trimmed = 0
			for s in range(len(ra)):
				if minfilt < 100:
					if nvis[s]+nnir[s]+nmir[s] < minfilt:
						member[s] = 0
						trimmed += 1
				else:
					if nvis[s] < int(minfilt_str[0]) or nnir[s] < int(minfilt_str[1]) or nmir[s] < int(minfilt_str[2]):
						member[s] = 0
						trimmed += 1
					
			print("Removed %d stars.  %d remaining." % (len(member[member==0]), len(member[member>0])))
			
		# Isochrone overplotting
		if choice == 5:
			if isoplot == 0:
				isonames = subprocess.check_output('ls ~/projects/isochrones/new/*.dat', shell=True).splitlines()
				isoname = raw_input('Enter isochrone name to overplot: ')
				isoidx = [x for x in range(len(isonames)) if isonames[x].find(isoname) >= 0]
				isof = open(isonames[isoidx[0]], "r")
				isolines = isof.read().splitlines()
				isof.close()
				isodata = np.zeros([len(isolines), 18])
				for l in range(len(isolines)):
					tmp = [float(x) for x in isolines[l].split()]
					isodata[l,0] = tmp[0]
					for j in range(1,18): isodata[l,j] = tmp[j+6]
				isoplot = 1
			else:
				removechoice = raw_input('Adjust parameters? (y|n): ')
				if removechoice == 'n':
					isoplot = 0
					print("Removing isochrone ridgeline.")
					continue
			isoage = input('Enter isochrone age: ')
			isod = input('Enter isochrone m-M: ')
			isoebv = input('Enter isochrone E(B-V): ')
			
		# Change CMD options
		if choice == 8:
			pmag = -1
			
		# Reset trimming options
		if choice == 9:
			for s in range(len(member)): member[s] = 1
			print("Restored", len(member), "stars.")
			
	# Now that trimming is done, print out everything
	catsplit = catalog.split('/')
	if len(catsplit) > 1: prefix = "/".join(catsplit[0:len(catsplit)-1]) + "/"
	else: prefix = ""
	
	namesplit = catsplit[len(catsplit)-1].split('.')
	print("Writing results to '%s'..." % (namesplit[0]+".Trimmed.txt"))
	out = open(prefix+namesplit[0]+".Trimmed.txt", 'w')
	for i in range(len(id2mass)):
		if member[i] == 0: continue
		outstring = ""
		outstring += "%16s " % (id2mass[i])					# Add 2MASS ID to output
		outstring += "%9.5f %9.5f " % (ra[i], dec[i])		# Add coordinates to output
		for f in range(19):									# Add filter magnitudes to output
			outstring += "%6.3f %5.3f " % (mags[i, 2*f], mags[i, 2*f+1])
		for v in range(6):									# Add kinematic information to output
			outstring += "%8.3f " % (mags[i, v+38])
		outstring += "%5d " % (mempct[i])					# Add member information to output
		outstring += "%5s " % (memchar[i])
		print(outstring, file=out)
	out.close()	
	
	
Example #12
0
def main(srcID, radius, DoDec=True, output="tgss.skymodel"):
    """
   tgss2bbs2: 
   
   This inputs are srcID (string) as a co-ordinate or object ID
                   radius (float) is radius in degrees, converted in caller function
                   DoDec (bool) Option to do deconvolution
   The result is saved in atext file which is both logged locally and sent to the user
        through wget or through the browser
   """
    patch = True

    objName = srcID
    radInDeg = float(radius)
    outFileName = output
    inOnePatch = patch

    # Get the sources in the cut-out as a VO table
    url = 'http://vo.astron.nl/tgssadr/q/cone/scs.xml'
    try:
        t = vo.conesearch(url,
                          pos=get_icrs_coordinates(objName),
                          radius=radInDeg)
    except IndexError:
        f = open(outFileName, 'w')
        f.write(
            "Index Error when polling VirtualObservatory. Bad object name??")
        f.close()
        return

    f = open(outFileName, 'w')
    if patch:
        # Write all selected components as a single patch
        f.write(
            "FORMAT = Name, Type, Patch, Ra, Dec, I, Q, U, V, MajorAxis, MinorAxis, Orientation, ReferenceFrequency='147500000.0', SpectralIndex='[]'\n\n"
        )
        # Get the coordinates of the source
        c = radec_to_string.radec_to_string(
            [
                get_icrs_coordinates(objName).ra.value,
                get_icrs_coordinates(objName).dec.value
            ],
            separators=[':', ':', '$', '.', ".", ''])
        newRA = c.split("$")[0]
        newDec = c.split("$")[1]
        # Create the header
        f.write(' , , Patch, {ra}, {dec}\n'.format(ra=newRA, dec=newDec))

        for item in t:
            # VO table has RA and DEC in degrees. Convert it to hmsdms format
            coords = radec_to_string.radec_to_string(
                [float(item['RA']), float(item['DEC'])],
                separators=[':', ':', '$', '.', ".", ''])
            newRA = coords.split("$")[0]
            newDec = coords.split("$")[1]
            #use radec_to_string to convert coordinates instead of Astropy
            if ((item['Sint'] / item['Spk']) >
                (2 * math.sqrt(0.027**2 +
                               (0.784 * (item['Spk'] / item['Island_RMS'])**
                                (-0.925))**2) + 1.071)):
                srctp = 'GAUSSIAN'
                if not DoDec:
                    maja = item['MAJAX']
                    mina = item['MINAX']
                    pax = item['PA']

                else:
                    bmaj1, bmin1, bpa1 = Beam_deconv_new.psfTGSS1(item["DEC"])
                    A1, B1, C1 = Beam_deconv_new.elliptic2quadratic(
                        bmaj1, bmin1, bpa1)
                    A2, B2, C2 = Beam_deconv_new.elliptic2quadratic(
                        item["MAJAX"], item["MINAX"], item["PA"])
                    Ak, Bk, Ck = Beam_deconv_new.deconvolve(
                        A2, B2, C2, A1, B1, C1)
                    maja, mina, pax = Beam_deconv_new.quadratic2elliptic(
                        Ak, Bk, Ck)
                    if maja == None:
                        maja = ""
                        mina = ""
                        pax = ""
                    else:
                        ## Some nice pretty formatting
                        maja = "{0:0.1f}".format(maja)
                        mina = "{0:0.1f}".format(mina)
                        pax = "{0:0.1f}".format(pax)
                if pax < 10 and pax != "":
                    pa1 = "{0:.2f}".format(float(pax))
                else:
                    pa1 = pax
                if item['PA'] > 0:
                    paxi = ' ' + str(pa1)
                else:
                    paxi = pa1
                if pax == '' or pax == 'nan':  #Deconvolution fails to converge. Made it into a point source for now
                    srctp = 'POINT   '
                    maja = '    '
                    mina = '    '
                    paxi = '     '
            else:
                srctp = 'POINT   '
                maja = '    '
                mina = '    '
                paxi = '     '

        # Write an entry for this source into the output file inside the above defined patch
            f.write(
                "{name}, {src}, Patch, {ra}, {dec}, {i}, 0, 0, 0, {ma}, {mi}, {pa}, , [-0.73]\n"
                .format(name=item['ID'],
                        src=srctp,
                        ra=newRA,
                        dec=newDec,
                        i='{0: >9}'.format(format(item['Sint'] / 1e3, '.4f')),
                        ma=maja,
                        mi=mina,
                        pa=paxi))
    else:
        # Writes sources without a patch
        f.write(
            "FORMAT = Name, Type, Ra, Dec, I, Q, U, V, MajorAxis, MinorAxis, Orientation, ReferenceFrequency='147610000.0', SpectralIndex='[]'\n\n"
        )
        for item in t:
            # VO table has RA and DEC in degrees. Convert it to hmsdms format
            coords = radec_to_string.radec_to_string(
                [float(item['RA']), float(item['DEC'])],
                separators=[':', ':', '$', '.', ".", ''])
            newRA = coords.split("$")[0]
            newDec = coords.split("$")[1]
            # Write an entry for this source into the output file
            #Case Gaussian
            f.write(
                "{name}, GAUSSIAN, {ra}, {dec}, {i}, 0, 0, 0, {ma}, {mi}, {pa}, , [-0.8]\n"
                .format(name=item['ID'],
                        ra=newRA,
                        dec=newDec,
                        i=item['Sint'] / 1e3,
                        ma=item['MAJAX'],
                        mi=item['MINAX'],
                        pa=item['PA']))
    f.close()
Example #13
0
    def query_region(self,
                     objectname,
                     match_tol=1.0,
                     obj_radius=1.0,
                     bycoord=False):
        '''
        Fetch remote data from NED and SIMBAD matching coordinates and build table.
        '''
        # Create custom query objects.
        customSimbad = Simbad()
        customNed = Ned()

        # Log SIMBAD votable (changeable) fields.
        logging.debug("SIMBAD votable fields")
        logging.debug(customSimbad.get_votable_fields())

        customSimbad.remove_votable_fields('coordinates')
        # customSimbad.add_votable_fields("otype(3)", "ra(d)", "dec(d)")
        customSimbad.add_votable_fields("otype", "ra(d)", "dec(d)")

        # Download object data from both SIMBAD and NED.
        logging.info(
            "Querying SIMBAD and NED for region {}".format(objectname))

        if bycoord:
            try:
                objectcoords = SkyCoord(objectname)
            except (ValueError, u.UnitsError):
                logging.info("Invalid coordinates.")
                return
        else:
            # Resolve the object name into sky coordinate using NED
            # ensures that NED and SIMBAD searches are using the same position
            sesame_database.set('ned')
            try:
                objectcoords = get_icrs_coordinates(objectname)
            except NameResolveError:
                logging.info("Name resolution failed.")
                return

        logging.info("Name resolved to coordinates {}".format(objectcoords))

        # SIMBAD
        logging.info("SIMBAD is currently being queried...")
        try:
            with warnings.catch_warnings(
            ):  # suppress warnings generated by SIMBAD query
                warnings.simplefilter("ignore")
                simbad_table = customSimbad.query_region(objectcoords,
                                                         radius=obj_radius *
                                                         u.arcmin)
        # workaround. If SIMBAD query finds nothing, returns None but we want a zero-length table
            if type(simbad_table) is not Table:
                logging.debug("No SIMBAD objects")
                simbad_table = Table(data=None,
                                     names=DataController.simbad_table_cols,
                                     dtype=DataController.simbad_table_dtypes,
                                     masked=True)
            logging.info("SUCCESS: SIMBAD Data retrieved.")
        except Timeout:
            logging.debug("SIMBAD timeout error")
            return

    # NED
        logging.info("NED is currently being queried...")
        for attempt in range(
                3):  # sometimes NED times out, so try a couple of times
            Ned.TIMEOUT = (attempt + 1) * DataController.ned_timeout_default
            try:
                ned_table = Ned.query_region(objectcoords,
                                             radius=obj_radius * u.arcmin)
                logging.info("SUCCESS: NED Data retrieved.")
            except RequestException:
                logging.debug("NED problem, retrying")
            else:  # if attempt successful break out of loop, no need to try again
                break
        else:  # closes for loop: executes only if all attempts fail
            logging.debug("NED query failed")
            return

# Save some query stats.
        self.stats.query_name = objectname
        self.stats.sim_count = len(simbad_table)
        self.stats.ned_count = len(ned_table)

        # process tables
        ned_table = self.reformat_table(
            ned_table,
            keepcolsifpresent=[
                'Object Name',
                # cover NED changing names of cols
                'RA(deg)',
                'RA',
                'DEC(deg)',
                'DEC',
                'Type'
            ],
            old_name='Object Name',
            new_name='Name_N',
            old_type='Type',
            new_type='Type_N')

        logging.info("Reformatting tables.")
        simbad_table = self.reformat_table(
            simbad_table,
            keepcolsifpresent=["MAIN_ID", "RA_d", "DEC_d", "OTYPE"],
            old_name='MAIN_ID',
            new_name='Name_S',
            old_type='OTYPE',
            new_type='Type_S')

        logging.info("Building sky coordinates.")
        # Build SkyCoord from appropriate ned and simbad col's with matching units
        ned_coo = SkyCoord(ra=ned_table['RA(deg)'], dec=ned_table['DEC(deg)'])
        sim_coo = SkyCoord(ra=simbad_table['RA_d'], dec=simbad_table['DEC_d'])

        logging.info("Finding object matches.")
        # Find object matches
        if len(ned_coo) > 0 and len(sim_coo) > 0:
            matched_ned, matched_sim, ned_only, sim_only = self.symmetric_match_sky_coords_v2(
                ned_coo, sim_coo, match_tol * u.arcsec)
        else:
            matched_ned = []
            matched_sim = []
            ned_only = []
            sim_only = []
        logging.debug("")
        logging.debug("Matched NED rows:")
        logging.debug(ned_table[matched_ned])
        logging.debug("Matched SIMBAD rows:")
        logging.debug(simbad_table[matched_sim])
        logging.debug("")

        self.stats.overlap_count = len(matched_ned)

        # Explore results
        logging.debug("Matched NED:")
        logging.debug(matched_ned)
        logging.debug("Matched SIMBAD")
        logging.debug(matched_sim)
        logging.debug("NED ONLY")
        logging.debug(ned_only)
        logging.debug("SIMBAD ONLY")
        logging.debug(sim_only)

        # Generate the matched table and save the result.
        logging.info("Building combined table.")
        matched_table = hstack(
            [ned_table[matched_ned], simbad_table[matched_sim]],
            join_type='outer',
            metadata_conflicts='silent')  # Hide the metadata warning.
        self.combined_table = matched_table
def vizier_sed(target_name, r=5, source_path="."):
    from astropy.coordinates import get_icrs_coordinates
    from desk.set_up.vizier_sed import query_sed
    from astropy.table import Table
    import astropy.units as u
    """Obtains SED using Morgan Fouesneau's vizier_sed script
    (https://gist.github.com/mfouesneau/6caaae8651a926516a0ada4f85742c95).
    Package then is parsed into a version usable by the DESK.

    Parameters
    ----------
    target : str or tuple
        Name of target to be resolved by Vizier
        or tuple with ra and dec in degrees.
    r : float
        Cone radius to search for photometry within vizier.
    returns:
        csv file with photometry in wavelength (um),
        flux (Jy), and instrument filter.
    """
    # Checks if name
    if isinstance(target_name, str):
        if "(" in target_name:  # command line passes tuple as string
            results = query_sed(eval(target_name), radius=float(r))
            csv_name = ("vizier_phot_" + str(eval(target_name)[0]) + "_" +
                        str(eval(target_name)[1]) + ".csv")
        else:
            coords = get_icrs_coordinates(target_name)
            results = query_sed([coords.ra.value, coords.dec.value],
                                radius=float(r))
            csv_name = target_name.replace(" ", "_") + "_sed.csv"

    # Checks if tuple of ra and dec in deg
    elif isinstance(target_name, tuple):
        results = query_sed(target_name, radius=r)
        csv_name = ("vizier_phot_" + str(target_name[0]) + "_" +
                    str(target_name[1]) + ".csv")

    else:
        raise ValueError(
            "Input format not understood: " + str(target_name) +
            "\n Examples: " + "\n\t desk.vizier_sed('HM Sge')" +
            "\n\t desk.vizier_sed('HMSge', 5)" +
            "\n\t desk.vizier_sed((295.4879586347,16.7446716483))" +
            "\n\t desk.vizier_sed((295.4879586347,16.7446716483), 4)")

    output_table = Table(
        (
            results["sed_freq"].to(u.um, equivalencies=u.spectral()).value,
            results["sed_flux"],
            results["sed_filter"],
        ),
        names=("wave_um", "flux_jy", "filter"),
    )
    output_table.sort("wave_um")

    output_table.write(source_path + "/" + csv_name, overwrite=True)
    print("\nPhotometry saved as: '" + csv_name + "'")
    print(
        "\n\tTo explore photometry further, go to:\n\t http://vizier.unistra.fr/vizier/sed/ \n"
    )
Example #15
0
def extract_list(t,
                 resolve=False,
                 check_exists=True,
                 use_fields=True,
                 imagesize=0.5):
    ''' t is an astropy table with columns name and optionally ra,dec which will be used if resolve=False. If use_fields is True, unmosaiced fields from all the sky will be checked, else only mosaics. imagesize is in degrees '''
    f = Finder()
    for r in t:
        n = r['name']
        filename = n + '.fits'
        if check_exists and os.path.isfile(filename):
            continue
        if resolve:
            c = get_icrs_coordinates(n)
            ra = float(c.ra.degree)
            dec = float(c.dec.degree)
        else:
            ra = r['ra']
            dec = r['dec']
        bf = f.find(ra, dec)
        if bf is None:
            print('%s not found' % n)
            continue
        field = bf['id']
        success = False
        if bf['sep'] < 1.95 and os.path.isdir('/data/lofar/DR2/mosaics/' +
                                              field):
            # extract from mosaics dir
            print('Extracting %s from mosaic %s' % (n, field))
            extract_and_save('/data/lofar/DR2/mosaics/' + field +
                             '/mosaic-blanked.fits',
                             ra,
                             dec,
                             imagesize,
                             outname=filename)
            fieldhdu = fits.open(
                '/data/lofar/DR2/fields/' + field +
                '/image_full_ampphase_di_m.NS_shift.int.facetRestored.fits')
            date = fieldhdu[0].header['DATE-OBS']
            fieldhdu.close()
            hdu = fits.open(filename)
            maxy, maxx = hdu[0].data.shape
            success = ~np.isnan(hdu[0].data[maxy // 2, maxx // 2])
            if not success:
                print('Image is centrally blanked!')
            else:
                hdu[0].header['DATE-OBS'] = date
                hdu[0].header['OBJECT'] = field + '_mosaic'
                hdu.writeto(filename, overwrite=True)

        if not success and use_fields:
            scale = 5.9124 / bf['nvss_scale']
            print('Extracting %s from field %s with scale factor %.3f' %
                  (n, field, scale))
            extract_and_save(
                '/data/lofar/DR2/fields/' + field +
                '/image_full_ampphase_di_m.NS_shift.int.facetRestored.fits',
                ra,
                dec,
                imagesize,
                outname=n + '.fits',
                scale=scale)
Example #16
0
def add_obj_coordinates(hdr, object_name, args):
    RA = RA_hours = DEC = redshift = equinox = ""

    # Standard star he 3 is not found in NED
    if object_name[:] == "he3":
        object_name = "WD 0644+375"

    # Search NED for the object_name
    try:
        query = urllib2.urlopen("http://ned.ipac.caltech.edu/cgi-bin/"+\
                                "nph-objsearch?extend=no&out_equinox=J2000&of="+\
                                "ascii_tab&objname=" + object_name)
        result = query.readlines()
        last_line = result[-1].split()
        RA = last_line[3]
        RA_hours = float(RA) * 24/360.         
        DEC = float(last_line[4])
        equinox = "2000"
        redshift = last_line[7]             
    except:
        pass
    
    # If still no RA_obj is found, try finding them on Sesame
    if RA_hours == "":
        try:
            c = coord.get_icrs_coordinates(object_name)
            RA_hours = c.fk5.ra.hourangle
            DEC = c.fk5.dec.degree
            equinox = c.fk5.equinox.jyear_str[1:]
        except coord.name_resolve.NameResolveError:
            pass

    # Maybe there is a RA, DEC in the header?
    if RA_hours == ""  and args.RA_keyword != "" and args.DEC_keyword != "":
        if hdr.has_key(args.RA_keyword):
            RA = hdr[args.RA_keyword] 
            DEC = hdr[args.DEC_keyword]
            # Format of RA?
            if RA.count(":") > 0:          # hours:min:sec
                RA = RA.split(":")         # [hours, min, sec]
                RA_hours = float(RA[0]) + float(RA[1])/60. + float(RA[2])/3600.
            elif len(RA.split()) == 3:     # hours min sec
                RA = RA.split()            # [hours, min, sec]
                RA_hours = float(RA[0]) + float(RA[1])/60. + float(RA[2])/3600.
            elif len(RA.split()) == 0:     # single number?
                try:
                    RA = float(RA)         # Assuming it is in degrees
                    RA_hours = RA*24./360
                except:
                    pass
            # Same for DEC:
            if len(DEC.split()) == 3:      # deg arcmin arcsec
                DEC = DEC.split()
                DEC = float(DEC[0]) + float(DEC[1])/60. + float(DEC[2])/3600.
            RA_hours = str(RA_hours)
            DEC = str(DEC)
            print "\n Not found in NED or Sesame: ", object_name, RA_hours, DEC
                    
    # Write results, whatever you have found.     
    hdr["object"] = (object_name, "Name of the object")
    hdr["RA"] = (RA, "Right Ascension")
    hdr["DEC"] = (DEC, "Declination ")
    hdr["RA_hours"] = (RA_hours, "RA of the object (hours)")
    hdr["DEC_deg"] = (DEC, "DEC of the object (degrees)")
    hdr["equinox"] = (equinox, "equinox of coordinates")
    if redshift != "":
        hdr["redshift"] = (redshift, "Redshift of the object")  
    return hdr