Signal Processing

class endgame.signal.BaseFeatureExtractor(fs=None)[source]

Bases: BaseEstimator, TransformerMixin, SignalMixin

Base 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:

BaseFeatureExtractor

Returns:

self

abstractmethod transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

fit_transform(X, y=None, **fit_params)[source]

Fit and transform in one step.

Return type:

ndarray

get_feature_names_out(input_features=None)[source]

Get output feature names.

Return type:

list[Text]

Returns:

List[str] – Feature names.

class endgame.signal.BaseSignalTransformer(fs=None, copy=True)[source]

Bases: BaseEstimator, TransformerMixin, SignalMixin

Base class for all signal processing transformers.

Provides sklearn-compatible interface with signal-specific extensions.

Parameters:
  • fs (float, optional) – Sample rate in Hz. Required for frequency-dependent operations.

  • copy (bool, default=True) – Whether to copy input data before processing.

n_samples_seen_

Number of samples processed during fit.

Type:

int

n_channels_seen_

Number of channels seen during fit.

Type:

int

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:

BaseSignalTransformer

Returns:

self

abstractmethod transform(X)[source]

Transform the signal.

Parameters:

X (array-like) – Input signal.

Return type:

ndarray

Returns:

np.ndarray – Transformed signal.

fit_transform(X, y=None, **fit_params)[source]

Fit and transform in one step.

Return type:

ndarray

inverse_transform(X)[source]

Inverse transform (if applicable).

Parameters:

X (array-like) – Transformed signal.

Return type:

ndarray

Returns:

np.ndarray – Reconstructed signal.

Raises:

NotImplementedError – If inverse transform is not supported.

class endgame.signal.SignalMixin[source]

Bases: object

Mixin 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: BaseSignalTransformer

Butterworth 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:

ButterworthFilter

transform(X)[source]

Apply zero-phase Butterworth filter.

Parameters:

X (array-like) – Input signal(s).

Return type:

ndarray

Returns:

np.ndarray – Filtered signal(s).

get_frequency_response(n_points=512)[source]

Get the filter’s frequency response.

Parameters:

n_points (int, default=512) – Number of frequency points.

Return type:

tuple[ndarray, ndarray]

Returns:

  • freqs (np.ndarray) – Frequency array in Hz.

  • response (np.ndarray) – Magnitude response (absolute value).

class endgame.signal.FIRFilter(lowcut=None, highcut=None, fs=None, numtaps=101, window='hamming', pass_zero=None)[source]

Bases: BaseSignalTransformer

FIR 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.

fit(X, y=None, **fit_params)[source]

Fit the filter.

Return type:

FIRFilter

transform(X)[source]

Apply FIR filter.

Return type:

ndarray

class endgame.signal.SavgolFilter(window_length=11, polyorder=3, deriv=0, delta=1.0, mode='interp', fs=None)[source]

Bases: BaseSignalTransformer

Savitzky-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.

fit(X, y=None, **fit_params)[source]

Fit the filter.

Return type:

SavgolFilter

transform(X)[source]

Apply Savitzky-Golay filter.

Return type:

ndarray

class endgame.signal.NotchFilter(freq, fs, Q=30, harmonics=0)[source]

Bases: BaseSignalTransformer

Notch filter for removing specific frequencies.

Typically used to remove powerline interference (50/60 Hz) and its harmonics.

Parameters:
  • freq (float or List[float]) – Notch frequency/frequencies in Hz.

  • fs (float) – Sample rate in Hz.

  • Q (float, default=30) – Quality factor. Higher Q = narrower notch.

  • harmonics (int, default=0) – Number of harmonics to also filter (0 = fundamental only).

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)
fit(X, y=None, **fit_params)[source]

Design notch filter(s).

Return type:

NotchFilter

transform(X)[source]

Apply notch filter(s).

Return type:

ndarray

class endgame.signal.MedianFilter(kernel_size=3, fs=None)[source]

Bases: BaseSignalTransformer

Median filter for impulse noise removal.

Non-linear filter that replaces each sample with the median of neighboring samples. Excellent for removing spikes/artifacts.

