stats

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BhattacharyyaDistanceFunc

func BhattacharyyaDistanceFunc(p, q []float64) float64

BhattacharyyaDistanceFunc calculates Bhattacharyya distance

func BrayCurtisDistanceFunc

func BrayCurtisDistanceFunc(a, b []float64) float64

BrayCurtisDistanceFunc calculates Bray-Curtis distance

func CanberraDistanceFunc

func CanberraDistanceFunc(a, b []float64) float64

CanberraDistanceFunc calculates Canberra distance

func ChebyshevDistanceFunc

func ChebyshevDistanceFunc(a, b []float64) float64

ChebyshevDistanceFunc calculates Chebyshev distance (L∞ norm)

func CosineDistanceFunc

func CosineDistanceFunc(a, b []float64) float64

CosineDistanceFunc calculates cosine distance (1 - cosine similarity)

func CosineSimilarityFunc

func CosineSimilarityFunc(a, b []float64) float64

CosineSimilarityFunc calculates cosine similarity between two vectors

func DistanceMatrix

func DistanceMatrix(data [][]float64, metric DistanceMetric) [][]float64

DistanceMatrix computes pairwise distances between all vectors

func EarthMoversDistanceFunc

func EarthMoversDistanceFunc(a, b []float64) float64

EarthMoversDistanceFunc calculates Earth Mover's Distance (Wasserstein distance) This is a simplified 1D implementation

func EuclideanDistanceFunc

func EuclideanDistanceFunc(a, b []float64) float64

EuclideanDistanceFunc calculates Euclidean distance between two points

func GetAlignmentQuality

func GetAlignmentQuality(dtwResult *DTWResult) map[string]float64

GetAlignmentQuality calculates quality metrics (wrapper for DTW function)

func GetDistanceMetricName

func GetDistanceMetricName(metric DistanceMetric) string

GetDistanceMetricName returns human-readable name for distance metric

func GetEntropyTypeName

func GetEntropyTypeName(entropyType EntropyType) string

GetEntropyTypeName returns the human-readable name of the entropy type

func GetMomentTypeName

func GetMomentTypeName(momentType MomentType) string

GetMomentTypeName returns the human-readable name of the moment type

func HammingDistanceFunc

func HammingDistanceFunc(a, b []float64) float64

HammingDistanceFunc calculates Hamming distance (for binary vectors)

func HellingerDistanceFunc

func HellingerDistanceFunc(p, q []float64) float64

HellingerDistanceFunc calculates Hellinger distance

func IsValidDistance

func IsValidDistance(a, b []float64, metric DistanceMetric) bool

IsValidDistance checks if two vectors can be compared with the given metric

func JaccardDistanceFunc

func JaccardDistanceFunc(a, b []float64) float64

JaccardDistanceFunc calculates Jaccard distance (1 - Jaccard similarity)

func JensenShannonDistanceFunc

func JensenShannonDistanceFunc(p, q []float64) float64

JensenShannonDistanceFunc calculates Jensen-Shannon distance

func KLDivergenceFunc

func KLDivergenceFunc(p, q []float64) float64

KLDivergenceFunc calculates Kullback-Leibler divergence (requires probability distributions)

func MahalanobisDistanceFunc

func MahalanobisDistanceFunc(a, b []float64) float64

MahalanobisDistanceFunc calculates Mahalanobis distance Note: This is a simplified version that assumes identity covariance matrix For full implementation, pass covariance matrix as additional parameter

func ManhattanDistanceFunc

func ManhattanDistanceFunc(a, b []float64) float64

ManhattanDistanceFunc calculates Manhattan (L1) distance between two points

func MinkowskiDistanceFunc

func MinkowskiDistanceFunc(a, b []float64, p float64) float64

MinkowskiDistanceFunc calculates Minkowski distance with parameter p

func NearestNeighbors

func NearestNeighbors(query []float64, data [][]float64, k int, metric DistanceMetric) []int

NearestNeighbors finds k nearest neighbors for a query point

func PearsonCorrelationFunc

func PearsonCorrelationFunc(a, b []float64) float64

PearsonCorrelationFunc calculates Pearson correlation coefficient

func PearsonDistanceFunc

func PearsonDistanceFunc(a, b []float64) float64

PearsonDistanceFunc calculates Pearson correlation distance (1 - |correlation|)

Types

type AlignPoint

type AlignPoint struct {
	QueryIndex int     `json:"query_index"` // Index in query sequence
	RefIndex   int     `json:"ref_index"`   // Index in reference sequence
	Cost       float64 `json:"cost"`        // Local cost at this point
}

