Hubble Source Catalog SWEEPS Proper Motion (CasJobs Version)

Contents

Hubble Source Catalog SWEEPS Proper Motion (CasJobs Version)#

2019 - 2022, Steve Lubow, Rick White, Trenton McKinney#

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.

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#

  1. This notebook requires the use of Python 3.

  2. Modules can be installed with conda, if using the Anaconda distribution of python, or with pip.

    • If you are using conda, do not install / update / remove a module with pip, that exists in a conda channel.

    • If a module is not available with conda, then it’s okay to install it with pip

  3. Install mastcasjobs and casjobs with pip:

pip install mastcasjobs

Set up your CasJobs account information#

You must have a MAST Casjobs account. 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.

import astropy
import time
import sys
import os
import requests
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.colors import LogNorm
from pathlib import Path

# 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 packaging.version import Version 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

from PIL import Image
from io import BytesIO

## 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 width for pprint
astropy.conf.max_width = 150
/tmp/ipykernel_1949/609964975.py:14: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
  from pkg_resources import get_distribution
# set universal matplotlib parameters
plt.rcParams.update({'font.size': 16})
HSCContext = "HSCv3"

Set up Casjobs environment.

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.

DBtable = "SWEEPS"
jobs = mastcasjobs.MastCasJobs(context="MyDB")

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

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

    # get main information
    query = f"""
        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.{DBtable}
        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
    """

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

    # slower version using CasJobs output queue
    # tab = jobs.get_table(DBtable, verbose=False)
    
    # fast version using special MAST Casjobs service
    tab = jobs.fast_table(DBtable, verbose=True)
Retrieving table MyDB.SWEEPS (if it exists)
11.5 s: Retrieved 157.86MB table MyDB.SWEEPS
17.8 s: Converted to 443932 row table
tab
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
..................................................................
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 #

fig, ax = plt.subplots(figsize=(12, 10))
ax.scatter('RA', 'Dec', data=tab, s=1, alpha=0.1)
ax.set(xlabel='RA', ylabel='Dec', title=f'{len(tab)} stars in SWEEPS')
ax.invert_xaxis()
../../../_images/856fb7caf05e1d345f6a685c34b3461e62460935c6884f24131bf882cffeb2f5.png

Proper Motion Histograms #

Proper motion histograms for lon and lat#

bin = 0.2
hrange = (-20, 20)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1

fig, ax = plt.subplots(figsize=(12, 10))
for col, label in zip(['lpm', 'bpm'], ['Longitude', 'Latitude']):
    ax.hist(col, data=tab, range=hrange, bins=bincount, label=label, histtype='step', linewidth=2)
ax.set(xlabel='Proper motion [mas/yr]', ylabel=f'Number [in {bin:.2} mas bins]', title=f'{len(tab):,} stars in SWEEPS')
_ = ax.legend()
../../../_images/ee861f65e8cc88337c9bd0707a300e9106115fe7dd8afa631f46e3826460bfc9.png

Proper motion error cumulative histogram for lon and lat#

bin = 0.01
hrange = (0, 2)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1

fig, ax = plt.subplots(figsize=(12, 10))
for col, label in zip(['lpmerr', 'bpmerr'], ['Longitude Error', 'Latitude Error']):
    ax.hist(col, data=tab, range=hrange, bins=bincount, label=label, histtype='step', cumulative=1, linewidth=2)
ax.set(xlabel='Proper motion error [mas/yr]', ylabel=f'Cumulative number [in {bin:0.2} mas bins]', title=f'{len(tab):,} stars in SWEEPS')
_ = ax.legend(loc='upper left')
../../../_images/9786fe355e6cc6c9db13c40f7b34b017f613eefac1ba97bedd7c4a898c5a492e.png

Proper motion error log histogram for lon and lat#

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

fig, ax = plt.subplots(figsize=(12, 10))
for col, label in zip(['lpmerr', 'bpmerr'], ['Longitude Error', 'Latitude Error']):
    ax.hist(col, data=tab, range=hrange, bins=bincount, label=label, histtype='step', linewidth=2)
ax.set(xlabel='Proper motion error [mas/yr]', ylabel=f'Number [in {bin:0.2} mas bins]', title=f'{len(tab):,} stars in SWEEPS', yscale='log')
_ = ax.legend(loc='upper right')
../../../_images/3f60ffc08de710f1614dc648a17f52a7fd5f99b0ae0bbe16063a3a2319a43d0b.png

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.

# 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.flatten(), y.flatten(), 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]
kde took 1.5 sec
Plotting 170054 of 442682 points
fig, ax = plt.subplots(figsize=(12, 10))
sc = ax.scatter(xs, np.exp(ys), c=zs, s=2, edgecolors='none', cmap='plasma')
ax.set(xlabel='Date range [yr]', ylabel='Proper motion error [mas/yr]',
       title=f'{len(tab):,} stars in SWEEPS\nLongitude PM error', yscale='log')
_ = fig.colorbar(sc, ax=ax)
../../../_images/2b7fbb5cae46a920f54c2d669aa6addefdf28c97fda3918c7b44b5e2c219c29d.png

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.

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

tsplit = 6
dmaglim = 0.05

wmag = np.where((tab['a_f606w_mad'] < dmaglim) & (tab['a_f814w_mad'] < dmaglim))[0]
w1 = wmag[tab['dT'][wmag] <= tsplit]
w2 = wmag[tab['dT'][wmag] > tsplit]
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(12, 12), sharey=True, tight_layout=True)

for ax, w in zip([ax1, ax2], [w1, w2]):
    for col, label in zip(['lpmerr', 'bpmerr'], ['Longitude Error', 'Latitude Error']):
        data = tab[w]
        ax.hist(col, data=data, range=hrange, bins=bincount, label=label, histtype='step', linewidth=2)
        
ax1.set(xlabel='Proper motion error [mas/yr]', ylabel=f'Number [in {bin:0.2} mas bins]',
        title=f'{len(w1):,} stars in SWEEPS with dT < {tsplit} yrs, dmag < {dmaglim}', yscale='log')
ax2.set(xlabel='Proper motion error [mas/yr]', ylabel=f'Number [in {bin:0.2} mas bins]',
        title=f'{len(w2):,} stars in SWEEPS with dT > {tsplit} yrs, dmag < {dmaglim}', yscale='log')

ax1.legend()
ax2.legend()
<matplotlib.legend.Legend at 0x7f5f84547190>
../../../_images/06782c29326b0e94b156f3e2c544a8a8e20ceb999af6f81ae16cc2f6abdeddc3.png

Number of Visits Histogram #

bin = 1
hrange = (0, 130)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1

fig, ax = plt.subplots(figsize=(12, 10))
ax.hist('NumVisits', data=tab, range=hrange, bins=bincount, label='Number of visits ', histtype='step', linewidth=2)
ax.set(xlabel='Number of visits', ylabel='Number of objects', title=f'{len(tab):,} stars in SWEEPS')
_ = ax.margins(x=0)
../../../_images/4cbc0d41d9106bc7b1aa8594a0867ae9f90fd3097805a307e8159c0a39e2fa9f.png

Time Histograms #

First plot histogram of observation dates.

bin = 1
hrange = (2000, 2020)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1

fig, ax = plt.subplots(figsize=(12, 10))
ax.hist('yr', data=tab, range=hrange, bins=bincount, label='year ', histtype='step', linewidth=2)
ax.set(xlabel='mean detection epoch (year)', ylabel='Number of objects', title=f'{len(tab):,} stars in SWEEPS')
ax.set_xticks(ticks=range(2000, 2021, 2))
_ = ax.margins(x=0)
../../../_images/7ebb124a76660f83b3f2004b0c7143654470f9415ebc4409af218c35533a70dd.png

