Documentation
ΒΆ
Overview ΒΆ
Package distance provides comprehensive distance, similarity, and divergence metrics for vectors, strings, sets, probability distributions, and time series.
Package distance provides distance metrics and optimization algorithms.
Cryptographic randomness is not required for these mathematical optimization functions (simulated annealing, genetic algorithms, PSO, differential evolution). Using crypto/rand would be unnecessarily slow and provide no security benefit.
Index ΒΆ
- Variables
- func Adam(_ OptimizationFunc, grad GradientFunc, initial []float64, learningRate float64, ...) []float64
- func Autocorrelation[T Number](data []T, lag int) (float64, error)
- func BFGS(f OptimizationFunc, grad GradientFunc, initial []float64, iterations int, ...) []float64
- func BatchCompute[T Number](vectors [][]T, distFn DistanceFunc[T]) ([][]float64, error)
- func BatchComputeParallel[T Number](vectors [][]T, distFn DistanceFunc[T], workers int) ([][]float64, error)
- func BatchComputeWithContext[T Number](ctx context.Context, vectors [][]T, distFn DistanceFunc[T], workers int) ([][]float64, error)
- func Bhattacharyya[T Float](p, q []T) (float64, error)
- func BrayCurtis[T Number](a, b []T) (float64, error)
- func Canberra[T Number](a, b []T) (float64, error)
- func Centroid[T Number](vectors [][]T) ([]float64, error)
- func Chebyshev[T Number](a, b []T) (float64, error)
- func ChiSquare[T Float](p, q []T) (float64, error)
- func ComputeToPoint[T Number](vectors [][]T, point []T, distFn DistanceFunc[T]) ([]float64, error)
- func ComputeWithContext[T Number](ctx context.Context, a, b []T, distFn DistanceFunc[T]) (float64, error)
- func ConjugateGradient(f OptimizationFunc, grad GradientFunc, initial []float64, iterations int, ...) []float64
- func Cosine[T Number](a, b []T) (float64, error)
- func CosineDistanceSet[T comparable](a, b []T) (float64, error)
- func CosineSimilarity[T Number](a, b []T) (float64, error)
- func CosineSimilaritySet[T comparable](a, b []T) (float64, error)
- func CosineSimilarityStrings(a, b string) (float64, error)
- func CrossEntropy[T Float](p, q []T) (float64, error)
- func DTW[T Number](a, b []T) (float64, error)
- func DTWWithWindow[T Number](a, b []T, window int) (float64, error)
- func DamerauLevenshtein(a, b string) (int, error)
- func DiceDistance[T comparable](a, b []T) (float64, error)
- func DiceSorensen[T comparable](a, b []T) (float64, error)
- func DifferentialEvolution(f OptimizationFunc, dimensions int, bounds [][]float64, popSize int, ...) []float64
- func DotProduct[T Number](a, b []T) (float64, error)
- func EditDistance(a, b string, insertCost, deleteCost, replaceCost int) (int, error)
- func Equirectangular(a, b Coord) float64
- func EquirectangularWithRadius(a, b Coord, radius float64) float64
- func Euclidean[T Number](a, b []T) (float64, error)
- func EuclideanSquared[T Number](a, b []T) (float64, error)
- func Frechet[T Number](a, b [][]T) (float64, error)
- func GeneticAlgorithm(f OptimizationFunc, dimensions int, bounds [][]float64, popSize int, ...) []float64
- func GradientDescent(_ OptimizationFunc, grad GradientFunc, initial []float64, learningRate float64, ...) []float64
- func GradientDescentWithMomentum(_ OptimizationFunc, grad GradientFunc, initial []float64, learningRate float64, ...) []float64
- func GraphEditDistance(g1, g2 *Graph) float64
- func GreatCircle(a, b Coord) float64
- func GreatCircleWithRadius(a, b Coord, radius float64) float64
- func Hamming[T Number](a, b []T) (float64, error)
- func HammingString(a, b string) (int, error)
- func Hausdorff[T Number](a, b [][]T) (float64, error)
- func Haversine(a, b Coord) float64
- func HaversineMiles(a, b Coord) float64
- func HaversineWithRadius(a, b Coord, radius float64) float64
- func Hellinger[T Float](p, q []T) (float64, error)
- func JaccardIndex(a, b string, n int) (float64, error)
- func JaccardSet[T comparable](a, b []T) (float64, error)
- func JaccardSimilarity[T comparable](a, b []T) (float64, error)
- func Jaro(a, b string) (float64, error)
- func JaroWinkler(a, b string, prefixScale float64) (float64, error)
- func JensenShannonDivergence[T Float](p, q []T) (float64, error)
- func KLDivergence[T Float](p, q []T) (float64, error)
- func KNearestNeighbors[T Number](vectors [][]T, k int, distFn DistanceFunc[T]) ([][]int, error)
- func LCSDistance(a, b string) (int, error)
- func LCSRatio(a, b string) (float64, error)
- func Levenshtein(a, b string) (int, error)
- func LongestCommonSubsequence(a, b string) (int, error)
- func LongestCommonSubstring[T comparable](a, b []T) int
- func Manhattan[T Number](a, b []T) (float64, error)
- func Metaphone(s string) string
- func Minkowski[T Number](a, b []T, p float64) (float64, error)
- func MongeElkan(a, b string, tokenSim func(string, string) float64) (float64, error)
- func NGramDistance(a, b string, n int) (float64, error)
- func NearestNeighbor[T Number](vectors [][]T, query []T, distFn DistanceFunc[T]) (int, float64, error)
- func NeedlemanWunsch[T comparable](a, b []T, match, mismatch, gap int) (int, error)
- func NelderMead(f OptimizationFunc, initial []float64, iterations int, ...) []float64
- func Norm[T Number](v []T, p float64) (float64, error)
- func NormalizedLevenshtein(a, b string) (float64, error)
- func OverlapCoefficient[T comparable](a, b []T) (float64, error)
- func PairwiseDistinctCount[T Number](vectors [][]T, threshold float64, distFn DistanceFunc[T]) (int, error)
- func ParticleSwarmOptimization(f OptimizationFunc, dimensions int, bounds [][]float64, swarmSize int, ...) []float64
- func PearsonCorrelation[T Number](a, b []T) (float64, error)
- func PearsonDistance[T Number](a, b []T) (float64, error)
- func PhoneticDistance(a, b string, encoder func(string) string) int
- func QGramDistance(a, b string, q int) (int, error)
- func RadiusNeighbors[T Number](vectors [][]T, radius float64, distFn DistanceFunc[T]) ([][]int, error)
- func RatcliffObershelp(a, b string) (float64, error)
- func SimulatedAnnealing(f OptimizationFunc, initial []float64, initialTemp float64, ...) []float64
- func SmithWaterman[T comparable](a, b []T, match, mismatch, gap int) (int, error)
- func SmithWatermanString(a, b string, match, mismatch, gap int) (int, error)
- func SoftDTW[T Number](a, b []T, gamma float64) (float64, error)
- func SorensenDice(a, b string) (float64, error)
- func Soundex(s string) string
- func SpearmanCorrelation[T Number](a, b []T) (float64, error)
- func TanimotoCoefficient[T Number](a, b []T) (float64, error)
- func TanimotoDistance[T Number](a, b []T) (float64, error)
- func TokenSetRatio(a, b string) (float64, error)
- func TokenSortRatio(a, b string) (float64, error)
- func TotalVariation[T Float](p, q []T) (float64, error)
- func TverskyIndex(a, b string, alpha, beta float64) (float64, error)
- func Validate[T Number](a, b []T) error
- func ValidateWeights[T Number](v []T, weights []float64) error
- func Vincenty(a, b Coord) (float64, error)
- func VincentyKm(a, b Coord) (float64, error)
- func Wasserstein1D[T Number](a, b []T) (float64, error)
- func WeightedEuclidean[T Number](a, b []T, weights []float64) (float64, error)
- type BatchComputer
- type Coord
- type DistanceFunc
- type Float
- type GradientFunc
- type Graph
- func (g *Graph) AStar(source, target int, heuristic func(int, int) float64) (float64, []int)
- func (g *Graph) AddEdge(from, to int, weight float64)
- func (g *Graph) AddUndirectedEdge(a, b int, weight float64)
- func (g *Graph) BFS(source, target int) (int, []int)
- func (g *Graph) BellmanFord(source int) (map[int]float64, bool)
- func (g *Graph) CommuteTime(source, target int) float64
- func (g *Graph) ConnectedComponents() [][]int
- func (g *Graph) Dijkstra(source, target int) (float64, []int)
- func (g *Graph) FloydWarshall() map[int]map[int]float64
- func (g *Graph) GraphDiameter() float64
- func (g *Graph) GraphRadius() float64
- func (g *Graph) IsConnected() bool
- func (g *Graph) ResistanceDistance(source, target int) float64
- type Individual
- type Metric
- type Number
- type OptimizationFunc
- type Options
- type Particle
- type StringDistanceFunc
Constants ΒΆ
This section is empty.
Variables ΒΆ
var ( // ErrDimensionMismatch is returned when vector dimensions don't match. ErrDimensionMismatch = errors.New("dimension mismatch between vectors") // ErrEmptyInput is returned when input is empty. ErrEmptyInput = errors.New("empty input provided") // ErrInvalidParameter is returned when a parameter value is invalid. ErrInvalidParameter = errors.New("invalid parameter value") // ErrZeroVector is returned when a zero vector is encountered. ErrZeroVector = errors.New("zero vector encountered") // ErrNegativeValue is returned when a negative value is found in input that requires non-negative values. ErrNegativeValue = errors.New("negative value in input") )
Functions ΒΆ
func Adam ΒΆ
func Adam( _ OptimizationFunc, grad GradientFunc, initial []float64, learningRate float64, beta1, beta2 float64, epsilon float64, iterations int, ) []float64
Adam optimizer (Adaptive Moment Estimation) Time: O(iterations * d), Space: O(d)
func Autocorrelation ΒΆ
Autocorrelation computes autocorrelation at lag k. Measures correlation of a signal with a delayed copy of itself. Time: O(n), Space: O(1)
func BFGS ΒΆ
func BFGS( f OptimizationFunc, grad GradientFunc, initial []float64, iterations int, tolerance float64, ) []float64
BFGS performs BFGS quasi-Newton optimization Time: O(iterations * dΒ²), Space: O(dΒ²)
func BatchCompute ΒΆ
func BatchCompute[T Number](vectors [][]T, distFn DistanceFunc[T]) ([][]float64, error)
BatchCompute computes distances between all pairs of vectors (distance matrix). Time: O(nΒ²d), Space: O(nΒ²) where n=vectors, d=dimensions
func BatchComputeParallel ΒΆ
func BatchComputeParallel[T Number](vectors [][]T, distFn DistanceFunc[T], workers int) ([][]float64, error)
BatchComputeParallel computes distance matrix in parallel. Time: O(nΒ²d/workers), Space: O(nΒ²)
func BatchComputeWithContext ΒΆ
func BatchComputeWithContext[T Number](ctx context.Context, vectors [][]T, distFn DistanceFunc[T], workers int) ([][]float64, error)
BatchComputeWithContext computes distance matrix with cancellation.
func Bhattacharyya ΒΆ
Bhattacharyya computes Bhattacharyya distance. Measures similarity between probability distributions. Range [0, +β) where 0=identical Time: O(n), Space: O(1)
func BrayCurtis ΒΆ
BrayCurtis computes the Bray-Curtis dissimilarity. Used in ecology and biology for compositional data. Range [0, 1] where 0=identical, 1=completely different Time: O(n), Space: O(1)
func Canberra ΒΆ
Canberra computes the Canberra distance (weighted Manhattan distance). Sensitive to small changes near zero. Used in biology/ecology. Time: O(n), Space: O(1)
func Centroid ΒΆ
Centroid computes the centroid (mean) of a set of vectors. Time: O(nd), Space: O(d)
func Chebyshev ΒΆ
Chebyshev computes the L-infinity norm (maximum absolute difference). Also known as: Chessboard distance Time: O(n), Space: O(1)
func ChiSquare ΒΆ
ChiSquare computes Chi-square distance. Used for histogram comparison in computer vision. Time: O(n), Space: O(1)
func ComputeToPoint ΒΆ
func ComputeToPoint[T Number](vectors [][]T, point []T, distFn DistanceFunc[T]) ([]float64, error)
ComputeToPoint computes distances from all vectors to a single point. Time: O(nd), Space: O(n)
func ComputeWithContext ΒΆ
func ComputeWithContext[T Number](ctx context.Context, a, b []T, distFn DistanceFunc[T]) (float64, error)
ComputeWithContext computes distance with cancellation support.
func ConjugateGradient ΒΆ
func ConjugateGradient( f OptimizationFunc, grad GradientFunc, initial []float64, iterations int, tolerance float64, ) []float64
ConjugateGradient performs conjugate gradient optimization Time: O(iterations * d), Space: O(d)
func Cosine ΒΆ
Cosine computes the cosine distance (1 - cosine similarity). Measures angle between vectors, range [0, 2] (0=identical direction, 2=opposite) Time: O(n), Space: O(1)
func CosineDistanceSet ΒΆ
func CosineDistanceSet[T comparable](a, b []T) (float64, error)
CosineDistanceSet computes cosine distance for bag-of-words sets. Time: O(n+m), Space: O(n+m)
func CosineSimilarity ΒΆ
CosineSimilarity computes the cosine similarity (dot product of normalized vectors). Range [-1, 1] where 1=identical, 0=orthogonal, -1=opposite Time: O(n), Space: O(1)
func CosineSimilaritySet ΒΆ
func CosineSimilaritySet[T comparable](a, b []T) (float64, error)
CosineSimilaritySet computes cosine similarity for bag-of-words. Uses term frequency vectors constructed from sets. Time: O(n+m), Space: O(n+m)
func CosineSimilarityStrings ΒΆ
CosineSimilarityStrings computes cosine similarity for strings Treats strings as character frequency vectors Range [0, 1] where 1=identical distribution Time: O(n+m), Space: O(n+m)
func CrossEntropy ΒΆ
CrossEntropy computes cross-entropy H(P,Q). Used in ML loss functions: H(P,Q) = -Ξ£ p(x) log q(x) Time: O(n), Space: O(1)
func DTW ΒΆ
DTW computes Dynamic Time Warping distance between two time series. Allows matching sequences of different lengths. Time: O(mn), Space: O(min(m,n)) with optimization
func DTWWithWindow ΒΆ
DTWWithWindow computes DTW with Sakoe-Chiba band constraint. Window limits how far sequences can deviate (improves performance). Time: O(mn), Space: O(min(m,n))
func DamerauLevenshtein ΒΆ
DamerauLevenshtein computes Damerau-Levenshtein distance. Includes transposition of adjacent characters (ab -> ba). Time: O(mn), Space: O(mn)
func DiceDistance ΒΆ
func DiceDistance[T comparable](a, b []T) (float64, error)
DiceDistance computes Dice distance (1 - Dice coefficient). Time: O(n+m), Space: O(n)
func DiceSorensen ΒΆ
func DiceSorensen[T comparable](a, b []T) (float64, error)
DiceSorensen computes Dice-SΓΈrensen coefficient. Similarity = 2|A β© B| / (|A| + |B|) Range [0, 1] where 1=identical Time: O(n+m), Space: O(n)
func DifferentialEvolution ΒΆ
func DifferentialEvolution( f OptimizationFunc, dimensions int, bounds [][]float64, popSize int, generations int, mutationFactor float64, crossoverProb float64, ) []float64
DifferentialEvolution performs differential evolution Time: O(generations * popSize * d), Space: O(popSize * d)
func DotProduct ΒΆ
DotProduct computes the dot product (inner product) of two vectors. Time: O(n), Space: O(1)
func EditDistance ΒΆ
EditDistance computes generic edit distance with custom costs Time: O(mn), Space: O(min(m,n))
func Equirectangular ΒΆ
Equirectangular computes approximate distance using equirectangular projection. Fast but less accurate approximation for small distances. Returns distance in kilometers. Time: O(1), Space: O(1)
func EquirectangularWithRadius ΒΆ
EquirectangularWithRadius computes equirectangular distance with custom radius. Time: O(1), Space: O(1)
func Euclidean ΒΆ
Euclidean computes the L2 norm (straight-line distance) between two vectors. Time: O(n), Space: O(1)
func EuclideanSquared ΒΆ
EuclideanSquared computes squared Euclidean distance (faster, avoids sqrt). Time: O(n), Space: O(1)
func Frechet ΒΆ
Frechet computes discrete FrΓ©chet distance between two curves. Measures similarity considering the flow of the curves. Time: O(mn), Space: O(mn)
func GeneticAlgorithm ΒΆ
func GeneticAlgorithm( f OptimizationFunc, dimensions int, bounds [][]float64, popSize int, generations int, mutationRate float64, crossoverRate float64, ) []float64
GeneticAlgorithm performs genetic algorithm optimization Time: O(generations * popSize * d), Space: O(popSize * d)
func GradientDescent ΒΆ
func GradientDescent( _ OptimizationFunc, grad GradientFunc, initial []float64, learningRate float64, iterations int, ) []float64
GradientDescent performs gradient descent optimization Time: O(iterations * d), Space: O(d)
func GradientDescentWithMomentum ΒΆ
func GradientDescentWithMomentum( _ OptimizationFunc, grad GradientFunc, initial []float64, learningRate float64, momentum float64, iterations int, ) []float64
GradientDescentWithMomentum performs gradient descent with momentum Time: O(iterations * d), Space: O(d)
func GraphEditDistance ΒΆ
GraphEditDistance computes graph edit distance between two graphs Time: Exponential (NP-hard), Space: O(VΒ²)
func GreatCircle ΒΆ
GreatCircle computes great-circle distance using spherical law of cosines. Simpler but less accurate for small distances than Haversine. Returns distance in kilometers. Time: O(1), Space: O(1)
func GreatCircleWithRadius ΒΆ
GreatCircleWithRadius computes great-circle distance with custom radius. Time: O(1), Space: O(1)
func Hamming ΒΆ
Hamming computes the Hamming distance (number of differing positions). Time: O(n), Space: O(1)
func HammingString ΒΆ
HammingString computes Hamming distance for strings (must be equal length). Time: O(n), Space: O(1)
func Hausdorff ΒΆ
Hausdorff computes Hausdorff distance between two point sets. Measures maximum distance from a point in one set to the nearest point in the other. Time: O(nm), Space: O(1)
func Haversine ΒΆ
Haversine computes great-circle distance using Haversine formula. Returns distance in kilometers by default. Time: O(1), Space: O(1)
func HaversineMiles ΒΆ
HaversineMiles computes Haversine distance in miles. Time: O(1), Space: O(1)
func HaversineWithRadius ΒΆ
HaversineWithRadius computes Haversine distance with custom Earth radius. Time: O(1), Space: O(1)
func Hellinger ΒΆ
Hellinger computes Hellinger distance. Related to Bhattacharyya: HΒ² = 1 - BC Range [0, 1] where 0=identical, 1=completely different Time: O(n), Space: O(1)
func JaccardIndex ΒΆ
JaccardIndex computes Jaccard index for strings (using n-grams) Range [0, 1] where 1=identical Time: O(n+m), Space: O(n+m)
func JaccardSet ΒΆ
func JaccardSet[T comparable](a, b []T) (float64, error)
JaccardSet computes Jaccard distance for sets. Distance = 1 - |A β© B| / |A βͺ B| Range [0, 1] where 0=identical, 1=completely different Time: O(n+m), Space: O(n)
func JaccardSimilarity ΒΆ
func JaccardSimilarity[T comparable](a, b []T) (float64, error)
JaccardSimilarity computes Jaccard similarity coefficient. Similarity = |A β© B| / |A βͺ B| Range [0, 1] where 1=identical, 0=no overlap Time: O(n+m), Space: O(n)
func Jaro ΒΆ
Jaro computes the Jaro similarity between two strings. Returns similarity in [0, 1] where 1=identical Time: O(mn), Space: O(max(m,n))
func JaroWinkler ΒΆ
JaroWinkler computes Jaro-Winkler similarity (Jaro with prefix bonus). prefixScale: scaling factor for prefix (standard: 0.1) Returns similarity in [0, 1] where 1=identical Time: O(mn), Space: O(max(m,n))
func JensenShannonDivergence ΒΆ
JensenShannonDivergence computes Jensen-Shannon divergence. Symmetric version of KL divergence: JS(P||Q) = JS(Q||P) Bounded: 0 β€ JS β€ log(2) Time: O(n), Space: O(n)
func KLDivergence ΒΆ
KLDivergence computes Kullback-Leibler divergence KL(P||Q). Measures how probability distribution P diverges from Q. NOTE: Asymmetric (KL(P||Q) β KL(Q||P)) Time: O(n), Space: O(1)
func KNearestNeighbors ΒΆ
func KNearestNeighbors[T Number](vectors [][]T, k int, distFn DistanceFunc[T]) ([][]int, error)
KNearestNeighbors finds k nearest neighbors for each vector. Returns indices of k nearest neighbors for each vector. Time: O(nΒ²d), Space: O(nk)
func LCSDistance ΒΆ
LCSDistance computes distance based on LCS. Returns: len(a) + len(b) - 2*LCS(a,b) Time: O(mn), Space: O(min(m,n))
func LCSRatio ΒΆ
LCSRatio computes LCS-based similarity ratio Range [0, 1] where 1=identical Time: O(mn), Space: O(min(m,n))
func Levenshtein ΒΆ
Levenshtein computes the Levenshtein edit distance between two strings. Counts minimum insertions, deletions, and substitutions. Time: O(mn), Space: O(min(m,n)) with optimization
func LongestCommonSubsequence ΒΆ
LongestCommonSubsequence computes the length of LCS. Time: O(mn), Space: O(min(m,n))
func LongestCommonSubstring ΒΆ
func LongestCommonSubstring[T comparable](a, b []T) int
LongestCommonSubstring computes longest common substring length for sequences. Time: O(mn), Space: O(mn)
func Manhattan ΒΆ
Manhattan computes the L1 norm (sum of absolute differences). Also known as: Taxicab distance, City Block distance Time: O(n), Space: O(1)
func Metaphone ΒΆ
Metaphone computes metaphone phonetic encoding Returns phonetic code for phonetic matching Time: O(n), Space: O(n)
func Minkowski ΒΆ
Minkowski computes the Lp norm with parameter p. p=1: Manhattan, p=2: Euclidean, p=inf: Chebyshev Time: O(n), Space: O(1)
func MongeElkan ΒΆ
MongeElkan computes Monge-Elkan similarity Uses maximum token similarity Range [0, 1] where 1=identical Time: O(nΒ²m), Space: O(n)
func NGramDistance ΒΆ
NGramDistance computes distance based on n-gram overlap. Time: O(m+n), Space: O(m+n)
func NearestNeighbor ΒΆ
func NearestNeighbor[T Number](vectors [][]T, query []T, distFn DistanceFunc[T]) (int, float64, error)
NearestNeighbor finds the nearest neighbor for a query point. Time: O(nd), Space: O(1)
func NeedlemanWunsch ΒΆ
func NeedlemanWunsch[T comparable](a, b []T, match, mismatch, gap int) (int, error)
NeedlemanWunsch computes global sequence alignment score. Time: O(mn), Space: O(mn)
func NelderMead ΒΆ
func NelderMead( f OptimizationFunc, initial []float64, iterations int, alpha, gamma, rho, sigma float64, ) []float64
NelderMead performs Nelder-Mead simplex optimization Time: O(iterations * dΒ²), Space: O(dΒ²)
func NormalizedLevenshtein ΒΆ
NormalizedLevenshtein computes normalized Levenshtein distance Range [0, 1] where 0=identical Time: O(mn), Space: O(min(m,n))
func OverlapCoefficient ΒΆ
func OverlapCoefficient[T comparable](a, b []T) (float64, error)
OverlapCoefficient computes overlap coefficient. Overlap = |A β© B| / min(|A|, |B|) Range [0, 1] where 1=one is subset of the other Time: O(n+m), Space: O(n)
func PairwiseDistinctCount ΒΆ
func PairwiseDistinctCount[T Number](vectors [][]T, threshold float64, distFn DistanceFunc[T]) (int, error)
PairwiseDistinctCount counts pairs with distance above threshold. Useful for diversity metrics. Time: O(nΒ²d), Space: O(1)
func ParticleSwarmOptimization ΒΆ
func ParticleSwarmOptimization( f OptimizationFunc, dimensions int, bounds [][]float64, swarmSize int, iterations int, inertia float64, cognitive float64, social float64, ) []float64
ParticleSwarmOptimization performs PSO Time: O(iterations * swarmSize * d), Space: O(swarmSize * d)
func PearsonCorrelation ΒΆ
PearsonCorrelation computes Pearson correlation coefficient. Range [-1, 1] where 1=perfect positive, -1=perfect negative, 0=no correlation Time: O(n), Space: O(1)
func PearsonDistance ΒΆ
PearsonDistance computes distance based on Pearson correlation. Range [0, 2] where 0=perfect correlation, 2=perfect anti-correlation Time: O(n), Space: O(1)
func PhoneticDistance ΒΆ
PhoneticDistance computes distance between phonetic encodings Returns 0 if phonetically similar Time: O(1), Space: O(1)
func QGramDistance ΒΆ
QGramDistance computes q-gram distance Time: O(n+m), Space: O(n+m)
func RadiusNeighbors ΒΆ
func RadiusNeighbors[T Number](vectors [][]T, radius float64, distFn DistanceFunc[T]) ([][]int, error)
RadiusNeighbors finds all neighbors within radius for each vector. Time: O(nΒ²d), Space: O(n*m) where m=avg neighbors
func RatcliffObershelp ΒΆ
RatcliffObershelp computes Ratcliff/Obershelp similarity Also known as Gestalt Pattern Matching Range [0, 1] where 1=identical Time: O(nΒ²), Space: O(n)
func SimulatedAnnealing ΒΆ
func SimulatedAnnealing( f OptimizationFunc, initial []float64, initialTemp float64, coolingRate float64, iterations int, stepSize float64, ) []float64
SimulatedAnnealing performs simulated annealing optimization Time: O(iterations * d), Space: O(d)
func SmithWaterman ΒΆ
func SmithWaterman[T comparable](a, b []T, match, mismatch, gap int) (int, error)
SmithWaterman computes local sequence alignment score. Used for DNA/protein sequence comparison. Time: O(mn), Space: O(mn)
func SmithWatermanString ΒΆ
SmithWatermanString computes Smith-Waterman local alignment for strings Returns alignment score Time: O(mn), Space: O(mn)
func SoftDTW ΒΆ
SoftDTW computes differentiable DTW using soft-min. Useful for machine learning applications. gamma controls smoothness (smaller = closer to DTW). Time: O(mn), Space: O(mn)
func SorensenDice ΒΆ
SorensenDice computes SΓΈrensen-Dice coefficient for strings Uses bigrams (2-grams) for comparison Range [0, 1] where 1=identical Time: O(n+m), Space: O(n+m)
func Soundex ΒΆ
Soundex computes Soundex phonetic encoding Returns 4-character code for phonetic matching Time: O(n), Space: O(1)
func SpearmanCorrelation ΒΆ
SpearmanCorrelation computes Spearman rank correlation. Measures monotonic relationship between variables. Time: O(n log n), Space: O(n)
func TanimotoCoefficient ΒΆ
TanimotoCoefficient computes Tanimoto coefficient (generalized Jaccard). For binary vectors: Tanimoto = dot(a,b) / (||a||Β² + ||b||Β² - dot(a,b)) Time: O(n), Space: O(1)
func TanimotoDistance ΒΆ
TanimotoDistance computes Tanimoto distance (1 - Tanimoto coefficient). Time: O(n), Space: O(1)
func TokenSetRatio ΒΆ
TokenSetRatio computes similarity using set intersection of tokens Range [0, 1] where 1=identical Time: O(n), Space: O(n)
func TokenSortRatio ΒΆ
TokenSortRatio computes similarity after sorting tokens Useful for comparing similar strings with different word order Range [0, 1] where 1=identical Time: O(n log n), Space: O(n)
func TotalVariation ΒΆ
TotalVariation computes total variation distance. Maximum difference in probabilities across all events. Range [0, 1] Time: O(n), Space: O(1)
func TverskyIndex ΒΆ
TverskyIndex computes Tversky index (asymmetric Jaccard) alpha and beta control asymmetry Time: O(n+m), Space: O(n+m)
func ValidateWeights ΒΆ
ValidateWeights checks if weights match vector dimensions
func Vincenty ΒΆ
Vincenty computes geodesic distance using Vincenty formula. More accurate than Haversine for oblate spheroid (WGS-84 ellipsoid). Returns distance in meters. Time: O(1) with iteration, Space: O(1)
func VincentyKm ΒΆ
VincentyKm computes Vincenty distance in kilometers. Time: O(1) with iteration, Space: O(1)
func Wasserstein1D ΒΆ
Wasserstein1D computes 1D Wasserstein (Earth Mover's) distance. For 1D distributions, this equals the area between CDFs. Time: O(n log n), Space: O(n)
Types ΒΆ
type BatchComputer ΒΆ
type BatchComputer[T Number] interface { ComputePairwise(vectors [][]T) ([][]float64, error) ComputeToPoint(vectors [][]T, point []T) ([]float64, error) ComputeWithContext(ctx context.Context, a, b []T) (float64, error) }
BatchComputer for efficient batch distance calculations
type Coord ΒΆ
type Coord struct {
Lat float64 // Latitude in degrees [-90, 90]
Lon float64 // Longitude in degrees [-180, 180]
}
Coord represents a geographic coordinate (latitude, longitude).
type DistanceFunc ΒΆ
DistanceFunc is a function that computes distance between two vectors. Note: This name stutters with the package name. Consider using batch.Func or similar patterns in client code to avoid repetition.
type GradientFunc ΒΆ
GradientFunc computes the gradient of the function
type Graph ΒΆ
type Graph struct {
// contains filtered or unexported fields
}
Graph represents a weighted graph for distance calculations
func (*Graph) AStar ΒΆ
AStar computes shortest path using A* with heuristic Time: O(E log V) with good heuristic, Space: O(V)
func (*Graph) AddUndirectedEdge ΒΆ
AddUndirectedEdge adds an undirected edge
func (*Graph) BellmanFord ΒΆ
BellmanFord computes shortest paths handling negative weights Returns distances and whether negative cycle exists Time: O(VE), Space: O(V)
func (*Graph) CommuteTime ΒΆ
CommuteTime computes approximate expected commute time for random walk. WARNING: This is a simplified approximation using shortest path distance. True commute time requires computing hitting times using the fundamental matrix of the random walk, which involves matrix inversion. For accurate commute time, use a specialized graph analysis library. Time: O((V+E)logV), Space: O(V)
func (*Graph) ConnectedComponents ΒΆ
ConnectedComponents finds connected components Time: O(V+E), Space: O(V)
func (*Graph) Dijkstra ΒΆ
Dijkstra computes shortest path distance from source to target Returns distance and path. Returns inf if no path exists. Time: O((V+E)logV), Space: O(V)
func (*Graph) FloydWarshall ΒΆ
FloydWarshall computes all-pairs shortest paths Time: O(VΒ³), Space: O(VΒ²)
func (*Graph) GraphDiameter ΒΆ
GraphDiameter computes the diameter (maximum shortest path) Time: O(VΒ³), Space: O(VΒ²)
func (*Graph) GraphRadius ΒΆ
GraphRadius computes the radius (minimum eccentricity) Time: O(VΒ³), Space: O(VΒ²)
func (*Graph) IsConnected ΒΆ
IsConnected checks if graph is connected Time: O(V+E), Space: O(V)
func (*Graph) ResistanceDistance ΒΆ
ResistanceDistance computes approximate effective resistance between nodes. WARNING: This is a simplified approximation using shortest path distance. A full implementation requires computing the Moore-Penrose pseudoinverse of the graph Laplacian matrix, which is computationally expensive. For accurate resistance distance, use a specialized linear algebra library. Time: O((V+E)logV), Space: O(V)
type Individual ΒΆ
Individual represents a genetic algorithm individual
type Metric ΒΆ
type Metric interface {
Name() string
Distance(a, b any) (float64, error)
IsSymmetric() bool // Some metrics like KL divergence are asymmetric
IsMetric() bool // Satisfies metric space axioms (triangle inequality, etc.)
}
Metric interface for any distance metric
type Number ΒΆ
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
Number constraint for generic numeric types
type OptimizationFunc ΒΆ
OptimizationFunc represents a function to minimize/maximize
type Options ΒΆ
type Options struct {
Normalize bool // Normalize result to [0,1]
Weights []float64 // Dimension weights
Parallel bool // Use parallel computation for batch operations
MaxDistance float64 // Early termination threshold (0 means no limit)
}
Options for configurable distance calculations
type Particle ΒΆ
type Particle struct {
Position []float64
Velocity []float64
BestPosition []float64
BestFitness float64
Fitness float64
}
Particle represents a PSO particle
type StringDistanceFunc ΒΆ
StringDistanceFunc computes distance between strings