AlignPoint represents a point in the alignment path

type AlignmentAnalyzer

type AlignmentAnalyzer struct {
	// contains filtered or unexported fields
}

AlignmentAnalyzer provides comprehensive audio alignment capabilities WHY: Audio alignment is crucial for fingerprint matching, synchronization, and determining similarity between audio segments of different lengths

func NewAlignmentAnalyzer

func NewAlignmentAnalyzer(method AlignmentMethod, maxLag, sampleRate, hopSize, windowSize int, confidenceThresh float64) *AlignmentAnalyzer

func (*AlignmentAnalyzer) AlignAudio

func (aa *AlignmentAnalyzer) AlignAudio(queryPCM, referencePCM []float64, sampleRate int) (*AlignmentResult, error)

AlignAudio aligns two audio signals using energy-based features

func (*AlignmentAnalyzer) AlignFeatures

func (aa *AlignmentAnalyzer) AlignFeatures(query, reference [][]float64, sampleRate int) (*AlignmentResult, error)

AlignFeatures aligns two feature sequences (e.g., MFCC, chroma)

func (*AlignmentAnalyzer) AnalyzeAlignmentConsistency

func (aa *AlignmentAnalyzer) AnalyzeAlignmentConsistency(query, reference [][]float64, sampleRate int, numTrials int) (*AlignmentStats, error)

AnalyzeAlignmentConsistency analyzes consistency across multiple alignment attempts

func (*AlignmentAnalyzer) FindBestAlignment

func (aa *AlignmentAnalyzer) FindBestAlignment(query, reference [][]float64, sampleRate int) (*AlignmentResult, error)

FindBestAlignment tries multiple methods and returns the best result

type AlignmentMethod

type AlignmentMethod int

AlignmentMethod defines different alignment approaches

const (
	AlignmentDTW AlignmentMethod = iota
	AlignmentCrossCorrelation
	AlignmentPhaseCorrelation
	AlignmentHybrid
)

type AlignmentResult

type AlignmentResult struct {
	// Primary alignment information
	Method        AlignmentMethod `json:"method"`
	Offset        int             `json:"offset"`         // Sample offset (negative = query is delayed)
	OffsetSeconds float64         `json:"offset_seconds"` // Offset in seconds
	Confidence    float64         `json:"confidence"`     // Alignment confidence (0-1)
	Similarity    float64         `json:"similarity"`     // Overall similarity score

	// DTW-specific results
	DTWResult *DTWResult `json:"dtw_result,omitempty"`

	// Cross-correlation results
	CrossCorrResult *CorrelationResult `json:"cross_corr_result,omitempty"`

	// Quality metrics
	AlignmentQuality float64 `json:"alignment_quality"` // Quality of alignment
	NoiseLevel       float64 `json:"noise_level"`       // Estimated noise level
	Stability        float64 `json:"stability"`         // Stability of alignment

	// Analysis metadata
	QueryLength     int     `json:"query_length"`
	ReferenceLength int     `json:"reference_length"`
	ProcessingTime  float64 `json:"processing_time"` // Processing time (ms)
	SampleRate      int     `json:"sample_rate"`
}

AlignmentResult contains comprehensive alignment analysis

type AlignmentStats

type AlignmentStats struct {
	MeanOffset   float64 `json:"mean_offset"`
	StdDevOffset float64 `json:"stddev_offset"`
	MedianOffset float64 `json:"median_offset"`
	OffsetRange  float64 `json:"offset_range"`
	Consistency  float64 `json:"consistency"` // How consistent are multiple alignments
}

AlignmentStats provides statistical analysis of alignment results

type AutoCorrelation

type AutoCorrelation struct {
	// contains filtered or unexported fields
}

AutoCorrelation computes auto-correlation of a signal

func NewAutoCorrelation

func NewAutoCorrelation(maxLag int) *AutoCorrelation

NewAutoCorrelation creates a new auto-correlation calculator

func (*AutoCorrelation) Compute

func (ac *AutoCorrelation) Compute(signal []float64) (*CorrelationResult, error)

Compute calculates auto-correlation of a signal

func (*AutoCorrelation) SetParameters

func (ac *AutoCorrelation) SetParameters(corrType CorrelationType, method CorrelationMethod)

SetParameters updates the correlation parameters

type Cluster