Parameters:
  • kernel_size (int, default=3) – Filter window size. Must be odd.

  • fs (float | None)

Examples

>>> # Remove spike artifacts
>>> filt = MedianFilter(kernel_size=5)
>>> clean = filt.fit_transform(signal_with_spikes)
fit(X, y=None, **fit_params)[source]

Fit the filter.

Return type:

MedianFilter

transform(X)[source]

Apply median filter.

Return type:

ndarray

class endgame.signal.FilterBank(bands, fs, filter_type='butterworth', order=4, numtaps=101, output='dict')[source]

Bases: BaseSignalTransformer

Bank 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']
fit(X, y=None, **fit_params)[source]

Design all bandpass filters.

Return type:

FilterBank

transform(X)[source]

Apply filter bank.

Parameters:

X (array-like) – Input signal.

Return type:

WSGIEnvironment | ndarray

Returns:

dict or np.ndarray – If output=’dict’: {band_name: filtered_signal} If output=’stack’: (n_bands, …) array

property band_names: list[str]

Get list of band names.

class endgame.signal.FFTTransformer(fs, output='magnitude', one_sided=True, n_fft=None, normalize=True, copy=True)[source]

Bases: BaseSignalTransformer

Fast 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:

FFTTransformer

Returns:

self

transform(X)[source]

Compute FFT of signal.

Parameters:

X (array-like) – Input signal.

Return type:

ndarray

Returns:

np.ndarray – FFT result based on output parameter.

get_frequency_resolution()[source]

Get frequency resolution in Hz.

Return type:

float

class endgame.signal.WelchPSD(fs, nperseg=None, noverlap=None, nfft=None, window='hann', detrend='constant', scaling='density', average='mean', copy=True)[source]

Bases: BaseSignalTransformer

Welch’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:

WelchPSD

Returns:

self

transform(X)[source]

Compute PSD using Welch’s method.

Parameters:

X (array-like) – Input signal.

Return type:

ndarray

Returns:

np.ndarray – Power spectral density.

get_frequency_bands(X, bands)[source]

Get PSD values within specified frequency bands.

Parameters:
  • X (np.ndarray) – Input signal.

  • bands (dict) – Dictionary mapping band names to (low, high) frequency tuples.

Return type:

WSGIEnvironment[Text, ndarray]

Returns:

dict – Dictionary mapping band names to PSD arrays within each band.

class endgame.signal.MultitaperPSD(fs, bandwidth=None, n_tapers=None, low_bias=True, adaptive=False, normalization='full', copy=True)[source]

Bases: BaseSignalTransformer

Multitaper 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)
fit(X, y=None, **fit_params)[source]

Fit the transformer (compute DPSS tapers).

Parameters:
  • X (array-like) – Input signal.

  • y (ignored)

Return type:

MultitaperPSD

Returns:

self

transform(X)[source]

Compute multitaper PSD.

Parameters:

X (array-like) – Input signal.

Return type:

ndarray

Returns:

np.ndarray – Power spectral density.

class endgame.signal.BandPowerExtractor(fs, bands=None, method='welch', relative=True, log_power=False, welch_params=None, multitaper_params=None)[source]

Bases: BaseFeatureExtractor

Extract 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.

feature_names_

Names of extracted features.

Type:

list of str

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:

BandPowerExtractor

Returns:

self

transform(X)[source]

Extract band power features.

Parameters:

X (array-like) – Input signals of shape (n_samples, n_timepoints) or (n_samples, n_channels, n_timepoints).

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted band power features.

get_feature_names_out(input_features=None)[source]

Get output feature names.

Return type:

list[Text]

class endgame.signal.SpectralFeatureExtractor(fs, method='welch', edge_percentiles=None, welch_params=None)[source]

Bases: BaseFeatureExtractor

Extract 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.

feature_names_

Names of extracted features.

Type:

list of str

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:

SpectralFeatureExtractor

Returns:

self

transform(X)[source]

Extract spectral features.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted spectral features.

get_feature_names_out(input_features=None)[source]

Get output feature names.

Return type:

list[Text]

