Merge commit 'd803bfe2b1fe7f5e219e50ac20d6801a0a58ac75' as 'vendor/ruvector'
This commit is contained in:
257
vendor/ruvector/crates/ruvector-postgres/src/hyperbolic/lorentz.rs
vendored
Normal file
257
vendor/ruvector/crates/ruvector-postgres/src/hyperbolic/lorentz.rs
vendored
Normal file
@@ -0,0 +1,257 @@
|
||||
// Lorentz Hyperboloid Model Implementation
|
||||
// Implements isometric model of hyperbolic space
|
||||
|
||||
use crate::hyperbolic::EPSILON;
|
||||
use simsimd::SpatialSimilarity;
|
||||
|
||||
/// Lorentz/Hyperboloid model for hyperbolic space
|
||||
/// Points live on the hyperboloid: -x₀² + x₁² + ... + xₙ² = -1/K
|
||||
pub struct LorentzModel {
|
||||
/// Curvature of the hyperbolic space (typically -1.0)
|
||||
pub curvature: f32,
|
||||
}
|
||||
|
||||
impl LorentzModel {
|
||||
/// Create a new Lorentz model with specified curvature
|
||||
pub fn new(curvature: f32) -> Self {
|
||||
assert!(curvature < 0.0, "Curvature must be negative");
|
||||
Self { curvature }
|
||||
}
|
||||
|
||||
/// Minkowski inner product: -x₀y₀ + x₁y₁ + ... + xₙyₙ
|
||||
pub fn minkowski_dot(&self, x: &[f32], y: &[f32]) -> f32 {
|
||||
assert_eq!(x.len(), y.len(), "Vectors must have same dimension");
|
||||
assert!(x.len() >= 2, "Need at least 2 dimensions for Lorentz model");
|
||||
|
||||
let time_part = -x[0] * y[0];
|
||||
let spatial_part = if x.len() > 1 {
|
||||
f32::dot(&x[1..], &y[1..]).unwrap_or(0.0) as f32
|
||||
} else {
|
||||
0.0f32
|
||||
};
|
||||
|
||||
time_part + spatial_part
|
||||
}
|
||||
|
||||
/// Compute Lorentz distance between two points
|
||||
/// d(x, y) = acosh(-⟨x, y⟩_L)
|
||||
pub fn distance(&self, x: &[f32], y: &[f32]) -> f32 {
|
||||
let inner = -self.minkowski_dot(x, y);
|
||||
|
||||
// Clamp to avoid numerical errors in acosh
|
||||
let arg = inner.max(1.0);
|
||||
let distance = arg.acosh();
|
||||
|
||||
// Scale by curvature
|
||||
let k = self.curvature.abs().sqrt();
|
||||
distance / k
|
||||
}
|
||||
|
||||
/// Convert from Poincaré ball coordinates to Lorentz hyperboloid
|
||||
/// x → (1 + ||x||², 2x₁, 2x₂, ..., 2xₙ) / (1 - ||x||²)
|
||||
pub fn from_poincare(&self, x: &[f32]) -> Vec<f32> {
|
||||
let norm_sq = f32::dot(x, x).unwrap_or(0.0) as f32;
|
||||
let norm_sq = norm_sq.max(0.0);
|
||||
let denominator = 1.0f32 - norm_sq + EPSILON;
|
||||
|
||||
if denominator <= EPSILON {
|
||||
// Point at infinity, return large time coordinate
|
||||
let mut result = vec![0.0f32; x.len() + 1];
|
||||
result[0] = 1e6f32; // Large time coordinate
|
||||
return result;
|
||||
}
|
||||
|
||||
let time_coord = (1.0f32 + norm_sq) / denominator;
|
||||
let spatial_scale = 2.0f32 / denominator;
|
||||
|
||||
let mut result: Vec<f32> = Vec::with_capacity(x.len() + 1);
|
||||
result.push(time_coord);
|
||||
for &xi in x {
|
||||
result.push(xi * spatial_scale);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Convert from Lorentz hyperboloid to Poincaré ball coordinates
|
||||
/// (x₀, x₁, ..., xₙ) → (x₁, ..., xₙ) / (x₀ + 1)
|
||||
pub fn to_poincare(&self, x: &[f32]) -> Vec<f32> {
|
||||
assert!(x.len() >= 2, "Need at least 2 dimensions for Lorentz model");
|
||||
|
||||
let time_coord = x[0];
|
||||
let denominator = time_coord + 1.0 + EPSILON;
|
||||
|
||||
if denominator <= EPSILON {
|
||||
// Point at infinity, return origin
|
||||
return vec![0.0; x.len() - 1];
|
||||
}
|
||||
|
||||
x[1..].iter().map(|&xi| xi / denominator).collect()
|
||||
}
|
||||
|
||||
/// Verify that a point lies on the hyperboloid
|
||||
/// Should satisfy: -x₀² + x₁² + ... + xₙ² = -1/K
|
||||
pub fn is_on_hyperboloid(&self, x: &[f32]) -> bool {
|
||||
let k = self.curvature.abs();
|
||||
let expected = -1.0 / k;
|
||||
let actual = self.minkowski_dot(x, x);
|
||||
(actual - expected).abs() < EPSILON * 10.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::hyperbolic::poincare::PoincareBall;
|
||||
|
||||
const TOL: f32 = 1e-3;
|
||||
|
||||
#[test]
|
||||
fn test_lorentz_creation() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
assert_eq!(model.curvature, -1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Curvature must be negative")]
|
||||
fn test_lorentz_positive_curvature_panics() {
|
||||
let _model = LorentzModel::new(1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_minkowski_dot() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
let x = vec![2.0, 1.0, 1.0];
|
||||
let y = vec![3.0, 2.0, 1.0];
|
||||
|
||||
// -2*3 + 1*2 + 1*1 = -6 + 2 + 1 = -3
|
||||
let result = model.minkowski_dot(&x, &y);
|
||||
assert!((result - (-3.0)).abs() < TOL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_minkowski_dot_self() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
let x = vec![1.5, 1.0, 0.5];
|
||||
|
||||
// -1.5² + 1.0² + 0.5² = -2.25 + 1.0 + 0.25 = -1.0
|
||||
let result = model.minkowski_dot(&x, &x);
|
||||
assert!((result - (-1.0)).abs() < TOL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distance_same_point() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
let x = vec![1.5, 1.0, 0.5];
|
||||
let dist = model.distance(&x, &x);
|
||||
assert!(dist < TOL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distance_different_points() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
let x = vec![1.5, 1.0, 0.5];
|
||||
let y = vec![2.0, 1.5, 0.5];
|
||||
let dist = model.distance(&x, &y);
|
||||
assert!(dist > 0.0);
|
||||
assert!(dist < f32::INFINITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distance_symmetric() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
let x = vec![1.5, 1.0, 0.5];
|
||||
let y = vec![2.0, 1.5, 0.5];
|
||||
let d1 = model.distance(&x, &y);
|
||||
let d2 = model.distance(&y, &x);
|
||||
assert!((d1 - d2).abs() < TOL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_poincare_conversion_origin() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
let poincare_origin = vec![0.0, 0.0];
|
||||
let lorentz = model.from_poincare(&poincare_origin);
|
||||
|
||||
// Origin should map to (1, 0, 0)
|
||||
assert!((lorentz[0] - 1.0).abs() < TOL);
|
||||
assert!(lorentz[1].abs() < TOL);
|
||||
assert!(lorentz[2].abs() < TOL);
|
||||
|
||||
assert!(model.is_on_hyperboloid(&lorentz));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_poincare_conversion_roundtrip() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
let original = vec![0.3, 0.4];
|
||||
|
||||
let lorentz = model.from_poincare(&original);
|
||||
assert!(model.is_on_hyperboloid(&lorentz));
|
||||
|
||||
let recovered = model.to_poincare(&lorentz);
|
||||
|
||||
for i in 0..original.len() {
|
||||
assert!((recovered[i] - original[i]).abs() < TOL);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_poincare_on_hyperboloid() {
|
||||
let model = LorentzModel::new(-1.0);
|
||||
let points = vec![
|
||||
vec![0.0, 0.0],
|
||||
vec![0.3, 0.4],
|
||||
vec![0.5, 0.0],
|
||||
vec![0.2, 0.7],
|
||||
];
|
||||
|
||||
for point in points {
|
||||
let lorentz = model.from_poincare(&point);
|
||||
assert!(
|
||||
model.is_on_hyperboloid(&lorentz),
|
||||
"Point {:?} -> {:?} not on hyperboloid",
|
||||
point,
|
||||
lorentz
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distance_consistency_with_poincare() {
|
||||
let lorentz_model = LorentzModel::new(-1.0);
|
||||
let poincare_ball = PoincareBall::new(-1.0);
|
||||
|
||||
let p1 = vec![0.2, 0.3];
|
||||
let p2 = vec![0.4, 0.1];
|
||||
|
||||
let l1 = lorentz_model.from_poincare(&p1);
|
||||
let l2 = lorentz_model.from_poincare(&p2);
|
||||
|
||||
let lorentz_dist = lorentz_model.distance(&l1, &l2);
|
||||
let poincare_dist = poincare_ball.distance(&p1, &p2);
|
||||
|
||||
// Distances should be approximately equal
|
||||
assert!(
|
||||
(lorentz_dist - poincare_dist).abs() < TOL,
|
||||
"Lorentz: {}, Poincaré: {}",
|
||||
lorentz_dist,
|
||||
poincare_dist
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_curvature_scaling() {
|
||||
let model1 = LorentzModel::new(-1.0);
|
||||
let model2 = LorentzModel::new(-4.0);
|
||||
|
||||
let x = vec![1.5, 1.0, 0.5];
|
||||
let y = vec![2.0, 1.5, 0.5];
|
||||
|
||||
let d1 = model1.distance(&x, &y);
|
||||
let d2 = model2.distance(&x, &y);
|
||||
|
||||
// Higher curvature magnitude should give shorter distances
|
||||
assert!(d2 < d1);
|
||||
}
|
||||
}
|
||||
30
vendor/ruvector/crates/ruvector-postgres/src/hyperbolic/mod.rs
vendored
Normal file
30
vendor/ruvector/crates/ruvector-postgres/src/hyperbolic/mod.rs
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
// Hyperbolic Embeddings Module
|
||||
// Implements Poincaré ball and Lorentz hyperboloid models for hierarchical embeddings
|
||||
|
||||
pub mod lorentz;
|
||||
pub mod operators;
|
||||
pub mod poincare;
|
||||
|
||||
pub use lorentz::LorentzModel;
|
||||
pub use poincare::PoincareBall;
|
||||
|
||||
/// Default curvature for hyperbolic space
|
||||
pub const DEFAULT_CURVATURE: f32 = -1.0;
|
||||
|
||||
/// Epsilon for numerical stability
|
||||
pub const EPSILON: f32 = 1e-8;
|
||||
|
||||
/// Maximum value to prevent overflow
|
||||
pub const MAX_NORM: f32 = 1.0 - 1e-5;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_constants() {
|
||||
assert_eq!(DEFAULT_CURVATURE, -1.0);
|
||||
assert!(EPSILON > 0.0);
|
||||
assert!(MAX_NORM < 1.0);
|
||||
}
|
||||
}
|
||||
394
vendor/ruvector/crates/ruvector-postgres/src/hyperbolic/operators.rs
vendored
Normal file
394
vendor/ruvector/crates/ruvector-postgres/src/hyperbolic/operators.rs
vendored
Normal file
@@ -0,0 +1,394 @@
|
||||
// PostgreSQL Functions for Hyperbolic Operations
|
||||
// Exposes hyperbolic geometry functions to SQL
|
||||
|
||||
use pgrx::prelude::*;
|
||||
|
||||
use super::{lorentz::LorentzModel, poincare::PoincareBall, DEFAULT_CURVATURE};
|
||||
|
||||
/// Compute Poincaré distance between two vectors
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `a` - First vector
|
||||
/// * `b` - Second vector
|
||||
/// * `curvature` - Curvature of hyperbolic space (default: -1.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Poincaré distance as f32
|
||||
///
|
||||
/// # Example
|
||||
/// ```sql
|
||||
/// SELECT ruvector_poincare_distance(
|
||||
/// ARRAY[0.3, 0.4]::real[],
|
||||
/// ARRAY[0.1, 0.2]::real[],
|
||||
/// -1.0
|
||||
/// );
|
||||
/// ```
|
||||
#[pg_extern(immutable, parallel_safe)]
|
||||
fn ruvector_poincare_distance(
|
||||
a: Vec<f32>,
|
||||
b: Vec<f32>,
|
||||
curvature: default!(f32, "DEFAULT_CURVATURE"),
|
||||
) -> f32 {
|
||||
if a.is_empty() || b.is_empty() {
|
||||
error!("Vectors cannot be empty");
|
||||
}
|
||||
if a.len() != b.len() {
|
||||
error!("Vectors must have the same dimension");
|
||||
}
|
||||
if curvature >= 0.0 {
|
||||
error!("Curvature must be negative");
|
||||
}
|
||||
|
||||
let ball = PoincareBall::new(curvature);
|
||||
ball.distance(&a, &b)
|
||||
}
|
||||
|
||||
/// Compute Lorentz/hyperboloid distance between two vectors
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `a` - First vector (on hyperboloid)
|
||||
/// * `b` - Second vector (on hyperboloid)
|
||||
/// * `curvature` - Curvature of hyperbolic space (default: -1.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Lorentz distance as f32
|
||||
///
|
||||
/// # Example
|
||||
/// ```sql
|
||||
/// SELECT ruvector_lorentz_distance(
|
||||
/// ARRAY[1.5, 1.0, 0.5]::real[],
|
||||
/// ARRAY[2.0, 1.5, 0.5]::real[],
|
||||
/// -1.0
|
||||
/// );
|
||||
/// ```
|
||||
#[pg_extern(immutable, parallel_safe)]
|
||||
fn ruvector_lorentz_distance(
|
||||
a: Vec<f32>,
|
||||
b: Vec<f32>,
|
||||
curvature: default!(f32, "DEFAULT_CURVATURE"),
|
||||
) -> f32 {
|
||||
if a.len() < 2 || b.len() < 2 {
|
||||
error!("Lorentz vectors must have at least 2 dimensions");
|
||||
}
|
||||
if a.len() != b.len() {
|
||||
error!("Vectors must have the same dimension");
|
||||
}
|
||||
if curvature >= 0.0 {
|
||||
error!("Curvature must be negative");
|
||||
}
|
||||
|
||||
let model = LorentzModel::new(curvature);
|
||||
model.distance(&a, &b)
|
||||
}
|
||||
|
||||
/// Perform Möbius addition in Poincaré ball
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `a` - First vector
|
||||
/// * `b` - Second vector
|
||||
/// * `curvature` - Curvature of hyperbolic space (default: -1.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Result of Möbius addition
|
||||
///
|
||||
/// # Example
|
||||
/// ```sql
|
||||
/// SELECT ruvector_mobius_add(
|
||||
/// ARRAY[0.3, 0.4]::real[],
|
||||
/// ARRAY[0.1, 0.1]::real[],
|
||||
/// -1.0
|
||||
/// );
|
||||
/// ```
|
||||
#[pg_extern(immutable, parallel_safe)]
|
||||
fn ruvector_mobius_add(
|
||||
a: Vec<f32>,
|
||||
b: Vec<f32>,
|
||||
curvature: default!(f32, "DEFAULT_CURVATURE"),
|
||||
) -> Vec<f32> {
|
||||
if a.is_empty() || b.is_empty() {
|
||||
error!("Vectors cannot be empty");
|
||||
}
|
||||
if a.len() != b.len() {
|
||||
error!("Vectors must have the same dimension");
|
||||
}
|
||||
if curvature >= 0.0 {
|
||||
error!("Curvature must be negative");
|
||||
}
|
||||
|
||||
let ball = PoincareBall::new(curvature);
|
||||
ball.mobius_add(&a, &b)
|
||||
}
|
||||
|
||||
/// Exponential map in Poincaré ball
|
||||
/// Maps tangent vector at base point to the manifold
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `base` - Base point on the manifold
|
||||
/// * `tangent` - Tangent vector at base point
|
||||
/// * `curvature` - Curvature of hyperbolic space (default: -1.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Point on the manifold
|
||||
///
|
||||
/// # Example
|
||||
/// ```sql
|
||||
/// SELECT ruvector_exp_map(
|
||||
/// ARRAY[0.2, 0.3]::real[],
|
||||
/// ARRAY[0.1, 0.1]::real[],
|
||||
/// -1.0
|
||||
/// );
|
||||
/// ```
|
||||
#[pg_extern(immutable, parallel_safe)]
|
||||
fn ruvector_exp_map(
|
||||
base: Vec<f32>,
|
||||
tangent: Vec<f32>,
|
||||
curvature: default!(f32, "DEFAULT_CURVATURE"),
|
||||
) -> Vec<f32> {
|
||||
if base.is_empty() || tangent.is_empty() {
|
||||
error!("Vectors cannot be empty");
|
||||
}
|
||||
if base.len() != tangent.len() {
|
||||
error!("Vectors must have the same dimension");
|
||||
}
|
||||
if curvature >= 0.0 {
|
||||
error!("Curvature must be negative");
|
||||
}
|
||||
|
||||
let ball = PoincareBall::new(curvature);
|
||||
ball.exp_map(&base, &tangent)
|
||||
}
|
||||
|
||||
/// Logarithmic map in Poincaré ball
|
||||
/// Maps point on manifold to tangent space at base point
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `base` - Base point on the manifold
|
||||
/// * `target` - Target point on the manifold
|
||||
/// * `curvature` - Curvature of hyperbolic space (default: -1.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Tangent vector at base point
|
||||
///
|
||||
/// # Example
|
||||
/// ```sql
|
||||
/// SELECT ruvector_log_map(
|
||||
/// ARRAY[0.2, 0.3]::real[],
|
||||
/// ARRAY[0.4, 0.5]::real[],
|
||||
/// -1.0
|
||||
/// );
|
||||
/// ```
|
||||
#[pg_extern(immutable, parallel_safe)]
|
||||
fn ruvector_log_map(
|
||||
base: Vec<f32>,
|
||||
target: Vec<f32>,
|
||||
curvature: default!(f32, "DEFAULT_CURVATURE"),
|
||||
) -> Vec<f32> {
|
||||
if base.is_empty() || target.is_empty() {
|
||||
error!("Vectors cannot be empty");
|
||||
}
|
||||
if base.len() != target.len() {
|
||||
error!("Vectors must have the same dimension");
|
||||
}
|
||||
if curvature >= 0.0 {
|
||||
error!("Curvature must be negative");
|
||||
}
|
||||
|
||||
let ball = PoincareBall::new(curvature);
|
||||
ball.log_map(&base, &target)
|
||||
}
|
||||
|
||||
/// Convert from Poincaré ball to Lorentz hyperboloid coordinates
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `poincare` - Vector in Poincaré ball
|
||||
/// * `curvature` - Curvature of hyperbolic space (default: -1.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Vector in Lorentz hyperboloid coordinates
|
||||
///
|
||||
/// # Example
|
||||
/// ```sql
|
||||
/// SELECT ruvector_poincare_to_lorentz(
|
||||
/// ARRAY[0.3, 0.4]::real[],
|
||||
/// -1.0
|
||||
/// );
|
||||
/// ```
|
||||
#[pg_extern(immutable, parallel_safe)]
|
||||
fn ruvector_poincare_to_lorentz(
|
||||
poincare: Vec<f32>,
|
||||
curvature: default!(f32, "DEFAULT_CURVATURE"),
|
||||
) -> Vec<f32> {
|
||||
if poincare.is_empty() {
|
||||
error!("Vector cannot be empty");
|
||||
}
|
||||
if curvature >= 0.0 {
|
||||
error!("Curvature must be negative");
|
||||
}
|
||||
|
||||
let model = LorentzModel::new(curvature);
|
||||
model.from_poincare(&poincare)
|
||||
}
|
||||
|
||||
/// Convert from Lorentz hyperboloid to Poincaré ball coordinates
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `lorentz` - Vector in Lorentz hyperboloid coordinates
|
||||
/// * `curvature` - Curvature of hyperbolic space (default: -1.0)
|
||||
///
|
||||
/// # Returns
|
||||
/// Vector in Poincaré ball
|
||||
///
|
||||
/// # Example
|
||||
/// ```sql
|
||||
/// SELECT ruvector_lorentz_to_poincare(
|
||||
/// ARRAY[1.5, 1.0, 0.5]::real[],
|
||||
/// -1.0
|
||||
/// );
|
||||
/// ```
|
||||
#[pg_extern(immutable, parallel_safe)]
|
||||
fn ruvector_lorentz_to_poincare(
|
||||
lorentz: Vec<f32>,
|
||||
curvature: default!(f32, "DEFAULT_CURVATURE"),
|
||||
) -> Vec<f32> {
|
||||
if lorentz.len() < 2 {
|
||||
error!("Lorentz vector must have at least 2 dimensions");
|
||||
}
|
||||
if curvature >= 0.0 {
|
||||
error!("Curvature must be negative");
|
||||
}
|
||||
|
||||
let model = LorentzModel::new(curvature);
|
||||
model.to_poincare(&lorentz)
|
||||
}
|
||||
|
||||
/// Compute Minkowski inner product for Lorentz model
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `a` - First vector
|
||||
/// * `b` - Second vector
|
||||
///
|
||||
/// # Returns
|
||||
/// Minkowski inner product
|
||||
///
|
||||
/// # Example
|
||||
/// ```sql
|
||||
/// SELECT ruvector_minkowski_dot(
|
||||
/// ARRAY[2.0, 1.0, 1.0]::real[],
|
||||
/// ARRAY[3.0, 2.0, 1.0]::real[]
|
||||
/// );
|
||||
/// ```
|
||||
#[pg_extern(immutable, parallel_safe)]
|
||||
fn ruvector_minkowski_dot(a: Vec<f32>, b: Vec<f32>) -> f32 {
|
||||
if a.len() < 2 || b.len() < 2 {
|
||||
error!("Vectors must have at least 2 dimensions");
|
||||
}
|
||||
if a.len() != b.len() {
|
||||
error!("Vectors must have the same dimension");
|
||||
}
|
||||
|
||||
let model = LorentzModel::new(DEFAULT_CURVATURE);
|
||||
model.minkowski_dot(&a, &b)
|
||||
}
|
||||
|
||||
#[cfg(feature = "pg_test")]
|
||||
#[pg_schema]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TOL: f32 = 1e-4;
|
||||
|
||||
#[pg_test]
|
||||
fn test_poincare_distance_basic() {
|
||||
let a = vec![0.0, 0.0];
|
||||
let b = vec![0.5, 0.0];
|
||||
let dist = ruvector_poincare_distance(a, b, DEFAULT_CURVATURE);
|
||||
assert!(dist > 0.0);
|
||||
assert!(dist < f32::INFINITY);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_poincare_distance_symmetric() {
|
||||
let a = vec![0.3, 0.4];
|
||||
let b = vec![0.1, 0.2];
|
||||
let d1 = ruvector_poincare_distance(a.clone(), b.clone(), DEFAULT_CURVATURE);
|
||||
let d2 = ruvector_poincare_distance(b, a, DEFAULT_CURVATURE);
|
||||
assert!((d1 - d2).abs() < TOL);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_poincare_distance_same() {
|
||||
let a = vec![0.3, 0.4];
|
||||
let dist = ruvector_poincare_distance(a.clone(), a, DEFAULT_CURVATURE);
|
||||
assert!(dist < TOL);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_lorentz_distance_basic() {
|
||||
let a = vec![1.5, 1.0, 0.5];
|
||||
let b = vec![2.0, 1.5, 0.5];
|
||||
let dist = ruvector_lorentz_distance(a, b, DEFAULT_CURVATURE);
|
||||
assert!(dist > 0.0);
|
||||
assert!(dist < f32::INFINITY);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_mobius_add_identity() {
|
||||
let a = vec![0.3, 0.4];
|
||||
let origin = vec![0.0, 0.0];
|
||||
let result = ruvector_mobius_add(a.clone(), origin, DEFAULT_CURVATURE);
|
||||
for i in 0..a.len() {
|
||||
assert!((result[i] - a[i]).abs() < TOL);
|
||||
}
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_exp_log_inverse() {
|
||||
let base = vec![0.2, 0.3];
|
||||
let tangent = vec![0.1, 0.1];
|
||||
|
||||
let point = ruvector_exp_map(base.clone(), tangent.clone(), DEFAULT_CURVATURE);
|
||||
let recovered = ruvector_log_map(base, point, DEFAULT_CURVATURE);
|
||||
|
||||
for i in 0..tangent.len() {
|
||||
assert!((recovered[i] - tangent[i]).abs() < TOL);
|
||||
}
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_poincare_lorentz_conversion() {
|
||||
let poincare = vec![0.3, 0.4];
|
||||
let lorentz = ruvector_poincare_to_lorentz(poincare.clone(), DEFAULT_CURVATURE);
|
||||
let recovered = ruvector_lorentz_to_poincare(lorentz, DEFAULT_CURVATURE);
|
||||
|
||||
for i in 0..poincare.len() {
|
||||
assert!((recovered[i] - poincare[i]).abs() < TOL);
|
||||
}
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_minkowski_dot_basic() {
|
||||
let a = vec![2.0, 1.0, 1.0];
|
||||
let b = vec![3.0, 2.0, 1.0];
|
||||
let result = ruvector_minkowski_dot(a, b);
|
||||
// -2*3 + 1*2 + 1*1 = -3
|
||||
assert!((result - (-3.0)).abs() < TOL);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
#[should_panic(expected = "Vectors cannot be empty")]
|
||||
fn test_poincare_distance_empty() {
|
||||
let _ = ruvector_poincare_distance(vec![], vec![0.1], DEFAULT_CURVATURE);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
#[should_panic(expected = "Vectors must have the same dimension")]
|
||||
fn test_poincare_distance_different_dims() {
|
||||
let _ = ruvector_poincare_distance(vec![0.1], vec![0.1, 0.2], DEFAULT_CURVATURE);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
#[should_panic(expected = "Curvature must be negative")]
|
||||
fn test_poincare_distance_positive_curvature() {
|
||||
let _ = ruvector_poincare_distance(vec![0.1], vec![0.2], 1.0);
|
||||
}
|
||||
}
|
||||
267
vendor/ruvector/crates/ruvector-postgres/src/hyperbolic/poincare.rs
vendored
Normal file
267
vendor/ruvector/crates/ruvector-postgres/src/hyperbolic/poincare.rs
vendored
Normal file
@@ -0,0 +1,267 @@
|
||||
// Poincaré Ball Model Implementation
|
||||
// Implements conformal model of hyperbolic space
|
||||
|
||||
use crate::hyperbolic::{EPSILON, MAX_NORM};
|
||||
use simsimd::SpatialSimilarity;
|
||||
|
||||
/// Poincaré ball model for hyperbolic space
|
||||
pub struct PoincareBall {
|
||||
/// Curvature of the hyperbolic space (typically -1.0)
|
||||
pub curvature: f32,
|
||||
}
|
||||
|
||||
impl PoincareBall {
|
||||
/// Create a new Poincaré ball with specified curvature
|
||||
pub fn new(curvature: f32) -> Self {
|
||||
assert!(curvature < 0.0, "Curvature must be negative");
|
||||
Self { curvature }
|
||||
}
|
||||
|
||||
/// Compute squared norm of a vector
|
||||
#[inline]
|
||||
fn norm_squared(&self, x: &[f32]) -> f32 {
|
||||
(f32::dot(x, x).unwrap_or(0.0) as f32).max(0.0)
|
||||
}
|
||||
|
||||
/// Compute norm of a vector
|
||||
#[inline]
|
||||
fn norm(&self, x: &[f32]) -> f32 {
|
||||
self.norm_squared(x).sqrt()
|
||||
}
|
||||
|
||||
/// Project vector to within the Poincaré ball
|
||||
pub fn project(&self, x: &[f32]) -> Vec<f32> {
|
||||
let norm = self.norm(x);
|
||||
if norm < MAX_NORM {
|
||||
x.to_vec()
|
||||
} else {
|
||||
// Scale to MAX_NORM to stay within ball
|
||||
let scale = MAX_NORM / (norm + EPSILON);
|
||||
x.iter().map(|&v| v * scale).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute Poincaré distance between two points
|
||||
/// d(x, y) = acosh(1 + 2 * ||x - y||² / ((1 - ||x||²)(1 - ||y||²)))
|
||||
pub fn distance(&self, x: &[f32], y: &[f32]) -> f32 {
|
||||
assert_eq!(x.len(), y.len(), "Vectors must have same dimension");
|
||||
|
||||
let x_norm_sq = self.norm_squared(x);
|
||||
let y_norm_sq = self.norm_squared(y);
|
||||
|
||||
// Compute ||x - y||²
|
||||
let diff: Vec<f32> = x.iter().zip(y.iter()).map(|(&a, &b)| a - b).collect();
|
||||
let diff_norm_sq = self.norm_squared(&diff);
|
||||
|
||||
// Compute conformal factors
|
||||
let x_factor = 1.0 - x_norm_sq;
|
||||
let y_factor = 1.0 - y_norm_sq;
|
||||
|
||||
// Prevent division by zero
|
||||
if x_factor <= EPSILON || y_factor <= EPSILON {
|
||||
return f32::INFINITY;
|
||||
}
|
||||
|
||||
// d(x, y) = acosh(1 + 2 * ||x - y||² / ((1 - ||x||²)(1 - ||y||²)))
|
||||
let numerator = 2.0 * diff_norm_sq;
|
||||
let denominator = x_factor * y_factor;
|
||||
let ratio = numerator / (denominator + EPSILON);
|
||||
|
||||
let arg = 1.0 + ratio;
|
||||
let distance = arg.acosh();
|
||||
|
||||
// Scale by curvature
|
||||
let k = self.curvature.abs().sqrt();
|
||||
distance / k
|
||||
}
|
||||
|
||||
/// Möbius addition: x ⊕ y
|
||||
/// Formula: (1 + 2⟨x,y⟩ + ||y||²)x + (1 - ||x||²)y / (1 + 2⟨x,y⟩ + ||x||²||y||²)
|
||||
pub fn mobius_add(&self, x: &[f32], y: &[f32]) -> Vec<f32> {
|
||||
assert_eq!(x.len(), y.len(), "Vectors must have same dimension");
|
||||
|
||||
let x_norm_sq = self.norm_squared(x);
|
||||
let y_norm_sq = self.norm_squared(y);
|
||||
let xy_dot = f32::dot(x, y).unwrap_or(0.0) as f32;
|
||||
|
||||
let numerator_x_coeff = 1.0f32 + 2.0f32 * xy_dot + y_norm_sq;
|
||||
let numerator_y_coeff = 1.0f32 - x_norm_sq;
|
||||
let denominator = 1.0f32 + 2.0f32 * xy_dot + x_norm_sq * y_norm_sq + EPSILON;
|
||||
|
||||
let result: Vec<f32> = x
|
||||
.iter()
|
||||
.zip(y.iter())
|
||||
.map(|(&xi, &yi)| (numerator_x_coeff * xi + numerator_y_coeff * yi) / denominator)
|
||||
.collect();
|
||||
|
||||
self.project(&result)
|
||||
}
|
||||
|
||||
/// Exponential map: exp_x(v) maps tangent vector v at point x to the manifold
|
||||
/// Uses approximation for numerical stability
|
||||
pub fn exp_map(&self, base: &[f32], tangent: &[f32]) -> Vec<f32> {
|
||||
assert_eq!(
|
||||
base.len(),
|
||||
tangent.len(),
|
||||
"Vectors must have same dimension"
|
||||
);
|
||||
|
||||
let tangent_norm = self.norm(tangent);
|
||||
if tangent_norm < EPSILON {
|
||||
return base.to_vec();
|
||||
}
|
||||
|
||||
let k = self.curvature.abs().sqrt();
|
||||
let lambda_base = 2.0 / (1.0 - self.norm_squared(base) + EPSILON);
|
||||
|
||||
let coeff = (k * lambda_base * tangent_norm / 2.0).tanh() / (k * tangent_norm + EPSILON);
|
||||
|
||||
let scaled_tangent: Vec<f32> = tangent.iter().map(|&v| v * coeff).collect();
|
||||
|
||||
self.mobius_add(base, &scaled_tangent)
|
||||
}
|
||||
|
||||
/// Logarithmic map: log_x(y) maps point y to tangent space at point x
|
||||
pub fn log_map(&self, base: &[f32], target: &[f32]) -> Vec<f32> {
|
||||
assert_eq!(base.len(), target.len(), "Vectors must have same dimension");
|
||||
|
||||
// Compute -x ⊕ y
|
||||
let neg_base: Vec<f32> = base.iter().map(|&v| -v).collect();
|
||||
let diff = self.mobius_add(&neg_base, target);
|
||||
|
||||
let diff_norm = self.norm(&diff);
|
||||
if diff_norm < EPSILON {
|
||||
return vec![0.0; base.len()];
|
||||
}
|
||||
|
||||
let k = self.curvature.abs().sqrt();
|
||||
let lambda_base = 2.0 / (1.0 - self.norm_squared(base) + EPSILON);
|
||||
|
||||
let coeff =
|
||||
2.0 / (k * lambda_base + EPSILON) * (k * diff_norm).atanh() / (diff_norm + EPSILON);
|
||||
|
||||
diff.iter().map(|&v| v * coeff).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TOL: f32 = 1e-4;
|
||||
|
||||
#[test]
|
||||
fn test_poincare_ball_creation() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
assert_eq!(ball.curvature, -1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Curvature must be negative")]
|
||||
fn test_poincare_positive_curvature_panics() {
|
||||
let _ball = PoincareBall::new(1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_project_within_ball() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let x = vec![0.5, 0.5];
|
||||
let projected = ball.project(&x);
|
||||
assert_eq!(projected, x);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_project_outside_ball() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let x = vec![1.5, 1.5]; // Norm > 1
|
||||
let projected = ball.project(&x);
|
||||
let norm = ball.norm(&projected);
|
||||
assert!(norm <= MAX_NORM);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distance_origin() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let origin = vec![0.0, 0.0];
|
||||
let point = vec![0.5, 0.0];
|
||||
let dist = ball.distance(&origin, &point);
|
||||
assert!(dist > 0.0);
|
||||
assert!(dist < f32::INFINITY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distance_symmetric() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let x = vec![0.3, 0.4];
|
||||
let y = vec![0.1, 0.2];
|
||||
let d1 = ball.distance(&x, &y);
|
||||
let d2 = ball.distance(&y, &x);
|
||||
assert!((d1 - d2).abs() < TOL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distance_same_point() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let x = vec![0.3, 0.4];
|
||||
let dist = ball.distance(&x, &x);
|
||||
assert!(dist < TOL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mobius_add_identity() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let x = vec![0.3, 0.4];
|
||||
let origin = vec![0.0, 0.0];
|
||||
let result = ball.mobius_add(&x, &origin);
|
||||
for i in 0..x.len() {
|
||||
assert!((result[i] - x[i]).abs() < TOL);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_exp_map_zero_tangent() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let base = vec![0.3, 0.4];
|
||||
let tangent = vec![0.0, 0.0];
|
||||
let result = ball.exp_map(&base, &tangent);
|
||||
assert_eq!(result, base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_log_exp_inverse() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let base = vec![0.2, 0.3];
|
||||
let tangent = vec![0.1, 0.1];
|
||||
|
||||
let point = ball.exp_map(&base, &tangent);
|
||||
let recovered = ball.log_map(&base, &point);
|
||||
|
||||
for i in 0..tangent.len() {
|
||||
assert!((recovered[i] - tangent[i]).abs() < TOL);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_log_map_same_point() {
|
||||
let ball = PoincareBall::new(-1.0);
|
||||
let base = vec![0.3, 0.4];
|
||||
let result = ball.log_map(&base, &base);
|
||||
for &v in &result {
|
||||
assert!(v.abs() < TOL);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_curvature_scaling() {
|
||||
let ball1 = PoincareBall::new(-1.0);
|
||||
let ball2 = PoincareBall::new(-4.0);
|
||||
let x = vec![0.3, 0.4];
|
||||
let y = vec![0.1, 0.2];
|
||||
|
||||
let d1 = ball1.distance(&x, &y);
|
||||
let d2 = ball2.distance(&x, &y);
|
||||
|
||||
// Higher curvature magnitude should give shorter distances
|
||||
assert!(d2 < d1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user