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¶

  • Intialization
  • Properties of Full Catalog
    • Sky Coverage
    • Proper Motion Distributions
    • Visit Distribution
    • Time Coverage Distributions
    • Magnitude Distributions
    • Color Magnitude Diagram
    • Detection Positions
  • Good Photometric Objects
  • Science Applications
    • Proper Motions on the CMD
    • Proper Motions in Bulge Versus Disk
    • White Dwarfs
    • QSO Candidates
    • High Proper Motion Objects
    • HLA Cutout Images for Selected Objects

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
conda install pillow
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, time, sys, os, requests
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

from PIL import Image
from io import BytesIO

# 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)
26.2 s: Retrieved 157.86MB table MyDB.SWEEPS
35.6 s: Converted to 443932 row table
Out[3]:
Table length=443932
ObjIDRADecRAerrDecerrNumFiltersNumVisitsa_f606wa_f606w_na_f606w_mada_f814wa_f814w_na_f814w_madbpmlpmbpmerrlpmerrpmdevyrdTyrStartyrEnd
int64float64float64float64float64int32int32float64int32float64float64int32float64float64float64float64float64float64float64float64float64float64
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
4000709002296269.8288659917366-29.2061883313426270.39579456040561920.568720892374067224724.883499145507812470.0534000396728515623.122600555419922470.02719879150390625-4.005807625507199-6.5588263182465570.235406290571774060.340674205756104963.46896633623448422013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709002297269.83003885466655-29.2061904198919960.313070788295750360.2545495594934844624621.571399688720703460.0218000411987304720.795000076293945460.027649879455566406-0.8725751200872276-7.5085460405162530.435135895394770770.208555078768050241.87553183921704172013.51523827019923.00678224901781552011.80131195436252014.8080942033803
..................................................................
4000937456444269.76701171186426-29.2307814869144561.5801529928810231.665855064943876821124.251300811767578110.02369880676269531223.03260040283203110.027099609375-3.5849521715767922-9.3554425535373052.030434886938051.74176942488094945.3581283080737622013.86471096136482.2340810435016442012.57419473213422014.8082757756358
4000941127104269.7541169187084-29.19255243173842415.9439178908170055.28823046580772521325.18440055847168130.0660991668701171924.42060089111328130.07610130310058594-1769.42979628392642184.89905234349041928.32368852195331914.965872171469541.4397341929387152004.15294145978920.0175091894821587032004.143782912162004.1612921016422
4000941133220269.7226622209822-29.1897739931455471.7813631746709361.79732580954235721023.586899757385254100.01385021209716796922.529250144958496100.03670024871826172-262.66535678489396-109.42569661510447381.1594930877206165.398057636290675.9204437361438952004.1536298462520.017168194235319722004.14486056057562004.1620287548108
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']

plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.scatter(x, y, s=1)
plt.autoscale(tight=True)
plt.xlabel('RA')
plt.ylabel('Dec')
dc=0.01
plt.xlim(min(x)-dc, max(x)+dc)
plt.ylim(min(y)-dc, max(y)+dc)
plt.gca().invert_xaxis()
plt.text(0.5,0.93,'{:,} stars in SWEEPS'.format(len(x)),
       horizontalalignment='left',
       transform=plt.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
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.hist(tab['lpm'], range=hrange, bins=bincount, label='Longitude', 
           histtype='step', linewidth=2)
plt.hist(tab['bpm'], range=hrange, bins=bincount, label='Latitude', 
           histtype='step', linewidth=2)
plt.xlabel('Proper motion [mas/yr]')
plt.ylabel('Number [in {:.2} mas bins]'.format(bin))
plt.legend(loc='upper right')
plt.autoscale(enable=True, axis='x', tight=True)
plt.ylim(0,13500)
plt.title('{:,} stars in SWEEPS'.format(len(tab)))
plt.tight_layout()
plt.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
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.hist(tab['lpmerr'], range=hrange, bins=bincount, label='Longitude Error', 
           histtype='step', cumulative=1, linewidth=2)
plt.hist(tab['bpmerr'], range=hrange, bins=bincount, label='Latitude Error', 
           histtype='step', cumulative=1, linewidth=2)
plt.xlabel('Proper motion error [mas/yr]')
plt.ylabel('Cumulative number [in {:0.2} mas bins]'.format(bin))
plt.legend(loc='upper right')
plt.autoscale(enable=True, axis='x', tight=True)
plt.ylim(0,500000)
plt.title('{:,} stars in SWEEPS'.format(len(tab)))
plt.tight_layout()
plt.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
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.hist(tab['lpmerr'], range=hrange, bins=bincount, label='Longitude Error', 
           histtype='step', linewidth=2)
plt.hist(tab['bpmerr'], range=hrange, bins=bincount, label='Latitude Error', 
           histtype='step', linewidth=2)
plt.xlabel('Proper motion error [mas/yr]')
plt.ylabel('Number [in {:0.2} mas bins]'.format(bin))
plt.legend(loc='upper right')
plt.yscale('log')
plt.autoscale(enable=True, axis='x', tight=True)
plt.ylim(0,15000)
plt.title('{:,} stars in SWEEPS'.format(len(tab)))
plt.tight_layout()
plt.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]

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

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

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

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