endgame.signal.compute_psd(x, fs, method='welch', **kwargs)[source]

Convenience function to compute PSD.

Parameters:
  • x (np.ndarray) – Input signal.

  • fs (float) – Sample rate in Hz.

  • method (str, default='welch') – PSD estimation method: ‘welch’, ‘multitaper’, ‘fft’.

  • **kwargs – Additional parameters for the PSD method.

Return type:

tuple[ndarray, ndarray]

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:
  • x (np.ndarray) – Input signal.

  • fs (float) – Sample rate in Hz.

  • band (tuple of (low, high)) – Frequency band in Hz.

  • method (str, default='welch') – PSD estimation method.

  • relative (bool, default=False) – If True, return relative band power.

Return type:

float

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: BaseFeatureExtractor

Comprehensive 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.

feature_names_

Names of all extracted features.

Type:

list of str

Examples

>>> extractor = TimeDomainFeatures(fs=256)
>>> features = extractor.fit_transform(signals)
>>> print(extractor.feature_names_)
fit(X, y=None, **fit_params)[source]

Fit all feature extractors.

Parameters:
  • X (array-like) – Input signals.

  • y (ignored)

Return type:

TimeDomainFeatures

Returns:

self

transform(X)[source]

Extract all time-domain features.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.StatisticalFeatures(fs=None, features=None)[source]

Bases: BaseFeatureExtractor

Extract 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’.

feature_names_

Names of extracted features.

Type:

list of str

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']
fit(X, y=None, **fit_params)[source]

Fit the extractor.

Parameters:
  • X (array-like) – Input signals.

  • y (ignored)

Return type:

StatisticalFeatures

Returns:

self

transform(X)[source]

Extract statistical features.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.HjorthParameters(fs=None, normalize=False)[source]

Bases: BaseFeatureExtractor

Extract 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:
  • fs (float, optional) – Sample rate in Hz.

  • normalize (bool, default=False) – If True, normalize by signal variance.

feature_names_

Names of extracted features.

Type:

list of str

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)
fit(X, y=None, **fit_params)[source]

Fit the extractor.

Parameters:
  • X (array-like) – Input signals.

  • y (ignored)

Return type:

HjorthParameters

Returns:

self

transform(X)[source]

Extract Hjorth parameters.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, 3) – Hjorth parameters [activity, mobility, complexity].

class endgame.signal.ZeroCrossingFeatures(fs=None, threshold=0.0, compute_rate=True)[source]

Bases: BaseFeatureExtractor

Extract zero-crossing related features.

Computes features based on signal zero crossings and threshold crossings.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • threshold (float, default=0.0) – Threshold for crossing detection.

  • compute_rate (bool, default=True) – If True, compute crossing rate (requires fs).

feature_names_

Names of extracted features.

Type:

list of str

Examples

>>> zc = ZeroCrossingFeatures(fs=256)
>>> features = zc.fit_transform(signals)
fit(X, y=None, **fit_params)[source]

Fit the extractor.

Parameters:
  • X (array-like) – Input signals.

  • y (ignored)

Return type:

ZeroCrossingFeatures

Returns:

self

transform(X)[source]

Extract zero-crossing features.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.PeakFeatures(fs=None, height=None, threshold=None, distance=None, prominence=None, width=None)[source]

Bases: BaseFeatureExtractor

Extract 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.

feature_names_

Names of extracted features.

Type:

list of str

Examples

>>> peaks = PeakFeatures(fs=256, prominence=0.5)
>>> features = peaks.fit_transform(signals)
fit(X, y=None, **fit_params)[source]

Fit the extractor.

Parameters:
  • X (array-like) – Input signals.

  • y (ignored)

Return type:

PeakFeatures

Returns:

self

transform(X)[source]

Extract peak features.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

endgame.signal.compute_hjorth(x)[source]

Compute Hjorth parameters.

Parameters:

x (np.ndarray) – Input signal.

Return type:

tuple[float, float, float]

Returns:

tuple of (activity, mobility, complexity)

endgame.signal.compute_rms(x)[source]

Compute root mean square of a signal.

Parameters:

x (np.ndarray) – Input signal.

Return type:

float

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:

float

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:

float

Returns:

float – Line length.

endgame.signal.count_zero_crossings(x, threshold=0.0)[source]

Count zero crossings in a signal.

Parameters:
  • x (np.ndarray) – Input signal.

  • threshold (float, default=0.0) – Threshold for crossing detection.

Return type:

int

Returns:

int – Number of zero crossings.

class endgame.signal.PermutationEntropy(fs=None, order=3, delay=1, normalize=True)[source]

Bases: BaseFeatureExtractor

Permutation entropy feature extractor.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • order (int, default=3) – Embedding dimension.

  • delay (int, default=1) – Time delay.

  • normalize (bool, default=True) – Normalize entropy by maximum possible value.

Examples

>>> pe = PermutationEntropy(order=3)
>>> features = pe.fit_transform(signals)
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:

PermutationEntropy

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.SampleEntropy(fs=None, order=2, r=None)[source]

Bases: BaseFeatureExtractor

Sample entropy feature extractor.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • order (int, default=2) – Embedding dimension.

  • r (float, optional) – Tolerance threshold. If None, uses 0.2 * std(x).

Examples

>>> se = SampleEntropy(order=2)
>>> features = se.fit_transform(signals)
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:

SampleEntropy

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.ApproximateEntropy(fs=None, order=2, r=None)[source]

Bases: BaseFeatureExtractor

Approximate entropy feature extractor.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • order (int, default=2) – Embedding dimension.

  • r (float, optional) – Tolerance threshold. If None, uses 0.2 * std(x).

Examples

>>> ae = ApproximateEntropy(order=2)
>>> features = ae.fit_transform(signals)
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:

ApproximateEntropy

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.SpectralEntropy(fs, method='welch', nperseg=None, normalize=True)[source]

Bases: BaseFeatureExtractor

Spectral entropy feature extractor.

Parameters:
  • fs (float) – Sample rate in Hz.

  • method (str, default='welch') – PSD estimation method.

  • nperseg (int, optional) – Segment length for Welch.

  • normalize (bool, default=True) – Normalize by maximum entropy.

Examples

>>> se = SpectralEntropy(fs=256)
>>> features = se.fit_transform(signals)
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:

SpectralEntropy

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.SVDEntropy(fs=None, order=3, delay=1, normalize=True)[source]

Bases: BaseFeatureExtractor

SVD entropy feature extractor.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • order (int, default=3) – Embedding dimension.

  • delay (int, default=1) – Time delay.

  • normalize (bool, default=True) – Normalize by maximum entropy.

Examples

>>> svde = SVDEntropy(order=3)
>>> features = svde.fit_transform(signals)
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:

SVDEntropy

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

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: BaseFeatureExtractor

Comprehensive 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)
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:

EntropyFeatureExtractor

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

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:
  • x (np.ndarray) – 1D signal.

  • order (int, default=3) – Embedding dimension (typically 3-7).

  • delay (int, default=1) – Time delay between elements.

  • normalize (bool, default=True) – If True, normalize by log2(order!).

Return type:

float

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:
  • x (np.ndarray) – 1D signal.

  • order (int, default=2) – Embedding dimension.

  • r (float, optional) – Tolerance threshold. If None, uses 0.2 * std(x).

Return type:

float

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:
  • x (np.ndarray) – 1D signal.

  • order (int, default=2) – Embedding dimension.

  • r (float, optional) – Tolerance threshold. If None, uses 0.2 * std(x).

Return type:

float

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:
  • x (np.ndarray) – 1D signal.

  • fs (float) – Sample rate in Hz.

  • method (str, default='welch') – PSD estimation method: ‘welch’ or ‘fft’.

  • nperseg (int, optional) – Segment length for Welch’s method.

  • normalize (bool, default=True) – If True, normalize by log2(n_freqs).

Return type:

float

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.

Parameters:
  • x (np.ndarray) – 1D signal.

  • order (int, default=3) – Embedding dimension.

  • delay (int, default=1) – Time delay.

  • normalize (bool, default=True) – If True, normalize by log2(order).