Then plot histogram of observation duration for the objects.

bin = 0.25
hrange = (0, 15)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1

fig, ax = plt.subplots(figsize=(12, 10))
ax.hist('dT', data=tab, range=hrange, bins=bincount, label='year ', histtype='step', linewidth=2)
_ = ax.set(xlabel='time span (years)', ylabel='Number of objects', title=f'{len(tab):,} stars in SWEEPS', yscale='log')
../../../_images/9c143da7873f9c269559dbdcd4245951e4e89acc9406b8e06fba498478f15003.png

Magnitude Histograms #

Aper2 magnitude histograms for F606W and F814W#

bin = 0.025
hrange = (16, 28)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1

fig, ax = plt.subplots(figsize=(12, 10))
for col, label in zip(['a_f606w', 'a_f814w'], ['F606W', 'F814W']):
    ax.hist(col, data=tab, range=hrange, bins=bincount, label=label, histtype='step', linewidth=2)
ax.set(xlabel='magnitude', ylabel=f'Number [in {bin:0.2} mas bins]', title=f'{len(tab):,} stars in SWEEPS')
_ = ax.legend(loc='upper right')
../../../_images/a0ffc71500ea17b5681d3d387e5872bfac538c15e2bd5c9fb60e0fd9b60f8c65.png

Aper2 magnitude error histograms for F606W and F814W#

bin = 0.001
hrange = (0, 0.2)
bincount = int((hrange[1]-hrange[0])/bin + 0.5) + 1

fig, ax = plt.subplots(figsize=(12, 10))
for col, label in zip(['a_f606w_mad', 'a_f814w_mad'], ['F606W', 'F814W']):
    ax.hist(col, data=tab, range=hrange, bins=bincount, label=label, histtype='step', linewidth=2)
ax.set(xlabel='magnitude error (median absolute deviation)', ylabel=f'Number of stars[in {bin:0.2} magnitude bins]',
       title=f'{len(tab):,} stars in SWEEPS')
_ = ax.legend(loc='upper right')
../../../_images/85ed05aead7851b3ae1ed10573672a6e8e13cdb8f85500dfa66a7cf1a757a1aa.png

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

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(f"Plotting {len(wran)} of {len(zs)} points")
xs = xs[wran]
ys = ys[wran]
zs = zs[wran]
kde took 1.8 sec
Plotting 147179 of 443502 points
fig, ax = plt.subplots(figsize=(12, 10))
sc = ax.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')
ax.set(xlabel='A_F606W - A_F814W', ylabel='A_F606W', title=f'{len(x):,} stars in SWEEPS')
ax.invert_yaxis()
fig.colorbar(sc, ax=ax)
<matplotlib.colorbar.Colorbar at 0x7f5fada8ab90>
../../../_images/0403caaa119e68f4343d7f03817deef6c5cc0356bf9eca5cb6be605f2b0850c6.png

Detection Positions #

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

# 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 = f"""SELECT dT, dLon, dLat 
        from AstromSourcePositions where ObjID={Obj}
        order by dT
        """
    pos = jobs.quick(query, context=HSCContext, task_name="SWEEPS/Microlensing", astropy=True, system=True)
    
    # get the PM fit parameters
    query = f"""SELECT pmlon, pmlonerr, pmlat, pmlaterr
        from AstromProperMotions where ObjID={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 = f"""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={Obj} and i1.filter='f606w' and i2.filter='f814w' 
        """
    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']
    # xpm = np.linspace(0, max(x), 10)
    xpm = np.array([x.min(), x.max()])
        
    y1 = pos['dLon']
    ypm1 = lpm*xpm
    
    y2 = pos['dLat']
    ypm2 = bpm*xpm

    # plot figure
    fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3), tight_layout=True)
    
    ax1.scatter(x, y1, s=10)
    ax1.plot(xpm, ypm1, '-r')
    
    ax2.scatter(x, y2, s=10)
    ax2.plot(xpm, ypm2, '-r')
    
    ax1.set_xlabel('dT (yrs)', fontsize=10)
    ax1.set_ylabel('dLon (mas)', fontsize=10)
    ax2.set_xlabel('dT (yrs)', fontsize=10)
    ax2.set_ylabel('dLat (mas)', fontsize=10)
    
    fig.suptitle(f"ObjID {Obj}"
                 f"\n{len(x)} detections, (lpm, bpm) = ({lpm:.1f}, {bpm:.1f}) mas/yr"
                 f"\n(f606w, f606w-f814w) = ({f606w:.1f}, {f606wmf814w:.1f})", size=10)
    
    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.

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(f"Plotting {len(wi)} objects")
for o in objid[wi]:
    positions(o, jobs=jobs)
Plotting 21 objects
../../../_images/8978fd29eba1d05c11ce0270d0778766c52d7894091da1269d49f445b7618110.png ../../../_images/435741efa266658a1a6a31fe571b5ca35e266c31070c63d60a6ccde9c94fc371.png ../../../_images/4ae2f22b2b97e40d8255a6d24ed7c2ffee2d416ac09f479c07ef29adae61296a.png ../../../_images/98f34e7fdd95c35cba7d70c0e7dfc95886a01606f785d54133b9e5a1e969ffb8.png ../../../_images/87dafe77e2ba7c91d82817c694df38b6c834841491d4e36e51a1c0c65642e978.png ../../../_images/8f341f8002a8a7d56b81720e8b6ecc75a9a42e3f85cd3f0c970eb8fa898f3ea5.png ../../../_images/8be3839d81bc84b3a049be77a177d9029a45085f1d14e0f3384cf2c0e6322a35.png ../../../_images/9bf1faf89f1e39fa21668bf5df43f9b0de2efc35d5b443b7bff19ddf4676d71d.png ../../../_images/c46fa765cd084b7f98aee83d26162169872872abcd1a12abf42321e5fba08a6f.png ../../../_images/2ae58b7d763c666cdeedaea9911ec590a3c9a5ad4ee212a6d14955615d979012.png ../../../_images/46d5cd8f7df3a3b0ac52d34f461ad26980e352061d970b18af1960e7179f0ce2.png ../../../_images/c48876df80652a2a25018f47e3f3e39ee30532805d2cb863e613cfed3171287e.png ../../../_images/2cb4c244e16a4bb800393a427eecb75bab9f24a54cf8aa370908828a0f7c33de.png ../../../_images/79328bd0b89498ee376bbcf5648acd042074ebcceaf9d3efdc79a759f51498de.png ../../../_images/7a36bbe46f0dda65e8f5c308a370e97c759cd23618cf5f8724299ec8a5eeefcd.png ../../../_images/4095d56dda29ccae4f2661fdeb48e015eaceb05f9646cf949fd4e3e95eed5041.png ../../../_images/09a2321591d3d03cedc921d0298349d149d2f9c1ff1c9acf33053d78e13e9ced.png ../../../_images/078cfee9495a357e940cc58655a85be3d0952126355ce625cc05b799f7e64732.png ../../../_images/bfcaee68942a6950fe91da1a22a9774973550b12335929ddb294645e4980eebd.png ../../../_images/763968e39152d14d5c48c752bdede25144d6f19933c7e9dbf0483a69e140be6d.png ../../../_images/c46c6335f87548b291274e8253423bd94c41f9efc2237f6b35325954e587d6c9.png

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.)

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(f"Plotting {len(wran)} of {len(zs1)} points")
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(f"{(time.time()-t0):.1f} s: completed kde")