Number of Visits Histogram ¶

In [10]:
bin = 1
hrange = (0,130)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.hist(tab['NumVisits'], range=hrange, bins=bincount, label='Number of visits ', 
           histtype='step', linewidth=2)
plt.xlabel('Number of visits')
plt.ylabel('Number of objects')
plt.autoscale(enable=True, axis='x', tight=True)
plt.ylim(0,200000)
plt.title('{:,} stars in SWEEPS'.format(len(tab)))
plt.tight_layout()
plt.savefig('{}sweeps_numvisits_hist.png'.format(resPath))

Time Histograms ¶

First plot histogram of observation dates.

In [11]:
bin = 1
hrange = (2000, 2020)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.hist(tab['yr'], range=hrange, bins=bincount, label='year ', histtype='step', linewidth=2)
plt.xlabel('mean detection epoch (year)')
plt.ylabel('Number of objects')
plt.autoscale(enable=True, axis='x', tight=True)
plt.ylim(0,300000)
plt.title('{:,} stars in SWEEPS'.format(len(tab)))
plt.tight_layout()
plt.savefig('{}sweeps_year_hist.png'.format(resPath))

Then plot histogram of observation duration for the objects.

In [12]:
bin = 0.25
hrange = (0, 15)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.hist(tab['dT'], range=hrange, bins=bincount, label='year ', histtype='step', linewidth=2)
plt.xlabel('time span (years)')
plt.ylabel('Number of objects')
plt.autoscale(enable=True, axis='x', tight=True)
plt.yscale('log')
plt.title('{:,} stars in SWEEPS'.format(len(tab)))
plt.tight_layout()
plt.savefig('{}sweeps_year_hist.png'.format(resPath))

Magnitude Histograms ¶

Aper2 magnitude histograms for F606W and F814W¶

In [13]:
bin = 0.025
hrange = (16,28)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.hist(tab['a_f606w'], range=hrange, bins=bincount, label='F606W', 
           histtype='step',  linewidth=2)
plt.hist(tab['a_f814w'], range=hrange, bins=bincount, label='F814W', 
           histtype='step', linewidth=2)
plt.xlabel('magnitude')
plt.ylabel('Number of stars[in {:0.2} magnitude bins]'.format(bin))
plt.legend(loc='upper right')
plt.autoscale(enable=True, axis='x', tight=True)
plt.title('{:,} stars in SWEEPS'.format(len(tab)))
plt.tight_layout()
plt.savefig('{}sweeps_mag_hist.png'.format(resPath))

Aper2 magnitude error histograms for F606W and F814W¶

In [14]:
bin = 0.001
hrange = (0,0.2)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.hist(tab['a_f606w_mad'], range=hrange, bins=bincount, label='F606W', 
           histtype='step',  linewidth=2)
plt.hist(tab['a_f814w_mad'], range=hrange, bins=bincount, label='F814W', 
           histtype='step', linewidth=2)
plt.xlabel('magnitude error (median absolute deviation)')
plt.ylabel('Number of stars[in {:0.2} magnitude bins]'.format(bin))
plt.legend(loc='upper right')
plt.autoscale(enable=True, axis='x', tight=True)
plt.ylim(0,15000)
plt.title('{:,} stars in SWEEPS'.format(len(tab)))
plt.tight_layout()
plt.savefig('{}sweeps_magerr_hist.png'.format(resPath))

Color-Magnitude Diagram ¶

Color-magnitude diagram¶

Plot the color-magnitude diagram for the ~440k points retrieved from the database. This uses fastkde to compute the kernel density estimate for the crowded plot, which is very fast. See https://pypi.org/project/fastkde/ for instructions -- or just do

pip install fastkde
In [15]:
f606w = tab['a_f606w']
f814w = tab['a_f814w']
RminusI = f606w-f814w

# Calculate the point density
w = np.where((RminusI > -1) & (RminusI < 4))[0]
x = np.array(RminusI[w])
y = np.array(f606w[w])
t0 = time.time()
myPDF,axes = fastKDE.pdf(x,y,numPoints=2**10+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]

plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.scatter(xs, ys, c=zs, s=2, edgecolor='none', cmap='plasma')
plt.autoscale(tight=True)
plt.xlabel('A_F606W - A_F814W')
plt.ylabel('A_F606W')
plt.gca().invert_yaxis()
plt.xlim(-1,4)
plt.ylim(27.5,17.5)
plt.colorbar()
plt.text(.93,.93,'{:,} stars in SWEEPS'.format(len(x)),
       horizontalalignment='right',
       transform=plt.gca().transAxes)
