use relate_core::{Error, ErrorKind, Result, Value, VectorCoordKind};
use relate_ir::VectorMetric;
use crate::vector_config::{vector_dimension, VECTOR_DIMENSIONS_MAX, VECTOR_DIMENSIONS_MIN};
use crate::vector_similarity::{value_coords, CandidateCoords};
use relate_model::{CoordError, VectorCoords};
enum CoordFault {
NullCoordinate,
NonFinite,
NotNumeric,
}
fn as_floats(v: &Value) -> std::result::Result<Vec<f64>, CoordFault> {
let Some(coords) = value_coords(v) else {
return Err(CoordFault::NotNumeric);
};
match coords {
CandidateCoords::Vector(packed) => Ok(packed.to_f64_vec()),
CandidateCoords::List(values) => {
let mut out = Vec::with_capacity(values.len());
let (mut null, mut not_numeric, mut non_finite) = (false, false, false);
for value in values {
match value {
Value::Int(i) => out.push(*i as f64),
Value::Float(f) => {
non_finite |= !f.is_finite();
out.push(*f);
}
Value::Null => null = true,
_ => not_numeric = true,
}
}
let fault = if null {
Some(CoordFault::NullCoordinate)
} else if not_numeric {
Some(CoordFault::NotNumeric)
} else if non_finite {
Some(CoordFault::NonFinite)
} else {
None
};
match fault {
Some(fault) => Err(fault),
None => Ok(out),
}
}
}
}
enum Coords<'a> {
List(&'a [Value]),
Parsed(Vec<f64>),
}
impl Coords<'_> {
fn len(&self) -> usize {
match self {
Self::List(items) => items.len(),
Self::Parsed(floats) => floats.len(),
}
}
fn number_at(&self, i: usize) -> Option<f64> {
match self {
Self::List(items) => items[i].as_number(),
Self::Parsed(floats) => Some(floats[i]),
}
}
}
pub(crate) fn vector_construct(vals: &[Value]) -> Result<Value> {
if vals.iter().any(Value::is_null) {
return Ok(Value::Null);
}
let numbers = match &vals[0] {
Value::List(items) => Coords::List(items),
Value::String(s) => Coords::Parsed(
VectorCoordKind::parse_coordinates(s)
.ok_or_else(|| Error::ty("InvalidVectorCoordinates"))?,
),
_ => return Err(Error::ty("vector() requires a numeric list")),
};
let dim = vals[1]
.as_int()
.ok_or_else(|| Error::ty("vector() dimension must be an integer"))?;
let Some(dimension) = vector_dimension(dim) else {
return Err(Error::argument_value_kind(
ErrorKind::NumberOutOfRange,
format!(
"vector() dimension is outside the range {VECTOR_DIMENSIONS_MIN} to \
{VECTOR_DIMENSIONS_MAX}"
),
));
};
if dimension != numbers.len() {
return Err(Error::ty("vector() dimension does not match list"));
}
let coord_name = vals[2]
.as_string()
.ok_or_else(|| Error::ty("vector() coordinate type must be a keyword"))?
.to_ascii_uppercase();
let coord = VectorCoordKind::from_alias(&coord_name)
.ok_or_else(|| Error::ty("unknown vector coordinate type"))?;
let ns = (0..numbers.len())
.map(|i| {
numbers
.number_at(i)
.ok_or_else(|| Error::ty("vector() coordinates must be numbers"))
})
.collect::<Result<Vec<f64>>>()?;
let tokens = ns
.iter()
.map(|&n| {
coord.coerce(n).map_err(|reason| {
match reason {
CoordError::NonFinite => {
Error::ty("vector() coordinates must be finite numbers")
}
CoordError::Overflow => Error::ty("Overflow"),
CoordError::Inexact => Error::ty("InvalidVectorCoordinates"),
}
})
})
.collect::<Result<Vec<_>>>()?;
let coords = VectorCoords::from_coords(coord, tokens.into_iter())
.expect("coerced coordinates conform to their kind by construction");
Ok(Value::vector(coord, coords))
}
pub(crate) fn vector_dimension_count(vals: &[Value]) -> Result<Value> {
Ok(match plain_vector(vals.first().unwrap_or(&Value::Null))? {
Some(xs) => Value::Int(xs.len() as i64),
None => Value::Null,
})
}
pub(crate) fn plain_vector(value: &Value) -> Result<Option<Vec<f64>>> {
match value {
Value::Null => Ok(None),
Value::Vector { .. } => as_floats(value).map(Some).map_err(|fault| match fault {
CoordFault::NotNumeric => Error::invalid_argument_type("expected a VECTOR"),
CoordFault::NullCoordinate | CoordFault::NonFinite => {
invalid_vector("not a valid vector")
}
}),
_ => Err(Error::invalid_argument_type("expected a VECTOR")),
}
}
pub(crate) fn vector_metric(a: &[f64], b: &[f64], metric: VectorMetric) -> Result<f64> {
let round = |v: f64| v as f32 as f64;
Ok(match metric {
VectorMetric::Euclidean => round(
a.iter()
.zip(b)
.map(|(x, y)| (x - y).powi(2))
.sum::<f64>()
.sqrt(),
),
VectorMetric::EuclideanSquared => {
round(a.iter().zip(b).map(|(x, y)| (x - y).powi(2)).sum())
}
VectorMetric::Manhattan => round(a.iter().zip(b).map(|(x, y)| (x - y).abs()).sum()),
VectorMetric::Cosine => {
let dot: f64 = a.iter().zip(b).map(|(x, y)| x * y).sum();
let na: f64 = a.iter().map(|x| x * x).sum::<f64>().sqrt();
let nb: f64 = b.iter().map(|x| x * x).sum::<f64>().sqrt();
round(1.0 - round(dot / (na * nb)))
}
VectorMetric::Dot => round(-a.iter().zip(b).map(|(x, y)| x * y).sum::<f64>()),
VectorMetric::Hamming => a.iter().zip(b).filter(|(x, y)| x != y).count() as f64,
})
}
pub(crate) fn vector_distance_metric(vals: &[Value; 2], metric: VectorMetric) -> Result<Value> {
match (plain_vector(&vals[0])?, plain_vector(&vals[1])?) {
(None, _) | (_, None) => Ok(Value::Null),
(Some(a), Some(b)) => {
if a.len() != b.len() {
return Err(dimension_mismatch());
}
Ok(Value::Float(vector_metric(&a, &b, metric)?))
}
}
}
pub(crate) fn vector_norm_metric(val: &Value, metric: VectorMetric) -> Result<Value> {
if !matches!(metric, VectorMetric::Euclidean | VectorMetric::Manhattan) {
return Err(Error::syntax("UnknownDistanceMetric"));
}
match plain_vector(val)? {
None => Ok(Value::Null),
Some(a) => {
let zero = vec![0.0; a.len()];
Ok(Value::Float(vector_metric(&a, &zero, metric)?))
}
}
}
fn invalid_vector(detail: &str) -> Error {
Error::argument_value_kind(ErrorKind::InvalidArgumentValue, detail)
}
fn dimension_mismatch() -> Error {
invalid_vector("vectors must have same dimensions")
}
fn similarity_coords(a: &Value, b: &Value, wrong_type: &str) -> Result<(Vec<f64>, Vec<f64>)> {
match (as_floats(a), as_floats(b)) {
(Ok(x), Ok(y)) => Ok((x, y)),
(Err(CoordFault::NullCoordinate | CoordFault::NonFinite), _)
| (_, Err(CoordFault::NullCoordinate | CoordFault::NonFinite)) => {
Err(invalid_vector("not a valid vector"))
}
_ => Err(Error::ty(wrong_type)),
}
}
pub(crate) fn vector_cosine(vals: &[Value]) -> Result<Value> {
let (Some(a), Some(b)) = (vals.first(), vals.get(1)) else {
return Err(Error::ty("vector.similarity.cosine needs two lists"));
};
if a.is_null() || b.is_null() {
return Ok(Value::Null);
}
let (x, y) = similarity_coords(a, b, "vector.similarity.cosine needs numeric lists")?;
if x.len() != y.len() || x.is_empty() {
return Err(dimension_mismatch());
}
if x.iter().all(|f| *f == 0.0) || y.iter().all(|f| *f == 0.0) {
return Err(invalid_vector("not a valid vector"));
}
let dot: f64 = x.iter().zip(&y).map(|(a, b)| a * b).sum();
let nx: f64 = x.iter().map(|a| a * a).sum::<f64>().sqrt();
let ny: f64 = y.iter().map(|a| a * a).sum::<f64>().sqrt();
if nx == 0.0 || ny == 0.0 {
return Ok(Value::Float(0.0));
}
let raw = (dot / (nx * ny)) as f32 as f64;
Ok(Value::Float(((1.0 + raw) / 2.0) as f32 as f64))
}
pub(crate) fn vector_euclidean(vals: &[Value]) -> Result<Value> {
let (Some(a), Some(b)) = (vals.first(), vals.get(1)) else {
return Err(Error::ty("vector.similarity.euclidean needs two lists"));
};
if a.is_null() || b.is_null() {
return Ok(Value::Null);
}
let (x, y) = similarity_coords(a, b, "vector.similarity.euclidean needs numeric lists")?;
if x.len() != y.len() {
return Err(dimension_mismatch());
}
if x.is_empty() {
return Err(invalid_vector("not a valid vector"));
}
let d2: f64 = x.iter().zip(&y).map(|(a, b)| (a - b) * (a - b)).sum();
Ok(Value::Float((1.0 / (1.0 + d2)) as f32 as f64))
}
#[cfg(test)]
mod tests {
use super::*;
use relate_model::VectorCoords;
fn list(xs: &[f64]) -> Value {
Value::List(
xs.iter()
.map(|x| Value::Float(*x))
.collect::<Vec<_>>()
.into(),
)
}
fn construct(items: Value, dim: i64, coord: &str) -> Result<Value> {
vector_construct(&[items, Value::Int(dim), Value::String(coord.into())])
}
#[test]
fn integer_coord_coerces_nan_to_zero() {
let v = construct(list(&[f64::NAN, 2.0]), 2, "INT8").unwrap();
assert_eq!(
v,
Value::vector(VectorCoordKind::Int8, VectorCoords::from_int(vec![0, 2]))
);
}
#[test]
fn integer_coord_rejects_out_of_range_and_non_finite() {
assert!(construct(list(&[128.0]), 1, "INT8").is_err());
assert!(construct(list(&[f64::INFINITY]), 1, "INT64").is_err());
}
#[test]
fn integer_coord_truncates_toward_zero_within_the_kind_width() {
let one = |coord: &str, n: f64| construct(list(&[n]), 1, coord);
let int = |coord, value| Value::vector(coord, VectorCoords::from_int(vec![value]));
assert_eq!(one("INT8", 127.9).unwrap(), int(VectorCoordKind::Int8, 127));
assert_eq!(
one("INT8", -128.9).unwrap(),
int(VectorCoordKind::Int8, -128)
);
assert!(one("INT8", 128.0).is_err());
assert!(one("INT8", -129.0).is_err());
assert_eq!(
one("INT64", 9_223_372_036_854_775_808.0).unwrap(),
int(VectorCoordKind::Int64, i64::MAX)
);
assert!(one("INT64", 9.3e18).is_err());
assert_eq!(
one("INT64", -9_223_372_036_854_775_808.0).unwrap(),
int(VectorCoordKind::Int64, i64::MIN)
);
}
#[test]
fn float32_coord_narrows_but_must_stay_finite() {
let v = construct(list(&[1.5]), 1, "FLOAT32").unwrap();
assert_eq!(
v,
Value::vector(VectorCoordKind::Float32, VectorCoords::from_f32(vec![1.5]))
);
assert!(construct(list(&[1e300]), 1, "FLOAT32").is_err());
assert!(construct(list(&[f64::NAN]), 1, "FLOAT32").is_err());
}
#[test]
fn float64_coord_requires_finite() {
let v = construct(list(&[1e300]), 1, "FLOAT64").unwrap();
assert_eq!(
v,
Value::vector(
VectorCoordKind::Float64,
VectorCoords::from_f64(vec![1e300])
)
);
assert!(construct(list(&[f64::NAN]), 1, "FLOAT64").is_err());
assert!(construct(list(&[f64::NEG_INFINITY]), 1, "FLOAT64").is_err());
}
#[test]
fn similarity_rejects_non_finite_coordinates() {
let finite = list(&[1.0, 2.0]);
for bad in [f64::INFINITY, f64::NEG_INFINITY] {
let with_bad = Value::List(vec![Value::Float(bad), Value::Float(2.0)].into());
for (name, f) in [
(
"euclidean",
vector_euclidean as fn(&[Value]) -> Result<Value>,
),
("cosine", vector_cosine),
] {
let err = f(&[finite.clone(), with_bad.clone()]).unwrap_err();
assert!(
matches!(err, Error::ArgumentValue { .. }),
"{name} / {bad}: {err:?}"
);
}
}
}
#[test]
fn narrow_float_coords_round_and_overflow_loudly() {
assert_eq!(
construct(list(&[1.0, 0.1]), 2, "FLOAT16").unwrap(),
Value::vector(
VectorCoordKind::Float16,
VectorCoords::from_f32(vec![1.0, 0.099975586]),
)
);
assert!(construct(list(&[65520.0]), 1, "FLOAT16").is_err());
assert_eq!(
construct(list(&[257.0]), 1, "BFLOAT16").unwrap(),
Value::vector(
VectorCoordKind::BFloat16,
VectorCoords::from_f32(vec![256.0])
)
);
assert!(construct(list(&[1e39]), 1, "BFLOAT16").is_err());
}
}