Signal Processing¶
- class endgame.signal.BaseFeatureExtractor(fs=None)[source]¶
Bases:
BaseEstimator,TransformerMixin,SignalMixinBase class for feature extraction from signals.
Unlike transformers that output signals, feature extractors output feature vectors suitable for machine learning.
- Parameters:
fs (float, optional) – Sample rate in Hz.
- fit(X, y=None, **fit_params)[source]¶
Fit the feature extractor.
- Parameters:
X (array-like) – Input signals of shape (n_samples, n_timepoints) or (n_samples, n_channels, n_timepoints).
y (ignored)
- Return type:
- Returns:
self
- class endgame.signal.BaseSignalTransformer(fs=None, copy=True)[source]¶
Bases:
BaseEstimator,TransformerMixin,SignalMixinBase class for all signal processing transformers.
Provides sklearn-compatible interface with signal-specific extensions.
- Parameters:
- fit(X, y=None, **fit_params)[source]¶
Fit the transformer.
Most signal transformers don’t need fitting, but this provides a consistent sklearn interface.
- Parameters:
X (array-like) – Input signal.
y (ignored)
**fit_params (dict) – Additional parameters.
- Return type:
- Returns:
self
- abstractmethod transform(X)[source]¶
Transform the signal.
- Parameters:
X (array-like) – Input signal.
- Return type:
- Returns:
np.ndarray – Transformed signal.
- inverse_transform(X)[source]¶
Inverse transform (if applicable).
- Parameters:
X (array-like) – Transformed signal.
- Return type:
- Returns:
np.ndarray – Reconstructed signal.
- Raises:
NotImplementedError – If inverse transform is not supported.
- class endgame.signal.SignalMixin[source]¶
Bases:
objectMixin providing common signal processing functionality.
Handles input validation, reshaping, and sample rate management for all signal processing transformers.
- class endgame.signal.ButterworthFilter(lowcut=None, highcut=None, fs=None, order=4, btype=None, padlen=None)[source]¶
Bases:
BaseSignalTransformerButterworth IIR filter with zero-phase filtering.
Applies a Butterworth filter using scipy.signal.filtfilt for zero-phase distortion (forward-backward filtering).
- Parameters:
lowcut (float, optional) – Low cutoff frequency in Hz. Required for highpass/bandpass.
highcut (float, optional) – High cutoff frequency in Hz. Required for lowpass/bandpass.
fs (float) – Sample rate in Hz.
order (int, default=4) – Filter order. Higher = sharper rolloff but more ringing.
btype (str, optional) – Filter type: ‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’. Auto-detected from lowcut/highcut if not specified.
padlen (int, optional) – Padding length for filtfilt. Default is 3 * max(len(a), len(b)).
Examples
>>> # Bandpass filter 0.5-50 Hz >>> filt = ButterworthFilter(lowcut=0.5, highcut=50, fs=256, order=4) >>> filtered = filt.fit_transform(signal)
>>> # Highpass filter (remove DC and drift) >>> filt = ButterworthFilter(lowcut=0.1, fs=256) >>> filtered = filt.fit_transform(signal)
Notes
Uses second-order sections (SOS) format for numerical stability, especially at higher orders.
- fit(X, y=None, **fit_params)[source]¶
Fit the filter (designs the filter coefficients).
- Return type:
- transform(X)[source]¶
Apply zero-phase Butterworth filter.
- Parameters:
X (array-like) – Input signal(s).
- Return type:
- Returns:
np.ndarray – Filtered signal(s).
- class endgame.signal.FIRFilter(lowcut=None, highcut=None, fs=None, numtaps=101, window='hamming', pass_zero=None)[source]¶
Bases:
BaseSignalTransformerFIR filter using window-based design.
Finite Impulse Response filter designed using the window method. Linear phase (no phase distortion) when using filtfilt.
- Parameters:
lowcut (float, optional) – Low cutoff frequency in Hz.
highcut (float, optional) – High cutoff frequency in Hz.
fs (float) – Sample rate in Hz.
numtaps (int, default=101) – Number of filter taps (filter length). Must be odd for Type I filter.
window (str, default='hamming') – Window function: ‘hamming’, ‘hann’, ‘blackman’, ‘kaiser’, etc.
pass_zero (bool or str, optional) – If True, DC gain is 1. Auto-detected if not specified.
Examples
>>> # Bandpass FIR filter >>> filt = FIRFilter(lowcut=1, highcut=40, fs=256, numtaps=101) >>> filtered = filt.fit_transform(signal)
Notes
FIR filters are inherently stable and have linear phase, but require more taps than IIR filters for sharp transitions.
- class endgame.signal.SavgolFilter(window_length=11, polyorder=3, deriv=0, delta=1.0, mode='interp', fs=None)[source]¶
Bases:
BaseSignalTransformerSavitzky-Golay smoothing filter.
Performs polynomial smoothing using local least-squares fitting. Preserves signal features better than simple moving average.
- Parameters:
window_length (int, default=11) – Window size in samples. Must be odd and > polyorder.
polyorder (int, default=3) – Polynomial order for fitting.
deriv (int, default=0) – Derivative order (0 = smoothing, 1 = first derivative, etc.)
delta (float, default=1.0) – Sample spacing (for derivative calculation).
mode (str, default='interp') – Edge handling: ‘mirror’, ‘constant’, ‘nearest’, ‘wrap’, ‘interp’.
fs (float | None)
Examples
>>> # Smooth signal >>> filt = SavgolFilter(window_length=11, polyorder=3) >>> smoothed = filt.fit_transform(noisy_signal)
>>> # Compute smooth derivative >>> filt = SavgolFilter(window_length=11, polyorder=3, deriv=1, delta=1/fs) >>> velocity = filt.fit_transform(position)
Notes
Savitzky-Golay filters are particularly good for preserving peaks and other high-frequency features while removing noise.
- class endgame.signal.NotchFilter(freq, fs, Q=30, harmonics=0)[source]¶
Bases:
BaseSignalTransformerNotch filter for removing specific frequencies.
Typically used to remove powerline interference (50/60 Hz) and its harmonics.
- Parameters:
Examples
>>> # Remove 60 Hz powerline noise >>> notch = NotchFilter(freq=60, fs=256, Q=30) >>> clean = notch.fit_transform(signal)
>>> # Remove 50 Hz and first 3 harmonics >>> notch = NotchFilter(freq=50, fs=1000, Q=30, harmonics=3) >>> clean = notch.fit_transform(signal)
- class endgame.signal.MedianFilter(kernel_size=3, fs=None)[source]¶
Bases:
BaseSignalTransformerMedian filter for impulse noise removal.
Non-linear filter that replaces each sample with the median of neighboring samples. Excellent for removing spikes/artifacts.
Examples
>>> # Remove spike artifacts >>> filt = MedianFilter(kernel_size=5) >>> clean = filt.fit_transform(signal_with_spikes)
- class endgame.signal.FilterBank(bands, fs, filter_type='butterworth', order=4, numtaps=101, output='dict')[source]¶
Bases:
BaseSignalTransformerBank of parallel bandpass filters.
Decomposes signal into multiple frequency bands simultaneously. Useful for spectral analysis and feature extraction.
- Parameters:
bands (Dict[str, Tuple[float, float]]) – Dictionary mapping band names to (low, high) frequency tuples. Example: {‘alpha’: (8, 13), ‘beta’: (13, 30)}
fs (float) – Sample rate in Hz.
filter_type (str, default='butterworth') – Filter type: ‘butterworth’ or ‘fir’.
order (int, default=4) – Filter order (for Butterworth).
numtaps (int, default=101) – Number of taps (for FIR).
output (str, default='dict') – Output format: ‘dict’ (separate bands) or ‘stack’ (3D array).
Examples
>>> bands = { ... 'delta': (0.5, 4), ... 'theta': (4, 8), ... 'alpha': (8, 13), ... 'beta': (13, 30), ... 'gamma': (30, 100), ... } >>> fb = FilterBank(bands=bands, fs=256) >>> band_signals = fb.fit_transform(eeg_signal) >>> alpha_signal = band_signals['alpha']
- class endgame.signal.FFTTransformer(fs, output='magnitude', one_sided=True, n_fft=None, normalize=True, copy=True)[source]¶
Bases:
BaseSignalTransformerFast Fourier Transform for frequency spectrum analysis.
Computes the FFT of input signals, returning either the full complex spectrum, magnitude, power, or phase.
- Parameters:
fs (float) – Sample rate in Hz.
output (str, default='magnitude') – Output type: ‘complex’, ‘magnitude’, ‘power’, ‘phase’, ‘db’.
one_sided (bool, default=True) – If True, return only positive frequencies (real FFT).
n_fft (int, optional) – FFT length. If None, uses signal length.
normalize (bool, default=True) – If True, normalize FFT by signal length.
copy (bool, default=True) – Whether to copy input data.
- freqs_¶
Frequency bins after fit.
- Type:
np.ndarray
Examples
>>> fft_trans = FFTTransformer(fs=256, output='magnitude') >>> spectrum = fft_trans.fit_transform(signal) >>> freqs = fft_trans.freqs_
- fit(X, y=None, **fit_params)[source]¶
Fit the transformer (compute frequency bins).
- Parameters:
X (array-like) – Input signal.
y (ignored)
- Return type:
- Returns:
self
- class endgame.signal.WelchPSD(fs, nperseg=None, noverlap=None, nfft=None, window='hann', detrend='constant', scaling='density', average='mean', copy=True)[source]¶
Bases:
BaseSignalTransformerWelch’s method for Power Spectral Density estimation.
Estimates PSD by averaging modified periodograms from overlapping segments.
- Parameters:
fs (float) – Sample rate in Hz.
nperseg (int, optional) – Length of each segment. Default is 256 or signal length.
noverlap (int, optional) – Number of points to overlap. Default is nperseg // 2.
nfft (int, optional) – FFT length. Default is nperseg.
window (str or tuple, default='hann') – Window function to use.
detrend (str or False, default='constant') – Detrending method: ‘constant’, ‘linear’, or False.
scaling (str, default='density') – ‘density’ for V^2/Hz, ‘spectrum’ for V^2.
average (str, default='mean') – Averaging method: ‘mean’ or ‘median’.
copy (bool, default=True) – Whether to copy input data.
- freqs_¶
Frequency bins after fit.
- Type:
np.ndarray
Examples
>>> psd = WelchPSD(fs=256, nperseg=256) >>> power = psd.fit_transform(signal) >>> freqs = psd.freqs_
- fit(X, y=None, **fit_params)[source]¶
Fit the transformer.
- Parameters:
X (array-like) – Input signal.
y (ignored)
- Return type:
- Returns:
self
- transform(X)[source]¶
Compute PSD using Welch’s method.
- Parameters:
X (array-like) – Input signal.
- Return type:
- Returns:
np.ndarray – Power spectral density.
- class endgame.signal.MultitaperPSD(fs, bandwidth=None, n_tapers=None, low_bias=True, adaptive=False, normalization='full', copy=True)[source]¶
Bases:
BaseSignalTransformerMultitaper Power Spectral Density estimation.
Uses multiple orthogonal tapers (DPSS/Slepian sequences) to reduce variance in PSD estimation while maintaining frequency resolution.
- Parameters:
fs (float) – Sample rate in Hz.
bandwidth (float, optional) – Frequency bandwidth of the tapers in Hz. Default is 4 * fs / n_samples (NW=4).
n_tapers (int, optional) – Number of tapers to use. Default is 2 * bandwidth - 1.
low_bias (bool, default=True) – Only use tapers with concentration ratio > 0.9.
adaptive (bool, default=False) – Use adaptive weighting for combining tapers.
normalization (str, default='full') – PSD normalization: ‘full’, ‘length’.
copy (bool, default=True) – Whether to copy input data.
- freqs_¶
Frequency bins after fit.
- Type:
np.ndarray
- dpss_¶
DPSS tapers used.
- Type:
np.ndarray
- eigenvalues_¶
Eigenvalues of the tapers.
- Type:
np.ndarray
References
Thomson, D.J. (1982). Spectrum estimation and harmonic analysis. Proceedings of the IEEE, 70(9), 1055-1096.
Examples
>>> mt_psd = MultitaperPSD(fs=256, bandwidth=4) >>> power = mt_psd.fit_transform(signal)
- class endgame.signal.BandPowerExtractor(fs, bands=None, method='welch', relative=True, log_power=False, welch_params=None, multitaper_params=None)[source]¶
Bases:
BaseFeatureExtractorExtract power in specified frequency bands.
Computes absolute and relative band powers from signals, commonly used for EEG analysis.
- Parameters:
fs (float) – Sample rate in Hz.
bands (dict) – Dictionary mapping band names to (low, high) frequency tuples. Default includes standard EEG bands.
method (str, default='welch') – PSD estimation method: ‘welch’, ‘multitaper’, ‘fft’.
relative (bool, default=True) – If True, also compute relative band powers.
log_power (bool, default=False) – If True, return log10 of band powers.
welch_params (dict, optional) – Additional parameters for Welch’s method.
multitaper_params (dict, optional) – Additional parameters for multitaper method.
Examples
>>> bands = {'alpha': (8, 13), 'beta': (13, 30)} >>> bp = BandPowerExtractor(fs=256, bands=bands) >>> features = bp.fit_transform(eeg_signals)
- DEFAULT_BANDS = {'alpha': (8, 13), 'beta': (13, 30), 'delta': (0.5, 4), 'gamma': (30, 100), 'theta': (4, 8)}¶
- fit(X, y=None, **fit_params)[source]¶
Fit the extractor.
- Parameters:
X (array-like) – Input signals.
y (ignored)
- Return type:
- Returns:
self
- class endgame.signal.SpectralFeatureExtractor(fs, method='welch', edge_percentiles=None, welch_params=None)[source]¶
Bases:
BaseFeatureExtractorExtract comprehensive spectral features from signals.
Computes a variety of frequency-domain features including: - Spectral centroid, spread, skewness, kurtosis - Spectral entropy - Spectral edge frequencies - Spectral flatness and rolloff - Peak frequency
- Parameters:
fs (float) – Sample rate in Hz.
method (str, default='welch') – PSD estimation method: ‘welch’, ‘multitaper’, ‘fft’.
edge_percentiles (list of float, default=[0.5, 0.75, 0.9, 0.95]) – Percentiles for spectral edge frequency computation.
welch_params (dict, optional) – Additional parameters for Welch’s method.
Examples
>>> extractor = SpectralFeatureExtractor(fs=256) >>> features = extractor.fit_transform(signals)
- fit(X, y=None, **fit_params)[source]¶
Fit the extractor.
- Parameters:
X (array-like) – Input signals.
y (ignored)
- Return type:
- Returns:
self
- endgame.signal.compute_psd(x, fs, method='welch', **kwargs)[source]¶
Convenience function to compute PSD.
- Parameters:
- Return type:
- Returns:
freqs (np.ndarray) – Frequency bins.
psd (np.ndarray) – Power spectral density.
Examples
>>> freqs, psd = compute_psd(signal, fs=256, method='welch')
- endgame.signal.compute_band_power(x, fs, band, method='welch', relative=False)[source]¶
Compute power in a frequency band.
- Parameters:
- Return type:
- Returns:
float – Band power.
Examples
>>> alpha_power = compute_band_power(eeg, fs=256, band=(8, 13))
- class endgame.signal.TimeDomainFeatures(fs=None, include_statistical=True, include_hjorth=True, include_zero_crossing=True, include_peaks=True, statistical_features=None, peak_params=None)[source]¶
Bases:
BaseFeatureExtractorComprehensive time-domain feature extraction.
Combines multiple time-domain feature extractors into a single transformer for convenience.
- Parameters:
fs (float, optional) – Sample rate in Hz.
include_statistical (bool, default=True) – Include statistical features.
include_hjorth (bool, default=True) – Include Hjorth parameters.
include_zero_crossing (bool, default=True) – Include zero-crossing features.
include_peaks (bool, default=True) – Include peak features.
statistical_features (list of str, optional) – Specific statistical features to include.
peak_params (dict, optional) – Parameters for peak detection.
Examples
>>> extractor = TimeDomainFeatures(fs=256) >>> features = extractor.fit_transform(signals) >>> print(extractor.feature_names_)
- class endgame.signal.StatisticalFeatures(fs=None, features=None)[source]¶
Bases:
BaseFeatureExtractorExtract statistical features from signals.
Computes basic and higher-order statistical measures.
- Parameters:
fs (float, optional) – Sample rate in Hz (not used but kept for consistency).
features (list of str, optional) – Features to compute. Default includes all. Options: ‘mean’, ‘std’, ‘var’, ‘min’, ‘max’, ‘range’, ‘median’, ‘mad’, ‘iqr’, ‘skew’, ‘kurtosis’, ‘rms’, ‘energy’, ‘line_length’, ‘crest_factor’.
Examples
>>> extractor = StatisticalFeatures() >>> features = extractor.fit_transform(signals)
- ALL_FEATURES = ['mean', 'std', 'var', 'min', 'max', 'range', 'median', 'mad', 'iqr', 'skew', 'kurtosis', 'rms', 'energy', 'line_length', 'crest_factor']¶
- class endgame.signal.HjorthParameters(fs=None, normalize=False)[source]¶
Bases:
BaseFeatureExtractorExtract Hjorth parameters from signals.
Computes the three Hjorth parameters: - Activity: Signal variance (power) - Mobility: Mean frequency (normalized first derivative variance) - Complexity: Change in frequency (bandwidth)
- Parameters:
References
Hjorth, B. (1970). EEG analysis based on time domain properties. Electroencephalography and clinical neurophysiology, 29(3), 306-310.
Examples
>>> hjorth = HjorthParameters() >>> features = hjorth.fit_transform(eeg_signals)
- class endgame.signal.ZeroCrossingFeatures(fs=None, threshold=0.0, compute_rate=True)[source]¶
Bases:
BaseFeatureExtractorExtract zero-crossing related features.
Computes features based on signal zero crossings and threshold crossings.
- Parameters:
Examples
>>> zc = ZeroCrossingFeatures(fs=256) >>> features = zc.fit_transform(signals)
- class endgame.signal.PeakFeatures(fs=None, height=None, threshold=None, distance=None, prominence=None, width=None)[source]¶
Bases:
BaseFeatureExtractorExtract peak-related features from signals.
Detects peaks and computes statistics about their amplitude, width, and distribution.
- Parameters:
fs (float, optional) – Sample rate in Hz.
height (float or tuple, optional) – Required height of peaks.
threshold (float, optional) – Required threshold of peaks.
distance (int, optional) – Required minimal horizontal distance between peaks.
prominence (float or tuple, optional) – Required prominence of peaks.
width (float or tuple, optional) – Required width of peaks in samples.
Examples
>>> peaks = PeakFeatures(fs=256, prominence=0.5) >>> features = peaks.fit_transform(signals)
- endgame.signal.compute_rms(x)[source]¶
Compute root mean square of a signal.
- Parameters:
x (np.ndarray) – Input signal.
- Return type:
- Returns:
float – RMS value.
- endgame.signal.compute_energy(x)[source]¶
Compute signal energy (sum of squared values).
- Parameters:
x (np.ndarray) – Input signal.
- Return type:
- Returns:
float – Signal energy.
- endgame.signal.compute_line_length(x)[source]¶
Compute line length (sum of absolute differences).
- Parameters:
x (np.ndarray) – Input signal.
- Return type:
- Returns:
float – Line length.
- class endgame.signal.PermutationEntropy(fs=None, order=3, delay=1, normalize=True)[source]¶
Bases:
BaseFeatureExtractorPermutation entropy feature extractor.
- Parameters:
Examples
>>> pe = PermutationEntropy(order=3) >>> features = pe.fit_transform(signals)
- class endgame.signal.SampleEntropy(fs=None, order=2, r=None)[source]¶
Bases:
BaseFeatureExtractorSample entropy feature extractor.
- Parameters:
Examples
>>> se = SampleEntropy(order=2) >>> features = se.fit_transform(signals)
- class endgame.signal.ApproximateEntropy(fs=None, order=2, r=None)[source]¶
Bases:
BaseFeatureExtractorApproximate entropy feature extractor.
- Parameters:
Examples
>>> ae = ApproximateEntropy(order=2) >>> features = ae.fit_transform(signals)
- class endgame.signal.SpectralEntropy(fs, method='welch', nperseg=None, normalize=True)[source]¶
Bases:
BaseFeatureExtractorSpectral entropy feature extractor.
- Parameters:
Examples
>>> se = SpectralEntropy(fs=256) >>> features = se.fit_transform(signals)
- class endgame.signal.SVDEntropy(fs=None, order=3, delay=1, normalize=True)[source]¶
Bases:
BaseFeatureExtractorSVD entropy feature extractor.
- Parameters:
Examples
>>> svde = SVDEntropy(order=3) >>> features = svde.fit_transform(signals)
- class endgame.signal.EntropyFeatureExtractor(fs, include_permutation=True, include_sample=True, include_approximate=False, include_svd=True, include_spectral=True, perm_order=3, sample_order=2, svd_order=3)[source]¶
Bases:
BaseFeatureExtractorComprehensive entropy feature extractor.
Extracts multiple entropy measures in a single transformer.
- Parameters:
fs (float) – Sample rate in Hz.
include_permutation (bool, default=True) – Include permutation entropy.
include_sample (bool, default=True) – Include sample entropy.
include_approximate (bool, default=False) – Include approximate entropy (slow).
include_svd (bool, default=True) – Include SVD entropy.
include_spectral (bool, default=True) – Include spectral entropy.
perm_order (int, default=3) – Permutation entropy order.
sample_order (int, default=2) – Sample/approximate entropy order.
svd_order (int, default=3) – SVD entropy order.
Examples
>>> extractor = EntropyFeatureExtractor(fs=256) >>> features = extractor.fit_transform(signals)
- endgame.signal.permutation_entropy(x, order=3, delay=1, normalize=True)[source]¶
Compute permutation entropy of a signal.
Permutation entropy measures the complexity of a time series by analyzing the order relations between successive values.
- Parameters:
- Return type:
- Returns:
float – Permutation entropy value.
References
Bandt, C., & Pompe, B. (2002). Permutation entropy: a natural complexity measure for time series. Physical review letters, 88(17), 174102.
- endgame.signal.sample_entropy(x, order=2, r=None)[source]¶
Compute sample entropy of a signal.
Sample entropy measures the complexity of a time series based on approximate entropy but without counting self-matches.
- Parameters:
- Return type:
- Returns:
float – Sample entropy value.
References
Richman, J. S., & Moorman, J. R. (2000). Physiological time-series analysis using approximate entropy and sample entropy.
- endgame.signal.approximate_entropy(x, order=2, r=None)[source]¶
Compute approximate entropy of a signal.
Approximate entropy measures the likelihood that similar patterns remain similar on the next comparison.
- Parameters:
- Return type:
- Returns:
float – Approximate entropy value.
References
Pincus, S. M. (1991). Approximate entropy as a measure of system complexity. Proceedings of the National Academy of Sciences, 88(6), 2297-2301.
- endgame.signal.spectral_entropy(x, fs, method='welch', nperseg=None, normalize=True)[source]¶
Compute spectral entropy of a signal.
Spectral entropy measures the flatness of the power spectrum, indicating how spread the spectral energy is across frequencies.
- Parameters:
- Return type:
- Returns:
float – Spectral entropy value.
- endgame.signal.svd_entropy(x, order=3, delay=1, normalize=True)[source]¶
Compute SVD entropy of a signal.
SVD entropy measures the complexity of a time series using singular value decomposition of the embedded signal.
- class endgame.signal.HiguchiFD(fs=None, kmax=10)[source]¶
Bases:
BaseFeatureExtractorHiguchi fractal dimension feature extractor.
- Parameters:
Examples
>>> hfd = HiguchiFD(kmax=10) >>> features = hfd.fit_transform(signals)
- class endgame.signal.PetrosianFD(fs=None)[source]¶
Bases:
BaseFeatureExtractorPetrosian fractal dimension feature extractor.
- Parameters:
fs (float, optional) – Sample rate in Hz.
Examples
>>> pfd = PetrosianFD() >>> features = pfd.fit_transform(signals)
- class endgame.signal.KatzFD(fs=None)[source]¶
Bases:
BaseFeatureExtractorKatz fractal dimension feature extractor.
- Parameters:
fs (float, optional) – Sample rate in Hz.
Examples
>>> kfd = KatzFD() >>> features = kfd.fit_transform(signals)
- class endgame.signal.HurstExponent(fs=None, max_lag=None)[source]¶
Bases:
BaseFeatureExtractorHurst exponent feature extractor.
- Parameters:
Examples
>>> he = HurstExponent() >>> features = he.fit_transform(signals)
- class endgame.signal.DFA(fs=None, scale_min=4, scale_max=None, n_scales=10)[source]¶
Bases:
BaseFeatureExtractorDetrended Fluctuation Analysis feature extractor.
- Parameters:
Examples
>>> dfa = DFA() >>> features = dfa.fit_transform(signals)
- class endgame.signal.LempelZivComplexity(fs=None, threshold=None)[source]¶
Bases:
BaseFeatureExtractorLempel-Ziv complexity feature extractor.
- Parameters:
Examples
>>> lzc = LempelZivComplexity() >>> features = lzc.fit_transform(signals)
- class endgame.signal.ComplexityFeatureExtractor(fs=None, include_higuchi=True, include_petrosian=True, include_katz=True, include_hurst=True, include_dfa=True, include_lzc=True, higuchi_kmax=10)[source]¶
Bases:
BaseFeatureExtractorComprehensive complexity feature extractor.
Extracts multiple complexity measures in a single transformer.
- Parameters:
fs (float, optional) – Sample rate in Hz.
include_higuchi (bool, default=True) – Include Higuchi fractal dimension.
include_petrosian (bool, default=True) – Include Petrosian fractal dimension.
include_katz (bool, default=True) – Include Katz fractal dimension.
include_hurst (bool, default=True) – Include Hurst exponent.
include_dfa (bool, default=True) – Include DFA exponent.
include_lzc (bool, default=True) – Include Lempel-Ziv complexity.
higuchi_kmax (int, default=10) – kmax for Higuchi FD.
Examples
>>> extractor = ComplexityFeatureExtractor() >>> features = extractor.fit_transform(signals)
- endgame.signal.higuchi_fd(x, kmax=10)[source]¶
Compute Higuchi fractal dimension of a signal.
The Higuchi fractal dimension (HFD) estimates the fractal dimension of a time series by analyzing the length of the curve at different scales.
- Parameters:
x (np.ndarray) – 1D signal.
kmax (int, default=10) – Maximum scale factor.
- Return type:
- Returns:
float – Higuchi fractal dimension (typically 1-2).
References
Higuchi, T. (1988). Approach to an irregular time series on the basis of the fractal theory. Physica D: Nonlinear Phenomena, 31(2), 277-283.
- endgame.signal.petrosian_fd(x)[source]¶
Compute Petrosian fractal dimension of a signal.
The Petrosian fractal dimension (PFD) provides a fast estimate of the fractal dimension based on the number of sign changes in the first derivative.
- Parameters:
x (np.ndarray) – 1D signal.
- Return type:
- Returns:
float – Petrosian fractal dimension.
References
Petrosian, A. (1995). Kolmogorov complexity of finite sequences and recognition of different preictal EEG patterns.
- endgame.signal.katz_fd(x)[source]¶
Compute Katz fractal dimension of a signal.
The Katz fractal dimension estimates the complexity based on the ratio of the total path length to the maximum distance from the first point.
- Parameters:
x (np.ndarray) – 1D signal.
- Return type:
- Returns:
float – Katz fractal dimension.
References
Katz, M. J. (1988). Fractals and the analysis of waveforms. Computers in Biology and Medicine, 18(3), 145-156.
- endgame.signal.hurst_exponent(x, max_lag=None)[source]¶
Compute Hurst exponent of a signal using R/S analysis.
The Hurst exponent (H) measures the long-term memory of a time series: - H < 0.5: Anti-persistent (mean-reverting) - H = 0.5: Random walk (no memory) - H > 0.5: Persistent (trending)
- Parameters:
x (np.ndarray) – 1D signal.
max_lag (int, optional) – Maximum lag for R/S calculation. If None, uses n//2.
- Return type:
- Returns:
float – Hurst exponent (typically 0-1).
References
Hurst, H. E. (1951). Long-term storage capacity of reservoirs. Transactions of the American Society of Civil Engineers, 116, 770-799.
- endgame.signal.detrended_fluctuation(x, scale_min=4, scale_max=None, n_scales=10)[source]¶
Compute Detrended Fluctuation Analysis (DFA) exponent.
DFA measures the self-similarity in a non-stationary time series by analyzing the fluctuations around local linear trends.
- Parameters:
- Return type:
- Returns:
float – DFA exponent (alpha): - alpha < 0.5: Anti-correlated - alpha = 0.5: White noise - alpha = 1.0: 1/f noise (pink noise) - alpha = 1.5: Brownian noise - alpha > 1.0: Non-stationary, unbounded
References
Peng, C. K., et al. (1994). Mosaic organization of DNA nucleotides. Physical Review E, 49(2), 1685.
- endgame.signal.lempel_ziv_complexity(x, threshold=None)[source]¶
Compute Lempel-Ziv complexity of a signal.
LZC measures the complexity of a signal by counting the number of distinct patterns found during sequential parsing.
- Parameters:
x (np.ndarray) – 1D signal.
threshold (float, optional) – Threshold for binarization. If None, uses median.
- Return type:
- Returns:
float – Normalized Lempel-Ziv complexity (0-1).
References
Lempel, A., & Ziv, J. (1976). On the complexity of finite sequences. IEEE Transactions on Information Theory, 22(1), 75-81.
- class endgame.signal.CovarianceEstimator(fs=None, estimator='empirical', copy=True)[source]¶
Bases:
BaseSignalTransformerEstimate covariance matrices from multi-channel signals.
- Parameters:
Examples
>>> cov_est = CovarianceEstimator(estimator='oas') >>> covmats = cov_est.fit_transform(X) # X: (n_trials, n_channels, n_samples)
- class endgame.signal.CSP(fs=None, n_components=4, reg=None, log=True, cov_estimator='empirical', copy=True)[source]¶
Bases:
BaseSignalTransformerCommon Spatial Patterns for discriminative spatial filtering.
CSP finds spatial filters that maximize variance for one class while minimizing variance for another class.
- Parameters:
fs (float, optional) – Sample rate in Hz.
n_components (int, default=4) – Number of CSP components (filters) per class.
reg (float or str, optional) – Regularization parameter or method (‘ledoit_wolf’, ‘oas’).
log (bool, default=True) – Apply log transform to variances (recommended for classification).
cov_estimator (str, default='empirical') – Covariance estimator.
copy (bool, default=True) – Whether to copy input data.
- filters_¶
Spatial filters of shape (n_filters, n_channels).
- Type:
np.ndarray
- patterns_¶
Spatial patterns of shape (n_channels, n_filters).
- Type:
np.ndarray
- eigenvalues_¶
Eigenvalues corresponding to each filter.
- Type:
np.ndarray
References
Koles, Z. J., et al. (1990). Spatial patterns underlying population differences in the background EEG.
Examples
>>> csp = CSP(n_components=4) >>> features = csp.fit_transform(X, y) # X: (n_trials, n_channels, n_samples)
- class endgame.signal.TangentSpace(fs=None, metric='riemann', reference=None, cov_estimator='empirical')[source]¶
Bases:
BaseFeatureExtractorTangent space projection for Riemannian geometry.
Projects covariance matrices onto the tangent space at the Riemannian mean, enabling use of Euclidean classifiers.
- Parameters:
fs (float, optional) – Sample rate in Hz.
metric (str, default='riemann') – Metric for mean computation: ‘riemann’, ‘euclid’, ‘logeuclid’.
reference (np.ndarray, optional) – Reference point (mean). If None, computed from training data.
cov_estimator (str, default='empirical') – Covariance estimator for input signals.
- reference_¶
Reference covariance matrix.
- Type:
np.ndarray
References
Barachant, A., et al. (2012). Multiclass brain-computer interface classification by Riemannian geometry.
Examples
>>> ts = TangentSpace() >>> # From covariance matrices >>> features = ts.fit_transform(covmats) >>> # Or from raw signals (computes covariances internally) >>> features = ts.fit_transform(X, input_type='signals')
- fit(X, y=None, input_type='covariances', **fit_params)[source]¶
Fit the tangent space projector.
- Parameters:
X (np.ndarray) – Either covariance matrices (n_trials, n_channels, n_channels) or raw signals (n_trials, n_channels, n_samples).
y (ignored)
input_type (str, default='covariances') – Type of input: ‘covariances’ or ‘signals’.
- Return type:
- Returns:
self
- set_fit_request(*, input_type='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
fitmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- Parameters:
input_type (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
input_typeparameter infit.self (TangentSpace)
- Returns:
self (object) – The updated object.
- Return type:
- set_transform_request(*, input_type='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
transformmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- Parameters:
input_type (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
input_typeparameter intransform.self (TangentSpace)
- Returns:
self (object) – The updated object.
- Return type:
- class endgame.signal.FilterBankCSP(fs, bands, n_components=4, filter_order=5)[source]¶
Bases:
BaseSignalTransformerFilter Bank Common Spatial Patterns.
Applies CSP to multiple frequency bands and concatenates features.
- Parameters:
Examples
>>> bands = [(4, 8), (8, 12), (12, 30)] >>> fbcsp = FilterBankCSP(fs=256, bands=bands) >>> features = fbcsp.fit_transform(X, y)
- class endgame.signal.CoherenceFeatureExtractor(fs, bands=None, nperseg=None)[source]¶
Bases:
BaseFeatureExtractorExtract coherence features between all channel pairs.
- Parameters:
Examples
>>> coh = CoherenceFeatureExtractor(fs=256) >>> features = coh.fit_transform(X) # X: (n_trials, n_channels, n_samples)
- DEFAULT_BANDS = {'alpha': (8, 13), 'beta': (13, 30), 'delta': (0.5, 4), 'gamma': (30, 50), 'theta': (4, 8)}¶
- class endgame.signal.PLVFeatureExtractor(fs, bands=None)[source]¶
Bases:
BaseFeatureExtractorExtract phase-locking value features between channel pairs.
- Parameters:
Examples
>>> plv = PLVFeatureExtractor(fs=256) >>> features = plv.fit_transform(X)
- DEFAULT_BANDS = {'alpha': (8, 13), 'beta': (13, 30), 'theta': (4, 8)}¶
- class endgame.signal.BurstSuppressionFeatures(fs, burst_threshold_std=2.0, suppression_threshold=10.0, min_burst_ms=100.0, min_suppression_ms=500.0)[source]¶
Bases:
BaseFeatureExtractorExtract burst-suppression features from signals.
Commonly used in EEG analysis for detecting anesthesia depth and certain pathological states.
- Parameters:
fs (float) – Sample rate in Hz.
burst_threshold_std (float, default=2.0) – Threshold for burst detection.
suppression_threshold (float, default=10.0) – Threshold for suppression detection.
min_burst_ms (float, default=100.0) – Minimum burst duration.
min_suppression_ms (float, default=500.0) – Minimum suppression duration.
Examples
>>> bsr = BurstSuppressionFeatures(fs=256) >>> features = bsr.fit_transform(signals)
- class endgame.signal.SpikeFeatures(fs, threshold_std=3.0, max_duration_ms=70.0)[source]¶
Bases:
BaseFeatureExtractorExtract spike-related features from signals.
- Parameters:
Examples
>>> spike_feat = SpikeFeatures(fs=256) >>> features = spike_feat.fit_transform(signals)
- class endgame.signal.ConnectivityFeatureExtractor(fs, include_coherence=True, include_plv=True, bands=None)[source]¶
Bases:
BaseFeatureExtractorComprehensive connectivity feature extractor.
Combines coherence, PLV, and cross-correlation features.
- Parameters:
Examples
>>> conn = ConnectivityFeatureExtractor(fs=256) >>> features = conn.fit_transform(X)
- DEFAULT_BANDS = {'alpha': (8, 13), 'beta': (13, 30), 'theta': (4, 8)}¶
- endgame.signal.coherence(x, y, fs, nperseg=None, noverlap=None)[source]¶
Compute magnitude-squared coherence between two signals.
- Parameters:
- Return type:
- Returns:
freqs (np.ndarray) – Frequency bins.
coh (np.ndarray) – Coherence values (0-1).
- endgame.signal.phase_locking_value(x, y, fs, band=None)[source]¶
Compute phase-locking value between two signals.
PLV measures the consistency of phase difference between signals.
- Parameters:
- Return type:
- Returns:
float – Phase-locking value (0-1).
References
Lachaux, J. P., et al. (1999). Measuring phase synchrony in brain signals. Human brain mapping, 8(4), 194-208.
- endgame.signal.cross_correlation(x, y, max_lag=None, normalize=True)[source]¶
Compute cross-correlation between two signals.
- Parameters:
- Return type:
- Returns:
lags (np.ndarray) – Lag values.
corr (np.ndarray) – Cross-correlation values.
- endgame.signal.detect_bursts(x, fs, threshold_std=2.0, min_duration_ms=100.0)[source]¶
Detect burst periods in a signal.
Bursts are periods where signal amplitude exceeds a threshold.
- Parameters:
- Return type:
- Returns:
list of (start, end) tuples – Burst intervals as sample indices.
- endgame.signal.detect_suppressions(x, fs, threshold_uv=10.0, min_duration_ms=500.0)[source]¶
Detect suppression periods in a signal.
Suppressions are periods of low amplitude activity.
- Parameters:
- Return type:
- Returns:
list of (start, end) tuples – Suppression intervals as sample indices.
- endgame.signal.detect_spikes(x, fs, threshold_std=3.0, max_duration_ms=70.0, min_duration_ms=20.0)[source]¶
Detect spikes in a signal.
Spikes are brief, high-amplitude transients.
- Parameters:
- Return type:
- Returns:
list of int – Spike peak locations as sample indices.
- class endgame.signal.CWTTransformer(fs, wavelet='morl', freqs=None, n_freqs=32, output='power', normalize=True, copy=True)[source]¶
Bases:
BaseSignalTransformerContinuous Wavelet Transform for time-frequency analysis.
Computes CWT using complex Morlet or other wavelets, producing a time-frequency representation.
- Parameters:
fs (float) – Sample rate in Hz.
wavelet (str, default='morl') – Wavelet to use. Options: ‘morl’ (Morlet), ‘cmor’ (complex Morlet), ‘cgau’ (complex Gaussian), ‘mexh’ (Mexican hat), ‘gaus’.
freqs (array-like, optional) – Frequencies to analyze in Hz. If None, uses logarithmically spaced frequencies from 1 Hz to Nyquist.
n_freqs (int, default=32) – Number of frequency bins if freqs is None.
output (str, default='power') – Output type: ‘complex’, ‘magnitude’, ‘power’, ‘phase’.
normalize (bool, default=True) – Whether to normalize coefficients.
copy (bool, default=True) – Whether to copy input data.
- scales_¶
Wavelet scales used.
- Type:
np.ndarray
- freqs_¶
Corresponding frequencies in Hz.
- Type:
np.ndarray
Examples
>>> cwt = CWTTransformer(fs=256, freqs=np.arange(1, 50)) >>> tfr = cwt.fit_transform(signal) # (n_freqs, n_samples)
- fit(X, y=None, **fit_params)[source]¶
Fit the transformer (compute scales).
- Parameters:
X (array-like) – Input signal.
y (ignored)
- Return type:
- Returns:
self
- class endgame.signal.DWTTransformer(fs=None, wavelet='db4', level=None, mode='symmetric', output='coeffs', copy=True)[source]¶
Bases:
BaseSignalTransformerDiscrete Wavelet Transform for multi-resolution analysis.
Decomposes signal into approximation and detail coefficients at multiple scales.
- Parameters:
fs (float, optional) – Sample rate in Hz.
wavelet (str, default='db4') – Wavelet to use. Options: ‘db1’-‘db20’, ‘sym2’-‘sym20’, ‘coif1’-‘coif5’, ‘bior’, ‘rbio’, etc.
level (int, optional) – Decomposition level. If None, uses maximum level.
mode (str, default='symmetric') – Signal extension mode: ‘symmetric’, ‘periodic’, ‘reflect’, etc.
output (str, default='coeffs') – Output type: ‘coeffs’ (all coefficients), ‘detail’ (detail only), ‘approx’ (approximation only).
copy (bool, default=True) – Whether to copy input data.
Examples
>>> dwt = DWTTransformer(wavelet='db4', level=4) >>> coeffs = dwt.fit_transform(signal)
- fit(X, y=None, **fit_params)[source]¶
Fit the transformer.
- Parameters:
X (array-like) – Input signal.
y (ignored)
- Return type:
- Returns:
self
- transform(X)[source]¶
Compute DWT of signal.
- Parameters:
X (array-like) – Input signal.
- Return type:
- Returns:
np.ndarray – DWT coefficients concatenated into a single array.
- inverse_transform(coeffs)[source]¶
Reconstruct signal from DWT coefficients.
- Parameters:
coeffs (array-like) – DWT coefficients (concatenated).
- Return type:
- Returns:
np.ndarray – Reconstructed signal.
- set_inverse_transform_request(*, coeffs='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
inverse_transformmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed toinverse_transformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it toinverse_transform.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- Parameters:
coeffs (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
coeffsparameter ininverse_transform.self (DWTTransformer)
- Returns:
self (object) – The updated object.
- Return type:
- class endgame.signal.WaveletPacketTransformer(fs=None, wavelet='db4', level=None, mode='symmetric', order='freq', copy=True)[source]¶
Bases:
BaseSignalTransformerWavelet Packet Decomposition for full frequency resolution.
Unlike DWT which only decomposes approximation coefficients, wavelet packets decompose both approximation and detail coefficients at each level.
- Parameters:
fs (float, optional) – Sample rate in Hz.
wavelet (str, default='db4') – Wavelet to use.
level (int, optional) – Decomposition level. If None, uses maximum level.
mode (str, default='symmetric') – Signal extension mode.
order (str, default='freq') – Node ordering: ‘freq’ (frequency order) or ‘natural’.
copy (bool, default=True) – Whether to copy input data.
Examples
>>> wp = WaveletPacketTransformer(wavelet='db4', level=3) >>> coeffs = wp.fit_transform(signal) # (8, n_coeffs)
- fit(X, y=None, **fit_params)[source]¶
Fit the transformer.
- Parameters:
X (array-like) – Input signal.
y (ignored)
- Return type:
- Returns:
self
- class endgame.signal.WaveletFeatureExtractor(fs=None, wavelet='db4', level=None, features=None, use_packet=False)[source]¶
Bases:
BaseFeatureExtractorExtract features from wavelet coefficients.
Computes statistical features from wavelet decomposition at multiple scales.
- Parameters:
fs (float, optional) – Sample rate in Hz.
wavelet (str, default='db4') – Wavelet to use.
level (int, optional) – Decomposition level.
features (list of str, optional) – Features to extract. Default: [‘energy’, ‘mean’, ‘std’, ‘entropy’].
use_packet (bool, default=False) – If True, use wavelet packet decomposition.
Examples
>>> extractor = WaveletFeatureExtractor(wavelet='db4', level=4) >>> features = extractor.fit_transform(signals)
- DEFAULT_FEATURES = ['energy', 'mean', 'std', 'entropy']¶
- endgame.signal.compute_cwt(x, fs, freqs=None, wavelet='morl')[source]¶
Convenience function to compute CWT.
- Parameters:
- Return type:
- Returns:
freqs (np.ndarray) – Analysis frequencies.
coeffs (np.ndarray) – CWT coefficients (power).
Examples
>>> freqs, power = compute_cwt(signal, fs=256)
- endgame.signal.compute_dwt(x, wavelet='db4', level=None)[source]¶
Convenience function to compute DWT.
- Parameters:
- Return type:
- Returns:
list of np.ndarray – Coefficients [approx, detail1, detail2, …].
Examples
>>> coeffs = compute_dwt(signal, wavelet='db4', level=4) >>> approx, d1, d2, d3, d4 = coeffs