plt.savefig("{}sweeps_colormag1.png".format(resPath))
kde took 4.1 sec
Plotting 147230 of 443502 points

Detection Positions ¶

Define a function to plot the PM fit for an object.

In [16]:
# define function
def positions(Obj, jobs=None):
    """
    input parameter Obj is the value of the ObjID 
    optional jobs parameter re-uses casjobs jobs variable
    output plots change in (lon, lat) as a function of time
    overplots proper motion fit
    provides number of objects and magnitude/color information
    """
    if not jobs:
        jobs = mastcasjobs.MastCasJobs(context=HSCContext)

    # execute these as "system" queries so they don't fill up your Casjobs history

    # get the measured positions as a function of time
    query = """SELECT dT, dLon, dLat 
        from AstromSourcePositions where ObjID={}
        order by dT
        """.format(Obj)
    pos = jobs.quick(query, context=HSCContext, task_name="SWEEPS/Microlensing",
                     astropy=True, system=True)
    
    # get the PM fit parameters
    query = """SELECT pmlon, pmlonerr, pmlat, pmlaterr
        from AstromProperMotions where ObjID={}
        """.format(Obj)
    pm = jobs.quick(query, context=HSCContext, task_name="SWEEPS/Microlensing",
                    astropy=True, system=True)
    
    lpm = pm['pmlon'][0]
    bpm = pm['pmlat'][0]
    
    # get the intercept for the proper motion fit referenced to the start time
    # time between mean epoch and zero (ref) epoch (years)

    # get median magnitudes and colors for labeling
    query = """SELECT a_f606w=i1.MagMed, a_f606_m_f814w=i1.MagMed-i2.MagMed
        from AstromSumMagAper2 i1 
        join AstromSumMagAper2 i2 on i1.ObjID=i2.ObjID 
        where i1.ObjID={} and i1.filter='f606w' and i2.filter='f814w' 
        """.format(Obj)
    phot = jobs.quick(query, context=HSCContext, task_name="SWEEPS/Microlensing",
                      astropy=True, system=True)
    f606w = phot['a_f606w'][0]
    f606wmf814w = phot['a_f606_m_f814w'][0]

    x = pos['dT']
    y = pos['dLon']
    plt.rcParams.update({'font.size':10})
    plt.figure(1,(6,3))
    plt.subplot(121)
    plt.scatter(x, y, s=10)
    # xpm = np.linspace(0, max(x), 10)
    xpm = np.array([x.min(),x.max()])
    ypm = lpm*xpm
    plt.plot(xpm, ypm, '-r')
    plt.xlabel('dT (yrs)')
    plt.ylabel('dLon (mas)')
    y = pos['dLat']
    plt.subplot(122)
    plt.scatter(x, y, s=10)
    ypm = bpm*xpm
    plt.plot(xpm, ypm, '-r')
    plt.xlabel('dT (yrs)')
    plt.ylabel('dLat (mas)')
    plt.suptitle("""ObjID {0}
{1} detections,  (lpm, bpm) = ({2:.1f}, {3:.1f}) mas/yr
(f606w, f606w-f814w) = ({4:.1f}, {5:.1f})""".format(Obj, len(x), lpm, bpm, f606w, f606wmf814w),
                  size=10)
    plt.tight_layout(rect=[0, 0.0, 1, 0.88])
    plt.show()
    plt.close()

Plot positions of objects that are detected in more than 90 visits with a median absolute deviation from the fit of less than 1.5 mas and proper motion error less than 1.0 mas/yr.¶

In [17]:
n = tab['NumVisits']
dev = tab['pmdev']
objid = tab['ObjID']
lpmerr0 = np.array(tab['lpmerr'])
bpmerr0 = np.array(tab['bpmerr'])
wi = np.where( (dev < 1.5) & (n > 90) & (np.sqrt(bpmerr0**2+lpmerr0**2) < 1.0))[0]
print("Plotting {} objects".format(len(wi)))
for o in objid[wi]:
    positions(o, jobs=jobs)
Plotting 21 objects

Good Photometric Objects ¶

Look at photometric error distribution to pick out good photometry objects as a function of magnitude ¶

The photometric error is mainly a function of magnitude. We make a cut slightly above the typical error to exclude objects that have poor photometry. (In the SWEEPS field, that most often is the result of blending and crowding.)

In [18]:
f606w = tab['a_f606w']
f814w = tab['a_f814w']
RminusI = f606w-f814w

w = np.where((RminusI > -1) & (RminusI < 4))[0]
f606w_mad = tab['a_f606w_mad']
f814w_mad = tab['a_f814w_mad']

t0=time.time()
# Calculate the point density
x1 = np.array(f606w[w])
y1 = np.array(f606w_mad[w])
y1log = np.log(y1)
myPDF1,axes1 = fastKDE.pdf(x1,y1log,numPoints=2**10+1)
finterp = RectBivariateSpline(axes1[1],axes1[0],myPDF1)
z1 = finterp(y1log,x1,grid=False)
# Sort the points by density, so that the densest points are plotted last
idx = z1.argsort()
xs1, ys1, zs1 = x1[idx], y1[idx], z1[idx]

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

