MoonSpectrum

    MoonBit-native scientific signal processing toolkit with FFT, spectra, windows, convolution, FIR filters, and CLI analysis.

    signal-processing
    fft
    spectrum
    dsp
    science
    Download zip
    Author
    Version
    0.1.1
    License
    Apache-2.0
    Last updated
    3 months ago
    Downloads
    219

    #MoonSpectrum

    CI

    MoonSpectrum 是一个面向 MoonBit 生态的科学信号处理基础库。它提供复数运算、DFT/FFT、频谱分析、窗函数、卷积、基础 FIR 滤波和命令行分析工具,目标是补齐 MoonBit 在传感器数据、实验数据、振动信号、周期信号和教学验证中的基础算法能力。

    本项目不做音频播放、采集或设备后端,也不依赖 native FFI。当前版本已覆盖 STFT、periodogram PSD、IIR 滤波和重采样;后续再扩展 Welch PSD、跨通道分析和 WebAssembly 可视化。

    #Why

    MoonBit 已经有一些音频、图形、矩阵和工程工具包,但通用科学信号处理方向还缺少一个小而稳的基础库。MoonSpectrum 的定位是:

    • 给 MoonBit 项目提供可复用的 FFT、频谱、窗函数、卷积和基础滤波能力。
    • 给 OSC2026 评审提供可直接运行的测试、示例数据和 CLI。
    • 给后续生态扩展留下清楚边界,而不是把音频引擎、数据框、可视化和控制系统混在一起。

    #Installation

    MoonSpectrum is a MoonBit module. The repository is the source distribution; the published module metadata and dependency version are recorded in moon.mod.

    #From the repository

    Install the current MoonBit toolchain from the official installer, then clone the repository and refresh its pinned dependency:

    # Windows PowerShell Set-ExecutionPolicy RemoteSigned -Scope CurrentUser irm https://cli.moonbitlang.com/install/powershell.ps1 | iex git clone https://github.com/chgttyyr/MoonSpectrum.git cd MoonSpectrum moon update moon check --target all

    # Linux or macOS curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash git clone https://github.com/chgttyyr/MoonSpectrum.git cd MoonSpectrum moon update moon check --target all

    The competition review environment recommended MoonBit 0.10.3. The CI uses the official latest-toolchain installer and prints moon version --all; this keeps the workflow usable when the installer advances while retaining the 0.10.3-compatible project commands. If starting a new copy instead of using the committed moon.mod, the equivalent dependency command is moon add moonbitlang/x@0.4.45.

    #Features

    • Complex 复数类型:加减乘、缩放、幅值、近似比较。
    • DFT / radix-2 FFT / inverse FFT。
    • 幅度谱、功率谱、频率 bin、主频检测。
    • STFT、periodogram PSD、单边 PSD、线性重采样。
    • 信号生成:正弦波、方波、脉冲、线性 chirp、确定性白噪声。
    • 窗函数:Rectangular、Hann、Hamming、Blackman。
    • 卷积:线性卷积、循环卷积。
    • 基础滤波:移动平均、FIR taps、IIR biquad 低通/高通/带通。
    • CLI:demo、fft、analyze、window、convolve。

    #Quick Start

    moon test moon run cmd/main -- demo moon run cmd/main -- fft examples/sine.csv --sample-rate 8 moon run cmd/main -- analyze examples/sine.csv --sample-rate 8 moon run cmd/main -- window hann 4 moon run cmd/main -- convolve examples/sine.csv examples/kernel.csv

    Typical output:

    {"samples":8,"sample_rate":8,"dominant_bin":2,"dominant_frequency":2,"magnitude":4}

    #API Sketch

    test {
    let signal = sine_wave(length=8, sample_rate=8.0, frequency=2.0)
    let spectrum = fft(real_signal(signal))
    let peak = dominant_peak(spectrum, 8.0)
    inspect(peak.index, content="2")
    }

    The root package exports the public API. CLI code lives in cmd/main and uses the same library functions as users would.

    #Project Layout

    • complex.mbt - complex arithmetic and approximate comparisons.
    • fft.mbt - DFT, FFT, inverse FFT, real signal conversion.
    • analysis.mbt - spectra, frequency bins, peak detection.
    • signals.mbt - test/demo signal generation.
    • windows.mbt - window functions and window application.
    • convolution.mbt - linear and circular convolution.
    • filters.mbt - moving average, FIR filtering, low/high-pass taps.
    • stft.mbt, psd.mbt, resampling.mbt, iir_filters.mbt - extended scientific signal-processing primitives.
    • cmd/main - CLI entry point.
    • examples - small CSV fixtures for smoke tests.
    • docs/fixtures.md - fixture provenance, construction rules, and expected numeric invariants.
    • docs/competition - OSC2026 proposal and acceptance material.

    #Verification

    moon info moon fmt --check moon check --target all --warn-list +73 moon build --target all moon test --target all powershell -ExecutionPolicy Bypass -File scripts\verify_acceptance.ps1 -SkipPublishDryRun

    MoonSpectrum is published as the Mooncakes module chgttyyr/MoonSpectrum@0.1.1. The moon.mod file is the source of truth for the package metadata shown on Mooncakes.

    #Current Boundaries

    • FFT currently requires power-of-two input length.
    • CSV parser intentionally handles simple single-column numeric fixtures.
    • Time zones, timestamps, streaming IO, STFT, IIR, and visualization are future work.
    • No native FFI is used in v0.1.1.

    #Roadmap

    • STFT and spectrogram data export.
    • Welch PSD and cross-correlation.
    • IIR biquad filters.
    • Resampling and interpolation helpers.
    • Browser/WebAssembly demo for frequency-domain visualization.
    • More robust CSV/JSON data pipeline.

    #License

    Apache-2.0.

    SpectrumError

    pub(all) suberror SpectrumError {
    EmptySignal
    LengthMismatch
    NonPowerOfTwo(length~ : Int)
    InvalidArgument(message~ : String)
    } derive(Eq, ToJson,
    Debug
    )

    Biquad

    pub(all) struct Biquad {
    b0 : Double
    b1 : Double
    b2 : Double
    a1 : Double
    a2 : Double
    x1 : Double
    x2 : Double
    y1 : Double
    y2 : Double
    } derive(Eq, ToJson,
    Debug
    )

    Biquad::bandpass

    fn Biquad::bandpass(cutoff_hz : Double, sample_rate : Double, q? : Double) -> Biquad raise SpectrumError

    Biquad::filter

    fn Biquad::filter(self : Biquad, signal : ArrayView[Double]) -> Array[Double] raise SpectrumError

    Biquad::highpass

    fn Biquad::highpass(cutoff_hz : Double, sample_rate : Double, q? : Double) -> Biquad raise SpectrumError

    Biquad::lowpass

    fn Biquad::lowpass(cutoff_hz : Double, sample_rate : Double, q? : Double) -> Biquad raise SpectrumError

    Biquad::new

    fn Biquad::new(b0 : Double, b1 : Double, b2 : Double, a1 : Double, a2 : Double) -> Biquad

    Biquad::step

    fn Biquad::step(self : Biquad, x : Double) -> Double

    Complex

    pub(all) struct Complex {
    re : Double
    im : Double
    } derive(Eq, ToJson,
    Debug
    )

    Complex::add

    fn Complex::add(self : Complex, other : Complex) -> Complex

    Complex::approx_equal

    fn Complex::approx_equal(self : Complex, other : Complex, eps? : Double) -> Bool

    Complex::magnitude

    fn Complex::magnitude(self : Complex) -> Double

    Complex::mul

    fn Complex::mul(self : Complex, other : Complex) -> Complex

    Complex::scale

    fn Complex::scale(self : Complex, factor : Double) -> Complex

    Complex::sub

    fn Complex::sub(self : Complex, other : Complex) -> Complex

    Complex::zero

    fn Complex::zero() -> Complex

    Peak

    pub(all) struct Peak {
    index : Int
    frequency : Double
    magnitude : Double
    } derive(Eq, ToJson,
    Debug
    )

    WindowKind

    pub(all) enum WindowKind {
    Rectangular
    Hann
    Hamming
    Blackman
    } derive(Eq, ToJson,
    Debug
    )

    apply_window

    fn apply_window(signal : ArrayView[Double], weights : ArrayView[Double]) -> Array[Double] raise SpectrumError

    approx_equal

    fn approx_equal(a : Double, b : Double, eps? : Double) -> Bool

    bandpass_fir_taps

    fn bandpass_fir_taps(length~ : Int, low_cutoff_hz~ : Double, high_cutoff_hz~ : Double, sample_rate~ : Double) -> Array[Double] raise SpectrumError

    bandstop_fir_taps

    fn bandstop_fir_taps(length~ : Int, low_cutoff_hz~ : Double, high_cutoff_hz~ : Double, sample_rate~ : Double) -> Array[Double] raise SpectrumError

    chirp

    fn chirp(length~ : Int, sample_rate~ : Double, start_hz~ : Double, end_hz~ : Double, amplitude? : Double) -> Array[Double] raise SpectrumError

    circular_convolve

    fn circular_convolve(signal : ArrayView[Double], kernel : ArrayView[Double]) -> Array[Double] raise SpectrumError

    complex

    fn complex(re~ : Double, im~ : Double) -> Complex

    convolve

    fn convolve(signal : ArrayView[Double], kernel : ArrayView[Double]) -> Array[Double] raise SpectrumError

    dft

    fn dft(signal : ArrayView[Complex]) -> Array[Complex] raise SpectrumError

    dominant_peak

    fn dominant_peak(spectrum : ArrayView[Complex], sample_rate : Double) -> Peak raise SpectrumError

    fft

    fn fft(signal : ArrayView[Complex]) -> Array[Complex] raise SpectrumError

    fir_filter

    fn fir_filter(signal : ArrayView[Double], taps : ArrayView[Double]) -> Array[Double] raise SpectrumError

    frequency_bins

    fn frequency_bins(length : Int, sample_rate : Double) -> Array[Double] raise SpectrumError

    highpass_taps

    fn highpass_taps(length~ : Int, cutoff_hz~ : Double, sample_rate~ : Double) -> Array[Double] raise SpectrumError

    ifft

    fn ifft(spectrum : ArrayView[Complex]) -> Array[Complex] raise SpectrumError

    impulse

    fn impulse(length~ : Int, index? : Int, amplitude? : Double) -> Array[Double] raise SpectrumError

    lowpass_taps

    fn lowpass_taps(length~ : Int, cutoff_hz~ : Double, sample_rate~ : Double) -> Array[Double] raise SpectrumError

    magnitude_spectrum

    fn magnitude_spectrum(spectrum : ArrayView[Complex]) -> Array[Double]

    moving_average

    fn moving_average(signal : ArrayView[Double], width : Int) -> Array[Double] raise SpectrumError

    periodogram

    fn periodogram(signal : ArrayView[Double], sample_rate : Double, window_kind? : WindowKind) -> Array[Double] raise SpectrumError

    power_spectrum

    fn power_spectrum(spectrum : ArrayView[Complex]) -> Array[Double]

    real_signal

    fn real_signal(values : ArrayView[Double]) -> Array[Complex]

    resample_linear

    fn resample_linear(signal : ArrayView[Double], target_length : Int) -> Array[Double] raise SpectrumError

    resample_sinc

    fn resample_sinc(signal : ArrayView[Double], target_length : Int) -> Array[Double] raise SpectrumError

    sine_wave

    fn sine_wave(length~ : Int, sample_rate~ : Double, frequency~ : Double, amplitude? : Double) -> Array[Double] raise SpectrumError

    single_sided_psd

    fn single_sided_psd(two_sided_psd : ArrayView[Double]) -> Array[Double] raise SpectrumError

    square_wave

    fn square_wave(length~ : Int, sample_rate~ : Double, frequency~ : Double, amplitude? : Double) -> Array[Double] raise SpectrumError

    stft

    fn stft(signal : ArrayView[Double], window_kind : WindowKind, window_length : Int, hop_size : Int) -> Array[Array[Complex]] raise SpectrumError

    white_noise

    fn white_noise(length~ : Int, seed~ : UInt, amplitude? : Double) -> Array[Double] raise SpectrumError

    window

    fn window(kind : WindowKind, length : Int) -> Array[Double] raise SpectrumError