type Cluster struct {
	ID       int         `json:"id"`
	Center   []float64   `json:"center"`   // Cluster centroid
	Points   [][]float64 `json:"points"`   // Points in this cluster
	Indices  []int       `json:"indices"`  // Original indices of points
	Size     int         `json:"size"`     // Number of points in cluster
	Variance float64     `json:"variance"` // Within-cluster variance
	Radius   float64     `json:"radius"`   // Maximum distance from center
}

Cluster represents a cluster of data points

type Clustering

type Clustering struct {
	// contains filtered or unexported fields
}

Clustering implements various clustering algorithms for audio feature analysis

References:

  • Jain, A. K., & Dubes, R. C. (1988). "Algorithms for clustering data"
  • MacQueen, J. (1967). "Some methods for classification and analysis of multivariate observations"
  • Arthur, D., & Vassilvitskii, S. (2007). "k-means++: The advantages of careful seeding"
  • Ester, M., et al. (1996). "A density-based algorithm for discovering clusters in large spatial databases with noise"
  • Rousseeuw, P. J. (1987). "Silhouettes: a graphical aid to the interpretation and validation of cluster analysis"

func NewClustering

func NewClustering() *Clustering

NewClustering creates a new clustering analyzer with default parameters

func NewClusteringWithParams

func NewClusteringWithParams(params ClusteringParams) *Clustering

NewClusteringWithParams creates a clustering analyzer with custom parameters

func (*Clustering) Fit

func (c *Clustering) Fit(data [][]float64) (*ClusteringResult, error)

Fit performs clustering on the input data

type ClusteringAlgorithm

type ClusteringAlgorithm int

ClusteringAlgorithm represents different clustering methods

const (
	KMeans ClusteringAlgorithm = iota
	KMedoids
	HierarchicalAgglomerative
	DBSCAN
	GaussianMixture
)

type ClusteringParams

type ClusteringParams struct {
	NumClusters   int                 `json:"num_clusters"`
	MaxIterations int                 `json:"max_iterations"`
	Tolerance     float64             `json:"tolerance"`
	Algorithm     ClusteringAlgorithm `json:"algorithm"`
	Distance      DistanceMetric      `json:"distance"`
	Linkage       LinkageCriterion    `json:"linkage"`

	// DBSCAN specific parameters
	Epsilon   float64 `json:"epsilon"`    // Maximum distance between points
	MinPoints int     `json:"min_points"` // Minimum points to form cluster

	// Initialization parameters
	InitMethod string `json:"init_method"` // "random", "kmeans++", "manual"
	RandomSeed int64  `json:"random_seed"`

	// Convergence parameters
	RelativeTolerance bool `json:"relative_tolerance"`
}

ClusteringParams contains parameters for clustering algorithms

type ClusteringResult

type ClusteringResult struct {
	Clusters           []Cluster   `json:"clusters"`
	Labels             []int       `json:"labels"`            // Cluster assignment for each point
	Centers            [][]float64 `json:"centers"`           // Cluster centers
	Inertia            float64     `json:"inertia"`           // Total within-cluster sum of squares
	SilhouetteScore    float64     `json:"silhouette_score"`  // Overall silhouette coefficient
	DaviesBouldinIndex float64     `json:"davies_bouldin"`    // Davies-Bouldin index
	CalinskiHarabasz   float64     `json:"calinski_harabasz"` // Calinski-Harabasz index
	NumClusters        int         `json:"num_clusters"`
	Converged          bool        `json:"converged"`
	Iterations         int         `json:"iterations"`
}

ClusteringResult contains the results of clustering analysis

type CorrelationMethod

type CorrelationMethod int

CorrelationMethod represents different computational approaches

const (
	// Direct time-domain calculation
	TimeDomain CorrelationMethod = iota

	// FFT-based frequency domain (faster for large signals)
	FrequencyDomain

	// Sliding window approach
	SlidingWindow
)

type CorrelationResult

type CorrelationResult struct {
	// Primary correlation values
	Correlations []float64 `json:"correlations"`
	Lags         []int     `json:"lags"`

	// Peak correlation information
	PeakCorrelation float64 `json:"peak_correlation"`
	PeakLag         int     `json:"peak_lag"`
	PeakIndex       int     `json:"peak_index"`

	// Statistical significance
	PValue          float64 `json:"p_value"`
	IsSignificant   bool    `json:"is_significant"`
	ConfidenceLevel float64 `json:"confidence_level"`

	// Correlation quality metrics
	SNR            float64 `json:"snr"`              // Signal-to-noise ratio
	Sharpness      float64 `json:"sharpness"`        // Peak sharpness
	SecondPeak     float64 `json:"second_peak"`      // Second highest peak
	PeakToSidelobe float64 `json:"peak_to_sidelobe"` // Peak-to-sidelobe ratio

	// Computational details
	Method          CorrelationMethod `json:"method"`
	Type            CorrelationType   `json:"type"`
	MaxLag          int               `json:"max_lag"`
	OverlapLength   int               `json:"overlap_length"`
	ComputationTime float64           `json:"computation_time"` // in milliseconds
}

