Skip to content

Analysis Module

Analysis functions for spectra, transfer functions, sonograms and damping estimates. The calculate_* functions take a TimeData (or a TimeDataList for ensemble averages) and return a new result without changing their input. Modal fitting is in the Modal Analysis module.

FFT Analysis

calculate_fft

calculate_fft(time_data, time_range=None, window=None)

Calculate the one-sided FFT of every channel of one TimeData.

The spectrum is the raw np.fft.rfft of the (optionally windowed) samples inside time_range: it is not scaled to an amplitude or power spectrum. The frequency resolution is the reciprocal of the selected segment's duration.

The result is stamped with source_signature (a hash of the source samples, see pydvma._signature) and source_settings (the arguments of this call, with time_range recorded as the range actually used: the whole record when the argument was None).

Parameters:

  • time_data (TimeData) –

    The capture to transform.

  • time_range (list or ndarray or PlotData, default: None ) –

    [t_start, t_stop] in seconds; samples with t_start <= t <= t_stop are used. A PlotData uses its current x-axis limits. None (the default) uses the whole record.

  • window (str, default: None ) –

    A scipy.signal.windows name such as 'hann', 'hamming' or 'blackman', or None (the default) for a rectangular (boxcar) window.

Returns:

  • freq_data ( FreqData ) –

    The complex spectrum, one column per channel, with the source's units and channel_cal_factors copied across and id_link set to the source's unique_id.

Raises:

  • Exception –

    time_data is not a single TimeData.

Transfer Functions

calculate_tf

calculate_tf(time_data, ch_in=0, time_range=None, window=None, N_frames=1, overlap=0.5)

Calculate the transfer functions of one capture (H1 estimator).

Every channel other than ch_in is treated as an output, and its TF is Pxy[ch_in, ch_out] / Pxy[ch_in, ch_in] from calculate_cross_spectrum_matrix, with the matching coherence. The calibration carried onto the result is the ratio cal[ch_out] / cal[ch_in] and the units are '<out>/<in>' (compound units parenthesised by wrap_unit).

The result is stamped with source_signature (a hash of the source samples, see pydvma._signature) and source_settings (the arguments of this call, with time_range recorded as the range actually used: the whole record when the argument was None).

Parameters:

  • time_data (TimeData) –

    The capture to analyse.

  • ch_in (int, default: 0 ) –

    Column index of the input (reference) channel (default 0).

  • time_range (list or ndarray, default: None ) –

    [t_start, t_stop] in seconds. None (the default) uses the whole record.

  • window (str, default: None ) –

    A scipy.signal.windows name applied to each frame before its FFT, or None (the default) for a rectangular window.

  • N_frames (int, default: 1 ) –

    Number of averaging frames (default 1); see calculate_cross_spectrum_matrix. With 1 frame the coherence is identically 1.

  • overlap (float, default: 0.5 ) –

    Fractional overlap between frames, from 0 to 1 (default 0.5).

Returns:

  • tf_data ( TfData ) –

    tf_data and tf_coherence of shape (n_freq, n_channels - 1), one column per output channel in ascending channel order (listed in settings.ch_out_set).

Raises:

  • Exception –

    time_data is not a single TimeData.

calculate_tf_averaged

calculate_tf_averaged(time_data_list, ch_in=0, time_range=None, window=None)

Calculate transfer functions averaged across an ensemble of separate captures.

Each record is taken as one independent measurement (one frame, no sub-frame averaging): the cross-spectra are averaged across the ensemble, then the H1 estimator Pxy[ch_in, ch_out] / Pxy[ch_in, ch_in] is formed, with the same phase convention as calculate_tf. Intended for repeated measurements such as impulse-hammer tests.

The records must share a channel count and a sample rate (to within TF_ENSEMBLE_FS_TOLERANCE, 0.1 %); records of different lengths are all truncated to the shortest, and that length is recorded as source_settings['n_samples'].