Return type:

float

Returns:

float – SVD entropy value.

class endgame.signal.HiguchiFD(fs=None, kmax=10)[source]

Bases: BaseFeatureExtractor

Higuchi fractal dimension feature extractor.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • kmax (int, default=10) – Maximum scale factor.

Examples

>>> hfd = HiguchiFD(kmax=10)
>>> features = hfd.fit_transform(signals)
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:

HiguchiFD

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.PetrosianFD(fs=None)[source]

Bases: BaseFeatureExtractor

Petrosian fractal dimension feature extractor.

Parameters:

fs (float, optional) – Sample rate in Hz.

Examples

>>> pfd = PetrosianFD()
>>> features = pfd.fit_transform(signals)
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:

PetrosianFD

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.KatzFD(fs=None)[source]

Bases: BaseFeatureExtractor

Katz fractal dimension feature extractor.

Parameters:

fs (float, optional) – Sample rate in Hz.

Examples

>>> kfd = KatzFD()
>>> features = kfd.fit_transform(signals)
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:

KatzFD

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.HurstExponent(fs=None, max_lag=None)[source]

Bases: BaseFeatureExtractor

Hurst exponent feature extractor.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • max_lag (int, optional) – Maximum lag for R/S calculation.

Examples

>>> he = HurstExponent()
>>> features = he.fit_transform(signals)
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:

HurstExponent

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.DFA(fs=None, scale_min=4, scale_max=None, n_scales=10)[source]

Bases: BaseFeatureExtractor

Detrended Fluctuation Analysis feature extractor.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • scale_min (int, default=4) – Minimum scale.

  • scale_max (int, optional) – Maximum scale.

  • n_scales (int, default=10) – Number of scales.

Examples

>>> dfa = DFA()
>>> features = dfa.fit_transform(signals)
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:

DFA

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.LempelZivComplexity(fs=None, threshold=None)[source]

Bases: BaseFeatureExtractor

Lempel-Ziv complexity feature extractor.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • threshold (float, optional) – Binarization threshold.

Examples

>>> lzc = LempelZivComplexity()
>>> features = lzc.fit_transform(signals)
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:

LempelZivComplexity

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

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: BaseFeatureExtractor

Comprehensive 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)
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:

ComplexityFeatureExtractor

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

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:

float

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:

float

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:

float

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:

float

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:
  • x (np.ndarray) – 1D signal.

  • scale_min (int, default=4) – Minimum scale (window size).

  • scale_max (int, optional) – Maximum scale. If None, uses n//4.

  • n_scales (int, default=10) – Number of scales to evaluate.

Return type:

float

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:

float

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: BaseSignalTransformer

Estimate covariance matrices from multi-channel signals.

Parameters:
  • fs (float, optional) – Sample rate in Hz.

  • estimator (str, default='empirical') – Covariance estimator: ‘empirical’, ‘oas’, ‘lwf’, ‘scm’.

  • copy (bool, default=True) – Whether to copy input data.

n_channels_

Number of channels.

Type:

int

Examples

>>> cov_est = CovarianceEstimator(estimator='oas')
>>> covmats = cov_est.fit_transform(X)  # X: (n_trials, n_channels, n_samples)
fit(X, y=None, **fit_params)[source]

Fit the estimator.

Parameters:
  • X (np.ndarray) – Multi-channel signals of shape (n_trials, n_channels, n_samples).

  • y (ignored)

Return type:

CovarianceEstimator

Returns:

self

transform(X)[source]

Compute covariance matrices.

Parameters:

X (np.ndarray) – Multi-channel signals of shape (n_trials, n_channels, n_samples).

Return type:

ndarray

Returns:

np.ndarray – Covariance matrices of shape (n_trials, n_channels, n_channels).

class endgame.signal.CSP(fs=None, n_components=4, reg=None, log=True, cov_estimator='empirical', copy=True)[source]

Bases: BaseSignalTransformer

Common 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)
fit(X, y, **fit_params)[source]

Fit CSP spatial filters.

