Skip to content

API Reference

Taiyou edited this page Jan 27, 2026 · 2 revisions

API Reference

RecurrenceAnalyzer

Core class for Recurrence Quantification Analysis.

from src import RecurrenceAnalyzer

Constructor

RecurrenceAnalyzer(
    embedding_dim=1,        # Embedding dimension (m)
    time_delay=1,           # Time delay (tau)
    threshold=None,         # Fixed recurrence threshold (epsilon)
    threshold_ratio=0.1,    # Fraction of max distance (used if threshold=None)
    metric='euclidean',     # Distance metric: 'euclidean', 'chebyshev', 'cityblock'
    min_diag_length=2,      # Minimum diagonal line length for DET
    min_vert_length=2,      # Minimum vertical line length for LAM
    theiler_window=1,       # Theiler window width
    rr_exclude_theiler=True # Whether to exclude Theiler window from RR denominator
)

Methods

embed(x) -> np.ndarray

Perform Takens' time-delay embedding.

  • x: 1D time series (n_samples,)
  • Returns: Embedded array (n_vectors, embedding_dim)
analyzer = RecurrenceAnalyzer(embedding_dim=3, time_delay=5)
embedded = analyzer.embed(signal)  # shape: (n - 10, 3)

compute_distance_matrix(x) -> np.ndarray

Compute pairwise distance matrix in reconstructed phase space.

  • x: 1D time series or pre-embedded 2D array
  • Returns: Symmetric distance matrix
  • Side effect: Sets distance_matrix_ and embedded_series_

compute_recurrence_matrix(x, threshold=None) -> np.ndarray

Compute binary recurrence matrix R(i,j) = 1 if d(i,j) <= epsilon.

  • x: 1D time series
  • threshold: Override threshold (optional)
  • Returns: Binary matrix (0/1), dtype int8
  • Side effect: Sets recurrence_matrix_

compute_rqa_measures(x, threshold=None) -> dict

Compute all 9 standard RQA measures.

  • x: 1D time series
  • threshold: Override threshold (optional)
  • Returns: Dictionary with keys RR, DET, L, Lmax, ENTR, LAM, TT, Vmax, TND
measures = analyzer.compute_rqa_measures(signal, threshold=0.5)
print(f"Determinism: {measures['DET']:.4f}")

auto_threshold(x, target_rr=0.05, tol=0.005, max_iter=50) -> float

Automatically select threshold via bisection to achieve target recurrence rate.

  • x: 1D time series
  • target_rr: Target recurrence rate (default: 5%)
  • tol: Convergence tolerance
  • Returns: Optimal threshold value
eps = analyzer.auto_threshold(signal, target_rr=0.05)
measures = analyzer.compute_rqa_measures(signal, threshold=eps)

estimate_embedding_parameters(x, max_dim=10, max_delay=50) -> (int, int)

Estimate optimal embedding dimension and time delay.

Uses Auto-Mutual Information (AMI) first minimum for delay and False Nearest Neighbours (FNN) for dimension.

  • x: 1D time series
  • Returns: (optimal_dim, optimal_delay)
dim, delay = analyzer.estimate_embedding_parameters(signal)
analyzer = RecurrenceAnalyzer(embedding_dim=dim, time_delay=delay)

fit(X) -> self / transform(X) -> np.ndarray / fit_transform(X) -> np.ndarray

scikit-learn compatible interface. transform returns a 1D array of 9 RQA measures.

from sklearn.pipeline import Pipeline

pipe = Pipeline([
    ('rqa', RecurrenceAnalyzer(embedding_dim=3, time_delay=10, threshold=0.5)),
])
features = pipe.fit_transform(signal)  # array of 9 values

Attributes (after fitting)

Attribute Type Description
recurrence_matrix_ np.ndarray Binary recurrence matrix
distance_matrix_ np.ndarray Pairwise distance matrix
embedded_series_ np.ndarray Phase-space embedded time series

CrossRecurrenceAnalyzer

Cross-Recurrence Quantification Analysis for two coupled time series.

from src import CrossRecurrenceAnalyzer

Constructor

CrossRecurrenceAnalyzer(
    embedding_dim=1,
    time_delay=1,
    threshold=None,
    threshold_ratio=0.1,
    metric='euclidean',
    min_diag_length=2,
    min_vert_length=2,
    normalize=True          # Z-score normalize both series before analysis
)

Methods

compute_cross_recurrence_matrix(x, y, threshold=None) -> np.ndarray

Compute cross-recurrence matrix between two time series.

  • x, y: 1D time series (can differ in length)
  • Returns: Binary cross-recurrence matrix (n_x, n_y)
  • Side effect: Sets cross_recurrence_matrix_, cross_distance_matrix_

