Worked Example — SoFT: Basic usage¶
Track a feature moving across a sequence of synthetic images using WaLSAlib.SoFT.
The example generates five 100 × 100 pixel FITS images containing a Gaussian feature moving diagonally, adds Gaussian noise, and measures the feature’s trajectory.
Tracking a moving feature
The feature has an amplitude of 100 and a Gaussian width of 5 pixels, and moves by five pixels in each coordinate per frame. The noise standard deviation is 5. Tracking uses a threshold of 20, a minimum size of 10 pixels, and dx=dt=1. The noise varies between runs.
Run the example¶
Save the Python source below as soft-basic-usage.py and run it in a working directory:
The script imports the module with from WaLSAlib import SoFT and runs SoFT.track_all. It creates temp_data/ with the input images, intermediate masks, and dataframe.json, then plots the tracked trajectory. Existing tracking outputs in that directory are replaced on each run.
The X and Y columns contain the feature positions across the sequence. See FITS sequence tracking for input preparation and outputs for the table’s column definitions. For observations, set the threshold, minimum size, pixel scale, and cadence to suit the data.
Source Code¶
View Python code
# Based on the SoFT basic tracking example by Michele Berretti and contributors.
# Source: https://github.com/mib-unitn/SoFT/blob/4de0a50844a655f427a7f9791e12ce32c953e6c4/examples/plot_basic_usage.py
# Original copyright and GPLv3 terms apply; see GPL-3.0.txt.
"""Detect and track a moving feature using WaLSAlib.SoFT."""
import numpy as np
import matplotlib.pyplot as plt
from WaLSAlib import SoFT
import os
import shutil
import astropy.io.fits
def main():
# Create a temporary directory for data
data_dir = "temp_data" + os.sep
os.makedirs(data_dir, exist_ok=True)
os.makedirs(os.path.join(data_dir, "00-data"), exist_ok=True)
os.makedirs(os.path.join(data_dir, "01-mask"), exist_ok=True)
os.makedirs(os.path.join(data_dir, "02-id"), exist_ok=True)
os.makedirs(os.path.join(data_dir, "03-assoc"), exist_ok=True)
# Generate synthetic frames
# We'll create a moving Gaussian blob
nx, ny = 100, 100
n_frames = 5
x, y = np.meshgrid(np.arange(nx), np.arange(ny))
for t in range(n_frames):
# Blob moves along x=y
cx, cy = 20 + t * 5, 20 + t * 5
sigma = 5
blob = 100 * np.exp(-((x - cx)**2 + (y - cy)**2) / (2 * sigma**2))
# Add some noise
noise = np.random.normal(0, 5, (ny, nx))
frame = blob + noise
filename = os.path.join(data_dir, "00-data", f"{t:04d}.fits")
astropy.io.fits.writeto(filename, frame, overwrite=True)
# Plot the first and last frame for visualization
if t == 0 or t == n_frames - 1:
plt.figure()
plt.title(f"Frame {t}")
plt.imshow(frame, origin='lower', cmap='gray')
plt.colorbar()
plt.show()
# Set tracking parameters
l_thr = 20 # Low threshold
min_size = 10
dx = 1.0
dt = 1.0
sign = "both"
separation = True
verbose = True
cores = 1
# Run tracking
print("Running tracking...")
SoFT.track_all(data_dir, cores, l_thr, min_size, dx, dt, sign, separation, verbose)
# Check results
# Read the resulting dataframe
import pandas as pd
df_path = os.path.join(data_dir, "dataframe.json")
if os.path.exists(df_path):
df = pd.read_json(df_path)
print("Tracking results:")
print(df.head())
# Plot trajectory
plt.figure()
plt.title("Tracked Trajectory")
for _, row in df.iterrows():
plt.plot(row['X'], row['Y'], 'o-', label=f"Label {row['label']}")
plt.legend()
plt.xlabel("X pixel")
plt.ylabel("Y pixel")
plt.show()
else:
print("No dataframe found.")
# Cleanup
# shutil.rmtree(data_dir)
if __name__ == "__main__":
main()
Download Python source · Original SoFT example · GPLv3 license
Based on the example by Michele Berretti and contributors. Cite Berretti et al. (2025) and WaLSAlib when using SoFT in research.