304.2. Cross match queries#
304.2. Cross match queries¶
For the Rubin Science Platform at data.lsst.cloud.
Data Release: Prompt Products
Container Size: Large
LSST Science Pipelines version: r30.0.11
Last verified to run: 2026-11-24
Repository: github.com/lsst/tutorial-notebooks
DOI: 10.11578/rubin/dc.20250909.20
Learning objective: Cross match to a list of extragalactic transients and retrieve light curves.
LSST data products: ppdb.DiaForcedSource, ppdb.DiaObject
Packages: lsst.rsp
Credit: Originally developed by the Rubin Community Science team. Please consider acknowledging them if this notebook is used for the preparation of journal articles, software releases, or other notebooks.
Get Support: Everyone is encouraged to ask questions or raise issues in the Support Category of the Rubin Community Forum. Rubin staff will respond to all questions posted there.
1. Introduction¶
This tutorial demonstrates how to make efficient queries for the common question of "does LSST have difference-image light curves at these sky coordinates?"
Do not query source tables by coordinate.
Queries by coordinate on the DiaSource or DiaForcedSource table are very inefficient, because these tables contain measurements on many images at the exact same coordinates.
It is more efficient to do the spatial cross-match with DiaObject once, and then retrieve fluxes for successful matches based on the diaObjectId.
Avoid putting asynchronous queries into for loops.
Although it is possible loop over a set of RA/Dec and make a spatial cross-match query for each coordinate, this should be avoided.
TAP queries have a rate limit to prevent the shared system from being overloaded by a single user with many queries executing simultaneously.
The correct method is to upload a table of coordinates and cross-match using a TAP table join.
This notebook demonstrates how to upload a table of coordinates and use the TAP service to cross-match to the DiaObject table and then retrieve light curves for successful cross-matches.
Related tutorials: The 300-level tutorial on transient light curves. The 200-level tutorials on the DiaObject, DiaSource, and DiaForcedSource catalogs. The 100-level tutorials on catalog access with TAP and ADQL query statements.
1.1. Import packages¶
Import numpy, a fundamental package for scientific computing with arrays in Python
(numpy.org), and
matplotlib, a comprehensive library for data visualization
(matplotlib.org;
matplotlib gallery).
From the lsst package, import modules for accessing the Table Access Protocol (TAP) service and image display functions from the LSST Science Pipelines (pipelines.lsst.io).
import matplotlib.pyplot as plt
import numpy as np
from astropy.time import Time
from astropy.table import Table
from lsst.rsp import RSPDiscovery
from lsst.utils.plotting import (get_multiband_plot_colors,
get_multiband_plot_symbols,
set_rubin_plotstyle)
1.2. Define parameters and functions¶
Create an instance of the TAP service.
discovery = RSPDiscovery("prompt")
tap_service = discovery.get_tap_client()
Define filter names, plot markers, and colors for plotting
set_rubin_plotstyle()
filter_colors = get_multiband_plot_colors()
filter_names = filter_colors.keys()
filter_symbols = get_multiband_plot_symbols()
2. Load the coordinate list¶
A list of classified supernovae that were reported to the Transient Name Server (TNS) around the time when Prompt Processing restarted in Oct 2026 has been generated for this demonstration. The file was generated on Nov 24 2026.
The TNS search query was executed by:
- setting "reported within the last" 3 months
- checking the box "Limit to classified supernovae"
- setting the Discovery Date Range to Oct 1 2026 to Nov 24 2026
Read the file into an Astropy table.
path = '/rubin/cst_repos/tutorial-notebooks-data/data/'
filename = 'ppdb_304_2_tns_search_Oct1_Nov24_2026.ecsv'
tns_table = Table.read(path + filename, format='ascii.ecsv')
Display the first five rows of the table.
tns_table[:5]
| name | ra | dec | type | disc_mjd |
|---|---|---|---|---|
| str11 | float64 | float64 | str17 | float64 |
| SN 2026akhl | 141.27888749999997 | -20.212358333333334 | SN Ia | 61363.58719 |
| SN 2026akhh | 58.99368749999999 | -17.098824999999998 | SN Ia | 61361.46206 |
| SN 2026akbo | 159.91212916666666 | 25.320422222222223 | SN Ia | 61361.25462 |
| SN 2026ajxu | 40.15348333333333 | 45.506569444444445 | SN Ia | 61359.40141 |
| SN 2026ajsm | 51.22556666666666 | -33.092130555555556 | SN Ia | 61342.860451388886 |
3. Cross-match to the DiaObject table¶
Create the query that joins the TNS search results table with the DiaObject table using a (generous) cross-match radius of 2". Only retrieve diaObjects that were first detected before Nov 24 2026, the date the input file of TNS supernovae was created.
search_radius = 2.0/3600.0
date_run = Time("2026-11-24", format="iso", scale="utc")
query = """
SELECT diao.diaObjectId, diao.ra, diao.dec, diao.nDiaSources,
ut.ra AS ut_ra, ut.dec AS ut_dec,
ut.name AS ut_name, ut.type AS ut_type, ut.disc_mjd AS ut_disc_mjd,
DISTANCE(POINT('ICRS', diao.ra, diao.dec),
POINT('ICRS', ut.ra, ut.dec)) AS distance
FROM ppdb.DiaObject AS diao
JOIN TAP_UPLOAD.ut AS ut
ON DISTANCE(POINT('ICRS', diao.ra, diao.dec),
POINT('ICRS', ut.ra, ut.dec)) < {}
WHERE diao.firstDiaSourceMjdTai < {}
""".format(search_radius, date_run.mjd)
print(query)
SELECT diao.diaObjectId, diao.ra, diao.dec, diao.nDiaSources,
ut.ra AS ut_ra, ut.dec AS ut_dec,
ut.name AS ut_name, ut.type AS ut_type, ut.disc_mjd AS ut_disc_mjd,
DISTANCE(POINT('ICRS', diao.ra, diao.dec),
POINT('ICRS', ut.ra, ut.dec)) AS distance
FROM ppdb.DiaObject AS diao
JOIN TAP_UPLOAD.ut AS ut
ON DISTANCE(POINT('ICRS', diao.ra, diao.dec),
POINT('ICRS', ut.ra, ut.dec)) < 0.0005555555555555556
WHERE diao.firstDiaSourceMjdTai < 61368.0
Execute the query, uploading the table to the TAP service.
job = tap_service.submit_job(query, uploads={"ut": tns_table})
job.run()
job.wait(phases=['COMPLETED', 'ERROR'])
print('Job phase is', job.phase)
if job.phase == 'ERROR':
job.raise_if_error()
Job phase is COMPLETED
Retrieve the query results as an Astropy table. Assert that the number of rows should be 12.
assert job.phase == 'COMPLETED'
diao_table = job.fetch_result().to_table()
assert len(diao_table) == 12
print(len(diao_table))
12
Option to display the results table.
# diao_table
3.1. Check for duplicate matches¶
Get the number of unique matches between the SN in the table and rows of the DiaObject table using the number of unique elements of the ut_name (the SN name) column.
unique_matches, count_matches = np.unique(diao_table['ut_name'], return_counts=True)
print(f"Of the {len(diao_table)} cross-matches returned, {len(unique_matches)} are unique.")
Of the 12 cross-matches returned, 12 are unique.
For any SN that had more than one cross-match result to the DiaObject table, the following cell would print its name and the number of matches, and also the identifier, number of diaSources, and the sky distances for each match.
When a cross-match yields duplicates, the real astrophyscial transients are usually the closest diaObject or the one with lots of detections (as spurious artifacts are often only detected once).
This is not needed for this sample, as there were no duplicates.
# tx = np.where(count_matches > 1)[0]
# for x in tx:
# print(' ')
# print(unique_matches[x], count_matches[x])
# ix = np.where(diao_table['ut_name'] == unique_matches[x])[0]
# for i in ix:
# print(diao_table['diaObjectId'][i],
# diao_table['nDiaSources'][i],
# np.round(diao_table['distance'][i], 6))
# del ix
# del tx
del unique_matches, count_matches
3.2. Histogram of nDiaSource¶
Plot a histogram of the number of detections (nDiaSources) per object.
fig = plt.figure(figsize=(10, 4))
plt.hist(diao_table['nDiaSources'], bins=30)
plt.xlabel('Number of detections per object', fontsize=12)
plt.ylabel('Number of objects', fontsize=12)
plt.title('Distribution of the number of detections in any filter')
plt.show()
Figure 1: A histogram of the number of 5$\sigma$ difference-image detections per cross-matched
diaObject.
4. Retrieve all light curves¶
Create and execute a query to retrieve the light curves for all cross-matched objects from the DiaSource table.
id_array = np.asarray(diao_table['diaObjectId'], dtype='long')
id_list = "(" + ", ".join(str(value) for value in id_array) + ")"
query = """SELECT diaObjectId, psfFlux, psfFluxErr, band, midpointMjdTai
FROM ppdb.DiaSource
WHERE diaObjectId IN {}""".format(id_list)
job = tap_service.submit_job(query)
job.run()
job.wait(phases=['COMPLETED', 'ERROR'])
print('Job phase is', job.phase)
if job.phase == 'ERROR':
job.raise_if_error()
assert job.phase == 'COMPLETED'
dias_fluxes = job.fetch_result().to_table()
Job phase is COMPLETED
Similar to the query above, but use the DiaForcedSource table.
query = """SELECT diaObjectId, psfFlux, psfFluxErr, band, midpointMjdTai
FROM ppdb.DiaForcedSource
WHERE diaObjectId IN {}""".format(id_list)
job = tap_service.submit_job(query)
job.run()
job.wait(phases=['COMPLETED', 'ERROR'])
print('Job phase is', job.phase)
if job.phase == 'ERROR':
job.raise_if_error()
assert job.phase == 'COMPLETED'
diafs_fluxes = job.fetch_result().to_table()
Job phase is COMPLETED
4.1. Visualize the light curves¶
For SN 2026ahhp, plot the lightcurve with both the detections (diaSources) and forced flux measurements.
i = np.where(diao_table['ut_name'] == 'SN 2026ahhp')[0]
dsx = np.where(dias_fluxes['diaObjectId'] == diao_table['diaObjectId'][i])[0]
dfsx = np.where(diafs_fluxes['diaObjectId'] == diao_table['diaObjectId'][i])[0]
fig = plt.figure(figsize=(10, 4))
for f, filt in enumerate(filter_names):
fx = np.where(dias_fluxes['band'][dsx] == filt)[0]
plt.errorbar(dias_fluxes['midpointMjdTai'][dsx[fx]],
dias_fluxes['psfFlux'][dsx[fx]],
yerr=dias_fluxes['psfFluxErr'][dsx[fx]],
fmt=filter_symbols[filt], ms=10, mew=1,
mec=filter_colors[filt], ecolor=filter_colors[filt],
alpha=0.8, color='none', label=filt)
del fx
fx = np.where(diafs_fluxes['band'][dfsx] == filt)[0]
if len(fx) > 0:
plt.plot(diafs_fluxes['midpointMjdTai'][dfsx[fx]],
diafs_fluxes['psfFlux'][dfsx[fx]],
filter_symbols[filt], ms=10, mew=0,
color=filter_colors[filt], alpha=0.5)
del fx
plt.xlabel('MJD', fontsize=12)
plt.ylabel('Flux (nJy)', fontsize=12)
plt.legend(loc='best', ncol=3)
plt.title(diao_table['ut_name'][i[0]])
plt.show()
Figure 2: The lightcurve for the diaObject cross-matched to SN 2026ahhp. The SNR>5 detected diaSources are shown as empty symbols (as in the legend), and the forced fluxes as solid transparent symbols.
Option to create lightcurves for all matched diaObjects.
# for i in range(len(diao_table)):
# dsx = np.where(dias_fluxes['diaObjectId'] == diao_table['diaObjectId'][i])[0]
# dfsx = np.where(diafs_fluxes['diaObjectId'] == diao_table['diaObjectId'][i])[0]
# fig = plt.figure(figsize=(10, 2))
# for f, filt in enumerate(filter_names):
# fx = np.where(dias_fluxes['band'][dsx] == filt)[0]
# plt.errorbar(dias_fluxes['midpointMjdTai'][dsx[fx]],
# dias_fluxes['psfFlux'][dsx[fx]],
# yerr=dias_fluxes['psfFluxErr'][dsx[fx]],
# fmt=filter_symbols[filt], ms=10, mew=1,
# mec=filter_colors[filt], ecolor=filter_colors[filt],
# alpha=0.8, color='none', label=filt)
# del fx
# fx = np.where(diafs_fluxes['band'][dfsx] == filt)[0]
# if len(fx) > 0:
# plt.plot(diafs_fluxes['midpointMjdTai'][dfsx[fx]],
# diafs_fluxes['psfFlux'][dfsx[fx]],
# filter_symbols[filt], ms=10, mew=0,
# color=filter_colors[filt], alpha=0.5)
# del fx
# plt.xlabel('MJD', fontsize=12)
# plt.ylabel('Flux (nJy)', fontsize=12)
# plt.legend(loc='best', ncol=3)
# plt.title(diao_table['ut_name'][i])
# plt.show()