x2 = np.array(f814w[w])
y2 = np.array(f814w_mad[w])
y2log = np.log(y2)
myPDF2,axes2 = fastKDE.pdf(x2,y2log,numPoints=2**10+1)
finterp = RectBivariateSpline(axes2[1],axes2[0],myPDF2)
z2 = finterp(y2log,x2,grid=False)
idx = z2.argsort()
xs2, ys2, zs2 = x2[idx], y2[idx], z2[idx]
print("{:.1f} s: completed kde".format(time.time()-t0))

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

xr = (18,27)
xx = np.arange(501)*(xr[1]-xr[0])/500.0 + xr[0]
xcut1 = 24.2
xnorm1 = 0.03
xcut2 = 23.0
xnorm2 = 0.03

# only plot a subset of the points to speed things up
qsel = 3
xs1 = xs1[::qsel]
ys1 = ys1[::qsel]
zs1 = zs1[::qsel]
xs2 = xs2[::qsel]
ys2 = ys2[::qsel]
zs2 = zs2[::qsel]

plt.figure(1,(15,8))
plt.subplot(121)
plt.yscale('log')
plt.scatter(xs1,ys1,c=zs1,s=2,edgecolor='none',cmap='plasma')
plt.autoscale(tight=True)
# overplot an error limit that varies with magnitude of the form listed below
plt.plot(xx,xnorm1 * (1. + 10.**(0.4*(xx-xcut1))),linewidth=2.0,
           label='$%.2f (1+10^{0.4(M-%.1f)})$' % (xnorm1,xcut1))
plt.legend(loc='upper left')
plt.xlabel('F606W')
plt.ylabel('F606W_MAD')

plt.subplot(122)
plt.yscale('log')
plt.scatter(xs2,ys2,c=zs2,s=2,edgecolor='none',cmap='plasma')
plt.autoscale(tight=True)
# overplot an error limit that varies with magnitude of the form listed below
plt.plot(xx,xnorm2 * (1. + 10.**(0.4*(xx-xcut2))),linewidth=2.0,
           label='$%.2f (1+10^{0.4(M-%.1f)})$' % (xnorm2,xcut2))
plt.legend(loc='upper left')
plt.xlabel('F814W')
plt.ylabel('F814W_MAD')
plt.tight_layout()
Plotting 274457 of 443502 points
8.5 s: completed kde
Plotting 250807 of 443502 points

Define function to apply noise cut and plot color-magnitude diagram with cut¶

Note that we reduce the R-I range to 0-3 here because there are very few objects left bluer than R-I = 0 or redder than R-I = 3.

In [19]:
def noisecut(tab, factor=1.0):
    """Return boolean array with noise cut in f606w and f814w using model
    factor is normalization factor to use (>1 means allow more noise)
    """
    f606w = tab['a_f606w']
    f814w = tab['a_f814w']
    f606w_mad = tab['a_f606w_mad']
    f814w_mad = tab['a_f814w_mad']
    
    # noise model computed above
    xcut_f606w = 24.2
    xnorm_f606w = 0.03 * factor
    xcut_f814w = 23.0
    xnorm_f814w = 0.03 * factor
    return ((f606w_mad < xnorm_f606w*(1+10.0**(0.4*(f606w-xcut_f606w))))
          & (f814w_mad < xnorm_f814w*(1+10.0**(0.4*(f814w-xcut_f814w))))
           )

# low-noise objects
good = noisecut(tab,factor=1.0)

# Calculate the point density
w = np.where((RminusI > 0) & (RminusI < 3) & good)[0]
x = np.array(RminusI[w])
y = np.array(f606w[w])
t0 = time.time()
myPDF,axes = fastKDE.pdf(x,y,numPoints=2**10+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.075)[0]
print("Plotting {} of {} points".format(len(wran),len(zs)))
xs = xs[wran]
ys = ys[wran]
zs = zs[wran]

plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.scatter(xs, ys, c=zs, s=2, edgecolor='none', cmap='plasma')
plt.xlabel('A_F606W - A_F814W')
plt.ylabel('A_F606W')
plt.gca().invert_yaxis()
plt.xlim(-1,4)
plt.ylim(27.5,17.5)
plt.colorbar()
plt.text(.93,.93,'{:,} stars in SWEEPS'.format(len(x)),
       horizontalalignment='right',
       transform=plt.gca().transAxes)
plt.savefig("{}sweeps_colormag2.png".format(resPath))
kde took 3.1 sec
Plotting 129892 of 333525 points

Science Applications ¶

Proper Motions of Good Objects ¶

Average proper motion in color-magnitude bins¶