# 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(f"Plotting {len(wran)} of {len(zs2)} points")
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]
Plotting 274795 of 443502 points
4.4 s: completed kde
Plotting 250596 of 443502 points
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(15, 8), tight_layout=True)

ax1.scatter(xs1, ys1, c=zs1, s=2, edgecolors='none', cmap='plasma')
ax1.plot(xx, xnorm1 * (1. + 10.**(0.4*(xx-xcut1))), linewidth=2.0,
         label=f'${xnorm1:.2f} (1+10^{{0.4(M-{xcut1:.1f})}})$')

ax2.scatter(xs2, ys2, c=zs2, s=2, edgecolors='none', cmap='plasma')
ax2.plot(xx, xnorm2 * (1. + 10.**(0.4*(xx-xcut2))), linewidth=2.0,
         label=f'${xnorm2:.2f} (1+10^{{0.4(M-{xcut2:.1f})}})$')

ax1.legend(loc='upper left')
ax2.legend(loc='upper left')

ax1.set(xlabel='F606W', ylabel='F606W_MAD', yscale='log')
ax2.set(xlabel='F814W', ylabel='F814W_MAD', yscale='log')
[Text(0.5, 0, 'F814W'), Text(0, 0.5, 'F814W_MAD'), None]
../../../_images/285034c35bc1080d6c5cb8f792d5ae42fcfa4ebdb3bc058ed9f8e7cb322b57a9.png

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.

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(f"kde took {(time.time()-t0):.1f} sec")

# 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(f"Plotting {len(wran)} of {len(zs)} points")
xs = xs[wran]
ys = ys[wran]
zs = zs[wran]
kde took 1.5 sec
Plotting 129817 of 333525 points
fig, ax = plt.subplots(figsize=(12, 10))

sc = ax.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')
ax.set(xlabel='A_F606W - A_F814W', ylabel='A_F606W',
       title=f'{len(x):,} stars in SWEEPS', xlim=(-1, 4), ylim=(27.5, 17.5))
_ = fig.colorbar(sc, ax=ax)
../../../_images/09780043fb17da24ebb5a0fd74de2a7c8ac61fab2aa03c696ba62f0371ba9890.png

Science Applications #

Proper Motions of Good Objects #

Average proper motion in color-magnitude bins#

# 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)

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]
fig, ax = plt.subplots(figsize=(12, 10))

Q = ax.quiver(xx[ww], yy[ww], lpm_mean[ww], bpm_mean[ww], color='red', width=0.0015)
qlength = 5
ax.quiverkey(Q, 0.8, 0.97, qlength, f'{qlength} mas/yr', coordinates='axes', labelpos='W')
ax.invert_yaxis()
_ = ax.set(xlabel='A_F606W - A_F814W', ylabel='A_F606W',
           xlim=(xedge[0], xedge[-1]), ylim=(yedge[-1], yedge[0]))
../../../_images/ca1f92eb8258339cb0049097be68d82df1018730cad496f87e5f507159816517.png

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

Mean longitude PM as image#

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(20, 6), tight_layout=True, sharey=True)

# plot ax1
p1 = ax1.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')
ax1.set(xlabel='A_F606W - A_F814W', ylabel='A_F606W',
        title=f'Color-magnitude\n{len(x):,} stars in SWEEPS')
ax1.set(xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax1.invert_yaxis()
fig.colorbar(p1, ax=ax1)

# plot ax2
mask = (lpm_msigma <= 1.0) & (count2d > 10)
im2 = (lpm_mean+lpm.mean())*mask
im2[~mask] = np.nan
vmax = np.nanmax(np.abs(im2))

p2 = ax2.imshow(im2, cmap='RdYlGn', aspect="auto", origin="lower",
                extent=(xedge[0], xedge[-1], yedge[0], yedge[-1]))
ax2.set(xlabel='A_F606W - A_F814W',
        title='Mean Longitude PM\n$\\sigma(\\mathrm{PM}) \\leq 1$ and $N > 10$')
ax2.set(xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax2.invert_yaxis()
cb2 = fig.colorbar(p2, ax=ax2)
cb2.ax.set_ylabel('mas/yr', rotation=270, labelpad=15)

# plat ax3
im3 = lpm_rms*(count2d > 10)

p3 = ax3.imshow(im3, cmap='magma', aspect="auto", origin="lower",
                extent=(xedge[0], xedge[-1], yedge[0], yedge[-1]),
                norm=LogNorm(vmin=im3[im3 > 0].min(), vmax=im3.max()))
ax3.set(xlabel='A_F606W - A_F814W',
        title='RMS in Longitude PM\nN > 10')
ax3.set(xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax3.invert_yaxis()
cb3 = fig.colorbar(p3, ax=ax3)
_ = cb3.ax.set_ylabel('mas/yr', rotation=270)
../../../_images/77ca44a254ecf0d62bd55b1d659afecd00360a4041c1eb55b2c90bca0888b53a.png

Mean latitude PM as image#

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(20, 6), tight_layout=True, sharey=True)

# plot ax1
p1 = ax1.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')
ax1.set(xlabel='A_F606W - A_F814W', ylabel='A_F606W',
        title=f'Color-magnitude\n{len(x):,} stars in SWEEPS')
ax1.set(xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax1.invert_yaxis()
fig.colorbar(p1, ax=ax1)

# plot ax2
mask = (bpm_msigma <= 1.0) & (count2d > 10)
im2 = (bpm_mean+bpm.mean())*mask
im2[~mask] = np.nan
vmax = np.nanmax(np.abs(im2))

p2 = ax2.imshow(im2, cmap='RdYlGn', aspect="auto", origin="lower",
                extent=(xedge[0], xedge[-1], yedge[0], yedge[-1]))
ax2.set(xlabel='A_F606W - A_F814W',
        title='Mean Latitude PM\n$\\sigma(\\mathrm{PM}) \\leq 1$ and $N > 10$')
ax2.set(xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax2.invert_yaxis()
cb2 = fig.colorbar(p2, ax=ax2)
cb2.ax.set_ylabel('mas/yr', rotation=270, labelpad=15)

# plot ax3
im3 = bpm_rms*(count2d > 10)

p3 = ax3.imshow(im3, cmap='magma', aspect="auto", origin="lower",
                extent=(xedge[0], xedge[-1], yedge[0], yedge[-1]),
                norm=LogNorm(vmin=im3[im3 > 0].min(), vmax=im3.max()))
ax3.set(xlabel='A_F606W - A_F814W',
        title='RMS in Latitude PM\nN > 10')
ax3.set(xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax3.invert_yaxis()
cb3 = fig.colorbar(p3, ax=ax3)
_ = cb3.ax.set_ylabel('mas/yr', rotation=270)
../../../_images/1b75c4af86c3804048c399399fde04dd1ecd7af93eda74694ee897a902693e8e.png

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.

# 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(f"color_domain {color_domain}")
print(f"mag_domain   {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.156051675824816]
mag_domain   [19.356585323810577, 26.480549454689026]

Plot the results to check that they look reasonable.

ridgexf = yoff + np.exp(p(xx))

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12, 6), tight_layout=True)

ax1.plot(axes[1][wx], ridgex, 'bo')
ax1.plot(axes[1][wx], ridgexf, color='red')
ax1.set(xlabel='R', ylabel='R-I')

# 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:]))

ax2.semilogy(axes[1][wx], np.exp(p(xx)) *
             models.Polynomial1D.horner(xx, (p.parameters * np.arange(len(p.parameters)))[1:]), color='red')
_ = ax2.set(xlabel='R', ylabel='Fit derivative', title=f'Min deriv {deriv.min():.6f}')
../../../_images/e486a4c1edb76da12a76dfa80809d72db6145f9a0d533f0f9e69bc5cde48c5ad.png

Plot the ridgeline on the CMD#

fig, ax = plt.subplots(figsize=(12, 10))

sc = ax.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')

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

ax.set(xlabel='A_F606W - A_F814W', ylabel='A_F606W',
       title=f'Color-magnitude\n{len(x):,} stars in SWEEPS',
       xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax.invert_yaxis()
_ = fig.colorbar(sc, ax=ax)
../../../_images/b0c38067b76026df8fdff97635f9139d2bb680ba0cfabed8f8ab4d8e0fd5d43d.png

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

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])

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])

# don't plot huge error points
wp = np.where(lpm_msigma1d < 1)
1.0020693112164736 23.784969024110392 1.0020693112164736 20.784969024110392
(394,) (394,)
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(14, 7), tight_layout=True)

