Skip to content

HMath.Signal

Module index · Numerical conventions

Description

CPU reference DSP. Sample rates/frequencies are in Hz, times in seconds, angular frequencies in radians/sample. Filtering uses causal zero-state initial conditions and transposed direct form II; state is explicit and may be carried across blocks. Convolution is full linear convolution; correlation lags run -(length y-1)..length x-1 and real-valued y is reversed.

Filter prototypes use the classical bilinear transform and prewarped edges; elliptic prototypes use Jacobi elliptic identities and the nome degree equation (see https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.ellipap.html and https://dlmf.nist.gov/22.6). Bessel is delay-normalized, so its supplied edge is a prototype scale, not the Butterworth half-power frequency. Wavelets use periodic extension; lengths must be divisible by 2^levels.

On this page

API Purpose
convolution Direct full real linear convolution, with explicit quadratic work budget; an empty operand yields an empty result.
circularConvolution Length-N periodic convolution of two equally sized nonempty real signals (N<=4096).
correlation Full real cross-correlation, equivalent to convolution with the reversed second signal.
autocorrelation Unnormalized full autocorrelation with zero lag in the middle.
overlapAdd Block FFT linear convolution; block is the number of new input samples, not the padded transform length.
overlapSave Streaming FFT convolution with explicit transform length >= kernel length; retained block size is N-M+1.
Filter Opaque normalized numerator/denominator and caller-visible persistent delay state.
iir Normalize finite ascending z^-1 coefficients by nonzero a0 and initialize a zero transposed-direct-form-II state.
fir Construct a causal zero-state finite-impulse-response filter; maximum 257 taps.
filterCoefficients Read normalized padded (numerator,denominator) coefficients in increasing delay order.
filterState Read explicit delay state after a block; the list is immutable and independently reusable.
resetFilter Preserve coefficients while replacing every delay with zero.
filterSignal Process a finite input block, returning both its output and the filter state for the next block.
FilterFamily Classical analog prototypes with ripple/attenuation parameters in decibels.
Butterworth Declaration and type contract below.
ChebyshevI Declaration and type contract below.
ChebyshevII Declaration and type contract below.
Elliptic Declaration and type contract below.
Bessel Declaration and type contract below.
FilterBand Prewarped low/high edge or ordered band edges, all in Hz.
Lowpass Declaration and type contract below.
Highpass Declaration and type contract below.
Bandpass Declaration and type contract below.
Bandstop Declaration and type contract below.
designIIR Orders 1..8; rippleattenuation in dB; all edges strictly inside (0, fs2).
frequencyResponse Complex unit-circle response at omega radians/sample; reject poles and nonfinite arithmetic.
notch Second-order notch or unity-magnitude all-pass with center omega in (0,pi) and positive quality factor Q.
allPass Second-order notch or unity-magnitude all-pass with center omega in (0,pi) and positive quality factor Q.
movingAverage Causal zero-state box FIR with supplied width; initial outputs include implicit leading zeros.
medianFilter Centered odd-width running median using replicate endpoint padding.
gaussianFilter Centered normalized Gaussian convolution with supplied sigma in samples and odd support width.
savitzkyGolay Centered local QR polynomial fit; choose width, degree, derivative order and positive sample spacing.
wiener Local mean/variance Wiener shrinkage; optional noise variance, otherwise average local variance is estimated.
Window Symmetric endpoint-inclusive windows, with shape parameters betasigmaalpha/attenuation as appropriate.
Hann Declaration and type contract below.
Hamming Declaration and type contract below.
Blackman Declaration and type contract below.
Bartlett Declaration and type contract below.
Kaiser Declaration and type contract below.
Gaussian Declaration and type contract below.
Tukey Declaration and type contract below.
FlatTop Declaration and type contract below.
DolphChebyshev Declaration and type contract below.
window Generate a finite symmetric window.
windowedSinc Given window kind, odd tap count in [1,257], cutoff frequency and positive sample rate, return normalized low-pass FIR coefficients.
downsample Select indices congruent to offset modulo factor; this primitive performs no implicit anti-alias filtering.
upsample Insert factor-1 zeros after each sample, with a checked 1048576-element output budget.
resamplePolyphase Zero-extended centered polyphase FIR resampling.
resample Construct a Kaiser-windowed anti-alias/interpolation FIR, then evaluate only the necessary rational polyphase taps.
antiAlias Centered replicate-padded low-pass before decimation by factor; cutoff is 0.45factor cyclessample.
Peak Interior peak index, height, topographic prominence and half-prominence width in samples.
Peak Declaration and type contract below.
peakIndex Zero-based sample index of the detected peak.
peakHeight Sample amplitude at peakIndex.
peakProminence Peak height above its reference surrounding contour level.
peakWidth Estimated width at the selected prominence height, measured in samples.
peaks Interior local maxima; flat plateaus select the lower middle index.
zeroCrossings Interpolated opposite-sign transitions; zero plateaus count once, leading/trailing zeros are ignored.
envelope Magnitude of the periodic analytic-signal representation.
unwrapPhase Remove nearest multiples of 2*pi from adjacent phase jumps; reject overflowing finite differences before integer conversion.
detrend Subtract a constant mean or a fitted linear trend in sample index.
normalize Divide by maximum absolute amplitude; reject an empty or identically zero signal.
smooth Centered odd-width arithmetic mean with replicate endpoint padding.
noiseEstimate Robust Gaussian noise sigma from median absolute adjacent differences divided by sqrt(2)*Phi^-1(0.75).
signalToNoise 20*(log10(signal RMS)-log10(noise RMS)) in dB; both energies must be positive.
rms Scaled root-mean-square calculation that avoids overflow when the RMS itself is representable.
GaussianState Mean and symmetric positive semidefinite covariance, dimension 1..64.
gaussianState Validate a mean and symmetric positive semidefinite covariance; Cholesky roundoff tolerance is 1e-12*max(1,diagonal).
stateMean Read the posterior mean vector.
stateCovariance Read the symmetric posterior covariance matrix.
kalman One linear Gaussian prediction+measurement update.
extendedKalman EKF with checked central-difference Jacobians (step 1e-5*max(1,abs x)).
unscentedKalman Scaled UKF. alpha>0, beta>=0, n+kappa>0, lambda+n>0.
Wavelet Orthogonal Haar, 4-tap db2, 8-tap db4, and reversible CDF 5/3 lifting.
Haar Declaration and type contract below.
Daubechies2 Declaration and type contract below.
Daubechies4 Declaration and type contract below.
Biorthogonal53 Declaration and type contract below.
WaveletTree Opaque multilevel approximation and detail coefficients, retaining family and original length.
dwt Periodic multilevel analysis; length must be divisible by 2^levels, with levels 0..20 and length <=1048576.
idwt Invert multilevel analysis using orthogonal synthesis or inverse CDF 5/3 lifting.
waveletApproximation Coarsest approximation coefficients after all requested levels.
waveletDetails Detail bands ordered from finest first to coarsest last.
MotherWavelet Admissible corrected complex Morlet, real Mexican hat, or real first Gaussian derivative.
Morlet Declaration and type contract below.
MexicanHat Declaration and type contract below.
GaussianDerivative Declaration and type contract below.
cwt Direct zero-extended CWT.
WaveletPacket Opaque complete binary low/high analysis tree in natural binary order, rather than frequency-sorted Gray order.
waveletPackets Recursively analyze both approximation and detail branches to the supplied depth.
inverseWaveletPackets Reconstruct a complete packet tree exactly up to floating roundoff.
packetBands Leaf coefficient bands in natural binary low/high tree order.
waveletDenoise Soft-threshold detail coefficients; optional explicit threshold, otherwise finest-band MAD universal threshold.

Documentation

convolution

convolution :: [Double] -> [Double] -> Either MathError [Double] Source #

Direct full real linear convolution, with explicit quadratic work budget; an empty operand yields an empty result.

circularConvolution

circularConvolution :: [Double] -> [Double] -> Either MathError [Double] Source #

Length-N periodic convolution of two equally sized nonempty real signals (N<=4096).

correlation

correlation :: [Double] -> [Double] -> Either MathError [Double] Source #

Full real cross-correlation, equivalent to convolution with the reversed second signal.

autocorrelation

autocorrelation :: [Double] -> Either MathError [Double] Source #

Unnormalized full autocorrelation with zero lag in the middle.

overlapAdd

overlapAdd :: Int -> [Double] -> [Double] -> Either MathError [Double] Source #

Block FFT linear convolution; block is the number of new input samples, not the padded transform length.

overlapSave

overlapSave :: Int -> [Double] -> [Double] -> Either MathError [Double] Source #

Streaming FFT convolution with explicit transform length >= kernel length; retained block size is N-M+1.

Filter

data Filter Source #

Opaque normalized numerator/denominator and caller-visible persistent delay state.

Instances

Instances details
Show Filter Source # 
Instance details

Defined in HMath.Signal

Eq Filter Source # 
Instance details

Defined in HMath.Signal

Methods

(==) :: Filter -> Filter -> Bool #

(/=) :: Filter -> Filter -> Bool #

iir

iir :: [Double] -> [Double] -> Either MathError Filter Source #

Normalize finite ascending z^-1 coefficients by nonzero a0 and initialize a zero transposed-direct-form-II state.

fir

fir :: [Double] -> Either MathError Filter Source #

Construct a causal zero-state finite-impulse-response filter; maximum 257 taps.

filterCoefficients

filterCoefficients :: Filter -> ([Double], [Double]) Source #

Read normalized padded (numerator,denominator) coefficients in increasing delay order.

filterState

filterState :: Filter -> [Double] Source #

Read explicit delay state after a block; the list is immutable and independently reusable.

resetFilter

resetFilter :: Filter -> Filter Source #

Preserve coefficients while replacing every delay with zero.

filterSignal

filterSignal :: Filter -> [Double] -> Either MathError ([Double], Filter) Source #

Process a finite input block, returning both its output and the filter state for the next block.

FilterFamily

data FilterFamily Source #

Classical analog prototypes with ripple/attenuation parameters in decibels.

Instances

Instances details
Show FilterFamily Source # 
Instance details

Defined in HMath.Signal

Eq FilterFamily Source # 
Instance details

Defined in HMath.Signal

FilterBand

data FilterBand Source #

Prewarped low/high edge or ordered band edges, all in Hz.

Instances

Instances details
Show FilterBand Source # 
Instance details

Defined in HMath.Signal

Eq FilterBand Source # 
Instance details

Defined in HMath.Signal

designIIR

designIIR :: FilterFamily -> FilterBand -> Int -> Double -> Either MathError Filter Source #

Orders 1..8; rippleattenuation in dB; all edges strictly inside (0, fs2). Expanded coefficients are a bounded reference representation; high orders should use cascaded sections in production applications.

frequencyResponse

frequencyResponse :: Filter -> Double -> Either MathError (Complex Double) Source #

Complex unit-circle response at omega radians/sample; reject poles and nonfinite arithmetic.

notch

notch :: Double -> Double -> Either MathError Filter Source #

Second-order notch or unity-magnitude all-pass with center omega in (0,pi) and positive quality factor Q.

allPass

allPass :: Double -> Double -> Either MathError Filter Source #

Second-order notch or unity-magnitude all-pass with center omega in (0,pi) and positive quality factor Q.

movingAverage

movingAverage :: Int -> [Double] -> Either MathError [Double] Source #

Causal zero-state box FIR with supplied width; initial outputs include implicit leading zeros.

medianFilter

medianFilter :: Int -> [Double] -> Either MathError [Double] Source #

Centered odd-width running median using replicate endpoint padding.

gaussianFilter

gaussianFilter :: Int -> Double -> [Double] -> Either MathError [Double] Source #

Centered normalized Gaussian convolution with supplied sigma in samples and odd support width.

savitzkyGolay

savitzkyGolay :: Int -> Int -> Int -> Double -> [Double] -> Either MathError [Double] Source #

Centered local QR polynomial fit; choose width, degree, derivative order and positive sample spacing.

wiener

wiener :: Int -> Maybe Double -> [Double] -> Either MathError [Double] Source #

Local mean/variance Wiener shrinkage; optional noise variance, otherwise average local variance is estimated.

Window

data Window Source #

Symmetric endpoint-inclusive windows, with shape parameters betasigmaalpha/attenuation as appropriate.

Instances

Instances details
Show Window Source # 
Instance details

Defined in HMath.Signal

Eq Window Source # 
Instance details

Defined in HMath.Signal

Methods

(==) :: Window -> Window -> Bool #

(/=) :: Window -> Window -> Bool #

window

window :: Window -> Int -> Either MathError [Double] Source #

Generate a finite symmetric window. Gaussian sigma is relative to half length; Dolph attenuation is in dB.

windowedSinc

windowedSinc :: Window -> Int -> Double -> Double -> Either MathError [Double] Source #

Given window kind, odd tap count in [1,257], cutoff frequency and positive sample rate, return normalized low-pass FIR coefficients. Require 0<cutoff<rate/2 and finite parameters; invalid values or normalization failure returns Left MathError.

downsample

downsample :: Int -> Int -> [Double] -> Either MathError [Double] Source #

Select indices congruent to offset modulo factor; this primitive performs no implicit anti-alias filtering.

upsample

upsample :: Int -> [Double] -> Either MathError [Double] Source #

Insert factor-1 zeros after each sample, with a checked 1048576-element output budget.

resamplePolyphase

resamplePolyphase :: Int -> Int -> [Double] -> [Double] -> Either MathError [Double] Source #

Zero-extended centered polyphase FIR resampling. Only nonzero upsampled phases are evaluated. Output has ceiling(N*up/down) samples, no group delay. Kernel has odd length and is centered at index length/2; gain includes up.

resample

resample :: Int -> Int -> Int -> [Double] -> Either MathError [Double] Source #

Construct a Kaiser-windowed anti-alias/interpolation FIR, then evaluate only the necessary rational polyphase taps.

antiAlias

antiAlias :: Int -> Int -> [Double] -> Either MathError [Double] Source #

Centered replicate-padded low-pass before decimation by factor; cutoff is 0.45factor cyclessample.

Peak

data Peak Source #

Interior peak index, height, topographic prominence and half-prominence width in samples.

Constructors

Peak 

Fields

Instances

Instances details
Show Peak Source # 
Instance details

Defined in HMath.Signal

Methods

showsPrec :: Int -> Peak -> ShowS #

show :: Peak -> String #

showList :: [Peak] -> ShowS #

Eq Peak Source # 
Instance details

Defined in HMath.Signal

Methods

(==) :: Peak -> Peak -> Bool #

(/=) :: Peak -> Peak -> Bool #

peaks

peaks :: Double -> Int -> [Double] -> Either MathError [Peak] Source #

Interior local maxima; flat plateaus select the lower middle index. Width is linearly interpolated at half prominence; endpoints are not peaks.

zeroCrossings

zeroCrossings :: [Double] -> Either MathError [Double] Source #

Interpolated opposite-sign transitions; zero plateaus count once, leading/trailing zeros are ignored.

envelope

envelope :: [Double] -> Either MathError [Double] Source #

Magnitude of the periodic analytic-signal representation.

unwrapPhase

unwrapPhase :: [Double] -> Either MathError [Double] Source #

Remove nearest multiples of 2*pi from adjacent phase jumps; reject overflowing finite differences before integer conversion.

detrend

detrend :: Bool -> [Double] -> Either MathError [Double] Source #

Subtract a constant mean or a fitted linear trend in sample index.

normalize

normalize :: [Double] -> Either MathError [Double] Source #

Divide by maximum absolute amplitude; reject an empty or identically zero signal.

smooth

smooth :: Int -> [Double] -> Either MathError [Double] Source #

Centered odd-width arithmetic mean with replicate endpoint padding.

noiseEstimate

noiseEstimate :: [Double] -> Either MathError Double Source #

Robust Gaussian noise sigma from median absolute adjacent differences divided by sqrt(2)*Phi^-1(0.75).

signalToNoise

signalToNoise :: [Double] -> [Double] -> Either MathError Double Source #

20*(log10(signal RMS)-log10(noise RMS)) in dB; both energies must be positive.

rms

rms :: [Double] -> Either MathError Double Source #

Scaled root-mean-square calculation that avoids overflow when the RMS itself is representable.

GaussianState

data GaussianState Source #

Mean and symmetric positive semidefinite covariance, dimension 1..64. User-supplied transition/measurement callbacks must be finite, pure and total.

Instances

Instances details
Show GaussianState Source # 
Instance details

Defined in HMath.Signal

Eq GaussianState Source # 
Instance details

Defined in HMath.Signal

gaussianState

gaussianState :: [Double] -> [[Double]] -> Either MathError GaussianState Source #

Validate a mean and symmetric positive semidefinite covariance; Cholesky roundoff tolerance is 1e-12*max(1,diagonal). Accepted tiny negative pivots are clipped, and the stored covariance is reconstructed from that factor. Thus a tolerated negative input variance never escapes through stateCovariance.

stateMean

stateMean :: GaussianState -> [Double] Source #

Read the posterior mean vector.

stateCovariance

stateCovariance :: GaussianState -> [[Double]] Source #

Read the symmetric posterior covariance matrix.

kalman

kalman :: [[Double]] -> [[Double]] -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState Source #

One linear Gaussian prediction+measurement update. Uses Joseph covariance update to preserve positive semidefiniteness under roundoff.

extendedKalman

extendedKalman :: ([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState Source #

EKF with checked central-difference Jacobians (step 1e-5*max(1,abs x)).

unscentedKalman

unscentedKalman :: Double -> Double -> Double -> ([Double] -> [Double]) -> ([Double] -> [Double]) -> [[Double]] -> [[Double]] -> [Double] -> GaussianState -> Either MathError GaussianState Source #

Scaled UKF. alpha>0, beta>=0, n+kappa>0, lambda+n>0. Process noise is incorporated before regenerating measurement sigma points.

Wavelet

data Wavelet Source #

Orthogonal Haar, 4-tap db2, 8-tap db4, and reversible CDF 5/3 lifting. CDF coefficients use the unnormalized lifting convention (constant detail=0).

Instances

Instances details
Show Wavelet Source # 
Instance details

Defined in HMath.Signal

Eq Wavelet Source # 
Instance details

Defined in HMath.Signal

Methods

(==) :: Wavelet -> Wavelet -> Bool #

(/=) :: Wavelet -> Wavelet -> Bool #

WaveletTree

data WaveletTree Source #

Opaque multilevel approximation and detail coefficients, retaining family and original length.

Instances

Instances details
Show WaveletTree Source # 
Instance details

Defined in HMath.Signal

Eq WaveletTree Source # 
Instance details

Defined in HMath.Signal

dwt

dwt :: Wavelet -> Int -> [Double] -> Either MathError WaveletTree Source #

Periodic multilevel analysis; length must be divisible by 2^levels, with levels 0..20 and length <=1048576.

idwt

idwt :: WaveletTree -> Either MathError [Double] Source #

Invert multilevel analysis using orthogonal synthesis or inverse CDF 5/3 lifting.

waveletApproximation

waveletApproximation :: WaveletTree -> [Double] Source #

Coarsest approximation coefficients after all requested levels.

waveletDetails

waveletDetails :: WaveletTree -> [[Double]] Source #

Detail bands ordered from finest first to coarsest last.

MotherWavelet

data MotherWavelet Source #

Admissible corrected complex Morlet, real Mexican hat, or real first Gaussian derivative.

Instances

Instances details
Show MotherWavelet Source # 
Instance details

Defined in HMath.Signal

Eq MotherWavelet Source # 
Instance details

Defined in HMath.Signal

cwt

cwt :: MotherWavelet -> Double -> [Double] -> [Double] -> Either MathError [[Complex Double]] Source #

Direct zero-extended CWT. Scales are in seconds; coefficients use dt/sqrt(s) quadrature. Morlet subtracts its nonzero-mean correction exp(-omega²/2).

WaveletPacket

data WaveletPacket Source #

Opaque complete binary low/high analysis tree in natural binary order, rather than frequency-sorted Gray order.

Instances

Instances details
Show WaveletPacket Source # 
Instance details

Defined in HMath.Signal

Eq WaveletPacket Source # 
Instance details

Defined in HMath.Signal

waveletPackets

waveletPackets :: Wavelet -> Int -> [Double] -> Either MathError WaveletPacket Source #

Recursively analyze both approximation and detail branches to the supplied depth.

inverseWaveletPackets

inverseWaveletPackets :: WaveletPacket -> Either MathError [Double] Source #

Reconstruct a complete packet tree exactly up to floating roundoff.

packetBands

packetBands :: WaveletPacket -> [[Double]] Source #

Leaf coefficient bands in natural binary low/high tree order.

waveletDenoise

waveletDenoise :: Wavelet -> Int -> Maybe Double -> [Double] -> Either MathError [Double] Source #

Soft-threshold detail coefficients; optional explicit threshold, otherwise finest-band MAD universal threshold.