In [20]:
# good defined above
f606w = tab['a_f606w']
f814w = tab['a_f814w']
RminusI = f606w-f814w
w = np.where((RminusI > 0) & (RminusI < 3) & good)[0]
lpm = np.array(tab['lpm'][w])
bpm = np.array(tab['bpm'][w])
x = np.array(RminusI[w])
y = np.array(f606w[w])

nbins = 50
count2d, yedge, xedge = np.histogram2d(y, x, bins=nbins)
lpm_sum = np.histogram2d(y, x, bins=nbins, weights=lpm-lpm.mean())[0]
bpm_sum = np.histogram2d(y, x, bins=nbins, weights=bpm-bpm.mean())[0]
lpm_sumsq = np.histogram2d(y, x, bins=nbins, weights=(lpm-lpm.mean())**2)[0]
bpm_sumsq = np.histogram2d(y, x, bins=nbins, weights=(bpm-bpm.mean())**2)[0]

ccount = count2d.clip(1) 
lpm_mean = lpm_sum/ccount
bpm_mean = bpm_sum/ccount
lpm_rms = np.sqrt(lpm_sumsq/ccount-lpm_mean**2)
bpm_rms = np.sqrt(bpm_sumsq/ccount-bpm_mean**2)
lpm_msigma = lpm_rms/np.sqrt(ccount)
bpm_msigma = bpm_rms/np.sqrt(ccount)

plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
ww = np.where(count2d > 100)
yy, xx = np.mgrid[:nbins,:nbins]
xx = (0.5*(xedge[1:]+xedge[:-1]))[xx]
yy = (0.5*(yedge[1:]+yedge[:-1]))[yy]
# plt.scatter(xs, ys, c=zs, s=2, edgecolor='none', cmap='plasma')
Q = plt.quiver(xx[ww],yy[ww],lpm_mean[ww],bpm_mean[ww],color='red',width=0.0015)
qlength = 5
plt.quiverkey(Q,0.8,0.97,qlength,'{} mas/yr'.format(qlength),coordinates='axes',labelpos='W')
plt.gca().invert_yaxis()
plt.autoscale(tight=True)
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[-1],yedge[0]))
plt.xlabel('A_F606W - A_F814W')
plt.ylabel('A_F606W')
plt.savefig('{}sweeps_vecmean.png'.format(resPath))

RMS in longitude PM as a function of color/magnitude¶

Mean longitude PM as image¶

In [21]:
plt.rcParams.update({'font.size': 16})
plt.figure(1,(20,6))

sub1 = plt.subplot(131)
plt.scatter(xs, ys, c=zs, s=2, edgecolor='none', cmap='plasma')
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[0],yedge[-1]))
plt.gca().invert_yaxis()
plt.xlabel('A_F606W - A_F814W')
plt.ylabel('A_F606W')
plt.text(0.97, 0.97,
       'Color-magnitude\n{:,} stars\nin SWEEPS'.format(len(x)),
       horizontalalignment='right', verticalalignment='top',
       transform=plt.gca().transAxes)
plt.colorbar()

sub2 = plt.subplot(132)
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[0],yedge[-1]))
mask = (lpm_msigma <= 1.0) & (count2d > 10)
im = (lpm_mean+lpm.mean())*mask
im[~mask] = np.nan
vmax = np.nanmax(np.abs(im))
plt.imshow(im,cmap='RdYlGn',aspect="auto",origin="lower",
            extent=(xedge[0],xedge[-1],yedge[0],yedge[-1]))
plt.gca().invert_yaxis()
plt.xlabel('A_F606W - A_F814W')
plt.text(0.97, 0.97,'Mean Longitude PM\n$\sigma(\mathrm{PM}) \leq 1$ and $N > 10$',
       horizontalalignment='right', verticalalignment='top',
       transform=plt.gca().transAxes)
cbar = plt.colorbar()
cbar.ax.set_ylabel('mas/yr', rotation=270)

sub2 = plt.subplot(133)
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[0],yedge[-1]))
im = lpm_rms*(count2d>10)
plt.imshow(im,cmap='magma',aspect="auto",origin="lower",
            extent=(xedge[0],xedge[-1],yedge[0],yedge[-1]),
            norm=LogNorm(vmin=im[im>0].min(), vmax=im.max()))
plt.gca().invert_yaxis()
plt.xlabel('A_F606W - A_F814W')
plt.text(0.97, 0.97,'RMS in Longitude PM\nN > 10',
       horizontalalignment='right', verticalalignment='top',
       transform=plt.gca().transAxes)
cbar = plt.colorbar()
cbar.ax.set_ylabel('mas/yr', rotation=270)

plt.tight_layout()
plt.savefig("{}sweeps_PMlon.png".format(resPath))

Mean latitude PM as image¶

In [22]:
plt.rcParams.update({'font.size': 16})
plt.figure(1,(20,6))

