from pathlib import Path
import kete
import numpy as np
from astropy.io import fits
from astropy.wcs import WCS
import skyloc as sloc
sloc.set_log_level("INFO") # "DEBUG" = verbose, "INFO" = normal, "WARNING" = quietLocating SSOs in observed images (ground station)
(Pre-requisite: 00-Quickstart.ipynb)
This is a special guide to find all known SSOs inside real astrometric FITS images (data from a ground station, SRO) and builds their ephemerides. It demonstrates three accuracy/speed trade-offs:
- Option 1 (Crude but fast) — a single fast N-body pass (~1” order accuracy, often enough).
- Option 2 (Higher accuracy) — high-accuracy options for (≪ 1” order accuracy).
- One can first filter objects that are likely within the FoV by Opt1 (fast), and then refine their positions by Opt2 (slow).
- Option 3 (1 and then 2) — in one convenience call,
sloc.locator_twice.
It then cross-checks the crude vs. refined results and overlays the detections on the image.
Prerequisite:
import skyloc as slocrequires theketebackend (pip install skyloc[kete]).
# Download the orbit information file from JPL SBDB
# ~ 4-10min for the first time, ~10s for subsequent runs.
orb, m_ng = sloc.fetch_orb(
output="../../../workspace/__Database/data_general/orb_sbdb-2026-04-24.parq",
update_output=999, # days - if output's last-modified is older than this, it will be updated
# filters=[
# ("kind", "not in", ("au")),
# ("kind", "in", ("cu", "cn")),
# ("condition_code", "in", ["0", "1"]),
# ]
)
# orb = orb.loc[orb["desig"] != "2025 N1"]2026-06-11T01:30:53.96+0900 [INFO] skyloc.query: Loaded 1492926 objects (60 columns)
1. Case of Observed Data
This is an example usage when you already have observational data (including WCS and exposure information)
observatory = (37.071667, 240.58861, 1.400) # lat, lon in deg, height in km
# Say your FITS files are here:
fitspaths = list(Path("testdata").glob("*.fits"))
hdus = {}
wcss = {}
fovs = []
for fpath in fitspaths:
hdul = fits.open(fpath)
hdu = hdul[0]
hdus[fpath.stem] = hdu # Say you save the data HDU only
# This FITS has JD at the *end* of the exposure, so we need to adjust it:
jd_mid = hdu.header["JD"] - float(hdu.header["EXPTIME"]) / 86400 / 2
wcs = WCS(hdu.header)
wcss[fpath.stem] = wcs
# Convert to kete-understandable observer state vector
observer = kete.spice.earth_pos_to_ecliptic(
jd_mid, *observatory, name=fpath.stem
)
# Since "earth_pos_to_ecliptic" returns proper Sun-centered observer,
# there is no need to use sloc.fov.make_rect_fov.
# That function will be useful when you specify an observer that is not
# Sun-centered. Thus, just use kete's RectangleFOV.from_wcs:
fovs.append(kete.fov.RectangleFOV.from_wcs(wcs, observer))
# some convenience for FOVs...
fovs = sloc.FOVCollection(fovs)
fovsFOVCollection with 1 FOVs
Digression: Example usage of FOVCollection
You can run each line of the code below, to see how the FOVCollection object can be used (it basically is a wrapper around kete’s FOVList, but is slightly more useful).
# FOVCollection will be very convenient when working with a lot of FOVs.
# You can access by:
_fov = fovs[0]
# or
_fov = fovs["oph_003_20250715061809_wcs"]
# also
print(fovs.fov_jds_by_desig())
# Also save as fovs.save("test.bin") and load with fovs = FOVCollection.load("test.bin")
# mask by filenames:
filenames = [
"oph_003_20250715061809_wcs",
"oph_004_20250715061809_wcs",
"oph_005_20250715061809_wcs",
]
print(fovs.mask_by_desig(filenames))
# you can use
print(fovs[fovs.mask_by_desig(filenames)])[2460871.76208333]
[ True]
[GenericRectangle(pointing=Vector([-0.259881393334, -0.887721372535, 0.380016349838], Ecliptic), observer=State(desig="oph_003_20250715061809_wcs", jd=2460871.7620833335, pos=[0.39189681098679247, -0.9378206039626024, 9.075946481989258e-5], vel=[0.01580798729092634, 0.006554231878741213, 1.8375394994441517e-6], frame=Ecliptic, center_id=10), lon_width=3.3763728873296674, lat_width=3.377464375939519)]
Option 1: Simple, one-time integration
Run N-body integrator with options that are fast but slightly less accurate.
# === 1.5M objs: ~35s on MBP 14" [2024, macOS 26.5, M4Pro(8P+4E/G20c/N16c/48G)]
# Initialize
sl1 = sloc.SSOLocator(fovs=fovs, orb=orb, non_gravs=False)
# ^^^^^^^^^^^^^^^
# Automatically use non-gravitational accelerations if parameters are available
# N-body propagate to mean JD of FOVs
# (later N-body simulations will be done *from* this JD0)
sl1.propagate_n_body(include_asteroids=False, jd0=np.mean)
# Check which FOVs contain which objects. dt_limit: 3 days (i.e., simple
# interpolation is used within 3 days and skips full N-body propagation)
sl1.fov_state_check(include_asteroids=False, dt_limit=3.)
fovc_hasobj1 = sl1.fovc_hasobj
orb_infov1 = sl1.orb.loc[sl1.orb_infov_mask].copy()
print(f"Number of FOVs with objects: {fovc_hasobj1.shape[0]} out of {len(fovs)}")
print(f"Number of objects in FOVs : {orb_infov1.shape[0]}")2026-06-11T01:31:31.13+0900 [INFO] skyloc.core: Propagated 1492921 states to JD 2460871.76
2026-06-11T01:31:31.35+0900 [INFO] skyloc.core: FOV check: 176 objects in 1 FOVs
Number of FOVs with objects: 1 out of 1
Number of objects in FOVs : 176
Option 2: Higher Accuracy
In case you need ≪1” accuracy, you can turn on these options:
sl2 = sloc.SSOLocator(fovs=fovs, orb=orb, non_gravs=True)
# ^^^^
sl2.propagate_n_body(include_asteroids=True)
# ^^^^
# include the major asteroids as perturbers to propagate to JD0
sl2.fov_state_check(include_asteroids=True)
# ^^^^
# do same for propagating to FoV time from JD0A more efficient approach is to run a second round based on sl1:
sl2 = sloc.SSOLocator(
fovs=fovc_hasobj1,
orb=orb_infov1,
non_gravs=False
)
# on MBP 14" [2024, macOS 15.2, M4Pro(8P+4E/G20c/N16c/48G)]
# ~100k objects in orb & 1500 FOVs. (states retrieved ~20 days after jd0)
sl2.propagate_n_body(include_asteroids=True, jd0=np.mean) # ~ 1s only
sl2.fov_state_check(include_asteroids=True, dt_limit=0.1) # ~10s for dt_limit=0.5, 15s for 0.25, 25s for 0.1
sl2.calc_ephems(add_jds=True, add_obsid=True, drop_obsindex=True) # ~ 10s for ~800k rows
# If you want the exact (non-compacted) values in ephemeris, you can run:
# sl2.calc_ephems(compact=False)
# Default compaction dtypes are here: print(sloc.EPH_DTYPES_BASE)
fovc_hasobj2 = sl2.fovc_hasobj
orb_infov2 = sl2.orb.loc[sl2.orb_infov_mask].copy()2026-06-11T01:31:31.41+0900 [INFO] skyloc.core: Propagated 176 states to JD 2460871.76
2026-06-11T01:31:31.42+0900 [INFO] skyloc.core: FOV check: 176 objects in 1 FOVs
Option 3: Same as Option 2, but using utility function
In many cases, you will run sl1 and sl2. That means you can simplify the lines of code into one utility function, as in sloc.locator_twice:
# Total ~36s for 1.5M objects
# Two steps in one function:
sl1, sl2 = sloc.locator_twice(
fovs=fovs,
orb=orb,
include_asteroids=(False, True),
dt_limit=(3, 0.1),
add_obsid=True,
drop_obsindex=True,
add_jds=True
)
sl2.eph2026-06-11T01:32:08.44+0900 [INFO] skyloc.core: Propagated 1492921 states to JD 2460871.76
2026-06-11T01:32:08.63+0900 [INFO] skyloc.core: FOV check: 176 objects in 1 FOVs
2026-06-11T01:32:08.67+0900 [INFO] skyloc.core: Propagated 176 states to JD 2460871.76
2026-06-11T01:32:08.67+0900 [INFO] skyloc.core: FOV check: 176 objects in 1 FOVs
| desig | alpha | r_hel | r_obs | hel_ecl_lon | hel_ecl_lat | obs_ecl_lon | obs_ecl_lat | glx_lon | glx_lat | ... | dec | racosdec_rate | dec_rate | sky_motion | sky_motion_pa | sun_target_pa | vmag | jd_tdb | jd_utc | obsid | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 17006 | 19.912742 | 2.111094 | 1.266470 | -89.030972 | 12.942826 | -107.694086 | 21.918111 | 18.116171 | 25.501743 | ... | -0.520766 | -0.145353 | -0.264841 | 0.302106 | -151.240632 | 120.640527 | 16.492867 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 1 | 5280 | 19.778067 | 2.102829 | 1.252984 | -88.741195 | 12.510030 | -107.283223 | 21.312580 | 17.674891 | 24.907475 | ... | -1.167619 | -0.096851 | -0.215985 | 0.236706 | -155.847782 | 120.229881 | 16.946845 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 2 | 7889 | 24.702241 | 1.691054 | 0.805780 | -83.467525 | 10.809762 | -105.898612 | 23.171658 | 20.116153 | 24.484233 | ... | 0.533848 | -0.992619 | -1.510819 | 1.807725 | -146.694798 | 122.507311 | 17.056176 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 3 | 15356 | 17.496673 | 2.377973 | 1.545491 | -90.914459 | 13.953075 | -107.380680 | 21.774341 | 18.100212 | 25.177577 | ... | -0.698369 | -0.265575 | -0.357213 | 0.445119 | -143.370523 | 120.623118 | 17.376145 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 4 | 18955 | 14.714640 | 2.731988 | 1.899730 | -91.522660 | 15.224325 | -105.224593 | 22.184718 | 19.402587 | 23.516823 | ... | -0.513819 | -0.249765 | -0.106083 | 0.271360 | -113.012389 | 121.862202 | 17.782897 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 171 | 2016 LH89 | 1.068238 | 37.587906 | 36.845148 | -103.801526 | 23.560530 | -104.830759 | 24.065020 | 21.441944 | 23.942650 | ... | 1.319096 | -0.043458 | -0.013044 | 0.045374 | -106.707360 | 123.818007 | 24.690468 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 172 | 2021 QV102 | 11.003957 | 3.684524 | 2.882973 | -95.791831 | 16.980895 | -106.229057 | 21.914378 | 18.717871 | 24.257015 | ... | -0.682199 | -0.313528 | -0.114352 | 0.333731 | -110.038293 | 121.192945 | 24.697203 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 173 | 2016 LN90 | 0.985279 | 40.411130 | 39.663387 | -105.079301 | 20.318159 | -106.040571 | 20.718490 | 17.603789 | 23.605820 | ... | -1.890169 | -0.039708 | -0.009270 | 0.040776 | -103.140035 | 120.118016 | 24.929332 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 174 | 2021 PT6 | 12.094854 | 3.417197 | 2.619938 | -96.349602 | 15.742334 | -107.961067 | 20.722267 | 16.794744 | 25.244113 | ... | -1.677412 | -0.423801 | -0.126026 | 0.442142 | -106.560922 | 119.446230 | 26.725515 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 175 | 2018 V2 | 2.526705 | 15.991438 | 15.243710 | -104.119408 | 20.465627 | -106.579994 | 21.517790 | 18.174664 | 24.393286 | ... | -1.039646 | -0.148602 | -0.023134 | 0.150392 | -98.848499 | 120.682098 | 34.263076 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
176 rows × 21 columns
eph = sl2.eph
eph = eph.loc[eph["vmag"] < 19].copy()
eph
# Save nightly ephemeris to a file by, e.g.,
# eph.to_parquet("eph_<DATE>_{orb['soln_date'].max()}.parq", index=False)| desig | alpha | r_hel | r_obs | hel_ecl_lon | hel_ecl_lat | obs_ecl_lon | obs_ecl_lat | glx_lon | glx_lat | ... | dec | racosdec_rate | dec_rate | sky_motion | sky_motion_pa | sun_target_pa | vmag | jd_tdb | jd_utc | obsid | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 17006 | 19.912742 | 2.111094 | 1.266470 | -89.030972 | 12.942826 | -107.694086 | 21.918111 | 18.116171 | 25.501743 | ... | -0.520766 | -0.145353 | -0.264841 | 0.302106 | -151.240632 | 120.640527 | 16.492867 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 1 | 5280 | 19.778067 | 2.102829 | 1.252984 | -88.741195 | 12.510030 | -107.283223 | 21.312580 | 17.674891 | 24.907475 | ... | -1.167619 | -0.096851 | -0.215985 | 0.236706 | -155.847782 | 120.229881 | 16.946845 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 2 | 7889 | 24.702241 | 1.691054 | 0.805780 | -83.467525 | 10.809762 | -105.898612 | 23.171658 | 20.116153 | 24.484233 | ... | 0.533848 | -0.992619 | -1.510819 | 1.807725 | -146.694798 | 122.507311 | 17.056176 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 3 | 15356 | 17.496673 | 2.377973 | 1.545491 | -90.914459 | 13.953075 | -107.380680 | 21.774341 | 18.100212 | 25.177577 | ... | -0.698369 | -0.265575 | -0.357213 | 0.445119 | -143.370523 | 120.623118 | 17.376145 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 4 | 18955 | 14.714640 | 2.731988 | 1.899730 | -91.522660 | 15.224325 | -105.224593 | 22.184718 | 19.402587 | 23.516823 | ... | -0.513819 | -0.249765 | -0.106083 | 0.271360 | -113.012389 | 121.862202 | 17.782897 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 5 | 46576 | 16.648102 | 2.469843 | 1.636653 | -91.074779 | 14.226900 | -106.700988 | 21.766214 | 18.373732 | 24.597116 | ... | -0.780027 | -0.249582 | -0.300540 | 0.390661 | -140.292236 | 120.870081 | 18.215027 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 6 | 8168 | 14.327223 | 2.840246 | 2.017675 | -91.988603 | 16.570370 | -105.259177 | 23.666712 | 20.871106 | 24.143598 | ... | 0.963379 | -0.344069 | -0.076861 | 0.352549 | -102.592549 | 123.249448 | 18.374847 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 7 | 33647 | 17.059882 | 2.358620 | 1.510327 | -89.560518 | 13.520114 | -105.438337 | 21.409770 | 18.543475 | 23.379966 | ... | -1.263593 | -0.215149 | -0.199360 | 0.293315 | -132.818616 | 121.023978 | 18.524114 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 8 | 40096 | 14.531976 | 2.801069 | 1.977223 | -92.247153 | 15.761275 | -105.822336 | 22.629061 | 19.601588 | 24.202168 | ... | -0.013171 | -0.266893 | -0.310134 | 0.409163 | -139.285614 | 122.032733 | 18.577712 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
| 9 | 121225 | 16.137678 | 2.535639 | 1.703341 | -90.607109 | 15.561787 | -105.517002 | 23.535146 | 20.635577 | 24.307900 | ... | 0.857490 | -0.261459 | -0.111257 | 0.284145 | -113.050891 | 123.011404 | 18.771906 | 2.460872e+06 | 2.460872e+06 | oph_003_20250715061809_wcs |
10 rows × 21 columns
import numpy as np
from IPython.core.interactiveshell import InteractiveShell
from matplotlib import pyplot as plt
from astropy.nddata import Cutout2D
%config InlineBackend.figure_format = 'retina'
# %matplotlib notebook
InteractiveShell.ast_node_interactivity = 'last_expr'
# We need to do it in a separate cell. See:
# https://github.com/jupyter/notebook/issues/3385
plt.style.use('default')
plt.rcParams.update({
'font.family': 'latin modern math', 'font.size':12, 'mathtext.fontset':'stix',
'axes.formatter.use_mathtext': True, 'axes.formatter.limits': (-4, 4),
'axes.grid': False, 'grid.color': 'gray', 'grid.linewidth': 0.5,
'xtick.top': True, 'ytick.right': True,
'xtick.direction': 'inout', 'ytick.direction': 'inout',
'xtick.minor.size': 2.0, 'ytick.minor.size': 2.0, # default 2.0
'xtick.major.size': 4.0, 'ytick.major.size': 4.0, # default 3.5
'xtick.minor.visible': True, 'ytick.minor.visible': True
})
testid = fitspaths[0].stem
xypos, infov = sloc.all_world2pix_infov(wcss[testid], eph[["ra", "dec"]], 0)
eph["x"] = xypos[:, 0]
eph["y"] = xypos[:, 1]
eph["infov"] = infov
nobj = np.sum(infov)
nrow = 3
ncol = nobj // nrow + 1 if nobj % nrow else nobj // nrow
fig, axs = plt.subplots(nrow, ncol, figsize=(2.2*ncol, 2.2*nrow), layout="constrained", gridspec_kw=None, sharex=False, sharey=False)
for i, row in eph.iterrows():
if not row["infov"]:
continue
cut = Cutout2D(
hdus[testid].data,
(row["x"], row["y"]),
size=(25, 25),
mode='partial',
fill_value=10
)
ax = axs.flat[i]
ax.imshow(
cut.data,
origin='lower',
vmin=np.percentile(cut.data, 20),
vmax=np.percentile(cut.data, 90)
)
ax.set(
title=f"{row['desig']}\n(V={row['vmag']:.1f})",
)
from astropy.visualization import ZScaleInterval, ImageNormalize, LinearStretch
from photutils.aperture import CircularAperture
def znorm(image, stretch=LinearStretch(), **kwargs):
return ImageNormalize(image, interval=ZScaleInterval(**kwargs), stretch=stretch)
def zimshow(ax, image, stretch=LinearStretch(), cmap=None, **kwargs):
return ax.imshow(image, norm=znorm(image, stretch=stretch, **kwargs), origin='lower', cmap=cmap)
fig, axs = plt.subplots(1, 1, figsize=(8, 5), layout="constrained", gridspec_kw=None, sharex=False, sharey=False)
zimshow(axs, hdus[testid].data, stretch=LinearStretch())
aps = CircularAperture(eph[["x", "y"]], r=10)
aps.plot(axs, color='r', lw=1.5)
for i, row in eph.iterrows():
if not row["infov"]:
continue
axs.text(
row["x"],
row["y"],
f"{row['desig']}\n(V={row['vmag']:.1f})",
color='k',
fontsize=8,
ha='center',
va='bottom'
)
plt.show();WARNING: AstropyDeprecationWarning: Passing 'ax' positionally to 'plot' is deprecated as of version 3.0 and will be removed in version 4.0. Pass it as a keyword argument instead (e.g., ax=...). [warnings]

