Hubble Source Catalog SWEEPS Proper Motion (API Version)#

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

A new MAST interface supports queries to the current and previous versions of the Hubble Source Catalog. It allows searches of the summary table (with multi-filter mean photometry) and the detailed table (with all the multi-epoch measurements). It also has an associated API, which is used in this notebook.

The web-based user interface to the HSC does not currently include access to the new proper motions available for the SWEEPS field in version 3.1 of the Hubble Source Catalog. However those tables are accessible via the API. This notebook shows how to use them.

This notebook is similar to the previously released version that uses CasJobs rather than the new API. The Casjobs interface is definitely more powerful and flexible, but the API is simpler to use for users who are not already experienced Casjobs users. Currently the API does not include easy access to the colors and magnitudes of the SWEEPS objects, but they will be added soon.

Additional information is available on the SWEEPS Proper Motions help page.

A notebook that provides a quick introduction to the HSC API is also available. Another notebook generates a color-magnitude diagram for the Small Magellanic Cloud in only a couple of minutes.

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 4 minutes (depending on the speed of your computer).

Table of Contents#

  • Initialization

  • Properties of Full Catalog

    • Sky Coverage

    • Proper Motion Distributions

    • Visit Distribution

    • Time Coverage Distributions

    • Detection Positions

    • Positions for a Sample With Good PMs

  • Science Applications

    • 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

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

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

from PIL import Image
from io import BytesIO

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
# set universal matplotlib parameters
plt.rcParams.update({'font.size': 16})

MAST API functions#

  • Execute HSC searches and resolve names using MAST query.

  • Here we define several interrelated functions for retrieving information from the MAST API.

    • The hcvcone(ra, dec, radius [, keywords]) function searches the HCV catalog near a position.

    • The hcvsearch() function performs general non-positional queries.

    • The hcvmetadata() function gives information about the columns available in a table.

hscapiurl = "https://catalogs.mast.stsci.edu/api/v0.1/hsc"


def hsccone(ra, dec, radius, table="summary", release="v3", format="csv", magtype="magaper2",
            columns=None, baseurl=hscapiurl, verbose=False, **kw):
    """Do a cone search of the HSC catalog
    
    Parameters
    ----------
    ra (float): (degrees) J2000 Right Ascension
    dec (float): (degrees) J2000 Declination
    radius (float): (degrees) Search radius (<= 0.5 degrees)
    table (string): summary, detailed, propermotions, or sourcepositions
    release (string): v3 or v2
    magtype (string): magaper2 or magauto (only applies to summary table)
    format: csv, votable, json
    columns: list of column names to include (None means use defaults)
    baseurl: base URL for the request
    verbose: print info about request
    **kw: other parameters (e.g., 'numimages.gte':2)
    """
    
    data = kw.copy()
    data['ra'] = ra
    data['dec'] = dec
    data['radius'] = radius
    return hscsearch(table=table, release=release, format=format, magtype=magtype,
                     columns=columns, baseurl=baseurl, verbose=verbose, **data)


def hscsearch(table="summary", release="v3", magtype="magaper2", format="csv",
              columns=None, baseurl=hscapiurl, verbose=False, **kw):
    """Do a general search of the HSC catalog (possibly without ra/dec/radius)
    
    Parameters
    ----------
    table (string): summary, detailed, propermotions, or sourcepositions
    release (string): v3 or v2
    magtype (string): magaper2 or magauto (only applies to summary table)
    format: csv, votable, json
    columns: list of column names to include (None means use defaults)
    baseurl: base URL for the request
    verbose: print info about request
    **kw: other parameters (e.g., 'numimages.gte':2).  Note this is required!
    """
    
    data = kw.copy()
    if not data:
        raise ValueError("You must specify some parameters for search")
    if format not in ("csv", "votable", "json"):
        raise ValueError("Bad value for format")
    url = "{}.{}".format(cat2url(table, release, magtype, baseurl=baseurl), format)
    if columns:
        # check that column values are legal
        # create a dictionary to speed this up
        dcols = {}
        for col in hscmetadata(table, release, magtype)['name']:
            dcols[col.lower()] = 1
        badcols = []
        for col in columns:
            if col.lower().strip() not in dcols:
                badcols.append(col)
        if badcols:
            raise ValueError(f"Some columns not found in table: {', '.join(badcols)}")
        # two different ways to specify a list of column values in the API
        # data['columns'] = columns
        data['columns'] = f"[{','.join(columns)}]"

    # either get or post works
    # r = requests.post(url, data=data)
    r = requests.get(url, params=data)

    if verbose:
        print(r.url)
    r.raise_for_status()
    if format == "json":
        return r.json()
    else:
        return r.text


