src/euclidean.rs

Mon, 30 Dec 2024 09:49:08 -0500

author
Tuomo Valkonen <tuomov@iki.fi>
date
Mon, 30 Dec 2024 09:49:08 -0500
branch
dev
changeset 67
d7c0f431cbd6
parent 64
4f6ca107ccb1
permissions
-rw-r--r--

Discrete gradients

/*!
Euclidean spaces.
*/

use std::ops::{Mul, MulAssign, Div, DivAssign, Add, Sub, AddAssign, SubAssign, Neg};
use crate::types::*;
use crate::instance::Instance;
use crate::norms::{HasDual, Reflexive};

/// Space (type) with Euclidean and vector space structure
///
/// The type should implement vector space operations (addition, subtraction, scalar
/// multiplication and scalar division) along with their assignment versions, as well
/// as an inner product.
pub trait Euclidean<F : Float> : HasDual<F, DualSpace=Self> + Reflexive<F>
    + Mul<F, Output=<Self as Euclidean<F>>::Output> + MulAssign<F>
    + Div<F, Output=<Self as Euclidean<F>>::Output> + DivAssign<F>
    + Add<Self, Output=<Self as Euclidean<F>>::Output>
    + Sub<Self, Output=<Self as Euclidean<F>>::Output>
    + for<'b> Add<&'b Self, Output=<Self as Euclidean<F>>::Output>
    + for<'b> Sub<&'b Self, Output=<Self as Euclidean<F>>::Output>
    + AddAssign<Self> + for<'b> AddAssign<&'b Self>
    + SubAssign<Self> + for<'b> SubAssign<&'b Self>
    + Neg<Output=<Self as Euclidean<F>>::Output>
{
    type Output : Euclidean<F>;

    // Inner product
    fn dot<I : Instance<Self>>(&self, other : I) -> F;

    /// Calculate the square of the 2-norm, $\frac{1}{2}\\|x\\|_2^2$, where `self` is $x$.
    ///
    /// This is not automatically implemented to avoid imposing
    /// `for <'a> &'a Self : Instance<Self>` trait bound bloat.
    fn norm2_squared(&self) -> F;

    /// Calculate the square of the 2-norm divided by 2, $\frac{1}{2}\\|x\\|_2^2$,
    /// where `self` is $x$.
    #[inline]
    fn norm2_squared_div2(&self) -> F {
        self.norm2_squared()/F::TWO
    }

    /// Calculate the 2-norm $‖x‖_2$, where `self` is $x$.
    #[inline]
    fn norm2(&self) -> F {
        self.norm2_squared().sqrt()
    }

    /// Calculate the 2-distance squared $\\|x-y\\|_2^2$, where `self` is $x$.
    fn dist2_squared<I : Instance<Self>>(&self, y : I) -> F;

    /// Calculate the 2-distance $\\|x-y\\|_2$, where `self` is $x$.
    #[inline]
    fn dist2<I : Instance<Self>>(&self, y : I) -> F {
        self.dist2_squared(y).sqrt()
    }

    /// Projection to the 2-ball.
    #[inline]
    fn proj_ball2(mut self, ρ : F) -> Self {
        self.proj_ball2_mut(ρ);
        self
    }

    /// In-place projection to the 2-ball.
    #[inline]
    fn proj_ball2_mut(&mut self, ρ : F) {
        let r = self.norm2();
        if r>ρ {
            *self *= ρ/r
        }
    }
}

/// Trait for [`Euclidean`] spaces with dimensions known at compile time.
pub trait StaticEuclidean<F : Float> : Euclidean<F> {
    /// Returns the origin
    fn origin() -> <Self as Euclidean<F>>::Output;
}

mercurial