sl1.calc_ephems(add_obsid=True, drop_obsindex=False, add_jds=True)from astropy.coordinates import SkyCoord
coo1 = SkyCoord(sl1.eph["ra"], sl1.eph["dec"], frame="icrs", unit="deg")
coo2 = SkyCoord(sl2.eph["ra"], sl2.eph["dec"], frame="icrs", unit="deg")
fig, axs = plt.subplots(1, 1, figsize=(8, 5), layout="constrained", gridspec_kw=None, sharex=False, sharey=False)
#axs[0].
axs.hist(1000*coo1.separation(coo2).to_value("arcsec"))
axs.set(
xlabel="Separation (mas)",
ylabel="Count",
title="Separation between crude and refined N-body simulations"
)
plt.show();
Note that the two cases show only < 0.02 mas (Milli-arcsec) differences in sky coordinates. Exclusion of massive asteroids and increasing two-body approximation time range (dt_limit) can easily increase the computation speed by ~100s times, while achieving << 1-arcsec (<< 1-mas for vast majority of the cases) accuracy.
Fast WCS
In case your WCS is Tan-SIP style, you may use FastTanSipWCS for faster WCS calculation:
w_a = WCS(hdus["oph_003_20250715061809_wcs"].header)
w_f = sloc.FastTanSipWCS(hdus["oph_003_20250715061809_wcs"].header)
# Warmup numba:
w_f.all_world2pix(eph["ra"], eph["dec"], 0)
# timing
print("Timing FastTanSipWCS:")
%timeit -n 100 -r 100 w_f.all_world2pix(eph["ra"], eph["dec"], 0)
print("Timing Astropy WCS:")
%timeit -n 100 -r 100 w_a.all_world2pix(eph[["ra", "dec"]], 0)Timing FastTanSipWCS:
8.63 μs ± 434 ns per loop (mean ± std. dev. of 100 runs, 100 loops each)
Timing Astropy WCS:
107 μs ± 8.72 μs per loop (mean ± std. dev. of 100 runs, 100 loops each)