REST API Reference¶
Base URL: http://localhost:5000
FastMODA provides REST APIs for extracting signal features programmatically. All analysis methods return JSON responses suitable for feature engineering in machine learning pipelines.
All analysis endpoints use async processing: the POST returns immediately with a
task_id; poll GET /status/<task_id> (typically every ~500ms) until status is
"complete" or "error".
Spectral Analysis¶
Extract time-frequency features from single signals.
POST /analyze¶
Upload a signal and extract spectral features including band powers, instantaneous frequency tracking, changepoint detection, dominant frequency components, and periodicity analysis.
Request:
curl -X POST http://localhost:5000/analyze \
-F "file=@signal.npy" \
-F "fs=100.0" \
-F "win=1.0" \
-F "pen=10"
Form parameters:
file(required): signal file (.mat,.npy, or.csv)fs(required): sampling frequency in Hzwin(optional): window size in seconds (default: 1.0)pen(optional): changepoint penalty — higher = fewer changepoints (default: 10, or"auto")
Response:
{
"task_id": "uuid-string",
"signal_length": 10000,
"sampling_rate": 100.0,
"duration": 100.0,
"optimized": true
}
GET /status/<task_id>¶
Poll for analysis results.
In progress:
Complete:
{
"status": "complete",
"progress": 100,
"stage": "Complete!",
"results": {
"signal": "<plotly-json>",
"spectrogram": "<plotly-json>",
"timeline": "<plotly-json>",
"instantaneous_freq": "<plotly-json>",
"band_powers": "<plotly-json>",
"periodicity": "<plotly-json>",
"frequency_summary": [
{ "rank": 1, "frequency": 10.5, "band": "alpha", "duration": 25.3, "duration_pct": 25.3, "occurrences": 12 }
],
"component_plots": [
{ "rank": 1, "frequency": 10.5, "band": "alpha", "duration": 25.3, "occurrences": 12, "plot": "<plotly-json>" }
]
},
"num_changepoints": 15,
"num_windows": 400
}
Feature extraction example:
import requests, numpy as np, time
signal = np.random.randn(10000)
np.save('temp_signal.npy', signal)
response = requests.post('http://localhost:5000/analyze',
files={'file': open('temp_signal.npy', 'rb')},
data={'fs': 100.0, 'win': 1.0, 'pen': 10})
task_id = response.json()['task_id']
while True:
status = requests.get(f'http://localhost:5000/status/{task_id}').json()
if status['status'] == 'complete':
break
time.sleep(0.5)
freq_features = status['results']['frequency_summary']
features = []
for comp in freq_features[:5]:
features.append(comp['frequency'])
features.append(comp['duration_pct'])
features.append(comp['occurrences'])
Continuous Wavelet Transform¶
POST /analyze_cwt¶
Morlet / Lognorm / Bump continuous wavelet transform. Two modes:
legacy=false— the fast vectorised transform (ridge_gpu.cwt_complex), driven byn_freqsandn_cycles.legacy=true(default) — a faithful port of MODA'swt.m(fastmoda.legacy_moda.wt_legacy): exact wavelet forms, MODA's frequency discretization (freq, set by the number of voicesnv), detrend+bandpass preprocessing, predictive padding and cone of influence. Use this whenever you are comparing against MODA.
Request (MODA-equivalent settings):
curl -X POST http://localhost:5000/analyze_cwt \
-F "file=@signal.npy" \
-F "fs=16" \
-F "wavelet=Morlet" \
-F "freq_min=0.01" -F "freq_max=2" \
-F "legacy=true" -F "f0=2" \
-F "padding=predictive" \
-F "cut_edges=true" \
-F "return_matrix=true"
Form parameters:
file(required): signal file (.mat,.npy, or.csv)fs(required): sampling frequency in Hzwavelet(optional):Lognorm(default),Morlet, orBumpfreq_min/freq_max(optional): band of interest (defaults0.5/fs/2)legacy(optional):truefor the MODA-faithfulwt.mpath (defaultfalse)f0(required whenlegacy=true): MODA's resolution parameter,q = 2πf0— typically 1 or 2, rarely 3. Determines the number of voices per octave and hence the number of frequency bins, son_freqsandn_cyclesare not used on this path. It is required rather than defaulted because it fixes the frequency discretization: guessing one would return a transform at a resolution you did not ask for. Alegacy=truerequest without it is rejected with400.nv(optional): voices per octave, overriding the valuef0impliesn_freqs(default path only): number of log-spaced bins (default 50)n_cycles(default path only): resolution parameter (default 6.0)padding(optional):predictive(MODA's default),symmetric,zero,periodic. Defaults topredictiveon the legacy path andsymmetricon the fast one, so omitting it keeps each path on its own convention.preprocess(legacy only):true(default) applies MODA'sPreprocess='on'— polynomial detrend plus a band-pass over[freq_min, freq_max]before padding. The fast path has no equivalent and ignores it.cut_edges(optional):trueNaNs out coefficients outside the cone of influence, as MODA's CutEdges does (defaultfalse)plot_type(optional):amplitude(default) orpower— affects the heatmap onlyreturn_matrix(optional):truealso persists the complex coefficients for download (defaultfalse)
Frequency resolution: how f0 sets the bin count¶
On the legacy path you supply only f0; MODA's own rule then fixes everything
else. The number of voices per octave is derived from the wavelet's 50% frequency
support and rounded up, and the frequency discretization is 2^(k/nv):
No = log2(fmax / fmin) # octaves spanned
nv = ceil(nv_real(f0, wavelet)) # voices per octave
Nf = floor(nv·log2 fmax) − ceil(nv·log2 fmin) + 1
For Morlet over 0.01–2 Hz this reproduces MODA's console output exactly:
f0 |
nv_real |
nv |
Nf |
|---|---|---|---|
| 1 | 30.85 | 31 | 237 |
| 2 | 63.89 | 64 | 490 |
| 3 | 96.40 | 97 | 742 |
The nv actually used comes back in the response as nv.
Results (in GET /status/<task_id> → results):
cwt_plot: Plotly heatmap JSON (dB — for display only, never invert it for analysis)time_avg_power: time-averaged power per frequency bin, raw units, equal to MATLAB'smean(abs(WT).^2, 2, 'omitnan')total_power:sum(time_avg_power, 'omitnan')freqs: MODA's frequency discretization (freq) in Hznv,n_freq_bins,n_times,f0andpreprocess(legacy),dominant_freq,boundary_hint, and thepadding/cut_edges/waveletactually used — echoed back so a run records the defaults that filled themselves incwt_matrix_url: present whenreturn_matrix=true— see below
GET /cwt_matrix/<token>¶
Download the complex coefficients saved by return_matrix=true. Returns a
.npz holding:
| Key | Shape | Notes |
|---|---|---|
cwt |
(n_freq, n_time) complex64 |
NaN outside the cone of influence when cut_edges=true |
freqs |
(n_freq,) |
Hz |
times |
(n_time,) |
seconds |
import io, numpy as np, requests
d = np.load(io.BytesIO(requests.get(base + results['cwt_matrix_url']).content))
WT, freqs = d['cwt'], d['freqs']
time_avg_pow = np.nanmean(np.abs(WT) ** 2, axis=1) # == results['time_avg_power']
total_pwr = np.nansum(time_avg_pow) # == results['total_power']
Files expire with the rest of the upload folder (UPLOAD_TTL_SECONDS, default 1h).
MODWT Wavelet Transform¶
Maximal Overlap Discrete Wavelet Transform for multi-scale signal decomposition.
POST /analyze_modwt¶
Decompose a signal into wavelet scales using shift-invariant MODWT. Extracts wavelet coefficients per level, frequency content per scale, energy distribution across scales, and perfect-reconstruction verification.
Request:
curl -X POST http://localhost:5000/analyze_modwt \
-F "file=@signal.npy" \
-F "fs=100.0" \
-F "wavelet=la8" \
-F "level=5"
Form parameters:
file(required),fs(required)wavelet(optional):'la8','d4','d6','la16'(default:'la8')level(optional): decomposition levels (default: auto =floor(log2(N)))
Response (after polling /status/<task_id>):
{
"status": "complete",
"results": {
"coefficients_plot": "<plotly-json>",
"heatmap_plot": "<plotly-json>",
"reconstruction_plot": "<plotly-json>",
"energy_plot": "<plotly-json>",
"n_levels": 5,
"reconstruction_error": 1.2e-15,
"scale_info": [
{ "level": 1, "freq_range": [25.0, 50.0], "energy_pct": 15.3 },
{ "level": 2, "freq_range": [12.5, 25.0], "energy_pct": 22.1 }
]
}
}
Useful derived features: energy per scale, dominant scales, frequency range per scale, scale-specific statistics (mean/std/peaks).
Wavelet Coherence¶
Analyze phase synchronization between multiple signals (2–6 signals).
Requires GPU acceleration
POST /analyze_coherence¶
Request:
curl -X POST http://localhost:5000/analyze_coherence \
-F "files=@signal1.npy" \
-F "files=@signal2.npy" \
-F "fs=100.0" \
-F "f0=1"
Form parameters:
files(required): 2–6 signal filesfs(required)legacy(defaulttrue): MODA's phase coherence, a port ofwphcoh.mon transforms from thewt.mport. Requiresf0.legacy=falseselects the fast path.f0(required on the legacy path): MODA's resolution parameter. It is not derived from anything else;central_freqis the fast path's cycle count, notf0.freq_min(default 0.5),freq_max(defaultfs/2),wavelet_type,preprocess,cut_edges,surrogate_method,n_surrogateswin,overlap,numcycles,central_freq: fast path only
Response (after polling): pairwise coherence plots per signal pair, e.g.
result.pair_plots["signal1_vs_signal2"]. Useful features: time-averaged coherence per
frequency, peak coherence frequencies, phase difference at peaks, time-localized
coherence changes.
Bispectrum Analysis¶
Detect quadratic phase coupling and frequency interactions (1–2 signals).
Requires GPU acceleration
POST /analyze_bispectrum¶
Request:
curl -X POST http://localhost:5000/analyze_bispectrum \
-F "files=@signal.npy" \
-F "fs=100.0" \
-F "freq_min=0.5" \
-F "freq_max=50.0" \
-F "f0=1" \
-F "bispec_type=111"
Form parameters:
files(required): 1–2 signal filesfs(required)freq_min(default 0.5),freq_max(defaultfs/2)legacy(defaulttrue): MODA's wavelet bispectrum, a port ofbispecWavNew.m, on MODA's own frequency grid with the third transform evaluated at exactlyf1 + f2. Cells MODA does not compute areNaN.legacy=falseselects the fast path.f0(required on the legacy path): MODA's resolution parameter; fixes the frequency binsn_freqs(fast path only, default 50): the legacy grid follows fromf0bispec_type(default'122'): on the legacy path one of MODA's four, whereB(f1,f2) = <W_a(f1) · W_b(f2) · conj(W_b(f1+f2))>
| Type | a |
b |
MODA's name |
|---|---|---|---|
111 |
signal 1 | signal 1 | autobispectrum of signal 1 |
222 |
signal 2 | signal 2 | autobispectrum of signal 2 |
122 |
signal 1 | signal 2 | cross-bispectrum |
211 |
signal 2 | signal 1 | cross-bispectrum |
POST /analyze_bispectrum4¶
All four bispectrum types of a pair at once, as MODA's Bispectrum GUI computes them.
files(required): exactly 2 signal files;fs(required)legacy(defaulttrue):bispecWavNew.m's port for each of111,222,122and211. Requiresf0. Four full bispectra, so expect four times/analyze_bispectrum's run time.legacy=falseselects the FFT bispectrum.f0(required on the legacy path),freq_min,freq_max(default: MODA's)nfft: fast path only
POST /analyze_biphase¶
Biamplitude and biphase over time at one frequency pair.
files(required): 1 or 2 signal files;fs(required);f1,f2(Hz)legacy(defaulttrue): port ofbiphaseWavNew.m:xx = W1(f1) · W2(f2) · conj(W2(f1+f2)), each transform evaluated at exactly that frequency,biphase = unwrap(angle(xx)). Requiresf0. As in MODA, all three use the second signal's transform options (padding included), which is what the Bispectrum GUI passes.legacy=falseselects the fast path.f0(required on the legacy path),freq_min,freq_max,waveletn_cycles: fast path only
POST /filter_butter¶
Band-pass filter.
file(required),fs(required),f_low,f_high(defaultfs/4),detrend_degree(default 0)legacy(defaulttrue): MODA'sloop_butter, which picks the filter order itself (the highest before the Butterworth filter goes unstable) and applies it withfiltfilt.orderis ignored; the order used is in the result. On MODA's path the Bayesian module'sloop_butteris the one every caller reaches, the Filtering module's included.legacy=falseusesorder(default 4).
POST /analyze_ridge¶
Ridge extraction: instantaneous frequency, amplitude and phase of the dominant component in a band.
file(required),fs(required),freq_min(default 0.5),freq_max(defaultfs/2)legacy(defaulttrue): MODA's pair, ports ofecurve.m(the ridge path and its time-frequency support) andrectfr.m'direct'(the component, integrated across that support, so the amplitude is the component's ownA). Requiresf0.legacy=falseselects the fast path: per-sample argmax, with the amplitude read at one bin (A/2).f0(required on the legacy path),wavelet(defaultlognorm),nv,padding(defaultpredictive),preprocess(defaulttrue)cut_edges: defaultfalseon the legacy path, as MODA's ridge extraction callswt;trueon the fast pathsmooth_len,n_freqs,n_cycles: fast path only
POST /analyze_wft¶
Windowed Fourier transform.
file(required),fs(required)legacy(defaulttrue): MODA's transform, a port ofwft.m. Requiresf0.legacy=falseselects the fixed-window Gaussian STFT, which takeswindow_size(default 256) andhop_size(default 128) and nothing else below.f0(required on the legacy path): the window's resolution parameter, aswft.mtakes it; its own default is 1. The MODA GUI passesf0 / fminhere, so to reproduce a GUI run send that quotient.window(defaultgaussian):gaussian,hann,blackman,exp,rectorkaiser;kaiser_asets Kaiser's shape (default 3)freq_min,freq_max(defaultfs/2);fstep(defaultauto, MODA's rule from the window)padding(defaultpredictive),preprocess(defaulttrue),cut_edges(defaultfalse, as inwft.m)plot_type:amplitude(default) orpower
The result reports method: "wft_legacy", the frequency step fstep and the
number of bins, with the plot under stft_plot.
Response:
{
"status": "complete",
"result": {
"bispectrum_plot": "<plotly-json>",
"coupling_strength": 0.82,
"top_couplings": [
{ "f1": 10.5, "f2": 20.3, "f3": 30.8, "strength": 0.95 },
{ "f1": 15.2, "f2": 15.2, "f3": 30.4, "strength": 0.87 }
],
"bispec_type": "122",
"freq_range": [0.5, 50.0]
}
}
Useful features: overall coupling strength, strongest frequency triad, number of significant couplings, coupling concentration (spectral vs broadband).
Bayesian Inference¶
Infer directional coupling between two signals.
POST /analyze_bayesian¶
Request:
curl -X POST http://localhost:5000/analyze_bayesian \
-F "files=@signal1.npy" \
-F "files=@signal2.npy" \
-F "fs=100.0" \
-F "band1_low=0.5" \
-F "band1_high=2.0" \
-F "band2_low=0.5" \
-F "band2_high=2.0" \
-F "window_s=40.0" \
-F "n_surrogates=19"
Form parameters:
files(required): exactly 2 signal filesfs(required)legacy(defaulttrue): MODA's own chain, ported fromfull_bayesian.m(which is what the Bayesian GUI runs):loop_butterband-pass, Hilbert phase,bayes_mainwindow by window,dircandCFprint, and cyclic-phase-permutation surrogates.legacy=falseselects the fast inference, which on a server without a GPU falls back to a windowed phase-locking value; that is not Bayesian inference and reports the same value in both directions.band1_low/band1_high,band2_low/band2_high(band edges, Hz)window_s(default 40.0);window_s × fsmust be a whole number of samplesoverlap(default 1.0): MODA's step between windows as a fraction of the window, so 1 means back to back;overlap × window_s × fsmust be whole toopropagation(default 0.2),bn(Fourier order, default 2),signif(default 95),n_surrogates(default 19)
Two signals with identical phases make the noise matrix singular, and MODA stops with an error there; so does the port.
On the legacy path the result adds filter_order1/filter_order2 (the
orders loop_butter chose) and the time-averaged coupling functions mcf1
(2→1) and mcf2 (1→2) on MODA's cf_grid (0:0.13:2π). See the
changelog for how closely the filter
stage can match MATLAB.
Response:
{
"status": "complete",
"result": {
"coupling_plot": "<plotly-json>",
"mean_cpl1": 0.35,
"mean_cpl2": 0.68,
"mean_direction": 0.42,
"band1": [0.5, 2.0],
"band2": [0.5, 2.0],
"window_s": 40.0,
"n_surrogates": 19
}
}
cpl1: coupling strength 2→1cpl2: coupling strength 1→2direction: net direction (-1: 2→1, +1: 1→2, 0: bidirectional); on the legacy pathdirc.m's(cpl2-cpl1)/(cpl1+cpl2)- Significance is assessed against the surrogate distribution.
POST /analyze_coupling¶
Coupling functions and direction between two signals.
files(required): exactly 2;fs(required); band edges as/analyze_bayesian;bn(default 3),win_s(default 40),overlap(default 1.0, as above),propagation(default 0.2)legacy(defaulttrue): MODA's Bayesian inference without surrogates;q21/q12areCFprint's coupling functions averaged over windows, and the direction isdirc.m's (+1 = 1→2).legacy=falseselects a sliding-window least-squares fit, whose direction plot uses the opposite sign.
POST /classify and stored features¶
The feature vector's wavelet features now come from |wt_legacy| (MODA's
wt.m, f0 = 1). Models record the feature set they were trained on
(moda-wt-v1); models without it, or trained on the fast CWT (fast-v0),
are ignored and /classify returns 503 until
scripts/train_condition_classifiers.py is rerun. /analyze_features does
not use a wavelet transform.
GPU Info¶
GET /api/gpu-info¶
{
"pytorch_available": true,
"cuda_available": true,
"device_name": "Tesla V100-SXM2-32GB",
"device_count": 1,
"optimized": true
}
Response format notes¶
- Plotly JSON — all plots are Plotly JSON strings; parse with
JSON.parse()(JavaScript) orjson.loads()(Python). - Async processing —
POSTreturns immediately withtask_id; poll/status/<task_id>(typical interval 500ms). - Error handling:
- File formats —
.mat(reads thesigorsignalvariable),.npy,.csv(first column used).
Performance tips¶
- Batch processing — process multiple signals sequentially to amortize startup costs.
- GPU acceleration — use GPU-backed endpoints (coherence, bispectrum, Bayesian) for a 10–50x speedup.
- Window size — balance time vs frequency resolution; 0.5–2.0s is typical.
- Changepoint tuning — a higher penalty gives fewer, more significant changepoints.
Configuration¶
Uploads are limited to 50 MB. The other settings, and running the server for devices on a network, are in Hosting FastMODA for Devices.
See Training a Classifier and Programmatic Usage for building on top of this API.