The result is stamped with source_signature (hashing every source's samples, concatenated in list order) and source_settings. That settings snapshot records time_range as passed (None meaning "the whole of each record"), whereas calculate_tf records the range it resolved, because an ensemble of records has no single resolved range.

Parameters:

  • time_data_list (TimeDataList) –

    The ensemble of captures.

  • ch_in (int, default: 0 ) –

    Column index of the input (reference) channel (default 0).

  • time_range (list or ndarray, default: None ) –

    [t_start, t_stop] in seconds, applied to every record. None (the default) uses the whole of each record.

  • window (str, default: None ) –

    A scipy.signal.windows name, or None (the default) for a rectangular window.

Returns:

  • tf_data ( TfData ) –

    One column per output channel, with calibration ratios and units taken from the first record and id_link listing every record's unique_id.

Raises:

  • Exception –

    time_data_list is not a TimeDataList.

  • ValueError –

    The list is empty, or its records differ in channel count or sample rate.

calculate_bla

calculate_bla(time_data_list, run_spec)

Best Linear Approximation with noise/nonlinearity separation (Schoukens random-phase multisine method, SISO and MISO unified).

Consumes the M x n_exc captures of a BLA run (ordering [(m, e) for m in range(M) for e in range(n_exc)]), slices exact N-sample periods after discarding t_periods transients, DFTs each period (no window — the data is periodic by construction) and estimates, per response channel: the BLA frequency-response matrix (mean over realisations of the per-realisation n_exc x n_exc solve), the noise standard deviation bla_sigma_n (period-to- period scatter propagated through the input-matrix inverse, with the 1/P of the period average folded in) and the nonlinear-distortion standard deviation bla_sigma_nl (realisation scatter minus that noise variance, floored at zero).

Only the excited bins are analysed, so the returned frequency axis is k * fs / N over k1..k2 — a sparse, exactly-on-bin axis, not the full rfft grid.

Start-time offsets between captures are harmless for measured x: x and y share the ADC clock, so the common phase rotation exp(-j*w*tau) cancels in the solve. For x_mode='commanded' the input spectra are instead regenerated analytically from the seed, using the same phase and scaling law as acquisition.multisine_generator; that is only valid when AO and AI are hardware-synced (the caller enforces that), because otherwise per-capture start jitter leaks into the realisation scatter and corrupts sigma_NL.

Unlike the other ensemble entry points this takes a plain list, not a or a method: the captures carry no record of their own (m, e) indices, so the ORDER of the list is load-bearing input, and a DataSet — an unordered bag the user can add to, reorder or partly delete — cannot express it. The caller assembles the list in run order; a wrong length is caught here, a wrong order is not.

Parameters:

  • time_data_list (list) –

    The M * n_exc captures of the run, in (m, e) order — realisation outer, experiment inner.

  • run_spec (dict) –

    BlaRunSpec — multisine (a dict of n_samples, k1, k2, p_periods, t_periods, seed, amp_rms, n_exc, M), x_mode ('measured' or 'commanded'), x_channels (per-excitation input channel indices, or None for commanded x), resp_channels (response channel indices) and fs (the actual capture rate in Hz).

Returns a of n_exc objects, one per excitation, each holding every response channel as a column of tf_data and carrying bla_sigma_nl, bla_sigma_n and the bla run-spec dict. tf_coherence is None: coherence is not the right quality measure here — the sigma pair is. Both sigmas are PER-REALISATION standard deviations in linear FRF units — the distortion and noise level of a single realisation, not the error bar on the returned BLA, which is sqrt(M) smaller (sigma_BLA = sigma_tot / sqrt(M)).

Cross-Spectrum Analysis

calculate_cross_spectrum_matrix

calculate_cross_spectrum_matrix(time_data, time_range=None, window=None, N_frames=1, overlap=0.5)

Compute the full cross-spectrum matrix and coherence matrix of a multi-channel TimeData block using Welch's method.

Equivalent to looping scipy.signal.csd (with scaling='spectrum') and scipy.signal.coherence over every channel pair, but vectorised: each segment is FFT'd once across all channels, and the cross-spectrum matrix is formed as a tensor outer product conj(X[:,f,i]) * X[:,f,j] averaged over segments. Output is byte-equivalent to the scipy reference to within FFT round-off.

The DC bin (and, for an even segment length, the Nyquist bin) of the coherence matrix is undefined under a boxcar window: constant detrending zeroes each segment's mean, so the auto-spectra there are pure round-off and Cxy is a 0/0 ratio. It is returned as 0 in that degenerate case rather than NaN; treat it as "no information at DC", not a real coherence.

Parameters:

  • time_data (TimeData) –

    The capture to analyse.

  • time_range (list or ndarray or PlotData, default: None ) –

    [t_start, t_stop] in seconds. A PlotData uses its current x-axis limits. None (the default) uses the whole record.

  • window (str, default: None ) –

    A scipy.signal.windows name, applied to each segment. None (the default) means 'boxcar'.

  • N_frames (int, default: 1 ) –

    Number of averaging frames (default 1). The segment length is ceil(N / ((N_frames + 1) * (1 - overlap))) samples for a selection of N samples, which gives exactly N_frames segments at the default overlap of 0.5. Must be at least 1.

  • overlap (float, default: 0.5 ) –

    Fractional overlap between segments, from 0 to 1 (default 0.5).

Returns:

  • cross_spec_data ( CrossSpecData ) –

    Pxy of shape (n_channels, n_channels, n_freq) as a power SPECTRUM (unit**2; divide by the result's enbw_hz for a density), Cxy of the same shape, and the source's units and channel_cal_factors.

Raises:

  • Exception –

    time_data is not a single TimeData.

  • ValueError –

    N_frames makes the segment longer than the selected record.

calculate_cross_spectra_averaged

calculate_cross_spectra_averaged(time_data_list, time_range=None, window=None)

Average the cross-spectrum matrix across an ensemble of separate captures.

Each TimeData in the list is treated as one independent measurement (one frame, no sub-frame averaging) and its cross-spectrum matrix (calculate_cross_spectrum_matrix with N_frames=1) is averaged with equal weight; the coherence is then formed from the averaged matrix. Intended for repeated measurements such as impulse-hammer tests.

Every record must give the same frequency bins (same channel count, sample rate and length); this function does not check that.

Parameters:

  • time_data_list (TimeDataList) –

    The ensemble of captures.

  • time_range (list or ndarray, default: None ) –

    [t_start, t_stop] in seconds, applied to every record. None (the default) uses the whole of each record.

  • window (str, default: None ) –

    A scipy.signal.windows name, or None (the default) for a rectangular window.

Returns:

  • cross_spec_data ( CrossSpecData ) –

    The averaged Pxy and its coherence Cxy, with units and channel_cal_factors from the first record and id_link listing every record's unique_id.

Raises:

  • Exception –

    time_data_list is not a TimeDataList.

Time-Frequency Analysis

calculate_sonogram

calculate_sonogram(time_data, nperseg=None, noverlap=None)

Calculates a complex STFT spectrogram (sonogram) for every channel of a object using a Hann window, and returns a .

Provenance: the result is stamped with source_signature (a hash of the source samples, see pydvma._signature) and source_settings — {'calc': 'sonogram', 'method': 'stft', ...} with the EFFECTIVE nperseg / noverlap recorded (the values derived from the record length when either argument was None).

Channel calibration factors and units are copied from the source, and id_link is set to the source's unique_id (same provenance convention as the other calculate_* functions).

The segmentation is done by _spectrogram_complex_lowmem rather than scipy.signal.spectrogram directly: scipy's internal sliding_window_view builds a huge NOMINAL intermediate that the 32-bit WASM/pyodide engine rejects with "array is too big" for a large nperseg on a long, high-rate record. The low-memory helper strides directly to the decimated windows and is byte-identical to scipy (pinned in the test suite). See that helper's docstring for the full rationale.

Parameters:

  • time_data (<TimeData> object) –

    time series data

  • nperseg (int, default: None ) –

    STFT segment length; defaults to ~1/50th of the time series so roughly 50 segments span the data

  • noverlap (int, default: None ) –

    overlap between segments, default nperseg // 2

calculate_cwt

calculate_cwt(time_data, f_range=None, voices_per_octave=16, w0=6.0, max_time_columns=2000, uniform_freq=True, progress_callback=None)

Continuous wavelet transform (complex Morlet) as a SonoData.

Provenance: the result is stamped with source_signature and source_settings — {'calc': 'sonogram', 'method': 'cwt', ...} with the EFFECTIVE f_range recorded (the automatic band when the argument was None or one-sided), exactly as calculate_sonogram records its effective window.

A drop-in ALTERNATIVE to calculate_sonogram: produces the SAME SonoData shape (sono_data of shape (n_freq, n_frames, n_channels), complex, with time_axis and freq_axis) so the whole downstream pipeline — the .dvma container, the web-UI heat map, and the damping fit — reuses unchanged. Where the STFT sonogram has a FIXED time-frequency resolution, the wavelet transform is constant-Q: long (narrow-band) wavelets at low frequency and short (wide-band) wavelets at high frequency, which is why it separates closely-spaced low-frequency modes that a single-window STFT smears together (demonstrated in the damping tests).

The transform is computed on LOG-spaced frequencies (voices_per_octave per octave; see _cwt_default_frequencies for the default band and _morlet_cwt_1d for the FFT construction and amplitude normalisation).

FREQUENCY AXIS (uniform_freq): the CWT is naturally sampled on a log-frequency grid, but the web-UI heat renderer maps each frequency ROW-INDEX linearly to a canvas pixel row and labels a LINEAR frequency axis, i.e. it assumes UNIFORM bin spacing. With uniform_freq=True (default, the display path) the complex image is therefore resampled onto a uniform grid spanning the same band (via _resample_freq_axis) so the existing renderer places and labels it correctly with no renderer change. TRADE-OFF: a uniform linear axis compresses low frequencies (exactly as the STFT sonogram already does), so the wavelet's finer low-frequency detail is not fully resolved in the heat MAP; it IS retained in the analysis and in the damping fit, which uses uniform_freq=False to keep the native log grid. (A log-y heat renderer — owned by the plot layer — would let the native log axis display with full low-frequency detail.)

TIME AXIS / MEMORY: the output time axis is decimated so it has at most max_time_columns frames (None keeps every sample). This bounds the returned image — it is a display/analysis picture, not raw data — and, together with the per-channel loop, keeps peak memory low on the 32-bit WASM engine. Worst case is n_freq x max_time_columns complex per returned image (~7 MB at the defaults), with only single-channel, single-scale full-length FFT temporaries alive during the compute. The default cap keeps the image far below CWT_MAX_IMAGE_BYTES; max_time_columns=None on a long record can exceed it, and then _morlet_cwt_1d refuses with a sizing error rather than allocating.

Parameters:

  • time_data (<TimeData> object) –

    time series data (all channels).

  • f_range (tuple or None, default: None ) –

    (f_min, f_max) in Hz; None uses the default band (see _cwt_default_frequencies). Either side may be None to keep that side automatic; a reversed band raises.

  • voices_per_octave (int, default: 16 ) –

    log-frequency density (default 16).

  • w0 (float, default: 6.0 ) –

    non-dimensional Morlet frequency (default 6.0) — the wavelet Q. Higher = more cycles under the envelope = finer frequency resolution but coarser time resolution; lower sharpens time localisation at the cost of frequency smearing.

  • max_time_columns (int or None, default: 2000 ) –

    cap on output time frames (default 2000); None disables time decimation.

  • uniform_freq (bool, default: True ) –

    resample onto a uniform frequency grid for display (default True); False returns the native log grid (used by the damping fit).

  • progress_callback (callable or None, default: None ) –

    optional f(done, total) for a long-running caller. It covers the WHOLE call — total = n_channels * n_freqs and done counts scales across every channel, so a 2-channel transform reads 50 % when the first channel finishes. None (default) is a no-op and the result is bit-identical either way; see _morlet_cwt_1d for the per-scale contract and the cheap-and-never-raises requirement.

Damping

calculate_damping_from_sono

calculate_damping_from_sono(time_data, n_chan=1, nperseg=None, start_time=None, peak_threshold=None)

Calculate damping from an STFT sonogram.

Computes a Hann-window sonogram (noverlap=0) and fits the free-decay of each detected band. See _fit_modes_from_image for the fit core (this is the phase_has_carrier=False / STFT case) and calculate_damping_from_cwt for the wavelet alternative.

Parameters:

  • time_data (<TimeData> object) –

    time series data

  • n_chan (int, default: 1 ) –

    channel index to analyze, default is 1

  • nperseg (int, default: None ) –

    number of samples per segment for spectrogram

  • start_time (float, default: None ) –

    start time (seconds) for analysis; None infers it from the pretrigger (see _resolve_damping_start_slice)

  • peak_threshold (float, default: None ) –

    normalised peak-picking threshold in 0..1 (fraction of the start-slice magnitude's min→max range, as peakutils.indexes interprets it); None keeps the automatic 10 * median / max choice (see _fit_modes_from_image)

Returns:

  • fn ( ndarray ) –

    array of natural frequencies (Hz)

  • Qn ( ndarray ) –

    array of Q factors (1/(2*zeta))

  • fit_data ( dict ) –

    dict containing data needed for plotting the fits: - 't': time axis - 'fits': list of dicts, each with keys: - 't_fit': time values for the fit region (the decay's stretch above floor + DECAY_FLOOR_MARGIN_DB) - 'real_fit': the fitted line, ln|S| - 'real_data': the measured ln|S| - 'f_peak': peak frequency (Hz) - 'Qn': Q factor for this mode - 'noise': the bin's noise floor, as ln|S| - 't_cross': where the fitted line meets the floor (s) - 'range_db': the decay's loudest frame above the floor (dB) - 'time_slice' / 'start_time': the fit-start frame index and its time (s) — the resolved free-decay start - 'threshold': the normalised peak threshold actually used - 'slice_freq' / 'slice_mag': the start-slice magnitude spectrum the peak picker scanned - 'peaks_freq' / 'peaks_mag': the candidate peaks it detected (before any per-peak fit failures are dropped)

calculate_damping_from_cwt

calculate_damping_from_cwt(time_data, n_chan=1, start_time=None, f_range=None, voices_per_octave=16, w0=6.0, peak_threshold=None, progress_callback=None)

Calculate damping from a continuous wavelet transform (complex Morlet).

The wavelet alternative to calculate_damping_from_sono: it fits the same per-mode free-decay, but on the CWT image, whose constant-Q resolution separates closely-spaced low-frequency modes that a fixed-window STFT smears into one band. Only channel n_chan is transformed, on the NATIVE log-frequency grid (_cwt_default_frequencies).

The phase-to-frequency mapping differs from the STFT: the analytic Morlet coefficient's phase advances at the signal's own frequency, so the fit core is called with phase_has_carrier=True (see _fit_modes_from_image).

SIZE / MEMORY. The fit image is n_freqs x n_columns complex, and at full rate that is ruinous on a lab-length record: 30 s at 48 kHz over the default band is ~16 GB. Two bounds apply. (1) The time axis is decimated to _cwt_damping_time_step — the coarsest step the phase unwrap tolerates for the band's top frequency, with margin. A DEFAULT-band fit tops out at 0.4*fs so its step stays 1 and its numbers are unchanged; f_range is what buys the decimation, and it shrinks n_freqs at the same time. (2) Whatever remains is checked against CWT_MAX_IMAGE_BYTES before allocation, so an impossible request raises a ValueError that names the record, the grid and the remedies instead of failing opaquely. A long record therefore needs an explicit f_range — which is also the honest analysis, since a 30 s record has nothing to say about a 19 kHz mode's decay.

Parameters:

  • time_data (TimeData) –

    time series data

  • n_chan (int, default: 1 ) –

    channel index to analyze, default is 1

  • start_time (float, default: None ) –

    start time (seconds); None infers it from the pretrigger (see _resolve_damping_start_slice)

  • f_range (tuple or None, default: None ) –

    (f_min, f_max) Hz restricting the fitted band; None uses the default band (see _cwt_default_frequencies). Either side may be None to keep that side automatic; a reversed band raises ValueError

  • voices_per_octave (int, default: 16 ) –

    log-frequency density, default 16

  • w0 (float, default: 6.0 ) –

    non-dimensional Morlet frequency, default 6.0

  • peak_threshold (float, default: None ) –

    normalised peak-picking threshold in 0..1; None keeps the automatic choice (see calculate_damping_from_sono)

  • progress_callback (callable or None, default: None ) –

    optional f(done, total) reporting the TRANSFORM only — total is the number of analysis frequencies and done counts scales (see _morlet_cwt_1d). The per-mode curve fits that follow are deliberately NOT counted: the mode count is unknown until the transform has finished and the peaks have been picked, so including them would grow total mid-call and make a progress bar jump backwards. They are also the cheap half — a handful of scipy.optimize.curve_fit calls against one inverse FFT per scale. None (default) is a no-op.

Returns:

  • fn ( ndarray ) –

    Natural frequencies of the fitted modes in Hz.

  • Qn ( ndarray ) –

    Q factors, 1/(2*zeta).

  • fit_data ( dict ) –

    Plotting data for the fits, with the same keys as calculate_damping_from_sono returns.

Raises:

  • ValueError –

    f_range is reversed, or the CWT image would exceed CWT_MAX_IMAGE_BYTES (narrow f_range or shorten the record).

calculate_damping_by_band

calculate_damping_by_band(time_data, n_chan=1, bands='octave', start_time=None, f_range=None, filter_order=4)

Band-centred decay metrics via a filter bank + the Schroeder integral.

The room-acoustics alternative to the sonogram peak fits (calculate_damping_from_sono / _from_cwt): instead of picking modal peaks, the free decay is band-pass filtered into standard bands (zero-phase Butterworth, sosfiltfilt), each band's energy-decay curve is formed with the Schroeder backward integral, and straight-line fits of that curve give the band's decay metrics:

  • EDT — early decay time, 0 to -10 dB fit x6 (perceived reverberance)
  • T20 — -5 to -25 dB fit x3
  • T30 — -5 to -35 dB fit x2
  • T60 — the reverberation time: the first TRUSTED of T30, T20 and EDT (see below); NaN when none is trusted
  • Qn — the equivalent band-centred Q factor, Q = pi*fc*T60 / (3*ln 10) (~= fc*T60/2.20), from T60 = 3*ln10/(zeta*wn)

Each band's curve stops where its decay meets the noise (2026-11-24, after vibration_apps' decay.js; see _band_decay_cut): the floor is the band's mean square over the last DECAY_TAIL_FRACTION of the decay, a line through its level in blocks of max(10 ms, 2/fc) from the loudest block to DECAY_FLOOR_MARGIN_DB above the floor gives the crossover, and the Schroeder integral stops there with the decay's own energy beyond it added. Integrated to the end of the record instead, the noise counted as decay and a decay that ended early read many times too long.

A metric is NaN when the band's curve never spans that fit window, and flagged (EDT_flag / T20_flag / T30_flag: comma-joined reasons, '' when trusted) when the band does not support it: 'range' — the decay starts less than DECAY_NEEDS_DB (20 / 35 / 45 dB, ISO 3382) above the noise; 'short' — it is shorter than the band filter's own ringing, 16/(f_hi - f_lo) (Jacobsen and Rindel); 'bent' — its fitted line falls outside DECAY_DROP_RANGE of the window's own drop. A flagged value is still reported; only T60 skips it.

Parameters:

  • time_data (TimeData) –

    time series data

  • n_chan (int, default: 1 ) –

    channel index to analyze, default is 1

  • bands (str, default: 'octave' ) –

    'all' (one broadband band over the whole f_range), 'octave', 'third-octave' or 'tenth-decade' (10^(1/10) spacing, ~a third octave on base-10-preferred centres). Ladders anchor at 1000 Hz and keep only bands whose FULL width lies inside f_range.

  • start_time (float, default: None ) –

    free-decay start (seconds); None infers it from the pretrigger (see _resolve_damping_start_slice), or, with no pretrigger, takes the onset: the loudest sample plus 2.3 ms (_decay_onset)

  • f_range (tuple, default: None ) –

    (f_min, f_max) Hz analysis range; None uses 4/T .. 0.4*fs, where T is the decay's length

  • filter_order (int, default: 4 ) –

    Butterworth section order, default 4 (applied forward-backward, so the effective roll-off doubles)

Returns:

  • result ( dict ) –

    The per-band arrays fc, f_lo, f_hi (Hz) and EDT, T20, T30, T60 (s) and Qn (NaN where unfittable); bands (the argument); start_time (the resolved decay start, s); per band noise_db (the floor, dB re the loudest block), range_db (the loudest block above the floor), cut_time (where the curve stops, s after the start) and the lists EDT_flag / T20_flag / T30_flag; and band_data, one dict per band carrying the plotting payload: the (decimated) EDC edc_t / edc_db up to the cut, cut_t, and the T60 fit window fit_t / fit_db.

Raises:

  • ValueError –

    bands is not one of the four names above, or fewer than 64 samples follow the decay start.

Signal Processing

resample_to_fs

resample_to_fs(y, fs, fs_new, stopband_db=96.0)

Resample a signal to a new sample rate with a band-limited FIR filter.

Used by acquisition.log_data's digital low-pass (capture above fs, then resample down to it) and by the web logger's Resample tool. The rate change is rational — fs_new/fs is approximated by up/down (Fraction.limit_denominator, refined when needed by the simplest fraction within a 1e-9 relative tolerance), so a device-coerced capture rate still lands exactly on a round target: the NI 9234's 8533.33 Hz -> 2000 is up/down = 15/64, and the USB-6003's 80 MHz-timebase 48019.2077 Hz -> 8000 is 833/5000 (a ratio the coarse 1024-denominator bound alone would miss). A ratio whose exact form would need an unreasonably large polyphase FIR (> 2^19 taps — this code also runs under 32-bit WASM) degrades gracefully to the coarse fraction, in which case fs_out may differ slightly from fs_new. The rate change is applied as polyphase FIR filtering (scipy.signal.resample_poly) with a Kaiser-designed linear-phase kernel, group-delay compensated (effectively zero-phase; an IIR resampler would distort phase, which matters for transfer-function and modal work).

Filter placement (f_Nyq = min(fs, fs_new)/2):

  • Downsampling (fs_new < fs): stopband at the NEW Nyquist, passband edge at fs_new/2.56 — the standard DSA guard-band convention (passband to 0.78x Nyquist), the same margin a delta-sigma module's built-in anti-alias filter uses. Everything above the new Nyquist is attenuated by stopband_db (default 96 dB) BEFORE the rate drops, so nothing aliases; rejecting the out-of-band noise also buys ~10*log10(fs/fs_new) dB of broadband-noise process gain. This is what makes it the noise-REDUCING method (multiplexed-SAR hardware — NI USB-6003/6212, sound cards — has no analogue anti-alias filter at all, so this chain is what stands between out-of-band content and your band).
  • Upsampling (fs_new > fs): stopband at the ORIGINAL Nyquist (kills the zero-stuffing images, so NO frequency content above the original band is invented — the failure mode of linear interpolation, whose triangular kernel is a sinc^2 filter that both droops the passband and leaks imaging residue), passband to 0.92x the original Nyquist so the recorded band passes essentially untouched.

The first/last ~numtaps/(2*down) output samples carry the usual FIR edge transient. Sample 0 maps to sample 0 (delay-compensated), so a pretrigger position at input index k lands at output index k * up/down.

Parameters:

  • y (ndarray) –

    Shape (N,) or (N, n_channels), one time series per column.

  • fs (float) –

    Current sample rate in Hz.

  • fs_new (float) –

    Target sample rate in Hz (> 0). fs_new == fs returns the input unchanged.

  • stopband_db (float, default: 96.0 ) –

    Stopband attenuation of the Kaiser design in dB (default 96).

Returns:

  • y_out ( ndarray ) –

    The resampled array, with the same number of dimensions as y.

  • fs_out ( float ) –

    The exact output rate fs * up/down, equal to fs_new whenever the ratio is representable.

  • factors ( tuple[int, int] ) –

    The rational factors (up, down) used.

Raises:

  • ValueError –

    fs or fs_new is not positive, or fs_new is too small relative to fs to represent.

multiply_by_power_of_iw

multiply_by_power_of_iw(data, power, channel_list)

Multiply chosen channels of a spectrum or TF by (i*omega)**power, in place.

Converts between displacement, velocity and acceleration: for example power=1 turns a displacement spectrum into velocity and power=-2 turns acceleration into displacement, with omega = 2*pi*f from the item's own freq_axis.

The argument is MODIFIED IN PLACE (its freq_data or tf_data columns are overwritten) and the same object is returned, so take a copy.deepcopy first if the original is still needed. The cumulative power applied to each channel is kept in an iw_power_counter array on the item (created on first use), so power=1 followed by power=-1 returns the counter to where it started.

For a negative power the bin at 0 Hz (f = 0) has no finite value and is set to 0. It is not restored by a later positive power. Only a bin actually at 0 Hz is treated this way, so an axis that does not start at 0 Hz (such as a BLA set's excited bins) is scaled throughout.

Parameters:

  • data (FreqData or TfData) –

    The item to scale.

  • power (int or float) –

    The exponent p in (i*omega)**p.

  • channel_list (list[int] or ndarray) –

    Column indices of freq_data / tf_data to scale; other columns are left unchanged. Pass a list even for one channel ([1]): a bare integer raises a broadcasting ValueError.

Returns:

  • data ( FreqData or TfData ) –

    data itself, after scaling. Any other type is returned unchanged after printing a message.

clean_impulse

clean_impulse(time_data, ch_impulse=0)

Taper the tail of a hammer-force channel to zero after the impulse.

Only channel ch_impulse is changed. The pulse width T is estimated from the width of the largest peak at half its amplitude, assuming a half-cosine pulse (T = 1.5 x that width). Samples up to the estimated end of the pulse (peak + T/2) are unchanged; after it the channel is ramped to zero with a half-cosine taper of length 10 T and is zero from then on.

The result is a deep copy marked impulse_cleaned = True; a TimeData already marked that way is returned as it is (the same object), so cleaning twice changes nothing. The outcome is printed and also stored in the module variable analysis.MESSAGE, including a warning when the taper changed any sample by more than 10 % of the peak amplitude (a sign of a double hit, or of the wrong channel).

Parameters:

  • time_data (TimeData) –

    The capture to clean. If it has no impulse_cleaned attribute, one is added (set to False).

  • ch_impulse (int, default: 0 ) –

    Column index of the force (impulse) channel (default 0).

Returns:

  • time_data ( TimeData ) –

    A cleaned deep copy, or time_data itself if it was already cleaned.

best_match

best_match(tf_data_list, freq_range=None, set_ref=0, ch_ref=0)

Scale factors that overlay a family of transfer functions on one reference.

Every TF column of every set is compared with ONE reference column (set set_ref, channel ch_ref) over freq_range, both interpolated onto a common frequency grid. Each factor is the ratio of their RMS magnitudes, signed by a real least-squares fit, so a column multiplied by its factor lies over the reference; the reference's own factor is 1. Useful for comparing TFs measured at different drive levels or gains.

To apply them, tf_data_list.set_calibration_factors_all([f.ravel() for f in factors]). That REPLACES each set's channel_cal_factors, including any physical calibration they held, rather than multiplying into them.

Parameters:

  • tf_data_list (TfDataList) –

    The transfer functions to match.

  • freq_range ((list, ndarray or PlotData), default: None ) –

    The band to match over, [f_min, f_max] in Hz. A PlotData uses its visible x-range. None (the default) uses the reference set's whole frequency axis, where noise at the ends can skew the factors, so prefer a band where the TFs are clean.

  • set_ref (int, default: 0 ) –

    Index of the reference set. Default 0.

  • ch_ref (int, default: 0 ) –

    Index of the reference channel (TF column) in that set. Default 0.

Returns:

  • factors ( list of np.ndarray ) –

    One array per set, in order, of shape (n_channels, 1): the factor for each of that set's TF columns, relative to set set_ref, channel ch_ref.

Raises:

  • ValueError –

    If tf_data_list is not a TfDataList.

Units

wrap_unit

wrap_unit(unit)

Parenthesise a COMPOUND unit so it composes unambiguously.

A unit containing anything other than a letter or a digit is wrapped: 'm/s2' -> '(m/s2)', while 'N' and 'Pa' are left bare. Without this, a transfer function's unit string is ambiguous — 'm/s2/N' reads equally as (m/s2)/N (what it means) or m/(s2*N) (what it does not) — and anything reading the file outside pydvma has to guess.

Idempotent: a unit already wrapped in a single matched outer pair is returned unchanged, so composing twice does not nest.

TWIN of the browser's wrapUnit (webui/src/lib/model/calibration.ts), which builds the same strings for its own plot labels; the two are pinned by the shared vectors in UNIT_WRAP_VECTORS, mirrored in webui/tests/model/wrapUnit.test.ts.

NB an OLD file keeps whatever it was written with: an unparenthesised 'm/s2/N' cannot be split back into numerator and denominator without guessing, so it is left alone rather than rewritten.

Parameters:

  • unit (str) –

    A unit string, e.g. 'm/s2'.

Returns the unit, parenthesised only if it needs it.

Acoustics

Sound pressure level, frequency weighting, band levels and calibration from a reference tone. The web app's frequency view draws the same curves and bands from a TypeScript twin pinned to these by shared known-answer vectors.

P_REF module-attribute

P_REF = 2e-05

Reference sound pressure, 20 micropascals.

weighting_db

weighting_db(f, curve)

IEC 61672-1 frequency weighting in dB.

The analytic A and C curves (poles 20.6, 107.7, 737.9 and 12194 Hz), normalised to exactly 0 dB at 1 kHz.

Parameters:

  • f (array_like) –

    Frequencies in Hz.

  • curve (str) –

    'Z' (flat), 'A' or 'C'.

Returns an array of weightings in dB shaped like f. 'Z' gives zeros; f <= 0 gives -inf for 'A' and 'C'.

Raises:

  • ValueError –

    curve is not 'Z', 'A' or 'C'.

band_table

band_table(bands, f_lo, f_hi)

IEC 61260 base-10 octave or third-octave bands inside a range.

Parameters:

  • bands (str) –

    'octave' or 'third-octave'.

  • f_lo (float) –

    Lowest frequency a band may reach, Hz.

  • f_hi (float) –

    Highest frequency a band may reach, Hz.

Returns a dict of equal-length lists centre (exact midbands), nominal (IEC labels), lower and upper (band edges). Only bands with lower >= f_lo and upper <= f_hi are listed.

Raises:

  • ValueError –

    bands is not a known kind.

band_levels

band_levels(f, psd, bands='octave', weighting='Z', min_bins=3)

Band powers from a power spectral DENSITY.

power = sum(psd * 10**(W/10) * df) over the bins with lower <= f < upper. A power SPECTRUM would over-count broadband power by the window's noise bandwidth, so a density is required.

Parameters:

  • f (array_like) –

    Frequency axis in Hz, uniformly spaced.

  • psd (array_like) –

    Density in unit^2/Hz, shape (Nf,) or (Nc, Nf).

  • bands (str, default: 'octave' ) –

    'octave' or 'third-octave'.

  • weighting (str, default: 'Z' ) –

    'Z', 'A' or 'C'.

  • min_bins (int, default: 3 ) –

    Bands with fewer bins are dropped.

Returns a dict with the band_table keys plus power (shape (Nb,) or (Nc, Nb), unit^2) and n_bins. The weighting at 0 Hz is -inf dB, i.e. zero weight, so the DC bin adds nothing.

tone_rms

tone_rms(x, fs, freq, bin_neighbours=2)

Robust RMS amplitude of a single tone, via a windowed periodogram.

Windows x with a periodic Hann window and sums power over the 2 * bin_neighbours + 1 bins around the tone's expected bin, then normalises by the window's power gain (Parseval), so leakage from a tone off a bin centre is captured while broadband noise elsewhere is not.

Parameters:

  • x (ndarray) –

    1D real time-domain samples.

  • fs (float) –

    Sample rate in Hz.

  • freq (float) –

    Expected tone frequency in Hz.

  • bin_neighbours (int, default: 2 ) –

    Bins summed either side of the nearest bin.

Returns the tone's RMS amplitude in the units of x.

reference_tone_calibration

reference_tone_calibration(time_data, channel, ref_rms, freq, *, freq_tolerance=0.05, check_clip=True)

Sensitivity of one channel from an acoustic calibrator's tone.

Analyses the middle 80 % of the record. The sensitivity is the measured tone rms (stored units) over ref_rms (engineering units, e.g. 1 Pa).

Parameters:

  • time_data (TimeData) –

    The capture; settings.input_vmax(channel) is used for the clip check when available.

  • channel (int) –

    Channel holding the calibrator tone.

  • ref_rms (float) –

    The calibrator's rms level in engineering units; a finite number above zero.

  • freq (float) –

    The calibrator's frequency in Hz.

  • freq_tolerance (float, default: 0.05 ) –

    Allowed fractional offset of the spectral peak from freq before a warning is raised.

  • check_clip (bool, default: True ) –

    False skips the clip check, for a capture whose settings state no input rail (clipped is then False).

Returns a dict: sensitivity (stored units per engineering unit), measured_rms, peak_freq, tone_to_total_db, clipped and warnings (strings quoting the numbers). Warnings cover a peak more than freq_tolerance from freq, broadband rms more than 1 dB above the tone, and a peak at or above 0.95 of the input rail.

Raises:

  • ValueError –

    ref_rms is not a finite number above zero, which has no sensitivity to give.