CorrelationResult contains comprehensive correlation analysis results

type CorrelationType

type CorrelationType int

CorrelationType represents different types of correlation calculations

const (
	// Pearson correlation (linear correlation)
	Pearson CorrelationType = iota

	// Spearman rank correlation
	Spearman

	// Kendall tau correlation
	Kendall

	// Normalized cross-correlation
	NormalizedCrossCorrelation

	// Zero-normalized cross-correlation
	ZeroNormalizedCrossCorrelation
)

type CrossCorrelation

type CrossCorrelation struct {
	// contains filtered or unexported fields
}

CrossCorrelation computes cross-correlation between two signals

References: - Rabiner, L., Schafer, R. (1978). "Digital Processing of Speech Signals" - Oppenheim, A.V., Schafer, R.W. (2010). "Discrete-Time Signal Processing" - Lewis, J.P. (1995). "Fast Template Matching" - Knuth, D.E. (1998). "The Art of Computer Programming, Vol. 2"

Cross-correlation is fundamental for: - Audio alignment and synchronization - Echo detection and cancellation - Pattern matching in signals - Time delay estimation - Audio fingerprint matching

func NewCrossCorrelation

func NewCrossCorrelation(maxLag int) *CrossCorrelation

NewCrossCorrelation creates a new cross-correlation calculator with default settings

func NewCrossCorrelationWithParams

func NewCrossCorrelationWithParams(maxLag int, corrType CorrelationType, method CorrelationMethod) *CrossCorrelation

NewCrossCorrelationWithParams creates a cross-correlation calculator with custom parameters

func (*CrossCorrelation) Compute

func (cc *CrossCorrelation) Compute(signal1, signal2 []float64) (*CorrelationResult, error)

Compute calculates cross-correlation between two signals with comprehensive analysis

type DTWAlignment

type DTWAlignment struct {
	// contains filtered or unexported fields
}

DTWAlignment represents Dynamic Time Warping alignment WHY: DTW is essential for aligning audio sequences of different lengths, crucial for audio fingerprint matching and similarity computation

func NewDTWAlignment

func NewDTWAlignment() *DTWAlignment

NewDTWAlignment creates a new DTW alignment instance

func NewDTWAlignmentWithParams

func NewDTWAlignmentWithParams(constraintBand int, stepPattern string, metric DistanceMetric) *DTWAlignment

NewDTWAlignmentWithParams creates DTW with custom parameters

func (*DTWAlignment) Align

func (dtw *DTWAlignment) Align(query, reference [][]float64) (*DTWResult, error)

Align performs DTW alignment between two sequences

func (*DTWAlignment) AlignVectors

func (dtw *DTWAlignment) AlignVectors(query, reference []float64) (*DTWResult, error)

AlignVectors aligns two 1D feature vectors

func (*DTWAlignment) ConstrainedAlign

func (dtw *DTWAlignment) ConstrainedAlign(query, reference [][]float64, startConstraint, endConstraint [2]int) (*DTWResult, error)

ConstrainedAlign performs DTW with global path constraints

func (*DTWAlignment) GetAlignmentQuality

func (dtw *DTWAlignment) GetAlignmentQuality(result *DTWResult) map[string]float64

GetAlignmentQuality calculates quality metrics for the alignment

func (*DTWAlignment) OptimizeStepPattern

func (dtw *DTWAlignment) OptimizeStepPattern(query, reference [][]float64) (string, error)

OptimizeStepPattern selects best step pattern for given data

type DTWResult

type DTWResult struct {
	Distance    float64      `json:"distance"`     // Total DTW distance
	Path        []AlignPoint `json:"path"`         // Optimal alignment path
	CostMatrix  [][]float64  `json:"cost_matrix"`  // DTW cost matrix
	QueryLength int          `json:"query_length"` // Length of query sequence
	RefLength   int          `json:"ref_length"`   // Length of reference sequence
	Normalized  bool         `json:"normalized"`   // Whether distance is normalized
	StepPattern string       `json:"step_pattern"` // Step pattern used
	Constraint  int          `json:"constraint"`   // Band constraint used
}

DTWResult contains DTW alignment results

type DistanceFunction