def hscmetadata(table="summary", release="v3", magtype="magaper2", baseurl=hscapiurl):
    """Return metadata for the specified catalog and table
    
    Parameters
    ----------
    table (string): summary, detailed, propermotions, or sourcepositions
    release (string): v3 or v2
    magtype (string): magaper2 or magauto (only applies to summary table)
    baseurl: base URL for the request
    
    Returns an astropy table with columns name, type, description
    """
    url = "{}/metadata".format(cat2url(table, release, magtype, baseurl=baseurl))
    r = requests.get(url)
    r.raise_for_status()
    v = r.json()
    # convert to astropy table
    tab = Table(rows=[(x['name'], x['type'], x['description']) for x in v],
                names=('name', 'type', 'description'))
    return tab


def cat2url(table="summary", release="v3", magtype="magaper2", baseurl=hscapiurl):
    """Return URL for the specified catalog and table
    
    Parameters
    ----------
    table (string): summary, detailed, propermotions, or sourcepositions
    release (string): v3 or v2
    magtype (string): magaper2 or magauto (only applies to summary table)
    baseurl: base URL for the request
    
    Returns a string with the base URL for this request
    """
    checklegal(table, release, magtype)
    if table == "summary":
        url = f"{baseurl}/{release}/{table}/{magtype}"
    else:
        url = f"{baseurl}/{release}/{table}"
    return url


def checklegal(table, release, magtype):
    """Checks if this combination of table, release and magtype is acceptable
    
    Raises a ValueError exception if there is problem
    """
    
    releaselist = ("v2", "v3")
    if release not in releaselist:
        raise ValueError(f"Bad value for release (must be one of {', '.join(releaselist)})")
    if release == "v2":
        tablelist = ("summary", "detailed")
    else:
        tablelist = ("summary", "detailed", "propermotions", "sourcepositions")
    if table not in tablelist:
        raise ValueError(f"Bad value for table (for {release} must be one of {', '.join(tablelist)})")
    if table == "summary":
        magtypelist = ("magaper2", "magauto")
        if magtype not in magtypelist:
            raise ValueError(f"Bad value for magtype (must be one of {', '.join(magtypelist)})")

Use metadata query to get information on available columns#

This query works for any of the tables in the API (summary, detailed, propermotions, sourcepositions).

meta = hscmetadata("propermotions")
print(' '.join(meta['name']))
meta[:5]
objID numSources raMean decMean lonMean latMean raMeanErr decMeanErr lonMeanErr latMeanErr pmRA pmDec pmLon pmLat pmRAErr pmDecErr pmLonErr pmLatErr pmRADev pmDecDev pmLonDev pmLatDev epochStart epochEnd epochMean DSigma NumFilters NumVisits NumImages CI CI_Sigma KronRadius KronRadius_Sigma HTMID X Y Z
Table length=5
nametypedescription
str16str5str31
objIDlongobjID_descriptionTBD
numSourcesintnumSources_descriptionTBD
raMeanfloatraMean_descriptionTBD
decMeanfloatdecMean_descriptionTBD
lonMeanfloatlonMean_descriptionTBD

Retrieve data on selected SWEEPS objects#

