API Reference

This section provides comprehensive documentation for all classes, methods, and functions in the Neurological LRD Analysis library.

Core Classes

BiomedicalHurstEstimatorFactory

class neurological_lrd_analysis.biomedical_hurst_factory.BiomedicalHurstEstimatorFactory[source]

Bases: object

Main factory for biomedical time series Hurst exponent estimation

__init__()[source]
estimate(data, method, confidence_method=ConfidenceMethod.BOOTSTRAP, confidence_level=0.95, preprocess=True, assess_quality=True, **kwargs)[source]

Main estimation method

Parameters: - data: Time series data - method: Estimator type or group type - confidence_method: Method for confidence interval estimation - confidence_level: Confidence level (0-1) - preprocess: Whether to preprocess data - assess_quality: Whether to assess data quality - **kwargs: Additional parameters for specific methods

Return type:

Union[HurstResult, GroupHurstResult]

HurstResult

class neurological_lrd_analysis.biomedical_hurst_factory.HurstResult(hurst_estimate, estimator_name, confidence_interval, confidence_level, confidence_method, standard_error, bias_estimate, variance_estimate, bootstrap_samples, computation_time, memory_usage, convergence_flag, data_quality_score, missing_data_fraction, outlier_fraction, stationarity_p_value, regression_r_squared, scaling_range, goodness_of_fit, signal_to_noise_ratio, artifact_detection, additional_metrics)[source]

Bases: object

Comprehensive result container for Hurst exponent estimation

hurst_estimate: float
estimator_name: str
confidence_interval: Tuple[float, float]
confidence_level: float
confidence_method: str
standard_error: float
bias_estimate: float | None
variance_estimate: float
bootstrap_samples: ndarray | None
computation_time: float
memory_usage: float | None
convergence_flag: bool
data_quality_score: float
missing_data_fraction: float
outlier_fraction: float
stationarity_p_value: float | None
regression_r_squared: float | None
scaling_range: Tuple[int, int] | None
goodness_of_fit: float | None
signal_to_noise_ratio: float | None
artifact_detection: Dict[str, Any]
additional_metrics: Dict[str, Any]
to_dict()[source]

Convert result to dictionary for serialization

__init__(hurst_estimate, estimator_name, confidence_interval, confidence_level, confidence_method, standard_error, bias_estimate, variance_estimate, bootstrap_samples, computation_time, memory_usage, convergence_flag, data_quality_score, missing_data_fraction, outlier_fraction, stationarity_p_value, regression_r_squared, scaling_range, goodness_of_fit, signal_to_noise_ratio, artifact_detection, additional_metrics)

BiomedicalDataProcessor

class neurological_lrd_analysis.biomedical_hurst_factory.BiomedicalDataProcessor[source]

Bases: object

Specialized preprocessing for biomedical time series data

static assess_data_quality(data)[source]

Comprehensive data quality assessment for biomedical signals

Return type:

Dict[str, Any]

static preprocess_biomedical_data(data, handle_missing='interpolate', remove_outliers=True, detrend=True, filter_artifacts=True, trim_convergence=False, stability_threshold=0.05, min_stable_fraction=0.1)[source]

Preprocess biomedical time series data

Return type:

Tuple[ndarray, Dict[str, Any]]

Enumerations

EstimatorType

class neurological_lrd_analysis.biomedical_hurst_factory.EstimatorType(value)[source]

Types of Hurst estimators available

DFA = 'dfa'
RS_ANALYSIS = 'rs'
HIGUCHI = 'higuchi'
DETRENDED_MA = 'dma'
GENERALIZED_HURST = 'ghe'
PERIODOGRAM = 'periodogram'
WHITTLE_MLE = 'whittle'
GPH = 'gph'
DWT = 'dwt'
CWT = 'cwt'
NDWT = 'ndwt'
WAVELET_LEADERS = 'leaders'
ABRY_VEITCH = 'abry_veitch'
MFDFA = 'mfdfa'
MF_DMA = 'mf_dma'
RANDOM_FOREST = 'rf'
SVR = 'svr'
TEMPORAL = 'temporal'
SPECTRAL = 'spectral'
WAVELET = 'wavelet'
ALL = 'all'

ConfidenceMethod

class neurological_lrd_analysis.biomedical_hurst_factory.ConfidenceMethod(value)[source]

Methods for confidence interval estimation

BOOTSTRAP = 'bootstrap'
THEORETICAL = 'theoretical'
CROSS_VALIDATION = 'cross_validation'
BAYESIAN = 'bayesian'
NONE = 'none'

Machine Learning Baselines

TimeSeriesFeatureExtractor

class neurological_lrd_analysis.ml_baselines.feature_extraction.TimeSeriesFeatureExtractor(include_spectral=True, include_wavelet=True, include_fractal=True, include_biomedical=True, sampling_rate=250.0)[source]

Bases: object

Comprehensive feature extractor for time series data.

Extracts statistical, spectral, wavelet, fractal, and biomedical-specific features that are relevant for Hurst exponent estimation.

__init__(include_spectral=True, include_wavelet=True, include_fractal=True, include_biomedical=True, sampling_rate=250.0)[source]

Initialize the feature extractor.

Parameters:

include_spectralbool

Whether to include spectral features

include_waveletbool

Whether to include wavelet features

include_fractalbool

Whether to include fractal features

include_biomedicalbool

Whether to include biomedical-specific features

sampling_ratefloat

Sampling rate for biomedical feature extraction

extract_features(data, true_hurst=None)[source]

Extract comprehensive features from time series data.

Return type:

FeatureSet

Parameters:

datanp.ndarray

Time series data

true_hurstfloat, optional

True Hurst exponent (for validation)

Returns:

: FeatureSet

Extracted features

RandomForestEstimator

class neurological_lrd_analysis.ml_baselines.ml_estimators.RandomForestEstimator(n_estimators=100, max_depth=None, min_samples_split=2, min_samples_leaf=1, random_state=42, **kwargs)[source]

Bases: BaseMLEstimator

Random Forest estimator for Hurst exponent prediction.

__init__(n_estimators=100, max_depth=None, min_samples_split=2, min_samples_leaf=1, random_state=42, **kwargs)[source]

Initialize Random Forest estimator.

Parameters:

n_estimatorsint

Number of trees in the forest

max_depthint, optional

Maximum depth of trees

min_samples_splitint

Minimum samples to split a node

min_samples_leafint

Minimum samples in a leaf

random_stateint

Random state for reproducibility

**kwargs

Additional parameters for RandomForestRegressor

SVREstimator

class neurological_lrd_analysis.ml_baselines.ml_estimators.SVREstimator(kernel='rbf', C=1.0, gamma='scale', epsilon=0.1, **kwargs)[source]

Bases: BaseMLEstimator

Support Vector Regression estimator for Hurst exponent prediction.

__init__(kernel='rbf', C=1.0, gamma='scale', epsilon=0.1, **kwargs)[source]

Initialize SVR estimator.

Parameters:

kernelstr

Kernel type (‘rbf’, ‘linear’, ‘poly’, ‘sigmoid’)

Cfloat

Regularization parameter

gammastr or float

Kernel coefficient

epsilonfloat

Epsilon-tube parameter

**kwargs

Additional parameters for SVR

GradientBoostingEstimator

class neurological_lrd_analysis.ml_baselines.ml_estimators.GradientBoostingEstimator(n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_split=2, min_samples_leaf=1, random_state=42, **kwargs)[source]

Bases: BaseMLEstimator

Gradient Boosting estimator for Hurst exponent prediction.

__init__(n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_split=2, min_samples_leaf=1, random_state=42, **kwargs)[source]

Initialize Gradient Boosting estimator.

Parameters:

n_estimatorsint

Number of boosting stages

learning_ratefloat

Learning rate

max_depthint