Parameters:
  • X (np.ndarray) – Multi-channel signals of shape (n_trials, n_channels, n_samples).

  • y (np.ndarray) – Binary class labels.

Return type:

CSP

Returns:

self

transform(X)[source]

Apply CSP spatial filters.

Parameters:

X (np.ndarray) – Multi-channel signals of shape (n_trials, n_channels, n_samples).

Return type:

ndarray

Returns:

np.ndarray – CSP features of shape (n_trials, n_filters).

class endgame.signal.TangentSpace(fs=None, metric='riemann', reference=None, cov_estimator='empirical')[source]

Bases: BaseFeatureExtractor

Tangent 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

feature_names_

Names of tangent space features.

Type:

list

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:

TangentSpace

Returns:

self

transform(X, input_type='covariances')[source]

Project to tangent space.

Parameters:
  • X (np.ndarray) – Either covariance matrices or raw signals.

  • input_type (str, default='covariances') – Type of input: ‘covariances’ or ‘signals’.

Return type:

ndarray

Returns:

np.ndarray – Tangent space features of shape (n_trials, n_features).

set_fit_request(*, input_type='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the fit method.

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 (see sklearn.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 to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • 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_type parameter in fit.

  • self (TangentSpace)

Returns:

self (object) – The updated object.

Return type:

TangentSpace

set_transform_request(*, input_type='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the transform method.

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 (see sklearn.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 to transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to 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:
  • input_type (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for input_type parameter in transform.

  • self (TangentSpace)

Returns:

self (object) – The updated object.

Return type:

TangentSpace

class endgame.signal.FilterBankCSP(fs, bands, n_components=4, filter_order=5)[source]

Bases: BaseSignalTransformer

Filter Bank Common Spatial Patterns.

Applies CSP to multiple frequency bands and concatenates features.

Parameters:
  • fs (float) – Sample rate in Hz.

  • bands (list of tuple) – Frequency bands as (low, high) tuples.

  • n_components (int, default=4) – Number of CSP components per band.

  • filter_order (int, default=5) – Order of bandpass filters.

Examples

>>> bands = [(4, 8), (8, 12), (12, 30)]
>>> fbcsp = FilterBankCSP(fs=256, bands=bands)
>>> features = fbcsp.fit_transform(X, y)
fit(X, y, **fit_params)[source]

Fit FilterBank CSP.

Parameters:
  • X (np.ndarray) – Multi-channel signals of shape (n_trials, n_channels, n_samples).

  • y (np.ndarray) – Binary class labels.

Return type:

FilterBankCSP

Returns:

self

transform(X)[source]

Apply FilterBank CSP.

Parameters:

X (np.ndarray) – Multi-channel signals of shape (n_trials, n_channels, n_samples).

Return type:

ndarray

Returns:

np.ndarray – FBCSP features of shape (n_trials, n_bands * n_components * 2).

class endgame.signal.CoherenceFeatureExtractor(fs, bands=None, nperseg=None)[source]

Bases: BaseFeatureExtractor

Extract coherence features between all channel pairs.

Parameters:
  • fs (float) – Sample rate in Hz.

  • bands (dict, optional) – Frequency bands for band-averaged coherence. Default includes standard EEG bands.

  • nperseg (int, optional) – Segment length for coherence estimation.

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)}
fit(X, y=None, **fit_params)[source]

Fit the extractor.

Parameters:
  • X (np.ndarray) – Multi-channel signals of shape (n_trials, n_channels, n_samples).

  • y (ignored)

Return type:

CoherenceFeatureExtractor

Returns:

self

transform(X)[source]

Extract coherence features.

Parameters:

X (np.ndarray) – Multi-channel signals of shape (n_trials, n_channels, n_samples).

Return type:

ndarray

Returns:

np.ndarray – Coherence features of shape (n_trials, n_features).

class endgame.signal.PLVFeatureExtractor(fs, bands=None)[source]

Bases: BaseFeatureExtractor

Extract phase-locking value features between channel pairs.

Parameters:
  • fs (float) – Sample rate in Hz.

  • bands (dict, optional) – Frequency bands for band-specific PLV.

Examples

>>> plv = PLVFeatureExtractor(fs=256)
>>> features = plv.fit_transform(X)
DEFAULT_BANDS = {'alpha': (8, 13), 'beta': (13, 30), 'theta': (4, 8)}
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:

PLVFeatureExtractor

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

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: BaseFeatureExtractor

Extract 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)
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:

BurstSuppressionFeatures

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.SpikeFeatures(fs, threshold_std=3.0, max_duration_ms=70.0)[source]

Bases: BaseFeatureExtractor

Extract spike-related features from signals.

Parameters:
  • fs (float) – Sample rate in Hz.

  • threshold_std (float, default=3.0) – Detection threshold in standard deviations.

  • max_duration_ms (float, default=70.0) – Maximum spike duration.

Examples

>>> spike_feat = SpikeFeatures(fs=256)
>>> features = spike_feat.fit_transform(signals)
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:

SpikeFeatures

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

class endgame.signal.ConnectivityFeatureExtractor(fs, include_coherence=True, include_plv=True, bands=None)[source]

Bases: BaseFeatureExtractor

Comprehensive connectivity feature extractor.

Combines coherence, PLV, and cross-correlation features.

Parameters:
  • fs (float) – Sample rate in Hz.

  • include_coherence (bool, default=True) – Include coherence features.

  • include_plv (bool, default=True) – Include PLV features.

  • bands (dict, optional) – Frequency bands for analysis.

Examples

>>> conn = ConnectivityFeatureExtractor(fs=256)
>>> features = conn.fit_transform(X)
DEFAULT_BANDS = {'alpha': (8, 13), 'beta': (13, 30), 'theta': (4, 8)}
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:

ConnectivityFeatureExtractor

Returns:

self

transform(X)[source]

Extract features from signals.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

endgame.signal.coherence(x, y, fs, nperseg=None, noverlap=None)[source]

Compute magnitude-squared coherence between two signals.

Parameters:
  • x (np.ndarray) – Input signals.

  • y (np.ndarray) – Input signals.

  • fs (float) – Sample rate in Hz.

  • nperseg (int, optional) – Segment length.

  • noverlap (int, optional) – Overlap between segments.

Return type:

tuple[ndarray, ndarray]

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:
  • x (np.ndarray) – Input signals.

  • y (np.ndarray) – Input signals.

  • fs (float) – Sample rate in Hz.

  • band (tuple, optional) – Frequency band (low, high) to filter before computing PLV.

Return type:

float

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:
  • x (np.ndarray) – Input signals.

  • y (np.ndarray) – Input signals.

  • max_lag (int, optional) – Maximum lag. If None, uses len(x) - 1.

  • normalize (bool, default=True) – Normalize to correlation coefficient (-1 to 1).

Return type:

tuple[ndarray, ndarray]

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:
  • x (np.ndarray) – Input signal.

  • fs (float) – Sample rate in Hz.

  • threshold_std (float, default=2.0) – Threshold in standard deviations above mean.

  • min_duration_ms (float, default=100.0) – Minimum burst duration in milliseconds.

Return type:

list[tuple[int, int]]

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:
  • x (np.ndarray) – Input signal (assumed to be in microvolts).

  • fs (float) – Sample rate in Hz.

  • threshold_uv (float, default=10.0) – Amplitude threshold in microvolts.

  • min_duration_ms (float, default=500.0) – Minimum suppression duration in milliseconds.

Return type:

list[tuple[int, int]]

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:
  • x (np.ndarray) – Input signal.

  • fs (float) – Sample rate in Hz.

  • threshold_std (float, default=3.0) – Threshold in standard deviations.

  • max_duration_ms (float, default=70.0) – Maximum spike duration in milliseconds.

  • min_duration_ms (float, default=20.0) – Minimum spike duration in milliseconds.

Return type:

list[int]

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: BaseSignalTransformer

Continuous 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:

CWTTransformer

Returns:

self

transform(X)[source]

Compute CWT of signal.

Parameters:

X (array-like) – Input signal.

Return type:

ndarray

Returns:

np.ndarray – CWT coefficients. Shape depends on input: - 1D input: (n_freqs, n_samples) - 2D input: (n_channels, n_freqs, n_samples) - 3D input: (n_trials, n_channels, n_freqs, n_samples)

get_frequencies()[source]

Get the analysis frequencies.

Return type:

ndarray

class endgame.signal.DWTTransformer(fs=None, wavelet='db4', level=None, mode='symmetric', output='coeffs', copy=True)[source]

Bases: BaseSignalTransformer

Discrete 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.

level_

Actual decomposition level used.

Type:

int

coeff_lengths_

Length of each coefficient array.

Type:

list of int

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:

DWTTransformer

Returns:

self

transform(X)[source]

Compute DWT of signal.

Parameters:

X (array-like) – Input signal.

Return type:

ndarray

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:

ndarray

Returns:

np.ndarray – Reconstructed signal.

set_inverse_transform_request(*, coeffs='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the inverse_transform method.

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 (see sklearn.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 to inverse_transform if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to inverse_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 coeffs parameter in inverse_transform.

  • self (DWTTransformer)

Returns:

self (object) – The updated object.

Return type:

DWTTransformer

class endgame.signal.WaveletPacketTransformer(fs=None, wavelet='db4', level=None, mode='symmetric', order='freq', copy=True)[source]

Bases: BaseSignalTransformer

Wavelet 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.

level_

Actual decomposition level used.

Type:

int

n_nodes_

Number of terminal nodes (2^level).

Type:

int

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:

WaveletPacketTransformer

Returns:

self

transform(X)[source]

Compute wavelet packet decomposition.

Parameters:

X (array-like) – Input signal.

Return type:

ndarray

Returns:

np.ndarray – Wavelet packet coefficients. Shape: (n_signals, n_nodes, n_coeffs_per_node)

get_frequency_bands()[source]

Get frequency bands for each wavelet packet node.

Return type:

list[tuple[float, float]]

Returns:

list of (low, high) tuples – Frequency bands in Hz for each node.

class endgame.signal.WaveletFeatureExtractor(fs=None, wavelet='db4', level=None, features=None, use_packet=False)[source]

Bases: BaseFeatureExtractor

Extract 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.

feature_names_

Names of extracted features.

Type:

list of str

Examples

>>> extractor = WaveletFeatureExtractor(wavelet='db4', level=4)
>>> features = extractor.fit_transform(signals)
DEFAULT_FEATURES = ['energy', 'mean', 'std', 'entropy']
fit(X, y=None, **fit_params)[source]

Fit the extractor.

Parameters:
  • X (array-like) – Input signals.

  • y (ignored)

Return type:

WaveletFeatureExtractor

Returns:

self

transform(X)[source]

Extract wavelet features.

Parameters:

X (array-like) – Input signals.

Return type:

ndarray

Returns:

np.ndarray of shape (n_samples, n_features) – Extracted features.

endgame.signal.compute_cwt(x, fs, freqs=None, wavelet='morl')[source]

Convenience function to compute CWT.

Parameters:
  • x (np.ndarray) – Input signal.

  • fs (float) – Sample rate in Hz.

  • freqs (np.ndarray, optional) – Frequencies to analyze.

  • wavelet (str, default='morl') – Wavelet to use.

Return type:

tuple[ndarray, ndarray]

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:
  • x (np.ndarray) – Input signal.

  • wavelet (str, default='db4') – Wavelet to use.

  • level (int, optional) – Decomposition level.

Return type:

list[ndarray]

Returns:

list of np.ndarray – Coefficients [approx, detail1, detail2, …].

Examples

>>> coeffs = compute_dwt(signal, wavelet='db4', level=4)
>>> approx, d1, d2, d3, d4 = coeffs
endgame.signal.reconstruct_from_dwt(coeffs, wavelet='db4')[source]

Reconstruct signal from DWT coefficients.

Parameters:
  • coeffs (list of np.ndarray) – Coefficients [approx, detail1, detail2, …].

  • wavelet (str, default='db4') – Wavelet used for decomposition.

Return type:

ndarray

Returns:

np.ndarray – Reconstructed signal.