This makes a single large request to the HSC search interface to the get the contents of the proper motions table. Despite its large size (460K rows), the query is relatively efficient: it takes about 25 seconds to retrieve the results from the server, and then another 20 seconds to convert it to an astropy table. The speed of the table conversion will depend on your computer.

Note that the query restricts the sample to objects with at least 20 images total spread over at least 10 different visits. These constraints can be modified depending on your science goals.

columns = """ObjID,raMean,decMean,raMeanErr,decMeanErr,NumFilters,NumVisits,
    pmLat,pmLon,pmLatErr,pmLonErr,pmLatDev,pmLonDev,epochMean,epochStart,epochEnd""".split(",")
columns = [x.strip() for x in columns]
columns = [x for x in columns if x and not x.startswith('#')]

# missing -- impossible with current data I think
# MagMed, n, MagMAD

constraints = {'NumFilters.gt': 1, 'NumVisits.gt': 9, 'NumImages.gt': 19}

# note the pagesize parameter, which allows retrieving very large results
# the default pagesize is 50000 rows

t0 = time.time()
results = hscsearch(table="propermotions", release='v3', columns=columns, verbose=True, pagesize=500000, **constraints)
print("{:.1f} s: retrieved data".format(time.time()-t0))
tab = ascii.read(results)
print(f"{(time.time()-t0):.1f} s: converted to astropy table")

# change some column names for consistency with the Casjobs version of this notebook
tab.rename_column("raMean", "RA")
tab.rename_column("decMean", "Dec")
tab.rename_column("raMeanErr", "RAerr")
tab.rename_column("decMeanErr", "Decerr")
tab.rename_column("pmLat", "bpm")
tab.rename_column("pmLon", "lpm")
tab.rename_column("pmLatErr", "bpmerr")
tab.rename_column("pmLonErr", "lpmerr")

# compute some additional columns

tab['pmdev'] = np.sqrt(tab['pmLonDev']**2+tab['pmLatDev']**2)
tab['yr'] = (tab['epochMean'] - 47892)/365.25+1990
tab['dT'] = (tab['epochEnd']-tab['epochStart'])/365.25
tab['yrStart'] = (tab['epochStart'] - 47892)/365.25+1990
tab['yrEnd'] = (tab['epochEnd'] - 47892)/365.25+1990

# delete some columns that are not needed after the computations
del tab['pmLonDev'], tab['pmLatDev'], tab['epochEnd'], tab['epochStart'], tab['epochMean']