compute_crqa_measures(x, y, threshold=None) -> dict

Compute 8 CRQA measures.

  • Returns: Dictionary with keys RR, DET, L, Lmax, ENTR, LAM, TT, Vmax
crqa = CrossRecurrenceAnalyzer(embedding_dim=3, time_delay=10, threshold=0.5)
measures = crqa.compute_crqa_measures(left_leg, right_leg)

compute_diagonal_profile(x, y, threshold=None) -> np.ndarray

Compute diagonal-wise recurrence rate profile. The peak location indicates the time lag between the two systems.

  • Returns: Array of recurrence rates for each diagonal offset
profile = crqa.compute_diagonal_profile(x, y)
lag = np.argmax(profile) - len(profile) // 2
print(f"Coupling lag: {lag} samples")

transform(X) -> np.ndarray

Transform paired time series (2D array with 2 columns) to CRQA feature vector (8 values).

Attributes (after fitting)

Attribute Type Description
cross_recurrence_matrix_ np.ndarray Binary cross-recurrence matrix
cross_distance_matrix_ np.ndarray Cross-distance matrix

RecurrencePlotter

Visualization tools for recurrence analysis.

from src import RecurrencePlotter

Constructor

RecurrencePlotter(figsize=(8, 8), dpi=100)

Methods

plot_recurrence(recurrence_matrix, title, ax, cmap, show_colorbar) -> Figure

Standard recurrence plot. Binary matrix rendered as black/white image.

plot_cross_recurrence(cross_recurrence_matrix, title, ax, cmap, xlabel, ylabel) -> Figure

Cross-recurrence plot for two time series.

plot_distance_matrix(distance_matrix, title, ax, cmap) -> Figure

Distance matrix as a colored heatmap.

plot_rqa_summary(rqa_measures, title, ax, color) -> Figure

Bar chart of RQA measures with value labels.

plot_rqa_comparison(measures_list, labels, title, ax) -> Figure

Grouped bar chart comparing RQA measures across multiple signals.

plotter = RecurrencePlotter()
fig = plotter.plot_rqa_comparison(
    [measures_periodic, measures_chaotic],
    labels=["Periodic", "Chaotic"],
)

plot_diagonal_histogram(recurrence_matrix, min_length, title, ax) -> Figure

Histogram of diagonal line length distribution.

plot_recurrence_with_timeseries(time_series, recurrence_matrix, title) -> Figure

Combined plot: recurrence matrix with time series shown along both axes.


GaitAnalysisPipeline

Unified pipeline integrating all internal features with optional external libraries.

from src import GaitAnalysisPipeline

Constructor

GaitAnalysisPipeline(
    embedding_dim=3,       # Embedding dimension for RQA/ACI
    time_delay=10,         # Time delay for embedding
    rqa_threshold=None,    # Fixed RQA threshold (None = auto-select)
    target_rr=0.05,        # Target recurrence rate for auto threshold
    theiler_window=1,      # Theiler window for RQA
    sampen_order=2,        # Embedding dimension for Sample Entropy
    sampen_r=None,         # Tolerance for SampEn (None = 0.2*std)
    permen_order=3,        # Order for Permutation Entropy
    dfa_order=1,           # Polynomial order for DFA
    poincare_lag=1,        # Lag for Poincare plot
)

Methods

analyze(x) -> dict

Full gait dynamics analysis. Returns nested dictionary with groups: variability, poincare, rqa, aci, entropy, fractal, metadata.

Internal features (always available): Stride Variability (7), Poincare (5), RQA (9), ACI (3).

External features (when libraries installed): Entropy measures from nolds/antropy/neurokit2, Fractal measures from nolds/antropy.

analyze_bilateral(left, right, threshold=None) -> dict

Bilateral analysis with CRQA coupling. Returns left, right, crqa, coupling_lag.

to_flat_dict() -> dict

Flatten to {'VAR_mean': 1.1, 'PC_SD1': 0.023, 'RQA_DET': 0.95, ...}.

to_feature_vector() -> np.ndarray

1D feature vector (up to 30 elements).

get_feature_names() -> list

Ordered feature names matching to_feature_vector().

summary() -> str

Human-readable analysis report.

fit(X) / transform(X) / fit_transform(X)

scikit-learn compatible interface.

Feature Vector Layout

Prefix Group Count Source
VAR_ Variability 7 StrideVariability
PC_ Poincare 5 PoincareAnalyzer
RQA_ Recurrence 9 RecurrenceAnalyzer
ACI_ Complexity 3 AttractorComplexityIndex
ENT_ Entropy 1-5 nolds / antropy / neurokit2
FRC_ Fractal 2-6 nolds / antropy

Clone this wiki locally