Maximum depth of trees

min_samples_splitint

Minimum samples to split a node

min_samples_leafint

Minimum samples in a leaf

random_stateint

Random state for reproducibility

**kwargs

Additional parameters for GradientBoostingRegressor

OptunaOptimizer

class neurological_lrd_analysis.ml_baselines.hyperparameter_optimization.OptunaOptimizer(study_name=None, direction='minimize', n_trials=100, timeout=None, pruner='median', sampler='tpe', random_state=42)[source]

Bases: object

Hyperparameter optimizer using Optuna.

__init__(study_name=None, direction='minimize', n_trials=100, timeout=None, pruner='median', sampler='tpe', random_state=42)[source]

Initialize the Optuna optimizer.

Parameters:

study_namestr, optional

Name of the study

directionstr

Optimization direction (‘minimize’ or ‘maximize’)

n_trialsint

Number of trials to run

timeoutfloat, optional

Timeout in seconds

prunerstr, optional

Pruning strategy (‘median’, ‘percentile’, ‘successive_halving’, None)

samplerstr, optional

Sampling strategy (‘tpe’, ‘random’, ‘cmaes’, ‘grid’)

random_stateint

Random state for reproducibility

optimize_random_forest(X, y, cv_folds=5, scoring='neg_mean_squared_error')[source]

Optimize Random Forest hyperparameters.

Return type:

OptimizationResult

Parameters:

Xnp.ndarray

Feature matrix

ynp.ndarray

Target values

cv_foldsint

Number of cross-validation folds

scoringstr

Scoring metric

Returns:

: OptimizationResult

Optimization results

optimize_svr(X, y, cv_folds=5, scoring='neg_mean_squared_error')[source]

Optimize SVR hyperparameters.

Return type:

OptimizationResult

Parameters:

Xnp.ndarray

Feature matrix

ynp.ndarray

Target values

cv_foldsint

Number of cross-validation folds

scoringstr

Scoring metric

Returns:

: OptimizationResult

Optimization results

optimize_gradient_boosting(X, y, cv_folds=5, scoring='neg_mean_squared_error')[source]

Optimize Gradient Boosting hyperparameters.

Return type:

OptimizationResult

Parameters:

Xnp.ndarray

Feature matrix

ynp.ndarray

Target values

cv_foldsint

Number of cross-validation folds

scoringstr

Scoring metric

Returns:

: OptimizationResult

Optimization results

PretrainedModelManager

class neurological_lrd_analysis.ml_baselines.pretrained_models.PretrainedModelManager(models_dir='pretrained_models')[source]

Bases: object

Manager for pretrained ML models.

Handles creation, storage, loading, and management of pretrained models for Hurst exponent estimation.

__init__(models_dir='pretrained_models')[source]

Initialize the pretrained model manager.

Parameters:

models_dirstr or Path

Directory to store pretrained models

create_training_data(hurst_values=None, lengths=None, n_samples_per_config=100, generators=None, contaminations=None, biomedical_scenarios=None, random_state=42)[source]

Create comprehensive training dataset.

Return type:

Tuple[ndarray, ndarray, Dict[str, Any]]

Parameters:

hurst_valuesList[float], optional

Hurst values to generate

lengthsList[int], optional

Time series lengths

n_samples_per_configint

Number of samples per configuration

generatorsList[str], optional

Data generators to use

contaminationsList[str], optional

Contamination types

biomedical_scenariosList[str], optional

Biomedical scenarios

random_stateint

Random state for reproducibility

Returns:

: Tuple[np.ndarray, np.ndarray, Dict[str, Any]]

(X, y, training_info) - features, targets, and metadata

train_model(training_config, X, y, training_info)[source]

Train a model and save it as pretrained.

Return type:

ModelMetadata

Parameters:

training_configTrainingConfig

Training configuration

Xnp.ndarray

Training features

ynp.ndarray

Training targets

training_infoDict[str, Any]

Training dataset information

Returns:

: ModelMetadata

Metadata for the trained model

load_model(model_id)[source]

Load a pretrained model.

Return type:

Tuple[BaseMLEstimator, ModelMetadata]

Parameters:

model_idstr

ID of the model to load

Returns:

: Tuple[BaseMLEstimator, ModelMetadata]

Loaded model and its metadata

list_models(model_type=None, status=None, tags=None)[source]

List available models with optional filtering.

Return type:

List[ModelMetadata]

Parameters:

model_typeMLBaselineType, optional

Filter by model type

statusModelStatus, optional

Filter by status

tagsList[str], optional

Filter by tags

Returns:

: List[ModelMetadata]

List of matching models

get_best_model(model_type, metric='validation_score')[source]

Get the best performing model of a given type.

Return type:

Tuple[BaseMLEstimator, ModelMetadata]

Parameters:

model_typeMLBaselineType

Type of model to get

metricstr

Metric to use for ranking

Returns:

: Tuple[BaseMLEstimator, ModelMetadata]

Best model and its metadata

predict(model_id, data, return_metadata=False)[source]

Make prediction using a pretrained model.

Return type:

Union[float, Tuple[float, ModelMetadata]]

Parameters:

model_idstr

ID of the model to use

datanp.ndarray

Time series data

return_metadatabool

Whether to return model metadata

Returns:

: Union[float, Tuple[float, ModelMetadata]]

Prediction result and optionally metadata

create_model_suite(training_configs, X, y, training_info)[source]

Create a suite of pretrained models.

Return type:

List[ModelMetadata]

Parameters:

training_configsList[TrainingConfig]

List of training configurations

Xnp.ndarray

Training features

ynp.ndarray

Training targets

training_infoDict[str, Any]

Training dataset information

Returns:

: List[ModelMetadata]

Metadata for all trained models

cleanup_models(keep_best=True, max_models_per_type=5)[source]

Clean up old or redundant models.

Return type:

None

Parameters:

keep_bestbool

Whether to keep the best performing model of each type

max_models_per_typeint

Maximum number of models to keep per type

PretrainedInference

class neurological_lrd_analysis.ml_baselines.inference.PretrainedInference(models_dir='pretrained_models')[source]

Bases: object

High-level interface for pretrained model inference.

Provides easy-to-use methods for Hurst exponent estimation using pretrained ML models with support for single predictions, batch processing, and ensemble methods.

__init__(models_dir='pretrained_models')[source]

Initialize the inference system.

Parameters:

models_dirstr or Path

Directory containing pretrained models

predict_single(data, model_id=None, model_type=None, use_best=True)[source]

Predict Hurst exponent for a single time series.

Return type:

PredictionResult

Parameters:

datanp.ndarray

Time series data

model_idstr, optional

Specific model ID to use

model_typeMLBaselineType, optional

Type of model to use (will select best if multiple available)

use_bestbool

Whether to use the best performing model if model_id not specified

Returns:

: PredictionResult

Prediction result with metadata

predict_batch(data_list, model_id=None, model_type=None, use_best=True, show_progress=True)[source]

Predict Hurst exponents for multiple time series.

Return type:

List[PredictionResult]

Parameters:

data_listList[np.ndarray]

List of time series data

model_idstr, optional

Specific model ID to use

model_typeMLBaselineType, optional

Type of model to use

use_bestbool

Whether to use the best performing model

show_progressbool

Whether to show progress during batch processing

Returns:

: List[PredictionResult]

List of prediction results

predict_ensemble(data, model_types=None, weights=None, include_uncertainty=True)[source]

Predict using ensemble of models.

Return type:

EnsembleResult

Parameters:

datanp.ndarray

Time series data

model_typesList[MLBaselineType], optional

Types of models to include in ensemble

weightsDict[str, float], optional

Weights for each model type

include_uncertaintybool

Whether to include uncertainty quantification

Returns:

: EnsembleResult

Ensemble prediction result

compare_models(data, model_types=None)[source]

Compare predictions from different model types.

Return type:

Dict[str, PredictionResult]

Parameters:

datanp.ndarray

Time series data

model_typesList[MLBaselineType], optional

Types of models to compare

Returns:

: Dict[str, PredictionResult]

Predictions from each model type

get_model_info(model_id=None)[source]

Get information about available models.

Return type:

Union[ModelMetadata, List[ModelMetadata]]

Parameters:

model_idstr, optional

Specific model ID, or None for all models

Returns:

: Union[ModelMetadata, List[ModelMetadata]]

Model metadata

benchmark_models(test_data, true_hurst, model_types=None)[source]

Benchmark model performance on test data.

Return type:

Dict[str, Dict[str, float]]

Parameters:

test_dataList[np.ndarray]

Test time series data

true_hurstList[float]

True Hurst exponents

model_typesList[MLBaselineType], optional

Types of models to benchmark

Returns:

: Dict[str, Dict[str, float]]

Performance metrics for each model type

ClassicalMLBenchmark

class neurological_lrd_analysis.ml_baselines.benchmark_comparison.ClassicalMLBenchmark(pretrained_models_dir='pretrained_models', classical_estimators=None, ml_estimators=None)[source]

Bases: object

Comprehensive benchmark comparing classical and ML methods.

Provides systematic comparison of classical Hurst estimation methods with machine learning baseline models across various test scenarios.

__init__(pretrained_models_dir='pretrained_models', classical_estimators=None, ml_estimators=None)[source]

Initialize the benchmark system.

Parameters:

pretrained_models_dirstr or Path

Directory containing pretrained ML models

classical_estimatorsList[EstimatorType], optional

Classical estimators to include

ml_estimatorsList[str], optional

ML model types to include

create_test_scenarios(hurst_values=None, lengths=None, n_samples_per_config=10, include_contamination=True, include_biomedical=True)[source]

Create comprehensive test scenarios.

Return type:

List[TimeSeriesSample]

Parameters:

hurst_valuesList[float], optional

Hurst values to test

lengthsList[int], optional

Time series lengths

n_samples_per_configint

Number of samples per configuration

include_contaminationbool

Whether to include contaminated data

include_biomedicalbool

Whether to include biomedical scenarios

Returns:

: List[TimeSeriesSample]

Test scenarios

benchmark_classical_methods(samples)[source]

Benchmark classical Hurst estimation methods.

Return type:

Dict[str, List[BenchmarkResult]]

Parameters:

samplesList[TimeSeriesSample]

Test scenarios

Returns:

: Dict[str, List[BenchmarkResult]]

Results for each classical method

benchmark_ml_methods(samples)[source]

Benchmark machine learning methods.

Return type:

Dict[str, List[BenchmarkResult]]

Parameters:

samplesList[TimeSeriesSample]

Test scenarios

Returns:

: Dict[str, List[BenchmarkResult]]

Results for each ML method

run_comprehensive_benchmark(test_scenarios=None, save_results=True, results_dir='benchmark_results')[source]

Run comprehensive benchmark comparison.

Return type:

Dict[str, Any]

Parameters:

test_scenariosList[TimeSeriesSample], optional

Test scenarios to use

save_resultsbool

Whether to save results to disk

results_dirstr or Path

Directory to save results

Returns:

: Dict[str, Any]

Complete benchmark results

calculate_summaries(results)[source]

Calculate performance summaries for all methods.

Return type:

Dict[str, BenchmarkSummary]

print_benchmark_summary(summaries)[source]

Print benchmark summary.

Return type:

None

save_benchmark_results(benchmark_data, results_dir)[source]

Save benchmark results to disk.

Return type:

None

create_visualizations(benchmark_data, save_path=None)[source]

Create comprehensive visualizations of benchmark results.

Return type:

None

Data Generation

Synthetic Data Generators

Synthetic data generation for Hurst exponent estimation benchmarking.

This module provides functions to generate various types of synthetic time series with known Hurst exponents for testing and validation purposes.

class neurological_lrd_analysis.benchmark_core.generation.TimeSeriesSample(data, true_hurst, length, contamination, seed=None)[source]

Container for a generated time series sample.

data: ndarray
true_hurst: float | None
length: int
contamination: str
seed: int | None = None
__init__(data, true_hurst, length, contamination, seed=None)
neurological_lrd_analysis.benchmark_core.generation.fbm_davies_harte(n, hurst, seed=None)[source]

Generate fractional Brownian motion using the Davies-Harte method.

This implementation uses the fbm library which provides a fast and accurate implementation of the Davies-Harte method for generating fBm samples.

Return type:

ndarray

Parameters:

nint

Length of the time series

hurstfloat

Hurst exponent (0 < H < 1)

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

Fractional Brownian motion time series

neurological_lrd_analysis.benchmark_core.generation.generate_fgn(n, hurst, seed=None)[source]

Generate fractional Gaussian noise.

Return type:

ndarray

Parameters:

nint

Length of the time series

hurstfloat

Hurst exponent (0 < H < 1)

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

Fractional Gaussian noise time series

neurological_lrd_analysis.benchmark_core.generation.generate_arfima(n, hurst, ar_coeffs=None, ma_coeffs=None, seed=None)[source]

Generate ARFIMA (AutoRegressive Fractionally Integrated Moving Average) time series.

Return type:

ndarray

Parameters:

nint

Length of the time series

hurstfloat

Hurst exponent (0 < H < 1), related to fractional differencing parameter d = H - 0.5

ar_coeffsList[float], optional

AR coefficients (default: [0.3, -0.1] for AR(2))

ma_coeffsList[float], optional

MA coefficients (default: [0.2] for MA(1))

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

ARFIMA time series

neurological_lrd_analysis.benchmark_core.generation.generate_mrw(n, hurst, lambda_param=0.12, sigma=1.0, seed=None)[source]

Generate Multifractal Random Walk (MRW) time series.

Return type:

ndarray

Parameters:

nint

Length of the time series

hurstfloat

Hurst exponent (0 < H < 1)

lambda_paramfloat, optional

Intermittency parameter (default: 0.12)

sigmafloat, optional

Volatility parameter (default: 1.0)

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

MRW time series

neurological_lrd_analysis.benchmark_core.generation.generate_fou(n, hurst, theta=1.0, sigma=1.0, seed=None)[source]

Generate Fractional Ornstein-Uhlenbeck (fOU) process.

Return type:

ndarray

Parameters:

nint

Length of the matrix

hurstfloat

Hurst exponent (0 < H < 1)

thetafloat, optional

Mean reversion parameter (default: 1.0)

sigmafloat, optional

Volatility parameter (default: 1.0)

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

fOU process

neurological_lrd_analysis.benchmark_core.generation.add_contamination(data, contamination_type, contamination_level=0.1, seed=None)[source]

Add contamination to time series data.

Return type:

ndarray

Parameters:

datanp.ndarray

Original time series

contamination_typestr
Type of contamination (‘none’, ‘noise’, ‘missing’, ‘outliers’, ‘trend’,

‘baseline_drift’, ‘electrode_pop’, ‘motion’, ‘powerline’, ‘heavy_tail’, ‘neural_avalanche’, ‘parkinsonian_tremor’, ‘epileptic_spike’, ‘burst_suppression’)

contamination_levelfloat

Level of contamination (0-1)

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

Contaminated time series

neurological_lrd_analysis.benchmark_core.generation.generate_grid(hurst_values, lengths, contaminations, contamination_level=0.1, generators=None, biomedical_scenarios=None, seed=None)[source]

Generate a grid of time series samples for benchmarking.

Return type:

List[TimeSeriesSample]

Parameters:

hurst_valuesList[float]

List of Hurst exponents to generate

lengthsList[int]

List of time series lengths to generate

contaminationsList[str]

List of contamination types to apply

contamination_levelfloat

Level of contamination to apply

generatorsList[str], optional

List of generator types to use (‘fbm’, ‘fgn’, ‘arfima’, ‘mrw’, ‘fou’) Default: [‘fbm’]

biomedical_scenariosList[str], optional

List of biomedical scenarios to generate (‘eeg_rest’, ‘ecg_normal’, etc.)

seedint, optional

Random seed for reproducibility

Returns:

: List[TimeSeriesSample]

List of generated time series samples

Biomedical Scenarios

Biomedical scenario-based time series data generation.

This module provides realistic biomedical time series generators (EEG, ECG, etc.) with appropriate contamination methods relevant to real biomedical data.

class neurological_lrd_analysis.benchmark_core.biomedical_scenarios.BiomedicalScenario(scenario_type, sampling_rate, duration, hurst_range, typical_amplitude, noise_level, artifact_probability)[source]

Configuration for biomedical time series scenarios.

scenario_type: str
sampling_rate: float
duration: float
hurst_range: Tuple[float, float]
typical_amplitude: float
noise_level: float
artifact_probability: float
__init__(scenario_type, sampling_rate, duration, hurst_range, typical_amplitude, noise_level, artifact_probability)
neurological_lrd_analysis.benchmark_core.biomedical_scenarios.generate_eeg_scenario(n, hurst, scenario='rest', contamination_level=0.1, seed=None)[source]

Generate realistic EEG time series data.

Return type:

ndarray

Parameters:

nint

Length of the time series

hurstfloat

Hurst exponent (0 < H < 1)

scenariostr

EEG scenario (‘rest’, ‘eyes_closed’, ‘eyes_open’, ‘sleep’, ‘seizure’)

contamination_levelfloat

Level of contamination/artifacts

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

EEG-like time series data

neurological_lrd_analysis.benchmark_core.biomedical_scenarios.generate_ecg_scenario(n, hurst, heart_rate=70.0, contamination_level=0.1, seed=None)[source]

Generate realistic ECG time series data.

Return type:

ndarray

Parameters:

nint

Length of the time series

hurstfloat

Hurst exponent (0 < H < 1)

heart_ratefloat

Heart rate in BPM

contamination_levelfloat

Level of contamination/artifacts

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

ECG-like time series data

neurological_lrd_analysis.benchmark_core.biomedical_scenarios.generate_respiratory_scenario(n, hurst, breathing_rate=15.0, contamination_level=0.1, seed=None)[source]

Generate realistic respiratory time series data.

Return type:

ndarray

Parameters:

nint

Length of the time series

hurstfloat

Hurst exponent (0 < H < 1)

breathing_ratefloat

Breathing rate in breaths per minute

contamination_levelfloat

Level of contamination/artifacts

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

Respiratory-like time series data

neurological_lrd_analysis.benchmark_core.biomedical_scenarios.add_eeg_artifacts(data, contamination_level, seed=None)[source]

Add EEG-specific artifacts to the signal.

Return type:

ndarray

Parameters:

datanp.ndarray

Original EEG signal

contamination_levelfloat

Level of contamination

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

EEG signal with artifacts

neurological_lrd_analysis.benchmark_core.biomedical_scenarios.add_ecg_artifacts(data, contamination_level, seed=None)[source]

Add ECG-specific artifacts to the signal.

Return type:

ndarray

Parameters:

datanp.ndarray

Original ECG signal

contamination_levelfloat

Level of contamination

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

ECG signal with artifacts

neurological_lrd_analysis.benchmark_core.biomedical_scenarios.add_respiratory_artifacts(data, contamination_level, seed=None)[source]

Add respiratory-specific artifacts to the signal.

Return type:

ndarray

Parameters:

datanp.ndarray

Original respiratory signal

contamination_levelfloat

Level of contamination

seedint, optional

Random seed for reproducibility

Returns:

: np.ndarray

Respiratory signal with artifacts

neurological_lrd_analysis.benchmark_core.biomedical_scenarios.generate_biomedical_scenario(scenario_type, n, hurst, contamination_level=0.1, auto_contamination=None, seed=None, **kwargs)[source]

Generate biomedical time series data for a specific scenario.

Return type:

ndarray

Parameters:

scenario_typestr

Type of biomedical scenario (‘eeg’, ‘ecg’, ‘respiratory’)

nint

Length of the time series

hurstfloat

Hurst exponent

contamination_levelfloat

Level of contamination/artifacts

auto_contaminationstr, optional

Automatic contamination type to apply (e.g., ‘parkinsonian_tremor’, ‘epileptic_spike’)

**kwargs

Additional parameters for specific scenarios

Returns:

: np.ndarray

Biomedical time series data

neurological_lrd_analysis.benchmark_core.biomedical_scenarios.generate_biomedical_grid(scenario_type, hurst_values, lengths, contamination_levels, **kwargs)[source]

Generate a grid of biomedical time series samples.

Return type:

List[TimeSeriesSample]

Parameters:

scenario_typestr

Type of biomedical scenario

hurst_valuesList[float]

List of Hurst exponents

lengthsList[int]

List of time series lengths

contamination_levelsList[float]

List of contamination levels

**kwargs

Additional parameters for specific scenarios

Returns:

: List[TimeSeriesSample]

List of biomedical time series samples

Benchmarking

Configuration and Results

Benchmark runner for Hurst exponent estimation methods.

This module provides functionality to run benchmarks on generated datasets and collect results for performance evaluation.

class neurological_lrd_analysis.benchmark_core.runner.ScoringWeights(success_rate=0.3, accuracy=0.3, speed=0.2, robustness=0.2)[source]

Weights for different performance metrics in the scoring function.

success_rate: float = 0.3
accuracy: float = 0.3
speed: float = 0.2
robustness: float = 0.2
__post_init__()[source]

Ensure weights sum to 1.0.

__init__(success_rate=0.3, accuracy=0.3, speed=0.2, robustness=0.2)
class neurological_lrd_analysis.benchmark_core.runner.BenchmarkConfig(output_dir, true_hurst=None, n_bootstrap=100, confidence_level=0.95, random_state=None, estimators=None, save_results=True, verbose=False, use_bayesian=False, num_samples=1000, num_warmup=500, scoring_weights=None)[source]

Configuration for benchmark runs.

output_dir: str
true_hurst: float | None = None
n_bootstrap: int = 100
confidence_level: float = 0.95
random_state: int | None = None
estimators: List[str] | None = None
save_results: bool = True
verbose: bool = False
use_bayesian: bool = False
num_samples: int = 1000
num_warmup: int = 500
scoring_weights: ScoringWeights | None = None
__post_init__()[source]

Initialize default scoring weights if not provided.

__init__(output_dir, true_hurst=None, n_bootstrap=100, confidence_level=0.95, random_state=None, estimators=None, save_results=True, verbose=False, use_bayesian=False, num_samples=1000, num_warmup=500, scoring_weights=None)
class neurological_lrd_analysis.benchmark_core.runner.BenchmarkResult(estimator, hurst_estimate, true_hurst=None, computation_time=0.0, convergence_flag=True, additional_metrics=<factory>, error_message=None, contamination=None, length=None, bias=None, absolute_error=None, relative_error=None, confidence_interval=None, p_value=None, standard_error=None)[source]

Result from a single estimator run.

estimator: str
hurst_estimate: float
true_hurst: float | None = None
computation_time: float = 0.0
convergence_flag: bool = True
additional_metrics: Dict[str, Any]
error_message: str | None = None
contamination: str | None = None
length: int | None = None
bias: float | None = None
absolute_error: float | None = None
relative_error: float | None = None
confidence_interval: tuple | None = None
p_value: float | None = None
standard_error: float | None = None
to_dict()[source]

Convert result to dictionary.

Return type:

Dict[str, Any]

__init__(estimator, hurst_estimate, true_hurst=None, computation_time=0.0, convergence_flag=True, additional_metrics=<factory>, error_message=None, contamination=None, length=None, bias=None, absolute_error=None, relative_error=None, confidence_interval=None, p_value=None, standard_error=None)
neurological_lrd_analysis.benchmark_core.runner.run_benchmark_on_dataset(samples, config)[source]

Run benchmark on a dataset of time series samples.

Return type:

List[BenchmarkResult]

Parameters:

samplesList[TimeSeriesSample]

List of time series samples to benchmark

configBenchmarkConfig

Benchmark configuration

Returns:

: List[BenchmarkResult]

List of benchmark results

neurological_lrd_analysis.benchmark_core.runner.save_benchmark_results(results, config, create_visualizations=True)[source]

Save benchmark results to files.

Return type:

None

Parameters:

resultsList[BenchmarkResult]

Benchmark results to save

configBenchmarkConfig

Benchmark configuration

create_visualizationsbool

Whether to create visualization plots

neurological_lrd_analysis.benchmark_core.runner.calculate_estimator_score(analysis, estimator, weights)[source]

Calculate a parametrized score for an estimator based on performance metrics.

Return type:

float

Parameters:

analysisDict[str, Any]

Analysis results from analyze_benchmark_results

estimatorstr

Name of the estimator

weightsScoringWeights

Weights for different metrics

Returns:

: float

Overall score (higher is better)

neurological_lrd_analysis.benchmark_core.runner.analyze_benchmark_results(results)[source]

Analyze benchmark results and compute performance metrics.

Return type:

Dict[str, Any]

Parameters:

resultsList[BenchmarkResult]

Benchmark results to analyze

Returns:

: Dict[str, Any]

Analysis results

neurological_lrd_analysis.benchmark_core.runner.create_leaderboard(results, weights=None)[source]

Create a leaderboard from benchmark results using parametrized scoring.

Return type:

DataFrame

Parameters:

resultsList[BenchmarkResult]

Benchmark results

weightsScoringWeights, optional

Weights for scoring function. If None, uses default weights.

Returns:

: pd.DataFrame

Leaderboard DataFrame sorted by overall score

Registry System

Estimator Registry

Registry for Hurst exponent estimation methods.

This module provides a registry system for managing and accessing different Hurst exponent estimation methods.

class neurological_lrd_analysis.benchmark_registry.registry.EstimatorResult(hurst_estimate, convergence_flag, computation_time, additional_metrics, error_message=None)[source]

Result from an estimator run.

hurst_estimate: float
convergence_flag: bool
computation_time: float
additional_metrics: Dict[str, Any]
error_message: str | None = None
to_dict()[source]

Convert result to dictionary.

Return type:

Dict[str, Any]

__init__(hurst_estimate, convergence_flag, computation_time, additional_metrics, error_message=None)
class neurological_lrd_analysis.benchmark_registry.registry.BaseEstimator(name)[source]

Base class for all Hurst exponent estimators.

__init__(name)[source]
abstractmethod estimate(data, **kwargs)[source]

Estimate Hurst exponent from data.

Return type:

EstimatorResult

class neurological_lrd_analysis.benchmark_registry.registry.FactoryEstimator(name, factory_method)[source]

Wrapper for estimators from the biomedical factory.

__init__(name, factory_method)[source]
estimate(data, **kwargs)[source]

Estimate using the biomedical factory.

Return type:

EstimatorResult

class neurological_lrd_analysis.benchmark_registry.registry.DFAEstimator[source]

DFA estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.HiguchiEstimator[source]

Higuchi estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.PeriodogramEstimator[source]

Periodogram estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.RSAnalysisEstimator[source]

R/S Analysis estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.GPHEstimator[source]

GPH estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.WhittleMLEEstimator[source]

Local Whittle MLE estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.GHEEstimator[source]

Generalized Hurst Exponent estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.MFDFAEstimator[source]

MFDFA estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.MFDMAEstimator[source]

MF-DMA estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.DWTLogscaleEstimator[source]

DWT Logscale estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.AbryVeitchEstimator[source]

Abry-Veitch estimator.

__init__()[source]
class neurological_lrd_analysis.benchmark_registry.registry.NDWTLogscaleEstimator[source]

NDWT Logscale estimator.

__init__()[source]
neurological_lrd_analysis.benchmark_registry.registry.get_registry()[source]

Get the list of available estimators.

Return type:

List[BaseEstimator]

neurological_lrd_analysis.benchmark_registry.registry.register_estimator(estimator)[source]

Register a new estimator.

Return type:

None

neurological_lrd_analysis.benchmark_registry.registry.get_estimator_by_name(name)[source]

Get an estimator by name.

Return type:

Optional[BaseEstimator]

neurological_lrd_analysis.benchmark_registry.registry.list_estimator_names()[source]

List all available estimator names.

Return type:

List[str]

neurological_lrd_analysis.benchmark_registry.registry.get_estimators_by_category(category)[source]

Get estimators by category.

Return type:

List[BaseEstimator]

neurological_lrd_analysis.benchmark_registry.registry.benchmark_estimator(estimator, data, n_runs=5)[source]

Benchmark an estimator on given data.

Return type:

Dict[str, Any]

Parameters:

estimatorBaseEstimator

Estimator to benchmark

datanp.ndarray

Data to test on

n_runsint

Number of runs for timing

Returns:

: Dict[str, Any]

Benchmark results

Backend Selection

Backend Selector

Backend selection logic for Hurst exponent estimation.

This module provides functionality to automatically select the best available backend based on hardware capabilities, data size, and performance requirements.

class neurological_lrd_analysis.benchmark_backends.selector.BackendType(value)[source]

Available backend types.

NUMPY = 'numpy'
NUMBA_CPU = 'numba_cpu'
NUMBA_GPU = 'numba_gpu'
JAX_CPU = 'jax_cpu'
JAX_GPU = 'jax_gpu'
neurological_lrd_analysis.benchmark_backends.selector.check_jax_availability()[source]

Check JAX availability and GPU support.

Return type:

Dict[str, bool]

neurological_lrd_analysis.benchmark_backends.selector.check_numba_availability()[source]

Check Numba availability and GPU support.

Return type:

Dict[str, bool]

neurological_lrd_analysis.benchmark_backends.selector.get_system_info()[source]

Get system information for backend selection.

Return type:

Dict[str, Any]

neurological_lrd_analysis.benchmark_backends.selector.get_available_backends()[source]

Get list of available backends.

Return type:

List[BackendType]

neurological_lrd_analysis.benchmark_backends.selector.select_backend(data_size, real_time=False, prefer_gpu=True, prefer_jax=True)[source]

Select the best available backend for the given requirements.

Return type:

str

Parameters:

data_sizeint

Size of the data to process

real_timebool

Whether real-time processing is required

prefer_gpubool

Whether to prefer GPU backends

prefer_jaxbool

Whether to prefer JAX backends

Returns:

: str

Selected backend name

neurological_lrd_analysis.benchmark_backends.selector.get_backend_info()[source]

Get information about available backends.

Return type:

Dict[str, Any]

neurological_lrd_analysis.benchmark_backends.selector.recommend_backend(data_size, use_case='general', **kwargs)[source]

Recommend backend with detailed reasoning.

Return type:

Dict[str, Any]

Parameters:

data_sizeint

Size of the data to process

use_casestr

Use case description (“general”, “real_time”, “batch”, “research”)

**kwargs

Additional parameters

Returns:

: Dict[str, Any]

Recommendation with reasoning

Individual Estimators

Temporal Estimators

DFA Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.DFAEstimator[source]

Bases: BaseHurstEstimator

Detrended Fluctuation Analysis optimized for biomedical signals

__init__()[source]
estimate(data, min_window=None, max_window=None, polynomial_order=1, overlap=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

R/S Analysis Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.RSAnalysisEstimator[source]

Bases: BaseHurstEstimator

Rescaled Range (R/S) Analysis estimator

__init__()[source]
estimate(data, min_window=None, max_window=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

Higuchi Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.HiguchiEstimator[source]

Bases: BaseHurstEstimator

Higuchi Fractal Dimension method

__init__()[source]
estimate(data, kmax=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

Generalized Hurst Exponent Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.GHEEstimator[source]

Bases: BaseHurstEstimator

Generalized Hurst Exponent estimator

__init__()[source]
estimate(data, q_values=None, max_tau=100, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

Spectral Estimators

Periodogram Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.PeriodogramEstimator[source]

Bases: BaseHurstEstimator

Periodogram-based Hurst estimation

__init__()[source]
estimate(data, low_freq_fraction=0.1, high_freq_cutoff=0.4, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

GPH Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.GPHEstimator[source]

Bases: BaseHurstEstimator

Geweke-Porter-Hudak (GPH) estimator

__init__()[source]
estimate(data, m_fraction=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

Whittle MLE Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.WhittleMLEEstimator[source]

Bases: BaseHurstEstimator

Local Whittle Maximum Likelihood Estimator

__init__()[source]
estimate(data, m_fraction=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

Wavelet Estimators

DWT Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.DWTEstimator[source]

Bases: BaseHurstEstimator

Discrete Wavelet Transform Logscale estimator

__init__()[source]
estimate(data, wavelet='db4', max_level=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

NDWT Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.NDWTEstimator[source]

Bases: BaseHurstEstimator

Non-decimated Wavelet Transform Logscale estimator

__init__()[source]
estimate(data, wavelet='db4', max_level=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

Abry-Veitch Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.AbryVeitchEstimator[source]

Bases: BaseHurstEstimator

Abry-Veitch wavelet-based estimator

__init__()[source]
estimate(data, wavelet='db4', max_level=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

Multifractal Estimators

MFDFA Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.MFDFAEstimator[source]

Bases: BaseHurstEstimator

Multifractal Detrended Fluctuation Analysis estimator (q=2)

__init__()[source]
estimate(data, q=2.0, min_window=None, max_window=None, polynomial_order=1, overlap=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

MF-DMA Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.MFDMAEstimator[source]

Bases: BaseHurstEstimator

Multifractal Detrended Moving Average estimator (q=2)

__init__()[source]
estimate(data, q=2.0, min_window=None, max_window=None, overlap=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

Bayesian Estimators

Bayesian Hurst Estimator

class neurological_lrd_analysis.biomedical_hurst_factory.BayesianHurstEstimator(estimator_type=EstimatorType.DFA)[source]

Bases: object

Bayesian inference for Hurst exponent estimation using NumPyro

__init__(estimator_type=EstimatorType.DFA)[source]
dfa_model(data, min_window=10, max_window=None)[source]

Bayesian model for DFA-based Hurst estimation

Model: log(F(n)) = log(C) + H * log(n) + ε where ε ~ Normal(0, σ²)

periodogram_model(data, low_freq_fraction=0.4)[source]

Bayesian model for periodogram-based Hurst estimation

Model: log(S(f)) = log(C) - (2H-1) * log(f) + ε

infer_hurst(data, num_samples=1000, num_warmup=500, num_chains=4, random_seed=42)[source]

Perform Bayesian inference for Hurst exponent

Return type:

Dict[str, Any]

Parameters:
datanp.ndarray

Time series data

num_samplesint

Number of MCMC samples

num_warmupint

Number of warmup samples

num_chainsint

Number of MCMC chains

random_seedint

Random seed for reproducibility

Returns:

: Dict containing posterior samples and statistics

static bayesian_confidence(estimator, data, estimator_type=EstimatorType.DFA, num_samples=1000, num_warmup=500, random_seed=None)[source]

Static method for Bayesian confidence estimation

Return type:

Tuple[float, Tuple[float, float], Dict[str, Any]]

Parameters:
estimatorBaseHurstEstimator

Estimator instance (not used in Bayesian approach, but kept for interface consistency)

datanp.ndarray

Time series data

estimator_typeEstimatorType

Type of estimator to use for Bayesian model

num_samplesint

Number of MCMC samples

num_warmupint

Number of warmup samples

random_seedint

Random seed

Returns:

: Tuple of (mean_estimate, credible_interval, inference_results)

Utility Machine Learning Functions

Feature Extraction Functions

neurological_lrd_analysis.ml_baselines.feature_extraction.extract_statistical_features(data)[source]

Extract statistical features from time series data.

Return type:

Dict[str, float]

Parameters:

datanp.ndarray

Time series data

Returns:

: Dict[str, float]

Statistical features

neurological_lrd_analysis.ml_baselines.feature_extraction.extract_spectral_features(data, scipy_signal, fft, fftfreq)[source]

Extract spectral features from time series data.

Return type:

Dict[str, float]

Parameters:

datanp.ndarray

Time series data

scipy_signalmodule

scipy.signal module

fftfunction

FFT function

fftfreqfunction

FFT frequency function

Returns:

: Dict[str, float]

Spectral features

neurological_lrd_analysis.ml_baselines.feature_extraction.extract_wavelet_features(data, pywt)[source]

Extract wavelet features from time series data.

Return type:

Dict[str, float]

Parameters:

datanp.ndarray

Time series data

pywtmodule

PyWavelets module

Returns:

: Dict[str, float]

Wavelet features

neurological_lrd_analysis.ml_baselines.feature_extraction.extract_fractal_features(data)[source]

Extract fractal features from time series data.

Return type:

Dict[str, float]

Parameters:

datanp.ndarray

Time series data

Returns:

: Dict[str, float]

Fractal features

neurological_lrd_analysis.ml_baselines.feature_extraction.extract_biomedical_features(data, sampling_rate)[source]

Extract biomedical-specific features from time series data.

Return type:

Dict[str, float]

Parameters:

datanp.ndarray

Time series data

sampling_ratefloat

Sampling rate in Hz

Returns:

: Dict[str, float]

Biomedical features

Hyperparameter Optimization Functions

neurological_lrd_analysis.ml_baselines.hyperparameter_optimization.create_optuna_study(study_name, direction='minimize', pruner='median', sampler='tpe', random_state=42)[source]

Create an Optuna study for hyperparameter optimization.

Return type:

Any

Parameters:

study_namestr

Name of the study

directionstr

Optimization direction

prunerstr

Pruning strategy

samplerstr

Sampling strategy

random_stateint

Random state

Returns:

: optuna.Study

Created study

neurological_lrd_analysis.ml_baselines.hyperparameter_optimization.optimize_hyperparameters(estimator_type, X, y, n_trials=100, timeout=None, cv_folds=5, scoring='neg_mean_squared_error', random_state=42)[source]

Optimize hyperparameters for a specific estimator type.

Return type:

OptimizationResult

Parameters:

estimator_typestr

Type of estimator (‘random_forest’, ‘svr’, ‘gradient_boosting’)

Xnp.ndarray

Feature matrix

ynp.ndarray

Target values

n_trialsint

Number of optimization trials

timeoutfloat, optional

Timeout in seconds

cv_foldsint

Number of cross-validation folds

scoringstr

Scoring metric

random_stateint

Random state

Returns:

: OptimizationResult

Optimization results

neurological_lrd_analysis.ml_baselines.hyperparameter_optimization.optimize_all_estimators(X, y, estimator_types=None, n_trials=100, timeout=None, cv_folds=5, scoring='neg_mean_squared_error', random_state=42)[source]

Optimize hyperparameters for all estimator types.

Return type:

Dict[str, OptimizationResult]

Parameters:

Xnp.ndarray

Feature matrix

ynp.ndarray

Target values

estimator_typesList[str], optional

Types of estimators to optimize

n_trialsint

Number of optimization trials

timeoutfloat, optional

Timeout in seconds

cv_foldsint

Number of cross-validation folds

scoringstr

Scoring metric

random_stateint

Random state

Returns:

: Dict[str, OptimizationResult]

Optimization results for each estimator

Pretrained Model Functions

neurological_lrd_analysis.ml_baselines.pretrained_models.create_default_training_configs()[source]

Create default training configurations for all model types.

Return type:

List[TrainingConfig]

neurological_lrd_analysis.ml_baselines.pretrained_models.create_pretrained_suite(models_dir='pretrained_models', force_retrain=False)[source]

Create a complete suite of pretrained models.

Return type:

PretrainedModelManager

Parameters:

models_dirstr or Path

Directory to store models

force_retrainbool

Whether to retrain existing models

Returns:

: PretrainedModelManager

Manager with trained models

Inference Functions

neurological_lrd_analysis.ml_baselines.inference.quick_predict(data, models_dir='pretrained_models', model_type=None)[source]

Quick prediction function for single time series.

Return type:

float

Parameters:

datanp.ndarray

Time series data

models_dirstr or Path

Directory containing pretrained models

model_typeMLBaselineType, optional

Type of model to use

Returns:

: float

Predicted Hurst exponent

neurological_lrd_analysis.ml_baselines.inference.quick_ensemble_predict(data, models_dir='pretrained_models', model_types=None)[source]

Quick ensemble prediction function.

Return type:

Tuple[float, float]

Parameters:

datanp.ndarray

Time series data

models_dirstr or Path

Directory containing pretrained models

model_typesList[MLBaselineType], optional

Types of models to include in ensemble

Returns:

: Tuple[float, float]

(mean_estimate, std_estimate)

Benchmark Functions

neurological_lrd_analysis.ml_baselines.benchmark_comparison.run_comprehensive_benchmark(pretrained_models_dir='pretrained_models', results_dir='benchmark_results', test_scenarios=None)[source]

Run comprehensive benchmark comparison.

Return type:

Dict[str, Any]

Parameters:

pretrained_models_dirstr or Path

Directory containing pretrained models

results_dirstr or Path

Directory to save results

test_scenariosList[TimeSeriesSample], optional

Test scenarios to use

Returns:

: Dict[str, Any]

Complete benchmark results

Functions

Helper Functions

Biomedical Hurst Exponent Estimation Factory

A comprehensive Python library for estimating Hurst exponents in biomedical time series data with statistical confidence, uncertainty quantification, and performance monitoring.

Developed as part of PhD research in Biomedical Engineering at the University of Reading, UK. Author: Davian R. Chin (PhD Candidate in Biomedical Engineering, University of Reading, UK) Email: d.r.chin@pgr.reading.ac.uk ORCiD: https://orcid.org/0009-0003-9434-3919 Research Focus: Physics-Informed Fractional Operator Learning for Real-Time Neurological Biomarker Detection: A Framework for Memory-Driven EEG Analysis

This library represents a significant contribution to the field of physics-informed machine learning for neurological signal processing, providing researchers and practitioners with a comprehensive toolkit for fractional operator learning and real-time biomarker detection in EEG and other neurological time series data.

Date: October 2025 License: MIT

Example Usage:

from neurological_lrd_analysis import BiomedicalHurstEstimatorFactory, EstimatorType

factory = BiomedicalHurstEstimatorFactory() result = factory.estimate(data, EstimatorType.DFA) print(f”Hurst exponent: {result.hurst_estimate:.3f}”)

class neurological_lrd_analysis.biomedical_hurst_factory.EstimatorType(value)[source]

Types of Hurst estimators available

DFA = 'dfa'
RS_ANALYSIS = 'rs'
HIGUCHI = 'higuchi'
DETRENDED_MA = 'dma'
GENERALIZED_HURST = 'ghe'
PERIODOGRAM = 'periodogram'
WHITTLE_MLE = 'whittle'
GPH = 'gph'
DWT = 'dwt'
CWT = 'cwt'
NDWT = 'ndwt'
WAVELET_LEADERS = 'leaders'
ABRY_VEITCH = 'abry_veitch'
MFDFA = 'mfdfa'
MF_DMA = 'mf_dma'
RANDOM_FOREST = 'rf'
SVR = 'svr'
TEMPORAL = 'temporal'
SPECTRAL = 'spectral'
WAVELET = 'wavelet'
ALL = 'all'
class neurological_lrd_analysis.biomedical_hurst_factory.ConfidenceMethod(value)[source]

Methods for confidence interval estimation

BOOTSTRAP = 'bootstrap'
THEORETICAL = 'theoretical'
CROSS_VALIDATION = 'cross_validation'
BAYESIAN = 'bayesian'
NONE = 'none'
class neurological_lrd_analysis.biomedical_hurst_factory.GroupHurstResult(individual_results, ensemble_estimate, ensemble_confidence_interval, method_agreement, best_method, consensus_estimate, weighted_estimate, total_computation_time)[source]

Results for group estimation (multiple methods)

individual_results: List[HurstResult]
ensemble_estimate: float
ensemble_confidence_interval: Tuple[float, float]
method_agreement: float
best_method: str
consensus_estimate: float
weighted_estimate: float
total_computation_time: float
to_dict()[source]

Convert group result to dictionary

__init__(individual_results, ensemble_estimate, ensemble_confidence_interval, method_agreement, best_method, consensus_estimate, weighted_estimate, total_computation_time)
class neurological_lrd_analysis.biomedical_hurst_factory.BaseHurstEstimator(name)[source]

Base class for all Hurst estimators

__init__(name)[source]
estimate(data, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

validate_data(data, min_length=50)[source]

Validate input data

Return type:

None

class neurological_lrd_analysis.biomedical_hurst_factory.DFAEstimator[source]

Detrended Fluctuation Analysis optimized for biomedical signals

__init__()[source]
estimate(data, min_window=None, max_window=None, polynomial_order=1, overlap=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.HiguchiEstimator[source]

Higuchi Fractal Dimension method

__init__()[source]
estimate(data, kmax=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.PeriodogramEstimator[source]

Periodogram-based Hurst estimation

__init__()[source]
estimate(data, low_freq_fraction=0.1, high_freq_cutoff=0.4, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.RSAnalysisEstimator[source]

Rescaled Range (R/S) Analysis estimator

__init__()[source]
estimate(data, min_window=None, max_window=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.GPHEstimator[source]

Geweke-Porter-Hudak (GPH) estimator

__init__()[source]
estimate(data, m_fraction=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.WhittleMLEEstimator[source]

Local Whittle Maximum Likelihood Estimator

__init__()[source]
estimate(data, m_fraction=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.GHEEstimator[source]

Generalized Hurst Exponent estimator

__init__()[source]
estimate(data, q_values=None, max_tau=100, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.DWTEstimator[source]

Discrete Wavelet Transform Logscale estimator

__init__()[source]
estimate(data, wavelet='db4', max_level=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.AbryVeitchEstimator[source]

Abry-Veitch wavelet-based estimator

__init__()[source]
estimate(data, wavelet='db4', max_level=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.NDWTEstimator[source]

Non-decimated Wavelet Transform Logscale estimator

__init__()[source]
estimate(data, wavelet='db4', max_level=None, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.MFDFAEstimator[source]

Multifractal Detrended Fluctuation Analysis estimator (q=2)

__init__()[source]
estimate(data, q=2.0, min_window=None, max_window=None, polynomial_order=1, overlap=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.MFDMAEstimator[source]

Multifractal Detrended Moving Average estimator (q=2)

__init__()[source]
estimate(data, q=2.0, min_window=None, max_window=None, overlap=0.5, **kwargs)[source]

Estimate Hurst exponent with additional metrics

Return type:

Tuple[float, Dict[str, Any]]

class neurological_lrd_analysis.biomedical_hurst_factory.ConfidenceEstimator[source]

Statistical confidence estimation for Hurst exponents

static bootstrap_confidence(estimator, data, n_bootstrap=100, confidence_level=0.95, random_state=None)[source]
Return type:

Tuple[float, Tuple[float, float], ndarray]

static theoretical_confidence(hurst_estimate, standard_error, n_samples, confidence_level=0.95)[source]
Return type:

Tuple[float, float]

class neurological_lrd_analysis.biomedical_hurst_factory.BayesianHurstEstimator(estimator_type=EstimatorType.DFA)[source]

Bayesian inference for Hurst exponent estimation using NumPyro

__init__(estimator_type=EstimatorType.DFA)[source]
dfa_model(data, min_window=10, max_window=None)[source]

Bayesian model for DFA-based Hurst estimation

Model: log(F(n)) = log(C) + H * log(n) + ε where ε ~ Normal(0, σ²)

periodogram_model(data, low_freq_fraction=0.4)[source]

Bayesian model for periodogram-based Hurst estimation

Model: log(S(f)) = log(C) - (2H-1) * log(f) + ε

infer_hurst(data, num_samples=1000, num_warmup=500, num_chains=4, random_seed=42)[source]

Perform Bayesian inference for Hurst exponent

Return type:

Dict[str, Any]

Parameters:

datanp.ndarray

Time series data

num_samplesint

Number of MCMC samples

num_warmupint

Number of warmup samples

num_chainsint

Number of MCMC chains

random_seedint

Random seed for reproducibility

Returns:

: Dict containing posterior samples and statistics

static bayesian_confidence(estimator, data, estimator_type=EstimatorType.DFA, num_samples=1000, num_warmup=500, random_seed=None)[source]

Static method for Bayesian confidence estimation

Return type:

Tuple[float, Tuple[float, float], Dict[str, Any]]

Parameters:

estimatorBaseHurstEstimator

Estimator instance (not used in Bayesian approach, but kept for interface consistency)

datanp.ndarray

Time series data

estimator_typeEstimatorType

Type of estimator to use for Bayesian model

num_samplesint

Number of MCMC samples

num_warmupint

Number of warmup samples

random_seedint

Random seed

Returns:

: Tuple of (mean_estimate, credible_interval, inference_results)

neurological_lrd_analysis.biomedical_hurst_factory.estimate_hurst(data, method='dfa', **kwargs)[source]

Convenience function for quick Hurst estimation

Return type:

HurstResult

neurological_lrd_analysis.biomedical_hurst_factory.compare_methods(data, methods=None, **kwargs)[source]

Convenience function for method comparison

Return type:

GroupHurstResult

Data Structures

TimeSeriesSample

class neurological_lrd_analysis.benchmark_core.generation.TimeSeriesSample(data, true_hurst, length, contamination, seed=None)[source]

Bases: object

Container for a generated time series sample.

data: ndarray
true_hurst: float | None
length: int
contamination: str
seed: int | None = None
__init__(data, true_hurst, length, contamination, seed=None)

BenchmarkConfig

class neurological_lrd_analysis.benchmark_core.runner.BenchmarkConfig(output_dir, true_hurst=None, n_bootstrap=100, confidence_level=0.95, random_state=None, estimators=None, save_results=True, verbose=False, use_bayesian=False, num_samples=1000, num_warmup=500, scoring_weights=None)[source]

Bases: object

Configuration for benchmark runs.

output_dir: str
true_hurst: float | None = None
n_bootstrap: int = 100
confidence_level: float = 0.95
random_state: int | None = None
estimators: List[str] | None = None
save_results: bool = True
verbose: bool = False
use_bayesian: bool = False
num_samples: int = 1000
num_warmup: int = 500
scoring_weights: ScoringWeights | None = None
__post_init__()[source]

Initialize default scoring weights if not provided.

__init__(output_dir, true_hurst=None, n_bootstrap=100, confidence_level=0.95, random_state=None, estimators=None, save_results=True, verbose=False, use_bayesian=False, num_samples=1000, num_warmup=500, scoring_weights=None)

BenchmarkResult

class neurological_lrd_analysis.benchmark_core.runner.BenchmarkResult(estimator, hurst_estimate, true_hurst=None, computation_time=0.0, convergence_flag=True, additional_metrics=<factory>, error_message=None, contamination=None, length=None, bias=None, absolute_error=None, relative_error=None, confidence_interval=None, p_value=None, standard_error=None)[source]

Bases: object

Result from a single estimator run.

estimator: str
hurst_estimate: float
true_hurst: float | None = None
computation_time: float = 0.0
convergence_flag: bool = True
additional_metrics: Dict[str, Any]
error_message: str | None = None
contamination: str | None = None
length: int | None = None
bias: float | None = None
absolute_error: float | None = None
relative_error: float | None = None
confidence_interval: tuple | None = None
p_value: float | None = None
standard_error: float | None = None
to_dict()[source]

Convert result to dictionary.

Return type:

Dict[str, Any]

__init__(estimator, hurst_estimate, true_hurst=None, computation_time=0.0, convergence_flag=True, additional_metrics=<factory>, error_message=None, contamination=None, length=None, bias=None, absolute_error=None, relative_error=None, confidence_interval=None, p_value=None, standard_error=None)

ScoringWeights

class neurological_lrd_analysis.benchmark_core.runner.ScoringWeights(success_rate=0.3, accuracy=0.3, speed=0.2, robustness=0.2)[source]

Bases: object

Weights for different performance metrics in the scoring function.

success_rate: float = 0.3
accuracy: float = 0.3
speed: float = 0.2
robustness: float = 0.2
__post_init__()[source]

Ensure weights sum to 1.0.

__init__(success_rate=0.3, accuracy=0.3, speed=0.2, robustness=0.2)

BaseEstimator

class neurological_lrd_analysis.benchmark_registry.registry.BaseEstimator(name)[source]

Bases: ABC

Base class for all Hurst exponent estimators.

__init__(name)[source]
abstractmethod estimate(data, **kwargs)[source]

Estimate Hurst exponent from data.

Return type:

EstimatorResult

EstimatorResult

class neurological_lrd_analysis.benchmark_registry.registry.EstimatorResult(hurst_estimate, convergence_flag, computation_time, additional_metrics, error_message=None)[source]

Bases: object

Result from an estimator run.

hurst_estimate: float
convergence_flag: bool
computation_time: float
additional_metrics: Dict[str, Any]
error_message: str | None = None
to_dict()[source]

Convert result to dictionary.

Return type:

Dict[str, Any]

__init__(hurst_estimate, convergence_flag, computation_time, additional_metrics, error_message=None)

Constants

BIOMEDICAL_SCENARIOS

neurological_lrd_analysis.benchmark_core.biomedical_scenarios.BIOMEDICAL_SCENARIOS

Dictionary containing predefined biomedical scenarios with their configurations.

Available scenarios:

  • eeg_rest: Resting state EEG

  • eeg_eyes_closed: Eyes closed EEG

  • eeg_sleep: Sleep state EEG

  • eeg_parkinsonian: Parkinson’s disease EEG

  • eeg_epileptic: Epileptic EEG

  • ecg_normal: Normal heart rate ECG

  • ecg_tachycardia: Tachycardia ECG

  • respiratory_rest: Resting respiratory signal

Each scenario includes:

  • scenario_type: Type of biomedical signal

  • hurst_range: Expected Hurst exponent range

  • typical_amplitude: Typical signal amplitude

  • noise_level: Typical noise level

  • auto_contamination: Automatic contamination type (if applicable)