tab
https://catalogs.mast.stsci.edu/api/v0.1/hsc/v3/propermotions.csv?pagesize=500000&NumFilters.gt=1&NumVisits.gt=9&NumImages.gt=19&columns=%5BObjID%2CraMean%2CdecMean%2CraMeanErr%2CdecMeanErr%2CNumFilters%2CNumVisits%2CpmLat%2CpmLon%2CpmLatErr%2CpmLonErr%2CpmLatDev%2CpmLonDev%2CepochMean%2CepochStart%2CepochEnd%5D
12.8 s: retrieved data
21.8 s: converted to astropy table
Table length=462899
ObjIDRADecRAerrDecerrNumFiltersNumVisitsbpmlpmbpmerrlpmerrpmdevyrdTyrStartyrEnd
int64float64float64float64float64int64int64float64float64float64float64float64float64float64float64float64
4000709004606269.84629586313974-29.2050122255796120.18047774041762040.19426558674102012460.08288446362915312-7.5349034924181140.24980533435284480.195324951483143361.31831873552006942013.51523827019923.00678224901781552011.80131195436252014.8080942033803
4000709004607269.8483807976172-29.2050173283818530.19988134421849050.186174763329276182464.77103972056131550.70627486106103390.2952943823022760.139672749038795371.50454702504652742013.51523827019923.00678224901781552011.80131195436252014.8080942033803
4000709004608269.81335912859953-29.205052485944590.34215885600236110.36056353088469692470.623967194412774-2.19701573357267850.215949918434534260.203995962864459452.72775236755855442013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709004609269.82526669583405-29.2050508482998050.34883001394782540.41167598654542612471.0369686053154874-7.9806338838158720.174810837314406720.270987092092025542.1139193259796432013.300790214705811.3719145413717642003.43617966200852014.8080942033803
4000709004610269.8296308224566-29.2050520824308932.0938487022217452.0060974104787377222-3.9758657414480760.76696310915656761.9700092890404432.49371155697486659.2763952767352062013.36504903955822.933583080481732011.80131195436252014.7348950348442
4000709004611269.8157033469999-29.20510242886403427.8869486982212574.082353243047675246-2.96629294915057471.820432863674738716.00685111539338510.613069038297004185.01488141638852013.39013065763511.3719145413717642003.43617966200852014.8080942033803
4000709004612269.84984289409994-29.2050511544798755.4512989011026540.3950096738194534213-1.1703168155081791-4.900408858267125.8569663569085593.239945907421289710.0811873176168432013.60909756573372.34334014995504262012.20402848387042014.5473686338253
4000709004615269.83732402150747-29.2051159355337484.42835170524497716.5812808879283472303.3556123245090874-9.4461680923218896.93309222541992118.3798458312439665.088090409985162013.59514598597553.00678224901781552011.80131195436252014.8080942033803
4000709004616269.8207026377875-29.2051131963468970.91503261076478031.51870032325406282420.6132876315339588-5.0596409837463410.70548971391037660.72311354578758088.0118968938428452013.253412056684311.3719145413717642003.43617966200852014.8080942033803
................................................
6000165252534269.71483815366565-29.206086214028341.33594776994389840.5573498829904994911-158.5890473271123820.397894750944268135.0319886592532499.187224335472463.321800575501832015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252545269.7151304059814-29.2060348342242831.31330820217140020.5753188700691569911-148.0714644649570264.08441219776404139.93188319578789.218592747867523.36905251053659432015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252557269.7170959958215-29.2060310812931481.04748894303441080.44892665653642305911-96.4535890138543-164.8949216740117108.836245500838274.525936106617952.82552546150625352015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252578269.7181053315153-29.2059486397204821.13745344095894340.7820141140582517911-351.0270921133267252.50310186752114140.5716522960252675.929240786908243.2885688221851552015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252579269.71539504162905-29.205976266396431.03045655115482380.6078680461509636911-228.79277774475963-121.21217408415274107.1036551495499487.77432668972562.94894432273044462015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252585269.7139116946398-29.205814011368681.09288299659774730.1737181086154091911-55.7317661312443356.702560650169243110.5725601821721864.646209025443372.34087350875307452015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252590269.7147254733658-29.2059121310389461.08581478032121080.3514023427469821911-189.748370998037945.448745954656275106.9487564590321777.531239507103652.7776782692039962015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252609269.715804778712-29.2058440024403331.15552932288573970.33405860052843767911-321.590214293594160.041693585055896765121.1004225804220268.686674361037752.89114549648759932015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252615269.71775504663-29.2058574610025871.00885362738852711.0012626630704595911-4.38245839524729225.536209929537428109.86328192409816122.457818350454863.3328989175710682015.5671637223780.0244001449480357042015.55126350699022015.5756636519384
6000165252625269.715136545852-29.205857066119880.96517610688359720.8510531750863013911-101.02664190234734-37.53601998368994117.3843076165260791.674558189191132.9698773612453772015.5671637223780.0244001449480357042015.55126350699022015.5756636519384

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/e07ca545a993f5e71474fa790c4568fb18af4791287481cfaec00d3f7a0d5f42.png

Proper Motion Histograms #

Proper motion histograms for lon and lat#

bins = 0.2
hrange = (-20, 20)
bincount = int((hrange[1]-hrange[0])/bins + 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 {bins:.2} mas bins]', title=f'{len(tab):,} stars in SWEEPS')
_ = ax.legend()
../../../_images/71aab9225bd42bae0d0f190264d79a1a3c274a32821e6c8b3404f0fdbeb06de4.png