ax1.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')
ax1.plot(xboundary, yboundary, color='red')
ax1.set(xlabel='R - I (A_F606W - A_F814W)', ylabel='R (A_F606W)',
        title=f'Color-magnitude\n{len(x):,} stars in SWEEPS',
        xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax1.invert_yaxis()

ax2.errorbar(x1d[wp], lpm_mean1d[wp], xerr=(xedge1d[1]-xedge1d[0])/2.0, yerr=lpm_msigma1d[wp], linestyle='')
ax2.set(xlabel='Distance from ridge line [R mag]', ylabel='Mean Longitude PM [mas/yr]',
        title=f'{len(x2):,} stars in SWEEPS\n1-sigma error bars on mean PM')
ax2.invert_xaxis()
../../../_images/91a2fca58d5c11976c866193c89ab26e92638b670c24736c681b9dfb6c4e5cf4.png

Reproduce Figure 1 from Calamida et al. 2014#

image

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(f"Plotting {len(wran)} of {len(zs)} points")
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(f"Selected {len(w):,} low-noise objects")

# 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(f"Selected {len(wred):,} red objects")
# main sequence objects
wmain = np.where((y > 21) & (y < 22.4) & (np.abs(x-xloc) < 0.1))[0]
print(f"Initially selected {len(wmain):,} MS objects")
# sort by distance from ridge and select the closest
wmain = wmain[np.argsort(np.abs(x[wmain]-xloc[wmain]))]
wmain = wmain[:len(wred)]
print(f"Selected {len(wmain):,} MS objects closest to ridge")
Plotting 156294 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
fig = plt.figure(figsize=(12, 8), tight_layout=True)
gs = gridspec.GridSpec(2, 2, width_ratios=[2, 1])

ax1 = fig.add_subplot(gs[:, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 1])

# plot ax1
ax1.scatter(xs, ys, c=zs, s=2, cmap='plasma', edgecolors='none')
ax1.scatter(x[wred], y[wred], c='red', s=2, edgecolors='none')
ax1.scatter(x[wmain], y[wmain], c='blue', s=2, edgecolors='none')
ax1.set(xlabel='F606W-F814W [mag]', ylabel='F606W [mag]', title=f'{len(x):,} stars in SWEEPS',
        xlim=(0, 3), ylim=(18, 27.5))
ax1.invert_yaxis()

# plot ax2
lrange = (-20, 5)
brange = (-12.5, 12.5)

# 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]

masks = [w, wsel]
sizes = [0.1, 2]
colors2 = ['darkgray', colors]

for mask, color, size in zip(masks, colors2, sizes):
    ax2.scatter('lpm', 'bpm', data=tab[mask], c=color, s=size)

ax2.set(ylabel='Latitude PM [mas/yr]', xlim=lrange, ylim=brange)

# plot ax3
bins = 0.5
bincount = int((lrange[1]-lrange[0])/bins + 0.5) + 1

masks = [w[wmain], w[wred]]
labels = ['MS', 'Red']
colors = ['b', 'r']

for mask, label, color in zip(masks, labels, colors):
    ax3.hist('lpm', data=tab[mask], range=lrange, bins=bincount, label=label, color=color, histtype='step')

ax3.set(xlabel='Longitude PM [mas/yr]', ylabel=f'Number [in {bins:.2} mas bins]')
_ = ax3.legend(loc='upper left')
../../../_images/382b369c44af3a32b18888b26296ae58ce3d7bd6569ae6482e1693431260a6aa.png

Mean and median proper motions of bulge stars compared with SgrA*#

(-6.379 \(\pm\) 0.026, -0.202 \(\pm\) 0.019) mas/yr Reid and Brunthaler (2004)

lpmmain = np.mean(tab['lpm'][w[wmain]])
bpmmain = np.mean(tab['bpm'][w[wmain]])

norm = 1.0/np.sqrt(len(tab['lpm'][w[wmain]]))
print("Bulge stars mean PM longitude {:.2f} +- {:.3f} latitude {:.2f} +- {:.3f}".format(
    np.mean(tab['lpm'][w[wmain]]), norm*np.std(tab['lpm'][w[wmain]]),
    np.mean(tab['bpm'][w[wmain]]), norm*np.std(tab['bpm'][w[wmain]])
    ))

norm = 1.2533/np.sqrt(len(tab['lpm'][w[wmain]]))
print("Bulge stars median PM longitude {:.2f} +- {:.3f} latitude {:.2f} +- {:.3f}".format(
    np.median(tab['lpm'][w[wmain]]), norm*np.std(tab['lpm'][w[wmain]]),
    np.median(tab['bpm'][w[wmain]]), norm*np.std(tab['bpm'][w[wmain]])
    ))
Bulge stars mean PM longitude -6.31 +- 0.059 latitude -0.13 +- 0.053
Bulge stars median PM longitude -6.45 +- 0.074 latitude -0.13 +- 0.067

White Dwarfs #

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

wwd = np.where((RminusI < 0.7)
               & (RminusI > 0) 
               & (f606w > 22.5) 
               & good 
               & (tab['lpm'] < 5) 
               & (tab['lpm'] > -20))[0]
xwd = np.array(RminusI[wwd])
ywd = np.array(f606w[wwd])

# 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(f"Plotting {len(wran)} of {len(zs)} points")
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(f"Selected {len(w):,} low-noise objects")

# 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(f"Selected {len(wmain):,} MS objects closest to ridge")
Plotting 156438 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
fig = plt.figure(figsize=(12, 8), tight_layout=True)
gs = gridspec.GridSpec(2, 2, width_ratios=[2, 1])

ax1 = fig.add_subplot(gs[:, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 1])

# plot ax1
ax1.scatter(xs, ys, c=zs, s=2, cmap='plasma', edgecolors='none')
ax1.scatter(x[wred], y[wred], c='red', s=2, edgecolors='none')
ax1.scatter(x[wmain], y[wmain], c='blue', s=2, edgecolors='none')
ax1.scatter(xwd, ywd, c='green', s=10, edgecolors='none')
ax1.set(xlabel='F606W-F814W [mag]', ylabel='F606W [mag]',
        title=f'{len(x):,} stars in SWEEPS', xlim=(0, 3), ylim=(18, 27.5))
ax1.invert_yaxis()

# plot ax2
lrange = (-20, 5)
brange = (-12.5, 12.5)

# 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]

masks = [w, wsel, wwd]
sizes = [0.1, 2, 2]
colors2 = ['darkgray', colors, 'green']

for mask, color, size in zip(masks, colors2, sizes):
    ax2.scatter('lpm', 'bpm', data=tab[mask], c=color, s=size)

ax2.set(ylabel='Latitude PM [mas/yr]', xlim=lrange, ylim=brange)

# plot ax3
bins = 0.5
bincount = int((lrange[1]-lrange[0])/bins + 0.5) + 1

masks = [wwd, w[wmain], w[wred]]
labels = ['WD', 'MS', 'Red']
colors = ['g', 'b', 'r']

for mask, label, color in zip(masks, labels, colors):
    ax3.hist('lpm', data=tab[mask], range=lrange, bins=bincount, label=label, color=color, histtype='step')

ax3.set(xlabel='Longitude PM [mas/yr]', ylabel=f'Number [in {bins:.2} mas bins]')
_ = ax3.legend(loc='upper left')
../../../_images/78402e3bd6daf1f59dc6da35c2903566a297280b88851ad72fa581c8abdf5e01.png

White dwarf mean PM and uncertainity#

norm = 1.0/np.sqrt(len(tab['lpm'][wwd]))
print("WD PM mean +- stdev longitude {:.2f} +- {:.3f} latitude {:.2f} +- {:.3f}".format(
    np.mean(tab['lpm'][wwd]), norm*np.std(tab['lpm'][wwd]),
    np.mean(tab['bpm'][wwd]), norm*np.std(tab['bpm'][wwd])
    ))
WD PM mean +- stdev longitude -5.60 +- 0.152 latitude -0.03 +- 0.245

WDs generally closer to bulge (MS) PM distribution#

bins = 0.5
bincount = int((lrange[1]-lrange[0])/bins + 0.5) + 1

masks = [wwd, w[wmain], w[wred]]
labels = ['WD', 'MS', 'Red']
colors = ['g', 'b', 'r']

fig, ax = plt.subplots(figsize=(8, 6))

for mask, label, color in zip(masks, labels, colors):
    ax.hist('lpm', data=tab[mask], range=lrange, bins=bincount, label=label, color=color, histtype='step', density=True, cumulative=1)
    
ax.set(xlabel='Longitude PM [mas/yr]', ylabel='Cumulative fraction')
_ = ax.legend(loc='upper left')
../../../_images/74ec3b79860e886133f7621e39975521f26728493d93927fc7614600211e2ce5.png

Look for quasar candidates (low PM blue stars) #

Note this includes all objects, not just “good” objects with low mag noise, because quasars might be variable too.

wqso1 = np.where((RminusI < 0.5)
                 & (np.sqrt(tab['bpm']**2+tab['lpm']**2) < 1.0)
                 & (tab['NumFilters'] > 2))[0]
wqso1 = wqso1[np.argsort(f606w[wqso1])]
tab[wqso1]
Table length=14
ObjIDRADecRAerrDecerrNumFiltersNumVisitsa_f606wa_f606w_na_f606w_mada_f814wa_f814w_na_f814w_madbpmlpmbpmerrlpmerrpmdevyrdTyrStartyrEnd
int64float64float64float64float64int32int32float64int32float64float64int32float64float64float64float64float64float64float64float64float64float64
4000710313439269.74005171773325-29.1960324733696620.62659640476711190.8430363739939153139418.632399559020996740.0441493988037109418.75860023498535770.22760009765625-0.27295919570065810.09336852951614050.120074967796713130.193544431979997666.6645611028851392010.410458098704312.1389362929372312003.4367273590012015.5756636519384
4000710257520269.76634477578085-29.2233101667974570.70106072268639690.9635875312674559149618.71660041809082750.0379009246826171918.785300254821777740.45225048065185547-0.579616612423514-0.0041956748645314320.12862608053011320.226135156132128127.0797343733470172010.450586592934812.1389362929372312003.4367273590012015.5756636519384
4000710307965269.7417955221381-29.1985938594320160.92059357282046350.8518786138892231149418.73979949951172730.0638999938964843818.865349769592285760.200050354003906250.3782536664095988-0.36868955902233850.21250729952998930.173450479126670947.67323066072039952010.48587754622912.1389362929372312003.4367273590012015.5756636519384
4000710352240269.7337926320315-29.181394875452980.69463568140069660.906134226177322447918.78339958190918740.02304935455322265618.512550354003906740.27725028991699220.63371794604432230.297155837378090540.150632729427004340.200701984422958786.7381081223247512009.773737000133711.3711852081716672003.4367273590012014.8079125671727
4000710347699269.7783405856686-29.179119311166470.411557788323881730.484193362005322648118.839149475097656760.033950805664062518.898500442504883730.23670005798339844-0.116781003128475530.64992525647767450.0848778177748430.110360525762329693.79050728910901662009.760042142227111.3711852081716672003.4367273590012014.8079125671727
4000710305789269.7500895465239-29.1997069628762741.23779853402990740.9596173093379398139518.883800506591797760.01639938354492187518.647899627685547750.104499816894531250.76136088973964420.060728015679124810.144585196792062830.3078910876643928.6696086746168462010.451318818121812.1389362929372312003.4367273590012015.5756636519384
4000710287023269.73049137354224-29.2087865146858370.58867814142106730.8187862653505924139319.005799293518066700.1794986724853515619.03809928894043770.4453010559082031-0.027042326411294833-0.106561818017951920.113687594145356840.185473848934728326.0600193408506422010.409980814181812.1389362929372312003.4367273590012015.5756636519384
4000711198572269.7837898799627-29.1710583461873870.242890611463202840.378799458135692845620.384400367736816520.03075027465820312520.409199714660645540.018199920654296875-0.39276687371980523-0.26149912803296160.071572579772810260.069548523746184072.63978326440014982008.052253504512210.9976219052332842003.4367273590012014.4343492642342
4000711114267269.77699533206413-29.2130203399329034.241370555135963.939764673878310843523.104300498962402320.03829956054687523.02050018310547330.07789993286132812-0.8306962177406612-0.068584987281524040.92216223248728991.349666416366427418.9259942776495722005.554219435558512.1364001366899472003.4367273590012015.573127495691
4000710335454269.7613531455845-29.1872063610708647.4742973298759631.483136231049532837723.993050575256348760.0631999969482421924.481599807739258790.20109939575195312-0.54231856855157350.70604156118027321.46469300447186380.818374901008934844.5428643744239852009.979332637238311.3711852081716672003.4367273590012014.8079125671727
4000710273567269.7541240409338-29.215787960244744.7482141647964491.694094522863292437824.544499397277832760.0755500793457031224.190000534057617780.12094974517822266-0.06045787883823814-0.296998397160966930.93281897176258610.578092189093136828.4006901952327272009.689665799419811.3413992910292122003.4367273590012014.7781266500303
4000710273213269.762844233717-29.2159930735964582.84914127596411462.158951117635643535825.248699188232422570.07260131835937525.19580078125570.114398956298828120.58745325924043080.39619888781943280.57457023306250710.489268627804960217.0350228161346032008.657572905504111.3711852081716672003.4367273590012014.8079125671727
4000710327380269.7667196275462-29.1898039056530221.49756615770321074.658478945843615535325.343299865722656520.0939502716064453125.171499252319336350.27519989013671875-0.59257648522096910.35109846224308780.400360430563875550.96311017225164223.3949711231211242008.199840995264811.3413992910292122003.4367273590012014.7781266500303
4000710296308269.7744892710409-29.204392434039083.85543709725692542.264390319511768337825.49880027770996750.0967006683349609425.095499992370605780.112750053405761720.189753023786942140.171716606536581270.71736161335096080.644308755073237427.1842846412212932009.57501534738411.3717329051641372003.43617966200852014.8079125671727
fig, ax = plt.subplots(figsize=(10, 10))
ax.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')
ax.plot(RminusI[wqso1], f606w[wqso1], 'rs', markersize=10, fillstyle='none')
ax.set(xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]))
ax.set(xlabel='R - I (A_F606W - A_F814W)', ylabel='R (A_F606W)',
       title=f'{len(x):,} stars in SWEEPS\n{len(wqso1)} low PM blue stars with NumFilters$\\geq3$')