sub1 = plt.subplot(131)
plt.scatter(xs, ys, c=zs, s=2, edgecolor='none', cmap='plasma')
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[0],yedge[-1]))
plt.gca().invert_yaxis()
plt.xlabel('A_F606W - A_F814W')
plt.ylabel('A_F606W')
plt.text(0.97,0.97,
       'Color-magnitude\n{:,} stars\nin SWEEPS'.format(len(x)),
       horizontalalignment='right', verticalalignment='top',
       transform=plt.gca().transAxes)
plt.colorbar()

sub2 = plt.subplot(132)
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[0],yedge[-1]))
mask = (bpm_msigma <= 1.0) & (count2d > 10)
im = (bpm_mean+bpm.mean())*mask
im[~mask] = np.nan
vmax = np.nanmax(np.abs(im))
plt.imshow(im,cmap='RdYlGn',aspect="auto",origin="lower",
            extent=(xedge[0],xedge[-1],yedge[0],yedge[-1]))
plt.gca().invert_yaxis()
plt.xlabel('A_F606W - A_F814W')
plt.text(.97,.97,'Mean Latitude PM\n$\sigma(\mathrm{PM}) \leq 1$ and $N > 10$',
       horizontalalignment='right', verticalalignment='top',
       transform=plt.gca().transAxes)
cbar = plt.colorbar()
cbar.ax.set_ylabel('mas/yr', rotation=270)

sub2 = plt.subplot(133)
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[0],yedge[-1]))
im = bpm_rms*(count2d>10)
plt.imshow(im,cmap='magma',aspect="auto",origin="lower",
            extent=(xedge[0],xedge[-1],yedge[0],yedge[-1]),
            norm=LogNorm(vmin=im[im>0].min(), vmax=im.max()))
plt.gca().invert_yaxis()
plt.xlabel('A_F606W - A_F814W')
plt.text(.97,.97,'RMS in Latitude PM\nN > 10',
       horizontalalignment='right', verticalalignment='top',
       transform=plt.gca().transAxes)
cbar = plt.colorbar()
cbar.ax.set_ylabel('mas/yr', rotation=270)

plt.tight_layout()
plt.savefig("{}sweeps_PMlat.png".format(resPath))

Proper Motions in Bulge and Disk ¶

Fit a smooth function to the main ridgeline of color-magnitude diagram¶

Fit the R-I vs R values, but force the function to increase montonically with R. We use a log transform of the y coordinate to help.

In [23]:
# locate ridge line
iridgex = np.argmax(myPDF,axis=1)
pdfx = myPDF[np.arange(len(iridgex),dtype=int),iridgex]
# pdfx = myPDF.max(axis=1)
wx = np.where(pdfx > 0.1)[0]
iridgex = iridgex[wx]
# use weighted sum of 2*hw+1 points around peak
hw = 10
pridgex = 0.0
pdenom = 0.0
for k in range(-hw,hw+1):
    wt = myPDF[wx,iridgex+k]
    pridgex = pridgex + k*wt
    pdenom = pdenom + wt
pridgex = iridgex + pridgex/pdenom
ridgex = np.interp(pridgex, np.arange(len(axes[0])), axes[0])

# Fit the data using a polynomial model
x0 = axes[1][wx].min()
x1 = axes[1][wx].max()
p_init = models.Polynomial1D(9)
fit_p = fitting.LinearLSQFitter()
xx = (axes[1][wx]-x0)/(x1-x0)
yoff = 0.65
yy = np.log(ridgex - yoff)
p = fit_p(p_init, xx, yy)

# define useful functions for the ridge line

def ridge_color(f606w, function=p, yoff=yoff, x0=x0, x1=x1):
    """Return R-I position of ridge line as a function of f606w magnitude
    
    function, yoff, x0, x1 are from polynomial fit above
    """
    return yoff + np.exp(p((f606w-x0)/(x1-x0)))

# calculate grid of function values for approximate inversion
rxgrid = axes[1][wx]
rygrid = ridge_color(rxgrid)
color_domain = [rygrid[0],rygrid[-1]]
mag_domain = [axes[1][wx[0]], axes[1][wx[-1]]]
print("color_domain {}".format(color_domain))
print("mag_domain   {}".format(mag_domain))

def ridge_mag(RminusI, xgrid=rxgrid, ygrid=rygrid):
    """Return f606w position of ridge line as a function of R-I color
    
    Uses simple linear interpolation to get approximate value
    """
    f606w = np.interp(RminusI,ygrid,xgrid)
    f606w[(RminusI < ygrid[0]) | (RminusI > ygrid[-1])] = np.nan
    return f606w
color_domain [0.6883374859498668, 2.156051675823446]
mag_domain   [19.356585323810577, 26.480549454689026]

Plot the results to check that they look reasonable.

In [24]:
ridgexf = yoff + np.exp(p(xx))

plt.figure(1,(12,6))
plt.subplot(121)
plt.plot(axes[1][wx], ridgex, 'bo')
plt.plot(axes[1][wx], ridgexf, color='red')
plt.ylabel('R-I')
plt.xlabel('R')