type DistanceFunction func(a, b []float64) float64

DistanceFunction is a function type for computing distance between two vectors

func GetDistanceFunction

func GetDistanceFunction(metric DistanceMetric) DistanceFunction

GetDistanceFunction returns the appropriate distance function for the given metric

type DistanceMetric

type DistanceMetric int

DistanceMetric represents different distance/similarity measures

const (
	EuclideanDistance DistanceMetric = iota
	ManhattanDistance
	CosineDistance
	PearsonDistance
	MahalanobisDistance
)

type Entropy

type Entropy struct {
	// contains filtered or unexported fields
}

Entropy implements various entropy measures for statistical analysis of audio signals

References: - Shannon, C.E. (1948). "A Mathematical Theory of Communication" - Rényi, A. (1961). "On Measures of Entropy and Information" - Tsallis, C. (1988). "Possible generalization of Boltzmann-Gibbs statistics" - Cover, T.M., Thomas, J.A. (2006). "Elements of Information Theory" - Beirlant, J., et al. (1997). "Nonparametric entropy estimation: An overview" - Paninski, L. (2003). "Estimation of entropy and mutual information"

Entropy measures the amount of information or uncertainty in a dataset: - Higher entropy = more unpredictable/random - Lower entropy = more predictable/structured

Applications in audio processing: - Signal complexity analysis - Audio texture characterization - Noise level estimation - Compression efficiency prediction - Audio event detection

func NewEntropy

func NewEntropy() *Entropy

NewEntropy creates a new entropy analyzer with default parameters

func NewEntropyWithParams

func NewEntropyWithParams(params EntropyParams) *Entropy

NewEntropyWithParams creates an entropy analyzer with custom parameters

func (*Entropy) Analyze

func (e *Entropy) Analyze(data []float64) (*EntropyResult, error)

Analyze computes comprehensive entropy analysis for the input data

func (*Entropy) CalculateSpecificEntropy

func (e *Entropy) CalculateSpecificEntropy(data []float64, entropyType EntropyType) (float64, error)

CalculateSpecificEntropy computes a specific type of entropy

func (*Entropy) GetParameters

func (e *Entropy) GetParameters() EntropyParams

GetParameters returns the current parameters

func (*Entropy) SetParameters

func (e *Entropy) SetParameters(params EntropyParams)

SetParameters updates the entropy calculation parameters

type EntropyParams

type EntropyParams struct {
	NumBins         int             `json:"num_bins"`
	HistogramMethod HistogramMethod `json:"histogram_method"`
	RenyiAlpha      float64         `json:"renyi_alpha"` // Parameter for Rényi entropy
	TsallisQ        float64         `json:"tsallis_q"`   // Parameter for Tsallis entropy

	// Normalization options
	NormalizeEntropy bool    `json:"normalize_entropy"`
	BaseLog          float64 `json:"base_log"` // Base for logarithm (2, e, 10)

	// Smoothing options
	SmoothHistogram bool    `json:"smooth_histogram"`
	SmoothingKernel string  `json:"smoothing_kernel"` // "gaussian", "uniform"
	SmoothingWidth  float64 `json:"smoothing_width"`

	// Boundary handling
	BoundaryMethod string  `json:"boundary_method"` // "reflect", "extend", "zero"
	MinProbability float64 `json:"min_probability"` // Minimum probability for log calculation
}

EntropyParams contains parameters for entropy calculation

type EntropyResult

type EntropyResult struct {
	// Primary entropy measures
	ShannonEntropy   float64 `json:"shannon_entropy"`
	RenyiEntropy     float64 `json:"renyi_entropy"`
	TsallisEntropy   float64 `json:"tsallis_entropy"`
	HartleyEntropy   float64 `json:"hartley_entropy"`
	CollisionEntropy float64 `json:"collision_entropy"`
	MinEntropy       float64 `json:"min_entropy"`

	// Normalized entropy measures (0-1 range)
	NormalizedShannon float64 `json:"normalized_shannon"`
	NormalizedRenyi   float64 `json:"normalized_renyi"`

	// Entropy rate and conditional entropy
	EntropyRate        float64 `json:"entropy_rate"`
	ConditionalEntropy float64 `json:"conditional_entropy"`

	// Histogram information
	Histogram       []float64       `json:"histogram"`
	BinEdges        []float64       `json:"bin_edges"`
	BinCenters      []float64       `json:"bin_centers"`
	NumBins         int             `json:"num_bins"`
	HistogramMethod HistogramMethod `json:"histogram_method"`

	// Statistical measures
	Variance float64 `json:"variance"`
	Skewness float64 `json:"skewness"`
	Kurtosis float64 `json:"kurtosis"`

	// Parameters used
	RenyiAlpha float64 `json:"renyi_alpha"`
	TsallisQ   float64 `json:"tsallis_q"`

	// Data characteristics
	NumSamples     int     `json:"num_samples"`
	DataRange      float64 `json:"data_range"`
	EffectiveRange float64 `json:"effective_range"` // Range containing 95% of data
}

