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
8.7 s: retrieved data
18.5 s: converted to astropy table
Table length=462899
ObjIDRADecRAerrDecerrNumFiltersNumVisitsbpmlpmbpmerrlpmerrpmdevyrdTyrStartyrEnd
int64float64float64float64float64int64int64float64float64float64float64float64float64float64float64float64
4000709002872269.80265870673486-29.2059572436900768.9065929916339944.750948845211954247-0.07214893672427546-9.9092721444491833.80494649801746965.89047336204338374.061937109478272013.319616239868811.3719145413717642003.43617966200852014.8080942033803
4000709002873269.80378770789946-29.2059748359940520.70962180324441950.91698765928121062424.312672332548042-2.36074389964024740.43075387242187470.52054715699623735.8866956022501092013.198496652833711.3719145413717642003.43617966200852014.8080942033803
4000709002876269.82296821680706-29.2058964767164220.77069734737907791.9541464863212482452.9641739091991512-0.98244067708584510.80501686274743330.93358329003071729.4217431101238262013.281854940974911.3719145413717642003.43617966200852014.8080942033803
4000709002877269.8332548589135-29.2058681552258080.274246678552267530.18316555715544097246-0.02656376817605078-5.1091932108010870.26999262979936670.287483405830419371.78814012733185872013.51523827019923.00678224901781552011.80131195436252014.8080942033803
4000709002878269.835302632853-29.205870738193870.18799998281184650.22453110670725465246-0.375486122675332-3.5408240126138290.215514988514709320.276041738798126051.2975477914312442013.51523827019923.00678224901781552011.80131195436252014.8080942033803
4000709002879269.8277124425253-29.205898255059791.002450202755213.4552107776665242352.7773433261106537-10.4390795863779931.14150475222603491.553771702687093912.3122713063381062013.266066399112311.3719145413717642003.43617966200852014.8080942033803
4000709002880269.82272881885933-29.2059863115730780.92576252269091632.6477117989045444238-2.1293053467134273-8.7992529638187150.89125744982097471.25889076449342157.4222116314036762013.245917098414311.3719145413717642003.43617966200852014.8080942033803
4000709002881269.82473057730886-29.2059377091150021.45681156934889924.4042875687886092370.7229890782462978-4.9468627065441550.88733070504084782.35601845293313814.9758931895210042013.270251752943511.3719145413717642003.43617966200852014.8080942033803
4000709002882269.8276616511264-29.205971304948260.78706408772736381.1392253570886217235-0.5371775072209872-7.4693543628041780.37776678452533760.64051991476982815.7051123146491392013.247960548827711.3719145413717642003.43617966200852014.8080942033803
................................................
4000830768301269.80659589077084-29.1993614673679541.77427209447217331.37938121376283942140.8224212989215296-9.394527064934560.47749082338603540.70323716864943766.1752792926110612012.474076302132711.3421286555118022003.43617966200852014.7783083175204
4000830768893269.8273004357832-29.1990732309845741.43344569440858071.599117709275305211-2.6446896669774187-8.4440985948687522.91686269658475571.9069768785843284.9900697921897472013.91228589621052.13757908847348732012.6705151149072014.8080942033803
4000830784615269.8475458930169-29.1916490816580353.0993793260130223.074101236864049212-1.4950991436991465-10.0502106797510254.0302293037409997.540172916531262510.6058530349889912013.6817674313821.39439765209029962013.11044813426252014.5048457863527
4000830785929269.84114859514546-29.191009629271441.08841051356221953.0145623075511576215-1.3287103052586406-6.0673171569998732.13416671341857933.72762413640112078.3080693034126162013.79509142540252.3094421306690032012.49865207271142014.8080942033803
4000830789933269.8255767370229-29.1891665610977217.992737747919983.31399230403260521736.322379099815805-15.02592638554461924.18953274499567710.91631988921965254.030777419016792013.52863379189832.1615098062902692012.34333598006242014.5048457863527
4000830792754269.83978411658575-29.1877552018048162.6257010079373253.70494667603872372161.9621608038309186-4.9868939608156353.3914188724675884.579511699088743410.2475415973799522013.4188734504012.8886899947214932011.80131195436252014.690001949084
4000830795783269.81982628649195-29.16990421131334421.304863377676957.366043739608044213-13.274868786727028-4.46500711030085126.93127422881945.92458201492404262.5241526410727462013.79571607528062.3094421306690032012.49865207271142014.8080942033803
4000830807333269.83912629454755-29.1864015237465862.27327480055736641.8547825492630352212-2.478043357373299-2.5207067692298912.9472319827642452.99021168724250957.2231951075755822014.0996043648842.3094421306690032012.49865207271142014.8080942033803
4000830813222269.822832157458-29.175153223967582.2197354559835043.4460507000417135215-2.7377186929987865-3.70272117348028474.5344368856750882.50764232181652711.070163084727992013.45602680440922.2956152853570642012.34333598006242014.6389512654196
4000830815915269.79028283835504-29.17668137497327835.6730409123986811.438278094527297219-57.4134367158742335.9672340713269438.71223740542565426.310656652752417126.677979921767422013.59240298317562.6040657195100062012.20402848387042014.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/6754958ab773284f508fe2b7583741ab4b2a4a2786cf21449e96524b4d6a0628.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/538e971df37e11c04b520624c61569a6a1032229a83011f6d69d8b1f3b7445fc.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/b30404547e29f94950ecb0f80586c369ea67121e358f9cb65bba920f18050f7a.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/674bbbf3955ebfa38d83055125851e4736932085be9a43ed589098fa35fccf96.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 182294 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/33e88a50e72e5421bbb09aaccbbce5d262e79052b1b4dfa68f03bd89f186920a.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/61c60e33695c46eb6f15aef59e73f9a68314515c1a59c4c640195f109628dd49.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/024908490fb1020e68650815c97a6b2bff583d2cefb4737a0743f6da889f6ec0.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/35f3b55a9cccc0d06cff42b26ec612a74cf08db44af599c3dc1e171dbf8e45db.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/169739acdec6c4c82f2b821ee31c387d995e59defbe51af467261dad12ce4953.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/8bdb3dc08941ba4a826124341c03b19affcbd0c24d2e0da65ace49e28ae6b7f8.png ../../../_images/d2c0e40b76c038b3b77e872ad26f3cb08c8d73d962ded8329b2c407e7f46e388.png ../../../_images/6e866b58d9a618fbfd627590035344dc45823d6bd75ac67d8593174f5c732842.png ../../../_images/146ab5c7e0782a5d7cd6a7938848304f5ce2647e270747e34ebe89693970d9a1.png ../../../_images/041d88714402d900ca87ec31ea8677c0a022d653058a29738c40d0b80600c529.png ../../../_images/1c9b1605ff279e02c636aa140f2b5b7cb053ead0c034d43623a5acd0dbb4471d.png ../../../_images/5624839f1005eb608fd6df40a784a5822eebe9f29a5a5d68caf8ea678ea2a8a8.png ../../../_images/8f500ecadb3a5f36d9800b1e855eb902a767522411e5b9d516307fbd93081ce8.png ../../../_images/08f42b2400c7fad0ff9b2c2599a4d574e4e581c388b6c97344d7941cacac4a6c.png ../../../_images/efaedd36256f5cad31a33a10200dd8ffc34bf452180340caf6a83eba0d12fb3b.png ../../../_images/199282e3ed2bec47d20540b1204f3fe70f5fea11ba1bb08182624d679d5a25ec.png ../../../_images/a7bccba11679e29b730b2d58e1ed9b58762d27d10d87577f9275cdeeaaef3a31.png ../../../_images/78affdc0d753bfe0056191a8f1bb5ca29ad844b210a045c19ff13f2fd6387210.png ../../../_images/1e8cfd31d5ad8dea4121348ecb853b37af3b5149d5fa8e907fc9307ffc335cdc.png ../../../_images/00aaedbe92be5c764b438c134f0ed1d4d453aacfebeede19c36b7c8ba8680aa9.png ../../../_images/604cf63aba4ec1ea221e7b2fb00ae4aeae675a0af62fed1ebb23fece2024a727.png ../../../_images/fc7afd2b16422df673b3d92d63d90cd4e9e7bcfe94da6bd5ca213b23459c13e6.png ../../../_images/cd972c65f6bd23cc7ef59c942d8f5a292ecfcbc04bce1ac6c5bcc16cd5340c98.png ../../../_images/2c942324d2652f5d0413121faa9060899bdccacfde4544df1e20d327820c7c5f.png ../../../_images/6a8b5d151537848218c0b6c7d99df2d89608ed8a16396168c5e947efdef25227.png ../../../_images/934ff18fa2b07a6251a6af26bed6b24f6b760665083f24fc3ceed93a0305d5c7.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/d5023fe23a410f5a02a6585527f51cf912d9f295786069512e111f6da6bea48d.png ../../../_images/a802f8b3f3afa7c96447d8b52d706f434f8ab9c23f7b000335db6672cfe3fc93.png ../../../_images/44fa66285c1d01e0ffd018171d741ff77404e1c2dde6fe565af0cf5ac7553400.png ../../../_images/ec0be0072445c3e98e8746668271eb662c8332bf110d6d8f93beee2fe53d7fd8.png ../../../_images/5d6c0fdcf9fe28afd9efbdeeded60774e47b9fb1506adc6e5506986e9abe41af.png ../../../_images/e8e20d0b12fe11eb57b0d8b885a3ca164970244fd34f2ece40fe852856659a93.png ../../../_images/1646c984794f4f38e7a9e5bc5c9f54cf57e69602352192673505755f041b1c25.png ../../../_images/935e1b7fe267b70c05a8045c66bfb504d3a8b299f84d2f0f3aa4aa6932631359.png ../../../_images/b78958ae84749e97e2b7614b55f89dfb2cc2bcbb5f22d50c22dc64067a06a579.png ../../../_images/165ce487f6622c2a0ec2c280e3a542a5b2aaf4394f210c98dc7e190de3d38738.png ../../../_images/b789d92d9b2fd79514b5b70bf8efdf2bb546055db1f63c2c5edc331edb0f8fea.png ../../../_images/d7e34ac879d6a55d8af726568d104ed03e1cce33f224ec7fa05af3f41f6b7a1a.png ../../../_images/cf62564ecad54fd42be2299349c5cabc18197eb2dc106c08528c07c847baded5.png ../../../_images/e2bba000a12e9ee800acec09586a789cb83db0fd2fead35d0420a69e9b702c6f.png ../../../_images/cb98228c8982278f9f1bba5c4e4fbb226a07de60878b007f07c2b7386d2120b9.png ../../../_images/ef431e4bd86fa8a461b2f17a4e402dd0f2143e34b812563f7f1f54883a9e1b03.png ../../../_images/15d160234d5bd19da2d2f8f176a62f9c5dbd3c04b49c7fcd1e3a5465069bdd35.png ../../../_images/df855cf8a3c4abfdf58b24e502dc90861147155ffd455f92a53a8a0ce1eaa42e.png ../../../_images/e0b7fd0864e7f08d5a639baabf5bb5cc6636c6d2d765aa140351e95db19eb0b4.png ../../../_images/c2063cdf5528b1eceec0a0f5a0af27b5eb310b4a44608de100357fa778726044.png ../../../_images/555c4c583daedc346ee97768d5cb34721fdf0b16f8aec5a9ecfd260737880b7a.png ../../../_images/7bb967c5bda4f0b5c75dd05d6abadff4f0fbfb7588115ad4ec38e4a7eb77a98c.png ../../../_images/863719eb5f1d085bd96b429f803b13256a359e9fbc5ece2c9194848b27572139.png ../../../_images/45cf4948b7860da054dee10a1df059bfa647c9259b362fca6a51d780f2637d50.png ../../../_images/46da8d38eeda99e53a61a7f810951d8c6ccbe1a4a0f56fd8515302e1650c630a.png ../../../_images/d491c183438f2d9ce0bfebe4bd757f79e4c520f0545e7d3fbb951d0bffe1734b.png ../../../_images/68fea3898a74ccd183efe819166b639468682ea74a2b688b7d312a04415b786e.png ../../../_images/e9827600a6498bd2450f3121a23c9f2a70c1dd63cba5a7061c610a9cc17f5fda.png ../../../_images/cf06759b89cbb1685e9a3b01dc1a2f23c7bea2687a0341b1ead2029fdd162964.png ../../../_images/cd93eec21f6afd275430a9448737f45068c82a43e34be00a4d3dbd46f4acbd14.png ../../../_images/7797315cee822b55e76caeb08c837f070b587ac16bffaf27964aa960db926c6c.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/37a0637e67ea442fd392a41868c9b0afb78e4e86eeeb4816ca0b5eac948be8ba.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=209459
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/0460b5b4b0843a1ef5c882a8bd21f40adb78e65f502988d68c3f3be61e1ed9af.png