← Wind Spectral Analysis for the FAST Radio Telescope
Wind spectrum walkthrough
Simulated wind data
Pick a wind record, then watch my internship script, cal_wind.py, turn it into three power spectra one step at a time. Each step highlights the lines of the original file that run, shows the intermediate values, and plots what changed.
Everything runs in your browser. The wind records are generated from a turbulence model with a seeded random generator; no telescope data is used. The step-by-step view uses a TypeScript port of the script. Section 5 can run the original Python file itself, unmodified, for comparison.
Choose the input
Watch it run
Step 1 of 8
Read and sort the records
Variables after this step
cal_wind.py · original fileimport numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import welch
from scipy.signal.windows import hann
import os
# ================= 绘图函数 =================
def plot_psd(f, psd, color, label, title_suffix, output_path, log_x=True):
"""
绘制功率谱图并保存。
f, psd : 频率,功率谱密度数组(psd 即纵轴数据)
color, label : 曲线颜色与图例(如不需图例可传 '')
log_x : True -> 双对数坐标, False -> 横轴线性、纵轴对数
"""
plt.figure(figsize=(8, 5))
if log_x:
plt.loglog(f, psd, color, linewidth=1.2, label=label)
else:
plt.semilogy(f, psd, color, linewidth=1.2, label=label)
plt.xlabel('Frequency (Hz)', fontsize=14)
plt.ylabel('PSD ((m/s)$^2$/Hz)', fontsize=14)
plt.title(f'Device {title_suffix}', fontsize=14)
plt.tick_params(labelsize=14)
plt.grid(False)
if label:
plt.legend(fontsize=12)
plt.tight_layout()
plt.savefig(output_path, dpi=150)
plt.close()
# ================= 主程序 =================
csv_file = "simulated_winddata.csv"
df = pd.read_csv(csv_file)
# 按设备分组并按时间排序(同一设备内必须按时间先后排列)
df = df.sort_values(["dev_code", "ts"])
output_dir = "psd_figures"
os.makedirs(output_dir, exist_ok=True)
for dev_name, group in df.groupby("dev_code"):
print(f"Processing device: {dev_name}")
# ---------- 数据提取 ----------
speed = group["wind_speed"].values
dir_idx = group["wind_dir"].values
dir_deg = dir_idx * 22.5 # 风向索引转为角度(0=N, 顺时针增加)
# ---------- 动态计算采样频率 ----------
# 支持不同设备采样频率不同,但同一设备需保持固定频率
ts = group["ts"].values
dt = np.median(np.diff(ts)) # 用中位数避免异常时间间隔影响
if dt <= 0:
raise ValueError(f"Device {dev_name}: 时间戳异常,间隔非正。")
Fs = 1.0 / dt # 该设备的真实采样频率
N = len(speed)
# ---------- 风向预处理(转换为数学坐标系下的风矢量方向)----------
north_ref_deg = 0.0 # 正北为 0°
is_clockwise = True # 风向按顺时针记录
is_from_direction = True # 风向表示来向
theta = dir_deg - north_ref_deg
if is_clockwise:
theta = -theta # 顺时针转为逆时针
theta = np.deg2rad(theta)
if is_from_direction:
theta = theta + np.pi # 来向加180°得去向(风矢量方向)
# ---------- 风速矢量分解 ----------
u_east = speed * np.cos(theta)
u_north = speed * np.sin(theta)
# ---------- 平均风方向(顺风向单位向量)----------
Ue_mean = np.mean(u_east)
Un_mean = np.mean(u_north)
U_mean = np.sqrt(Ue_mean**2 + Un_mean**2)
e_along_east = Ue_mean / U_mean
e_along_north = Un_mean / U_mean
# 横风向单位向量(顺风向逆时针转90°)
e_cross_east = -e_along_north
e_cross_north = e_along_east
# ---------- 顺风向与横风向风速 ----------
u_along = u_east * e_along_east + u_north * e_along_north
u_cross = u_east * e_cross_east + u_north * e_cross_north
# ---------- 脉动风速(减去各自均值)----------
speed_p = speed - np.mean(speed)
u_along_p = u_along - np.mean(u_along)
u_cross_p = u_cross - np.mean(u_cross)
# ---------- PSD 计算参数 ----------
nperseg = 1024
nfft = 2 ** (int(np.ceil(np.log2(N))) - 1) # 与 MATLAB 的 2^(nextpow2(N)-1) 等价
win = hann(nperseg, sym=False) # 周期窗,对应 MATLAB hann(1024,'periodic')
# ---------- 单边功率谱估计 ----------
# detrend=False 对应 MATLAB pwelch 默认不去趋势(脉动数据已去整体均值)
f, PSD_speed = welch(speed_p, fs=Fs, window=win, nperseg=nperseg,
nfft=nfft, return_onesided=True, detrend=False)
_, PSD_along = welch(u_along_p, fs=Fs, window=win, nperseg=nperseg,
nfft=nfft, return_onesided=True, detrend=False)
_, PSD_cross = welch(u_cross_p, fs=Fs, window=win, nperseg=nperseg,
nfft=nfft, return_onesided=True, detrend=False)
fs_text = f"{Fs:.2f} Hz"
# ---------- 绘图(六张图:两种坐标 × 三种曲线)----------
base_name = os.path.join(output_dir, dev_name)
# 双对数图
plot_psd(f, PSD_speed, 'k', 'Raw speed',
f"{dev_name} - Raw wind (log-log, Fs={fs_text})",
f"{base_name}_speed_psd_loglog.png", log_x=True)
plot_psd(f, PSD_along, 'b', 'Along-wind',
f"{dev_name} - Along-wind (log-log, Fs={fs_text})",
f"{base_name}_along_psd_loglog.png", log_x=True)
plot_psd(f, PSD_cross, 'r', 'Cross-wind',
f"{dev_name} - Cross-wind (log-log, Fs={fs_text})",
f"{base_name}_cross_psd_loglog.png", log_x=True)
# 横轴线性、纵轴对数图
plot_psd(f, PSD_speed, 'k', 'Raw speed',
f"{dev_name} - Raw wind (linear freq, Fs={fs_text})",
f"{base_name}_speed_psd_linearlog.png", log_x=False)
plot_psd(f, PSD_along, 'b', 'Along-wind',
f"{dev_name} - Along-wind (linear freq, Fs={fs_text})",
f"{base_name}_along_psd_linearlog.png", log_x=False)
plot_psd(f, PSD_cross, 'r', 'Cross-wind',
f"{dev_name} - Cross-wind (linear freq, Fs={fs_text})",
f"{base_name}_cross_psd_linearlog.png", log_x=False)
print(f"All devices processed. Figures saved in '{output_dir}'.")Output
Save the input as simulated_winddata.csv next to cal_wind.pyand run python cal_wind.py to get the same spectra as PNG files.
Check against the original Python
This button runs cal_wind.py exactly as archived, usingPyodide (Python compiled to WebAssembly) with the real pandas, NumPy and SciPy. The current input is written to a virtual simulated_winddata.csv first. The only stand-in is matplotlib: a small stub records what each plot would contain instead of drawing it. The results are then compared bin by bin with the port above.
The first run downloads about 25 MB from the jsDelivr CDN and takes 10–40 seconds. Later runs are quick.
What this page reproduces and what it adds
- Steps 1–8 follow
cal_wind.pyline by line for one device. With the default processing options the port's spectra agree with SciPy's to within about 10−14 (relative), checked on several simulated records and again live in section 5. - The wind generator, the presets, the variants marked Java notes, proposed and corrected, and the two checks in step 8 were added for this page. They are not part of the archived script.
- The simulated turbulence uses Kaimal-type spectra with illustrative length scales (120 m along-wind, 40 m cross-wind). It produces realistic-looking spectra, but it is not a model of the wind at the telescope site.
- The 30-minute limit comes from the operations system's design notes, and 4 Hz and 10 Hz are the two sampling rates in their data-volume estimate.