Proper motion error cumulative histogram for lon and lat#

bins = 0.01
hrange = (0, 2)
bincount = int((hrange[1]-hrange[0])/bins + 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 {bins:0.2} mas bins]', title=f'{len(tab):,} stars in SWEEPS')
_ = ax.legend(loc='upper left')
../../../_images/abbfb418d4110c96bf4c0bc49113e1bab3b2db3b19924801c921e005378e17cb.png

Proper motion error log histogram for lon and lat#

bins = 0.01
hrange = (0, 6)
bincount = int((hrange[1]-hrange[0])/bins + 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 {bins:0.2} mas bins]', title=f'{len(tab):,} stars in SWEEPS', yscale='log')
_ = ax.legend(loc='upper right')
../../../_images/960bad50a47c287bf3073a5d94fba552b486d388724b64a7c97d1af13ca3d093.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, y, numPoints=2**9+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.6 sec
Plotting 181541 of 461199 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/3fb6fc9a0e6e8f9c1345ac53b08a05fef06da9f9761c5aed37457af87ae51740.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.

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

# select the data to plot
mask = tab['dT'] <= tsplit
data1 = tab[mask]
data2 = tab[~mask]
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(12, 12), sharey=True)

for ax, data in zip([ax1, ax2], [data1, data2]):
    for col, label in zip(['lpmerr', 'bpmerr'], ['Longitude Error', 'Latitude Error']):
        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 {bins:0.2} mas bins]',
        title=f'{len(data1):,} stars in SWEEPS with dT < {tsplit} yrs', yscale='log')
ax2.set(xlabel='Proper motion error [mas/yr]', ylabel=f'Number [in {bins:0.2} mas bins]',
        title=f'{len(data2):,} stars in SWEEPS with dT > {tsplit} yrs', yscale='log')

ax1.legend()
ax2.legend()

_ = fig.tight_layout()
../../../_images/96dbe68ffbf66b5369517c67d86726840ff573eabf660d858ef175a52de313ee.png

Number of Visits Histogram #