EntropyResult contains comprehensive entropy analysis results

type EntropyType

type EntropyType int

EntropyType represents different types of entropy measures

const (
	// Shannon entropy (information entropy)
	Shannon EntropyType = iota

	// Rényi entropy (generalized entropy)
	Renyi

	// Tsallis entropy (non-extensive entropy)
	Tsallis

	// Hartley entropy (max entropy)
	Hartley

	// Collision entropy (order-2 Rényi entropy)
	Collision

	// Min entropy (worst-case entropy)
	MinEntropy
)

type ExtremeInfo

type ExtremeInfo struct {
	Min           float64   `json:"min"`
	Max           float64   `json:"max"`
	Range         float64   `json:"range"`
	LowerOutliers []float64 `json:"lower_outliers"` // Values < Q1 - 1.5*IQR
	UpperOutliers []float64 `json:"upper_outliers"` // Values > Q3 + 1.5*IQR
	LowerExtreme  []float64 `json:"lower_extreme"`  // Values < Q1 - 3*IQR
	UpperExtreme  []float64 `json:"upper_extreme"`  // Values > Q3 + 3*IQR
}

ExtremeInfo contains information about extreme values

type HistogramMethod

type HistogramMethod int

HistogramMethod represents different histogram construction methods

const (
	// Fixed number of bins
	FixedBins HistogramMethod = iota

	// Sturges' rule: k = log2(n) + 1
	Sturges

	// Scott's rule: bin width = 3.49σn^(-1/3)
	Scott

	// Freedman-Diaconis rule: bin width = 2*IQR*n^(-1/3)
	FreedmanDiaconis

	// Square root rule: k = sqrt(n)
	SquareRoot

	// Doane's rule: extension of Sturges for non-normal data
	Doane
)

type LinkageCriterion

type LinkageCriterion int

LinkageCriterion for hierarchical clustering

const (
	SingleLinkage LinkageCriterion = iota
	CompleteLinkage
	AverageLinkage
	WardLinkage
)

type MomentParams

type MomentParams struct {
	MaxOrder         int  `json:"max_order"`         // Maximum moment order to compute
	ComputeLMoments  bool `json:"compute_l_moments"` // Whether to compute L-moments
	ComputeCumulants bool `json:"compute_cumulants"` // Whether to compute cumulants

	// Numerical stability options
	UseWelfordMethod  bool    `json:"use_welford_method"`  // Use Welford's algorithm for numerical stability
	ClampLargeMoments bool    `json:"clamp_large_moments"` // Clamp extremely large moments
	MaxMomentValue    float64 `json:"max_moment_value"`    // Maximum allowed moment value

	// Distribution fitting options
	FitDistribution bool `json:"fit_distribution"` // Attempt to fit known distributions
	TestNormality   bool `json:"test_normality"`   // Test for normality using moments

	// Robust estimation options
	UseRobustEstimation bool    `json:"use_robust_estimation"` // Use robust moment estimation
	TrimProportion      float64 `json:"trim_proportion"`       // Proportion to trim for robust estimation
}

MomentParams contains parameters for moment calculation

type MomentResult