# check the derivative plot to see if it stays positive
deriv = np.exp(p(xx))*models.Polynomial1D.horner(xx, 
                            (p.parameters * np.arange(len(p.parameters)))[1:])
plt.subplot(122)
plt.semilogy(axes[1][wx], np.exp(p(xx))*models.Polynomial1D.horner(xx, 
                            (p.parameters * np.arange(len(p.parameters)))[1:]),color='red')
plt.xlabel('R')
plt.ylabel('Fit derivative')
plt.title('Min deriv {:.6f}'.format(deriv.min()))
plt.tight_layout()

Plot the ridgeline on the CMD¶

In [25]:
plt.rcParams.update({'font.size': 16})
plt.figure(1,(12,10))
plt.scatter(xs, ys, c=zs, s=2, edgecolor='none', cmap='plasma')
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[0],yedge[-1]))
plt.gca().invert_yaxis()

# overplot ridge line
plt.plot(ridge_color(axes[1][wx]), axes[1][wx], color='red')
plt.plot(axes[0], ridge_mag(axes[0]), color='green')

plt.xlabel('A_F606W - A_F814W')
plt.ylabel('A_F606W')
plt.text(.97,.97,
       'Color-magnitude\n{:,} stars\nin SWEEPS'.format(len(x)),
       horizontalalignment='right', verticalalignment='top',
       transform=plt.gca().transAxes)
plt.colorbar()
# plt.savefig('{}sweeps_ridgeline.png'.format(resPath))
Out[25]:
<matplotlib.colorbar.Colorbar at 0x7f8ef8541e20>

Binned distribution of PM(Long) vs magnitude offset from ridge line¶

In [26]:
yloc = ridge_mag(x)
x1 = x[np.isfinite(yloc)]
wy = np.where((axes[0] >= x1.min()) & (axes[0] <= x1.max()))[0]
ridgey = ridge_mag(axes[0][wy])

# Weighted histogram
dmagmin = -2.0
dmagmax = 1.0
xmax = axes[0][wy[-1]]
# xmin = axes[0][wy[0]]
xmin = 1.0
wsel = np.where((y-yloc >= dmagmin) & (y-yloc <= dmagmax) & (x >= xmin) & (x <= xmax))[0]

x2 = y[wsel]-yloc[wsel]
y2 = lpm[wsel]-lpm.mean()
hrange = (dmagmin, dmagmax)
hbins = 50
count1d, xedge1d = np.histogram(x2,range=hrange,bins=hbins)
lpm_sum1d = np.histogram(x2,range=hrange,bins=hbins,weights=y2)[0]
lpm_sumsq1d = np.histogram(x2,range=hrange,bins=hbins,weights=y2**2)[0]

ccount1d = count1d.clip(1)
lpm_mean1d = lpm_sum1d/ccount1d
lpm_rms1d = np.sqrt(lpm_sumsq1d/ccount1d-lpm_mean1d**2)
lpm_msigma1d = lpm_rms1d/np.sqrt(ccount1d)
lpm_mean1d += lpm.mean()

x1d = 0.5*(xedge1d[1:]+xedge1d[:-1])

plt.rcParams.update({'font.size': 16})
plt.figure(1,(14,6))

sub1 = plt.subplot(121)
plt.scatter(xs, ys, c=zs, s=2, edgecolor='none', cmap='plasma')
plt.xlim((xedge[0],xedge[-1]))
plt.ylim((yedge[0],yedge[-1]))
plt.gca().invert_yaxis()
plt.xlabel('R - I (A_F606W - A_F814W)')
plt.ylabel('R (A_F606W)')
plt.text(.97,.97,
       'Color-magnitude\n{:,} stars\nin SWEEPS'.format(len(x)),
       horizontalalignment='right', verticalalignment='top',
       transform=plt.gca().transAxes)
xboundary = np.hstack((axes[0][wy],axes[0][wy[::-1]]))
yboundary = np.hstack((ridgey+dmagmax,ridgey[::-1]+dmagmin))
wb = np.where((xboundary >= xmin) & (xboundary <= xmax))
xboundary = xboundary[wb]
yboundary = yboundary[wb]
print(xboundary[0],yboundary[0],xboundary[-1],yboundary[-1])
print(xboundary.shape,yboundary.shape)
xboundary = np.append(xboundary,xboundary[0])
yboundary = np.append(yboundary,yboundary[0])
plt.plot(xboundary, yboundary, color='red')

sub1 = plt.subplot(122)
# don't plot huge error points
wp = np.where(lpm_msigma1d < 1)
plt.errorbar(x1d[wp], lpm_mean1d[wp], xerr=(xedge1d[1]-xedge1d[0])/2.0, 
               yerr=lpm_msigma1d[wp], linestyle='')