ax.invert_yaxis()
../../../_images/21a2b34c9caa6dbae6677bbed38ee3516ef5c235a171bc3fc8f7dbd09d6ebebc.png
objid = tab['ObjID']
print(f"Plotting {len(wqso1)} objects")
for o in objid[wqso1]:
    positions(o, jobs=jobs)
Plotting 14 objects
../../../_images/3f23911edf56155eaa5e26db4396393466c2e0e5edb8f3c253bea2fd737d81c0.png ../../../_images/ba6cc28273a8b9fae06055f178390265b86fc32eaecaea8ecc3bca3138d3462b.png ../../../_images/26be12c4e72686c964acc254768dc3b3076f7c09b7a69f756f3fd430bde04f4b.png ../../../_images/93560ea08babc3f1fb502d3a70e671647b1f07f3db751c457049ea14bfce4541.png ../../../_images/766ff3b776398ae5d991e2ee918206cb6bc31236556342a3d39d60e3fcb61697.png ../../../_images/9d13b73bf854ef36eec323854740d75a1a00ff7bc56834326d0967b9b9fa021e.png ../../../_images/2466f2ac3f16399749bee8675f8d98247ae7bf09e2147bdfb0ca55d7165aa8e3.png ../../../_images/f06391251c4294e8146c3d8f44b010947a08863c9b8afe3feedba2f8b00da1cc.png ../../../_images/361181eee5c845d7ad1a3efd9c67ebe8651f6f5b6625bf52005e3de9f21f884a.png ../../../_images/67c6541b2b44f19825303b983212360477b686a5c297e74537ee6e2c09cac065.png ../../../_images/a10b096da115bc73dfbfea38fe9ce327eee959bf250ef5d09940d22cd6b44a16.png ../../../_images/7859d510b3fb3afcc2d64679224940b1ba1ce5391cf052d3e793e3eebc6b2f34.png ../../../_images/e4b15034ba819f5c5fc4271a0c0c52a43f2a6bec893b7185a049ede57fe5298e.png ../../../_images/262b77abf625a3208f0bb3a75ab100784c804e2a4ad4e42e3d7972f6f2b9a63e.png

Try again with different criteria on proper motion fit quality#

wqso2 = np.where((RminusI < 0.5)
                 & (np.sqrt(tab['bpm']**2+tab['lpm']**2) < 2.0)
                 & (np.sqrt(tab['bpmerr']**2+tab['lpmerr']**2) < 2.0)
                 & (tab['pmdev'] < 4.0))[0]
wqso2 = wqso2[np.argsort(f606w[wqso2])]
tab[wqso2]
Table length=10
ObjIDRADecRAerrDecerrNumFiltersNumVisitsa_f606wa_f606w_na_f606w_mada_f814wa_f814w_na_f814w_madbpmlpmbpmerrlpmerrpmdevyrdTyrStartyrEnd
int64float64float64float64float64int32int32float64int32float64float64int32float64float64float64float64float64float64float64float64float64float64
4000710347699269.7783405856686-29.179119311166470.411557788323881730.484193362005322648118.839149475097656760.033950805664062518.898500442504883730.23670005798339844-0.116781003128475530.64992525647767450.0848778177748430.110360525762329693.79050728910901662009.760042142227111.3711852081716672003.4367273590012014.8079125671727
4000711253077269.6915378419676-29.240201450193220.47048817337398590.527016297536424224618.8927001953125450.01090049743652343818.636449813842773420.1782999038696289-1.7408991354864214-0.59470771026326410.36131623059721120.74823452127072992.96134036189064352013.50340094293923.006781202524872011.80167617768172014.8084573802066
4000711347522269.70065127433986-29.2320349526647440.458137394606503550.97255062095775424318.917999267578125430.02580070495605468818.648849487304688380.28500080108642580.5245222694829835-0.90253215714022780.53318792314672771.13299016246126933.73078094247710322013.46489691614353.006781202524872011.80167617768172014.8084573802066
4000709025473269.82873131529516-29.195122574848120.54113639375424790.692045030767130524618.92685031890869440.012649536132812518.75755023956299420.38874912261962890.8548976473145768-1.15783376955440320.28769067083577350.433552708535085933.4563402628410352013.31542570356511.3719145413717642003.43617966200852014.8080942033803
4000710279756269.7207706977463-29.2123085559488870.413744843922597470.4883003181612267127018.977749824523926540.02824974060058593818.614700317382812550.35890007019042970.033714894109117335-1.6007022288058330.090524207329567410.090737501394596063.6197013826943342009.67976228942312.1389362929372312003.4367273590012015.5756636519384
4000711345953269.71277619272627-29.231306080124010.47321918364871311.004685668423822324619.01865005493164460.01224994659423828118.701799392700195390.15010070800781250.349685603051353271.91399348040913870.72542488495716681.08618790828335833.7553155526457392013.50340094293923.006781202524872011.80167617768172014.8084573802066
4000709014231269.8069522092499-29.200219944064810.38345216597794820.54906701179173724719.06329917907715460.03770065307617187518.564849853515625460.0460500717163085941.0342947783087193-1.42792407655898760.155265468888894280.368898475427276552.00174138195950762013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000710326758269.75587447129374-29.1899951880466380.399232380202015570.37137690294128917139519.077000617980957760.02159976959228515619.024099349975586770.26650047302246094-1.1141957269870415-0.86749835590098590.099480220588749970.064240536257315773.0978789147166582010.451318818121512.1389362929372312003.4367273590012015.5756636519384
4000711198572269.7837898799627-29.1710583461873870.242890611463202840.378799458135692845620.384400367736816520.03075027465820312520.409199714660645540.018199920654296875-0.39276687371980523-0.26149912803296160.071572579772810260.069548523746184072.63978326440014982008.052253504512210.9976219052332842003.4367273590012014.4343492642342
4000724763944269.7747901164537-29.265234033836870.433776731714064060.447421664711086624622.25380039215088460.0594997406005859421.910449981689453460.0336999893188476561.1821223347200740.140849289910045030.59608815874312850.42645224887957963.36392085386135162013.5031453570163.006781709597822011.8014940660382014.8082757756358
fig, ax = plt.subplots(figsize=(10, 10))
ax.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')
ax.plot(RminusI[wqso2], f606w[wqso2], 'rs', markersize=10, fillstyle='none')
ax.set(xlabel='R - I (A_F606W - A_F814W)', ylabel='R (A_F606W)',
       xlim=(xedge[0], xedge[-1]), ylim=(yedge[0], yedge[-1]),
       title=f'{len(x):,} stars in SWEEPS\n{len(wqso2)} low PM blue stars\nwith NumFilters$\\geq3$')
ax.invert_yaxis()
../../../_images/b721f19aa178d8c065f87355d5732da549e58416a121175b4010cd69acc038b8.png
objid = tab['ObjID']
print(f"Plotting {len(wqso2)} objects")
for o in objid[wqso2]:
    positions(o, jobs=jobs)
Plotting 10 objects
../../../_images/766ff3b776398ae5d991e2ee918206cb6bc31236556342a3d39d60e3fcb61697.png ../../../_images/f5f2043c0978880b0a41b7af3b17015c076be337126d4218183588b8fdfac9a4.png ../../../_images/e8d8aff51aa9e6756edf8d6e59369435e561507598a45795a4a53d181edc6bc6.png ../../../_images/3b3f2b569ae63d0c429a129c749fddb971d3bbbce405e5229b0ece493ee92fca.png ../../../_images/11f32c770c0ff65c74c2c0a6216f4f0a67766f2dfbb7cf42319fdb08e19099e5.png ../../../_images/a4433952fb9e112465970ff6848aec8bf775429971179738676e9691eeb61293.png ../../../_images/756ef5495160ae34d26b006982ba795b505aebc198c1d6e1123419ca9d320abd.png ../../../_images/0a43245f6fbdbfea840948b588290f2170834d3dbeab6d67f60ec32ee0695bf5.png ../../../_images/f06391251c4294e8146c3d8f44b010947a08863c9b8afe3feedba2f8b00da1cc.png ../../../_images/923fd1c693f190f6495d5d908ae91acdaaf18111c6c445504ce6aa805dda84f3.png

High Proper Motion Objects #

Get a list of objects with high, accurately measured proper motions. Proper motions are measured relative to the main sequence sample (Galactic center approximately).

f606w = tab['a_f606w']
f814w = tab['a_f814w']
RminusI = f606w-f814w
lpm0 = np.array(tab['lpm'])
bpm0 = np.array(tab['bpm'])
lpmerr0 = np.array(tab['lpmerr'])
bpmerr0 = np.array(tab['bpmerr'])
pmtot0 = np.sqrt((bpm0-bpmmain)**2+(lpm0-lpmmain)**2)
pmerr0 = np.sqrt(bpmerr0**2+lpmerr0**2)

# sort samples by decreasing PM
wpml = np.where((pmtot0 > 12) & (pmtot0 < 15) & (pmerr0 < 1.0) & good)[0]
wpml = wpml[np.argsort(-pmtot0[wpml])]
xpml = np.array(RminusI[wpml])
ypml = np.array(f606w[wpml])

wpmh = np.where((pmtot0 > 15) & (pmerr0 < 1.0) & good)[0]
wpmh = wpmh[np.argsort(-pmtot0[wpmh])]
xpmh = np.array(RminusI[wpmh])
ypmh = np.array(f606w[wpmh])

# Calculate the point density
w = np.where((RminusI > -1) & (RminusI < 4) & 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(f"kde took {(time.time()-t0):.1f} sec")

# 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(f"Plotting {len(wran)} of {len(zs)} points")
xs = xs[wran]
ys = ys[wran]
zs = zs[wran]
kde took 1.4 sec
Plotting 99014 of 333743 points
fig, ax = plt.subplots(figsize=(12, 10))

ax.scatter(xs, ys, c=zs, s=2, edgecolors='none', cmap='plasma')
ax.scatter(xpml, ypml, s=40, c="green", marker="^", label='10 mas/yr < PM < 15 mas/yr')
ax.scatter(xpmh, ypmh, s=80, c="red", marker="^", label='15 mas/yr < PM')

ax.set(xlabel='A_F606W - A_F814W', ylabel='A_F606W',
       title=f'High proper motions relative to mean of main sequence sample (bulge)\n{len(x):,} stars in SWEEPS')

ax.invert_yaxis()
ax.legend()
<matplotlib.legend.Legend at 0x7f5fa9a69610>
../../../_images/cbc99f955405d0a142c88779eda0dc65d1118486b50ab1ef42269bcdb0404657.png
print(f"Plotting {len(wpmh)} objects")
for o in tab["ObjID"][wpmh]:
    positions(o, jobs=jobs)
Plotting 34 objects
../../../_images/5f9d80a12361ced64648ad40196038382daaf1141e1edb7102e21def7884b39e.png ../../../_images/c23c5ff53a96219a6c48c453f2241d12118e07797efba8c5e153480aac76a955.png ../../../_images/a855e66bfd86901b127b1abc08d81da9150614c9b49a5c561de0f636c993f17b.png ../../../_images/53dfe799a6eccd4cf35013309f9b21ae4fd595ce253b7cf99522cbcd1577aee7.png ../../../_images/961834158db85b41156f3491c3ea35837afd6bc988b5429a19e245d71518cfaa.png ../../../_images/17cf3099170ff6a78d40a20f66ee5500a26695cf9c86dda474b3e1f52395c6ed.png ../../../_images/f716e846fc1f36987659dd728b93c616762082a8f9654bdb06a1703e41c7f08d.png ../../../_images/5306f9476d565fc74dae207dcfd24e65a34e276f906bd24ba10c8e8b8ae87f4f.png ../../../_images/b1ed0dc89a4aa11cd05baa913fb6f550dde94d79d8883fbdc32a7c20d7b10c31.png ../../../_images/f73c60e3b337103e7ef900837723bddc8ca0ae37463e4b6b2ee547f964cabf79.png ../../../_images/69c485e410e4631832bf9d01c83051adac54d760214a1101a6a52e0d8bdc3987.png ../../../_images/ab03fd8ad0bf2c1847e920d629865bf226cfea9d6f29dfca768ed1831bd5829e.png ../../../_images/7076a552c4c19d227fc9087e8efd733afa9a4c14c5db9238a0e67dfa56dacd9d.png ../../../_images/7ee2c300440afc028b5551eaddaba04f071c8fce2764d9f6bb8b915491fb42ba.png ../../../_images/5ddd8f7382389c7e75c5fbe61b6d1bd039512ebd66dfaad703ad13f0e8e26ab8.png ../../../_images/abbb5a57d78947fa3b0c511c6ef2570acb718018bf63e82c3068e6329dd18b29.png ../../../_images/9926c20327a579fad4f980b80ca8cdcd197ae97ce60aa8b211bd5b43b0a43d32.png ../../../_images/c41529dfa12025e9e1b98a2a08b006add24dbfe9eaa8808b5d85830ee5a90a50.png ../../../_images/558433cfe82f59d7c3b03124d8a6a1e6f76e8267f9e9a406fa2cd0d7bd77ae19.png ../../../_images/e7af9131b95473e444e31f14c2f58f607cec6469db3ca4450ac209b5e7f558ef.png ../../../_images/1cd6f8629850d816af0b8f3932271a550af8ef02a1fa933664824c5b094377c7.png ../../../_images/1f3798f2ab795688985594a86b5d95e2f6303abb625366980e777a3e7bd1d526.png ../../../_images/5dc961dcd21efa43bead7c971932a7c1c57eca0880f18b553ed5ced140fbc4cc.png ../../../_images/0f354ced91101d0d4f8356f7a33e6a0b989e3678cfe9838546c03741c68df737.png ../../../_images/9b20375d58f6f0ccceb166dc84b0f8481b98e331b39e5518bdd50d0dcc19776a.png ../../../_images/0f624c2c291fea7163d87f5a1f966743eb5ab2031d0d5b445b04d0d6a7dd2d94.png ../../../_images/644d88541f1ba729fbf5650cab0a86ce22dccadfd98e96ff479839d1498e4d16.png ../../../_images/c6f5034c7de9c585c0127fcb0ecb595c69f7557f9c0a55d840f95be64082ef0e.png ../../../_images/752a512e87434aba2c5fcc825e4702eb8936a612379d24a2a5d55536db8a42c4.png ../../../_images/e90d38ccc0a7c3e40a90a8c96460ba866b7f11967111f9bfb1a507371e2219c2.png ../../../_images/429a946d7cb55ed89b879807db5efe3955677c22e779240f75740c34c1181f5e.png ../../../_images/dd132001d03fc9bf205d773b7cbcf146d1eda779bc7d3ce999c6c703982fcf1c.png ../../../_images/f3ceac177d4079895d59079fd99c3fef82c15f204453b3ededbd1fd95d4e9c0f.png ../../../_images/fae1ce0b8c17b57af672ee06989d4c5ade2b810c30592734ce055c0f4af7b119.png

Very red high proper motion objects#

wpmred =  np.where((pmtot0 > 12) & (pmerr0 < 1.0) & (RminusI > 2.6) & good)[0]
print(f"Plotting {len(wpmred)} objects")
for o in tab["ObjID"][wpmred]:
    positions(o, jobs=jobs)
Plotting 4 objects
../../../_images/c23c5ff53a96219a6c48c453f2241d12118e07797efba8c5e153480aac76a955.png ../../../_images/abbb5a57d78947fa3b0c511c6ef2570acb718018bf63e82c3068e6329dd18b29.png ../../../_images/58c2553a1ce4fad8f287bf34ab4f10e40d8a72d0f1203eac96dabe4be5b5841c.png ../../../_images/d53fd56cfeace09b01bf0a4ac70729af3468e17594e6b50c9955484ec1fa7b3f.png

Very blue high proper motion objects#

wpmblue =  np.where((pmtot0 > 8) & (pmerr0 < 1.0) & (RminusI < 0.5) & good)[0]
print(f"Plotting {len(wpmblue)} objects")
for o in tab["ObjID"][wpmblue]:
    positions(o, jobs=jobs)
Plotting 12 objects
../../../_images/f6610d02a7a6ae16ea57640815850ccb1d4288eba85e7dd283c61d23775ca777.png ../../../_images/80ad8040355e676b87ef0977ea123dcd1ed04a3864d8ab11aff3db5a8e546257.png ../../../_images/c41529dfa12025e9e1b98a2a08b006add24dbfe9eaa8808b5d85830ee5a90a50.png ../../../_images/1d818615de776dca7158d62d39e636a7aba5214cdb615279d07d9e794d10e3bf.png ../../../_images/865a7c4f1c3e0e35c3479436484c5e01beea975b464d765512af0746891f6d68.png ../../../_images/2636bdd40ac5b5a45a36e645336012b4dfa8e9a98fa2fde1de2234f91755c5af.png ../../../_images/15af075a9d477260c795440720dc87c6e29c699ef1fadffa324d2d61dd37d3f1.png ../../../_images/c7ae0034bd1921c0efb7c21c267a967d4ce432edf8518de630410ea93049f1ae.png ../../../_images/9fd6e610eefac97412f8805372c753c07436fd32b184714076f0dc8733952738.png ../../../_images/0479dca1d4d3b48735152873ddae85810bc016e09a5ecf73e247eabb923ee3c5.png ../../../_images/4b0d02453c290d8d2e528184e46344ace686269d9c57fc856ef774a41b96a91e.png ../../../_images/dd1c476ded1ab856d8102565bff8980e09230f31acf9161a2be443896a695a1c.png

Get HLA cutout images for selected objects #

Get HLA color cutout images for the high-PM objects. The query_hla function gets a table of all the color images that are available at a given position using the f814w+f606w filters. The get_image function reads a single cutout image (as a JPEG color image) and returns a PIL image object.

See the documentation on HLA VO services and the fitscut image cutout service for more information on the web services being used.

def query_hla(ra, dec, size=0.0, imagetype="color", inst="ACS", format="image/jpeg",
              spectral_elt=("f814w", "f606w"), autoscale=95.0, asinh=1, naxis=33):
    # convert a list of filters to a comma-separated string
    if not isinstance(spectral_elt, str):
        spectral_elt = ",".join(spectral_elt)
    siapurl = (f"https://hla.stsci.edu/cgi-bin/hlaSIAP.cgi?"
               f"pos={ra},{dec}&size={size}&imagetype={imagetype}&inst={inst}"
               f"&format={format}&spectral_elt={spectral_elt}"
               f"&autoscale={autoscale}&asinh={asinh}"
               f"&naxis={naxis}")
    votable = Table.read(siapurl, format="votable")
    return votable


def get_image(url):
    """Get image from a URL"""
    r = requests.get(url)
    im = Image.open(BytesIO(r.content))
    return im
# display earliest and latest images side-by-side
# wsel = wpmred
# wsel = wpmblue
# top 10 highest PM objects
wsel = wpmh[:10]
nim = len(wsel)
icols = 1        # objects per row
ncols = 2*icols  # two images for each object
nrows = (nim+icols-1)//icols

imsize = 33
xcross = np.array([-1, 1, 0, 0, 0])*2 + imsize/2
ycross = np.array([0, 0, 0, -1, 1])*2 + imsize/2

# selected data from tab
sd = tab[['RA', 'Dec', 'ObjID']][wsel]

# create the figure
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12, (12/ncols)*nrows))

# iterate each observation, and each set of axes for the first and last image
for (ax1, ax2), obj in zip(axes, sd):
    
    # get the image urls and observation datetime
    hlatab = query_hla(obj["RA"], obj["Dec"], naxis=imsize)[['URL', 'StartTime']]
    # sort the data by the observation datetime, and get the first and last observation url
    (url1, time1), (url2, time2) = hlatab[np.argsort(hlatab['StartTime'])][[0, -1]]
    
    # get the images
    im1 = get_image(url1)
    im2 = get_image(url2)
    
    # plot the images
    ax1.imshow(im1, origin="upper")
    ax2.imshow(im2, origin="upper")
    
    # plot the center
    ax1.plot(xcross, ycross, 'g')
    ax2.plot(xcross, ycross, 'g')
    
    # labels and titles
    ax1.set(ylabel=f'ObjID {obj["ObjID"]}', title=time1)
    ax2.set_title(time2)
../../../_images/a2fcbcdbe4bf236abff9673ed7dbfb239cbee316686680cccb77cc4c1942cf4f.png

Look at the entire collection of images for the highest PM object#

i = wpmh[0]

# selected data
sd = tab['ObjID', 'RA', 'Dec', 'a_f606w', 'a_f814w', 'bpm', 'lpm', 'yr', 'dT'][i]
display(sd)

imsize = 33
# get the URL and StartTime data
hlatab = query_hla(sd['RA'], sd['Dec'], naxis=imsize)[['URL', 'StartTime']]
# sort the data
hlatab = hlatab[np.argsort(hlatab['StartTime'])]

nim = len(hlatab)
ncols = 8
nrows = (nim+ncols-1)//ncols

xcross = np.array([-1, 1, 0, 0, 0])*2 + imsize/2
ycross = np.array([0, 0, 0, -1, 1])*2 + imsize/2
Row index=208405
ObjIDRADeca_f606wa_f814wbpmlpmyrdT
int64float64float64float64float64float64float64float64float64
4000711121911269.7367256594695-29.20969991911761820.6727504730224618.963199615478516-18.43788346257518-36.801459330875692004.1942381434012.749260607770275
# get the images: takes about 90 seconds for 77 images
images = [get_image(url) for url in hlatab['URL']]
# create the figure
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(20, (20/ncols)*nrows), tight_layout=True)
# flatten the axes for easy iteration and zipping
axes = axes.flat

plt.rcParams.update({"font.size": 11})
for ax, time1, img in zip(axes, hlatab['StartTime'], images):
    # plot image
    ax.imshow(img, origin="upper")
    # plot the center
    ax.plot(xcross, ycross, 'g')
    # set the title
    ax.set_title(time1)
    
# remove the last 3 unused axes
for ax in axes[nim:]:
    ax.remove()

_ = fig.suptitle(f"ObjectID: {sd['ObjID']}\nRA: {sd['RA']:0.2f} Dec: {sd['Dec']:0.2f}\nObservations: {nim}", y=1, fontsize=14)
../../../_images/3c284a573516ab805756d3041ff05f26e8650f1fd6cb48a4b46ccd56522f0333.png