Hubble Source Catalog SWEEPS Proper Motion Notebook

June 2019, Steve Lubow and Rick White

This notebook shows how to access the new proper motions available for the SWEEPS field in version 3.1 of the Hubble Source Catalog. Data tables in MAST CasJobs are queried from Python using the mastcasjobs module. Additional information is available on the SWEEPS Proper Motions help page.

This notebook is available for download.

Instructions:

  • Complete the initialization steps described below.
  • Run the notebook to completion.
  • Modify and rerun any sections of the Table of Contents below.

Running the notebook from top to bottom takes about 7 minutes (depending on the speed of your computer).

Table of Contents

Initialization

Install Python modules

This notebook requires the use of Python 3.

This needs some special modules in addition to the common requirements of astropy, numpy and scipy. For anaconda versions of Python the installation commands are:

conda install requests
pip install git+git://github.com/dfm/casjobs@master
pip install git+git://github.com/rlwastro/mastcasjobs@master
pip install fastkde

If you already have an older version of the mastcasjobs module, you may need to update it:

pip install --upgrade git+git://github.com/rlwastro/mastcasjobs@master

Set up your CasJobs account information

You must have a MAST Casjobs account (see https://mastweb.stsci.edu/hcasjobs to create one). Note that MAST Casjobs accounts are independent of SDSS Casjobs accounts.

For easy startup, you can optionally set the environment variables CASJOBS_USERID and/or CASJOBS_PW with your Casjobs account information. The Casjobs user ID and password are what you enter when logging into Casjobs.

This script prompts for your Casjobs user ID and password during initialization if the environment variables are not defined.

Other optional configuration

If desired, you can set resPath, the output directory, in the next code block (the default location is the current working directory, which is probably the same directory as this script).

In [1]:
resPath="./" # directory where generated plots are saved
HSCContext= "HSCv3"

%matplotlib inline
import astropy, pylab, time, sys, os, requests
import numpy as np
from matplotlib.colors import LogNorm

# check that version of mastcasjobs is new enough
# we are using some features not in version 0.0.1
from pkg_resources import get_distribution
from distutils.version import StrictVersion as V
assert V(get_distribution("mastcasjobs").version) >= V('0.0.2'), """
A newer version of mastcasjobs is required.
Update mastcasjobs to current version using this command:
pip install --upgrade git+git://github.com/rlwastro/mastcasjobs@master
"""

import mastcasjobs

## For handling ordinary astropy Tables
from astropy.table import Table
from astropy.io import fits, ascii

from fastkde import fastKDE
from scipy.interpolate import RectBivariateSpline
from astropy.modeling import models, fitting

# There are a number of relatively unimportant warnings that 
# show up, so for now, suppress them:
import warnings
warnings.filterwarnings("ignore")

# Set page width to fill browser for longer output lines
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
# set width for pprint
astropy.conf.max_width = 150

Set up Casjobs environment.

In [2]:
import getpass
if not os.environ.get('CASJOBS_USERID'):
    os.environ['CASJOBS_USERID'] = input('Enter Casjobs UserID:')
if not os.environ.get('CASJOBS_PW'):
    os.environ['CASJOBS_PW'] = getpass.getpass('Enter Casjobs password:')

Create table in MyDB with selected SWEEPS objects

Note that the query restricts the sample to matches with at least 10 detections in each of F606W and F814W. This can be modified depending on the science goals.

This uses an existing MyDB.SWEEPS table if it already exists in your CasJobs account. If you want to change the query, either change the name of the output table or drop the table to force it to be recreated. Usually the query completes in about a minute, but if the database server is heavily loaded then it can take much longer.

In [3]:
DBtable = "SWEEPS"
jobs = mastcasjobs.MastCasJobs(context="MyDB")

try:
    print("Retrieving table MyDB.{} (if it exists)".format(DBtable))
    tab = jobs.fast_table(DBtable, verbose=True)
except ValueError:
    print("Table MyDB.{} not found, running query to create it".format(DBtable))

    # drop table if it already exists
    jobs.drop_table_if_exists(DBtable)

    #get main information
    query = """
        select a.ObjID,  RA=a.raMean, Dec=a.decMean, RAerr=a.raMeanErr, Decerr=a.decMeanErr,
            c.NumFilters, c.NumVisits,
            a_f606w=i1.MagMed,  a_f606w_n=i1.n, a_f606w_mad=i1.MagMAD,
            a_f814w=i2.MagMed, a_f814w_n=i2.n, a_f814w_mad=i2.MagMAD,
            bpm=a.pmLat, lpm=a.pmLon, bpmerr=a.pmLatErr, lpmerr=a.pmLonErr,
            pmdev=sqrt(pmLonDev*pmLonDev+pmLatDev*pmLatDev),
            yr=(a.epochMean - 47892)/365.25+1990, 
            dT=(a.epochEnd-a.epochStart)/365.25,
            yrStart=(a.epochStart - 47892)/365.25+1990,
            yrEnd=(a.epochEnd - 47892)/365.25+1990
        into mydb.{}
        from AstromProperMotions a join AstromSumMagAper2 i1 on 
             i1.ObjID=a.ObjID and i1.n >=10 and i1.filter ='F606W' and i1.detector='ACS/WFC'
         join AstromSumMagAper2 i2 on 
             i2.ObjID=a.ObjID and i2.n >=10 and i2.filter ='F814W' and i2.detector='ACS/WFC'
         join AstromSumPropMagAper2Cat c on a.ObjID=c.ObjID
    """.format(DBtable)

    t0 = time.time()
    jobid = jobs.submit(query, task_name="SWEEPS", context=HSCContext)
    print("jobid=",jobid)
    results = jobs.monitor(jobid)
    print("Completed in {:.1f} sec".format(time.time()-t0))
    print(results)

    # slower version using CasJobs output queue
    # tab = jobs.get_table(DBtable, verbose=True)
    
    # fast version using special MAST Casjobs service
    tab = jobs.fast_table(DBtable, verbose=True)

tab
Retrieving table MyDB.SWEEPS (if it exists)
Table MyDB.SWEEPS not found, running query to create it
jobid= 11815903
Completed in 20.3 sec
(5, 'finished')
16.3 s: Retrieved 157.86MB table MyDB.SWEEPS
30.5 s: Converted to 443932 row table
Out[3]:
Table length=443932
ObjIDRADecRAerrDecerrNumFiltersNumVisitsa_f606wa_f606w_na_f606w_mada_f814wa_f814w_na_f814w_madbpmlpmbpmerrlpmerrpmdevyrdTyrStartyrEnd
int64float64float64float64float64int64int64float64int64float64float64int64float64float64float64float64float64float64float64float64float64float64
4000709002286269.7911379669984-29.2061561874114230.69648186245280990.273006233080014124722.127399444580078470.02160072326660156221.13010025024414470.01679992675781252.087558644949346-7.7382723294303710.388545822763860070.221156733689812372.8871545181336922013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709002287269.7955922590832-29.2061516314949860.240202167603863430.1852481139121781624721.508499145507812470.02999877929687520.69930076599121470.023900985717773438-2.8930568503344967-0.78985838465552450.13165847900535780.124621856958779961.4746766326637852013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709002288269.81608933789283-29.2061551966411950.30406841310206710.285040758620025624721.654399871826172470.0365009307861328120.85770034790039470.0171012878417968754.65866649193795-3.20988045803437850.139311721836511830.206480976047816261.95703573227134632013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709002289269.8259694163096-29.206156688407510.35643254265220670.3954220029733366324719.79170036315918470.02820014953613281219.06909942626953470.019300460815429688-0.45662407290928664-2.09090500454338320.157581759523336530.27638812821949082.24152384993776852013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709002290269.83486415728754-29.2061552669836430.162996398391985380.1406283940781183624620.566649436950684460.01594924926757812519.847750663757324460.0148010253906254.459275526783969-2.04336323443438860.178997279438553310.185035944688353961.00919709070525572013.51523827019923.00678224901781552011.80131195436252014.8080942033803
4000709002291269.83512411344606-29.20616352447980.182825831051080720.209350365068154124620.17770004272461460.02894973754882812519.489749908447266460.036399841308593754.090870144734149-8.0594731583940720.204463511521890520.262062125296961931.2930500270273292013.51523827019923.00678224901781552011.80131195436252014.8080942033803
4000709002292269.7964913295107-29.206187344833110.304911023972265270.2678449677785108624720.83639907836914470.0223999023437520.088300704956055470.02230072021484375-1.7001866534338244-5.9639674627591590.148141617998445470.19205176816533741.96717614892876542013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709002293269.7872745304419-29.2062578288523371.3518855043600481.046061418947137824625.99174976348877460.085249900817871124.204350471496582460.05684947967529297-2.290436263458843-9.5968385596236270.7793734808164730.64853540325800878.5180455742088712013.320615015201611.3719145413717642003.43617966200852014.8080942033803
4000709002294269.80888716219647-29.2061891896260021.41345961187521031.251804780286295324725.465349197387695460.0810499191284179723.27630043029785470.0321006774902343754.381302303073221-4.7018558763948480.47844287930018571.02193637753253526.4696545651479532013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709002295269.8234425365187-29.2061884736616260.355978575621609231.587710441067255823624.13195037841797360.0494003295898437523.0174503326416360.0381002426147460944.48015296877619-8.0009851082285050.50708762440657380.72865533809519864.1411578720269952013.17425026376711.2987153728356782003.43617966200852014.7348950348442
..................................................................
4000946339500269.6899686412092-29.276978451867841.75817441277581680.935409107408077421023.770350456237793100.0608997344970703122.6496000289917100.037400245666503906-4.433870501660679-1.67011670319295422.29307144543402861.37664593465365684.2984304123552942013.90004365082272.19134921116230432012.49901610545182014.6903653166141
4000946380565269.71004704275265-29.2583186194187231.43372735707951641.47165523030859921123.99720001220703110.0373001098632812522.51849937438965110.0200004577636718751.6111158133637464-6.7456632868311521.96316916518413591.7202803635641434.4095240844353392013.90025407658032.30944127475487142012.49901610545182014.8084573802066
4000946404892269.67530078168915-29.2471627342426751.37639069491067261.613389460139535321224.929399490356445120.0292005538940429723.21535015106201120.06190013885498047-4.240018447223827-5.3013959214746952.32404892866457272.46465178107854675.0340409696458412013.37253173202112.04586304942736242012.3890313766822014.4348944261094
4000946417296269.7016328152704-29.2460704665937433.1308309826369583.18514411287760721125.600500106811523110.2341995239257812524.028099060058594110.25039863586425780.3265864932598421-6.4913946479921566.3967154596976412.57826528259230478.8294470986630282013.77311224404482.019486200362752012.67087911625122014.6903653166141
4000949430259269.722986295747-29.211971120172651.3619639637737381.15890561289665531524.502249717712402140.0661497116088867223.928850173950195140.0568504333496093754.745787093281551-3.41492243483594750.98752439816221490.60066867391504575.0810874604947742004.5674490817626.2125723619169572004.143782912162010.356355274077
4000949692413269.847657491686-29.2134644371428682.36780346719586682.022459781954067321024.422550201416016100.1117000579833984422.581549644470215100.02095031738281251.6834992526734194-14.4904675061560653.47406421445087954.4926563980115825.9461131883186352013.9553403396031.50985393087614852013.29824027250422014.8080942033803
4000949719295269.8230388680129-29.200721201818856.92562390115529252.4988461075181621025.977850914001465100.1077995300292968824.156999588012695100.03194999694824219-0.009307948981069264-9.2555808485828021.85811783298020821.524192442646531415.4735455528271032012.470060074062510.7687844081356622003.43617966200852014.2049640701443
4000979902333269.804403240861-29.1928132654553962.38599567764471271.39284851594804221025.71024990081787100.0653505325317382824.112099647521973100.054700851440429690.7550276872362829-4.77459070250673453.62576861309534771.4617815676884975.0650346984665922013.65899151197162.53086655097392082012.20402848387042014.7348950348442
4000979908546269.8156665822647-29.1898545163315260.91437485936164812.123819200708503721225.4466495513916120.1591005325317382823.336549758911133120.06319999694824219-7.2055855532918205-9.6832928336088782.6182646869419673.07248080976638835.2462673095450552013.83403361107031.60174311365878672013.20635108972152014.8080942033803
4000980227788269.7998513044728-29.197077719265191.84948598148885651.599149165537078421224.400450706481934120.1038999557495117222.93809986114502120.020649909973144530.15278595605010709-7.1721525185359610.6919345570902570.493731637979113745.76197440994000852012.656872142421411.3719145413717642003.43617966200852014.8080942033803

Properties of Full Catalog

Sky Coverage

In [4]:
x = tab['RA']
y = tab['Dec']

pylab.rcParams.update({'font.size': 16})
pylab.figure(1,(12,10))
pylab.scatter(x, y, s=1)
pylab.autoscale(tight=True)
pylab.xlabel('RA')
pylab.ylabel('Dec')
dc=0.01
pylab.xlim(min(x)-dc, max(x)+dc)
pylab.ylim(min(y)-dc, max(y)+dc)
pylab.gca().invert_xaxis()
pylab.text(0.5,0.93,'{:,} stars in SWEEPS'.format(len(x)),
       horizontalalignment='left',
       transform=pylab.gca().transAxes)
Out[4]:
Text(0.5, 0.93, '443,932 stars in SWEEPS')

Proper Motion Histograms

Proper motion histograms for lon and lat

In [5]:
bin = 0.2
hrange = (-20,20)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1
pylab.rcParams.update({'font.size': 16})
pylab.figure(1,(12,10))
pylab.hist(tab['lpm'], range=hrange, bins=bincount, label='Longitude', 
           histtype='step', linewidth=2)
pylab.hist(tab['bpm'], range=hrange, bins=bincount, label='Latitude', 
           histtype='step', linewidth=2)
pylab.xlabel('Proper motion [mas/yr]')
pylab.ylabel('Number [in {:.2} mas bins]'.format(bin))
pylab.legend(loc='upper right')
pylab.autoscale(enable=True, axis='x', tight=True)
pylab.ylim(0,13500)
pylab.title('{:,} stars in SWEEPS'.format(len(tab)))
pylab.tight_layout()
pylab.savefig('{}sweeps_pmerr_hist.png'.format(resPath))

Proper motion error cumulative histogram for lon and lat

In [6]:
bin = 0.01
hrange = (0,2)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1
pylab.rcParams.update({'font.size': 16})
pylab.figure(1,(12,10))
pylab.hist(tab['lpmerr'], range=hrange, bins=bincount, label='Longitude Error', 
           histtype='step', cumulative=1, linewidth=2)
pylab.hist(tab['bpmerr'], range=hrange, bins=bincount, label='Latitude Error', 
           histtype='step', cumulative=1, linewidth=2)
pylab.xlabel('Proper motion error [mas/yr]')
pylab.ylabel('Cumulative number [in {:0.2} mas bins]'.format(bin))
pylab.legend(loc='upper right')
pylab.autoscale(enable=True, axis='x', tight=True)
pylab.ylim(0,500000)
pylab.title('{:,} stars in SWEEPS'.format(len(tab)))
pylab.tight_layout()
pylab.savefig('{}sweeps_pmerr_cumhist.png'.format(resPath))

Proper motion error log histogram for lon and lat

In [7]:
bin = 0.01
hrange = (0,6)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1
pylab.rcParams.update({'font.size': 16})
pylab.figure(1,(12,10))
pylab.hist(tab['lpmerr'], range=hrange, bins=bincount, label='Longitude Error', 
           histtype='step', linewidth=2)
pylab.hist(tab['bpmerr'], range=hrange, bins=bincount, label='Latitude Error', 
           histtype='step', linewidth=2)
pylab.xlabel('Proper motion error [mas/yr]')
pylab.ylabel('Number [in {:0.2} mas bins]'.format(bin))
pylab.legend(loc='upper right')
pylab.yscale('log')
pylab.autoscale(enable=True, axis='x', tight=True)
pylab.ylim(0,15000)
pylab.title('{:,} stars in SWEEPS'.format(len(tab)))
pylab.tight_layout()
pylab.savefig('{}sweeps_pmerr_loghist.png'.format(resPath))

Proper motion error as a function of dT

Exclude objects with dT near zero, and to improve the plotting add a bit of random noise to spread out the quanitized time values.

In [8]:
# restrict to sources with dT > 1 year
dtmin = 1.0
w = np.where(tab['dT']>dtmin)[0]
if ('rw' not in locals()) or len(rw) != len(w):
    rw = np.random.random(len(w))
x = np.array(tab['dT'][w]) + 0.5*(rw-0.5)
y = np.log(np.array(tab['lpmerr'][w]))

# Calculate the point density
t0 = time.time()
myPDF,axes = fastKDE.pdf(x,y,numPoints=2**9+1)
print("kde took {:.1f} sec".format(time.time()-t0))

# interpolate to get z values at points
finterp = RectBivariateSpline(axes[1],axes[0],myPDF)
z = finterp(y,x,grid=False)

# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
xs, ys, zs = x[idx], y[idx], z[idx]

# select a random subset of points in the most crowded regions to speed up plotting
wran = np.where(np.random.random(len(zs))*zs<0.05)[0]
print("Plotting {} of {} points".format(len(wran),len(zs)))
xs = xs[wran]
ys = ys[wran]
zs = zs[wran]

pylab.rcParams.update({'font.size': 16})
pylab.figure(1,(12,10))
pylab.yscale('log')
pylab.scatter(xs, np.exp(ys), c=zs, s=2, edgecolor='', cmap='plasma', 
              label='Longitude PM error')
pylab.autoscale(tight=True, axis='y')
pylab.xlim(0.0, max(x)*1.05)
pylab.xlabel('Date range [yr]')
pylab.ylabel('Proper motion error [mas/yr]')
pylab.legend(loc='best')
pylab.title('{:,} stars in SWEEPS'.format(len(tab)))
pylab.colorbar()
pylab.tight_layout()
# pylab.savefig('{}sweeps_pmerr_vs_dt.png'.format(resPath))
kde took 4.3 sec
Plotting 178182 of 442682 points

Proper motion error log histogram for lon and lat

Divide sample into points with $<6$ years of data and points with more than 6 years of data.

In [9]:
bin = 0.01
hrange = (0,6)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1

tsplit = 6
dmaglim = 0.05

pylab.rcParams.update({'font.size': 16})
pylab.figure(1,(12,12))
pylab.subplot(211)
wmag = np.where((tab['a_f606w_mad']<dmaglim) & (tab['a_f814w_mad']<dmaglim))[0]
w = wmag[tab['dT'][wmag]<=tsplit]
pylab.hist(tab['lpmerr'][w], range=hrange, bins=bincount, label='Longitude Error', 
           histtype='step', linewidth=2)
pylab.hist(tab['bpmerr'][w], range=hrange, bins=bincount, label='Latitude Error', 
           histtype='step', linewidth=2)
pylab.xlabel('Proper motion error [mas/yr]')
pylab.ylabel('Number [in {:0.2} mas bins]'.format(bin))
pylab.legend(loc='upper right')
pylab.yscale('log')
pylab.autoscale(enable=True, axis='x', tight=True)
pylab.ylim(0,15000)
pylab.title('{:,} stars in SWEEPS with dT < {} yrs, dmag < {}'.format(len(w),tsplit,dmaglim))
pylab.tight_layout()

pylab.subplot(212)
w = wmag[tab['dT'][wmag]>tsplit]
pylab.hist(tab['lpmerr'][w], range=hrange, bins=bincount, label='Longitude Error', 
           histtype='step', linewidth=2)
pylab.hist(tab['bpmerr'][w], range=hrange, bins=bincount, label='Latitude Error', 
           histtype='step', linewidth=2)
pylab.xlabel('Proper motion error [mas/yr]')
pylab.ylabel('Number [in {:0.2} mas bins]'.format(bin))
pylab.legend(loc='upper right')
pylab.yscale('log')
pylab.autoscale(enable=True, axis='x', tight=True)
pylab.ylim(0,15000)
pylab.title('{:,} stars in SWEEPS with dT > {} yrs, dmag < {}'.format(len(w),tsplit,dmaglim))
pylab.tight_layout()

pylab.savefig('{}sweeps_pmerr_loghist2.png'.format(resPath))