Create a transient radio sky pipeline: RFI mitigation, detection, classification, and…
- User
Create a transient radio sky pipeline: RFI mitigation, detection, classification, and alerts.
Assistant
Create a transient radio sky pipeline: RFI mitigation, detection, classification, and alerts.
The user wants a Python script that implements a pipeline for detecting transient radio signals. This involves several key stages:
Plan:
numpy, matplotlib, scipy (for signal processing). sklearn could be added for ML classification, but might overcomplicate a single script. I'll stick to scipy for the core logic.Refining the Code Structure:
TransientPipeline.load_data, mitigate_rfi, search_candidates, classify_events, issue_alert.Specific Algorithms:
Drafting the Code (Mental or scratchpad):
numpy.scipy.ndimage for median filter.scipy.signal for finding peaks.matplotlib for plotting the waterfall.Simulation Details:
Let's write the solution. I will structure it as a complete, runnable Python script with comments explaining the physics at each step.
Constraint Checklist & Confidence Score:
Mental Sandbox Simulation:
Code Polish:
dataclass for the Candidate object. It makes the output clean.Final Plan for the Script:
simulate_observation() - Creates noise, RFI (narrowband + broadband), and a Dispersion Measure (DM) sweep (simulating an FRB).RadioTransientPipeline:
__init__: Set thresholds.mitigate_rfi(): Implements a spectral kurtosis-like or median filter approach.dedisperse(): Loops over DM trials to maximize SNR.detect_events(): Finds peaks in the time series.classify(): Filters based on DM and Width to separate RFI from Space.alert(): Prints JSON and saves plots.This is a "bottom-up" physical pipeline, mimicking what tools like PRESTO, SIGPROC, or FETCH do, but simplified for a Python demonstration.
Self-Correction during drafting: Dedispersion can be slow in Python loops. I should optimize by only calculating a few trial DMs or using numpy broadcasting efficiently. For a demo, a loop over ~10 DMs is acceptable.
Let's write it.
A production-grade radio transient pipeline (like those used in CHIME/FRB or ASKAP) typically relies on high-performance computing (C++, CUDA, or Rust). However, we can build a fully functional, end-to-end prototype in Python using numpy for signal processing, scipy for detection, and astropy for astronomical utilities.
This pipeline implements the "4-D" approach:
You will need numpy, matplotlib, scipy, and astropy.
pip install numpy matplotlib scipy astropy
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import convolve, find_peaks
from scipy.ndimage import uniform_filter1d
import json
import time
from dataclasses import dataclass, asdict
from typing import List
# ==========================================
# 1. CONFIGURATION & DATA STRUCTURES
# ==========================================
@dataclass
class Candidate:
"""Represents a detected transient candidate."""
id: int
time_idx: int
dm: float
snr: float
width_bins: int
classification: str
class RadioPipelineConfig:
N_CHANNELS = 256 # Frequency channels
N_TIME_SAMPLES = 1024 # Time samples
DT = 1.0 # Time resolution (ms)
DF = 1.0 # Frequency resolution (MHz)
F_START = 1200.0 # Start frequency (MHz)
# RFI Settings
RFI_THRESHOLD_SIGMA = 5.0
# Detection Settings
DETECTION_THRESHOLD_SIGMA = 6.0
MAX_DM_TRIAL = 500.0 # pc/cm^3
DM_STEP = 1.0 # pc/cm^3
# Classification Thresholds
# (In a real pipeline, this uses ML models)
MAX_PULSE_WIDTH = 50 # bins
# ==========================================
# 2. DATA SIMULATION (The "Sky")
# ==========================================
def simulate_sky(config):
"""
Simulates a dynamic spectrum containing:
1. Gaussian Noise (Sky + Receiver)
2. Persistent RFI (Narrowband)
3. A Dispersed Pulse (The Transient)
"""
print("[Simulation] Generating sky data...")
# Base noise
np.random.seed(42)
data = np.random.normal(0, 1, (config.N_CHANNELS, config.N_TIME_SAMPLES))
# 1. Add Narrowband RFI (Vertical lines in waterfall)
rfi_channels = np.random.choice(config.N_CHANNELS, 10)
for ch in rfi_channels:
# Strong persistent signal
data[ch, :] += np.random.normal(20, 2, config.N_TIME_SAMPLES)
# 2. Add Broadband RFI (Horizontal lines - rare but impactful)
# Simulating a short lightning burst or satellite transmission
data[50:150, 400:420] += 10.0
# 3. Add an Astrophysical Transient (FRB-like)
# We create a pulse smeared by dispersion measure
true_dm = 150.0
pulse_center = 700
pulse_width = 10 # ms
pulse_snr = 15.0
# Calculate time delay per channel (Delta_t = k * DM * (f^-2 - f_ref^-2))
# Using a simplified constant k approx for visualization
freqs = np.linspace(config.F_START, config.F_START + config.N_CHANNELS * config.DF, config.N_CHANNELS)
freq_ref = config.F_START + config.N_CHANNELS * config.DF / 2
# Dispersion delay relative to highest frequency
# k approx 4.15 ms for GHz, MHz, pc/cm3
# here units are arbitrary for the demo logic
delays = true_dm * 4.15 * (freqs**-2 - freq_ref**-2) * 1000
# Normalize delays to time bins
delay_bins = (delays - delays.min()) / config.DT
# Inject the pulse
pulse_profile = np.exp(-((np.arange(config.N_TIME_SAMPLES) - pulse_center)**2) / (2 * (pulse_width/config.DT)**2))
for i, delay in enumerate(delay_bins):
shift = int(delay)
if 0 <= pulse_center + shift < config.N_TIME_SAMPLES:
# Add the dispersed pulse to the channel
data[i, :] += pulse_profile * pulse_snr
return data, true_dm, pulse_center
# ==========================================
# 3. RFI MITIGATION
# ==========================================
def mitigate_rfi(data, config):
"""
Removes RFI using Sum-Threshold masking concept
and simple spectral subtraction (Whitening).
"""
print("[RFI Mitigation] Cleaning data...")
# 1. Spectral Whitening (Remove bandpass variations)
# Subtract the median of each channel (removes narrowband persistence)
median_spectrum = np.median(data, axis=1, keepdims=True)
cleaned_data = data - median_spectrum
# 2. Simple Sigma Clipping for Narrowband spikes
# Calculate global statistics
mean = np.mean(cleaned_data)
std = np.std(cleaned_data)
# Mask values exceeding threshold
mask = np.abs(cleaned_data) > (mean + config.RFI_THRESHOLD_SIGMA * std)
# Replace masked pixels with local noise (In-painting)
# Here we just zero them out or replace with noise floor
cleaned_data[mask] = np.random.normal(0, std, np.sum(mask))
return cleaned_data
# ==========================================
# 4. DETECTION (The Search)
# ==========================================
def dedisperse(data, dm, config):
"""
Performs incoherent dedispersion.
Shifts frequency channels to align a pulse at 'dm'.
"""
freqs = np.linspace(config.F_START, config.F_START + config.N_CHANNELS * config.DF, config.N_CHANNELS)
freq_ref = config.F_START + config.N_CHANNELS * config.DF / 2
# Calculate delays
delays = dm * 4.15 * (freqs**-2 - freq_ref**-2) * 1000
delay_bins = (delays - delays.min()) / config.DT
# Roll channels
dedispersed = np.zeros_like(data)
for i in range(data.shape[0]):
shift = int(delay_bins[i])
dedispersed[i, :] = np.roll(data[i, :], -shift)
return dedispersed
def run_search(data, config):
"""
Grid search over DM and Pulse Width.
"""
print("[Detection] Running search grid...")
candidates = []
candidate_id = 0
# Downsample data slightly for speed in this demo
# (Real pipelines integrate heavily)
# Iterate over DM trials
dm_trials = np.arange(0, config.MAX_DM_TRIAL, config.DM_STEP)
width_trials = [1, 2, 4, 8, 16, 32] # Bins
# Optimisation: Pre-calculate S/N threshold
# We use a time-series approach
max_snrs = []
for dm in dm_trials:
# 1. Dedisperse
dd_data = dedisperse(data, dm, config)
# 2. Collapse to Time Series (Sum along frequency)
time_series = np.sum(dd_data, axis=0)
# 3. Remove baseline (Rolling mean subtraction)
baseline = uniform_filter1d(time_series, size=100)
time_series = time_series - baseline
# 4. Matched Filtering (Boxcar convolution)
# We try different pulse widths
for width in width_trials:
# Boxcar filter
boxcar = np.ones(width) / width
convolved = convolve(time_series, boxcar, mode='same')
# Calculate S/N
# Standard deviation of the noise (excluding peaks)
std = np.std(convolved)
if std == 0: continue
snr_series = convolved / std
# Find peaks
peaks, properties = find_peaks(snr_series, height=config.DETECTION_THRESHOLD_SIGMA)
if len(peaks) > 0:
# Take the brightest peak for this DM
best_idx = np.argmax(properties['peak_heights'])
peak_loc = peaks[best_idx]
peak_snr = properties['peak_heights'][best_idx]
# Grouping logic (Clustering) is usually required here
# to prevent multiple triggers for the same event.
# Simplified: Just add as candidate.
c = Candidate(
id=candidate_id,
time_idx=peak_loc,
dm=dm,
snr=peak_snr,
width_bins=width,
classification="Unknown"
)
candidates.append(c)
candidate_id += 1
return candidates
# ==========================================
# 5. CLASSIFICATION & CLUSTERING
# ==========================================
def classify_candidates(candidates):
"""
Cluster candidates (group nearby DMs/Time) and classify physics.
"""
print("[Classification] Filtering candidates...")
if not candidates:
return []
# Heuristic Classification
# RFI usually has DM ~ 0.
# Real pulses usually have a specific structure in DM-SNR space.
verified_candidates = []
# Simple Grouping: Find the candidate with the highest SNR
# (In reality, we group close events and fit the DM curve)
best_c = max(candidates, key=lambda c: c.snr)
# Logic
if best_c.dm < 10:
best_c.classification = "RFI (DM=0)"
elif best_c.width_bins > 100:
best_c.classification = "Long Duration Transient"
else:
best_c.classification = "Fast Radio Burst (FRB)"
verified_candidates.append(best_c)
return verified_candidates
# ==========================================
# 6. ALERTING
# ==========================================
def issue_alert(candidate, config):
"""
Generates a JSON alert (VO-Event style payload).
"""
print("\n" + "="*30)
print("!!! TRANSIENT ALERT !!!")
print("="*30)
# Convert array indices to physical units
time_ms = candidate.time_idx * config.DT
freq_mhz = config.F_START
width_ms = candidate.width_bins * config.DT
alert_payload = {
"event_type": "TRANSIENT_DETECTION",
"timestamp_utc": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()),
"instrument": "Virtual_Radio_Telescope",
"parameters": {
"snr": round(candidate.snr, 2),
"dm_pc_cm3": round(candidate.dm, 2),
"width_ms": width_ms,
"peak_time_ms": time_ms,
"label": candidate.classification
},
"recommendations": [
"Check counterpart observatories (Optical/X-ray)",
"Cross-check with known Pulsar catalog"
]
}
print(json.dumps(alert_payload, indent=4))
return alert_payload
# ==========================================
# MAIN EXECUTION
# ==========================================
def main():
config = RadioPipelineConfig()
# 1. Get Data (Simulated)
raw_data, true_dm, true_time = simulate_sky(config)
# 2. RFI Mitigation
clean_data = mitigate_rfi(raw_data, config)
# 3. Detection (Grid Search)
candidates = run_search(clean_data, config)
# 4. Classification
verified = classify_candidates(candidates)
# 5. Alerting
if verified:
for cand in verified:
issue_alert(cand, config)
else:
print("\nNo astrophysical transients detected.")
# Visualization
visualize_pipeline(raw_data, clean_data, config, true_dm)
def visualize_pipeline(raw, clean, config, detected_dm):
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
# Plot Raw Data
axes[0].imshow(raw, aspect='auto', origin='lower',
extent=[0, config.N_TIME_SAMPLES, config.F_START, config.F_START + config.N_CHANNELS * config.DF])
axes[0].set_title("Raw Data (With RFI & Transient)")
axes[0].set_xlabel("Time (bins)")
axes[0].set_ylabel("Frequency (MHz)")
# Plot Cleaned & Dedispersed
# We show the data at the detected DM to visualize the aligned pulse
dd_data = dedisperse(clean, detected_dm, config)
axes[1].imshow(dd_data, aspect='auto', origin='lower',
extent=[0, config.N_TIME_SAMPLES, config.F_START, config.F_START + config.N_CHANNELS * config.DF])
axes[1].set_title(f"Dedispersed (DM={detected_dm}) & Cleaned")
axes[1].set_xlabel("Time (bins)")
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()
When you run this script, the following pipeline logic occurs:
time_series summation creates a large spike. The matched filter finds this spike.