type MomentResult struct {
	// Basic descriptive statistics
	Mean     float64 `json:"mean"`     // First raw moment (μ₁)
	Variance float64 `json:"variance"` // Second central moment (σ²)
	StdDev   float64 `json:"std_dev"`  // Standard deviation (σ)
	Skewness float64 `json:"skewness"` // Third standardized moment
	Kurtosis float64 `json:"kurtosis"` // Fourth standardized moment (excess)

	// Raw moments about origin
	RawMoments []float64 `json:"raw_moments"` // μ'ᵣ = E[Xʳ]

	// Central moments about mean
	CentralMoments []float64 `json:"central_moments"` // μᵣ = E[(X-μ)ʳ]

	// Standardized moments
	StandardizedMoments []float64 `json:"standardized_moments"` // μᵣ/σʳ

	// Absolute moments
	AbsoluteMoments []float64 `json:"absolute_moments"` // E[|X-μ|ʳ]

	// Higher order moment statistics
	Hyperskewness float64 `json:"hyperskewness"` // Fifth standardized moment
	Hyperkurtosis float64 `json:"hyperkurtosis"` // Sixth standardized moment

	// Distribution shape measures
	CoefficientOfVariation float64 `json:"coefficient_of_variation"` // σ/μ
	StandardError          float64 `json:"standard_error"`           // σ/√n

	// Moment-based distribution measures
	PearsonMomentSkewness float64 `json:"pearson_moment_skewness"` // 3(μ-median)/σ
	BowleySkewness        float64 `json:"bowley_skewness"`         // Quartile-based skewness

	// L-moments (linear combinations of order statistics)
	LMoments      []float64 `json:"l_moments"`       // L₁, L₂, L₃, L₄, ...
	LMomentRatios []float64 `json:"l_moment_ratios"` // τ₂, τ₃, τ₄, ... (L-CV, L-skew, L-kurt)

	// Cumulants (moment-generating function derivatives)
	Cumulants []float64 `json:"cumulants"` // κ₁, κ₂, κ₃, κ₄, ...

	// Sample properties
	NumSamples  int     `json:"num_samples"`
	SampleRange float64 `json:"sample_range"`

	// Moment convergence information
	MomentOrder int    `json:"moment_order"` // Highest computed moment order
	Convergence []bool `json:"convergence"`  // Whether each moment converged
}

MomentResult contains comprehensive moment analysis results

type MomentType

type MomentType int

MomentType represents different types of moments

const (
	// Raw moments about the origin
	RawMoment MomentType = iota

	// Central moments about the mean
	CentralMoment

	// Standardized moments (normalized by standard deviation)
	StandardizedMoment

	// Absolute moments
	AbsoluteMoment

	// Logarithmic moments
	LogarithmicMoment
)

type Moments

type Moments struct {
	// contains filtered or unexported fields
}

Moments implements comprehensive statistical moment analysis for audio signals

References: - Kendall, M., Stuart, A. (1977). "The Advanced Theory of Statistics, Volume 1" - Hosking, J.R.M. (1990). "L-moments: Analysis and Estimation of Distributions" - Serfling, R., Xiao, P. (2007). "A contribution to multivariate L-moments" - Cramér, H. (1946). "Mathematical Methods of Statistics" - Pearson, K. (1895). "Contributions to the Mathematical Theory of Evolution" - Fisher, R.A. (1930). "The moments of the distribution for normal samples" - Welford, B.P. (1962). "Note on a method for calculating corrected sums of squares"

Moments provide fundamental characterization of probability distributions: - 1st moment: Location (mean) - 2nd moment: Spread (variance) - 3rd moment: Asymmetry (skewness) - 4th moment: Tail behavior (kurtosis) - Higher moments: Fine distribution details

Applications in audio processing: - Signal characterization and classification - Noise analysis and detection - Audio texture analysis - Distribution fitting and modeling - Anomaly detection in audio streams

func NewMoments

func NewMoments() *Moments

NewMoments creates a new moment analyzer with default parameters

func NewMomentsWithParams

func NewMomentsWithParams(params MomentParams) *Moments

NewMomentsWithParams creates a moment analyzer with custom parameters

func (*Moments) Analyze

func (m *Moments) Analyze(data []float64) (*MomentResult, error)

Analyze computes comprehensive moment analysis for the input data

func (*Moments) CalculateSpecificMoment

func (m *Moments) CalculateSpecificMoment(data []float64, momentType MomentType, order int) (float64, error)

CalculateSpecificMoment computes a specific moment of given type and order

func (*Moments) GetParameters

func (m *Moments) GetParameters() MomentParams

GetParameters returns the current parameters

func (*Moments) SetParameters

func (m *Moments) SetParameters(params MomentParams)

SetParameters updates the moment calculation parameters

type PercentileMethod

type PercentileMethod int

PercentileMethod represents different methods for calculating percentiles

const (
	// Linear interpolation between closest ranks (R-6, Excel, most common)
	Linear PercentileMethod = iota

	// Lower value of the two closest ranks (R-1)
	Lower

	// Higher value of the two closest ranks (R-3)
	Higher

	// Midpoint of the two closest ranks (R-2)
	Midpoint

	// Weighted average giving more weight to closer rank (R-4)
	Weighted

	// Method used by R default (R-7)
	RDefault

	// Median-unbiased method (R-8)
	MedianUnbiased

	// Approximately normal unbiased method (R-9)
	NormalUnbiased
)