bins = 1
hrange = (0, 130)
bincount = int((hrange[1]-hrange[0])/bins + 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/bb0c976f98b2850ecff4c05ee640eb543d581fe2a37da2b1723ac1a0f9f25478.png

Time Histograms #

First plot histogram of observation dates.

bins = 1
hrange = (2000, 2020)
bincount = int((hrange[1]-hrange[0])/bins + 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/9aa6500302f772399a4d65aa292f792f34efaec0399a224bf185148ee0614ec3.png

Then plot histogram of observation duration for the objects.

bins = 0.25
hrange = (0, 15)
bincount = int((hrange[1]-hrange[0])/bins + 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/c782ec78feea6c56c9ff9bb3d319619f02cbfc8780e82260ccf15bf25978a990.png

Detection Positions #

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

# define function
def positions(Obj):
    """
    input parameter Obj is the value of the ObjID 
    output plots change in (lon, lat) as a function of time
    overplots proper motion fit
    provides ObjID and proper motion information in labels
    """

    # get the measured positions as a function of time
    pos = ascii.read(hscsearch("sourcepositions", columns="dT,dLon,dLat".split(','), objid=Obj))
    pos.sort('dT')
    
    # get the PM fit parameters
    pm = ascii.read(hscsearch("propermotions", columns="pmlon,pmlonerr,pmlat,pmlaterr".split(','), objid=Obj))
    
    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)

    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', fontsize=10)
    
    plt.show()
    plt.close()

Plot positions for a sample of objects with good proper motions #

This selects 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)
Plotting 21 objects
../../../_images/c211ce5091aeed534414fca392b411af0ee031f44110d4e7be53a9903511c26e.png ../../../_images/0ad4bcd35abaa08ca138d7f6481207c2dfc7adfee76828d3b00c6ebb86aeee4e.png ../../../_images/bcfb94152fa43c220f1c52d161fb5626e38334595e274c130ca2ddc6232d2aba.png ../../../_images/ed9e302859dbeb3363027922664f224b1774a23a7b45d9e24e6e9c55841d9979.png ../../../_images/bd4180f644ef5c977f0644836bc92987624a1c7a5fa0e8e35828171c9e447df3.png ../../../_images/fb99921aea5c0e2f088199fed12ad0060eea59b9ac8217267be971cfbd94eb3e.png ../../../_images/02086f6e8aca27a17cb17bfa9a6e52daaccc9d76fe91fdff09c2628fbe9f605b.png ../../../_images/14c3620ddea8ebb3052f9108714a1553f96d61e1cec69ee5fb07abfd978fe73e.png ../../../_images/74a6224214f9fa38425b6a5f422e1b260746500ec28106a43e5f41a3a71b53ac.png ../../../_images/0ccac0a87a62ba863513fe40f175d46cd3979ab3ac47c84309a32d5254e0ca75.png ../../../_images/15e035509cadd7a3a0aae3683730745c3de8f2ec555e72bb9f8b50d968959a57.png ../../../_images/90e986b0fa764ecb7582ceabc390520e414ce8b2ffcc6475954c676e5e03becb.png ../../../_images/24e2da9e747780324e5ee8a3d4489c4908591d12efed9d4da55e31aacf642608.png ../../../_images/c91a65fba082118e114e594714eb4769a448246e378d2ba77f7376240f8624cf.png ../../../_images/199e314f81b7438cf619b7ce06add7759cad1d08fab447244f1f153985631626.png ../../../_images/d68b5803b47fd01105db1b04e575935085c1826ac17f30a17319fc3fb74a9433.png ../../../_images/8da72a690cbe4cdd384e65d6e44687de305062769a5b6132877ceb3f494c8c3b.png ../../../_images/95d4952b32bb836271dbeeae21d80f7d25e22dbe9bd0df27d76032f5e7f1e71b.png ../../../_images/b16d17a3d478fde70b37769ed988efd907ba3eab9e49a18bfa303cd8ade54010.png ../../../_images/e541e53cfbdd83881b83150f9968c48071e0b67cf2eea40b32f31bf921dc7b1e.png ../../../_images/7030f478ab9a284322f5c8196666d5d4d46771699e9859a855e78c95ef7f7168.png

Science Applications #

High Proper Motion Objects #

Get a list of objects with high, accurately measured proper motions. Proper motions are measured relative to the Galactic center.

lpm_sgra = -6.379 # +- 0.026
bpm_sgra = -0.202 # +- 0.019

lpm0 = np.array(tab['lpm'])
bpm0 = np.array(tab['bpm'])
lpmerr0 = np.array(tab['lpmerr'])
bpmerr0 = np.array(tab['bpmerr'])
pmtot0 = np.sqrt((bpm0-bpm_sgra)**2+(lpm0-lpm_sgra)**2)
pmerr0 = np.sqrt(bpmerr0**2+lpmerr0**2)
dev = tab['pmdev']

# sort samples by decreasing PM
wpmh = np.where((pmtot0 > 15) & (pmerr0 < 1.0) & (dev < 5))[0]
wpmh = wpmh[np.argsort(-pmtot0[wpmh])]

print(f"Plotting {len(wpmh)} objects")
for o in tab["ObjID"][wpmh]:
    positions(o)
Plotting 31 objects
../../../_images/fd1bf9068379464265121bd9d54cdf674592fb7a11303a6ea7a672846434e414.png ../../../_images/72cf3adfc40cd6198b4fffd1a570910e7bbae452271b4596b954b77b2ac8e17b.png ../../../_images/13b26ce71f3219bf05c5d0a8c274bc1f509b6fb37131983dcb19700f7a0c73e0.png ../../../_images/e9135337fbc090724eba097ec0e3be1ee91f2dfe62e6ee277d048a473bf12b18.png ../../../_images/182153a92ca915d20f7107327342dbcff95bf0167ba1e0b4443f6a26f0da7130.png ../../../_images/07a55b94a5703be73c676c31a427f490358ebb227f1658589d557febf072e944.png ../../../_images/fb899f2a5ddc50c29ffbfb92014ecfc94bfe430f4d7aea4afec333df0693fc41.png ../../../_images/ea93726179b7d8d19c5b48b8e03764821988ce4d9e81dccccf1d8ff42147c5d7.png ../../../_images/93691d3adc9c413b8bc6d0019a86eeff9ca7e2fecd1cfd1724238406280b6a9d.png ../../../_images/ff088b2278ac490d891a5442149fdb1706a4a0abe1486fe8c92dcc96a84caaf6.png ../../../_images/2d3454899a6dba4facb1a3c3f54724dc7a2aa963f4a1f495e86121604a8c0ff1.png ../../../_images/c9ca99989955a7793b7b8c142cdb7c52a59695d4d3785f6de858ee12a940b607.png ../../../_images/1178b58be75174ea0ef904e7b02283b14defcbddf13f2cbf2f7529d5c6ab0f5b.png ../../../_images/6ca3da7faf43c54de23ed5357b0f9c69ac7839307905bc7eb1e812d2ce22f143.png ../../../_images/591df3d69d6be1cd123a93c427a30abad1d1c89de059d1fc629cdc5188a31b2a.png ../../../_images/6d373189f3836c0701723ece1983757e87bc21c57a2dd61fdeab46acd9e7f489.png ../../../_images/41df0a47ba295d224908df96f742721e5e8407c13b195a705f263cf9c2b55fa2.png ../../../_images/e33e92c62b18c6a5363f27caed78a6bf26debc6d296b57a1fe34ca1d4e7fcd93.png ../../../_images/65a1b90c4cd397b0b1d6abce1c9bfd0c95b26869de2712855a1786bc94013ec2.png ../../../_images/513507938080700aa6b847c2dffcb4c391fa0c516d3b5ce4ccf059e5a8659541.png ../../../_images/9da3368f142f84bb05a76a2653ab8ed7a408ba609b9a0c4874b442de44ad3bed.png ../../../_images/3ddf40fd57d082e03374180c3955e461ac9495a76ffeb15424cd5ec7ea1607dc.png ../../../_images/6135a0b4783a7baf887c9e0bd3112908f6ae3543963fd2aedb3a18fe72449cf2.png ../../../_images/005d95155f72d426d989308479483bbeb642f2899a5d7a305cc07dc62423a7c1.png ../../../_images/28ea22e66731a97b4c4c573d30494b18352a83fe4bb8e480d11ed6adff287b7e.png ../../../_images/21d3d03fc573ebeedf06c104bbfcd9e6380089a8804434e667d2c29fa25c1c02.png ../../../_images/aa03d4301193b014d9e78a706ba8ae6332176316ed722f74afb3d900a2d1617c.png ../../../_images/fc5faebec59b5f601247979f6256b62e6b707e048007cc3e39b25ed0f106cc43.png ../../../_images/7288e13180217e02b41f61bf25d91a260576091b3c03b071559d81a889027506.png ../../../_images/ec5b6b50b86bbd96bec5136b1ac0c243e96cac1f32e57c821b7e77e5ac069a3e.png ../../../_images/f2f690ec5b9119a98abf5d0c15e41765996de2f17b2dbd6fdb1cfcdc6075c989.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 = ("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
# 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/91c4f106fb92b7194749f82661f2999c6b93154a6a00d399a546840a2bb5e1f4.png

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

i = wpmh[0]

# selected data
sd = tab['ObjID', 'RA', 'Dec', '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=197555
ObjIDRADecbpmlpmyrdT
int64float64float64float64float64float64float64
4000711121911269.7367256594695-29.209699919117618-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))
# 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)
fig.tight_layout()
../../../_images/200580605debb653414a61d3c67c5f6559d98fbe701729f5b3e7485efd7f2ad4.png