plt.autoscale(tight=True)
plt.xlabel('Distance from ridge line [R mag]')
plt.ylabel('Mean Longitude PM [mas/yr]')
plt.gca().invert_xaxis()
plt.text(.03,.97,'{:,} stars in SWEEPS\n1-sigma error bars on mean PM'.format(len(x2)),
       horizontalalignment='left', verticalalignment='top',
       transform=plt.gca().transAxes)
plt.tight_layout()
1.0020693112164736 23.784969024110666 1.0020693112164736 20.784969024110666
(394,) (394,)

Reproduce Figure 1 from Calamida et al. 2014¶

In [27]:
w = np.where((RminusI > 0) & (RminusI < 3) & good)[0]

# Calculate the point density
x = np.array(RminusI[w])
y = np.array(f606w[w])
myPDF,axes = fastKDE.pdf(x,y,numPoints=2**10+1)
finterp = RectBivariateSpline(axes[1],axes[0],myPDF)
z = finterp(y,x,grid=False)
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.1)[0]
print("Plotting {} of {} points".format(len(wran),len(zs)))
xs = xs[wran]
ys = ys[wran]
zs = zs[wran]

# locate ridge line in magnitude as a function of color
xloc = ridge_color(y)
ridgex = ridge_color(axes[1][wx])

# locate ridge line in color as function of magnitude
yloc = ridge_mag(x)
x1 = x[np.isfinite(yloc)]
wy = np.where((axes[0] >= x1.min()) & (axes[0] <= x1.max()))[0]
ridgey = ridge_mag(axes[0][wy])

# low-noise objects
print("Selected {:,} low-noise objects".format(len(w)))

# red objects
ylim = yloc - 1.5 - (yloc - 25.0).clip(0)/(1+10.0**(-0.4*(yloc-26.0)))
wred = np.where((y<25) & (y > 19.5) & (y < ylim) & (x-xloc > 0.35))[0]
#wred = np.where((y<25) & (y > 19.5) & ((y-yloc) < -1.5)
#                   & (x-xloc > 0.3))[0]
#                   & (x > 1.1) & (x < 2.5) & (x-xloc > 0.2))[0]
print("Selected {:,} red objects".format(len(wred)))
# main sequence objects
wmain = np.where((y>21) & (y<22.4) & (np.abs(x-xloc) < 0.1))[0]
print("Initially selected {:,} MS objects".format(len(wmain)))
# sort by distance from ridge and select the closest
wmain = wmain[np.argsort(np.abs(x[wmain]-xloc[wmain]))]
wmain = wmain[:len(wred)]
print("Selected {:,} MS objects closest to ridge".format(len(wmain)))

plt.rcParams.update({'font.size': 14})

plt.figure(1,(12,8))
plt.subplot2grid((2,3), (0,0), rowspan=2, colspan=2)
plt.scatter(xs,ys,c=zs,s=2,cmap='plasma',edgecolor='none')
plt.scatter(x[wred],y[wred],c='red',s=2,edgecolor='none')
plt.scatter(x[wmain],y[wmain],c='blue',s=2,edgecolor='none')
plt.xlim(0,3)
plt.ylim(18,27.5)
plt.xlabel('F606W-F814W [mag]')
plt.ylabel('F606W [mag]')
plt.gca().invert_yaxis()
plt.title('{:,} stars in SWEEPS'.format(len(x)))

lrange = (-20,5)
brange = (-12.5,12.5)

# plot MS and red points in random order
wsel = w[np.append(wmain,wred)]
colors = np.array(['blue']*len(wsel))
colors[len(wmain):] = 'red'
irs = np.argsort(np.random.random(len(wsel)))
wsel = wsel[irs]
colors = colors[irs]

plt.subplot2grid((2,3), (0,2), rowspan=1, colspan=1)
plt.scatter(tab['lpm'][w],tab['bpm'][w],c='darkgray',s=0.1)
plt.scatter(tab['lpm'][wsel],tab['bpm'][wsel],c=colors,s=2)
plt.xlim(*lrange)
plt.ylim(*brange)
plt.ylabel('Latitude PM [mas/yr]')

plt.subplot2grid((2,3), (1,2), rowspan=1, colspan=1)
bin = 0.5
bincount = int((lrange[1]-lrange[0])/bin + 0.5) + 1
plt.hist(tab['lpm'][w[wmain]], range=lrange, bins=bincount, label='MS', color='blue', 
           histtype='step')
plt.hist(tab['lpm'][w[wred]], range=lrange, bins=bincount, label='Red', color='red', 
           histtype='step')
plt.xlim(*lrange)
plt.xlabel('Longitude PM [mas/yr]')
plt.ylabel('Number [in {:.2} mas bins]'.format(bin))
plt.legend(loc='upper left')
plt.tight_layout()
plt.savefig('{}sweeps_calamida.png'.format(resPath))
Plotting 156351 of 333525 points
Selected 333,525 low-noise objects
Selected 2,797 red objects
Initially selected 59,605 MS objects
Selected 2,797 MS objects closest to ridge