Functions
IntrinsicTimescales.IntrinsicTimescales
— ModuleIntrinsicTimescales
A Julia package for estimation of timescales from time series data.
Features
- Standard techniques for INT calculation
- Approximate Bayesian Computation (ABC) for parameter inference
- ADVI for variational inference
- Multiple model types:
- Single timescale
- Single timescale with oscillations
- Models supporting missing data
- Summary statistics using periodogram, Welch (from DSP.jl) and Lomb-Scargle (from LombScargle.jl):
- Autocorrelation function (ACF)
- Power spectral density (PSD)
Submodules
Models
: Abstract model types and interfacesABC
: Approximate Bayesian Computation algorithmsTuringBackend
: Turing.jl integration for ADVISummaryStats
: ACF and PSD implementationsDistances
: Distance metrics for ABCUtils
: Utility functions for analysisOrnsteinUhlenbeck
: OU process generation using DifferentialEquations.jlOneTimescale
: Single timescale modelOneTimescaleAndOsc
: Single timescale with oscillationsOneTimescaleWithMissing
: Single timescale with missing dataOneTimescaleAndOscWithMissing
: Single timescale and oscillations with missing dataPlotting
: Plotting functions for results
IntrinsicTimescales.Models.AbstractTimescaleModel
— TypeAbstractTimescaleModel
Abstract type representing models for timescale inference. All concrete model implementations should subtype this.
IntrinsicTimescales.Models.BaseModel
— TypeBaseModel <: AbstractTimescaleModel
Base model structure for timescale inference using various methods.
Fields
data
: Input time series datatime
: Time points corresponding to the datadata_sum_stats
: Pre-computed summary statistics of the datafitmethod::Symbol
: Fitting method to use. Options::abc
,:advi
,:acw
summary_method::Symbol
: Summary statistic type. Options::psd
(power spectral density) or:acf
(autocorrelation)lags_freqs::AbstractVector{<:Real}
: Lags (for ACF) or frequencies (for PSD) at which to compute summary statisticsprior
: Prior distributions for parameters. Can be Vector{Distribution}, single Distribution, or "informed_prior"acwtypes::Union{Vector{Symbol}, Symbol}
: ACW analysis types (e.g., :ACW50, :ACW0, :ACWe, :tau, :knee)distance_method::Symbol
: Distance metric type. Options::linear
or:logarithmic
dt::Real
: Time step between observationsT::Real
: Total time span of the datanumTrials::Real
: Number of trials/iterationsdata_mean::Real
: Mean of the input datadata_sd::Real
: Standard deviation of the input data
IntrinsicTimescales.Models.check_acwtypes
— Methodcheck_acwtypes(acwtypes, possible_acwtypes)
Validate the ACW analysis types against allowed options.
Arguments
acwtypes
: Symbol or Vector of Symbols specifying ACW analysis typespossible_acwtypes
: Vector of allowed ACW analysis types
Returns
- Validated vector of ACW types
Throws
ErrorException
: If invalid ACW types are provided
IntrinsicTimescales.Models.check_inputs
— Methodcheck_inputs(fitmethod, summary_method)
Validate the fitting method and summary statistic choices.
Arguments
fitmethod
: Symbol specifying the fitting methodsummary_method
: Symbol specifying the summary statistic type
Throws
ArgumentError
: If invalid options are provided
IntrinsicTimescales.Models.check_model_inputs
— Functioncheck_model_inputs(data, time, fit_method, summary_method, prior, acwtypes, distance_method)
Validate inputs for timescale model construction.
Arguments
data
: Input time series datatime
: Time points corresponding to the datafit_method
: Fitting method (:abc, :advi)summary_method
: Summary statistic type (:psd or :acf)prior
: Prior distribution(s) for parametersacwtypes
: Types of ACW analysisdistance_method
: Distance metric type (:linear or :logarithmic)
Throws
ArgumentError
: If any inputs are invalid or incompatible
IntrinsicTimescales.Models.distance_function
— Functiondistance_function(model::AbstractTimescaleModel, summary_stats, summary_stats_synth)
Compute distance between two sets of summary statistics.
Arguments
model
: Model instancesummary_stats
: First set of summary statisticssummary_stats_synth
: Second set of summary statistics (typically from synthetic data)
Returns
- Distance value according to model.distance_method
IntrinsicTimescales.Models.draw_theta
— Functiondraw_theta(model::AbstractTimescaleModel)
Draw parameter values from the model's prior distributions.
Returns
- Array of proposed model parameters sampled from their respective priors
IntrinsicTimescales.Models.generate_data
— Functiongenerate_data(model::AbstractTimescaleModel, theta)
Generate synthetic data using the forward model with given parameters.
Arguments
model
: Model instancetheta
: Array of model parameters
Returns
- Synthetic dataset with same structure as the original data
IntrinsicTimescales.Models.generate_data_and_reduce
— Methodgenerate_data_and_reduce(model::AbstractTimescaleModel, theta)
Combined function to generate synthetic data and compute distance from observed data. This is a convenience function commonly used in ABC algorithms.
Arguments
model
: Model instancetheta
: Array of model parameters
Returns
- Distance value between synthetic and observed summary statistics
IntrinsicTimescales.Models.int_fit
— Functionfit(model::AbstractTimescaleModel, param_dict=nothing)
Fit the timescale model using the specified fitting method.
Arguments
model
: The timescale model instance to fitparam_dict
: Optional dictionary of fitting parameters. If not provided, default parameters will be used.
Returns
For ADVI fitting method:
samples
: Array of posterior samplesmap_estimate
: Maximum a posteriori estimate of parametersvi_result
: Full variational inference result object
For ABC fitting method:
samples
: Array of accepted parameter samplesweights
: Importance weights for the samplesdistances
: Distances between simulated and observed summary statistics
IntrinsicTimescales.Models.summary_stats
— Functionsummary_stats(model::AbstractTimescaleModel, data)
Compute summary statistics (PSD or ACF) from the data.
Arguments
model
: Model instancedata
: Input data (original or synthetic)
Returns
- Array of summary statistics computed according to model.summary_method
IntrinsicTimescales.ABC.ABCResults
— TypeABCResults
Container for ABC results to standardize plotting interface.
Fields
theta_history::Vector{Matrix{Float64}}
: History of parameter values across iterationsepsilon_history::Vector{Float64}
: History of epsilon valuesacc_rate_history::Vector{Float64}
: History of acceptance ratesweights_history::Vector{Vector{Float64}}
: History of weightsfinal_theta::Matrix{Float64}
: Final accepted parameter valuesfinal_weights::Vector{Float64}
: Final weightsMAP::Vector{Float64}
: Maximum A Posteriori (MAP) estimate of parameters
IntrinsicTimescales.ABC.abc_results
— Methodabc_results(output_record::Vector{NamedTuple})
Construct an ABCResults
struct from PMC-ABC output records.
Arguments
output_record::Vector{NamedTuple}
: Vector of named tuples containing PMC-ABC iteration results. Each tuple must contain:theta_accepted
: Accepted parameter valuesepsilon
: Epsilon threshold valuen_accepted
: Number of accepted samplesn_total
: Total number of samplesweights
: Importance weights
Returns
ABCResults
: Struct to contain ABC results. See the documentation forABCResults
for more details.
IntrinsicTimescales.ABC.basic_abc
— Methodbasic_abc(model::Models.AbstractTimescaleModel; kwargs...)
Perform basic ABC rejection sampling. The algorithm stops either when max_iter
is reached or when min_accepted
samples have been accepted.
Arguments
model::Models.AbstractTimescaleModel
: Model to perform inference onepsilon::Float64
: Acceptance threshold for distance between simulated and observed datamax_iter::Integer
: Maximum number of iterations to performmin_accepted::Integer
: Minimum number of accepted samples required before stoppingpmc_mode::Bool=false
: Whether to use PMC proposal distribution instead of priorweights::Array{Float64}
: Importance weights for PMC sampling (only used if pmc_mode=true)theta_prev::Array{Float64}
: Previous parameters for PMC sampling (only used if pmc_mode=true)tau_squared::Array{Float64}
: Covariance matrix for PMC sampling (only used if pmc_mode=true)show_progress::Bool=true
: Whether to show progress bar with acceptance count and speed
Returns
NamedTuple containing:
samples::Matrix{Float64}
: Matrix (maxiter × nparams) of all proposed parametersisaccepted::Vector{Bool}
: Boolean mask of accepted samples for firstn_total
iterationstheta_accepted::Matrix{Float64}
: Matrix (naccepted × nparams) of accepted parametersdistances::Vector{Float64}
: Vector of distances for firstn_total
iterationsn_accepted::Int
: Number of accepted samplesn_total::Int
: Total number of iterations performedepsilon::Float64
: Acceptance threshold usedweights::Vector{Float64}
: Uniform weights (ones) for accepted samplestau_squared::Matrix{Float64}
: Zero matrix (nparams × nparams) for basic ABCeff_sample::Int
: Effective sample size (equals n_accepted in basic ABC)
Implementation Details
- Draws parameters either from prior (basic mode) or PMC proposal (pmc_mode)
- Generates synthetic data and computes distance to observed data
- Accepts parameters if distance ≤ epsilon
- Stops when either maxiter reached or minaccepted samples accepted
- Returns uniform weights and zero covariance matrix in basic mode
IntrinsicTimescales.ABC.calc_weights
— Methodcalc_weights(theta_prev, theta, tau_squared, weights, prior)
Calculate importance weights for PMC-ABC algorithm.
Arguments
theta_prev::Union{Vector{Float64}, Matrix{Float64}}
: Previously accepted parameters. For multiple parameters, each row is a sample and each column is a parametertheta::Union{Vector{Float64}, Matrix{Float64}}
: Current parameters in same format as theta_prevtau_squared::Matrix{Float64}
: Covariance matrix for the proposal distributionweights::Vector{Float64}
: Previous iteration's importance weightsprior::Union{Vector, dist.Distribution}
: Prior distribution(s). Can be single distribution or vector of distributions
Returns
Vector{Float64}
: Normalized importance weights (sum to 1)
IntrinsicTimescales.ABC.compute_adaptive_alpha
— Methodcompute_adaptive_alpha(iteration::Integer, current_acc_rate::Float64, target_acc_rate::Float64; kwargs...)
Compute an adaptive step size (alpha) for epsilon adjustment in ABC, based on iteration progress and distance from target acceptance rate.
Arguments
Required Arguments
iteration::Integer
: Current iteration numbercurrent_acc_rate::Float64
: Current acceptance ratetarget_acc_rate::Float64
: Target acceptance rate to achieve
Optional Keyword Arguments
Bounds Parameters
alpha_max::Float64=0.9
: Maximum allowed alpha valuealpha_min::Float64=0.1
: Minimum allowed alpha valuetotal_iterations::Integer=100
: Total number of iterations planned
Adaptation Parameters
acc_rate_far::Float64=2.0
: Relative difference threshold for "far from target"acc_rate_close::Float64=0.2
: Relative difference threshold for "close to target"alpha_far_mult::Float64=1.5
: Multiplier for alpha when far from targetalpha_close_mult::Float64=0.5
: Multiplier for alpha when close to target
Returns
Float64
: Adaptive alpha value betweenalpha_min
andalpha_max
Implementation Details
Computes base alpha using linear decay between max and min:
base_alpha = alpha_max * (1 - progress) + alpha_min * progress
where
progress = iteration/total_iterations
Adjusts base alpha based on relative difference from target:
acc_rate_diff = |current_acc_rate - target_acc_rate|/target_acc_rate
Final alpha selection:
- If
acc_rate_diff > acc_rate_far
: More aggressive adaptationalpha = min(alpha_max, base_alpha * alpha_far_mult)
- If
acc_rate_diff < acc_rate_close
: More conservative adaptationalpha = max(alpha_min, base_alpha * alpha_close_mult)
- Otherwise: Use base alpha
alpha = base_alpha
- If
IntrinsicTimescales.ABC.draw_theta_pmc
— Methoddraw_theta_pmc(model, theta_prev, weights, tau_squared; jitter::Float64=1e-5)
Draw new parameter values using the PMC proposal distribution.
Arguments
model
: Model instancetheta_prev
: Previously accepted parametersweights
: Importance weights from previous iterationtau_squared
: Covariance matrix for proposal distributionjitter::Float64=1e-5
: Small value added to covariance diagonal for numerical stability
Returns
- Vector of proposed parameters
IntrinsicTimescales.ABC.effective_sample_size
— Methodeffective_sample_size(w::Vector{Float64})
Calculate effective sample size (ESS) from importance weights.
Arguments
w::Vector{Float64}
: Vector of importance sampling weights (need not be normalized)
Returns
Float64
: Effective sample size
Details
The effective sample size is always less than or equal to the actual number of samples. It reaches its maximum (equal to sample size) when all weights are equal, and approaches its minimum (1) when one weight dominates all others.
IntrinsicTimescales.ABC.find_MAP
— Functionfind_MAP(theta_accepted::AbstractArray{Float64}, N::Integer=10000)
Find Maximum A Posteriori (MAP) estimates with grid search.
Arguments
theta_accepted::AbstractArray{Float64}
: Matrix of accepted samples from the final step of ABCN::Integer=10000
: Number of random grid points to evaluate for each parameter
Returns
theta_map::Vector{Float64}
: MAP estimate of the parameters
IntrinsicTimescales.ABC.get_param_dict_abc
— Methodget_param_dict_abc()
Get default parameter dictionary for ABC algorithm.
Returns
Dictionary containing default values for all ABC parameters including:
Basic ABC Parameters
:epsilon_0 => 1.0
: Initial epsilon threshold:max_iter => 10000
: Maximum iterations per step:min_accepted => 100
: Minimum number of accepted samples:steps => 30
: Maximum PMC steps:sample_only => false
: If true, only perform sampling without adaptation
Acceptance Rate Parameters
:minAccRate => 0.01
: Minimum acceptance rate before early stopping:target_acc_rate => 0.01
: Target acceptance rate:target_epsilon => 1e-4
: Target epsilon for early stopping
Display Parameters
:show_progress => true
: Show progress bar:verbose => true
: Print detailed progress information
Numerical Stability Parameters
:jitter => 1e-6
: Small value added to covariance matrix
Epsilon Selection Parameters
:distance_max => 10.0
: Maximum valid distance:quantile_lower => 25.0
: Lower quantile for epsilon bounds:quantile_upper => 75.0
: Upper quantile for epsilon bounds:quantile_init => 50.0
: Initial quantile:acc_rate_buffer => 0.1
: Allowed deviation from target rate
Adaptive Alpha Parameters
:alpha_max => 0.9
: Maximum adaptation rate:alpha_min => 0.1
: Minimum adaptation rate:acc_rate_far => 2.0
: Threshold for "far from target":acc_rate_close => 0.2
: Threshold for "close to target":alpha_far_mult => 1.5
: Multiplier when far from target:alpha_close_mult => 0.5
: Multiplier when close to target
Early Stopping Parameters
:convergence_window => 5
: Steps to check for convergence:theta_rtol => 1e-2
: Relative tolerance for convergence:theta_atol => 1e-3
: Absolute tolerance for convergence
MAP Estimation Parameters
:N => 10000
: Number of grid points for MAP estimation
Example
params = get_param_dict_abc()
params[:epsilon_0] = 0.5 # Modify initial epsilon
params[:max_iter] = 5000 # Reduce maximum iterations
IntrinsicTimescales.ABC.pmc_abc
— Methodpmc_abc(model::Models.AbstractTimescaleModel; kwargs...)
Perform Population Monte Carlo Approximate Bayesian Computation (PMC-ABC) inference.
Arguments
Basic ABC parameters
model::Models.AbstractTimescaleModel
: Model to perform inference onepsilon_0::Real=1.0
: Initial epsilon threshold for acceptancemax_iter::Integer=10000
: Maximum number of iterations per stepmin_accepted::Integer=100
: Minimum number of accepted samples requiredsteps::Integer=10
: Maximum number of PMC steps to performsample_only::Bool=false
: If true, only perform sampling without adaptation
Acceptance rate parameters
minAccRate::Float64=0.01
: Minimum acceptance rate before early stoppingtarget_acc_rate::Float64=0.01
: Target acceptance rate for epsilon adaptationtarget_epsilon::Float64=5e-3
: Target epsilon value for early stopping
Display parameters
show_progress::Bool=true
: Whether to show progress barverbose::Bool=true
: Whether to print detailed progress information
Numerical stability parameters
jitter::Float64=1e-6
: Small value added to covariance matrix for stability
Epsilon selection parameters
distance_max::Float64=10.0
: Maximum distance to consider validquantile_lower::Float64=25.0
: Lower quantile for epsilon adjustmentquantile_upper::Float64=75.0
: Upper quantile for epsilon adjustmentquantile_init::Float64=50.0
: Initial quantile when no acceptance rateacc_rate_buffer::Float64=0.1
: Buffer around target acceptance rate
Adaptive alpha parameters
alpha_max::Float64=0.9
: Maximum adaptation ratealpha_min::Float64=0.1
: Minimum adaptation rateacc_rate_far::Float64=2.0
: Threshold for "far from target" adjustmentacc_rate_close::Float64=0.2
: Threshold for "close to target" adjustmentalpha_far_mult::Float64=1.5
: Multiplier for alpha when far from targetalpha_close_mult::Float64=0.5
: Multiplier for alpha when close to target
Early stopping parameters
convergence_window::Integer=3
: Number of steps to check for convergencetheta_rtol::Float64=1e-2
: Relative tolerance for parameter convergencetheta_atol::Float64=1e-3
: Absolute tolerance for parameter convergence
Returns
ABCResults
: A struct containing:
ABCResults.theta_history
: Parameter value history across iterationsABCResults.epsilon_history
: Epsilon value historyABCResults.acc_rate_history
: Acceptance rate historyABCResults.weight_history
: Weight historyABCResults.theta_final
: Final parameter valuesABCResults.weights_final
: Final weightsABCResults.theta_map
: MAP estimate
Early Stopping Conditions
The algorithm stops and returns results if any of these conditions are met:
- Acceptance rate falls below
minAccRate
- Parameters converge within tolerances over
convergence_window
steps - Epsilon falls below
target_epsilon
- Maximum number of
steps
reached
Implementation Details
- First step uses basic ABC with prior sampling
- Subsequent steps use PMC proposal with adaptive epsilon
- Epsilon is adjusted based on acceptance rates and distance quantiles
- Covariance and weights are updated each step unless
sample_only=true
- Parameter convergence is checked using both relative and absolute tolerances
IntrinsicTimescales.ABC.select_epsilon
— Methodselect_epsilon(distances::Vector{Float64}, current_epsilon::Float64; kwargs...)
Adaptively select the epsilon threshold for ABC based on acceptance rates and distance distribution. Uses a combination of quantile-based bounds and adaptive step sizes to adjust epsilon towards achieving the target acceptance rate.
Arguments
Required Arguments
distances::Vector{Float64}
: Vector of distances from ABC simulationscurrent_epsilon::Float64
: Current epsilon threshold value
Optional Keyword Arguments
Acceptance Rate Parameters
target_acc_rate::Float64=0.01
: Target acceptance rate to achievecurrent_acc_rate::Float64=0.0
: Current acceptance rateacc_rate_buffer::Float64=0.1
: Allowed deviation from target acceptance rate
Iteration Parameters
iteration::Integer=1
: Current iteration numbertotal_iterations::Integer=100
: Total number of iterations planned
Distance Processing Parameters
distance_max::Float64=10.0
: Maximum valid distance (larger values filtered out)quantile_lower::Float64=25.0
: Lower quantile for epsilon boundsquantile_upper::Float64=75.0
: Upper quantile for epsilon boundsquantile_init::Float64=50.0
: Initial quantile for first iteration
Adaptive Step Size Parameters
alpha_max::Float64=0.9
: Maximum adaptation ratealpha_min::Float64=0.1
: Minimum adaptation rateacc_rate_far::Float64=2.0
: Threshold for "far from target" adjustmentacc_rate_close::Float64=0.2
: Threshold for "close to target" adjustmentalpha_far_mult::Float64=1.5
: Multiplier for alpha when far from targetalpha_close_mult::Float64=0.5
: Multiplier for alpha when close to target
Returns
Float64
: New epsilon value
Implementation Details
- Filters out NaN and distances larger than distance_max
- Computes quantile-based bounds for epsilon adjustment
- Uses adaptive alpha value based on iteration and acceptance rate (see
compute_adaptive_alpha
) - For first iteration (iteration=1):
- Returns initial quantile of valid distances
- For subsequent iterations:
- If acceptance rate too high: decreases epsilon by (1-alpha)
- If acceptance rate too low: increases epsilon by (1+alpha)
- Keeps epsilon unchanged if within buffer of target rate
- Always constrains new epsilon between quantile bounds
Notes
- Returns current epsilon if no valid distances are found
- Uses computeadaptivealpha for step size calculation
- Adjustments are proportional to distance from target acceptance rate
IntrinsicTimescales.ABC.weighted_covar
— Methodweighted_covar(x::Matrix{Float64}, w::Vector{Float64})
Calculate weighted covariance matrix.
Arguments
x::Matrix{Float64}
: Matrix of observations where each row is an observation and each column is a variablew::Vector{Float64}
: Vector of weights corresponding to each observation (row of x)
Returns
Matrix{Float64}
: Weighted covariance matrix of size (nvariables × nvariables)
IntrinsicTimescales.ACW
— ModuleACW
Module providing autocorrelation width (ACW) calculations for time series analysis, including:
- ACW-0 (zero-crossing)
- ACW-50 (50% decay)
- ACW-euler (1/e decay)
- Exponential decay timescale (tau)
- Knee frequency estimation
IntrinsicTimescales.ACW.ACWResults
— TypeACWResults
Structure holding ACW analysis inputs and results.
Fields
fs::Real
: Sampling frequencyacw_results
: Computed ACW values (type depends on number of ACW types requested)acwtypes::Union{Vector{<:Symbol}, Symbol}
: Types of ACW computedn_lags::Union{Int, Nothing}
: Number of lags used for ACF calculationfreqlims::Union{Tuple{Real, Real}, Nothing}
: Frequency limits used for spectral analysisacf::Union{AbstractVector{<:Real}, AbstractArray{<:Real}, Nothing}
: Autocorrelation functionpsd::Union{AbstractVector{<:Real}, AbstractArray{<:Real}, Nothing}
: Power spectral densityfreqs::Union{AbstractVector{<:Real}, AbstractArray{<:Real}, Nothing}
: Frequency vector for PSDlags::Union{AbstractVector{<:Real}, AbstractArray{<:Real}, Nothing}
: Lag vector for ACFx_dim::Union{Int, Nothing}
: Dimension index corresponding to x-axis (lags/freqs)
Notes
- Supported ACW types: :acw0, :acw50, :acweuler, :auc, :tau, :knee
- Results order matches input acwtypes order
- If only one ACW type is requested,
acw_results
is a scalar; otherwise it's a vector
IntrinsicTimescales.ACW.acw
— Methodacw(data, fs; acwtypes=possible_acwtypes, n_lags=nothing, freqlims=nothing, time=nothing,
dims=ndims(data), return_acf=true, return_psd=true, average_over_trials=false,
trial_dims::Int=setdiff([1, 2], dims)[1], skip_zero_lag::Bool=false, max_peaks::Int=1, oscillation_peak::Bool=true,
allow_variable_exponent::Bool=false, parallel::Bool=false)
Compute various timescale measures for time series data. For detailed documentaion, see https://duodenum96.github.io/IntrinsicTimescales.jl/stable/acw/.
Arguments
data::AbstractArray{<:Real}
: Input time series datafs::Real
: Sampling frequencyacwtypes::Union{Vector{Symbol}, Symbol}=[:acw0, :acw50, :acweuler, :auc, :tau, :knee]
: Types of ACW to compute.
Supported ACW types:
- :acw0 - Time to first zero crossing
- :acw50 - Time to 50% decay
- :acweuler - Time to 1/e decay
- :auc - Area under curve of ACF before ACW0
- :tau - Exponential decay timescale
- :knee - Knee frequency from spectral analysis
n_lags::Union{Int, Nothing}=nothing
: Number of lags for ACF calculation. If not specified, uses 1.1 * ACW0.freqlims::Union{Tuple{Real, Real}, Nothing}=nothing
: Frequency limits for spectral analysis. If not specified, uses full frequency range.time::Union{Vector{Real}, Nothing}=nothing
: Time vector. This is required for Lomb-Scargle method in the case of missing data.dims::Int=ndims(data)
: Dimension along which to compute ACW (Dimension of time)return_acf::Bool=true
: Whether to return the ACFreturn_psd::Bool=true
: Whether to return the PSDaverage_over_trials::Bool=false
: Whether to average the ACF or PSD over trialstrial_dims::Int=setdiff([1, 2], dims)[1]
: Dimension along which to average the ACF or PSD over trials (Dimension of trials)skip_zero_lag::Bool=false
: Whether to skip the zero lag for fitting an exponential decay function. Used only for :tau.max_peaks::Int=1
: Maximum number of oscillatory peaks to fit in spectral analysisoscillation_peak::Bool=true
: Whether to fit an oscillation peak in the spectral analysisallow_variable_exponent::Bool=false
: Whether to allow variable exponent in spectral fittingparallel::Bool=false
: Whether to use parallel computation
Returns
ACWResults
: Structure containing computed ACW measures and intermediate results
Fields of the ACWResults structure:
fs::Real
: Sampling frequencyacw_results
: Computed ACW values (type depends on number of ACW types requested)acwtypes::Union{Vector{<:Symbol}, Symbol}
: Types of ACW computedn_lags::Union{Int, Nothing}
: Number of lags used for ACF calculationfreqlims::Union{Tuple{Real, Real}, Nothing}
: Frequency limits used for spectral analysisacf::Union{AbstractVector{<:Real}, AbstractArray{<:Real}, Nothing}
: Autocorrelation functionpsd::Union{AbstractVector{<:Real}, AbstractArray{<:Real}, Nothing}
: Power spectral densityfreqs::Union{AbstractVector{<:Real}, AbstractArray{<:Real}, Nothing}
: Frequency vector for PSDlags::Union{AbstractVector{<:Real}, AbstractArray{<:Real}, Nothing}
: Lag vector for ACFx_dim::Union{Int, Nothing}
: Dimension index corresponding to x-axis (lags/freqs)
IntrinsicTimescales.TuringBackend.ADVIResults
— TypeADVIResults{T<:Real}
Container for ADVI (Automatic Differentiation Variational Inference) results.
Fields
samples::AbstractArray{T}
: Matrix of posterior samplesMAP::AbstractVector{T}
: Maximum a posteriori estimatesvariational_posterior::Any
: Turing variational posterior object containing full inference results
IntrinsicTimescales.TuringBackend.create_turing_model
— Methodcreate_turing_model(model, data_sum_stats; σ_prior=Exponential(1))
Create a Turing probabilistic model for variational inference.
Arguments
model
: Model instance containing prior distributions and data generation methodsdata_sum_stats
: Summary statistics of the observed dataσ_prior=Exponential(1)
: Prior distribution for the uncertainty parameter σ
Returns
- Turing model object ready for inference
Notes
The created model includes:
- Parameter sampling from truncated priors (positive values only)
- Data generation using the model's forward simulation
- Likelihood computation using Normal distribution
IntrinsicTimescales.TuringBackend.fit_vi
— Methodfit_vi(model; n_samples=4000, n_iterations=10, n_elbo_samples=20,
optimizer=AutoForwardDiff())
Perform variational inference using ADVI (Automatic Differentiation Variational Inference).
Arguments
model
: Model instance to perform inference onn_samples::Int=4000
: Number of posterior samples to drawn_iterations::Int=10
: Number of ADVI iterationsn_elbo_samples::Int=20
: Number of samples for ELBO estimationoptimizer=AutoForwardDiff()
: Optimization algorithm for ADVI
Returns
ADVIResults
: Container with inference results including:samples_matrix
: Matrix of posterior samplesMAP
: Maximum a posteriori parameter estimatesvariational_posterior
: Turing variational posterior object containing full inference results
Notes
Uses Turing.jl's ADVI implementation for fast approximate Bayesian inference. The model is automatically constructed with appropriate priors and likelihood.
IntrinsicTimescales.TuringBackend.get_param_dict_advi
— Methodget_param_dict_advi()
Get default parameter dictionary for ADVI (Automatic Differentiation Variational Inference) algorithm.
Returns
Dictionary containing default values for ADVI parameters including:
n_samples
: Number of posterior samples to draw (default: 4000)n_iterations
: Number of ADVI iterations (default: 50)n_elbo_samples
: Number of samples for ELBO estimation (default: 20)autodiff
: Automatic differentiation backend (default: AutoForwardDiff())
IntrinsicTimescales.SummaryStats
— ModuleSummaryStats
Module for computing various summary statistics from time series data. Includes functions for:
- Autocorrelation (FFT and time-domain methods)
- Power spectral density (periodogram and Welch methods)
- Cross-correlation
- Special handling for missing data (NaN values)
IntrinsicTimescales.SummaryStats._comp_psd_lombscargle
— Method_comp_psd_lombscargle(times, data, frequency_grid)
Internal function to compute Lomb-Scargle periodogram for a single time series.
Arguments
times
: Time points vector (without NaN)data
: Time series data (without NaN)frequency_grid
: Pre-computed frequency grid
Returns
power
: Lomb-Scargle periodogram values
Notes
- Uses LombScargle.jl for core computation
- Assumes data has been pre-processed and doesn't contain NaN values
IntrinsicTimescales.SummaryStats.acf_statsmodels
— Methodacf_statsmodels(x::Vector{T}; kwargs...) where {T <: Real}
Julia implementation of statsmodels.tsa.stattools.acf function. Only for testing.
Arguments
x
: Time series data vectoradjusted=false
: Use n-k denominators if truenlags=nothing
: Number of lags (default: min(10*log10(n), n-1))qstat=false
: Return Ljung-Box Q-statisticsisfft=false
: Use FFT methodalpha=nothing
: Confidence level for intervalsbartlett_confint=false
: Use Bartlett's formulamissing_handling="conservative"
: NaN handling method
Returns
- Vector of autocorrelation values
Notes
- Supports multiple missing data handling methods:
- "none": No checks
- "raise": Error on NaN
- "conservative": NaN-aware computations
- "drop": Remove NaN values
IntrinsicTimescales.SummaryStats.acovf
— MethodEstimate autocovariances. Translated to Julia from statsmodels.tsa.stattools
Parameters
x : array_like Time series data. Must be 1d. adjusted : bool, default False If True, then denominators is n-k, otherwise n. demean : bool, default True If True, then subtract the mean x from each element of x. fft : bool, default True If True, use FFT convolution. This method should be preferred for long time series. missing : str, default "none" A string in ["none", "raise", "conservative", "drop"] specifying how the NaNs are to be treated. "none" performs no checks. "raise" raises an exception if NaN values are found. "drop" removes the missing observations and then estimates the autocovariances treating the non-missing as contiguous. "conservative" computes the autocovariance using nan-ops so that nans are removed when computing the mean and cross-products that are used to estimate the autocovariance. When using "conservative", n is set to the number of non-missing observations. nlag : {int, None}, default None Limit the number of autocovariances returned. Size of returned array is nlag + 1. Setting nlag when fft is False uses a simple, direct estimator of the autocovariances that only computes the first nlag + 1 values. This can be much faster when the time series is long and only a small number of autocovariances are needed.
Returns
ndarray The estimated autocovariances.
References
.. [1] Parzen, E., 1963. On spectral analysis with missing observations and amplitude modulation. Sankhya: The Indian Journal of Statistics, Series A, pp.383-392.
IntrinsicTimescales.SummaryStats.bat_autocorr
— Methodbat_autocorr(x::AbstractVector{<:Real})
Compute the normalized autocorrelation function of a 1D time series using FFT. Returns a vector containing the autocorrelation values.
IntrinsicTimescales.SummaryStats.bat_autocorr
— Methodbat_autocorr(x::AbstractMatrix{<:Real})
Compute the normalized autocorrelation function of a 2D time series using FFT. data is a matrix with dimensions (nseries × ntimepoints)
returns a matrix with dimensions (nseries × nlags)
IntrinsicTimescales.SummaryStats.bat_integrated_autocorr_len
— Functionbat_integrated_autocorr_len(
v::AbstractVectorOfSimilarVectors{<:Real};
c::Integer = 5, tol::Integer = 50, strict = true
)
Estimate the integrated autocorrelation length of variate series v
.
c
: Step size for window search.tol
: Minimum number of autocorrelation times needed to trust the estimate.strict
: Throw exception if result is not trustworthy
This estimate uses the iterative procedure described on page 16 of Sokal's notes to determine a reasonable window size.
Ported to Julia from the emcee Python package, under MIT License. Original authors Dan Foreman-Mackey et al.
IntrinsicTimescales.SummaryStats.bat_integrated_autocorr_weight
— Functionbat_integrated_autocorr_weight(
samples::DensitySampleVector;
c::Integer = 5, tol::Integer = 50, strict = true
)
Estimate the integrated autocorrelation weight of samples
.
IntrinsicTimescales.SummaryStats.comp_ac_fft
— Methodcomp_ac_fft(data::AbstractArray{T}; dims::Int=ndims(data), n_lags::Integer=size(data, dims), parallel::Bool=false) where {T <: Real}
Compute autocorrelation using FFT along specified dimension.
Arguments
data
: Array of time series datadims
: Dimension along which to compute autocorrelation (defaults to last dimension)n_lags
: Number of lags to compute (defaults to size of data along specified dimension)parallel
: Whether to use parallel computation
Returns
Array with autocorrelation values, the specified dimension becomes the dimension of lags while the other dimensions denote ACF values
IntrinsicTimescales.SummaryStats.comp_ac_fft
— Methodcomp_ac_fft(data::Vector{T}; n_lags::Real=length(data)) where {T <: Real}
Compute autocorrelation using FFT method.
Arguments
data
: Input time series vectorn_lags
: Number of lags to compute (defaults to length of data)
Returns
- Vector of autocorrelation values from lag 0 to n_lags-1
Notes
- Uses FFT for efficient computation
- Pads data to next power of 2 for FFT efficiency
- Normalizes by variance (first lag)
IntrinsicTimescales.SummaryStats.comp_ac_time
— Methodcomp_ac_time(data::AbstractArray{T}, max_lag::Integer; dims::Int=ndims(data), parallel::Bool=false) where {T <: Real}
Compute autocorrelation in time domain along specified dimension.
Arguments
data
: Array of time series datamax_lag
: Maximum lag to computedims
: Dimension along which to compute autocorrelation (defaults to last dimension)parallel=false
: Whether to use parallel computation
Returns
Array with autocorrelation values, the specified dimension becomes the dimension of lags while the other dimensions denote ACF values
IntrinsicTimescales.SummaryStats.comp_ac_time
— Methodcomp_ac_time(data::AbstractArray{T}, max_lag::Integer; dims::Int=ndims(data)) where {T <: Real}
Compute autocorrelation in time domain along specified dimension.
Arguments
data
: Array of time series datamax_lag
: Maximum lag to computedims
: Dimension along which to compute autocorrelation (defaults to last dimension)
Returns
Array with autocorrelation values, the specified dimension becomes the dimension of lags while the other dimensions denote ACF values
IntrinsicTimescales.SummaryStats.comp_ac_time_missing
— Methodcomp_ac_time_missing(data::AbstractArray{T}; kwargs...) where {T <: Real}
Compute autocorrelation for data with missing values.
Arguments
data
: Time series data (may contain NaN)dims=ndims(data)
: Dimension along which to computen_lags=size(data,dims)
: Number of lags to computeparallel=false
: Whether to use parallel computation
Returns
- Array of autocorrelation values
Notes
- Handles missing data using missing="conservative" approach of
statsmodels.tsa.stattools.acf. See https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.acf.html for details.
IntrinsicTimescales.SummaryStats.comp_cc
— Methodcomp_cc(data1::AbstractArray{T}, data2::AbstractArray{T}, max_lag::Integer;
dims::Int=ndims(data1)) where {T <: Real}
Compute cross-correlation between two arrays along specified dimension.
Arguments
data1
: First array of time series datadata2
: Second array of time series datamax_lag
: Maximum lag to computedims
: Dimension along which to compute cross-correlation (defaults to last dimension)
Returns
Array with cross-correlation values, reduced along specified dimension
IntrinsicTimescales.SummaryStats.comp_psd
— Methodcomp_psd(x::AbstractArray{T}, fs::Real; kwargs...) where {T <: Real}
Compute power spectral density using periodogram or welch method.
Arguments
x
: Time series data (time × channels)fs
: Sampling frequencydims=ndims(x)
: Dimension along which to compute PSDmethod="periodogram"
: Method to use ("periodogram" or "welch")window=dsp.hamming
: Window functionn=div(size(x,dims),8)
: Window size for Welch methodnoverlap=div(n,2)
: Overlap for Welch methodparallel=false
: Whether to use parallel computation
Returns
power
: Power spectral density values (excludes DC component)freqs
: Corresponding frequencies (excludes DC component)
IntrinsicTimescales.SummaryStats.comp_psd_adfriendly
— Methodcomp_psd_adfriendly(x::AbstractArray{<:Real}, fs::Real; dims::Int=ndims(x), parallel::Bool=false)
Compute power spectral density using an automatic differentiation (AD) friendly implementation.
Arguments
x
: Time series datafs
: Sampling frequencydims=ndims(x)
: Dimension along which to compute PSDparallel=false
: Whether to use parallel computation
Returns
power
: Power spectral density valuesfreqs
: Corresponding frequencies
IntrinsicTimescales.SummaryStats.comp_psd_lombscargle
— Methodcomp_psd_lombscargle(times, data, nanmask, dt; dims=ndims(data))
Compute Lomb-Scargle periodogram for data with missing values.
Arguments
times
: Time points vectordata
: Time series data (may contain NaN)nanmask
: Boolean mask indicating NaN positionsdt
: Time stepdims=ndims(data)
: Dimension along which to compute
Returns
power
: Lomb-Scargle periodogram valuesfrequency_grid
: Corresponding frequencies
Notes
- Handles irregular sampling due to missing data
- Uses frequency grid based on shortest valid time series
- Automatically determines appropriate frequency range
IntrinsicTimescales.SummaryStats.prepare_lombscargle
— Methodprepare_lombscargle(times, data, nanmask)
Prepare data for Lomb-Scargle periodogram computation by handling missing values.
Arguments
times
: Time points vectordata
: Time series data (may contain NaN)nanmask
: Boolean mask indicating NaN positions
Returns
valid_times
: Time points with NaN values removedvalid_data
: Data points with NaN values removedfrequency_grid
: Suggested frequency grid for analysis
IntrinsicTimescales.Distances
— ModuleDistances
Module providing distance metrics for comparing summary statistics in ABC inference. Currently implements linear (L2) and logarithmic distances.
IntrinsicTimescales.Distances.linear_distance
— Methodlinear_distance(data, synth_data)
Compute mean squared error (MSE) between summary statistics.
Arguments
data::Union{AbstractArray, Real}
: Observed data summary statisticssynth_data::Union{AbstractArray, Real}
: Simulated data summary statistics
Returns
Float64
: Mean squared difference between data and synth_data
Notes
- Handles both scalar and array inputs
- For arrays, computes element-wise differences before averaging
- Useful for comparing summary statistics on linear scales
IntrinsicTimescales.Distances.logarithmic_distance
— Methodlogarithmic_distance(data, synth_data)
Compute mean squared distance between logarithms of summary statistics.
Arguments
data::Union{AbstractArray, Real}
: Observed data summary statisticssynth_data::Union{AbstractArray, Real}
: Simulated data summary statistics
Returns
Float64
: Mean squared difference between log(data) and log(synth_data)
Notes
- Handles both scalar and array inputs
- For arrays, computes element-wise log differences before averaging
- Useful for comparing summary statistics spanning multiple orders of magnitude
- Assumes all values are positive
IntrinsicTimescales.Utils
— ModuleUtils
Module providing utility functions for time series analysis, including:
- Exponential decay fitting
- Oscillation peak detection
- Knee frequency estimation
- Lorentzian fitting
- ACF width calculations
IntrinsicTimescales.Utils.acw0
— Methodacw0(lags, acf; dims=ndims(acf), parallel=false)
Compute the ACW0 (autocorrelation width at zero crossing) along specified dimension.
Arguments
lags::AbstractVector{T}
: Vector of lag valuesacf::AbstractArray{T}
: Array of autocorrelation valuesdims::Int=ndims(acf)
: Dimension along which to compute ACW0parallel=false
: Whether to use parallel computation
Returns
- First lag where autocorrelation crosses zero
Notes
- Alternative measure of characteristic timescale
- More sensitive to noise than ACW50
IntrinsicTimescales.Utils.acw50
— Methodacw50(lags, acf; dims=ndims(acf), parallel=false)
Compute the ACW50 (autocorrelation width at 50%) along specified dimension.
Arguments
lags::AbstractVector{T}
: Vector of lag valuesacf::AbstractArray{T}
: Array of autocorrelation valuesdims::Int=ndims(acf)
: Dimension along which to compute ACW50parallel=false
: Whether to use parallel computation
Returns
- First lag where autocorrelation falls below 0.5
Notes
- Used for estimating characteristic timescales
- Related to tau by: tau = -acw50/log(0.5)
IntrinsicTimescales.Utils.acw_romberg
— Methodacw_romberg(dt, acf; dims=ndims(acf), parallel=false)
Calculate the area under the curve of ACF using Romberg integration.
Arguments
dt::Real
: Time stepacf::AbstractVector
: Array of autocorrelation valuesdims::Int=ndims(acf)
: Dimension along which to computeparallel=false
: Whether to use parallel computation
Returns
- AUC of ACF
Notes
- Returns only the integral value, discarding the error estimate
IntrinsicTimescales.Utils.acweuler
— Methodacweuler(lags, acf; dims=ndims(acf), parallel=false)
Compute the ACW at 1/e (≈ 0.368) along specified dimension.
Arguments
lags::AbstractVector{T}
: Vector of lag valuesacf::AbstractVector{S}
: Array of autocorrelation valuesdims::Int=ndims(acf)
: Dimension along which to computeparallel=false
: Whether to use parallel computation
Returns
- First lag where autocorrelation falls below 1/e
Notes
- For exponential decay, equals the timescale parameter tau
IntrinsicTimescales.Utils.expdecay
— Methodexpdecay(tau, lags)
Compute exponential decay function.
Arguments
tau::Real
: Timescale parameterlags::AbstractVector
: Time lags
Returns
- Vector of exp(-t/tau) values
Notes
- Used for fitting autocorrelation functions
- Assumes exponential decay model: acf = exp(-t/tau)
IntrinsicTimescales.Utils.expdecay_3_parameters
— Methodexpdecay_3_parameters(p, lags)
Compute exponential decay function with amplitude and offset parameters. This is used in acw
with the setting skip_zero_lag=true
.
Arguments
p::AbstractVector
: Parameters [A, tau, B] where:- A: Amplitude parameter
- tau: Timescale parameter
- B: Offset parameter
lags::AbstractVector
: Time lags
Returns
- Vector of A*(exp(-t/tau) + B) values
IntrinsicTimescales.Utils.find_knee_frequency
— Methodfind_knee_frequency(psd, freqs; dims=ndims(psd), min_freq=freqs[1], max_freq=freqs[end], constrained=false, allow_variable_exponent=false, parallel=false)
Find knee frequency by fitting Lorentzian to power spectral density.
Arguments
psd::AbstractArray{T}
: Power spectral density valuesfreqs::Vector{T}
: Frequency valuesdims::Int=ndims(psd)
: Dimension along which to computemin_freq::T=freqs[1]
: Minimum frequency to considermax_freq::T=freqs[end]
: Maximum frequency to considerconstrained::Bool=false
: Whether to use constrained optimizationallow_variable_exponent::Bool=false
: Whether to allow variable exponent (PLE)parallel=false
: Whether to use parallel computation
Returns
- Vector of the fit for the equation amp/(1 + (f/knee)^{exponent}).
If allowvariableexponent=false, assumes exponent=2 and returns [amplitude, kneefrequency]. If true, returns [amplitude, kneefrequency, exponent].
Notes
- Uses Lorentzian fitting with NonlinearSolve.jl or Optimization.jl
- Initial guess for amplitude based on low frequency power
- Initial guess for knee at half-power point
- Initial guess for exponent is 2.0 when variable exponent allowed
IntrinsicTimescales.Utils.find_oscillation_peak
— Methodfind_oscillation_peak(psd, freqs; min_freq=5.0/1000.0, max_freq=50.0/1000.0, min_prominence_ratio=0.1)
Find dominant oscillatory peak in power spectral density.
Arguments
psd::AbstractVector
: Power spectral density valuesfreqs::AbstractVector
: Frequency valuesmin_freq::Real=5.0/1000.0
: Minimum frequency to considermax_freq::Real=50.0/1000.0
: Maximum frequency to considermin_prominence_ratio::Real=0.1
: Minimum peak prominence as fraction of max PSD
Returns
- Frequency of most prominent peak, or NaN if no significant peak found
Notes
- Uses peak prominence for robustness
- Filters peaks by minimum prominence threshold
- Returns NaN if no peaks meet criteria
IntrinsicTimescales.Utils.fit_expdecay
— Methodfit_expdecay(lags, acf; dims=ndims(acf), parallel=false)
Fit exponential decay to autocorrelation function.
Arguments
lags::AbstractVector{T}
: Time lagsacf::AbstractArray{T}
: Autocorrelation valuesdims::Int=ndims(acf)
: Dimension along which to fitparallel=false
: Whether to use parallel computation
Returns
- Fitted timescale parameter(s)
Notes
- Uses NonlinearSolve.jl with FastShortcutNLLSPolyalg
- Initial guess based on ACW50
IntrinsicTimescales.Utils.fit_expdecay_3_parameters
— Methodfit_expdecay_3_parameters(lags, acf; parallel=false)
Fit a 3-parameter exponential decay function to autocorrelation data ( A*(exp(-t/tau) + B) ). Excludes lag 0 from fitting.
Arguments
lags::AbstractVector{T}
: Time lagsacf::AbstractVector{T}
: Autocorrelation valuesparallel=false
: Whether to use parallel computation
Returns
- Fitted timescale parameter (tau)
Notes
- Initial guess: A=0.5, tau from ACW50, B=0.0
IntrinsicTimescales.Utils.fit_gaussian
— Methodfit_gaussian(psd, freqs, initial_peak; min_freq=freqs[1], max_freq=freqs[end])
Fit Gaussian to power spectral density around a peak.
Arguments
psd::AbstractVector{<:Real}
: Power spectral density valuesfreqs::AbstractVector{<:Real}
: Frequency valuesinitial_peak::Real
: Initial guess for center frequencymin_freq::Real
: Minimum frequency to considermax_freq::Real
: Maximum frequency to consider
Returns
- Vector{Float64}: Fitted parameters [amplitude, centerfreq, stddev]
Notes
- Uses initial peak location from findoscillationpeak
IntrinsicTimescales.Utils.fooof_fit
— Methodfooof_fit(psd, freqs; dims=ndims(psd), min_freq=freqs[1], max_freq=freqs[end],
oscillation_peak=true, max_peaks=3, allow_variable_exponent=false, constrained=false, parallel=false)
Perform FOOOF-style fitting of power spectral density. The default behavior is to fit a Lorentzian with PLE = 2. If allowvariableexponent=true, the function will fit a Lorentzian with variable PLE.
Arguments
psd::AbstractArray{T}
: Power spectral density valuesfreqs::Vector{T}
: Frequency valuesdims::Int=ndims(psd)
: Dimension along which to computemin_freq::T=freqs[1]
: Minimum frequency to considermax_freq::T=freqs[end]
: Maximum frequency to consideroscillation_peak::Bool=true
: Whether to compute oscillation peaksmax_peaks::Int=3
: Maximum number of oscillatory peaks to fitreturn_only_knee::Bool=false
: Whether to return only knee frequencyallow_variable_exponent::Bool=false
: Whether to allow variable exponent (PLE)constrained::Bool=false
: Whether to use constrained optimizationparallel=false
: Whether to use parallel computation
Returns
If returnonlyknee=false:
- Tuple of (kneefrequency, oscillationparameters) where oscillationparameters is Vector of (centerfreq, amplitude, std_dev) for each peak
If returnonlyknee=true:
- knee_frequency only
Notes
- Implements iterative FOOOF-style fitting:
- Fit initial Lorentzian to PSD
- Find and fit Gaussian peaks iteratively
- Subtract all Gaussians from original PSD
- Refit Lorentzian to cleaned PSD
- Default behavior fits standard Lorentzian (PLE = 2)
- If allowvariableexponent=true, fits Lorentzian with variable PLE
IntrinsicTimescales.Utils.gaussian
— Methodgaussian(f, u)
Gaussian function for fitting oscillations.
Arguments
f::AbstractVector
: Frequency valuesu::Vector
: Parameters [amplitude, centerfreq, stddev]
Returns
- Vector of Gaussian values: amp * exp(-(f-center)²/(2*std²))
IntrinsicTimescales.Utils.get_slices
— Methodget_slices(x::AbstractArray{T}; dims::Int=ndims(x)) where {T}
Get array slices along all dimensions except the specified one.
Arguments
x::AbstractArray{T}
: Input arraydims::Int=ndims(x)
: Dimension to exclude when taking slices
Returns
- Iterator of array slices
Notes
- Returns slices along all dimensions except
dims
- Each slice represents a view into the array with
dims
fixed
IntrinsicTimescales.Utils.lorentzian
— Methodlorentzian(f, u)
Compute Lorentzian function values.
Arguments
f::AbstractVector
: Frequency valuesu::Vector
: Parameters [amplitude, knee_frequency]
Returns
- Vector of Lorentzian values: amp/(1 + (f/knee)²)
IntrinsicTimescales.Utils.lorentzian_initial_guess
— Methodlorentzian_initial_guess(psd, freqs; min_freq=freqs[1], max_freq=freqs[end])
Estimate initial parameters for Lorentzian fitting.
Arguments
psd::AbstractVector{<:Real}
: Power spectral density valuesfreqs::AbstractVector{<:Real}
: Frequency valuesmin_freq::Real
: Minimum frequency to considermax_freq::Real
: Maximum frequency to consider
Returns
- Vector{Float64}: Initial guess for [amplitude, knee_frequency]
Notes
- Estimates amplitude from average power of low frequencies.
- Estimates knee frequency from half-power point.
- If allowvariableexponent=true, sets initial guess for exponent to 2.0.
- Used as starting point for nonlinear fitting
IntrinsicTimescales.Utils.lorentzian_with_exponent
— Methodlorentzian_with_exponent(f, u)
Compute Lorentzian function values that allow variable exponent (PLE).
Arguments
f::AbstractVector
: Frequency valuesu::Vector
: Parameters [amplitude, knee_frequency, exponent]
Returns
- Vector of Lorentzian values: amp/(1 + (f/knee)^exponent)
Notes
- Generalizes standard Lorentzian to allow variable power law exponent
- When exponent=2, reduces to standard Lorentzian
IntrinsicTimescales.Utils.residual_expdecay!
— MethodResidual function for expdecay du: residual u: parameters p: data
IntrinsicTimescales.Utils.stack_and_reshape
— Methodstack_and_reshape(slices; dims::Int)
Reconstruct an array from slices by stacking and reshaping them back to original dimensions.
Arguments
slices
: Iterator or collection of array slices (fromget_slices
)dims::Int
: Dimension along which the original slicing was performed (should be same as dims fed intoget_slices
)
Returns
- Reconstructed array with proper dimension ordering
Example
# Split array into slices along dimension 2
x = rand(3, 4, 5)
slices = get_slices(x; dims=2)
# Reconstruct original array
x_reconstructed = stack_and_reshape(slices; dims=2)
IntrinsicTimescales.OrnsteinUhlenbeck
— ModuleOrnsteinUhlenbeck
Module for generating Ornstein-Uhlenbeck processes with various configurations. Uses DifferentialEquations.jl.
IntrinsicTimescales.OrnsteinUhlenbeck.generate_ou_process
— Methodgenerate_ou_process(tau, true_D, dt, duration, num_trials; standardize=true, rng=Random.default_rng(), deq_seed=nothing)
Generate an Ornstein-Uhlenbeck process with a single timescale
Arguments
tau::Union{Real, Vector{<:Real}}
: Timescale(s) of the OU processtrue_D::Real
: Target variance for scaling the processdt::Real
: Time step sizeduration::Real
: Total time lengthnum_trials::Real
: Number of trials/trajectoriesstandardize::Bool=true
: Whether to standardize output to match true_Drng::AbstractRNG=Random.default_rng()
: Random number generator for initial conditionsdeq_seed::Integer=nothing
: Random seed for DifferentialEquations.jl solver. Ifnothing
, uses StochasticDiffEq.jl defaults. Note that for full replicability,
you need to set both rng
and deq_seed
.
Returns
- Matrix{Float64}: Generated OU process data with dimensions (numtrials, numtimesteps)
Notes
- Uses generateouprocess_sciml internally
- Returns NaN matrix if SciML solver fails
- Standardizes output to have specified variance if standardize=true
IntrinsicTimescales.OrnsteinUhlenbeck.generate_ou_process_sciml
— Methodgenerate_ou_process_sciml(tau, true_D, dt, duration, num_trials, standardize; rng=Random.default_rng(), deq_seed=nothing)
Generate an Ornstein-Uhlenbeck process using DifferentialEquations.jl.
Arguments
tau::Union{T, Vector{T}}
: Timescale(s) of the OU processtrue_D::Real
: Target variance for scalingdt::Real
: Time step sizeduration::Real
: Total time lengthnum_trials::Integer
: Number of trials/trajectoriesstandardize::Bool
: Whether to standardize output to match true_Drng::AbstractRNG=Random.default_rng()
: Random number generator for initial conditionsdeq_seed::Union{Integer, Nothing}=nothing
: Random seed for DifferentialEquations.jl solver. Ifnothing
, uses StochasticDiffEq.jl defaults. Note that for full replicability,
you need to set both rng
and deq_seed
.
Returns
Tuple{Matrix{Float64}, ODESolution}
:- Scaled OU process data
- Full SDE solution object
Notes
- Switches between static and dynamic arrays based on num_trials
Example:
tau = 1.0
true_D = 1.0
dt = 0.01
duration = 10.0
num_trials = 100
ou, _ = generate_ou_process_sciml(tau, true_D, dt, duration, num_trials, true)
# Reproducible example
deq_seed = 42
ou, _ = generate_ou_process_sciml(tau, true_D, dt, duration, num_trials, true, rng=Xoshiro(42), deq_seed=deq_seed)
IntrinsicTimescales.OrnsteinUhlenbeck.generate_ou_with_oscillation
— Methodgenerate_ou_with_oscillation(theta, dt, duration, num_trials, data_mean, data_sd; rng=Random.default_rng(), deq_seed=nothing)
Generate a one-timescale OU process with an additive oscillation.
Arguments
theta::Vector{T}
: Parameters [timescale, frequency, coefficient]dt::Real
: Time step sizeduration::Real
: Total time lengthnum_trials::Integer
: Number of trialsdata_mean::Real
: Target mean valuedata_sd::Real
: Target standard deviationrng::AbstractRNG=Random.default_rng()
: Random number generator for initial conditionsdeq_seed::Union{Integer, Nothing}=nothing
: Random seed for DifferentialEquations.jl solver. Ifnothing
, uses StochasticDiffEq.jl defaults. Note that for full replicability,
you need to set both rng
and deq_seed
.
Returns
- Matrix{Float64}: Generated data with dimensions (numtrials, numtimesteps)
Notes
- Coefficient is bounded between 0 and 1
- Combines OU process with sinusoidal oscillation
- Standardizes and scales output to match target mean and standard deviation
- Returns NaN matrix if SciML solver fails
IntrinsicTimescales.OneTimescale
— ModuleOneTimescale
Module for inferring a single timescale from time series data using the Ornstein-Uhlenbeck process.
IntrinsicTimescales.OneTimescale.OneTimescaleModel
— TypeOneTimescaleModel <: AbstractTimescaleModel
Model for inferring a single timescale from time series data using the Ornstein-Uhlenbeck process. We recommend using the one_timescale_model
constructor function rather than creating directly.
Fields
data::AbstractArray{<:Real}
: Input time series datatime::AbstractVector{<:Real}
: Time points corresponding to the datafit_method::Symbol
: Fitting method (:abc or :advi)summary_method::Symbol
: Summary statistic type (:psd or :acf)lags_freqs
: Lags (for ACF) or frequencies (for PSD)prior
: Prior distribution(s) for parametersdistance_method::Symbol
: Distance metric type (:linear or :logarithmic)data_sum_stats
: Pre-computed summary statisticsdt::Real
: Time step between observationsT::Real
: Total time spannumTrials::Real
: Number of trials/iterationsdata_mean::Real
: Mean of input datadata_sd::Real
: Standard deviation of input datafreqlims
: Frequency limits for PSD analysisn_lags
: Number of lags for ACFfreq_idx
: Boolean mask for frequency selectiondims::Int
: Dimension along which to compute statisticsdistance_combined::Bool
: Whether to use combined distance metricweights::Vector{Real}
: Weights for combined distancedata_tau::Union{Real, Nothing}
: Pre-computed timescaleu0::Union{Vector{Real}, Nothing}
: Initial parameter guess
IntrinsicTimescales.Models.distance_function
— MethodModels.distance_function(model::OneTimescaleModel, sum_stats, data_sum_stats)
Calculate the distance between summary statistics of simulated and observed data.
Arguments
model::OneTimescaleModel
: Model instancesum_stats
: Summary statistics from simulated datadata_sum_stats
: Summary statistics from observed data
Returns
- Distance value based on model.distancemethod (:linear or :logarithmic) or combined distance if model.distancecombined is true
Notes
If distance_combined is true:
- For ACF: Combines ACF distance with fitted exponential decay timescale distance
- For PSD: Combines PSD distance with knee frequency timescale distance
IntrinsicTimescales.Models.generate_data
— MethodModels.generate_data(model::OneTimescaleModel, theta)
Generate synthetic data from the Ornstein-Uhlenbeck process with given timescale.
Arguments
model::OneTimescaleModel
: Model instance containing simulation parameterstheta
: Vector containing single timescale parameter (τ)
Returns
- Synthetic time series data with same dimensions as model.data
Notes
Uses the model's stored parameters:
data_sd
: Standard deviation for the OU processdt
: Time stepT
: Total time spannumTrials
: Number of trials/trajectories
IntrinsicTimescales.Models.int_fit
— Functionint_fit(model::OneTimescaleModel, param_dict::Dict=Dict())
Perform inference using the specified fitting method.
Arguments
model::OneTimescaleModel
: Model instanceparam_dict::Dict=Dict()
: Dictionary of algorithm parameters. If empty, uses defaults.
Returns
For ABC method:
posterior_samples
: Matrix of accepted parameter samplesposterior_MAP
: Maximum a posteriori estimateabc_record
: Full record of ABC iterations
For ADVI method:
ADVIResults
: Container with samples, MAP estimates, variances, and full chain
Notes
- For ABC: Uses Population Monte Carlo ABC with adaptive epsilon selection
- For ADVI: Uses Automatic Differentiation Variational Inference via Turing.jl
- Parameter dictionary can be customized for each method (see getparamdict_abc())
IntrinsicTimescales.Models.summary_stats
— MethodModels.summary_stats(model::OneTimescaleModel, data)
Compute summary statistics (ACF or PSD) from time series data.
Arguments
model::OneTimescaleModel
: Model instance specifying summary statistic typedata
: Time series data to analyze
Returns
For ACF (summary_method = :acf
):
- Mean autocorrelation function up to
n_lags
For PSD (summary_method = :psd
):
- Mean power spectral density within specified frequency range
Notes
- ACF is computed using FFT-based method
- PSD is computed and filtered according to model.freq_idx
- Throws ArgumentError if summary_method is invalid
IntrinsicTimescales.OneTimescale.combined_distance
— Methodcombined_distance(model::OneTimescaleModel, simulation_summary, data_summary,
weights, data_tau, simulation_tau)
Compute combined distance metric between simulated and observed data.
Arguments
model
: OneTimescaleModel instancesimulation_summary
: Summary statistics from simulationdata_summary
: Summary statistics from observed dataweights
: Weights for combining distancesdata_tau
: Timescale from observed datasimulation_tau
: Timescale from simulation
Returns
- Weighted combination of summary statistic distance and timescale distance
IntrinsicTimescales.OneTimescale.one_timescale_model
— Methodone_timescale_model(data, time, fit_method; kwargs...)
Construct a OneTimescaleModel for time series analysis.
Arguments
data
: Input time series datatime
: Time points corresponding to the datafit_method
: Fitting method to use (:abc or :advi)
Keyword Arguments
summary_method=:acf
: Summary statistic type (:psd or :acf)data_sum_stats=nothing
: Pre-computed summary statisticslags_freqs=nothing
: Custom lags or frequenciesprior=nothing
: Prior distribution(s) for parametersn_lags=nothing
: Number of lags for ACFdistance_method=nothing
: Distance metric typedt=time[2]-time[1]
: Time stepT=time[end]
: Total time spannumTrials=size(data,1)
: Number of trialsdata_mean=mean(data)
: Data meandata_sd=std(data)
: Data standard deviationfreqlims=nothing
: Frequency limits for PSDfreq_idx=nothing
: Frequency selection maskdims=ndims(data)
: Analysis dimensiondistance_combined=false
: Use combined distanceweights=[0.5, 0.5]
: Distance weightsdata_tau=nothing
: Pre-computed timescaleu0=nothing
: Initial parameter guess
Returns
OneTimescaleModel
: Model instance configured for specified analysis method
Notes
Two main usage patterns:
- ACF-based inference:
summary_method=:acf
,fit_method=:abc/:advi
- PSD-based inference:
summary_method=:psd
,fit_method=:abc/:advi
IntrinsicTimescales.OneTimescaleAndOsc.OneTimescaleAndOscModel
— TypeOneTimescaleAndOscModel <: AbstractTimescaleModel
Model for inferring a single timescale and oscillation from time series data using the Ornstein-Uhlenbeck process. Parameters: [tau, freq, coeff] representing timescale, oscillation frequency, and oscillation coefficient.
Fields
data::AbstractArray{<:Real}
: Input time series datatime::AbstractVector{<:Real}
: Time points corresponding to the datafit_method::Symbol
: Fitting method (:abc or :advi)summary_method::Symbol
: Summary statistic type (:psd or :acf)lags_freqs
: Lags (for ACF) or frequencies (for PSD)prior
: Prior distribution(s) for parametersdistance_method::Symbol
: Distance metric type (:linear or :logarithmic)data_sum_stats
: Pre-computed summary statisticsdt::Real
: Time step between observationsT::Real
: Total time spannumTrials::Real
: Number of trials/iterationsdata_mean::Real
: Mean of input datadata_sd::Real
: Standard deviation of input datafreqlims
: Frequency limits for PSD analysisn_lags
: Number of lags for ACFfreq_idx
: Boolean mask for frequency selectiondims::Int
: Dimension along which to compute statisticsdistance_combined::Bool
: Whether to use combined distance metricweights::Vector{Real}
: Weights for combined distancedata_tau::Union{Real, Nothing}
: Pre-computed timescaledata_osc::Union{Real, Nothing}
: Pre-computed oscillation frequency
IntrinsicTimescales.Models.distance_function
— MethodModels.distance_function(model::OneTimescaleAndOscModel, sum_stats, data_sum_stats)
Calculate the distance between summary statistics of simulated and observed data.
Arguments
model::OneTimescaleAndOscModel
: Model instancesum_stats
: Summary statistics from simulated datadata_sum_stats
: Summary statistics from observed data
Returns
- Distance value based on model.distancemethod (:linear or :logarithmic) or combined distance if model.distancecombined is true
Notes
If distance_combined is true:
- For ACF: Combines ACF distance with fitted exponential decay timescale distance
- For PSD: Combines PSD distance with knee frequency timescale distance and oscillation frequency distance
IntrinsicTimescales.Models.generate_data
— MethodModels.generate_data(model::OneTimescaleAndOscModel, theta::AbstractVector{<:Real})
Generate synthetic data from the Ornstein-Uhlenbeck process with oscillation.
Arguments
model::OneTimescaleAndOscModel
: Model instance containing simulation parameterstheta::AbstractVector{<:Real}
: Vector containing parameters [tau, freq, coeff]
Returns
- Synthetic time series data with same dimensions as model.data
Notes
Uses the model's stored parameters:
dt
: Time stepT
: Total time spannumTrials
: Number of trials/trajectoriesdata_mean
: Mean of the processdata_sd
: Standard deviation of the process
IntrinsicTimescales.Models.int_fit
— Functionint_fit(model::OneTimescaleAndOscModel, param_dict::Dict=Dict())
Perform inference using the specified fitting method.
Arguments
model::OneTimescaleAndOscModel
: Model instanceparam_dict::Dict=Dict()
: Dictionary of algorithm parameters. If empty, uses defaults.
Returns
For ABC method:
abc_record
: Complete record of ABC iterations including posterior samples and MAP estimate
For ADVI method:
result
: Results from variational inference containing samples, MAP estimates, and variational posterior
Notes
- For ABC: Uses Population Monte Carlo ABC with adaptive epsilon selection
- For ADVI: Uses Automatic Differentiation Variational Inference via Turing.jl
- Parameter dictionary can be customized for each method (see getparamdictabc() and getparamdictadvi())
IntrinsicTimescales.Models.summary_stats
— MethodModels.summary_stats(model::OneTimescaleAndOscModel, data)
Compute summary statistics (ACF or PSD) from time series data.
Arguments
model::OneTimescaleAndOscModel
: Model instance specifying summary statistic typedata
: Time series data to analyze
Returns
For ACF (summary_method = :acf
):
- Mean autocorrelation function up to
n_lags
For PSD (summary_method = :psd
):
- Mean power spectral density within specified frequency range
Notes
- ACF is computed using FFT-based method
- PSD is computed using AD-friendly implementation
- Throws ArgumentError if summary_method is invalid
IntrinsicTimescales.OneTimescaleAndOsc.combined_distance
— Methodcombined_distance(model::OneTimescaleAndOscModel, simulation_summary, data_summary,
weights, distance_method, data_tau, simulation_tau,
data_osc, simulation_osc)
Compute combined distance metric between simulated and observed data.
Arguments
model
: OneTimescaleAndOscModel instancesimulation_summary
: Summary statistics from simulationdata_summary
: Summary statistics from observed dataweights
: Weight vector for combining distances. For ACF: [w1, w2]. For PSD: [w1, w2, w3]distance_method
: Distance metric type (:linear or :logarithmic)data_tau
: Timescale from observed datasimulation_tau
: Timescale from simulationdata_osc
: Oscillation frequency from observed data (used for PSD only)simulation_osc
: Oscillation frequency from simulation (used for PSD only)
Returns
For ACF:
- Weighted combination: weights[1] * summarydistance + weights[2] * timescaledistance
For PSD:
- Weighted combination: weights[1] * summarydistance + weights[2] * timescaledistance + weights[3] * oscillation_distance
IntrinsicTimescales.OneTimescaleAndOsc.one_timescale_and_osc_model
— Methodone_timescale_and_osc_model(data, time, fit_method; kwargs...)
Construct a OneTimescaleAndOscModel for time series with oscillations. See https://duodenum96.github.io/IntrinsicTimescales.jl/stable/onetimescaleand_osc/ for details and complete examples.
Arguments
data
: Input time series datatime
: Time points corresponding to the datafit_method
: Fitting method to use (:abc or :advi)
Keyword Arguments
summary_method=:psd
: Summary statistic type (:psd or :acf)data_sum_stats=nothing
: Pre-computed summary statisticslags_freqs=nothing
: Custom lags or frequenciesprior=nothing
: Prior distribution(s) for parametersn_lags=nothing
: Number of lags for ACFdistance_method=nothing
: Distance metric typedt=time[2]-time[1]
: Time stepT=time[end]
: Total time spannumTrials=size(data,1)
: Number of trialsdata_mean=mean(data)
: Data meandata_sd=std(data)
: Data standard deviationfreqlims=nothing
: Frequency limits for PSDfreq_idx=nothing
: Frequency selection maskdims=ndims(data)
: Analysis dimensiondistance_combined=false
: Use combined distanceweights=[0.5, 0.5]
: Distance weights for combined distancedata_tau=nothing
: Pre-computed timescaledata_osc=nothing
: Pre-computed oscillation frequency
Returns
OneTimescaleAndOscModel
: Model instance configured for specified analysis method
Notes
Four main usage patterns:
- ACF-based ABC/ADVI:
summary_method=:acf
,fit_method=:abc/:advi
- PSD-based ABC/ADVI:
summary_method=:psd
,fit_method=:abc/:advi
IntrinsicTimescales.OneTimescaleWithMissing
— ModuleOneTimescaleWithMissing
Module for handling time series analysis with missing data. Uses specialized methods for handling NaN values:
- For ACF: Uses compactime_missing (equivalent to statsmodels.tsa.statstools.acf with missing="conservative")
- For PSD: Uses Lomb-Scargle periodogram to handle irregular sampling
IntrinsicTimescales.OneTimescaleWithMissing.OneTimescaleWithMissingModel
— TypeOneTimescaleWithMissingModel <: AbstractTimescaleModel
Model for inferring a single timescale from time series data with missing values.
Fields
data::AbstractArray{<:Real}
: Input time series data (may contain NaN)time::AbstractVector{<:Real}
: Time points corresponding to the datafit_method::Symbol
: Fitting method (:abc or :advi)summary_method::Symbol
: Summary statistic type (:psd or :acf)lags_freqs
: Lags (for ACF) or frequencies (for PSD)prior
: Prior distribution(s) for parametersdistance_method::Symbol
: Distance metric type (:linear or :logarithmic)data_sum_stats
: Pre-computed summary statisticsdt::Real
: Time step between observationsT::Real
: Total time spannumTrials::Real
: Number of trials/iterationsdata_mean::Real
: Mean of input data (excluding NaN)data_sd::Real
: Standard deviation of input data (excluding NaN)freqlims
: Frequency limits for PSD analysisn_lags
: Number of lags for ACFfreq_idx
: Boolean mask for frequency selectiondims::Int
: Dimension along which to compute statisticsdistance_combined::Bool
: Whether to use combined distance metricweights::Vector{Real}
: Weights for combined distancedata_tau::Union{Real, Nothing}
: Pre-computed timescalemissing_mask::AbstractArray{Bool}
: Boolean mask indicating NaN positions
IntrinsicTimescales.Models.distance_function
— MethodModels.distance_function(model::OneTimescaleWithMissingModel, sum_stats, data_sum_stats)
Calculate the distance between summary statistics of simulated and observed data.
Arguments
model::OneTimescaleWithMissingModel
: Model instancesum_stats
: Summary statistics from simulated datadata_sum_stats
: Summary statistics from observed data
Returns
- Distance value based on model.distancemethod (:linear or :logarithmic) or combined distance if model.distancecombined is true
Notes
If distance_combined is true:
- For ACF: Combines ACF distance with fitted exponential decay timescale distance
- For PSD: Combines PSD distance with knee frequency timescale distance
IntrinsicTimescales.Models.generate_data
— MethodModels.generate_data(model::OneTimescaleWithMissingModel, theta)
Generate synthetic data from the Ornstein-Uhlenbeck process and apply missing data mask.
Arguments
model::OneTimescaleWithMissingModel
: Model instance containing simulation parameterstheta
: Vector containing single timescale parameter (τ)
Returns
- Synthetic time series data with NaN values at positions specified by model.missing_mask
Notes
- Generates complete OU process data
- Applies missing data mask from original data
- Returns data with same missing value pattern as input
IntrinsicTimescales.Models.int_fit
— Functionint_fit(model::OneTimescaleWithMissingModel, param_dict=Dict())
Perform inference using the specified fitting method.
Arguments
model::OneTimescaleWithMissingModel
: Model instanceparam_dict=nothing
: Optional dictionary of algorithm parameters. If nothing, uses defaults.
Returns
For ABC method:
posterior_samples
: Matrix of accepted parameter samplesposterior_MAP
: Maximum a posteriori estimateabc_record
: Full record of ABC iterations
For ADVI method:
ADVIResults
: Container with samples, MAP estimates, variances, and full chain
Notes
- For ABC: Uses Population Monte Carlo ABC with adaptive epsilon selection
- For ADVI: Uses Automatic Differentiation Variational Inference via Turing.jl
- Parameter dictionary can be customized for each method (see getparamdict_abc())
IntrinsicTimescales.Models.summary_stats
— MethodModels.summary_stats(model::OneTimescaleWithMissingModel, data)
Compute summary statistics (ACF or PSD) from time series data with missing values.
Arguments
model::OneTimescaleWithMissingModel
: Model instance specifying summary statistic typedata
: Time series data to analyze (may contain NaN)
Returns
For ACF (summary_method = :acf
):
- Mean autocorrelation function up to
n_lags
, computed with missing data handling
For PSD (summary_method = :psd
):
- Mean Lomb-Scargle periodogram within specified frequency range
Notes
- ACF uses compactime_missing for proper handling of NaN values
- PSD uses Lomb-Scargle periodogram for irregular sampling
IntrinsicTimescales.OneTimescaleWithMissing.combined_distance
— Methodcombined_distance(model, simulation_summary, data_summary, weights, data_tau, simulation_tau)
Calculate a weighted combination of summary statistic distance and timescale distance.
Arguments
model::OneTimescaleWithMissingModel
: Model instancesimulation_summary
: Summary statistics from simulated datadata_summary
: Summary statistics from observed dataweights
: Weight vector for combining distancesdata_tau
: Timescale extracted from observed datasimulation_tau
: Timescale extracted from simulated data
Returns
- Combined weighted distance value
Notes
Uses the model's distance_method (:linear or :logarithmic) for summary statistic comparison and linear distance for timescale comparison.
IntrinsicTimescales.OneTimescaleWithMissing.one_timescale_with_missing_model
— Methodone_timescale_with_missing_model(data, time, fit_method; kwargs...)
Construct a OneTimescaleWithMissingModel for time series analysis with missing data. See https://duodenum96.github.io/IntrinsicTimescales.jl/stable/onetimescalewith_missing/ for details and complete examples.
Arguments
data
: Input time series data (may contain NaN)time
: Time points corresponding to the datafit_method
: Fitting method to use (:abc or :advi)
Keyword Arguments
summary_method=:acf
: Summary statistic type (:psd or :acf)data_sum_stats=nothing
: Pre-computed summary statisticslags_freqs=nothing
: Custom lags or frequenciesprior=nothing
: Prior distribution(s) for parametersn_lags=nothing
: Number of lags for ACFdistance_method=nothing
: Distance metric typedt=time[2]-time[1]
: Time stepT=time[end]
: Total time spannumTrials=size(data,1)
: Number of trialsdata_mean=nanmean(data)
: Data mean (excluding NaN)data_sd=nanstd(data)
: Data standard deviation (excluding NaN)freqlims=nothing
: Frequency limits for PSDfreq_idx=nothing
: Frequency selection maskdims=ndims(data)
: Analysis dimensiondistance_combined=false
: Use combined distanceweights=[0.5, 0.5]
: Distance weightsdata_tau=nothing
: Pre-computed timescale
Returns
OneTimescaleWithMissingModel
: Model instance configured for specified analysis method
Notes
Four main usage patterns:
- ACF-based ABC/ADVI:
summary_method=:acf
,fit_method=:abc/:advi
- PSD-based ABC/ADVI:
summary_method=:psd
,fit_method=:abc/:advi
IntrinsicTimescales.OneTimescaleAndOscWithMissing
— ModuleOneTimescaleAndOscWithMissing
Module for handling time series analysis with both oscillations and missing data. Uses specialized methods for handling NaN values:
- For ACF: Uses compactime_missing for proper handling of gaps
- For PSD: Uses Lomb-Scargle periodogram for irregular sampling
IntrinsicTimescales.OneTimescaleAndOscWithMissing.OneTimescaleAndOscWithMissingModel
— TypeOneTimescaleAndOscWithMissingModel <: AbstractTimescaleModel
Model for inferring a single timescale from time series data with missing values. Parameters: [tau, freq, coeff] representing timescale, oscillation frequency, and oscillation coefficient.
Fields
data::AbstractArray{<:Real}
: Input time series data (may contain NaN)time::AbstractVector{<:Real}
: Time points corresponding to the datafit_method::Symbol
: Fitting method (:abc, :advi)summary_method::Symbol
: Summary statistic type (:psd or :acf)lags_freqs
: Lags (for ACF) or frequencies (for PSD)prior
: Prior distribution(s) for parametersdistance_method::Symbol
: Distance metric type (:linear or :logarithmic)data_sum_stats
: Pre-computed summary statisticsdt::Real
: Time step between observationsT::Real
: Total time spannumTrials::Real
: Number of trials/iterationsdata_mean::Real
: Mean of input data (excluding NaN)data_sd::Real
: Standard deviation of input data (excluding NaN)freqlims
: Frequency limits for PSD analysisn_lags
: Number of lags for ACFfreq_idx
: Boolean mask for frequency selectiondims::Int
: Dimension along which to compute statisticsdistance_combined::Bool
: Whether to use combined distance metricweights::Vector{Real}
: Weights for combined distancedata_tau::Union{Real, Nothing}
: Pre-computed timescaledata_osc::Union{Real, Nothing}
: Pre-computed oscillation frequencymissing_mask::AbstractArray{Bool}
: Boolean mask indicating NaN positions
IntrinsicTimescales.Models.distance_function
— MethodModels.distance_function(model::OneTimescaleAndOscWithMissingModel, sum_stats, data_sum_stats)
Compute distance between simulated and observed summary statistics.
Arguments
model::OneTimescaleAndOscWithMissingModel
: Model instance specifying distance configurationsum_stats
: Summary statistics from simulationdata_sum_stats
: Summary statistics from observed data
Returns
- Distance value based on model configuration
Notes
- If distancecombined=true: Uses combineddistance with both the estimated parameters and the full summary statistics.
- If distance_combined=false: Uses simple distance based on full summary statistics.
- Distance methods: :linear (Euclidean) or :logarithmic (log-space Euclidean)
IntrinsicTimescales.Models.generate_data
— MethodModels.generate_data(model::OneTimescaleAndOscWithMissingModel, theta)
Generate synthetic data from the Ornstein-Uhlenbeck process with oscillation and apply missing data mask.
Arguments
model::OneTimescaleAndOscWithMissingModel
: Model instance containing simulation parameterstheta
: Vector containing parameters [tau, freq, coeff]
Returns
- Synthetic time series data with oscillations and NaN values at positions specified by model.missing_mask
Notes
- Generates complete OU process data with oscillation
- Applies missing data mask from original data
- Returns data with same missing value pattern as input
IntrinsicTimescales.Models.int_fit
— Functionint_fit(model::OneTimescaleAndOscWithMissingModel, param_dict=Dict())
Perform inference using the specified fitting method.
Arguments
model::OneTimescaleAndOscWithMissingModel
: Model instanceparam_dict=Dict()
: Dictionary of algorithm parameters. If empty, uses defaults.
Returns
For ABC method:
abc_record
: Complete ABC record containing accepted samples, distances, and convergence info
For ADVI method:
ADVIResults
: Container with samples, MAP estimates, variances, and convergence information
Notes
- For ABC: Uses Population Monte Carlo ABC with adaptive epsilon selection
- For ADVI: Uses Automatic Differentiation Variational Inference via Turing.jl
- Default parameters available via getparamdictabc() and getparamdictadvi()
IntrinsicTimescales.Models.summary_stats
— MethodModels.summary_stats(model::OneTimescaleAndOscWithMissingModel, data)
Compute summary statistics (ACF or PSD) from time series data with missing values.
Arguments
model::OneTimescaleAndOscWithMissingModel
: Model instance specifying summary statistic typedata
: Time series data to analyze (may contain NaN)
Returns
For ACF (summary_method = :acf
):
- Mean autocorrelation function up to
n_lags
, computed with missing data handling
For PSD (summary_method = :psd
):
- Mean Lomb-Scargle periodogram within specified frequency range
Notes
- ACF uses compactime_missing for proper handling of NaN values
- PSD uses Lomb-Scargle periodogram for irregular sampling
IntrinsicTimescales.OneTimescaleAndOscWithMissing.combined_distance
— Methodcombined_distance(model::OneTimescaleAndOscWithMissingModel, simulation_summary, data_summary,
weights, distance_method, data_tau, simulation_tau, data_osc, simulation_osc)
Compute combined distance metric between simulated and observed data.
Arguments
model
: OneTimescaleAndOscWithMissingModel instancesimulation_summary
: Summary statistics from simulationdata_summary
: Summary statistics from observed dataweights
: Weights for combining distances (length 2 for ACF, length 3 for PSD)distance_method
: Distance metric type (:linear or :logarithmic)data_tau
: Timescale from observed datasimulation_tau
: Timescale from simulationdata_osc
: Oscillation frequency from observed data (used only for PSD)simulation_osc
: Oscillation frequency from simulation (used only for PSD)
Returns
For ACF:
- Weighted combination: weights[1] * summarydistance + weights[2] * taudistance
For PSD:
- Weighted combination: weights[1] * summarydistance + weights[2] * taudistance + weights[3] * osc_distance
Notes
- Ensure weights vector has correct length: 2 for ACF, 3 for PSD method
IntrinsicTimescales.OneTimescaleAndOscWithMissing.one_timescale_and_osc_with_missing_model
— Methodone_timescale_and_osc_with_missing_model(data, time, fit_method; kwargs...)
Construct a OneTimescaleAndOscWithMissingModel for inferring timescales and oscillations from data with missing values.
Arguments
data
: Input time series data (may contain NaN values)time
: Time points corresponding to the datafit_method
: Fitting method to use (:abc or :advi)
Keyword Arguments
summary_method=:psd
: Summary statistic type (:psd or :acf)data_sum_stats=nothing
: Pre-computed summary statisticslags_freqs=nothing
: Custom lags or frequenciesprior=nothing
: Prior distribution(s) for parametersn_lags=nothing
: Number of lags for ACFdistance_method=nothing
: Distance metric type (:linear or :logarithmic)dt=time[2]-time[1]
: Time step between observationsT=time[end]
: Total time spandata_mean=nanmean(data)
: Data mean (excluding NaN values)data_sd=nanstd(data)
: Data standard deviation (excluding NaN values)freqlims=nothing
: Frequency limits for PSD analysis (defaults to (0.5/1000, 100/1000) kHz)freq_idx=nothing
: Frequency selection maskdims=ndims(data)
: Dimension along which to compute statisticsnumTrials=size(data, setdiff([1,2], dims)[1])
: Number of trials/iterationsdistance_combined=false
: Whether to use combined distance metricweights=[0.5, 0.5]
: Weights for combined distance (length 2 for ACF, length 3 for PSD)data_tau=nothing
: Pre-computed timescale for combined distancedata_osc=nothing
: Pre-computed oscillation frequency for combined distance
Returns
OneTimescaleAndOscWithMissingModel
: Model instance configured for specified analysis method
Notes
Main usage patterns:
- ACF-based analysis:
summary_method=:acf
- Uses autocorrelation with missing data handling - PSD-based analysis:
summary_method=:psd
- Uses Lomb-Scargle periodogram for irregular sampling
Key differences from regular model:
- Automatically detects and handles NaN values in input data
- Uses nanmean/nanstd for robust statistics computation
- Applies specialized missing-data algorithms for summary statistics
- Preserves missing data pattern in synthetic data generation
For combined distance (distance_combined=true
):
- ACF method: Combines summary distance with timescale distance (2 weights)
- PSD method: Combines summary, timescale, and oscillation distances (3 weights)
IntrinsicTimescales.Plotting.acwplot
— Functionacwplot(acwresults::ACWResults; only_acf::Bool=false, only_psd::Bool=false, show::Bool=true)
Placeholder function for plotting autocorrelation function (ACF) and power spectral density (PSD) results.
This function is implemented in the IntPlottingExt
extension package, which is automatically loaded when Plots.jl
is available. The extension provides comprehensive visualization capabilities for ACW analysis results.
Functionality (available when Plots.jl is loaded):
- Plots autocorrelation function and/or power spectral density from
ACWResults
- Supports plotting either ACF alone, PSD alone, or both in a subplot layout
- ACF plots show individual traces in color with mean overlaid in black
- PSD plots use logarithmic scales for both axes
- Handles up to 2-dimensional ACF data
Arguments (when extension is loaded):
acwresults::ACWResults
: Container with ACF and/or PSD analysis resultsonly_acf::Bool=false
: If true, plot only the autocorrelation functiononly_psd::Bool=false
: If true, plot only the power spectral densityshow::Bool=true
: Whether to display the plot immediately
Requirements:
- Requires
Plots.jl
to be loaded for the extension to activate - Install with:
using Plots
orimport Plots
See IntPlottingExt
documentation for complete details.
IntrinsicTimescales.Plotting.posterior_predictive
— Functionposterior_predictive(container::Union{ABCResults, ADVIResults}, model::Models.AbstractTimescaleModel; show::Bool=true, n_samples::Int=100)
Placeholder function for posterior predictive check plotting.
This function is implemented in the IntPlottingExt
extension package, which is automatically loaded when Plots.jl
is available. The extension provides posterior predictive checking visualization for both ABC and ADVI inference results.
Functionality (available when Plots.jl is loaded):
- Creates posterior predictive check plots showing data vs. model predictions
- Works with both
ABCResults
andADVIResults
containers - Shows posterior predictive intervals with uncertainty bands
- Automatically handles ACF and PSD summary statistics with appropriate scaling
- Supports logarithmic scaling when the distance method is logarithmic
Arguments:
container::Union{ABCResults, ADVIResults}
: Results container from inferencemodel::Models.AbstractTimescaleModel
: Model used for inferenceshow::Bool=true
: Whether to display the plot immediatelyn_samples::Int=100
: Number of posterior samples to use for prediction
Requirements:
- Requires
Plots.jl
to be loaded for the extension to activate - Install with:
using Plots
orimport Plots
See IntPlottingExt
documentation for complete details.
Index
IntrinsicTimescales.ACW
IntrinsicTimescales.Distances
IntrinsicTimescales.IntrinsicTimescales
IntrinsicTimescales.OneTimescale
IntrinsicTimescales.OneTimescaleAndOscWithMissing
IntrinsicTimescales.OneTimescaleWithMissing
IntrinsicTimescales.OrnsteinUhlenbeck
IntrinsicTimescales.SummaryStats
IntrinsicTimescales.Utils
IntrinsicTimescales.ABC.ABCResults
IntrinsicTimescales.ACW.ACWResults
IntrinsicTimescales.Models.AbstractTimescaleModel
IntrinsicTimescales.Models.BaseModel
IntrinsicTimescales.OneTimescale.OneTimescaleModel
IntrinsicTimescales.OneTimescaleAndOsc.OneTimescaleAndOscModel
IntrinsicTimescales.OneTimescaleAndOscWithMissing.OneTimescaleAndOscWithMissingModel
IntrinsicTimescales.OneTimescaleWithMissing.OneTimescaleWithMissingModel
IntrinsicTimescales.TuringBackend.ADVIResults
IntrinsicTimescales.ABC.abc_results
IntrinsicTimescales.ABC.basic_abc
IntrinsicTimescales.ABC.calc_weights
IntrinsicTimescales.ABC.compute_adaptive_alpha
IntrinsicTimescales.ABC.draw_theta_pmc
IntrinsicTimescales.ABC.effective_sample_size
IntrinsicTimescales.ABC.find_MAP
IntrinsicTimescales.ABC.get_param_dict_abc
IntrinsicTimescales.ABC.pmc_abc
IntrinsicTimescales.ABC.select_epsilon
IntrinsicTimescales.ABC.weighted_covar
IntrinsicTimescales.ACW.acw
IntrinsicTimescales.Distances.linear_distance
IntrinsicTimescales.Distances.logarithmic_distance
IntrinsicTimescales.Models.check_acwtypes
IntrinsicTimescales.Models.check_inputs
IntrinsicTimescales.Models.check_model_inputs
IntrinsicTimescales.Models.distance_function
IntrinsicTimescales.Models.distance_function
IntrinsicTimescales.Models.distance_function
IntrinsicTimescales.Models.distance_function
IntrinsicTimescales.Models.distance_function
IntrinsicTimescales.Models.draw_theta
IntrinsicTimescales.Models.generate_data
IntrinsicTimescales.Models.generate_data
IntrinsicTimescales.Models.generate_data
IntrinsicTimescales.Models.generate_data
IntrinsicTimescales.Models.generate_data
IntrinsicTimescales.Models.generate_data_and_reduce
IntrinsicTimescales.Models.int_fit
IntrinsicTimescales.Models.int_fit
IntrinsicTimescales.Models.int_fit
IntrinsicTimescales.Models.int_fit
IntrinsicTimescales.Models.int_fit
IntrinsicTimescales.Models.summary_stats
IntrinsicTimescales.Models.summary_stats
IntrinsicTimescales.Models.summary_stats
IntrinsicTimescales.Models.summary_stats
IntrinsicTimescales.Models.summary_stats
IntrinsicTimescales.OneTimescale.combined_distance
IntrinsicTimescales.OneTimescale.one_timescale_model
IntrinsicTimescales.OneTimescaleAndOsc.combined_distance
IntrinsicTimescales.OneTimescaleAndOsc.one_timescale_and_osc_model
IntrinsicTimescales.OneTimescaleAndOscWithMissing.combined_distance
IntrinsicTimescales.OneTimescaleAndOscWithMissing.one_timescale_and_osc_with_missing_model
IntrinsicTimescales.OneTimescaleWithMissing.combined_distance
IntrinsicTimescales.OneTimescaleWithMissing.one_timescale_with_missing_model
IntrinsicTimescales.OrnsteinUhlenbeck.generate_ou_process
IntrinsicTimescales.OrnsteinUhlenbeck.generate_ou_process_sciml
IntrinsicTimescales.OrnsteinUhlenbeck.generate_ou_with_oscillation
IntrinsicTimescales.Plotting.acwplot
IntrinsicTimescales.Plotting.posterior_predictive
IntrinsicTimescales.SummaryStats._comp_psd_lombscargle
IntrinsicTimescales.SummaryStats.acf_statsmodels
IntrinsicTimescales.SummaryStats.acovf
IntrinsicTimescales.SummaryStats.bat_autocorr
IntrinsicTimescales.SummaryStats.bat_autocorr
IntrinsicTimescales.SummaryStats.bat_integrated_autocorr_len
IntrinsicTimescales.SummaryStats.bat_integrated_autocorr_weight
IntrinsicTimescales.SummaryStats.comp_ac_fft
IntrinsicTimescales.SummaryStats.comp_ac_fft
IntrinsicTimescales.SummaryStats.comp_ac_time
IntrinsicTimescales.SummaryStats.comp_ac_time
IntrinsicTimescales.SummaryStats.comp_ac_time_missing
IntrinsicTimescales.SummaryStats.comp_cc
IntrinsicTimescales.SummaryStats.comp_psd
IntrinsicTimescales.SummaryStats.comp_psd_adfriendly
IntrinsicTimescales.SummaryStats.comp_psd_lombscargle
IntrinsicTimescales.SummaryStats.prepare_lombscargle
IntrinsicTimescales.TuringBackend.create_turing_model
IntrinsicTimescales.TuringBackend.fit_vi
IntrinsicTimescales.TuringBackend.get_param_dict_advi
IntrinsicTimescales.Utils.acw0
IntrinsicTimescales.Utils.acw50
IntrinsicTimescales.Utils.acw_romberg
IntrinsicTimescales.Utils.acweuler
IntrinsicTimescales.Utils.expdecay
IntrinsicTimescales.Utils.expdecay_3_parameters
IntrinsicTimescales.Utils.find_knee_frequency
IntrinsicTimescales.Utils.find_oscillation_peak
IntrinsicTimescales.Utils.fit_expdecay
IntrinsicTimescales.Utils.fit_expdecay_3_parameters
IntrinsicTimescales.Utils.fit_gaussian
IntrinsicTimescales.Utils.fooof_fit
IntrinsicTimescales.Utils.gaussian
IntrinsicTimescales.Utils.get_slices
IntrinsicTimescales.Utils.lorentzian
IntrinsicTimescales.Utils.lorentzian_initial_guess
IntrinsicTimescales.Utils.lorentzian_with_exponent
IntrinsicTimescales.Utils.residual_expdecay!
IntrinsicTimescales.Utils.stack_and_reshape