use super::Result;
pub trait Metric {
const INTEGER: bool = true;
fn combine(acc: f32, a: f32, b: f32) -> f32;
fn join(x: f32, y: f32) -> f32;
fn dist_int(q: &[u8], x: &[u8]) -> u32;
}
pub struct L1;
pub struct L2;
pub struct Linf;
pub struct Ip;
impl Metric for L1 {
#[inline(always)]
fn combine(acc: f32, a: f32, b: f32) -> f32 {
acc + (a - b).abs()
}
#[inline(always)]
fn join(x: f32, y: f32) -> f32 {
x + y
}
#[inline(always)]
fn dist_int(q: &[u8], x: &[u8]) -> u32 {
q.iter()
.zip(x)
.map(|(&a, &b)| u32::from(a.abs_diff(b)))
.sum()
}
}
impl Metric for L2 {
#[inline(always)]
fn combine(acc: f32, a: f32, b: f32) -> f32 {
let e = a - b;
acc + e * e
}
#[inline(always)]
fn join(x: f32, y: f32) -> f32 {
x + y
}
#[inline(always)]
fn dist_int(q: &[u8], x: &[u8]) -> u32 {
q.iter()
.zip(x)
.map(|(&a, &b)| {
let e = u32::from(a.abs_diff(b));
e * e
})
.sum()
}
}
#[inline(always)]
pub fn larger(x: f32, y: f32) -> f32 {
if y > x { y } else { x }
}
impl Metric for Linf {
#[inline(always)]
fn combine(acc: f32, a: f32, b: f32) -> f32 {
larger(acc, (a - b).abs())
}
#[inline(always)]
fn join(x: f32, y: f32) -> f32 {
larger(x, y)
}
#[inline(always)]
fn dist_int(q: &[u8], x: &[u8]) -> u32 {
u32::from(
q.iter()
.zip(x)
.map(|(&a, &b)| a.abs_diff(b))
.max()
.unwrap_or(0),
)
}
}
impl Metric for Ip {
const INTEGER: bool = false;
#[inline(always)]
fn combine(acc: f32, a: f32, b: f32) -> f32 {
acc - a * b
}
#[inline(always)]
fn join(x: f32, y: f32) -> f32 {
x + y
}
fn dist_int(_q: &[u8], _x: &[u8]) -> u32 {
unreachable!("the integer path is not used for the inner product")
}
}
#[derive(Clone, Copy)]
pub enum Kind {
L1,
L2,
Linf,
Ip,
}
impl Kind {
pub fn parse(metric: &str) -> Result<Kind> {
match metric {
"l1" => Ok(Kind::L1),
"l2" => Ok(Kind::L2),
"linf" => Ok(Kind::Linf),
"ip" => Ok(Kind::Ip),
_ => Err("metric must be 'l1', 'l2', 'linf' or 'ip' (inner product)".into()),
}
}
pub fn similarity(self) -> bool {
matches!(self, Kind::Ip)
}
}
macro_rules! with_metric {
($kind:expr, $m:ident => $body:expr) => {
match $kind {
$crate::metric::Kind::L1 => {
type $m = $crate::metric::L1;
$body
}
$crate::metric::Kind::L2 => {
type $m = $crate::metric::L2;
$body
}
$crate::metric::Kind::Linf => {
type $m = $crate::metric::Linf;
$body
}
$crate::metric::Kind::Ip => {
type $m = $crate::metric::Ip;
$body
}
}
};
}
pub(crate) use with_metric;
pub fn score(kind: Kind, q: &[f32], x: &[f32]) -> f32 {
let pairs = q.iter().zip(x);
match kind {
Kind::L2 => pairs.map(|(a, b)| (a - b) * (a - b)).sum::<f32>().sqrt(),
Kind::L1 => pairs.map(|(a, b)| (a - b).abs()).sum(),
Kind::Linf => pairs.fold(0.0f32, |m, (a, b)| larger(m, (a - b).abs())),
Kind::Ip => pairs.map(|(a, b)| a * b).sum(),
}
}