type PercentileResult

type PercentileResult struct {
	Values      []float64           `json:"values"`      // Original sorted values
	Percentiles map[float64]float64 `json:"percentiles"` // Percentile -> value mapping
	Quartiles   QuartileInfo        `json:"quartiles"`   // Q1, Q2, Q3 information
	Extremes    ExtremeInfo         `json:"extremes"`    // Min, max, outliers
	Summary     SummaryStats        `json:"summary"`     // Basic statistics
	Method      PercentileMethod    `json:"method"`      // Calculation method used
}

PercentileResult contains comprehensive percentile statistics

type Percentiles

type Percentiles struct {
	// contains filtered or unexported fields
}

Percentiles implements various percentile calculation methods for statistical analysis

References:

  • Hyndman, R.J., Fan, Y. (1996). "Sample Quantiles in Statistical Packages" The American Statistician, 50(4), 361-365
  • NIST/SEMATECH e-Handbook of Statistical Methods
  • Tukey, J.W. (1977). "Exploratory Data Analysis"
  • McGill, R., Tukey, J.W., Larsen, W.A. (1978). "Variations of box plots"

This implementation provides multiple percentile calculation methods: 1. Linear interpolation (most common, used by Excel) 2. Lower/Higher value methods 3. R-compatible methods (R-1 through R-9) 4. Outlier detection using IQR method 5. Comprehensive statistical summaries

func NewPercentiles

func NewPercentiles() *Percentiles

NewPercentiles creates a new percentile analyzer with linear interpolation method

func NewPercentilesWithMethod

func NewPercentilesWithMethod(method PercentileMethod) *Percentiles

NewPercentilesWithMethod creates a percentile analyzer with specified method

func NewPercentilesWithOutlierThreshold

func NewPercentilesWithOutlierThreshold(method PercentileMethod, outlierK, extremeK float64) *Percentiles

NewPercentilesWithOutlierThreshold creates analyzer with custom outlier detection

func (*Percentiles) Analyze

func (p *Percentiles) Analyze(data []float64) (*PercentileResult, error)

Analyze computes comprehensive percentile statistics for the input data

func (*Percentiles) CalculateBoxPlotStatistics

func (p *Percentiles) CalculateBoxPlotStatistics(data []float64) (float64, float64, float64, float64, float64, error)

CalculateBoxPlotStatistics computes the five-number summary for box plots Returns: min, Q1, median, Q3, max

func (*Percentiles) CalculateCustomPercentiles

func (p *Percentiles) CalculateCustomPercentiles(data []float64, percentiles []float64) (map[float64]float64, error)

CalculateCustomPercentiles computes percentiles for custom percentile values

func (*Percentiles) CalculatePercentile

func (p *Percentiles) CalculatePercentile(data []float64, percentile float64) (float64, error)

CalculatePercentile computes a single percentile value

func (*Percentiles) CalculatePercentileRank

func (p *Percentiles) CalculatePercentileRank(data []float64, value float64) (float64, error)

CalculatePercentileRank computes the percentile rank of a given value Returns the percentage of values that are less than or equal to the given value

func (*Percentiles) GetMethodName

func (p *Percentiles) GetMethodName() string

GetMethodName returns the human-readable name of the percentile method

func (*Percentiles) GetOutlierThresholds

func (p *Percentiles) GetOutlierThresholds() (float64, float64)

GetOutlierThresholds returns current outlier detection thresholds

func (*Percentiles) SetMethod

func (p *Percentiles) SetMethod(method PercentileMethod)

SetMethod changes the percentile calculation method

func (*Percentiles) SetOutlierThresholds

func (p *Percentiles) SetOutlierThresholds(outlierK, extremeK float64)

SetOutlierThresholds sets custom outlier detection thresholds

type QuartileInfo

type QuartileInfo struct {
	Q1  float64 `json:"q1"`  // First quartile (25th percentile)
	Q2  float64 `json:"q2"`  // Second quartile (50th percentile, median)
	Q3  float64 `json:"q3"`  // Third quartile (75th percentile)
	IQR float64 `json:"iqr"` // Interquartile range (Q3 - Q1)
}

QuartileInfo contains quartile-specific information

type SummaryStats

type SummaryStats struct {
	Count    int     `json:"count"`
	Mean     float64 `json:"mean"`
	Variance float64 `json:"variance"`
	StdDev   float64 `json:"std_dev"`
	Skewness float64 `json:"skewness"`
	Kurtosis float64 `json:"kurtosis"`
}

SummaryStats contains basic summary statistics

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL