Feature Extractors
pybasin.feature_extractors.feature_extractor.FeatureExtractor
Bases: ABC
Abstract base class for extracting features from ODE solutions.
Feature extractors transform ODE solution trajectories into feature vectors that can be used for basin of attraction classification. This class provides utilities for filtering solutions by time (to remove transients).
class AmplitudeExtractor(FeatureExtractor):
def extract_features(self, solution: Solution) -> torch.Tensor:
y_filtered = self.filter_time(solution)
return torch.max(torch.abs(y_filtered), dim=0)[0]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_steady
|
float | None
|
Time threshold for filtering transients. Only data after this time will be used for feature extraction. If |
None
|
Attributes
feature_names
property
Return the list of feature names.
If not explicitly set by a subclass, automatically generates names using
the pattern:
Returns:
| Type | Description |
|---|---|
list[str]
|
List of feature names. Length must match the number of features (F) in the output tensor from extract_features(). |
Functions
extract_features
abstractmethod
Extract features from an ODE solution.
This method must be implemented by subclasses to define how features are computed from solution trajectories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solution
|
Solution
|
ODE solution containing time series data for one or more trajectories. The solution.y tensor has shape (N, B, S) where N is the number of time steps, B is the batch size (number of initial conditions), and S is the number of state variables. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Feature tensor of shape (B, F) where B is the batch size and F is the number of features extracted per trajectory. |
filter_time
Filter out transient behavior by removing early time steps.
Removes time steps before time_steady to exclude transient dynamics
from feature extraction. This ensures features are computed only from
steady-state or long-term behavior.
If time_steady is None, defaults to 85% of the integration
time span (i.e. keeps the last 15% of time points).
extractor = FeatureExtractor(time_steady=9.0) # if time_span=(0, 10)
filtered = extractor.filter_time(solution)
# Only time points t >= 9.0 are included
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solution
|
Solution
|
ODE solution with time tensor of shape (N,) and y tensor of shape (N, B, S) where N is time steps, B is batch size, and S is number of state variables. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Filtered tensor of shape (N', B, S) where N' is the number of time steps after time_steady. If time_steady is 0 or less than all time points, returns the original solution.y unchanged. |
pybasin.ts_torch.torch_feature_extractor.TorchFeatureExtractor
Bases: FeatureExtractor
PyTorch-based feature extractor for time series features.
Supports per-state variable feature configuration using tsfresh-style FCParameters dictionaries, allowing different feature sets for different state variables.
For CPU extraction, uses multiprocessing to parallelize across batches. For GPU extraction, uses batched CUDA operations for optimal performance.
# Default: use comprehensive features for all states on CPU
extractor = TorchFeatureExtractor(time_steady=9.0)
# GPU extraction with default features
extractor = TorchFeatureExtractor(time_steady=9.0, device="gpu")
# Custom features for specific states, skip others
extractor = TorchFeatureExtractor(
time_steady=9.0,
features=None, # Don't extract features by default
features_per_state={
1: {"maximum": None, "minimum": None}, # Only extract for state 1
},
)
# Global features with per-state override
extractor = TorchFeatureExtractor(
time_steady=9.0,
features_per_state={
0: {"maximum": None}, # Override state 0
1: None, # Skip state 1
},
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_steady
|
float | None
|
Time threshold for filtering transients. If |
None
|
features
|
Literal['comprehensive', 'minimal'] | FCParameters | None
|
Default feature configuration to apply to all states. Can be: - 'comprehensive': Use TORCH_COMPREHENSIVE_FC_PARAMETERS (default) - 'minimal': Use TORCH_MINIMAL_FC_PARAMETERS (10 basic features) - FCParameters dict: Custom feature configuration - None: Skip states not explicitly configured in features_per_state |
'comprehensive'
|
features_per_state
|
dict[int, FCParameters | None] | None
|
Optional dict mapping state indices to FCParameters. Overrides |
None
|
normalize
|
bool
|
Whether to apply z-score normalization. Default True. |
True
|
device
|
Literal['cpu', 'gpu']
|
Execution device ('cpu' or 'gpu'). Default 'cpu'. |
'cpu'
|
n_jobs
|
int | None
|
Number of worker processes for CPU extraction. If None, uses all available CPU cores. Ignored when device='gpu'. |
None
|
impute_method
|
Literal['extreme', 'tsfresh']
|
Method for handling NaN/inf values in features: - 'extreme': Replace with extreme values (1e10) to distinguish unbounded trajectories. Best for systems with divergent solutions. (default) - 'tsfresh': Replace using tsfresh-style imputation (inf->max/min, NaN->median). Better when all trajectories are bounded. |
'extreme'
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If device='gpu' but CUDA is not available. |
Attributes
feature_names
property
Return the list of feature names in the format 'state_X__feature_name'.
Functions
extract_features
Extract features from an ODE solution using PyTorch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solution
|
Solution
|
ODE solution containing time series data with y tensor of shape (N, B, S) where N=timesteps, B=batch size, S=state variables. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Feature tensor of shape (B, F) where F is the total number of features. |
pybasin.feature_extractors.jax.jax_feature_extractor.JaxFeatureExtractor
Bases: FeatureExtractor
JAX-based feature extractor for time series features.
Supports per-state variable feature configuration using tsfresh-style FCParameters dictionaries, allowing different feature sets for different state variables.
Warning: Using JAX_COMPREHENSIVE_FC_PARAMETERS may cause very long JIT compile times (~40 minutes). Use JAX_MINIMAL_FC_PARAMETERS or a custom subset for faster compilation.
# Default: use minimal features for all states
extractor = JaxFeatureExtractor(time_steady=9.0)
# Custom features for specific states, skip others
extractor = JaxFeatureExtractor(
time_steady=9.0,
features=None, # Don't extract features by default
features_per_state={
1: {"log_delta": None}, # Only extract for state 1
},
)
# Global features with per-state override
extractor = JaxFeatureExtractor(
time_steady=9.0,
features_per_state={
0: {"maximum": None}, # Override state 0
1: None, # Skip state 1
},
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_steady
|
float | None
|
Time threshold for filtering transients. If |
None
|
features
|
FCParameters | None
|
Default FCParameters configuration to apply to all states. Defaults to JAX_MINIMAL_FC_PARAMETERS. Set to None to skip states not explicitly configured in features_per_state. |
JAX_MINIMAL_FC_PARAMETERS
|
features_per_state
|
dict[int, FCParameters | None] | None
|
Optional dict mapping state indices to FCParameters. Overrides |
None
|
normalize
|
bool
|
Whether to apply z-score normalization. Default True. |
True
|
use_jit
|
bool
|
Whether to JIT-compile extraction. Default True. |
True
|
device
|
str | None
|
JAX device to use ('cpu', 'gpu', 'cuda', 'cuda:N', or None for auto). |
None
|
impute_method
|
Literal['extreme', 'tsfresh']
|
Method for handling NaN/inf values in features. Options: - 'extreme': Replace with extreme values (1e10) to distinguish unbounded trajectories. Best for systems with divergent solutions. (default) - 'tsfresh': Replace using tsfresh-style imputation (inf->max/min, NaN->median). Better when all trajectories are bounded. |
'extreme'
|
Attributes
feature_names
property
Return the list of feature names in the format 'state_X__feature_name'.
Functions
extract_features
Extract features from an ODE solution using JAX.
pybasin.feature_extractors.tsfresh_feature_extractor.TsfreshFeatureExtractor
Bases: FeatureExtractor
Feature extractor using tsfresh for comprehensive time series analysis.
This extractor uses the tsfresh library to automatically extract a large number of time series features from ODE solutions. It converts PyTorch/JAX tensors to pandas DataFrames for tsfresh processing, then converts the results back to tensors.
Supports per-state variable feature configuration using tsfresh's kind_to_fc_parameters mechanism, allowing you to apply different feature sets to different state variables based on domain knowledge.
Internally, the solution tensor is converted to tsfresh's wide/flat DataFrame
format where each state variable becomes a column (state_0, state_1, etc.).
The kind_to_fc_parameters accepts integer state indices and maps them to these
column names automatically.
# Same minimal features for all states
extractor = TsfreshFeatureExtractor(
time_steady=9.0, default_fc_parameters=MinimalFCParameters(), n_jobs=-1, normalize=True
)
# Specific features for all states
extractor = TsfreshFeatureExtractor(
time_steady=950.0,
default_fc_parameters={"mean": None, "std": None, "maximum": None},
n_jobs=-1,
)
# Different features per state (e.g., pendulum: position vs velocity)
from tsfresh.feature_extraction import MinimalFCParameters, ComprehensiveFCParameters
extractor = TsfreshFeatureExtractor(
time_steady=950.0,
kind_to_fc_parameters={
0: {"mean": None, "maximum": None, "minimum": None},
1: ComprehensiveFCParameters(),
},
n_jobs=1, # Use n_jobs=1 for deterministic results
)
Note on parallelism: Setting n_jobs > 1 enables parallel feature extraction but introduces non-determinism due to floating-point arithmetic order. This can cause inconsistent classification results. Use n_jobs=1 for reproducible results.
Note on normalization: When normalize=True, the scaler is fitted on the FIRST dataset that calls extract_features(). For best results with supervised classifiers: - Either set normalize=False (recommended for KNN with few templates) - Or call fit_scaler() explicitly with representative data before extraction
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_steady
|
float | None
|
Time threshold for filtering transients. If |
None
|
default_fc_parameters
|
dict[str, Any] | Any | None
|
Default feature extraction parameters for all states. Can be one of: - MinimalFCParameters() - Fast extraction with ~20 features - ComprehensiveFCParameters() - Full extraction with ~800 features - Custom dict like {"mean": None, "maximum": None} for specific features - None - must provide kind_to_fc_parameters Default is MinimalFCParameters(). |
None
|
kind_to_fc_parameters
|
dict[int, dict[str, Any] | Any] | None
|
Optional dict mapping state indices (e.g. |
None
|
n_jobs
|
int
|
Number of parallel jobs for feature extraction. Default is 1. Set to -1 to use all available cores. |
1
|
normalize
|
bool
|
Whether to apply StandardScaler normalization to features. Highly recommended for distance-based classifiers like KNN. Default is True. |
True
|
Attributes
feature_names
property
Return the list of feature names.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of feature names from tsfresh extraction. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If extract_features has not been called yet. |
Functions
reset_scaler
Reset the scaler to unfitted state.
Call this if you need to refit the scaler on different data.
extract_features
Extract features from an ODE solution using tsfresh.
Converts the solution tensor to pandas DataFrame format expected by tsfresh, extracts features for each trajectory and state variable, then converts back to PyTorch tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solution
|
Solution
|
ODE solution with y tensor of shape (N, B, S) where N is time steps, B is batch size, and S is number of state variables. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Feature tensor of shape (B, F) where B is the batch size and F is the total number of features extracted by tsfresh across all state variables. |
pybasin.feature_extractors.nolds_feature_extractor.NoldsFeatureExtractor
Bases: FeatureExtractor
Feature extractor using nolds for nonlinear dynamics analysis.
Computes nonlinear dynamics features for each trajectory with multiprocessing parallelization. Uses tsfresh-style FCParameters configuration for specifying which features to extract and with what parameters.
Available features (passed directly to nolds):
* lyap_r: Largest Lyapunov exponent (Rosenstein's algorithm)
* lyap_e: Largest Lyapunov exponent (Eckmann's algorithm)
* sampen: Sample entropy
* hurst_rs: Hurst exponent (R/S analysis)
* corr_dim: Correlation dimension
* dfa: Detrended fluctuation analysis
* mfhurst_b: Multifractal Hurst exponent (basic method)
* mfhurst_dm: Multifractal Hurst exponent (DM method)
# Default: extract lyap_r and corr_dim from all states
extractor = NoldsFeatureExtractor(time_steady=9.0)
# Only extract Lyapunov exponents with custom parameters
extractor = NoldsFeatureExtractor(
time_steady=9.0,
features={"lyap_r": [{"emb_dim": 15}]},
)
# Per-state configuration
extractor = NoldsFeatureExtractor(
time_steady=9.0,
features=None,
features_per_state={
0: {"lyap_r": None},
1: {"corr_dim": [{"emb_dim": 10}]},
},
)
# Multiple parameter sets for same feature
extractor = NoldsFeatureExtractor(
time_steady=9.0,
features={
"lyap_r": [
{"emb_dim": 5},
{"emb_dim": 10},
],
},
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_steady
|
float
|
Time threshold for filtering transients. Default 0.0. |
0.0
|
features
|
NoldsFCParameters | None
|
Feature configuration for all states. Can be: * NoldsFCParameters dict: Feature names mapped to parameter lists * None: Skip states not in features_per_state Default extracts both lyap_r and corr_dim with nolds defaults. |
None
|
features_per_state
|
dict[int, NoldsFCParameters | None] | None
|
Optional dict mapping state indices to FCParameters. Overrides |
None
|
n_jobs
|
int | None
|
Number of worker processes. If None, uses all CPU cores. |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If nolds library is not installed. |
Attributes
feature_names
property
Return the list of feature names in format 'state_X__feature__params'.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If extract_features has not been called yet. |
Functions
extract_features
Extract nolds features from an ODE solution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solution
|
Solution
|
ODE solution with shape (N, B, S). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Features tensor of shape (B, F) where F depends on configuration. |